빠른 시작: Content Moderator 클라이언트 라이브러리 사용

중요

Azure Content Moderator는 2024년 2월부터 더 이상 사용되지 않으며 2027년 3월 15일에 사용 중지됩니다. 고급 AI 기능과 향상된 성능을 제공하는 Azure AI 콘텐츠 보안로 대체됩니다.

Azure AI 콘텐츠 보안 애플리케이션 및 서비스에서 유해한 사용자 생성 및 AI 생성 콘텐츠를 감지하도록 설계된 포괄적인 솔루션입니다. Azure AI 콘텐츠 보안 온라인 마켓플레이스, 게임 회사, 소셜 메시징 플랫폼, 엔터프라이즈 미디어 회사 및 K-12 교육 솔루션 공급자와 같은 많은 시나리오에 적합합니다. 기능 및 성능에 대한 개요는 다음과 같습니다.

  • 텍스트 및 이미지 감지 API: 텍스트 및 이미지에서 성적 콘텐츠, 폭력, 증오 및 자해를 여러 심각도 수준으로 스캔합니다.
  • Content Safety Studio: 최신 콘텐츠 조정 ML 모델을 사용하여 잠재적으로 공격적이거나 위험하거나 바람직하지 않은 콘텐츠를 처리하도록 설계된 온라인 도구입니다. 사용자가 자체 콘텐츠 조정 시스템을 빌드할 수 있도록 하는 템플릿 및 사용자 지정된 워크플로를 제공합니다.
  • 언어 지원: Azure AI 콘텐츠 보안 100개 이상의 언어를 지원하며 영어, 독일어, 일본어, 스페인어, 프랑스어, 이탈리아어, 포르투갈어 및 중국어로 특별히 학습됩니다.

Azure AI 콘텐츠 보안 콘텐츠 조정 요구 사항에 대한 강력하고 유연한 솔루션을 제공합니다. Content Moderator에서 Azure AI 콘텐츠 보안 전환하여 최신 도구와 기술을 활용하여 콘텐츠가 항상 정확한 사양으로 조정되도록 할 수 있습니다.

Azure AI 콘텐츠 보안 콘텐츠 조정 전략을 승격하는 방법을 알아봅니다.

.NET Azure Content Moderator 클라이언트 라이브러리를 시작합니다. 다음 단계에 따라 NuGet 패키지를 설치하고 기본 작업에 대한 예제 코드를 사용해 보세요.

Content Moderator는 잠재적으로 불쾌하거나 위험하거나 바람직하지 않은 콘텐츠를 처리할 수 있는 AI 서비스입니다. AI 기반 콘텐츠 조정 서비스를 사용하여 텍스트, 이미지 및 비디오를 검색하고 콘텐츠 플래그를 자동으로 적용합니다. 규정을 준수하거나 사용자에 대한 의도된 환경을 유지 관리하기 위해 앱에 콘텐츠 필터링 소프트웨어를 빌드합니다.

.NET Content Moderator 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 텍스트 조정
  • 이미지 조정

리퍼런스 설명서리브라리 소스 코드패키지(NuGet)샘플스<

필수 구성 요소

  • Azure 구독 - 무료로 만들기
  • Visual Studio IDE 또는 현재 버전의 .NET Core.
  • Azure 구독이 있으면 Azure 포털에서 Content Moderator 리소스 생성하여 키와 엔드포인트를 가져옵니다. 배포할 때까지 기다렸다가 리소스로 이동 단추를 클릭합니다.
    • 애플리케이션을 Content Moderator에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 빠른 시작에서 나중에 아래 코드에 키와 엔드포인트를 붙여 넣게 됩니다.
    • 무료 가격 책정 계층(F0)을 사용하여 서비스를 사용해 볼 수 있으며 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.

설정

새 C# 애플리케이션 만들기

Visual Studio 사용하여 새 .NET Core 애플리케이션을 만듭니다.

클라이언트 라이브러리 설치

새 프로젝트를 만든 후에는 솔루션 탐색기에서 프로젝트 솔루션을 마우스 오른쪽 단추로 클릭하고 NuGet 패키지 관리를 선택하여 클라이언트 라이브러리를 설치합니다. 열린 패키지 관리자에서 Browse를 선택하고 프리릴리즈 포함을 확인한 후 Microsoft.Azure.CognitiveServices.ContentModerator를 검색합니다. 버전을 2.0.0선택한 다음 설치합니다.

전체 빠른 시작 코드 파일을 한 번에 보고 싶으신가요? 이 빠른 시작의 코드 예제를 포함하는 GitHub에서 찾을 수 있습니다.

프로젝트 디렉터리에서 기본 설정 편집기 또는 IDE에서 Program.cs 파일을 엽니다. 다음 using 문을 추가합니다.

using Microsoft.Azure.CognitiveServices.ContentModerator;
using Microsoft.Azure.CognitiveServices.ContentModerator.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

Program 클래스에서 리소스의 키 및 엔드포인트에 대한 변수를 만듭니다.

중요

Azure 포털로 이동합니다. 필수 구성 요소 섹션에서 만든 Content Moderator 리소스가 성공적으로 배포된 경우 다음 단계에서리소스로 이동 단추를 클릭합니다. 리소스 관리 아래의 리소스 키 및 엔드포인트 페이지에서 키와 엔드포인트를 찾을 수 있습니다.

// Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
private static readonly string SubscriptionKey = "PASTE_YOUR_CONTENT_MODERATOR_SUBSCRIPTION_KEY_HERE";
// Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://westus.api.cognitive.microsoft.com
private static readonly string Endpoint = "PASTE_YOUR_CONTENT_MODERATOR_ENDPOINT_HERE";

중요

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault 같은 자격 증명을 저장하고 액세스하는 안전한 방법을 사용합니다. 자세한 내용은 Azure AI 서비스 security 문서를 참조하세요.

애플리케이션의 main() 메서드에서 이 빠른 시작에서 사용되는 메서드에 대한 호출을 추가합니다. 나중에 만들겠습니다.

// Create an image review client
ContentModeratorClient clientImage = Authenticate(SubscriptionKey, Endpoint);
// Create a text review client
ContentModeratorClient clientText = Authenticate(SubscriptionKey, Endpoint);
// Create a human reviews client
ContentModeratorClient clientReviews = Authenticate(SubscriptionKey, Endpoint);
// Moderate text from text in a file
ModerateText(clientText, TextFile, TextOutputFile);
// Moderate images from list of image URLs
ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);

개체 모델

다음 클래스는 Content Moderator .NET 클라이언트 라이브러리의 주요 기능 중 일부를 처리합니다.

이름 설명
ContentModeratorClient 이 클래스는 모든 Content Moderator 기능에 필요합니다. 구독 정보를 사용하여 인스턴스화하고 이를 사용하여 다른 클래스의 인스턴스를 생성합니다.
ImageModeration 이 클래스는 성인 콘텐츠, 개인 정보 또는 사람의 얼굴에 대한 이미지를 분석하는 기능을 제공합니다.
TextModeration 이 클래스는 언어, 욕설, 오류 및 개인 정보에 대한 텍스트를 분석하는 기능을 제공합니다.

