你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:使用内容审查器客户端库

重要

自 2024 年 2 月起,Azure内容审查器已弃用,将于 2027 年 3 月 15 日停用。 它替换为 Azure AI 内容安全,它提供了高级 AI 功能和增强的性能。

Azure AI 内容安全是一个全面的解决方案,旨在检测应用程序和服务中有害的用户生成和 AI 生成的内容。 Azure AI 内容安全适用于许多方案,例如在线市场、游戏公司、社交消息平台、企业媒体公司和 K-12 教育解决方案提供商。 下面是其特性和功能的概述:

  • 文本和图像检测 API:用多个严重级别扫描文本和图像,以检测性内容、暴力、仇恨和自我伤害。
  • 内容安全工作室:一种在线工具,旨在使用我们最新的内容审查 ML 模型处理潜在的冒犯性、风险或不良内容。 它提供模板和自定义工作流,使用户能够生成自己的内容审查系统。
  • 语言支持:Azure AI 内容安全支持 100 多种语言,并特别针对英语、德语、日语、西班牙语、法语、意大利语、葡萄牙语和中文进行了训练。

Azure AI 内容安全为内容审查需求提供可靠且灵活的解决方案。 通过从内容审查器切换到Azure AI 内容安全,可以利用最新的工具和技术来确保内容始终按确切规范进行审查。

详细了解 Azure AI 内容安全以及如何提升内容审查策略。

学习使用 Azure 内容审核客户端库(.NET)。 按照以下步骤安装 NuGet 包并试用基本任务的示例代码。

内容审查器是一种 AI 服务,可用于处理可能具有冒犯性、风险或其他不良内容的内容。 使用 AI 支持的内容审查服务自动扫描文本、图像和视频,并自动应用内容标志。 将内容筛选软件构建到应用中,以符合法规或维护用户的预期环境。

使用适用于.NET的内容审核器客户端库:

  • 中等文本
  • 调节图像

参考文档 | 库源代码 | 程序包(NuGet) | 示例

先决条件

  • Azure订阅 - 免费创建一个
  • Visual Studio IDE 或当前版本的 .NET Core
  • 获得Azure订阅后,在Azure门户中创建内容审查器资源以获取密钥和终结点。 等待部署,然后单击“ 转到资源 ”按钮。
    • 需要使用您创建的资源中的密钥和终结点,才能将应用程序连接到内容审查服务。 稍后您将在快速入门的步骤中,将密钥和终结点粘贴到下面的代码中。
    • 可以使用免费定价层(F0)试用该服务,稍后升级到生产付费层。

设置

创建新的 C# 应用程序

使用Visual Studio创建新的 .NET Core 应用程序。

安装客户端库

创建新项目后,右键单击 解决方案资源管理器 中的项目解决方案并选择 Manage NuGet 包来安装客户端库。 在打开的包管理器中,选择Browse,检查 Include prerelease,然后搜索 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门户。 如果在“先决条件”部分成功部署的内容审查器资源,请单击“后续步骤”下的“转到资源”按钮。 可以在资源的密钥和终结点页面中找到密钥和终结点,位于资源管理下。

// 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 服务 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 所有内容审查器功能都需要此类。 使用订阅信息对其进行实例化,并使用它生成其他类的实例。
ImageModeration 此类功能用于分析图像,识别其中是否包含成人内容、个人信息或人脸。
TextModeration 此类提供分析文本中的语言、亵渎、错误和个人信息功能。

代码示例

这些代码片段演示如何使用适用于.NET的内容审查器客户端库执行以下任务:

对客户端进行身份验证

在新方法中,使用终结点和密钥实例化客户端对象。

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

    return client;
}

中等文本

以下代码使用内容审查器客户端分析文本正文并将结果输出到控制台。 在 Program 类的根目录中,定义输入和输出文件:

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

然后在项目的根目录中添加 TextFile.txt 文件。 将自己的文本添加到此文件,或使用以下示例文本:

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

然后在 Program 类中某个位置定义文本审查方法:

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

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

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

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

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

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

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

调节图像

以下代码使用内容审查器客户端以及 ImageModeration 对象来分析成人和不雅内容的远程图像。

注意

还可以分析本地图像的内容。 有关使用本地映像的方法和操作,请参阅 参考文档

获取示例图像

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

分析内容

有关内容审查器检查的图像属性的详细信息,请参阅 图像审查概念 指南。

            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库来执行审查任务。 接下来,阅读概念指南,详细了解图像或其他媒体的审查。

快速入门Java版Azure内容审核客户端库。 按照以下步骤安装 Maven 包并试用基本任务的示例代码。

内容审查器是一种 AI 服务,可用于处理可能具有冒犯性、风险或其他不良内容的内容。 使用 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。 它导入内容审查器客户端库和用于 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门户。 如果在“先决条件”部分成功部署的内容审查器资源,请单击“后续步骤”下的“转到资源”按钮。 可以在资源的密钥和终结点页面中找到密钥和终结点,位于资源管理下。

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

