快速入門:使用 Content Moderator 客戶端函式庫

重要

Azure 內容版主自 2024 年 2 月起已不再使用,將於 2027 年 3 月 15 日正式退休。 它被 Azure AI 內容安全 取代,後者提供先進的 AI 功能與提升的效能。

Azure AI 內容安全 是一項全面的解決方案,旨在偵測應用程式與服務中有害的用戶生成及 AI 生成內容。 Azure AI 內容安全 適用於多種情境,如線上市場、遊戲公司、社交訊息平台、企業媒體公司及 K-12 教育解決方案提供者。 以下是其功能與能力的概述:

  • 文字與影像偵測 API:掃描多種嚴重程度的文字與圖片,偵測性內容、暴力、仇恨及自我傷害。
  • Content Safety Studio:一款線上工具,設計用來處理可能冒犯、風險或不受歡迎的內容,採用我們最新的內容審核機器學習模型。 它提供範本與客製化工作流程,讓使用者能建立自己的內容審核系統。
  • 語言支援:Azure AI 內容安全支援超過100種語言,並專門訓練英語、德語、日語、西班牙語、法語、義大利語、葡萄牙語及中文。

Azure AI 內容安全 提供強大且靈活的解決方案,滿足您的內容審核需求。 透過從內容管理員切換到 Azure AI 內容安全,您可以善用最新工具與技術,確保您的內容始終依照您的規格進行審核。

了解更多關於 Azure AI 內容安全 並探討它如何提升你的內容審核策略。

開始使用 Azure Content Moderator 的 .NET 客戶端函式庫。 請依照以下步驟安裝 NuGet 套件,並嘗試範例程式碼來執行基本任務。

內容管理員是一項人工智慧服務,讓你能處理可能冒犯、風險或其他不理想的內容。 使用由 AI 驅動的內容審核服務掃描文字、圖片和影片,並自動套用內容標記。 在您的應用程式中內建內容過濾軟體,以符合法規或維持使用者預期的環境。

使用 .NET 的內容管理員客戶端函式庫來:

  • 溫和文本
  • 審核影像

參考文件 | 函式庫原始碼 | Package (NuGet) | Samples

先決條件

  • Azure訂閱 - 免費建立一個
  • Visual Studio IDE或目前版本的 .NET Core。
  • 一旦你訂閱了Azure,在Azure入口網站建立內容管理員資源 以取得你的金鑰和端點。 等它部署完,然後點擊 「前往資源 」按鈕。
    • 你需要從你建立的資源中取得金鑰和端點,才能將應用程式連接到內容管理員。 你會在快速入門過程中,把你的金鑰和端點貼上到下面的程式碼中。
    • 你可以先用免費價格等級F0()試用服務,之後再升級到付費等級以進行生產。

設定

建立一個新的 C# 應用程式

使用 Visual Studio,建立一個新的 .NET Core 應用程式。

安裝用戶端函式庫

建立新專案後,請在 方案總管 右鍵點擊專案解決方案,並選擇 Manage NuGet Packages 安裝客戶端函式庫。 在開啟套件管理器時,選擇 Browse,勾選 Include prerelease,並搜尋 Microsoft.Azure.CognitiveServices.ContentModerator。 選擇版本 2.0.0,然後 安裝。

提示

想一次查看整個快速啟動程式碼檔案嗎? 你可以在 GitHub 找到它,裡面包含了這個快速入門的程式碼範例。

從專案目錄中,在你偏好的編輯器或整合開發環境中開啟 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;

在 程式 類別中,為資源的鍵與端點建立變數。

重要

前往 Azure 入口網站。 如果你在前置條件區塊建立的內容管理員資源成功部署,請點擊「下一步」下的「前往資源」按鈕。 你可以在資源的 金鑰與端點 頁面,在 資源管理的頁面找到你的金鑰和端點。

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

物件模型

以下類別處理內容管理員 .NET 用戶端函式庫的一些主要功能。

名稱 描述
ContentModeratorClient 此類別是所有內容版主功能所必需的。 你用訂閱資訊實例化它,並用它來產生其他類別的實例。
圖片管理 此類別提供分析影像是否含有成人內容、個人資訊或人臉的功能。
文字審核 此課程提供分析文本語言、髒話、錯誤及個人資訊的功能。

程式碼範例

這些程式碼片段展示了如何使用 .NET 內容管理員客戶端函式庫執行以下任務:

驗證客戶端

用新方法,用端點和鍵實例化客戶端物件。

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

    return client;
}

溫和文本

以下程式碼使用內容管理員用戶端分析正文,並將結果列印到主控台。 在 你的程式 類別根目錄中,定義輸入與輸出檔案:

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

接著在 你的程式 類別中定義文字審核方法:

/*
 * 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 物件,分析遠端影像中的成人及大膽內容。

註

你也可以分析當地圖片的內容。 請參閱 參考文件 ,了解如何處理本地影像的方法與操作。

取得範例圖片

在 程式 類別的根節點定義你的輸入與輸出檔案:

// 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。 在這個檔案中,你會新增要分析的圖片網址——每行一個網址。 你可以使用以下範例圖片:

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

定義輔助類別

在 程式 類別中加入以下類別定義。 這個內部類別會處理影像審查的結果。

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

定義影像調製方法

以下方法是遍歷文字檔中的圖片網址,建立 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());

分析內容

欲了解更多內容版主篩選圖片屬性的資訊,請參閱 圖片審核概念 指南。

            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 服務 訂閱,可以刪除該資源或資源群組。 刪除資源群組也會刪除與之相關的其他資源。

下一步

在這個快速入門中,你學會了如何使用內容管理員 .NET 函式庫來執行審核任務。 接著,請閱讀概念指南,進一步了解影像或其他媒體的審核。

開始使用 Azure Content Moderator 的 Java 客戶端函式庫。 請依照以下步驟安裝 Maven 套件,並嘗試範例程式碼來執行基本任務。

內容管理員是一項人工智慧服務,讓你能處理可能冒犯、風險或其他不理想的內容。 使用由 AI 驅動的內容審核服務掃描文字、圖片和影片,並自動套用內容標記。 在您的應用程式中內建內容過濾軟體,以符合法規或維持使用者預期的環境。

使用 Java 的 Content Moderator 用戶端函式庫來:

  • 溫和文本
  • 審核影像

參考文件 | 程式庫原始碼 |Artifact (Maven) | 範例

先決條件

  • Azure訂閱 - 免費建立
  • 目前版本的 Java 開發套件(JDK)
  • Gradle 建置工具,或其他相依管理工具。
  • 一旦你訂閱了Azure,在Azure入口網站建立內容管理員資源 以取得你的金鑰和端點。 等它部署完,然後點擊 「前往資源 」按鈕。
    • 你需要從你建立的資源中取得金鑰和端點,才能將應用程式連接到內容管理員。 你會在快速入門過程中,把你的金鑰和端點貼上到下面的程式碼中。
    • 你可以先用免費價格等級F0()試用服務,之後再升級到付費等級以進行生產。

設定

建立一個新的 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。 它匯入了內容管理員客戶端函式庫和 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 入口網站。 如果你在前置條件區塊建立的內容管理員資源成功部署,請點擊「下一步」下的「前往資源」按鈕。 你可以在資源的 金鑰與端點 頁面,在 資源管理的頁面找到你的金鑰和端點。

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

物件模型

以下類別處理內容管理員 Java 用戶端函式庫的一些主要功能。

名稱 描述
ContentModeratorClient 此類別是所有內容版主功能所必需的。 你用訂閱資訊實例化它,並用它來產生其他類別的實例。
圖片管理 此類別提供分析影像是否含有成人內容、個人資訊或人臉的功能。
文本審核 此課程提供分析文本語言、髒話、錯誤及個人資訊的功能。

程式碼範例

這些程式碼片段展示了如何使用 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;
}

分析內容

這行程式碼會檢查該網址下的圖片是否有成人或大膽內容。 有關這些術語的資訊,請參閱圖片審核概念指南。

// 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 服務 訂閱,可以刪除該資源或資源群組。 刪除資源群組也會刪除與之相關的其他資源。

下一步

在這個快速入門中,你學會了如何使用內容管理員 Java 函式庫來執行審核任務。 接著,請閱讀概念指南,進一步了解影像或其他媒體的審核。

開始使用 Azure Content Moderator 的 Python 客戶端函式庫。 請依照以下步驟安裝 PiPy 套件,並嘗試範例程式碼來執行基本任務。

內容管理員是一項人工智慧服務,讓你能處理可能冒犯、風險或其他不理想的內容。 使用由 AI 驅動的內容審核服務掃描文字、圖片和影片,並自動套用內容標記。 在您的應用程式中內建內容過濾軟體,以符合法規或維持使用者預期的環境。

使用 Python 的 Content Moderator 用戶端函式庫來:

  • 溫和文本
  • 使用自訂術語清單
  • 審核影像
  • 使用自訂圖片清單

參考文件 | 函式庫原始碼 | 套件(PiPy) | Samples

先決條件

  • Azure訂閱 - 免費建立一個
  • Python 3.x
    • 你的Python安裝應該包含pip。 你可以透過命令列執行 pip --version 來確認你有沒有安裝 PIP。 安裝最新版本的 Python 來取得 PIP。
  • 一旦你訂閱了Azure,建立內容管理員資源,在Azure入口網站取得你的金鑰和端點。 等它部署完,然後點擊 「前往資源 」按鈕。
    • 你需要從你建立的資源中取得金鑰和端點,才能將應用程式連接到內容管理員。 你會在快速入門過程中,把你的金鑰和端點貼上到下面的程式碼中。
    • 你可以先用免費價格等級F0()試用服務,之後再升級到付費等級以進行生產。

設定

安裝用戶端函式庫

安裝 Python 後,您可以使用以下指令安裝內容管理員客戶端函式庫:

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_ENDPOINT = "PASTE_YOUR_CONTENT_MODERATOR_ENDPOINT_HERE"
subscription_key = "PASTE_YOUR_CONTENT_MODERATOR_SUBSCRIPTION_KEY_HERE"

重要

記得完成後要移除該金鑰,且絕不要公開發布。 在生產環境方面,請使用像 Azure Key Vault 這類安全的憑證儲存和存取方式。 更多資訊請參閱 Azure AI 服務 security 文章。

物件模型

以下類別處理內容管理員 Python 用戶端函式庫的一些主要功能。

名稱 描述
ContentModeratorClient 此類別是所有內容版主功能所必需的。 你用訂閱資訊實例化它,並用它來產生其他類別的實例。
圖片管理作業 此類別提供分析影像是否含有成人內容、個人資訊或人臉的功能。
文字管理作業 此課程提供分析文本語言、髒話、錯誤及個人資訊的功能。

程式碼範例

這些程式碼片段展示了如何使用 Python 內容管理員客戶端函式庫完成以下任務:

驗證客戶端

用你的端點和金鑰實例化一個客戶端。 使用您的金鑰建立 CognitiveServicesCredentials 物件,並搭配端點使用該物件來建立 ContentModeratorClient](/python/api/msrest/msrest.authentication.cognitiveservicescredentials 物件。

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

溫和文本

以下程式碼使用內容管理員用戶端分析正文,並將結果列印到主控台。 首先,在專案根建立一個 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))

檢查是否有成人/露骨內容

以下程式碼會檢查該網址的圖片是否有成人或大膽內容,並將結果列印到主控台。 請參閱 圖片審核概念 指南,了解這些術語的含義。

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 類別允許您建立圖片清單,管理列表中的個別圖片,並與之比較其他圖片。

建立以下文字變數來儲存你在此情境中會使用的圖片網址。

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 helper 函式。

#
# 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 服務 訂閱,可以刪除該資源或資源群組。 刪除資源群組也會刪除與之相關的其他資源。

下一步

在這個快速入門中,你學會了如何使用內容管理員 Python 函式庫來執行審核任務。 接著,請閱讀概念指南,進一步了解影像或其他媒體的審核。

立即開始使用 Azure Content Moderator REST API。

內容管理員是一項人工智慧服務,讓你能處理可能冒犯、風險或其他不理想的內容。 使用由 AI 驅動的內容審核服務掃描文字、圖片和影片,並自動套用內容標記。 在您的應用程式中內建內容過濾軟體,以符合法規或維持使用者預期的環境。

使用 Content Moderator REST API 來:

  • 溫和文本
  • 審核影像

先決條件

  • Azure訂閱 - 免費建立一個
  • 一旦你訂閱了Azure,在Azure入口網站建立內容管理員資源 以取得你的金鑰和端點。 等它部署完,然後點擊 「前往資源 」按鈕。
    • 你需要從你建立的資源中取得金鑰和端點,才能將應用程式連接到內容管理員。 你會在快速入門過程中,把你的金鑰和端點貼上到下面的程式碼中。
    • 你可以先用免費價格等級F0()試用服務,之後再升級到付費等級以進行生產。
  • PowerShell 6.0+ 版本,或類似的命令列應用程式。

溫和文本

你會用類似以下的指令呼叫內容管理員 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. 把查詢網址的第一部分改成對應你訂閱金鑰的端點。

    註

    2019 年 7 月 1 日後新增的資源將使用自訂子網域名稱。 欲了解更多資訊及完整區域端點清單,請參閱 Foundry Tools 的自訂子網域名稱。

  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 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. 把查詢網址的第一部分改成對應你訂閱金鑰的端點。
  3. 可選擇性地將請求文中的 "Value" 網址改成你想要審核的遠端映像。

提示

你也可以透過將位元組資料傳入請求本體來管理本地影像。 請參考 參考文件 了解如何操作。

完成修改後,打開命令提示字元並輸入新指令。

檢視結果

你應該會在主控台視窗看到圖片審核結果以 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>"
}

欲了解更多內容版主篩選圖片屬性的資訊,請參閱 圖片審核概念 指南。

清理資源

如果你想清理並移除 Azure AI 服務 訂閱,可以刪除該資源或資源群組。 刪除資源群組也會刪除與之相關的其他資源。

下一步

在這份快速入門中,你學會了如何使用 Content Moderator REST API 來執行審核任務。 接著,請閱讀概念指南,進一步了解影像或其他媒體的審核。