코드 예제

이러한 코드 조각은 .NET 위해 Content Moderator 클라이언트 라이브러리를 사용하여 다음 작업을 수행하는 방법을 보여 줍니다.

클라이언트 인증

새 메서드에서 엔드포인트 및 키를 사용하여 클라이언트 개체를 인스턴스화합니다.

public static ContentModeratorClient Authenticate(string key, string endpoint)
{
    ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
    client.Endpoint = endpoint;

    return client;
}

텍스트 조정

다음 코드는 Content Moderator 클라이언트를 사용하여 텍스트 본문을 분석하고 결과를 콘솔에 출력합니다. Program 클래스의 루트에서 입력 및 출력 파일을 정의합니다.

// TEXT MODERATION
// Name of the file that contains text
private static readonly string TextFile = "TextFile.txt";
// The name of the file to contain the output from the evaluation.
private static string TextOutputFile = "TextModerationOutput.txt";

그런 다음 프로젝트의 루트에 TextFile.txt 파일을 추가합니다. 이 파일에 고유한 텍스트를 추가하거나 다음 샘플 텍스트를 사용합니다.

Is this a grabage email abcdef@abcd.com, phone: 4255550111, IP: 255.255.255.255, 1234 Main Boulevard, Panapolis WA 96555.
<offensive word> is the profanity here. Is this information PII? phone 4255550111

그런 다음 Program 클래스의 어딘가에 텍스트 조정 메서드를 정의합니다.

/*
 * TEXT MODERATION
 * This example moderates text from file.
 */
public static void ModerateText(ContentModeratorClient client, string inputFile, string outputFile)
{
    Console.WriteLine("--------------------------------------------------------------");
    Console.WriteLine();
    Console.WriteLine("TEXT MODERATION");
    Console.WriteLine();
    // Load the input text.
    string text = File.ReadAllText(inputFile);

    // Remove carriage returns
    text = text.Replace(Environment.NewLine, " ");
    // Convert string to a byte[], then into a stream (for parameter in ScreenText()).
    byte[] textBytes = Encoding.UTF8.GetBytes(text);
    MemoryStream stream = new MemoryStream(textBytes);

    Console.WriteLine("Screening {0}...", inputFile);
    // Format text

    // Save the moderation results to a file.
    using (StreamWriter outputWriter = new StreamWriter(outputFile, false))
    {
        using (client)
        {
            // Screen the input text: check for profanity, classify the text into three categories,
            // do autocorrect text, and check for personally identifying information (PII)
            outputWriter.WriteLine("Autocorrect typos, check for matching terms, PII, and classify.");

            // Moderate the text
            var screenResult = client.TextModeration.ScreenText("text/plain", stream, "eng", true, true, null, true);
            outputWriter.WriteLine(JsonConvert.SerializeObject(screenResult, Formatting.Indented));
        }

        outputWriter.Flush();
        outputWriter.Close();
    }

    Console.WriteLine("Results written to {0}", outputFile);
    Console.WriteLine();
}

이미지 조정

다음 코드는 ImageModeration 개체와 함께 Content Moderator 클라이언트를 사용하여 성인 및 외설 콘텐츠에 대한 원격 이미지를 분석합니다.

참고

로컬 이미지의 콘텐츠를 분석할 수도 있습니다. 로컬 이미지와 함께 작동하는 메서드 및 작업에 대한 참조 설명서를 참조하세요.

샘플 이미지 가져오기

Program 클래스의 루트에서 입력 및 출력 파일을 정의합니다.

// IMAGE MODERATION
//The name of the file that contains the image URLs to evaluate.
private static readonly string ImageUrlFile = "ImageFiles.txt";
// The name of the file to contain the output from the evaluation.
private static string ImageOutputFile = "ImageModerationOutput.json";

그런 다음 프로젝트의 루트에 입력 파일ImageFiles.txt만듭니다. 이 파일에서는 분석할 이미지의 URL(각 줄에 하나의 URL)을 추가합니다. 다음 샘플 이미지를 사용할 수 있습니다.

https://moderatorsampleimages.blob.core.windows.net/samples/sample2.jpg
https://moderatorsampleimages.blob.core.windows.net/samples/sample5.png

도우미 클래스 정의

Program 클래스 내에 다음 클래스 정의를 추가합니다. 이 내부 클래스는 이미지 조정 결과를 처리합니다.

// Contains the image moderation results for an image, 
// including text and face detection results.
public class EvaluationData
{
    // The URL of the evaluated image.
    public string ImageUrl;

    // The image moderation results.
    public Evaluate ImageModeration;

    // The text detection results.
    public OCR TextDetection;

    // The face detection results;
    public FoundFaces FaceDetection;
}

이미지 조정 방법 정의

다음 메서드는 텍스트 파일의 이미지 URL을 반복하고 EvaluationData 인스턴스를 만들고 성인/외설 콘텐츠, 텍스트 및 사람의 얼굴에 대한 이미지를 분석합니다. 그런 다음, 최종 EvaluationData 인스턴스를 목록에 추가하고 반환된 데이터의 전체 목록을 콘솔에 씁니다.

이미지를 반복합니다.

/*
 * IMAGE MODERATION
 * This example moderates images from URLs.
 */
public static void ModerateImages(ContentModeratorClient client, string urlFile, string outputFile)
{
    Console.WriteLine("--------------------------------------------------------------");
    Console.WriteLine();
    Console.WriteLine("IMAGE MODERATION");
    Console.WriteLine();
    // Create an object to store the image moderation results.
    List<EvaluationData> evaluationData = new List<EvaluationData>();

    using (client)
    {
        // Read image URLs from the input file and evaluate each one.
        using (StreamReader inputReader = new StreamReader(urlFile))
        {
            while (!inputReader.EndOfStream)
            {
                string line = inputReader.ReadLine().Trim();
                if (line != String.Empty)
                {
                    Console.WriteLine("Evaluating {0}...", Path.GetFileName(line));
                    var imageUrl = new BodyModel("URL", line.Trim());

콘텐츠 분석

Content Moderator가 화면으로 표시하는 이미지 특성에 대한 자세한 내용은 이미지 조정 개념 가이드를 참조하세요 .

            var imageData = new EvaluationData
            {
                ImageUrl = imageUrl.Value,

                // Evaluate for adult and racy content.
                ImageModeration =
                client.ImageModeration.EvaluateUrlInput("application/json", imageUrl, true)
            };
            Thread.Sleep(1000);

            // Detect and extract text.
            imageData.TextDetection =
                client.ImageModeration.OCRUrlInput("eng", "application/json", imageUrl, true);
            Thread.Sleep(1000);

            // Detect faces.
            imageData.FaceDetection =
                client.ImageModeration.FindFacesUrlInput("application/json", imageUrl, true);
            Thread.Sleep(1000);

            // Add results to Evaluation object
            evaluationData.Add(imageData);
        }
    }
}

파일에 조정 결과 쓰기

        // Save the moderation results to a file.
        using (StreamWriter outputWriter = new StreamWriter(outputFile, false))
        {
            outputWriter.WriteLine(JsonConvert.SerializeObject(
                evaluationData, Formatting.Indented));

            outputWriter.Flush();
            outputWriter.Close();
        }
        Console.WriteLine();
        Console.WriteLine("Image moderation results written to output file: " + outputFile);
        Console.WriteLine();
    }
}

