Skip to content

Commit ba86615

Browse files
committed
add blocklist qss
1 parent 9cbe4f3 commit ba86615

File tree

6 files changed

+581
-5
lines changed

6 files changed

+581
-5
lines changed

articles/ai-services/content-safety/how-to/use-blocklist.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -249,10 +249,10 @@ Copy the cURL command below to a text editor and make the following changes:
249249
curl --location --request POST '<endpoint>/contentsafety/text/blocklists/<your_list_name>:addOrUpdateBlocklistItems?api-version=2024-09-01' \
250250
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
251251
--header 'Content-Type: application/json' \
252-
--data-raw '"blocklistItems": [{
252+
--data-raw '{"blocklistItems": [{
253253
"description": "string",
254254
"text": "bleed"
255-
}]'
255+
}]}'
256256
```
257257

258258
> [!TIP]
@@ -379,7 +379,7 @@ blocklist_item_text_2 = "<block_item_text_2>"
379379
blocklist_items = [TextBlocklistItem(text=blocklist_item_text_1), TextBlocklistItem(text=blocklist_item_text_2)]
380380
try:
381381
result = client.add_or_update_blocklist_items(
382-
blocklist_name=blocklist_name, options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=blocklist_items)
382+
blocklist_name=blocklist_name, options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=blocklist_items))
383383
for blocklist_item in result.blocklist_items:
384384
print(
385385
f"BlocklistItemId: {blocklist_item.blocklist_item_id}, Text: {blocklist_item.text}, Description: {blocklist_item.description}"
@@ -1391,9 +1391,9 @@ Copy the cURL command below to a text editor and make the following changes:
13911391
curl --location --request POST '<endpoint>/contentsafety/text/blocklists/<your_list_name>:removeBlocklistItems?api-version=2024-09-01' \
13921392
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
13931393
--header 'Content-Type: application/json'
1394-
--data-raw '"blocklistItemIds":[
1394+
--data-raw '{"blocklistItemIds":[
13951395
"<item_id>"
1396-
]'
1396+
]}'
13971397
```
13981398

