クイック スタート:Content Moderator クライアント ライブラリを使用する

重要

Azure Content Moderator は 2024 年 2 月に非推奨となり、2027 年 2 月までに廃止される予定です。 これは、高度な AI 機能とパフォーマンス強化を提供する Azure AI Content Safety に置き換えられている最中です。

Azure AI Content Safety は、アプリケーションやサービスでユーザーまたは AI によって生成された有害コンテンツを検出するように設計された包括的なソリューションです。 Azure AI Content Safety は、オンライン マーケットプレース、ゲーム会社、ソーシャル メッセージング プラットフォーム、エンタープライズ メディア企業、K-12 教育ソリューション プロバイダーなど、多くのシナリオに適しています。 その特徴と機能の概要を次に示します。

  • テキストと画像を検出する API: テキストと画像をスキャンし、多様な重大度レベルで性的コンテンツ、暴力、憎悪、自傷行為を検出します。
  • Content Safety Studio: 最先端のコンテンツ モデレーション ML モデルを使用し、不快、危険、有害となる可能性があるコンテンツを処理するように設計されたオンライン ツール。 テンプレートとカスタマイズされたワークフローを備えており、ユーザーは独自のコンテンツ モデレーション システムを構築できます。
  • 言語サポート: Azure AI Content Safety は 100 を超える言語をサポートしており、とりわけ、英語、ドイツ語、日本語、スペイン語、フランス語、イタリア語、ポルトガル語、中国語でトレーニングされています。

Azure AI Content Safety は、コンテンツ モデレーションのニーズに対して堅牢で柔軟なソリューションを提供します。 Content Moderator から Azure AI Content Safety に切り替えることで、コンテンツが常に仕様に厳密に合わせてモデレートされるよう、最新のツールとテクノロジを活用できます。

Azure AI Content Safety の詳細はこちらをご覧いただき、コンテンツ モデレーション戦略を高める方法を模索してください。

.NET 用 Azure Content Moderator クライアント ライブラリの使用を開始します。 以下の手順に従って、NuGet パッケージをインストールし、基本タスクのコード例を試してみましょう。

Content Moderator は、不快感を与える可能性がある内容、リスクのある内容、その他望ましくない可能性のある内容を管理できる AI サービスです。 AI を利用したコンテンツ モデレーション サービスを使用して、テキスト、画像、ビデオをスキャンし、コンテンツ フラグを自動的に適用します。 法的規制に準拠したり、ユーザーに意図されている環境を維持したりするために、コンテンツ フィルタリング ソフトウェアをアプリに組み込みます。

.NET 用 Content Moderator クライアント ライブラリは、次の目的で使用できます。

  • テキストのモデレート
  • 画像のモデレート

リファレンスのドキュメント | ライブラリのソース コード | パッケージ (NuGet) | サンプル

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • Visual Studio IDE または現在のバージョンの .NET Core
  • Azure サブスクリプションを入手したら、Azure portal で Content Moderator リソースを作成し、キーとエンドポイントを取得します。 デプロイするまで待ち、 [リソースに移動] ボタンをクリックします。
    • 対象のアプリケーションを Content Moderator に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
    • Free 価格レベル (F0) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。

設定

新しい C# アプリケーションを作成する

Visual Studio を使用して、新しい .NET Core アプリケーションを作成します。

クライアント ライブラリをインストールする

新しいプロジェクトを作成したら、ソリューション エクスプローラーでプロジェクト ソリューションを右クリックし、 [NuGet パッケージの管理] を選択して、クライアント ライブラリをインストールします。 パッケージ マネージャーが開いたら、[参照] を選択し、[プレリリースを含める] をオンにして、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 Portal にアクセスします。 「前提条件」セクションで作成した Content Moderator リソースが正常にデプロイされた場合、 [次の手順] の下にある [リソースに移動] ボタンをクリックします。 キーとエンドポイントは、リソースの [key and endpoint](キーとエンドポイント) ページの [リソース管理] にあります。

// 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 サービスのセキュリティに関する記事を参照してください。

アプリケーションの 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();
}

画像のモデレート

次のコードでは、Content Moderator クライアントが ImageModeration オブジェクトとともに使用され、成人向けコンテンツやきわどい内容のリモート画像が分析されます。

Note