애플리케이션 실행

IDE 창 맨 위에 있는 디버그 단추를 클릭하여 애플리케이션을 실행합니다.

리소스 정리

Azure AI 서비스 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 연결된 다른 리소스도 삭제됩니다.

다음 단계

이 빠른 시작에서는 Content Moderator .NET 라이브러리를 사용하여 조정 작업을 수행하는 방법을 알아보았습니다. 다음으로, 개념 가이드를 읽어 이미지 또는 기타 미디어의 조정에 대해 자세히 알아봅니다.

Java Azure Content Moderator 클라이언트 라이브러리를 시작합니다. 다음 단계에 따라 Maven 패키지를 설치하고 기본 작업에 대한 예제 코드를 사용해 보세요.

Content Moderator는 잠재적으로 불쾌하거나 위험하거나 바람직하지 않은 콘텐츠를 처리할 수 있는 AI 서비스입니다. AI 기반 콘텐츠 조정 서비스를 사용하여 텍스트, 이미지 및 비디오를 검색하고 콘텐츠 플래그를 자동으로 적용합니다. 규정을 준수하거나 사용자에 대한 의도된 환경을 유지 관리하기 위해 앱에 콘텐츠 필터링 소프트웨어를 빌드합니다.

Java Content Moderator 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 텍스트 조정
  • 이미지 조정

리퍼런스 설명서 | 라이브러리 소스 코드 |아티팩트(Maven) | 샘플

필수 구성 요소

  • Azure 구독 - 무료로 구독 만들기
  • JDK(Java 개발 키트)
  • Gradle 빌드 도구 또는 다른 종속성 관리자.
  • Azure 구독이 있으면 Azure 포털에서 Content Moderator 리소스 생성하여 키와 엔드포인트를 가져옵니다. 배포할 때까지 기다렸다가 리소스로 이동 단추를 클릭합니다.
    • 애플리케이션을 Content Moderator에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 빠른 시작에서 나중에 아래 코드에 키와 엔드포인트를 붙여 넣게 됩니다.
    • 무료 가격 책정 계층(F0)을 사용하여 서비스를 사용해 볼 수 있으며 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.

설정

새 Gradle 프로젝트 만들기

콘솔 창(예: cmd, PowerShell 또는 Bash)에서 앱에 대한 새 디렉터리를 만들고 해당 디렉터리로 이동합니다.

mkdir myapp && cd myapp

gradle init 작업 디렉터리에서 명령을 실행합니다. 이 명령은 런타임에 애플리케이션을 만들고 구성하는 데 사용되는 build.gradle.kts를 포함하여 Gradle에 대한 필수 빌드 파일을 만듭니다.

gradle init --type basic

DSL을 선택하라는 메시지가 표시되면 Kotlin을 선택합니다.

클라이언트 라이브러리 설치

build.gradle.kts를 찾아 원하는 IDE 또는 텍스트 편집기를 사용하여 엽니다. 그런 다음, 다음 빌드 구성에서 복사합니다. 이 구성은 해당 진입점이 클래스 ContentModeratorQuickstart인 Java 애플리케이션으로 프로젝트를 정의합니다. JSON serialization용 Content Moderator 클라이언트 라이브러리 및 GSON sdk를 가져옵니다.

plugins {
    java
    application
}

application{ 
    mainClassName = "ContentModeratorQuickstart"
}

repositories{
    mavenCentral()
}

dependencies{
    compile(group = "com.microsoft.azure.cognitiveservices", name = "azure-cognitiveservices-contentmoderator", version = "1.0.2-beta")
    compile(group = "com.google.code.gson", name = "gson", version = "2.8.5")
}

Java 파일 만들기

작업 디렉터리에서 다음 명령을 실행하여 프로젝트 원본 폴더를 만듭니다.

mkdir -p src/main/java

새 폴더로 이동하여 ContentModeratorQuickstart.java 파일을 만듭니다. 기본 설정 편집기 또는 IDE에서 열고 다음 import 문을 추가합니다.

import com.google.gson.*;

import com.microsoft.azure.cognitiveservices.vision.contentmoderator.*;
import com.microsoft.azure.cognitiveservices.vision.contentmoderator.models.*;

import java.io.*;
import java.util.*;
import java.util.concurrent.*;

전체 빠른 시작 코드 파일을 한 번에 보고 싶으신가요? 이 빠른 시작의 코드 예제를 포함하는 GitHub에서 찾을 수 있습니다.

애플리케이션의 ContentModeratorQuickstart 클래스에서 리소스의 키 및 엔드포인트에 대한 변수를 만듭니다.

중요

Azure 포털로 이동합니다. 필수 구성 요소 섹션에서 만든 Content Moderator 리소스가 성공적으로 배포된 경우 다음 단계에서리소스로 이동 단추를 클릭합니다. 리소스 관리 아래의 리소스 키 및 엔드포인트 페이지에서 키와 엔드포인트를 찾을 수 있습니다.

private static final String subscriptionKey = "<your-subscription-key>";
private static final String endpoint = "<your-api-endpoint>";

중요

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault 같은 자격 증명을 저장하고 액세스하는 안전한 방법을 사용합니다. 자세한 내용은 Azure AI 서비스 security 문서를 참조하세요.

애플리케이션의 기본 메서드에서 이 빠른 시작에서 사용되는 메서드에 대한 호출을 추가합니다. 나중에 이러한 메서드를 정의합니다.

// Create a List in which to store the image moderation results.
List<EvaluationData> evaluationData = new ArrayList<EvaluationData>();

// Moderate URL images
moderateImages(client, evaluationData);
// Moderate text from file
moderateText(client);
// Create a human review
humanReviews(client);

개체 모델

다음 클래스는 Content Moderator Java 클라이언트 라이브러리의 주요 기능 중 일부를 처리합니다.

이름 설명
ContentModeratorClient 이 클래스는 모든 Content Moderator 기능에 필요합니다. 구독 정보를 사용하여 인스턴스화하고 이를 사용하여 다른 클래스의 인스턴스를 생성합니다.
ImageModeration 이 클래스는 성인 콘텐츠, 개인 정보 또는 사람의 얼굴에 대한 이미지를 분석하는 기능을 제공합니다.
TextModerations 이 클래스는 언어, 욕설, 오류 및 개인 정보에 대한 텍스트를 분석하는 기능을 제공합니다.