重要

请记住在完成操作后从代码中删除密钥,从不公开发布密钥。 对于生产,请使用安全的方式来存储和访问凭据,例如 Azure 密钥保管库。 有关详细信息,请参阅 Azure AI 服务 security 一文。

在应用程序的 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);

对象模型

以下类处理内容审查器Java客户端库的某些主要功能。

名字 描述
ContentModeratorClient 所有内容审查器功能都需要此类。 使用订阅信息对其进行实例化,并使用它生成其他类的实例。
ImageModeration 此类功能用于分析图像,识别其中是否包含成人内容、个人信息或人脸。
TextModerations 此类提供分析文本中的语言、亵渎、错误和个人信息功能。

代码示例

这些代码片段演示如何使用用于Java的内容审查器客户端库执行以下任务:

对客户端进行身份验证

在应用程序的 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 and 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 文件并查看内容审查的结果。

清理资源

如果要清理和删除Azure AI 服务订阅,可以删除资源或资源组。 删除资源组也会删除与之关联的任何其他资源。

后续步骤

本快速入门介绍了如何使用内容审查器Java库来执行审查任务。 接下来,阅读概念指南,详细了解图像或其他媒体的审查。

开始使用适用于Python的Azure内容审查器客户端库。 按照以下步骤安装 PiPy 包并试用基本任务的示例代码。

内容审查器是一种 AI 服务,可用于处理可能具有冒犯性、风险或其他不良内容的内容。 使用 AI 支持的内容审查服务自动扫描文本、图像和视频,并自动应用内容标志。 将内容筛选软件构建到应用中,以符合法规或维护用户的预期环境。

使用 Python 的内容审查器客户端库来执行以下操作:

  • 中等文本
  • 使用自定义术语列表
  • 调节图像
  • 使用自定义映像列表

参考文档 | 库源代码 | 包(PiPy) | 示例

先决条件

  • 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 密钥保管库。 有关详细信息,请参阅 Azure AI 服务 security 一文。

对象模型

以下类处理内容审查器Python客户端库的某些主要功能。

名字 描述
ContentModeratorClient 所有内容审查器功能都需要此类。 使用订阅信息对其进行实例化,并使用它生成其他类的实例。
ImageModerationOperations 此类功能用于分析图像,识别其中是否包含成人内容、个人信息或人脸。
TextModerationOperations 此类提供分析文本中的语言、亵渎、错误和个人信息功能。

代码示例

这些代码片段演示如何使用适用于Python的内容审查器客户端库执行以下任务:

对客户端进行身份验证

使用终结点和密钥实例化客户端。 使用密钥创建`CognitiveServicesCredentials`对象,然后将其与终结点结合使用,以创建ContentModeratorClient对象。

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)

调节图像

以下代码使用内容审查器客户端以及 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 部分中添加的图像的非正式列表。

创建映像列表

添加以下代码以创建映像列表并保存对其 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 服务订阅,可以删除资源或资源组。 删除资源组也会删除与之关联的任何其他资源。

后续步骤

本快速入门介绍了如何使用内容审查器Python库来执行审查任务。 接下来,阅读概念指南,详细了解图像或其他媒体的审查。

开始使用 Azure 内容审核 REST API。

内容审查器是一种 AI 服务,可用于处理可能具有冒犯性、风险或其他不良内容的内容。 使用 AI 支持的内容审查服务自动扫描文本、图像和视频,并自动应用内容标志。 将内容筛选软件构建到应用中,以符合法规或维护用户的预期环境。

使用内容审查器 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. 将有效的人脸订阅密钥分配给 Ocp-Apim-Subscription-Key

    重要

    请记住在完成操作后从代码中删除密钥,从不公开发布密钥。 对于生产,请使用安全的方式来存储和访问凭据,例如 Azure 密钥保管库。 有关详细信息,请参阅 Azure AI 服务 security 一文。

  2. 更改查询 URL 的第一部分,以匹配与订阅密钥对应的终结点。

    注意

    2019 年 7 月 1 日之后创建的新资源将使用自定义子域名称。 有关详细信息和区域终结点的完整列表,请参阅 Foundry 工具的自定义子域名称

  3. (可选)将请求正文更改为要分析的任何文本字符串。

进行更改后,打开命令提示符并输入新命令。

检查结果

应该会在控制台窗口中看到文本审查结果显示为 JSON 数据。 例如:

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

有关内容审查器筛查的文本特性的详细信息,请参阅 文本审查概念 指南。

调节图像

你将使用如下所示的命令来调用内容审查器 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>"
}

有关内容审查器检查的图像属性的详细信息,请参阅 图像审查概念 指南。

清理资源

如果要清理和删除Azure AI 服务订阅,可以删除资源或资源组。 删除资源组也会删除与之关联的任何其他资源。

后续步骤

在本快速入门中,你学习了如何使用内容审查器 REST API 执行审查任务。 接下来,阅读概念指南,详细了解图像或其他媒体的审查。