ローカルの画像コンテンツを分析することもできます。 ローカル画像を操作するメソッドと操作については、リファレンス ドキュメントを参照してください。

サンプル イメージの取得

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 を追加して行ごとに 1 つの 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 サブスクリプション - 無料アカウントを作成します
  • 最新バージョンの Java Development Kit (JDK)
  • Gradle ビルド ツール、または別の依存関係マネージャー。
  • Azure サブスクリプションを入手したら、Azure portal で Content Moderator リソースを作成し、キーとエンドポイントを取得します。 デプロイするまで待ち、 [リソースに移動] ボタンをクリックします。
    • 対象のアプリケーションを Content Moderator に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
    • Free 価格レベル (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 アプリケーションとしてプロジェクトを定義します。 これにより、Content Moderator クライアント ライブラリと、JSON シリアル化用に 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 Portal にアクセスします。 「前提条件」セクションで作成した Content Moderator リソースが正常にデプロイされた場合、 [次の手順] の下にある [リソースに移動] ボタンをクリックします。 キーとエンドポイントは、リソースの [key and endpoint](キーとエンドポイント) ページの [リソース管理] にあります。

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

重要

終わったらコードからキーを削除し、公開しないよう注意してください。 運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 詳細については、Azure AI サービスのセキュリティに関する記事を参照してください。

アプリケーションの main メソッドで、このクイックスタートで使用するメソッドの呼び出しを追加します。 これらのメソッドは後で定義します。

// 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();
    }
}

画像のモデレート

サンプル画像を設定する

新しいメソッドで BodyModelModel オブジェクトを構築し、画像を指し示す URL 文字列を渡します。

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 がインストールされているかどうかを確認するには、コマンド ラインで pip --version を実行します。 最新バージョンの Python をインストールして pip を入手してください。
  • Azure サブスクリプションを入手したら、Azure portal で Content Moderator リソースを作成し、キーとエンドポイントを取得します。 デプロイするまで待ち、 [リソースに移動] ボタンをクリックします。
    • 対象のアプリケーションを Content Moderator に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
    • Free 価格レベル (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 Portal にアクセスします。 「前提条件」セクションで作成した Content Moderator リソースが正常にデプロイされた場合、 [次の手順] の下にある [リソースに移動] ボタンをクリックします。 キーとエンドポイントは、リソースの [key and endpoint](キーとエンドポイント) ページの [リソース管理] にあります。

CONTENT_MODERATOR_ENDPOINT = "PASTE_YOUR_CONTENT_MODERATOR_ENDPOINT_HERE"
subscription_key = "PASTE_YOUR_CONTENT_MODERATOR_SUBSCRIPTION_KEY_HERE"

重要

終わったらコードからキーを削除し、公開しないよう注意してください。 運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 詳細については、Azure AI サービスのセキュリティに関する記事を参照してください。

オブジェクト モデル

以下のクラスでは、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)

画像のモデレート

次のコードでは、Content Moderator クライアントが ImageModerationOperations オブジェクトとともに使用され、成人向けコンテンツやきわどい内容の画像が分析されます。

サンプル イメージの取得

分析する画像に対する参照を定義します。

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"
]

Note

これは適切なリスト自体ではありませんが、コードの 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 portal で Content Moderator リソースを作成し、キーとエンドポイントを取得します。 デプロイするまで待ち、 [リソースに移動] ボタンをクリックします。
    • 対象のアプリケーションを Content Moderator に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
    • Free 価格レベル (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. Ocp-Apim-Subscription-Key を、有効な Face サブスクリプション キーに割り当てます。

    重要

    終わったらコードからキーを削除し、公開しないよう注意してください。 運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 詳細については、Azure AI サービスのセキュリティに関する記事を参照してください。

  2. このクエリ URL の最初の部分を、ご自分のサブスクリプション キーに対応するエンドポイントに合わせて変更します。

    Note

    2019 年 7 月 1 日より後に作成された新しいリソースには、カスタム サブドメイン名が使用されます。 リージョンのエンドポイントの詳細および全一覧については、「Azure AI サービスのカスタム サブドメイン名」を参照してください。

  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. Ocp-Apim-Subscription-Key を、有効な Face サブスクリプション キーに割り当てます。
  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 を使用して、モデレーション タスクを行う方法について学習しました。 次は、概念的なガイドを読んで、画像や他のメディアのモデレーションに関する詳細について学習します。