코드 예제

이러한 코드 조각은 Java Content Moderator 클라이언트 라이브러리를 사용하여 다음 작업을 수행하는 방법을 보여 줍니다.

클라이언트 인증

애플리케이션의 main 메서드에서 구독 엔드포인트 값 및 구독 키를 사용하여 ContentModeratorClient 개체를 만듭니다.

// Set CONTENT_MODERATOR_SUBSCRIPTION_KEY in your environment settings, with
// your key as its value.
// Set COMPUTER_MODERATOR_ENDPOINT in your environment variables with your Azure
// endpoint.
ContentModeratorClient client = ContentModeratorManager.authenticate(AzureRegionBaseUrl.fromString(endpoint),
        "CONTENT_MODERATOR_SUBSCRIPTION_KEY");

텍스트 조정

샘플 텍스트 설정

ContentModeratorQuickstart 클래스의 맨 위에서 로컬 텍스트 파일에 대한 참조를 정의합니다. 프로젝트 디렉터리에 .txt 파일을 추가하고 분석할 텍스트를 입력합니다.

// TEXT MODERATION variable
private static File textFile = new File("src\\main\\resources\\TextModeration.txt");

텍스트 분석

.txt 파일을 읽고 각 줄에서 screenText 메서드를 호출하는 새 메서드를 만듭니다.

public static void moderateText(ContentModeratorClient client) {
    System.out.println("---------------------------------------");
    System.out.println("MODERATE TEXT");
    System.out.println();

    try (BufferedReader inputStream = new BufferedReader(new FileReader(textFile))) {
        String line;
        Screen textResults = null;
        // For formatting the printed results
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        while ((line = inputStream.readLine()) != null) {
            if (line.length() > 0) {
                textResults = client.textModerations().screenText("text/plain", line.getBytes(), null);
                // Uncomment below line to print in console
                // System.out.println(gson.toJson(textResults).toString());
            }
        }

다음 코드를 추가하여 프로젝트 디렉터리의 .json 파일에 조정 결과를 출력합니다.

System.out.println("Text moderation status: " + textResults.status().description());
System.out.println();

// Create output results file to TextModerationOutput.json
BufferedWriter writer = new BufferedWriter(
        new FileWriter(new File("src\\main\\resources\\TextModerationOutput.json")));
writer.write(gson.toJson(textResults).toString());
System.out.println("Check TextModerationOutput.json to see printed results.");
System.out.println();
writer.close();

trycatch 문을 닫아 메서드를 완료합니다.

    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

이미지 조정

샘플 이미지 설정

새 메서드에서 이미지를 가리키는 지정된 URL 문자열을 사용하여 BodyModelModel 개체를 생성합니다.

public static void moderateImages(ContentModeratorClient client, List<EvaluationData> resultsList) {
    System.out.println();
    System.out.println("---------------------------------------");
    System.out.println("MODERATE IMAGES");
    System.out.println();

    try {
        String urlString = "https://moderatorsampleimages.blob.core.windows.net/samples/sample2.jpg";
        // Evaluate each line of text
        BodyModelModel url = new BodyModelModel();
        url.withDataRepresentation("URL");
        url.withValue(urlString);
        // Save to EvaluationData class for later
        EvaluationData imageData = new EvaluationData();
        imageData.ImageUrl = url.value();

도우미 클래스 정의

그런 다음 , ContentModeratorQuickstart.java 파일에서 ContentModeratorQuickstart 클래스 내에 다음 클래스 정의를 추가합니다. 이 내부 클래스는 이미지 조정 프로세스에서 사용됩니다.

// Contains the image moderation results for an image, including text and face
// detection from the image.
public static class EvaluationData {
    // The URL of the evaluated image.
    public String ImageUrl;
    // The image moderation results.
    public Evaluate ImageModeration;
    // The text detection results.
    public OCR TextDetection;
    // The face detection results;
    public FoundFaces FaceDetection;
}

콘텐츠 분석

이 코드 줄은 지정된 URL에서 성인 또는 외설 콘텐츠에 대한 이미지를 확인합니다. 이러한 용어에 대한 자세한 내용은 이미지 조정 개념 가이드를 참조하세요.

// Evaluate for adult and racy content.
imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
        new EvaluateUrlInputOptionalParameter().withCacheImage(true));
Thread.sleep(1000);

텍스트 확인

이 코드 줄은 이미지에서 표시되는 텍스트를 확인합니다.

// Detect and extract text from image.
imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
        new OCRUrlInputOptionalParameter().withCacheImage(true));
Thread.sleep(1000);

얼굴 확인

이 코드 줄은 사람의 얼굴에 대한 이미지를 확인합니다.

// Detect faces.
imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
        new FindFacesUrlInputOptionalParameter().withCacheImage(true));
Thread.sleep(1000);

마지막으로 반환된 정보를 목록에 저장합니다 EvaluationData .

resultsList.add(imageData);

루프 후에 while 결과를 출력하는 다음 코드를 추가합니다. 이 코드는 결과를 콘솔 및 출력 파일, src/main/resources/ModerationOutput.json에 저장합니다.

// Save the moderation results to a file.
// ModerationOutput.json contains the output from the evaluation.
// Relative paths are relative to the execution directory (where pom.xml is
// located).
BufferedWriter writer = new BufferedWriter(
        new FileWriter(new File("src\\main\\resources\\ImageModerationOutput.json")));
// For formatting the printed results
Gson gson = new GsonBuilder().setPrettyPrinting().create();

writer.write(gson.toJson(resultsList).toString());
System.out.println("Check ImageModerationOutput.json to see printed results.");
writer.close();

try 문을 닫고 catch 문을 추가하여 메서드를 완료합니다.

} catch (Exception e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
}

애플리케이션 실행

다음을 사용하여 앱을 빌드할 수 있습니다.

gradle build

다음 명령을 사용하여 애플리케이션을 실행합니다.gradle run

gradle run

그런 다음 src/main/resources/ModerationOutput.json 파일로 이동하여 콘텐츠 조정 결과를 확인합니다.

리소스 정리

Azure AI 서비스 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 연결된 다른 리소스도 삭제됩니다.

다음 단계

이 빠른 시작에서는 Content Moderator Java 라이브러리를 사용하여 조정 작업을 수행하는 방법을 알아보았습니다. 다음으로, 개념 가이드를 읽어 이미지 또는 기타 미디어의 조정에 대해 자세히 알아봅니다.

Python Azure Content Moderator 클라이언트 라이브러리를 시작합니다. 다음 단계에 따라 PiPy 패키지를 설치하고 기본 작업에 대한 예제 코드를 사용해 보세요.