13991399
> [!TIP]
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
---
2+
title: "Quickstart: Use a blocklist with C#"
3+
#services: cognitive-services
4+
author: PatrickFarley
5+
manager: nitinme
6+
ms.service: azure-ai-content-safety
7+
ms.custom:
8+
ms.topic: include
9+
ms.date: 02/22/2025
10+
ms.author: pafarley
11+
---
12+
13+
[Reference documentation](/dotnet/api/overview/azure/ai.contentsafety-readme) | [Library source code](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/contentsafety/Azure.AI.ContentSafety) | [Package (NuGet)](https://www.nuget.org/packages/Azure.AI.ContentSafety) | [Samples](https://github.com/Azure-Samples/AzureAIContentSafety/tree/main/dotnet/1.0.0)
14+
15+
16+
## Prerequisites
17+
18+
* An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services/)
19+
* The [Visual Studio IDE](https://visualstudio.microsoft.com/vs/) with workload .NET desktop development enabled. Or if you don't plan on using Visual Studio IDE, you need the current version of [.NET Core](https://dotnet.microsoft.com/download/dotnet-core).
20+
* Once you have your Azure subscription, <a href="https://aka.ms/acs-create" title="Create a Content Safety resource" target="_blank">create a Content Safety resource </a> in the Azure portal to get your key and endpoint. Enter a unique name for your resource, select your subscription, and select a resource group, supported region (see [Region availability](/azure/ai-services/content-safety/overview#region-availability)), and supported pricing tier. Then select **Create**.
21+
* The resource takes a few minutes to deploy. After it finishes, Select **go to resource**. In the left pane, under **Resource Management**, select **Subscription Key and Endpoint**. The endpoint and either of the keys are used to call APIs.
22+
23+
## Set up application
24+
25+
Create a new C# application.
26+
27+
#### [Visual Studio IDE](#tab/visual-studio)
28+
29+
Open Visual Studio, and under **Get started** select **Create a new project**. Set the template filters to _C#/All Platforms/Console_. Select **Console App** (command-line application that can run on .NET on Windows, Linux and macOS) and choose **Next**. Update the project name to _ContentSafetyQuickstart_ and choose **Next**. Select **.NET 6.0** or above, and choose **Create** to create the project.
30+
31+
### Install the client SDK
32+
33+
Once you've created a new project, install the client SDK by right-clicking on the project solution in the **Solution Explorer** and selecting **Manage NuGet Packages**. In the package manager that opens select **Browse**, and search for `Azure.AI.ContentSafety`. Select **Install**.
34+
35+
#### [CLI](#tab/cli)
36+
37+
In a console window (such as cmd, PowerShell, or Bash), use the `dotnet new` command to create a new console app with the name `content-safety-quickstart`. This command creates a simple "Hello World" C# project with a single source file: *Program.cs*.
38+
39+
```dotnet
40+
dotnet new console -n content-safety-quickstart
41+
```
42+
43+
Change your directory to the newly created app folder. You can build the application with:
44+
45+
```dotnet
46+
dotnet build
47+
```
48+
49+
The build output should contain no warnings or errors.
50+
51+
```console
52+
...
53+
Build succeeded.
54+
0 Warning(s)
55+
0 Error(s)
56+
...
57+
```
58+
59+
### Install the client SDK
60+
61+
Within the application directory, install the Computer Vision client SDK for .NET with the following command:
62+
63+
```dotnet
64+
dotnet add package Azure.AI.ContentSafety
65+
```
66+
67+
---
68+
69+
[!INCLUDE [Create environment variables](../env-vars.md)]
70+
71+
## Create and use a blocklist
72+
73+
From the project directory, open the *Program.cs* file that was created previously. Paste in the following code. This code creates a new blocklist, adds items to it, and then analyzes a text string against the blocklist.
74+
75+
```csharp
76+
using System;
77+
using Azure.AI.ContentSafety;
78+
using Azure;
79+
using Azure.Core;
80+
81+
class ContentSafetyBlocklist
82+
{
83+
public static void UseBlocklist()
84+
{
85+
86+
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
87+
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
88+
Console.WriteLine("Endpoint: "+ endpoint);
89+
Console.WriteLine("Key: "+ key);
90+
91+
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
92+
93+
var blocklistName = "ProductSaleBlocklist";
94+
var blocklistDescription = "Contains terms related to the sale of a product.";
95+
96+
var data = new
97+
{
98+
description = blocklistDescription,
99+
};
100+
101+
// create blocklist
102+
var createResponse = blocklistClient.CreateOrUpdateTextBlocklist(blocklistName, RequestContent.Create(data));
103+
104+
if (createResponse.Status == 201)
105+
{
106+
Console.WriteLine("\nBlocklist {0} created.", blocklistName);
107+
}
108+
109+
// Add blocklistItems
110+
111+
string blocklistItemText1 = "price";
112+
string blocklistItemText2 = "offer";
113+
114+
var blocklistItems = new TextBlocklistItem[] { new TextBlocklistItem(blocklistItemText1), new TextBlocklistItem(blocklistItemText2) };
115+
var addedBlocklistItems = blocklistClient.AddOrUpdateBlocklistItems(blocklistName, new AddOrUpdateTextBlocklistItemsOptions(blocklistItems));
116+
117+
if (addedBlocklistItems != null && addedBlocklistItems.Value != null)
118+
{
119+
Console.WriteLine("\nBlocklistItems added:");
120+
foreach (var addedBlocklistItem in addedBlocklistItems.Value.BlocklistItems)
121+
{
122+
Console.WriteLine("BlocklistItemId: {0}, Text: {1}, Description: {2}", addedBlocklistItem.BlocklistItemId, addedBlocklistItem.Text, addedBlocklistItem.Description);
123+
}
124+
}
125+
126+
// Analyze text
127+
ContentSafetyClient client = new ContentSafetyClient(new Uri(endpoint), new AzureKeyCredential(key));
128+
129+
// After you edit your blocklist, it usually takes effect in 5 minutes, please wait some time before analyzing with blocklist after editing.
130+
var request = new AnalyzeTextOptions("You can order a copy now for the low price of $19.99.");
131+
request.BlocklistNames.Add(blocklistName);
132+
request.HaltOnBlocklistHit = true;
133+
134+
Response<AnalyzeTextResult> response;
135+
try
136+
{
137+
response = client.AnalyzeText(request);
138+
}
139+
catch (RequestFailedException ex)
140+
{
141+
Console.WriteLine("Analyze text failed.\nStatus code: {0}, Error code: {1}, Error message: {2}", ex.Status, ex.ErrorCode, ex.Message);
142+
throw;
143+
}
144+
145+
if (response.Value.BlocklistsMatch != null)
146+
{
147+
Console.WriteLine("\nBlocklist match result:");
148+
foreach (var matchResult in response.Value.BlocklistsMatch)
149+
{
150+
Console.WriteLine("BlocklistName: {0}, BlocklistItemId: {1}, BlocklistText: {2}, ", matchResult.BlocklistName, matchResult.BlocklistItemId, matchResult.BlocklistItemText);
151+
}
152+
}
153+
}
154+
static void Main()
155+
{
156+
UseBlocklist();
157+
}
158+
}
159+
```
160+
161+
Optionally replace the blocklist name and items with your own.
162+
163+
#### [Visual Studio IDE](#tab/visual-studio)
164+
165+
Build and run the application by selecting **Start Debugging** from the **Debug** menu at the top of the IDE window (or press **F5**).
166+
167+
#### [CLI](#tab/cli)
168+
169+
Build and run the application from your application directory with these commands:
170+
171+
```dotnet
172+
dotnet build
173+
dotnet run
174+
```
175+
176+
---
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
---
2+
title: "Quickstart: Use a blocklist with Python"
3+
#services: cognitive-services
4+
author: PatrickFarley
5+
manager: nitinme
6+
ms.service: azure-ai-content-safety
7+
ms.custom:
8+
ms.topic: include
9+
ms.date: 02/22/2025
10+
ms.author: pafarley
11+
---
12+
13+
[Reference documentation](https://pypi.org/project/azure-ai-contentsafety/) | [Library source code](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/contentsafety/azure-ai-contentsafety) | [Package (PyPI)](https://pypi.org/project/azure-ai-contentsafety/) | [Samples](https://github.com/Azure-Samples/AzureAIContentSafety/tree/main/python/1.0.0) |
14+
15+
## Prerequisites
16+
17+
* An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services/)
18+
* Once you have your Azure subscription, <a href="https://aka.ms/acs-create" title="Create a Content Safety resource" target="_blank">create a Content Safety resource </a> in the Azure portal to get your key and endpoint. Enter a unique name for your resource, select your subscription, and select a resource group, supported region (see [Region availability](/azure/ai-services/content-safety/overview#region-availability)), and supported pricing tier. Then select **Create**.
19+
* The resource takes a few minutes to deploy. After it finishes, Select **go to resource**. In the left pane, under **Resource Management**, select **Subscription Key and Endpoint**. The endpoint and either of the keys are used to call APIs.
20+
* [Python 3.x](https://www.python.org/)
21+
* Your Python installation should include [pip](https://pip.pypa.io/en/stable/). You can check if you have pip installed by running `pip --version` on the command line. Get pip by installing the latest version of Python.
22+
23+
[!INCLUDE [Create environment variables](../env-vars.md)]
24+
25+
## Create and use a blocklist
26+
27+
The code in this section creates a new blocklist, adds items to it, and then analyzes a text string against the blocklist.
28+
29+
1. Open a command prompt, navigate to your project folder, and create a new file named *quickstart.py*.
30+
1. Run this command to install the Azure AI Content Safety library:
31+
32+
```console
33+
pip install azure-ai-contentsafety
34+
```
35+
36+
1. Copy the following code into *quickstart.py*:
37+
38+
```python
39+
import os
40+
from azure.ai.contentsafety import BlocklistClient
41+
from azure.ai.contentsafety import ContentSafetyClient
42+
from azure.core.credentials import AzureKeyCredential
43+
from azure.core.exceptions import HttpResponseError
44+
from azure.ai.contentsafety.models import (
45+
TextBlocklist, AddOrUpdateTextBlocklistItemsOptions, TextBlocklistItem, AnalyzeTextOptions
46+
)
47+
from azure.core.exceptions import HttpResponseError
48+
49+
key = os.environ["CONTENT_SAFETY_KEY"]
50+
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
51+
52+
# Create a Blocklist client
53+
client = BlocklistClient(endpoint, AzureKeyCredential(key))
54+
55+
blocklist_name = "<your-blocklist-name>"
56+
blocklist_description = "<description>"
57+
58+
try:
59+
blocklist = client.create_or_update_text_blocklist(
60+
blocklist_name=blocklist_name,
61+
options=TextBlocklist(blocklist_name=blocklist_name, description=blocklist_description),
62+
)
63+
if blocklist:
64+
print("\nBlocklist created or updated: ")
65+
print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
66+
except HttpResponseError as e:
67+
print("\nCreate or update text blocklist failed: ")
68+
if e.error:
69+
print(f"Error code: {e.error.code}")
70+
print(f"Error message: {e.error.message}")
71+
raise
72+
print(e)
73+
raise
74+
75+
76+
# add items
77+
blocklist_item_text_1 = "<block_item_text_1>"
78+
blocklist_item_text_2 = "<block_item_text_2>"
79+
80+
blocklist_items = [TextBlocklistItem(text=blocklist_item_text_1), TextBlocklistItem(text=blocklist_item_text_2)]
81+
try:
82+
result = client.add_or_update_blocklist_items(
83+
blocklist_name=blocklist_name, options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=blocklist_items))
84+
for blocklist_item in result.blocklist_items:
85+
print(
86+
f"BlocklistItemId: {blocklist_item.blocklist_item_id}, Text: {blocklist_item.text}, Description: {blocklist_item.description}"
87+
)
88+
except HttpResponseError as e:
89+
print("\nAdd blocklistItems failed: ")
90+
if e.error:
91+
print(f"Error code: {e.error.code}")
92+
print(f"Error message: {e.error.message}")
93+
raise
94+
print(e)
95+
raise
96+
97+
# analyze
98+
99+
# Create a Content Safety client
100+
client = ContentSafetyClient(endpoint, AzureKeyCredential(key))
101+
102+
input_text = "<sample input text>"
103+
104+
try:
105+
# After you edit your blocklist, it usually takes effect in 5 minutes, please wait some time before analyzing
106+
# with blocklist after editing.
107+
analysis_result = client.analyze_text(
108+
AnalyzeTextOptions(text=input_text, blocklist_names=[blocklist_name], halt_on_blocklist_hit=False)
109+
)
110+
if analysis_result and analysis_result.blocklists_match:
111+
print("\nBlocklist match results: ")
112+
for match_result in analysis_result.blocklists_match:
113+
print(
114+
f"BlocklistName: {match_result.blocklist_name}, BlocklistItemId: {match_result.blocklist_item_id}, "
115+
f"BlocklistItemText: {match_result.blocklist_item_text}"
116+
)
117+
except HttpResponseError as e:
118+
print("\nAnalyze text failed: ")
119+
if e.error:
120+
print(f"Error code: {e.error.code}")
121+
print(f"Error message: {e.error.message}")
122+
raise
123+
print(e)
124+
raise
125+
```
126+
127+
1. Replace the following placeholders with your own values:
128+
* `<your-blocklist-name>`: A unique name for your blocklist.
129+
* `<description>`: A description of your blocklist.
130+
* `<block_item_text_1>`: The first item to add to your blocklist.
131+
* `<block_item_text_2>`: The second item to add to your blocklist.
132+
* `<sample input text>`: The text you want to analyze against the blocklist.
133+
1. Then run the application with the `python` command on your quickstart file.
134+
135+
```console
136+
python quickstart.py
137+
```

0 commit comments

Comments
 (0)