快速入門:使用 Content Moderator 用戶端連結庫

重要

Azure Content Moderator 即將在 2024 年 2 月淘汰,將於 2027 年 2 月淘汰。 它正由 Azure AI 內容 保管庫 ty 取代,其提供進階 AI 功能和增強的效能。

Azure AI 內容 保管庫 ty 是一個完整的解決方案,其設計目的是在應用程式和服務中偵測有害的用戶產生和 AI 產生的內容。 Azure AI 內容 保管庫 ty 適用於許多案例,例如在線市集、遊戲公司、社交訊息平臺、企業媒體公司和 K-12 教育解決方案提供者。 以下是其特性和功能的概觀:

  • 文字和影像偵測 API:使用多個嚴重性層級掃描文字和影像中是否有性內容、暴力、仇恨和自我傷害。
  • 內容 保管庫 ty Studio:在線工具,其設計目的是使用我們最新的 con 帳篷模式 ration ML 模型來處理潛在的冒犯性、風險或不想要的內容。 它提供範本和自定義工作流程,讓用戶能夠建置自己的 con 帳篷模式 ration 系統。
  • 語言支援:Azure AI 內容 保管庫 ty 支援超過 100 種語言,並特別針對英文、德文、日文、西班牙文、法文、義大利文、葡萄牙文和中文進行訓練。

Azure AI 內容 保管庫 ty 為您的 con 帳篷模式 ration 需求提供健全且彈性的解決方案。 藉由從 Content Moderator 切換至 Azure AI 內容 保管庫 ty,您可以利用最新的工具和技術來確保您的內容一律會仲裁到確切的規格。

深入瞭解 Azure AI 內容 保管庫,並探索其如何提升您的 con 帳篷模式 ration 策略。

開始使用適用於 .NET 的 Azure Content Moderator 用戶端連結庫。 請遵循下列步驟來安裝 NuGet 套件,並試用基本工作的範例程序代碼。

Content Moderator 是一項 AI 服務,可讓您處理可能具冒犯性、有風險或不想要的內容。 使用 AI 支援的 con 帳篷模式 ration 服務來掃描文字、影像和影片,並自動套用內容旗標。 將內容篩選軟體建置至您的應用程式,以符合法規或維護使用者的預期環境。

使用適用於 .NET 的 Content Moderator 用戶端連結庫來:

  • 中度文字
  • 仲裁影像

參考文檔 | 庫原始程式碼 | 套件 (NuGet)範例 |

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶
  • Visual Studio IDE 或 .NET Core目前版本。
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立 Content Moderator 資源,以取得您的密鑰和端點。 等候部署,然後按兩下 [移至資源 ] 按鈕。
    • 您需要從您建立的資源取得密鑰和端點,才能將應用程式連線到 Content Moderator。 您稍後會在快速入門中將金鑰和端點貼到下列程式代碼中。
    • 您可以使用免費定價層 (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 入口網站。 如果您在部署成功的必要條件一節中建立的 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 金鑰保存庫。 如需詳細資訊,請參閱 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 物件來分析成人和猥褻內容的遠端影像。

注意

您也可以分析本機影像的內容。 如需使用本機映射的方法和作業,請參閱參考檔

取得範例影像

在 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 支援的 con 帳篷模式 ration 服務來掃描文字、影像和影片,並自動套用內容旗標。 將內容篩選軟體建置至您的應用程式,以符合法規或維護使用者的預期環境。

使用適用於 Java 的 Content Moderator 用戶端連結庫來:

  • 中度文字
  • 仲裁影像

參考文檔庫原始碼 |成品 | (Maven)範例 |

必要條件

設定

建立新的 Gradle 專案

在主控台視窗中(例如 cmd、PowerShell 或 Bash),為您的應用程式建立新的目錄,然後流覽至它。

mkdir myapp && cd myapp

gradle init從工作目錄執行 命令。 此命令會建立 Gradle 的基本組建檔案,包括 用於運行時間建立及設定應用程式的 build.gradle.kts

gradle init --type basic

當系統提示您選擇 DSL 時,請選取 [Kotlin]。

安裝客戶端連結庫

尋找 build.gradle.kts ,並使用您慣用的 IDE 或文字編輯器加以開啟。 然後複製下列組建組態。 此組態會將項目定義為 Java 應用程式,其進入點為 ContentModeratorQuickstart 類別。 它會匯入 Content Moderator 用戶端連結庫和 GSON SDK 以進行 JSON 串行化。

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 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

在應用程式的主要方法中,新增本快速入門中使用的方法呼叫。 您稍後會定義這些方法。

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

try關閉和 catch 語句以完成 方法。

    } 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 檔案,並檢視您的 con 帳篷模式 ration 結果。

清除資源

如果您想要清除和移除 Azure AI 服務訂用帳戶,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

下一步

在本快速入門中,您已瞭解如何使用 Content Moderator Java 連結庫來執行仲裁工作。 接下來,閱讀概念指南,以深入瞭解影像或其他媒體的仲裁。

開始使用適用於 Python 的 Azure Content Moderator 用戶端連結庫。 請遵循下列步驟來安裝 PiPy 套件,並試用基本工作的範例程式代碼。

Content Moderator 是一項 AI 服務,可讓您處理可能具冒犯性、有風險或不想要的內容。 使用 AI 支援的 con 帳篷模式 ration 服務來掃描文字、影像和影片,並自動套用內容旗標。 將內容篩選軟體建置至您的應用程式,以符合法規或維護使用者的預期環境。

使用適用於 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 金鑰保存庫。 如需詳細資訊,請參閱 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 腳本,以建立自定義字詞清單並儲存其識別碼。

#
# 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

定義清單詳細數據

您可以使用清單的識別碼來編輯其名稱和描述。

#
# 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"
)

取得清單中的所有字詞

您可以使用清單識別碼來傳回清單中的所有字詞。

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

注意

這不是適當的清單本身,而是將在程式碼區段中新增 add images 的非正式影像清單。

建立映像清單

新增下列程式代碼以建立映像清單,並儲存其標識碼的參考。

#
# 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())

更新清單詳細數據

您可以使用清單識別碼來更新清單的名稱和描述。

#
# 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 支援的 con 帳篷模式 ration 服務來掃描文字、影像和影片,並自動套用內容旗標。 將內容篩選軟體建置至您的應用程式,以符合法規或維護使用者的預期環境。

使用 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. 指派 Ocp-Apim-Subscription-Key 給您有效的臉部訂用帳戶密鑰。

    重要

    當您完成時,請記得從程式碼中移除密鑰,且絕不會公開發佈。 針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

  2. 變更查詢 URL 的第一個部分,以符合對應至訂用帳戶密鑰的端點。

    注意

    在 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 給您有效的臉部訂用帳戶密鑰。
  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 來執行仲裁工作。 接下來,閱讀概念指南,以深入瞭解影像或其他媒體的仲裁。