Content Moderator는 잠재적으로 불쾌하거나 위험하거나 바람직하지 않은 콘텐츠를 처리할 수 있는 AI 서비스입니다. AI 기반 콘텐츠 조정 서비스를 사용하여 텍스트, 이미지 및 비디오를 검색하고 콘텐츠 플래그를 자동으로 적용합니다. 규정을 준수하거나 사용자에 대한 의도된 환경을 유지 관리하기 위해 앱에 콘텐츠 필터링 소프트웨어를 빌드합니다.

Python Content Moderator 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 텍스트 조정
  • 사용자 지정 용어 목록 사용
  • 이미지 조정
  • 사용자 지정 이미지 목록 사용

리퍼런스 설명서라이브러리 소스 코드패키지(PiPy)샘플

필수 구성 요소

  • Azure 구독 - 무료로 만들기
  • Python 3.x
    • Python 설치에는 pip 포함되어야 합니다. 명령줄에서 실행 pip --version 하여 pip가 설치되어 있는지 확인할 수 있습니다. 최신 버전의 Python 설치하여 pip를 가져옵니다.
  • Azure 구독이 있으면 Azure 포털에서 Content Moderator 리소스 생성하여 키와 엔드포인트를 가져옵니다. 배포할 때까지 기다렸다가 리소스로 이동 단추를 클릭합니다.
    • 애플리케이션을 Content Moderator에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 빠른 시작에서 나중에 아래 코드에 키와 엔드포인트를 붙여 넣게 됩니다.
    • 무료 가격 책정 계층(F0)을 사용하여 서비스를 사용해 볼 수 있으며 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.

설정

클라이언트 라이브러리 설치

Python 설치한 후 다음 명령을 사용하여 Content Moderator 클라이언트 라이브러리를 설치할 수 있습니다.

pip install --upgrade azure-cognitiveservices-vision-contentmoderator

새 Python 애플리케이션 만들기

새 Python 스크립트를 만들고 기본 설정 편집기 또는 IDE에서 엽니다. 그런 다음 파일 맨 위에 다음 import 문을 추가합니다.

import os.path
from pprint import pprint
import time
from io import BytesIO
from random import random
import uuid

from azure.cognitiveservices.vision.contentmoderator import ContentModeratorClient
import azure.cognitiveservices.vision.contentmoderator.models
from msrest.authentication import CognitiveServicesCredentials

전체 빠른 시작 코드 파일을 한 번에 보고 싶으신가요? 이 빠른 시작의 코드 예제를 포함하는 GitHub에서 찾을 수 있습니다.

다음으로, 리소스의 엔드포인트 위치 및 키에 대한 변수를 만듭니다.

중요

Azure 포털로 이동합니다. 필수 구성 요소 섹션에서 만든 Content Moderator 리소스가 성공적으로 배포된 경우 다음 단계에서리소스로 이동 단추를 클릭합니다. 리소스 관리 아래의 리소스 키 및 엔드포인트 페이지에서 키와 엔드포인트를 찾을 수 있습니다.

CONTENT_MODERATOR_ENDPOINT = "PASTE_YOUR_CONTENT_MODERATOR_ENDPOINT_HERE"
subscription_key = "PASTE_YOUR_CONTENT_MODERATOR_SUBSCRIPTION_KEY_HERE"

중요

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault 같은 자격 증명을 저장하고 액세스하는 안전한 방법을 사용합니다. 자세한 내용은 Azure AI 서비스 security 문서를 참조하세요.

개체 모델

다음 클래스는 Content Moderator Python 클라이언트 라이브러리의 주요 기능 중 일부를 처리합니다.

이름 설명
ContentModeratorClient 이 클래스는 모든 Content Moderator 기능에 필요합니다. 구독 정보를 사용하여 인스턴스화하고 이를 사용하여 다른 클래스의 인스턴스를 생성합니다.
ImageModerationOperations 이 클래스는 성인 콘텐츠, 개인 정보 또는 사람의 얼굴에 대한 이미지를 분석하는 기능을 제공합니다.
TextModerationOperations 이 클래스는 언어, 욕설, 오류 및 개인 정보에 대한 텍스트를 분석하는 기능을 제공합니다.

코드 예제

이러한 코드 조각은 Python Content Moderator 클라이언트 라이브러리를 사용하여 다음 작업을 수행하는 방법을 보여 줍니다.

클라이언트 인증

엔드포인트 및 키를 사용하여 클라이언트를 인스턴스화합니다. CognitiveServicesCredentials](/python/api/msrest/msrest.authentication.cognitiveservicescredentials 개체를 키와 함께 만들고 엔드포인트와 함께 사용하여 ContentModeratorClient 개체를 만듭니다.

client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)

텍스트 조정

다음 코드는 Content Moderator 클라이언트를 사용하여 텍스트 본문을 분석하고 결과를 콘솔에 출력합니다. 먼저 프로젝트의 루트에 text_files/ 폴더를 만들고 content_moderator_text_moderation.txt 파일을 추가합니다. 이 파일에 고유한 텍스트를 추가하거나 다음 샘플 텍스트를 사용합니다.

Is this a grabage email abcdef@abcd.com, phone: 4255550111, IP: 255.255.255.255, 1234 Main Boulevard, Panapolis WA 96555.
<offensive word> is the profanity here. Is this information PII? phone 2065550111

새 폴더에 대한 참조를 추가합니다.

TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")

그런 다음, Python 스크립트에 다음 코드를 추가합니다.

# Screen the input text: check for profanity,
# do autocorrect text, and check for personally identifying
# information (PII)
with open(os.path.join(TEXT_FOLDER, 'content_moderator_text_moderation.txt'), "rb") as text_fd:
    screen = client.text_moderation.screen_text(
        text_content_type="text/plain",
        text_content=text_fd,
        language="eng",
        autocorrect=True,
        pii=True
    )
    assert isinstance(screen, Screen)
    pprint(screen.as_dict())

사용자 지정 용어 목록 사용

다음 코드에서는 텍스트 조정에 대한 사용자 지정 용어 목록을 관리하는 방법을 보여 줍니다. ListManagementTermListsOperations 클래스를 사용하여 용어 목록을 만들고, 개별 용어를 관리하고, 다른 텍스트 본문을 차단할 수 있습니다.

샘플 텍스트 가져오기

이 샘플을 사용하려면 프로젝트의 루트에 text_files/ 폴더를 만들고 content_moderator_term_list.txt 파일을 추가해야 합니다. 이 파일에는 용어 목록에 대해 검사할 유기 텍스트가 포함되어야 합니다. 다음 샘플 텍스트를 사용할 수 있습니다.

This text contains the terms "term1" and "term2".

아직 정의하지 않은 경우 폴더에 대한 참조를 추가합니다.

TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")

목록 만들기

Python 스크립트에 다음 코드를 추가하여 사용자 지정 용어 목록을 만들고 해당 ID 값을 저장합니다.

