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

适用于 .NET 的 Azure 内容审查器客户端库入门。 请按照以下步骤安装 NuGet 包并试用基本任务的示例代码。

内容审查器是一种 AI 服务,可用于处理可能的冒犯性、危险或不可取内容。 使用 AI 支持型内容审核服务扫描文本、图像和视频,并自动应用内容标志。 在应用中内置内容筛选软件,以符合法规或维护用户的预期环境。

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

  • 审查文本
  • 审查图像

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

先决条件

  • Azure 订阅 - 创建试用订阅
  • Visual Studio IDE 或最新版本的 .NET Core
  • 拥有 Azure 订阅后,请在 Azure 门户中创建内容审查器资源,以获取密钥和终结点。 等待其部署并单击“转到资源”按钮。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到内容审查器。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (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 门户。 如果在“先决条件”部分中创建的内容审查器资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。 在资源的“密钥和终结点”页的“资源管理”下可以找到密钥和终结点 。

		// 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://api.cognitive.azure.cn
		private static readonly string Endpoint = "PASTE_YOUR_CONTENT_MODERATOR_ENDPOINT_HERE";

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

在应用程序的 main() 方法中,添加对本快速入门中使用的方法的调用。 稍后将创建这些内容。

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

对象模型

以下类将处理内容审查器 .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.chinacloudapi.cn/samples/sample2.jpg
https://moderatorsampleimages.blob.core.chinacloudapi.cn/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 的内容审查器客户端库可以:

  • 审查文本
  • 审查图像

参考文档 | 库源代码 | 项目 (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 类中,为资源的密钥和终结点创建变量。

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

重要

转到 Azure 门户。 如果在“先决条件”部分中创建的内容审查器资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。 在资源的“密钥和终结点”页的“资源管理”下可以找到密钥和终结点 。

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产环境,请考虑使用安全的方法来存储和访问凭据。 有关详细信息,请参阅认知服务安全性一文。

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

结束 trycatch 语句以完成该方法。

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

审查图像

设置示例图像

在新方法中,使用指向图像的给定 URL 字符串构造一个 BodyModelModel 对象。

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

        try {
            String urlString = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/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 文件中,将以下类定义添加到 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 Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

对象模型

以下类将处理内容审查器 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.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/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.chinacloudapi.cn/samples/sample4.png",
        "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample6.png",
        "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample9.png"
    ],
    "Swimsuit": [
        "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample1.jpg",
        "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample3.png",
        "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample4.png",
        "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample16.png"
    ]
}

IMAGES_TO_MATCH = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample1.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample4.png",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/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.chinacloudapi.cn/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 来分析文本正文并将结果输出到控制台。

# <imagemod>
curl -v -X POST "https://api.cognitive.azure.cn/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.chinacloudapi.cn/samples/sample.jpg\"}"
# </imagemod>

# <textmod>
curl -v -X POST "https://api.cognitive.azure.cn/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" 
# </textmod>

将命令复制到文本编辑器,并进行以下更改:

  1. Ocp-Apim-Subscription-Key 分配到有效的人脸订阅密钥。

    重要

    完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 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"
}

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

审查图像

你将使用类似于以下的命令,调用内容审查器 API 来审查远程图像并将结果输出到控制台。

# <imagemod>
curl -v -X POST "https://api.cognitive.azure.cn/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.chinacloudapi.cn/samples/sample.jpg\"}"
# </imagemod>

# <textmod>
curl -v -X POST "https://api.cognitive.azure.cn/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" 
# </textmod>

将命令复制到文本编辑器,并进行以下更改:

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