Skip to content

Commit 3ed5d13

Browse files
committed
Content moderation quickstart image/text TS
1 parent 6ba1754 commit 3ed5d13

File tree

5 files changed

+242
-40
lines changed

5 files changed

+242
-40
lines changed
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
---
2+
title: "Quickstart: Analyze image content with TypeScript"
3+
description: In this quickstart, get started using the Azure AI Content Safety TypeScript SDK to analyze image content for objectionable material.
4+
author: PatrickFarley
5+
manager: nitinme
6+
ms.service: azure-ai-content-safety
7+
ms.custom:
8+
ms.topic: include
9+
ms.date: 07/11/2025
10+
ms.author: pafarley
11+
---
12+
13+
[Reference documentation](https://www.npmjs.com/package/@azure-rest/ai-content-safety/v/1.0.0) | [Library source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/contentsafety/ai-content-safety-rest) | [Package (npm)](https://www.npmjs.com/package/@azure-rest/ai-content-safety) | [Samples](https://github.com/Azure-Samples/AzureAIContentSafety/tree/main/js/1.0.0) |
14+
15+
16+
## Prerequisites
17+
18+
* An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services/)
19+
* [Node.js LTS](https://nodejs.org/)
20+
* [TypeScript](https://www.typescriptlang.org/)
21+
* [Visual Studio Code](https://code.visualstudio.com/)
22+
* 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**.
23+
* 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.
24+
25+
## Set up local development environment
26+
27+
1. Create a new directory for your project and navigate to it:
28+
29+
```console
30+
mkdir content-safety-image-analysis
31+
cd content-safety-image-analysis
32+
code .
33+
```
34+
35+
2. Create a new package for ESM modules in your project directory:
36+
37+
```console
38+
npm init -y
39+
npm pkg set type=module
40+
```
41+
42+
3. Install the required packages:
43+
44+
```console
45+
npm install @azure-rest/ai-content-safety
46+
```
47+
48+
4. Install development dependencies:
49+
50+
```console
51+
npm install typescript @types/node --save-dev
52+
```
53+
54+
5. Create a `tsconfig.json` file in your project directory:
55+
56+
```json
57+
{
58+
"compilerOptions": {
59+
"target": "es2022",
60+
"module": "esnext",
61+
"moduleResolution": "bundler",
62+
"rootDir": "./src",
63+
"outDir": "./dist/",
64+
"esModuleInterop": true,
65+
"forceConsistentCasingInFileNames": true,
66+
"strict": true,
67+
"skipLibCheck": true,
68+
"declaration": true,
69+
"sourceMap": true,
70+
"resolveJsonModule": true,
71+
"moduleDetection": "force",
72+
"allowSyntheticDefaultImports": true,
73+
"verbatimModuleSyntax": false
74+
},
75+
"include": [
76+
"src/**/*.ts"
77+
],
78+
"exclude": [
79+
"node_modules/**/*",
80+
"**/*.spec.ts"
81+
]
82+
}
83+
```
84+
85+
6. Update `package.json` to include a script for building TypeScript files:
86+
87+
```json
88+
"scripts": {
89+
"build": "tsc",
90+
"start": "node dist/index.js"
91+
}
92+
```
93+
94+
7. Create a `resources` folder and add a sample image to it.
95+
96+
8. Create a `src` directory for your TypeScript code.
97+
98+
[!INCLUDE [Create environment variables](../env-vars.md)]
99+
100+
## Analyze image content
101+
102+
Create a new file in your `src` directory, `index.ts` and paste in the following code. Replace the string used to create the `imagePath` variable with the path to your sample image.
103+
104+
```typescript
105+
import ContentSafetyClient, {
106+
isUnexpected,
107+
AnalyzeImageParameters,
108+
AnalyzeImage200Response,
109+
AnalyzeImageDefaultResponse,
110+
AnalyzeImageOptions,
111+
ImageCategoriesAnalysisOutput
112+
} from "@azure-rest/ai-content-safety";
113+
import { AzureKeyCredential } from "@azure/core-auth";
114+
import * as fs from "fs";
115+
import * as path from "path";
116+
import { fileURLToPath } from "url";
117+
118+
// Create __dirname equivalent for ESM modules
119+
const __filename = fileURLToPath(import.meta.url);
120+
const __dirname = path.dirname(__filename);
121+
122+
// Get endpoint and key from environment variables
123+
const endpoint = process.env.CONTENT_SAFETY_ENDPOINT;
124+
const key = process.env.CONTENT_SAFETY_KEY;
125+
126+
if (!endpoint || !key) {
127+
throw new Error("Missing required environment variables CONTENT_SAFETY_ENDPOINT or CONTENT_SAFETY_KEY");
128+
}
129+
130+
try {
131+
132+
const credential = new AzureKeyCredential(key);
133+
const client = ContentSafetyClient(endpoint, credential);
134+
135+
const imagePath = path.join(__dirname, '../resources/image.jpg');
136+
137+
const imageBuffer = fs.readFileSync(imagePath);
138+
const base64Image = imageBuffer.toString("base64");
139+
const analyzeImageOption: AnalyzeImageOptions = { image: { content: base64Image } };
140+
const analyzeImageParameters: AnalyzeImageParameters = { body: analyzeImageOption };
141+
142+
const result: AnalyzeImage200Response | AnalyzeImageDefaultResponse = await client.path("/image:analyze").post(analyzeImageParameters);
143+
144+
if (isUnexpected(result)) {
145+
throw result;
146+
}
147+
148+
const categoriesAnalysis = result.body.categoriesAnalysis as ImageCategoriesAnalysisOutput[];
149+
150+
for (const analysis of categoriesAnalysis) {
151+
console.log(`${analysis.category} severity: ${analysis.severity}`);
152+
}
153+
} catch (error) {
154+
console.error("Error analyzing image:", error);
155+
}
156+
```
157+
158+
## Build and run the sample
159+
160+
2. Compile the TypeScript code:
161+
162+
```console
163+
npm run build
164+
```
165+
166+
3. Run the compiled JavaScript:
167+
168+
```console
169+
node dist/index.js
170+
```
171+
172+
## Output
173+
174+
```console
175+
Hate severity: 0
176+
SelfHarm severity: 0
177+
Sexual severity: 0
178+
Violence severity: 0
179+
```

articles/ai-services/content-safety/includes/quickstarts/typescript-quickstart-text.md

Lines changed: 31 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -17,36 +17,36 @@ ms.author: pafarley
1717

1818
* An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services/)
1919
* [Node.js LTS](https://nodejs.org/)
20-
* [TypeScript](https://www.typescriptlang.org/) for writing the sample code
21-
* [Visual Studio Code](https://code.visualstudio.com/) or another IDE of your choice
20+
* [TypeScript](https://www.typescriptlang.org/)
21+
* [Visual Studio Code](https://code.visualstudio.com/)
2222
* 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**.
2323
* 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.
2424

2525
## Set up application
2626

27-
Create a new TypeScript application. In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
27+
1. Create a new TypeScript application. In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
2828

29-
```console
30-
mkdir content-safety-typescript && cd content-safety-typescript
31-
code .
32-
```
33-
34-
Initialize a new Node.js project with TypeScript:
29+
```console
30+
mkdir content-safety-typescript && cd content-safety-typescript
31+
code .
32+
```
33+
34+
2. Initialize a new Node.js project with TypeScript:
3535

36-
```bash
37-
npm init -y
38-
npm pkg set type=module
39-
```
36+
```console
37+
npm init -y
38+
npm pkg set type=module
39+
```
4040

4141
3. Install the required packages:
4242

43-
```bash
43+
```console
4444
npm install @azure-rest/ai-content-safety @azure/core-auth
4545
```
4646

4747
4. Install development dependencies:
4848

49-
```bash
49+
```console
5050
npm install typescript @types/node --save-dev
5151
```
5252

@@ -90,9 +90,7 @@ npm pkg set type=module
9090
}
9191
```
9292

93-
7. Create a `resources` folder and add a sample image to it.
94-
95-
8. Create a `src` directory for your TypeScript code.
93+
7. Create a `src` directory for your TypeScript code.
9694

9795
[!INCLUDE [Create environment variables](../env-vars.md)]
9896

@@ -106,19 +104,16 @@ Create a file in the `src` directory named `index.ts`. Open it in your preferred
106104
> See [Input requirements](../../overview.md#input-requirements) for maximum text length limitations.
107105
108106
```typescript
109-
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
107+
import ContentSafetyClient, {
108+
isUnexpected,
109+
AnalyzeTextParameters,
110+
AnalyzeText200Response,
111+
AnalyzeTextDefaultResponse,
112+
AnalyzeTextOptions,
113+
TextCategoriesAnalysisOutput
114+
} from "@azure-rest/ai-content-safety";
110115
import { AzureKeyCredential } from "@azure/core-auth";
111116

112-
// Define interfaces for better type safety
113-
interface TextAnalysisOptions {
114-
text: string;
115-
}
116-
117-
interface CategoryAnalysis {
118-
category: string;
119-
severity: number;
120-
}
121-
122117
// Get endpoint and key from environment variables
123118
const endpoint = process.env.CONTENT_SAFETY_ENDPOINT;
124119
const key = process.env.CONTENT_SAFETY_KEY;
@@ -133,12 +128,12 @@ try {
133128
const client = ContentSafetyClient(endpoint, credential);
134129

135130
// Replace with your own sample text string
136-
const text = "<your sample text>";
137-
const analyzeTextOption: TextAnalysisOptions = { text };
138-
const analyzeTextParameters = { body: analyzeTextOption };
131+
const text = "Replace with your text sample";
132+
const analyzeTextOption: AnalyzeTextOptions = { text };
133+
const analyzeTextParameters: AnalyzeTextParameters = { body: analyzeTextOption };
139134

140135
// Call the Content Safety API to analyze the text
141-
const result = await client.path("/text:analyze").post(analyzeTextParameters);
136+
const result: AnalyzeText200Response | AnalyzeTextDefaultResponse = await client.path("/text:analyze").post(analyzeTextParameters);
142137

143138
if (isUnexpected(result)) {
144139
throw result;
@@ -147,7 +142,7 @@ try {
147142
// Process and display the analysis results
148143
console.log("Text analysis results:");
149144

150-
const categoriesAnalysis = result.body.categoriesAnalysis as CategoryAnalysis[];
145+
const categoriesAnalysis = result.body.categoriesAnalysis as TextCategoriesAnalysisOutput[];
151146

152147
for (const analysis of categoriesAnalysis) {
153148
console.log(`${analysis.category} severity: ${analysis.severity}`);
@@ -161,13 +156,13 @@ try {
161156

162157
1. Build the TypeScript code:
163158

164-
```bash
159+
```console
165160
npm run build
166161
```
167162

168163
2. Run the application:
169164

170-
```bash
165+
```console
171166
npm start
172167
```
173168

articles/ai-services/content-safety/quickstart-image.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ manager: nitinme
77
ms.service: azure-ai-content-safety
88
ms.custom: build-2023, devx-track-python, devx-track-dotnet, devx-track-extended-java, devx-track-js
99
ms.topic: quickstart
10-
ms.date: 01/22/2025
10+
ms.date: 07/14/2025
1111
ms.author: pafarley
12-
zone_pivot_groups: programming-languages-content-safety
12+
zone_pivot_groups: programming-languages-content-safety-2
1313
---
1414

1515
# QuickStart: Analyze image content
@@ -58,7 +58,11 @@ For more information on image moderation, see the [Harm categories concept page]
5858

5959
::: zone-end
6060

61+
::: zone pivot="programming-language-typescript"
6162

63+
[!INCLUDE [TypeScript SDK quickstart](./includes/quickstarts/typescript-quickstart-image.md)]
64+
65+
::: zone-end
6266

6367
## Clean up resources
6468

articles/ai-services/content-safety/quickstart-text.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ manager: nitinme
77
ms.service: azure-ai-content-safety
88
ms.custom: build-2023, devx-track-python, devx-track-dotnet, devx-track-extended-java, devx-track-js
99
ms.topic: quickstart
10-
ms.date: 01/22/2025
10+
ms.date: 7/14/2025
1111
ms.author: pafarley
12-
zone_pivot_groups: programming-languages-content-safety
12+
zone_pivot_groups: programming-languages-content-safety-2
1313
---
1414

1515
# QuickStart: Analyze text content
@@ -58,7 +58,11 @@ For more information on text moderation, see the [Harm categories concept page](
5858
[!INCLUDE [Python SDK quickstart](./includes/quickstarts/javascript-quickstart-text.md)]
5959

6060
::: zone-end
61+
::: zone pivot="programming-language-typescript"
6162

63+
[!INCLUDE [TypeScript SDK quickstart](./includes/quickstarts/typescript-quickstart-text.md)]
64+
65+
::: zone-end
6266

6367

6468
## Clean up resources

zone-pivots/zone-pivot-groups.yml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ groups:
6868
title: Python
6969
- id: programming-language-rest
7070
title: REST
71+
7172
- id: programming-languages-content-safety-abridged
7273
# Owner: pafarley
7374
title: Programming languages
@@ -81,6 +82,25 @@ groups:
8182
title: Python
8283
- id: programming-language-rest
8384
title: REST
85+
- id: programming-languages-content-safety-2
86+
# Owner: pafarley
87+
title: Programming languages
88+
prompt: Choose a platform
89+
pivots:
90+
- id: programming-language-foundry-portal
91+
title: Foundry portal
92+
- id: programming-language-csharp
93+
title: C#
94+
- id: programming-language-java
95+
title: Java
96+
- id: programming-language-javascript
97+
title: JavaScript
98+
- id: programming-language-python
99+
title: Python
100+
- id: programming-language-rest
101+
title: REST
102+
- id: programming-language-typescript
103+
title: TypeScript
84104
- id: programming-languages-content-safety-foundry-rest
85105
# Owner: pafarley
86106
title: Programming languages

0 commit comments

Comments
 (0)