#
# Create list
#
print("\nCreating list")
custom_list = client.list_management_term_lists.create(
    content_type="application/json",
    body={
        "name": "Term list name",
        "description": "Term list description",
    }
)
print("List created:")
assert isinstance(custom_list, TermList)
pprint(custom_list.as_dict())
list_id = custom_list.id

목록 세부 정보 정의

목록의 ID를 사용하여 이름과 설명을 편집할 수 있습니다.

#
# Update list details
#
print("\nUpdating details for list {}".format(list_id))
updated_list = client.list_management_term_lists.update(
    list_id=list_id,
    content_type="application/json",
    body={
        "name": "New name",
        "description": "New description"
    }
)
assert isinstance(updated_list, TermList)
pprint(updated_list.as_dict())

목록에 용어 추가

다음 코드는 "term1""term2" 용어를 목록에 추가합니다.

#
# Add terms
#
print("\nAdding terms to list {}".format(list_id))
client.list_management_term.add_term(
    list_id=list_id,
    term="term1",
    language="eng"
)
client.list_management_term.add_term(
    list_id=list_id,
    term="term2",
    language="eng"
)

목록의 모든 용어 가져오기

목록 ID를 사용하여 목록의 모든 용어를 반환할 수 있습니다.

#
# Get all terms ids
#
print("\nGetting all term IDs for list {}".format(list_id))
terms = client.list_management_term.get_all_terms(
    list_id=list_id, language="eng")
assert isinstance(terms, Terms)
terms_data = terms.data
assert isinstance(terms_data, TermsData)
pprint(terms_data.as_dict())

목록 인덱스 새로 고침

목록에서 용어를 추가하거나 제거할 때마다 업데이트된 목록을 사용하려면 먼저 인덱스를 새로 고쳐야 합니다.

#
# Refresh the index
#
print("\nRefreshing the search index for list {}".format(list_id))
refresh_index = client.list_management_term_lists.refresh_index_method(
    list_id=list_id, language="eng")
assert isinstance(refresh_index, RefreshIndex)
pprint(refresh_index.as_dict())

print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
    LATENCY_DELAY))
time.sleep(LATENCY_DELAY * 60)

목록과 화면 텍스트 비교

사용자 지정 용어 목록의 주요 기능은 텍스트 본문을 목록과 비교하고 일치하는 용어가 있는지 여부를 찾는 것입니다.

#
# Screen text
#
with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
    screen = client.text_moderation.screen_text(
        text_content_type="text/plain",
        text_content=text_fd,
        language="eng",
        autocorrect=False,
        pii=False,
        list_id=list_id
    )
    assert isinstance(screen, Screen)
    pprint(screen.as_dict())

목록에서 용어 제거

다음 코드는 목록에서 용어를 "term1" 제거합니다.

#
# Remove terms
#
term_to_remove = "term1"
print("\nRemove term {} from list {}".format(term_to_remove, list_id))
client.list_management_term.delete_term(
    list_id=list_id,
    term=term_to_remove,
    language="eng"
)

목록에서 모든 용어 제거

다음 코드를 사용하여 모든 용어 목록을 지웁니다.

#
# Delete all terms
#
print("\nDelete all terms in the image list {}".format(list_id))
client.list_management_term.delete_all_terms(
    list_id=list_id, language="eng")

목록 삭제

다음 코드를 사용하여 사용자 지정 용어 목록을 삭제합니다.

#
# Delete list
#
print("\nDelete the term list {}".format(list_id))
client.list_management_term_lists.delete(list_id=list_id)

이미지 조정

다음 코드는 ImageModerationOperations 개체와 함께 Content Moderator 클라이언트를 사용하여 성인 및 외설 콘텐츠에 대한 이미지를 분석합니다.

샘플 이미지 가져오기

분석할 일부 이미지에 대한 참조를 정의합니다.

IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.windows.net/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.windows.net/samples/sample5.png"
]

그런 다음, 다음 코드를 추가하여 이미지를 순회합니다. 이 섹션의 나머지 코드는 이 루프 내부로 이동합니다.

for image_url in IMAGE_LIST:
    print("\nEvaluate image {}".format(image_url))

성인/외설 콘텐츠 확인

다음 코드는 지정된 URL에서 성인 또는 외설 콘텐츠에 대한 이미지를 확인하고 결과를 콘솔에 출력합니다. 이러한 용어의 의미에 대한 자세한 내용은 이미지 조정 개념 가이드를 참조하세요.

print("\nEvaluate for adult and racy content.")
evaluation = client.image_moderation.evaluate_url_input(
    content_type="application/json",
    cache_image=True,
    data_representation="URL",
    value=image_url
)
assert isinstance(evaluation, Evaluate)
pprint(evaluation.as_dict())

표시되는 텍스트 확인

다음 코드는 표시되는 텍스트 콘텐츠에 대한 이미지를 확인하고 콘솔에 결과를 출력합니다.

print("\nDetect and extract text.")
evaluation = client.image_moderation.ocr_url_input(
    language="eng",
    content_type="application/json",
    data_representation="URL",
    value=image_url,
    cache_image=True,
)
assert isinstance(evaluation, OCR)
pprint(evaluation.as_dict())

얼굴 확인

다음 코드는 사람의 얼굴에 대한 이미지를 확인하고 콘솔에 결과를 출력합니다.

print("\nDetect faces.")
evaluation = client.image_moderation.find_faces_url_input(
    content_type="application/json",
    cache_image=True,
    data_representation="URL",
    value=image_url
)
assert isinstance(evaluation, FoundFaces)
pprint(evaluation.as_dict())

사용자 지정 이미지 목록 사용

다음 코드에서는 이미지 조정을 위해 이미지의 사용자 지정 목록을 관리하는 방법을 보여 줍니다. 이 기능은 플랫폼에서 화면으로 표시하려는 동일한 이미지 집합의 인스턴스를 자주 수신하는 경우에 유용합니다. 이러한 특정 이미지 목록을 유지 관리하면 성능을 향상시킬 수 있습니다. ListManagementImageListsOperations 클래스를 사용하면 이미지 목록을 만들고, 목록의 개별 이미지를 관리하고, 다른 이미지를 비교할 수 있습니다.

다음 텍스트 변수를 만들어 이 시나리오에서 사용할 이미지 URL을 저장합니다.

IMAGE_LIST = {
    "Sports": [
        "https://moderatorsampleimages.blob.core.windows.net/samples/sample4.png",
        "https://moderatorsampleimages.blob.core.windows.net/samples/sample6.png",
        "https://moderatorsampleimages.blob.core.windows.net/samples/sample9.png"
    ],
    "Swimsuit": [
        "https://moderatorsampleimages.blob.core.windows.net/samples/sample1.jpg",
        "https://moderatorsampleimages.blob.core.windows.net/samples/sample3.png",
        "https://moderatorsampleimages.blob.core.windows.net/samples/sample4.png",
        "https://moderatorsampleimages.blob.core.windows.net/samples/sample16.png"
    ]
}

