azure-ai-contentsafety-java
microsoft/skills
Java용 Azure AI 콘텐츠 안전성 SDK를 사용하여 텍스트와 이미지의 유해한 콘텐츠를 분석하세요. 차단 목록 관리를 통해 혐오, 폭력, 성적 콘텐츠 및 자해 관련 콘텐츠 탐지를 지원합니다.
...모든 것을 확장하십시오Java용 Azure AI 콘텐츠 안전성 SDK
Java용 Azure AI 콘텐츠 안전성 SDK를 사용하여 콘텐츠 검토 애플리케이션을 구축하세요.
설치
com.azure
azure-ai-contentsafety
1.1.0-beta.1
클라이언트 생성
API 키 사용
import com.azure.ai.contentsafety.ContentSafetyClient;
import com.azure.ai.contentsafety.ContentSafetyClientBuilder;
import com.azure.ai.contentsafety.BlocklistClient;
import com.azure.ai.contentsafety.BlocklistClientBuilder;
import com.azure.core.credential.KeyCredential;
String endpoint = System.getenv("CONTENT_SAFETY_ENDPOINT");
String key = System.getenv("CONTENT_SAFETY_KEY");
ContentSafetyClient contentSafetyClient = new ContentSafetyClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint)
.buildClient();
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint)
.buildClient();
DefaultAzureCredential 사용 시
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// 또는 프로덕션 환경에서 특정 자격 증명을 직접 사용:
// https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes 참조
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
ContentSafetyClient client = new ContentSafetyClientBuilder()
.credential(credential)
.endpoint(endpoint)
.buildClient();
핵심 개념
유해성 범주
| 범주 | 설명 |
|---|---|
| 증오 | 정체성 집단에 기반한 차별적 언어 |
| 성적 | 성적 콘텐츠, 관계, 행위 |
| 폭력 | 신체적 피해, 무기, 부상 |
| 자해 | 자해, 자살 관련 콘텐츠 |
심각도 수준
- 텍스트: 0~7점 척도 (기본 출력값: 0, 2, 4, 6)
- 이미지: 0, 2, 4, 6 (축소된 척도)
핵심 패턴
텍스트 분석
import com.azure.ai.contentsafety.models.*;
AnalyzeTextResult result = contentSafetyClient.analyzeText(
new AnalyzeTextOptions("This is text to analyze"));
for (TextCategoriesAnalysis category : result.getCategoriesAnalysis()) {
System.out.printf("카테고리: %s, 심각도: %d%n",
category.getCategory(),
category.getSeverity());
}
옵션을 사용하여 텍스트 분석하기
AnalyzeTextOptions options = new AnalyzeTextOptions("분석할 텍스트")
.setCategories(Arrays.asList(
TextCategory.HATE,
TextCategory.VIOLENCE))
.setOutputType(AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS);
AnalyzeTextResult result = contentSafetyClient.analyzeText(options);
차단 목록을 사용하여 텍스트 분석
AnalyzeTextOptions options = new AnalyzeTextOptions("I h*te you and want to k*ll you")
.setBlocklistNames(Arrays.asList("my-blocklist"))
.setHaltOnBlocklistHit(true);
AnalyzeTextResult result = contentSafetyClient.analyzeText(options);
if (result.getBlocklistsMatch() != null) {
for (TextBlocklistMatch match : result.getBlocklistsMatch()) {
System.out.printf("차단 목록: %s, 항목: %s, 텍스트: %s%n",
match.getBlocklistName(),
match.getBlocklistItemId(),
match.getBlocklistItemText());
}
}
이미지 분석
import com.azure.ai.contentsafety.models.*;
import com.azure.core.util.BinaryData;
import java.nio.file.Files;
import java.nio.file.Paths;
// 파일에서 불러오기
byte[] imageBytes = Files.readAllBytes(Paths.get("image.png"));
ContentSafetyImageData imageData = new ContentSafetyImageData()
.setContent(BinaryData.fromBytes(imageBytes));
AnalyzeImageResult result = contentSafetyClient.analyzeImage(
new AnalyzeImageOptions(imageData));
for (ImageCategoriesAnalysis category : result.getCategoriesAnalysis()) {
System.out.printf("카테고리: %s, 심각도: %d%n",
category.getCategory(),
category.getSeverity());
}
URL에서 이미지 분석
ContentSafetyImageData imageData = new ContentSafetyImageData()
.setBlobUrl("https://example.com/image.jpg");
AnalyzeImageResult result = contentSafetyClient.analyzeImage(
new AnalyzeImageOptions(imageData));
차단 목록 관리
차단 목록 생성 또는 업데이트
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import java.util.Map;
Map description = Map.of("description", "사용자 지정 차단 목록");
BinaryData resource = BinaryData.fromObject(description);
Response response = blocklistClient.createOrUpdateTextBlocklistWithResponse(
"my-blocklist", resource, new RequestOptions());
if (response.getStatusCode() == 201) {
System.out.println("차단 목록 생성됨");
} else if (response.getStatusCode() == 200) {
System.out.println("차단 목록 업데이트됨");
}
차단 항목 추가
import com.azure.ai.contentsafety.models.*;
import java.util.Arrays;
List items = Arrays.asList(
new TextBlocklistItem("badword1").setDescription("모욕적인 단어"),
new TextBlocklistItem("badword2").setDescription("또 다른 단어")
);
AddOrUpdateTextBlocklistItemsResult result = blocklistClient.addOrUpdateBlocklistItems(
"my-blocklist",
new AddOrUpdateTextBlocklistItemsOptions(items));
for (TextBlocklistItem item : result.getBlocklistItems()) {
System.out.printf("추가됨: %s (ID: %s)%n",
item.getText(),
item.getBlocklistItemId());
}
차단 목록 열기
PagedIterable blocklists = blocklistClient.listTextBlocklists();
for (TextBlocklist blocklist : blocklists) {
System.out.printf("차단 목록: %s, 설명: %s%n",
blocklist.getName(),
blocklist.getDescription());
}
차단 목록 가져오기
TextBlocklist blocklist = blocklistClient.getTextBlocklist("my-blocklist");
System.out.println("이름: " + blocklist.getName());
차단 항목 나열
PagedIterable items =
blocklistClient.listTextBlocklistItems("my-blocklist");
for (TextBlocklistItem item : items) {
System.out.printf("ID: %s, 텍스트: %s%n",
item.getBlocklistItemId(),
item.getText());
}
블록 항목 제거
itemIds = Arrays.asList("item-id-1", "item-id-2");
blocklistClient.removeBlocklistItems(
"my-blocklist",
new RemoveTextBlocklistItemsOptions(itemIds));
차단 목록 삭제
blocklistClient.deleteTextBlocklist("my-blocklist");
오류 처리
import com.azure.core.exception.HttpResponseException;
try {
contentSafetyClient.analyzeText(new AnalyzeTextOptions("test"));
} catch (HttpResponseException e) {
System.out.println("상태: " + e.getResponse().getStatusCode());
System.out.println("오류: " + e.getMessage());
// 일반적인 오류 코드: InvalidRequestBody, ResourceNotFound, TooManyRequests
}
환경 변수
CONTENT_SAFETY_ENDPOINT=https://.cognitiveservices.azure.com/ # 모든 인증 방식에 필수
CONTENT_SAFETY_ENDPOINT=https:// .cognitiveservices.azure.com/ # 모든 인증 방식에 필수
AZURE_TOKEN_CREDENTIALS=prod # 프로덕션 환경에서 DefaultAzureCredential을 사용하는 경우에만 필수
모범 사례
- 차단 목록 지연: 변경 사항이 적용되는 데 약 5분이 소요됩니다
- 카테고리 선택: 지연 시간을 줄이기 위해 필요한 카테고리만 요청하십시오
- 중요도 임계값: 엄격한 검토를 위해서는 일반적으로 중요도 4 이상인 항목을 차단하십시오
- 일괄 처리: 처리량을 높이기 위해 여러 항목을 병렬로 처리하십시오
- 캐싱: 적절한 경우 차단 목록 결과를 캐싱하십시오
트리거 문구
- "콘텐츠 안전성 Java"
- "콘텐츠 검토 Azure"
- "텍스트 안전성 분석"
- "이미지 검토 Java"
- "차단 목록 관리"
- "혐오 발언 탐지"
- "유해 콘텐츠 필터"
---
name: azure-ai-contentsafety-java
description: Analyze text and images for harmful content using Azure AI Content Safety SDK for Java. Supports hate, violence, sexual content, and self-harm detection with blocklist management.
license: MIT
---
# Azure AI Content Safety SDK for Java
Build content moderation applications using the Azure AI Content Safety SDK for Java.
## Installation
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-contentsafety</artifactId>
<version>1.1.0-beta.1</version>
</dependency>
```
## Client Creation
### With API Key
```java
import com.azure.ai.contentsafety.ContentSafetyClient;
import com.azure.ai.contentsafety.ContentSafetyClientBuilder;
import com.azure.ai.contentsafety.BlocklistClient;
import com.azure.ai.contentsafety.BlocklistClientBuilder;
import com.azure.core.credential.KeyCredential;
String endpoint = System.getenv("CONTENT_SAFETY_ENDPOINT");
String key = System.getenv("CONTENT_SAFETY_KEY");
ContentSafetyClient contentSafetyClient = new ContentSafetyClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint)
.buildClient();
BlocklistClient blocklistClient = new BlocklistClientBuilder()
.credential(new KeyCredential(key))
.endpoint(endpoint)
.buildClient();
```
### With DefaultAzureCredential
```java
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
ContentSafetyClient client = new ContentSafetyClientBuilder()
.credential(credential)
.endpoint(endpoint)
.buildClient();
```
## Key Concepts
### Harm Categories
| Category | Description |
|----------|-------------|
| Hate | Discriminatory language based on identity groups |
| Sexual | Sexual content, relationships, acts |
| Violence | Physical harm, weapons, injury |
| Self-harm | Self-injury, suicide-related content |
### Severity Levels
- Text: 0-7 scale (default outputs 0, 2, 4, 6)
- Image: 0, 2, 4, 6 (trimmed scale)
## Core Patterns
### Analyze Text
```java
import com.azure.ai.contentsafety.models.*;
AnalyzeTextResult result = contentSafetyClient.analyzeText(
new AnalyzeTextOptions("This is text to analyze"));
for (TextCategoriesAnalysis category : result.getCategoriesAnalysis()) {
System.out.printf("Category: %s, Severity: %d%n",
category.getCategory(),
category.getSeverity());
}
```
### Analyze Text with Options
```java
AnalyzeTextOptions options = new AnalyzeTextOptions("Text to analyze")
.setCategories(Arrays.asList(
TextCategory.HATE,
TextCategory.VIOLENCE))
.setOutputType(AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS);
AnalyzeTextResult result = contentSafetyClient.analyzeText(options);
```
### Analyze Text with Blocklist
```java
AnalyzeTextOptions options = new AnalyzeTextOptions("I h*te you and want to k*ll you")
.setBlocklistNames(Arrays.asList("my-blocklist"))
.setHaltOnBlocklistHit(true);
AnalyzeTextResult result = contentSafetyClient.analyzeText(options);
if (result.getBlocklistsMatch() != null) {
for (TextBlocklistMatch match : result.getBlocklistsMatch()) {
System.out.printf("Blocklist: %s, Item: %s, Text: %s%n",
match.getBlocklistName(),
match.getBlocklistItemId(),
match.getBlocklistItemText());
}
}
```
### Analyze Image
```java
import com.azure.ai.contentsafety.models.*;
import com.azure.core.util.BinaryData;
import java.nio.file.Files;
import java.nio.file.Paths;
// From file
byte[] imageBytes = Files.readAllBytes(Paths.get("image.png"));
ContentSafetyImageData imageData = new ContentSafetyImageData()
.setContent(BinaryData.fromBytes(imageBytes));
AnalyzeImageResult result = contentSafetyClient.analyzeImage(
new AnalyzeImageOptions(imageData));
for (ImageCategoriesAnalysis category : result.getCategoriesAnalysis()) {
System.out.printf("Category: %s, Severity: %d%n",
category.getCategory(),
category.getSeverity());
}
```
### Analyze Image from URL
```java
ContentSafetyImageData imageData = new ContentSafetyImageData()
.setBlobUrl("https://example.com/image.jpg");
AnalyzeImageResult result = contentSafetyClient.analyzeImage(
new AnalyzeImageOptions(imageData));
```
## Blocklist Management
### Create or Update Blocklist
```java
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import java.util.Map;
Map<String, String> description = Map.of("description", "Custom blocklist");
BinaryData resource = BinaryData.fromObject(description);
Response<BinaryData> response = blocklistClient.createOrUpdateTextBlocklistWithResponse(
"my-blocklist", resource, new RequestOptions());
if (response.getStatusCode() == 201) {
System.out.println("Blocklist created");
} else if (response.getStatusCode() == 200) {
System.out.println("Blocklist updated");
}
```
### Add Block Items
```java
import com.azure.ai.contentsafety.models.*;
import java.util.Arrays;
List<TextBlocklistItem> items = Arrays.asList(
new TextBlocklistItem("badword1").setDescription("Offensive term"),
new TextBlocklistItem("badword2").setDescription("Another term")
);
AddOrUpdateTextBlocklistItemsResult result = blocklistClient.addOrUpdateBlocklistItems(
"my-blocklist",
new AddOrUpdateTextBlocklistItemsOptions(items));
for (TextBlocklistItem item : result.getBlocklistItems()) {
System.out.printf("Added: %s (ID: %s)%n",
item.getText(),
item.getBlocklistItemId());
}
```
### List Blocklists
```java
PagedIterable<TextBlocklist> blocklists = blocklistClient.listTextBlocklists();
for (TextBlocklist blocklist : blocklists) {
System.out.printf("Blocklist: %s, Description: %s%n",
blocklist.getName(),
blocklist.getDescription());
}
```
### Get Blocklist
```java
TextBlocklist blocklist = blocklistClient.getTextBlocklist("my-blocklist");
System.out.println("Name: " + blocklist.getName());
```
### List Block Items
```java
PagedIterable<TextBlocklistItem> items =
blocklistClient.listTextBlocklistItems("my-blocklist");
for (TextBlocklistItem item : items) {
System.out.printf("ID: %s, Text: %s%n",
item.getBlocklistItemId(),
item.getText());
}
```
### Remove Block Items
```java
List<String> itemIds = Arrays.asList("item-id-1", "item-id-2");
blocklistClient.removeBlocklistItems(
"my-blocklist",
new RemoveTextBlocklistItemsOptions(itemIds));
```
### Delete Blocklist
```java
blocklistClient.deleteTextBlocklist("my-blocklist");
```
## Error Handling
```java
import com.azure.core.exception.HttpResponseException;
try {
contentSafetyClient.analyzeText(new AnalyzeTextOptions("test"));
} catch (HttpResponseException e) {
System.out.println("Status: " + e.getResponse().getStatusCode());
System.out.println("Error: " + e.getMessage());
// Common codes: InvalidRequestBody, ResourceNotFound, TooManyRequests
}
```
## Environment Variables
```bash
CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com/ # Required for all auth methods
CONTENT_SAFETY_KEY=<your-api-key> # Only required for AzureKeyCredential auth
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Best Practices
1. **Blocklist Delay**: Changes take ~5 minutes to take effect
2. **Category Selection**: Only request needed categories to reduce latency
3. **Severity Thresholds**: Typically block severity >= 4 for strict moderation
4. **Batch Processing**: Process multiple items in parallel for throughput
5. **Caching**: Cache blocklist results where appropriate
## Trigger Phrases
- "content safety Java"
- "content moderation Azure"
- "analyze text safety"
- "image moderation Java"
- "blocklist management"
- "hate speech detection"
- "harmful content filter"
모든 파일
0개 파일azure-ai-contentsafety-java 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-ai-contentsafety-java # Copy SKILL.md to your .claude/skills/ directory
복사





집