IMAGES_TO_MATCH = [
    "https://moderatorsampleimages.blob.core.windows.net/samples/sample1.jpg",
    "https://moderatorsampleimages.blob.core.windows.net/samples/sample4.png",
    "https://moderatorsampleimages.blob.core.windows.net/samples/sample5.png",
    "https://moderatorsampleimages.blob.core.windows.net/samples/sample16.png"
]

참고

이는 적절한 목록 자체가 아니라 코드 섹션에 add images 추가될 비공식적인 이미지 목록입니다.

이미지 목록 만들기

다음 코드를 추가하여 이미지 목록을 만들고 해당 ID에 대한 참조를 저장합니다.

#
# Create list
#
print("Creating list MyList\n")
custom_list = client.list_management_image_lists.create(
    content_type="application/json",
    body={
        "name": "MyList",
        "description": "A sample list",
        "metadata": {
            "key_one": "Acceptable",
            "key_two": "Potentially racy"
        }
    }
)
print("List created:")
assert isinstance(custom_list, ImageList)
pprint(custom_list.as_dict())
list_id = custom_list.id

목록에 이미지 추가

다음 코드는 모든 이미지를 목록에 추가합니다.

print("\nAdding images to list {}".format(list_id))
index = {}  # Keep an index url to id for later removal
for label, urls in IMAGE_LIST.items():
    for url in urls:
        image = add_images(list_id, url, label)
        if image:
            index[url] = image.content_id

스크립트의 다른 위치에서 add_images 도우미 함수를 정의합니다.

#
# Add images
#
def add_images(list_id, image_url, label):
    """Generic add_images from url and label."""
    print("\nAdding image {} to list {} with label {}.".format(
        image_url, list_id, label))
    try:
        added_image = client.list_management_image.add_image_url_input(
            list_id=list_id,
            content_type="application/json",
            data_representation="URL",
            value=image_url,
            label=label
        )
    except APIErrorException as err:
        # sample4 will fail
        print("Unable to add image to list: {}".format(err))
    else:
        assert isinstance(added_image, Image)
        pprint(added_image.as_dict())
        return added_image

목록에서 이미지 가져오기

다음 코드는 목록에 있는 모든 이미지의 이름을 출력합니다.

#
# Get all images ids
#
print("\nGetting all image IDs for list {}".format(list_id))
image_ids = client.list_management_image.get_all_image_ids(list_id=list_id)
assert isinstance(image_ids, ImageIds)
pprint(image_ids.as_dict())

목록 세부 정보 업데이트

목록 ID를 사용하여 목록의 이름과 설명을 업데이트할 수 있습니다.

#
# Update list details
#
print("\nUpdating details for list {}".format(list_id))
updated_list = client.list_management_image_lists.update(
    list_id=list_id,
    content_type="application/json",
    body={
        "name": "Swimsuits and sports"
    }
)
assert isinstance(updated_list, ImageList)
pprint(updated_list.as_dict())

목록 세부 정보 가져오기

다음 코드를 사용하여 목록의 현재 세부 정보를 인쇄합니다.

#
# Get list details
#
print("\nGetting details for list {}".format(list_id))
list_details = client.list_management_image_lists.get_details(
    list_id=list_id)
assert isinstance(list_details, ImageList)
pprint(list_details.as_dict())

목록 인덱스 새로 고침

이미지를 추가하거나 제거한 후에는 목록 인덱스가 새로 고쳐져야 다른 이미지를 화면으로 표시할 수 있습니다.

#
# Refresh the index
#
print("\nRefreshing the search index for list {}".format(list_id))
refresh_index = client.list_management_image_lists.refresh_index_method(
    list_id=list_id)
assert isinstance(refresh_index, RefreshIndex)
pprint(refresh_index.as_dict())

print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
    LATENCY_DELAY))
time.sleep(LATENCY_DELAY * 60)

목록과 이미지 일치

이미지 목록의 주요 기능은 새 이미지를 비교하고 일치하는 항목이 있는지 확인하는 것입니다.

#
# Match images against the image list.
#
for image_url in IMAGES_TO_MATCH:
    print("\nMatching image {} against list {}".format(image_url, list_id))
    match_result = client.image_moderation.match_url_input(
        content_type="application/json",
        list_id=list_id,
        data_representation="URL",
        value=image_url,
    )
    assert isinstance(match_result, MatchResponse)
    print("Is match? {}".format(match_result.is_match))
    print("Complete match details:")
    pprint(match_result.as_dict())

목록에서 이미지 제거

다음 코드는 목록에서 항목을 제거합니다. 이 경우 목록 범주와 일치하지 않는 이미지입니다.

#
# Remove images
#
correction = "https://moderatorsampleimages.blob.core.windows.net/samples/sample16.png"
print("\nRemove image {} from list {}".format(correction, list_id))
client.list_management_image.delete_image(
    list_id=list_id,
    image_id=index[correction]
)

목록에서 모든 이미지 제거

이미지 목록을 지우려면 다음 코드를 사용합니다.

#
# Delete all images
#
print("\nDelete all images in the image list {}".format(list_id))
client.list_management_image.delete_all_images(list_id=list_id)

이미지 목록 삭제

다음 코드를 사용하여 지정된 이미지 목록을 삭제합니다.

#
# Delete list
#
print("\nDelete the image list {}".format(list_id))
client.list_management_image_lists.delete(list_id=list_id)

애플리케이션 실행

python 명령을 사용하여 시작 파일에서 앱을 실행하세요.

python quickstart-file.py

리소스 정리

Azure AI 서비스 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 연결된 다른 리소스도 삭제됩니다.

다음 단계

이 빠른 시작에서는 Content Moderator Python 라이브러리를 사용하여 조정 작업을 수행하는 방법을 알아보았습니다. 다음으로, 개념 가이드를 읽어 이미지 또는 기타 미디어의 조정에 대해 자세히 알아봅니다.

Azure Content Moderator REST API를 시작합니다.

Content Moderator는 잠재적으로 불쾌하거나 위험하거나 바람직하지 않은 콘텐츠를 처리할 수 있는 AI 서비스입니다. AI 기반 콘텐츠 조정 서비스를 사용하여 텍스트, 이미지 및 비디오를 검색하고 콘텐츠 플래그를 자동으로 적용합니다. 규정을 준수하거나 사용자에 대한 의도된 환경을 유지 관리하기 위해 앱에 콘텐츠 필터링 소프트웨어를 빌드합니다.

Content Moderator REST API를 사용하여 다음을 수행합니다.

  • 텍스트 조정
  • 이미지 조정

필수 구성 요소

  • Azure 구독 - 무료로 만들기
  • Azure 구독이 있으면 Azure 포털에서 Content Moderator 리소스 생성하여 키와 엔드포인트를 가져옵니다. 배포할 때까지 기다렸다가 리소스로 이동 단추를 클릭합니다.
    • 애플리케이션을 Content Moderator에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 빠른 시작에서 나중에 아래 코드에 키와 엔드포인트를 붙여 넣게 됩니다.
    • 무료 가격 책정 계층(F0)을 사용하여 서비스를 사용해 볼 수 있으며 나중에 프로덕션용 유료 계층으로 업그레이드할 수 있습니다.
  • PowerShell 버전 6.0 이상 또는 유사한 명령줄 애플리케이션.

텍스트 조정

다음과 같은 명령을 사용하여 Content Moderator API를 호출하여 텍스트 본문을 분석하고 결과를 콘솔에 출력합니다.

curl -v -X POST "https://westus.api.cognitive.microsoft.com/contentmoderator/moderate/v1.0/ProcessText/Screen?autocorrect=True&PII=True&classify=True&language={string}"
-H "Content-Type: text/plain"
-H "Ocp-Apim-Subscription-Key: {subscription key}"
--data-ascii "Is this a crap email abcdef@abcd.com, phone: 6657789887, IP: 255.255.255.255, 1 Microsoft Way, Redmond, WA 98052"

명령을 텍스트 편집기로 복사하고 다음을 변경합니다.

  1. 유효한 Face 구독 키에 Ocp-Apim-Subscription-Key를 할당합니다.

    중요

    완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault 같은 자격 증명을 저장하고 액세스하는 안전한 방법을 사용합니다. 자세한 내용은 Azure AI 서비스 security 문서를 참조하세요.

  2. 구독 키에 해당하는 엔드포인트와 일치하도록 쿼리 URL의 첫 번째 부분을 변경합니다.

    참고

    2019년 7월 1일 이후에 만들어진 새 리소스는 사용자 지정 하위 도메인 이름을 사용합니다. 자세한 내용과 지역 엔드포인트의 전체 목록은 Foundry 도구에 대한 사용자 지정 하위 도메인 이름을 참조하세요.

  3. 필요에 따라 요청 본문을 분석하려는 텍스트 문자열로 변경합니다.

변경한 후 명령 프롬프트를 열고 새 명령을 입력합니다.

결과를 분석하십시오

콘솔 창에 JSON 데이터로 표시되는 텍스트 조정 결과가 표시됩니다. 예를 들어:

{
  "OriginalText": "Is this a <offensive word> email abcdef@abcd.com, phone: 6657789887, IP: 255.255.255.255,\n1 Microsoft Way, Redmond, WA 98052\n",
  "NormalizedText": "Is this a <offensive word> email abide@ abed. com, phone: 6657789887, IP: 255. 255. 255. 255, \n1 Microsoft Way, Redmond, WA 98052",
  "AutoCorrectedText": "Is this a <offensive word> email abide@ abed. com, phone: 6657789887, IP: 255. 255. 255. 255, \n1 Microsoft Way, Redmond, WA 98052",
  "Misrepresentation": null,
  "PII": {
    "Email": [
      {
        "Detected": "abcdef@abcd.com",
        "SubType": "Regular",
        "Text": "abcdef@abcd.com",
        "Index": 21
      }
    ],
    "IPA": [
      {
        "SubType": "IPV4",
        "Text": "255.255.255.255",
        "Index": 61
      }
    ],
    "Phone": [
      {
        "CountryCode": "US",
        "Text": "6657789887",
        "Index": 45
      }
    ],
    "Address": [
      {
        "Text": "1 Microsoft Way, Redmond, WA 98052",
        "Index": 78
      }
    ]
  },
 "Classification": {
    "Category1": 
    {
      "Score": 0.5
    },
    "Category2": 
    {
      "Score": 0.6
    },
    "Category3": 
    {
      "Score": 0.5
    },
    "ReviewRecommended": true
  },
  "Language": "eng",
  "Terms": [
    {
      "Index": 10,
      "OriginalIndex": 10,
      "ListId": 0,
      "Term": "<offensive word>"
    }
  ],
  "Status": {
    "Code": 3000,
    "Description": "OK",
    "Exception": null
  },
  "TrackingId": "1717c837-cfb5-4fc0-9adc-24859bfd7fac"
}

Content Moderator가 화면으로 표시하는 텍스트 특성에 대한 자세한 내용은 텍스트 조정 개념 가이드를 참조하세요 .

이미지 조정

다음과 같은 명령을 사용하여 Content Moderator API를 호출하여 원격 이미지를 조정하고 결과를 콘솔에 출력합니다.

curl -v -X POST "https://westus.api.cognitive.microsoft.com/contentmoderator/moderate/v1.0/ProcessImage/Evaluate?CacheImage={boolean}" 
-H "Content-Type: application/json"
-H "Ocp-Apim-Subscription-Key: {subscription key}" 
--data-ascii "{\"DataRepresentation\":\"URL\", \"Value\":\"https://moderatorsampleimages.blob.core.windows.net/samples/sample.jpg\"}"

명령을 텍스트 편집기로 복사하고 다음을 변경합니다.

  1. 유효한 Face 구독 키에 Ocp-Apim-Subscription-Key를 할당합니다.
  2. 구독 키에 해당하는 엔드포인트와 일치하도록 쿼리 URL의 첫 번째 부분을 변경합니다.
  3. 필요에 따라 요청 본문의 "Value" URL을 조정하려는 원격 이미지로 변경합니다.

바이트 데이터를 요청 본문에 전달하여 로컬 이미지를 조정할 수도 있습니다. 이 작업을 수행하는 방법에 대한 자세한 내용은 참조 설명서를 참조하세요.

변경한 후 명령 프롬프트를 열고 새 명령을 입력합니다.

결과를 분석하십시오

콘솔 창에 JSON 데이터로 표시되는 이미지 조정 결과가 표시됩니다.

{
  "AdultClassificationScore": x.xxx,
  "IsImageAdultClassified": <Bool>,
  "RacyClassificationScore": x.xxx,
  "IsImageRacyClassified": <Bool>,
  "AdvancedInfo": [],
  "Result": false,
  "Status": {
    "Code": 3000,
    "Description": "OK",
    "Exception": null
  },
  "TrackingId": "<Request Tracking Id>"
}

Content Moderator가 화면으로 표시하는 이미지 특성에 대한 자세한 내용은 이미지 조정 개념 가이드를 참조하세요 .

리소스 정리

Azure AI 서비스 구독을 정리하고 제거하려면 리소스 또는 리소스 그룹을 삭제할 수 있습니다. 리소스 그룹을 삭제하면 연결된 다른 리소스도 삭제됩니다.

다음 단계

이 빠른 시작에서는 Content Moderator REST API를 사용하여 조정 작업을 수행하는 방법을 알아보았습니다. 다음으로, 개념 가이드를 읽어 이미지 또는 기타 미디어의 조정에 대해 자세히 알아봅니다.