快速入门:使用内容审查器客户端库Quickstart: Use the Content Moderator client library

适用于 .NET 的 Azure 内容审查器客户端库入门。Get started with the Azure Content Moderator client library for .NET. 请按照以下步骤安装 NuGet 包并试用基本任务的示例代码。Follow these steps to install the NuGet package and try out the example code for basic tasks.

内容审查器是一种 AI 服务,可用于处理可能的冒犯性、危险或不可取内容。Content Moderator is an AI service that lets you handle content that is potentially offensive, risky, or otherwise undesirable. 使用 AI 支持型内容审核服务扫描文本、图像和视频,并自动应用内容标志。Use the AI-powered content moderation service to scan text, image, and videos and apply content flags automatically.

使用适用于 .NET 的内容审查器客户端库可以:Use the Content Moderator client library for .NET to:

  • 审查文本Moderate text
  • 审查图像Moderate images

先决条件Prerequisites

  • Azure 订阅 - 创建试用订阅Azure subscription - Create one for trial
  • Visual Studio IDE 或最新版本的 .NET CoreThe Visual Studio IDE or current version of .NET Core.
  • 拥有 Azure 订阅后,在 Azure 门户中创建内容审查器资源,以获取密钥和终结点。Once you have your Azure subscription, create a Content Moderator resource in the Azure portal to get your key and endpoint. 等待其部署并单击“转到资源”按钮。Wait for it to deploy and click the Go to resource button.
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到内容审查器。You will need the key and endpoint from the resource you create to connect your application to Content Moderator. 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。You'll paste your key and endpoint into the code below later in the quickstart.
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。You can use the free pricing tier (F0) to try the service, and upgrade later to a paid tier for production.

设置Setting up

新建 C# 应用程序Create a new C# application

使用 Visual Studio 创建新的 .NET Core 应用程序。Using Visual Studio, create a new .NET Core application.

安装客户端库Install the client library

创建新项目后,右键单击“解决方案资源管理器”中的项目解决方案,然后选择“管理 NuGet 包”,以安装客户端库 。Once you've created a new project, install the client library by right-clicking on the project solution in the Solution Explorer and selecting Manage NuGet Packages. 在打开的包管理器中,选择“浏览”,选中“包括预发行版”并搜索 Microsoft.Azure.CognitiveServices.ContentModeratorIn the package manager that opens select Browse, check Include prerelease, and search for Microsoft.Azure.CognitiveServices.ContentModerator. 选择版本 2.0.0,然后选择“安装”。Select version 2.0.0, and then Install.

提示

想要立即查看整个快速入门代码文件?Want to view the whole quickstart code file at once? 可以在 GitHub 上找到它,其中包含此快速入门中的代码示例。You can find it on GitHub, which contains the code examples in this quickstart.

在首选的编辑器或 IDE 中,从项目目录打开 Program.cs 文件。From the project directory, open the Program.cs file in your preferred editor or IDE. 添加以下 using 语句:Add the following using statements:

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

在“Program”类中,为资源的密钥和终结点创建变量。In the Program class, create variables for your resource's key and endpoint.

重要

转到 Azure 门户。Go to the Azure portal. 如果在“先决条件”部分中创建的内容审查器资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。If the Content Moderator resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. 在资源的“密钥和终结点”页的“资源管理”下可以找到密钥和终结点 。You can find your key and endpoint in the resource's key and endpoint page, under resource management.

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。Remember to remove the key from your code when you're done, and never post it publicly. 对于生产环境,请考虑使用安全的方法来存储和访问凭据。For production, consider using a secure way of storing and accessing your credentials. 有关详细信息,请参阅认知服务安全性文章。See the Cognitive Services security article for more information.

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

在应用程序的 main() 方法中,添加对本快速入门中使用的方法的调用。In the application's main() method, add calls for the methods used in this quickstart. 稍后将创建这些内容。You will create these later.

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}
// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}
// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}
// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

对象模型Object model

以下类将处理内容审查器 .NET 客户端库的某些主要功能。The following classes handle some of the major features of the Content Moderator .NET client library.

名称Name 说明Description
ContentModeratorClientContentModeratorClient 所有内容审查器功能都需要此类。This class is needed for all Content Moderator functionality. 请使用你的订阅信息实例化此类,然后使用它来生成其他类的实例。You instantiate it with your subscription information, and you use it to produce instances of other classes.
ImageModerationImageModeration 此类提供用于分析成人内容、个人信息或人脸的功能。This class provides the functionality for analyzing images for adult content, personal information, or human faces.
TextModerationTextModeration 此类提供用于在文本中分析语言、猥亵内容、错误和个人信息的功能。This class provides the functionality for analyzing text for language, profanity, errors, and personal information.
评审Reviews 此类提供评审 API 的功能,包括用于创建作业、自定义工作流和人工评审的方法。This class provides the functionality of the Review APIs, including the methods for creating jobs, custom workflows, and human reviews.

代码示例Code examples

这些代码片段演示如何使用适用于 .NET 的内容审查器客户端库执行以下任务:These code snippets show you how to do the following tasks with the Content Moderator client library for .NET:

验证客户端Authenticate the client

在新方法中,使用终结点和密钥实例化客户端对象。In a new method, instantiate client objects with your endpoint and key.

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

审查文本Moderate text

以下代码使用内容审查器客户端分析文本的正文,并将结果输出到控制台。The following code uses a Content Moderator client to analyze a body of text and print the results to the console. 在 Program 类的根中,定义输入和输出文件:In the root of your Program class, define input and output files:

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

然后,在项目的根下添加一个 TextFile.txt 文件。Then at the root of your project add a TextFile.txt file. 将你自己的文本添加到此文件中,或使用以下示例文本:Add your own text to this file, or use the following sample text:

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

然后在 Program 类中的某个位置定义文本审查方法:Then define the text moderation method somewhere in your Program class:

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

审查图像Moderate images

以下代码使用内容审查器客户端和 ImageModeration 对象,分析远程图像中的成人内容和猥亵内容。The following code uses a Content Moderator client, along with an ImageModeration object, to analyze remote images for adult and racy content.

备注

还可以分析本地图像的内容。You can also analyze the content of a local image. 有关使用本地图像的方法和操作,请参阅参考文档See the reference documentation for methods and operations that work with local images.

获取示例图像Get sample images

在“Program”类的根中,定义输入和输出文件:Define your input and output files at the root of your Program class:

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

然后,在项目的根下创建输入文件 ImageFiles.txt。Then create the input file, ImageFiles.txt, at the root of your project. 在此文件中添加要分析的图像的 URL — 在每行添加一个 URL。In this file, you add the URLs of images to analyze—one URL on each line. 可使用以下示例图像:You can use the following sample images:

https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg
https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png

使用帮助器类Define helper class

在 Program 类中添加以下类定义。Add the following class definition within the Program class. 此内部类将处理图像审查结果。This inner class will handle image moderation results.

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

定义图像审查方法Define the image moderation method

以下方法将循环访问文本文件中的图像 URL,创建 EvaluationData 实例,并分析图像中的成人/猥亵内容、文本和人脸。The following method iterates through the image URLs in a text file, creates an EvaluationData instance, and analyzes the image for adult/racy content, text, and human faces. 然后,它将最终的 EvaluationData 实例添加到列表中,并将返回数据的完整列表写入控制台。Then it adds the final EvaluationData instance to a list and writes the complete list of returned data to the console.

循环访问图像Iterate through images

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

分析内容Analyze content

有关内容审查器屏幕的图像属性的详细信息,请参阅图像审查概念指南。For more information on the image attributes that Content Moderator screens for, see the Image moderation concepts guide.

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

将审查结果写入文件Write moderation results to file

// <snippet_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;
// </snippet_using>

/*
 * Content Moderator SDK Quickstart
 * 
 * Examples included:
 * - Image moderation - provide URL or image files for moderation
 * - Text moderation - provide text in a file for moderations
 * - Create human reviews for images - create a human review to be processed on the Content Moderator website.
 * 
 * Prerequisites:
 *  - Visual Studio 2019 (or 2017, but this is a .NET Core console app, not .NET Framework)
 *  - Create a C# console app in Visual Studio, then cut/paste this Program.cs file over your own (make sure namespaces match)
 *  - NuGet packages needed: Microsoft.Azure.CognitiveServices.ContentModerator & Newtonsoft.Json
 *  - Add the TextFile.txt and ImageFiles.txt included with this example to your bin/Debug/netcoreapp2.2 folder of your project.
 *  
 * How to Run:
 *  - Select start in Visual Studio
 *  - Image and text moderation results will appear, then the human reviews for images will start
 *  - Wait for the console command to tell you to perform a human review on https://{YOUR REGION}.contentmoderator.cognitive.microsoft.com
 *  - Perform the review on the website under Review-->Image. Select the "a" or "r" to test choosing the adult or racy markers, then choose "next".
 *  - Go back to the console and press enter to process the reviews.
 *  - The JSON returned will have review details in the console.
 *  - Check your output files for the image and text reviews. These files get created, only after the quickstart has run. 
 *    If testing multiple times, the output files will be overwritten with the latest moderation results.
 *    
 * References:
 *  - .NET SDK: https://docs.microsoft.com/dotnet/api/overview/cognitiveservices/client/contentmoderator?view=azure-dotnet
 *  - API (testing console): /cognitive-services/content-moderator/api-reference
 *  - Content Moderator documentation: /cognitive-services/content-moderator/
 */

namespace ContentModeratorQuickstart
{
    class Program
    {
        // AUTHENTICATION - ALL EXAMPLES
        // <snippet_creds>
        // Your Content Moderator subscription key is found in your Azure portal resource on the 'Keys' page.
        private static readonly string SubscriptionKey = "CONTENT_MODERATOR_SUBSCRIPTION_KEY";
        // Base endpoint URL. Found on 'Overview' page in Azure resource. For example: https://api.cognitive.azure.cn
        private static readonly string Endpoint = "CONTENT_MODERATOR_ENDPOINT";
        // </snippet_creds>

        // <snippet_image_vars>
        // 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";
        // </snippet_image_vars>

        // <snippet_text_vars>
        // 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";
        // </snippet_text_vars>

        // CREATE HUMAN REVIEWS FOR IMAGES
        // <snippet_review_urls>
        // The list of URLs of the images to create review jobs for.
        private static readonly string[] IMAGE_URLS_FOR_REVIEW = new string[] { "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png" };
        // </snippet_review_urls>
        // <snippet_review_vars>
        // The name of the team to assign the review to. Must be the team name used to create your Content Moderator website account. 
        // If you do not yet have an account, follow this: /cognitive-services/content-moderator/quick-start
        // Select the gear symbol (settings)-->Credentials to retrieve it. Your team name is the Id associated with your subscription.
        private static readonly string TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
        // The callback endpoint for completed human reviews.
        // For example: https://api.cognitive.azure.cn/contentmoderator/review/v1.0
        // As reviewers complete reviews, results are sent using an HTTP POST request.
        private static readonly string ReviewsEndpoint = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";
        // </snippet_review_vars>

        static void Main(string[] args)
        {
            // CLIENTS - each API call needs its own client
            // <snippet_client>
            // 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);
            // </snippet_client>

            // <snippet_imagemod_call>
            // Moderate images from list of image URLs
            ModerateImages(clientImage, ImageUrlFile, ImageOutputFile);
            // </snippet_imagemod_call>

            // <snippet_textmod_call>
            // Moderate text from text in a file
            ModerateText(clientText, TextFile, TextOutputFile);
            // </snippet_textmod_call>

            // <snippet_review_call>
            // Create image reviews for human reviewers
            CreateReviews(clientReviews, IMAGE_URLS_FOR_REVIEW, TEAM_NAME, ReviewsEndpoint);
            // </snippet_review_call>

            Console.WriteLine();
            Console.WriteLine("End of the quickstart.");
        }
        /*
         * END - MAIN
         */

        /*
         * AUTHENTICATE
         * Creates a new client with a validated subscription key and endpoint.
         */
        // <snippet_auth>
        public static ContentModeratorClient Authenticate(string key, string endpoint)
        {
            ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(key));
            client.Endpoint = endpoint;

            return client;
        }
        // </snippet_auth>

        // <snippet_imagemod_iterate>
        /*
         * 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());
                            // </snippet_imagemod_iterate>
                            // <snippet_imagemod_analyze>
                            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);
                        }
                    }
                }
                // </snippet_imagemod_analyze>
                // <snippet_imagemod_save>
                // 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();
            }
        }
        // </snippet_imagemod_save>

        // <snippet_dataclass>
        // 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;
        }
        // </snippet_dataclass>
        /*
         * END - IMAGE MODERATION
         */

        // <snippet_textmod>
        /*
         * 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();
        }
        // </snippet_textmod>
        /*
         * END - TEXT MODERATION
         */

        /*
         * CREATE HUMAN IMAGE REVIEWS
         * This example shows how to create image reviews for humans to review on the Content Moderator website.
         * Results of the review (once manually performed on the website) are then returned and written to OutputLog.txt.
         * 
         * Prerequisistes: 
         * 1. In your Content Moderator resource go to Resource Management -> Properties, then copy your Resource ID. 
         * 2. Go to the Content Moderator website.
         * 3. Click the gear sign (Settings) and go to "Credentials". 
         * 4. Under "Whitelisted Resource Id(s)" paste your Resource ID, then select the "+" button to add it.
         *    This enables the website to receive programmatic reviews from your Content Moderator resource in Azure.
         * 
         * For more information about the steps:
         * /cognitive-services/content-moderator/moderation-reviews-quickstart-dotnet
         * Use your Azure account with the review APIs:
         * /cognitive-services/content-moderator/review-tool-user-guide/configure
         */
        // <snippet_review_item>
        // Associates the review ID (assigned by the service) to the internal.
        public class ReviewItem
        {
            // The media type for the item to review. 
            public string Type;
            // The URL of the item to review.
            public string Url;
            // The internal content ID for the item to review.
            public string ContentId;
            // The ID that the service assigned to the review.
            public string ReviewId;
        }
        // </snippet_review_item>

        // <snippet_createreview_fields>
        // Create the reviews using the fixed list of images.
        private static void CreateReviews(ContentModeratorClient client, string[] ImageUrls, string teamName, string endpoint)
        {
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine("CREATE HUMAN IMAGE REVIEWS");

            // The minimum amount of time, in milliseconds, to wait between calls to the Image List API.
            const int throttleRate = 2000;
            // The number of seconds to delay after a review has finished before getting the review results from the server.
            const int latencyDelay = 45;

            // The name of the log file to create. Relative paths are relative to the execution directory.
            const string OutputFile = "OutputLog.txt";

            // The optional name of the subteam to assign the review to. Not used for this example.
            const string Subteam = null;

            // The media type for the item to review. Valid values are "image", "text", and "video".
            const string MediaType = "image";

            // The metadata key to initially add to each review item. This is short for 'score'.
            // It will enable the keys to be 'a' (adult) and 'r' (racy) in the response,
            // with a value of true or false if the human reviewer marked them as adult and/or racy.
            const string MetadataKey = "sc";
            // The metadata value to initially add to each review item.
            const string MetadataValue = "true";

            // A static reference to the text writer to use for logging.
            TextWriter writer;

            // The cached review information, associating a local content ID to the created review ID for each item.
            List<ReviewItem> reviewItems = new List<ReviewItem>();
            // </snippet_createreview_fields>

            // <snippet_createreview_create>
            using (TextWriter outputWriter = new StreamWriter(OutputFile, false))
            {
                writer = outputWriter;
                WriteLine(writer, null, true);
                WriteLine(writer, "Creating reviews for the following images:", true);

                // Create the structure to hold the request body information.
                List<CreateReviewBodyItem> requestInfo = new List<CreateReviewBodyItem>();

                // Create some standard metadata to add to each item.
                List<CreateReviewBodyItemMetadataItem> metadata =
                    new List<CreateReviewBodyItemMetadataItem>(new CreateReviewBodyItemMetadataItem[]
                    { new CreateReviewBodyItemMetadataItem(MetadataKey, MetadataValue) });

                // Populate the request body information and the initial cached review information.
                for (int i = 0; i < ImageUrls.Length; i++)
                {
                    // Cache the local information with which to create the review.
                    var itemInfo = new ReviewItem()
                    {
                        Type = MediaType,
                        ContentId = i.ToString(),
                        Url = ImageUrls[i],
                        ReviewId = null
                    };

                    WriteLine(writer, $" {Path.GetFileName(itemInfo.Url)} with id = {itemInfo.ContentId}.", true);

                    // Add the item informaton to the request information.
                    requestInfo.Add(new CreateReviewBodyItem(itemInfo.Type, itemInfo.Url, itemInfo.ContentId, endpoint, metadata));

                    // Cache the review creation information.
                    reviewItems.Add(itemInfo);
                }

                var reviewResponse = client.Reviews.CreateReviewsWithHttpMessagesAsync("application/json", teamName, requestInfo);
                // </snippet_createreview_create>

                // <snippet_createreview_ids>
                // Update the local cache to associate the created review IDs with the associated content.
                var reviewIds = reviewResponse.Result.Body;
                for (int i = 0; i < reviewIds.Count; i++) { reviewItems[i].ReviewId = reviewIds[i]; }

                WriteLine(outputWriter, JsonConvert.SerializeObject(reviewIds, Formatting.Indented));
                Thread.Sleep(throttleRate);

                // Get details of the reviews created that were sent to the Content Moderator website.
                WriteLine(outputWriter, null, true);
                WriteLine(outputWriter, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(outputWriter, $"Review {item.ReviewId} for item ID {item.ContentId} is " +
                        $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));
                    Thread.Sleep(throttleRate);
                }
                // </snippet_createreview_ids>

                // <snippet_createreview_results>
                Console.WriteLine();
                Console.WriteLine("Perform manual reviews on the Content Moderator site.");
                Console.WriteLine("Then, press any key to continue.");
                Console.ReadKey();

                // After the human reviews, the results are confirmed.
                Console.WriteLine();
                Console.WriteLine($"Waiting {latencyDelay} seconds for results to propagate.");
                Thread.Sleep(latencyDelay * 1000);

                // Get details from the human review.
                WriteLine(writer, null, true);
                WriteLine(writer, "Getting review details:", true);
                foreach (var item in reviewItems)
                {
                    var reviewDetail = client.Reviews.GetReviewWithHttpMessagesAsync(teamName, item.ReviewId);
                    WriteLine(writer, $"Review {item.ReviewId} for item ID {item.ContentId} is " + $"{reviewDetail.Result.Body.Status}.", true);
                    WriteLine(outputWriter, JsonConvert.SerializeObject(reviewDetail.Result.Body, Formatting.Indented));

                    Thread.Sleep(throttleRate);
                }

                Console.WriteLine();
                Console.WriteLine("Check the OutputLog.txt file for results of the review.");

                writer = null;
                outputWriter.Flush();
                outputWriter.Close();
            }
            Console.WriteLine("--------------------------------------------------------------");
        }
        // </snippet_createreview_results>

        // <snippet_writeline>
        // Helper function that writes a message to the log file, and optionally to the console.
        // If echo is set to true, details will be written to the console.
        private static void WriteLine(TextWriter writer, string message = null, bool echo = true)
        {
            writer.WriteLine(message ?? String.Empty);
            if (echo) { Console.WriteLine(message ?? String.Empty); }
        }
        // </snippet_writeline>
        /*
         * END - CREATE HUMAN IMAGE REVIEWS
         */
    }
}

运行应用程序Run the application

单击 IDE 窗口顶部的“调试”按钮,运行应用程序。Run the application by clicking the Debug button at the top of the IDE window.

清理资源Clean up resources

如果想要清理并删除认知服务订阅,可以删除资源或资源组。If you want to clean up and remove a Cognitive Services subscription, you can delete the resource or resource group. 删除资源组同时也会删除与之相关联的任何其他资源。Deleting the resource group also deletes any other resources associated with it.

后续步骤Next steps

本快速入门已介绍如何使用内容审查器 .NET 库来执行审查任务。In this quickstart, you learned how to use the Content Moderator .NET library to do moderation tasks. 接下来,请阅读概念指南来详细了解图像或其他媒体的审查。Next, learn more about the moderation of images or other media by reading a conceptual guide.

适用于 Java 的 Azure 内容审查器客户端库入门。Get started with the Azure Content Moderator client library for Java. 请按照以下步骤安装 Maven 包并试用基本任务的示例代码。Follow these steps to install the Maven package and try out the example code for basic tasks.

内容审查器是一种 AI 服务,可用于处理可能的冒犯性、危险或不可取内容。Content Moderator is an AI service that lets you handle content that is potentially offensive, risky, or otherwise undesirable. 使用 AI 支持型内容审核服务扫描文本、图像和视频,并自动应用内容标志。Use the AI-powered content moderation service to scan text, image, and videos and apply content flags automatically. 在应用中内置内容筛选软件,以符合法规或维护用户的预期环境。Build content filtering software into your app to comply with regulations or maintain the intended environment for your users.

使用适用于 Java 的内容审查器客户端库可以:Use the Content Moderator client library for Java to:

  • 审查文本Moderate text
  • 审查图像Moderate images

参考文档 | 库源代码 | 项目 (Maven) | 示例Reference documentation | Library source code | Artifact (Maven) | Samples

先决条件Prerequisites

  • Azure 订阅 - 创建试用订阅An Azure subscription - Create one for trial
  • 最新版的 Java 开发工具包 (JDK)The current version of the Java Development Kit (JDK)
  • Gradle 生成工具,或其他依赖项管理器。The Gradle build tool, or another dependency manager.
  • 拥有 Azure 订阅后,在 Azure 门户中创建内容审查器资源,以获取密钥和终结点。Once you have your Azure subscription, create a Content Moderator resource in the Azure portal to get your key and endpoint. 等待其部署并单击“转到资源”按钮。Wait for it to deploy and click the Go to resource button.
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到内容审查器。You will need the key and endpoint from the resource you create to connect your application to Content Moderator. 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。You'll paste your key and endpoint into the code below later in the quickstart.
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。You can use the free pricing tier (F0) to try the service, and upgrade later to a paid tier for production.

设置Setting up

创建新的 Gradle 项目Create a new Gradle project

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

mkdir myapp && cd myapp

从工作目录运行 gradle init 命令。Run the gradle init command from your working directory. 此命令将创建 Gradle 的基本生成文件,包括 build.gradle.kts,在运行时将使用该文件创建并配置应用程序。This command will create essential build files for Gradle, including build.gradle.kts, which is used at runtime to create and configure your application.

gradle init --type basic

当提示你选择一个 DSL 时,选择 KotlinWhen prompted to choose a DSL, select Kotlin.

安装客户端库Install the client library

找到 build.gradle.kts,并使用喜好的 IDE 或文本编辑器将其打开。Find build.gradle.kts and open it with your preferred IDE or text editor. 然后在该文件中复制以下生成配置。Then copy in the following build configuration. 此配置将项目定义一个 Java 应用程序,其入口点为 ContentModeratorQuickstart 类。This configuration defines the project as a Java application whose entry point is the class ContentModeratorQuickstart. 它会导入内容审查器客户端库以及用于 JSON 序列化的 GSON SDK。It imports the Content Moderator client library as well as the GSON sdk for JSON serialization.

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 文件Create a Java file

从工作目录运行以下命令,以创建项目源文件夹:From your working directory, run the following command to create a project source folder:

mkdir -p src/main/java

导航到新文件夹,创建名为 ContentModeratorQuickstart.java 的文件。Navigate to the new folder and create a file called ContentModeratorQuickstart.java. 在喜好的编辑器或 IDE 中打开该文件并添加以下 import 语句:Open it in your preferred editor or IDE and add the following import statements:


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

提示

想要立即查看整个快速入门代码文件?Want to view the whole quickstart code file at once? 可以在 GitHub 上找到它,其中包含此快速入门中的代码示例。You can find it on GitHub, which contains the code examples in this quickstart.

在应用程序的 ContentModeratorQuickstart 类中,为资源的密钥和终结点创建变量。In the application's ContentModeratorQuickstart class, create variables for your resource's key and endpoint.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

重要

转到 Azure 门户。Go to the Azure portal. 如果在“先决条件”部分中创建的 [产品名称] 资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。If the [Product name] resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. 在资源的“密钥和终结点”页的“资源管理”下可以找到密钥和终结点 。You can find your key and endpoint in the resource's key and endpoint page, under resource management.

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。Remember to remove the key from your code when you're done, and never post it publicly. 对于生产环境,请考虑使用安全的方法来存储和访问凭据。For production, consider using a secure way of storing and accessing your credentials. 有关详细信息,请参阅认知服务安全性文章。See the Cognitive Services security article for more information.

在应用程序的 main 方法中,添加对本快速入门中使用的方法的调用。In the application's main method, add calls for the methods used in this quickstart. 稍后将对这些调用进行定义。You'll define these later.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

对象模型Object model

以下类将处理内容审查器 Java 客户端库的某些主要功能。The following classes handle some of the major features of the Content Moderator Java client library.

名称Name 说明Description
ContentModeratorClientContentModeratorClient 所有内容审查器功能都需要此类。This class is needed for all Content Moderator functionality. 请使用你的订阅信息实例化此类,然后使用它来生成其他类的实例。You instantiate it with your subscription information, and you use it to produce instances of other classes.
ImageModerationImageModeration 此类提供用于分析成人内容、个人信息或人脸的功能。This class provides the functionality for analyzing images for adult content, personal information, or human faces.
TextModerationsTextModerations 此类提供用于在文本中分析语言、猥亵内容、错误和个人信息的功能。This class provides the functionality for analyzing text for language, profanity, errors, and personal information.

代码示例Code examples

这些代码片段演示如何使用适用于 Java 的内容审查器客户端库执行以下任务:These code snippets show you how to do the following tasks with the Content Moderator client library for Java:

验证客户端Authenticate the client

在应用程序的 main 方法中,使用订阅终结点值和订阅密钥创建一个 ContentModeratorClient 对象。In the application's main method, create a ContentModeratorClient object using your subscription endpoint value and subscription key.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

审查文本Moderate text

设置示例文本Set up sample text

在 ContentModeratorQuickstart 类的顶部,定义对本地文本文件的引用。At the top of your ContentModeratorQuickstart class, define a reference to a local text file. 在项目目录中添加一个 .txt 文件,然后输入要分析的文本。Add a .txt file to your project directory and enter the text you'd like to analyze.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

分析文本Analyze text

创建一个新方法,读取 .txt 文件并在每一行调用 screenText 方法。Create a new method that reads the .txt file and calls the screenText method on each line.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

添加以下代码,将审查结果打印到项目目录中的 .json 文件中。Add the following code to print the moderation results to a .json file in your project directory.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

结束 trycatch 语句以完成该方法。Close out the try and catch statement to complete the method.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

审查图像Moderate images

设置示例图像Set up sample image

在新方法中,使用指向图像的给定 URL 字符串构造一个 BodyModelModel 对象。In a new method, construct a BodyModelModel object with a given URL string that points to an image.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

使用帮助器类Define helper class

然后,在 ContentModeratorQuickstart 文件中,将以下类定义添加到 ContentModeratorQuickstart 类中。Then, in your ContentModeratorQuickstart.java file, add the following class definition inside the ContentModeratorQuickstart class. 将在图像审查过程中使用此内部类。This inner class is used in the image moderation process.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

分析内容Analyze content

以下代码行在给定 URL 处的图像中检查成人或猥亵内容。This line of code checks the image at the given URL for adult or racy content. 有关这些术语的信息,请参阅《图像审查概念指南》。See the Image moderation conceptual guide for information on these terms.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

检查文本Check for text

以代码行在图像中检查可见文本。This line of code checks the image for visible text.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

检查人脸Check for faces

以代码行在图像中检查人脸。This line of code checks the image for human faces.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

最后,将返回的信息存储在 EvaluationData 列表中。Finally, store the returned information in the EvaluationData list.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

while 循环的后面添加以下代码,用于将结果输出到控制台和输出文件 src/main/resources/ModerationOutput.jsonAfter the while loop, add the following code, which prints the results to the console and to an output file, src/main/resources/ModerationOutput.json.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

结束 try 语句并添加 catch 语句以完成该方法。Close out the try statement and add a catch statement to complete the method.


// <snippet_imports>
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.*;
// </snippet_imports>

/**
 * \ This quickstart: - Moderates a URL image - Moderates a text file - Creates
 * a human review for an image that posts to the Content Moderator website
 * 
 * A successful response shows a JSON representation of the moderation results.
 * 
 * Prerequisites: 1. Obtain an Azure Content Moderator resource 2. Clone or
 * download this repo:
 * https://github.com/Azure-Samples/cognitive-services-java-sdk-samples.git 3.
 * Use Java 8 or later 4. Set and add your Content Moderator subscription key
 * and endpoint environment variables in main() below. Aquire the endpoint from
 * your Content Moderator account... use only the base endpoint, for example:
 * https://api.cognitive.azure.cn
 * 
 * How to run: Run in your favorite IDE or... To use the command line: - Make
 * sure Maven is installed: https://maven.apache.org/install.html - Run from the
 * root folder (has pom.xml in it): mvn compile exec:java
 * -Dexec.cleanupDaemonThreads=false - All dependencies will be automatically
 * included. To list them (if desired): mvn dependency:list NOTE: You may see a
 * "WARNING: An illegal reflective access operation has occurred..." within the
 * results. This does not impact a successful result, so it can be ignored.
 * 
 * Resources: - Content Moderator documentation:
 * /cognitive-services/content-moderator/
 * - Content Moderator Java SDK:
 * https://docs.microsoft.com/java/api/com.microsoft.azure.cognitiveservices.vision.contentmoderator?view=azure-java-stable
 * - Content Moderator API:
 * /cognitive-services/content-moderator/api-reference
 */

public class ContentModeratorQuickstart {

    // MODERATE IMAGES variable
    private static File imageListFile = new File("src\\main\\resources\\ImageFiles.txt");

    // <snippet_textmod_var>
    // TEXT MODERATION variable
    private static File textFile = new File("src\\main\\resources\\TextModeration.txt");
    // </snippet_textmod_var>

    // HUMAN REVIEWS - IMAGES variables
    private static final String REVIEW_URL = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png";
    private static final long LATENCY_DELAY = 30; // milliseconds of delay
    // Add your Content Moderator team name and callback endpoint to your
    // environment variables.
    private static final String TEAM_NAME = "CONTENT_MODERATOR_TEAM_NAME";
    private static final String CALLBACK_ENDPOINT = "CONTENT_MODERATOR_REVIEWS_ENDPOINT";

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

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

    public static void main(String[] args) {

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

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

    /**
     * MODERATE IMAGES Read image URLs from the input file and evaluate/moderate
     * each one.
     */
    // <snippet_imagemod>
    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();
            // </snippet_imagemod>

            // <snippet_imagemod_ar>
            // Evaluate for adult and racy content.
            imageData.ImageModeration = client.imageModerations().evaluateUrlInput("application/json", url,
                    new EvaluateUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_ar>

            // <snippet_imagemod_text>
            // Detect and extract text from image.
            imageData.TextDetection = client.imageModerations().oCRUrlInput("eng", "application/json", url,
                    new OCRUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_text>

            // <snippet_imagemod_faces>
            // Detect faces.
            imageData.FaceDetection = client.imageModerations().findFacesUrlInput("application/json", url,
                    new FindFacesUrlInputOptionalParameter().withCacheImage(true));
            Thread.sleep(1000);
            // </snippet_imagemod_faces>

            // <snippet_imagemod_storedata>
            resultsList.add(imageData);
            // </snippet_imagemod_storedata>

            System.out.println("Image moderation status: " + imageData.ImageModeration.status().description());

            System.out.println();

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

            // <snippet_imagemod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // </snippet_imagemod_catch>
        System.out.println();
    }

    /**
     * END - MODERATE IMAGES
     */

    /**
     * MODERATE TEXT Read text as a string from the input file and evaluate/moderate
     * it. Check for profanity, autocorrect the text, check for personally
     * identifying information (PII), and classify the text.
     */
    // <snippet_textmod>
    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());
                }
            }
            // </snippet_textmod>

            // <snippet_textmod_print>
            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();
            // </snippet_textmod_print>
            // <snippet_textmod_catch>
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    // </snippet_textmod_catch>

    /**
     * END - MODERATE TEXT
     */

    /**
     * HUMAN REVIEWS - IMAGES This example will create a review for humans to
     * moderate on the Content Moderator website at: https://{LOCATION OR CUSTOM
     * NAME}.contentmoderator.cognitive.microsoft.com Requires you to moderate an
     * image on website (when prompted), then return to the app (IDE or console) to
     * initiate printing of the results of the review.
     */
    public static void humanReviews(ContentModeratorClient client) {
        System.out.println("---------------------------------------");
        System.out.println("HUMAN REVIEWS - IMAGES");
        System.out.println();

        System.out.println("Creating a review for the image: "
                + REVIEW_URL.substring(REVIEW_URL.lastIndexOf('/') + 1, REVIEW_URL.length()));
        System.out.println();

        // Create List for the review body items
        List<CreateReviewBodyItem> body = new ArrayList<>();
        List<CreateReviewBodyItemMetadataItem> metadata = new ArrayList<>();
        // This establishes the adult or racy score (sc) that will be returned (true)
        // with the results.
        metadata.add(new CreateReviewBodyItemMetadataItem().withKey("sc").withValue("true"));
        body.add(new CreateReviewBodyItem().withCallbackEndpoint(CALLBACK_ENDPOINT).withContent(REVIEW_URL)
                .withMetadata(metadata).withType("Image"));

        // Creates a review by POST to callback URL. Returns a list of string review
        // IDs.
        List<String> reviews = client.reviews().createReviews(TEAM_NAME, "Image", body, null);
        System.out.println();
        System.out.println("Getting review details before human review..."); // for comparison's sake
        System.out.println();

        // Returns a Review object, notice the "reviewerResultTags" is empty.
        Review reviewDetailsBefore = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonBefore = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonBefore.toJson(reviewDetailsBefore).toString());
        System.out.println();

        // Go to website to perform reviews
        System.out.println("Perform manual reviews on the Content Moderator review site, press ENTER when done...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Wait for server to process review
        System.out.println("Wait " + LATENCY_DELAY + " seconds for the server to process the request...");
        System.out.println();
        try {
            TimeUnit.SECONDS.sleep(LATENCY_DELAY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get review details again to view changes since the human review. The
        // "reviewerResultTags" is now full.
        System.out.println("Getting review details after human review...");
        System.out.println();
        Review reviewDetailsAfter = client.reviews().getReview(TEAM_NAME, reviews.get(0));
        Gson gsonAfter = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gsonAfter.toJson(reviewDetailsAfter).toString());
        System.out.println();
    }
    /**
     * END - HUMAN REVIEWS - IMAGES
     */
}

运行应用程序Run the application

可使用以下命令生成应用:You can build the app with:

gradle build

使用 gradle run 命令运行应用程序:Run the application with the gradle run command:

gradle run

然后导航到 src/main/resources/ModerationOutput.json 文件并查看内容审查的结果。Then navigate to the src/main/resources/ModerationOutput.json file and view the results of your content moderation.

清理资源Clean up resources

如果想要清理并删除认知服务订阅,可以删除资源或资源组。If you want to clean up and remove a Cognitive Services subscription, you can delete the resource or resource group. 删除资源组同时也会删除与之相关联的任何其他资源。Deleting the resource group also deletes any other resources associated with it.

后续步骤Next steps

本快速入门已介绍如何使用内容审查器 Java 库来执行审查任务。In this quickstart, you learned how to use the Content Moderator Java library to perform moderation tasks. 接下来,请阅读概念指南来详细了解图像或其他媒体的审查。Next, learn more about the moderation of images or other media by reading a conceptual guide.

适用于 Python 的 Azure 内容审查器客户端库入门。Get started with the Azure Content Moderator client library for Python. 请按照以下步骤安装 PiPy 包并试用基本任务的示例代码。Follow these steps to install the PiPy package and try out the example code for basic tasks.

内容审查器是一种 AI 服务,可用于处理可能的冒犯性、危险或不可取内容。Content Moderator is an AI service that lets you handle content that is potentially offensive, risky, or otherwise undesirable. 使用 AI 支持型内容审核服务扫描文本、图像和视频,并自动应用内容标志。Use the AI-powered content moderation service to scan text, image, and videos and apply content flags automatically. 然后,将应用与审阅工具进行集成,为人工审阅者团队提供一个联机审查环境。Then, integrate your app with the Review tool, an online moderator environment for a team of human reviewers. 在应用中内置内容筛选软件,以符合法规或维护用户的预期环境。Build content filtering software into your app to comply with regulations or maintain the intended environment for your users.

使用适用于 Python 的内容审查器客户端库可以:Use the Content Moderator client library for Python to:

  • 审查文本Moderate text
  • 使用自定义字词列表Use a custom terms list
  • 审查图像Moderate images
  • 使用自定义图像列表Use a custom image list

参考文档 | 库源代码 | 包 (PiPy) | 示例Reference documentation | Library source code | Package (PiPy) | Samples

先决条件Prerequisites

  • Azure 订阅 - 创建试用订阅Azure subscription - Create one for trial
  • Python 3.xPython 3.x
  • 拥有 Azure 订阅后,在 Azure 门户中创建内容审查器资源,以获取密钥和终结点。Once you have your Azure subscription, create a Content Moderator resource in the Azure portal to get your key and endpoint. 等待其部署并单击“转到资源”按钮。Wait for it to deploy and click the Go to resource button.
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到内容审查器。You will need the key and endpoint from the resource you create to connect your application to Content Moderator. 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。You'll paste your key and endpoint into the code below later in the quickstart.
    • 可以使用免费定价层 (F0) 试用该服务,然后再升级到付费层进行生产。You can use the free pricing tier (F0) to try the service, and upgrade later to a paid tier for production.

设置Setting up

安装客户端库Install the client library

安装 Python 后,可使用以下命令安装内容审查器客户端库:After installing Python, you can install the Content Moderator client library with the following command:

pip install --upgrade azure-cognitiveservices-vision-contentmoderator

创建新的 Python 应用程序Create a new python application

创建新的 Python 脚本,并在喜好的编辑器或 IDE 中打开它。Create a new Python script and open it in your preferred editor or IDE. 将以下 import 语句添加到该文件的顶部。Then add the following import statements to the top of the file.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

提示

想要立即查看整个快速入门代码文件?Want to view the whole quickstart code file at once? 可以在 GitHub 上找到它,其中包含此快速入门中的代码示例。You can find it on GitHub, which contains the code examples in this quickstart.

接下来,为资源的终结点位置和密钥创建变量。Next, create variables for your resource's endpoint location and key.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

重要

转到 Azure 门户。Go to the Azure portal. 如果在“先决条件”部分中创建的内容审查器资源已成功部署,请单击“后续步骤”下的“转到资源”按钮 。If the Content Moderator resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. 在资源的“密钥和终结点”页的“资源管理”下可以找到密钥和终结点 。You can find your key and endpoint in the resource's key and endpoint page, under resource management.

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。Remember to remove the key from your code when you're done, and never post it publicly. 对于生产环境,请考虑使用安全的方法来存储和访问凭据。For production, consider using a secure way of storing and accessing your credentials. 例如,Azure 密钥保管库For example, Azure key vault.

对象模型Object model

以下类将处理内容审查器 Python 客户端库的某些主要功能。The following classes handle some of the major features of the Content Moderator Python client library.

名称Name 说明Description
ContentModeratorClientContentModeratorClient 所有内容审查器功能都需要此类。This class is needed for all Content Moderator functionality. 请使用你的订阅信息实例化此类,然后使用它来生成其他类的实例。You instantiate it with your subscription information, and you use it to produce instances of other classes.
ImageModerationOperationsImageModerationOperations 此类提供用于分析成人内容、个人信息或人脸的功能。This class provides the functionality for analyzing images for adult content, personal information, or human faces.
TextModerationOperationsTextModerationOperations 此类提供用于在文本中分析语言、猥亵内容、错误和个人信息的功能。This class provides the functionality for analyzing text for language, profanity, errors, and personal information.
ReviewsOperationsReviewsOperations 此类提供评审 API 的功能,包括用于创建作业、自定义工作流和人工评审的方法。This class provides the functionality of the Review APIs, including the methods for creating jobs, custom workflows, and human reviews.

代码示例Code examples

这些代码片段演示如何使用适用于 Python 的内容审查器客户端库执行以下任务:These code snippets show you how to do the following tasks with the Content Moderator client library for Python:

验证客户端Authenticate the client

使用终结点和密钥实例化某个客户端。Instantiate a client with your endpoint and key. 使用密钥创建 CognitiveServicesCredentials 对象,然后在终结点上使用该对象创建 ContentModeratorClient 对象。Create a CognitiveServicesCredentials object with your key, and use it with your endpoint to create an ContentModeratorClient object.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

审查文本Moderate text

以下代码使用内容审查器客户端分析文本的正文,并将结果输出到控制台。The following code uses a Content Moderator client to analyze a body of text and print the results to the console. 首先,在项目的根目录中创建 text_files/ 文件夹,并在其中添加 content_moderator_text_moderation.txt 文件。First, create a text_files/ folder at the root of your project and add a content_moderator_text_moderation.txt file. 将你自己的文本添加到此文件中,或使用以下示例文本:Add your own text to this file, or use the following sample text:

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

添加对新文件夹的引用。Add a reference to the new folder.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

然后,将以下代码添加到 Python 脚本中。Then, add the following code to your Python script.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

使用自定义字词列表Use a custom terms list

以下代码演示如何管理用于审查文本的自定义字词列表。The following code shows how to manage a list of custom terms for text moderation. 可以使用 ListManagementTermListsOperations 类创建字词列表、管理各个字词,并根据该列表筛选其他文本正文。You can use the ListManagementTermListsOperations class to create a terms list, manage the individual terms, and screen other bodies of text against it.

获取示例文本Get sample text

若要使用此示例,必须在项目的根目录中创建 text_files/ 文件夹,并在其中添加 content_moderator_term_list.txt 文件。To use this sample, you must create a text_files/ folder at the root of your project and add a content_moderator_term_list.txt file. 此文件应包含要根据字词列表检查的有序文本。This file should contain organic text that will be checked against the list of terms. 可使用以下示例文本:You can use the following sample text:

This text contains the terms "term1" and "term2".

添加对该文件夹的引用(如果尚未定义引用)。Add a reference to the folder if you haven't already defined one.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

创建列表Create a list

将以下代码添加到 Python 脚本以创建自定义字词列表,并保存其 ID 值。Add the following code to your Python script to create a custom terms list and save its ID value.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

定义列表详细信息Define list details

可以使用列表的 ID 来编辑其名称和说明。You can use a list's ID to edit its name and description.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

将字词添加到列表Add a term to the list

以下代码将字词 "term1""term2" 添加到列表。The following code adds the terms "term1" and "term2" to the list.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

获取列表中的所有字词Get all terms in the list

可以使用列表 ID 返回列表中的所有字词。You can use the list ID to return all of the terms in the list.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

刷新列表索引Refresh the list index

每当在列表中添加或删除字词后,都必须先刷新索引,然后才能使用更新的列表。Whenever you add or remove terms from the list, you must refresh the index before you can use the updated list.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

根据列表筛选文本Screen text against the list

自定义字词列表的主要功能就是将文本正文与该列表进行比较,找出是否存在任何匹配的字词。The main functionality of the custom terms list is to compare a body of text against the list and find whether there are any matching terms.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

从列表中删除字词Remove a term from a list

以下代码从列表中删除字词 "term1"The following code removes the term "term1" from the list.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

从列表中删除所有字词Remove all terms from a list

使用以下代码可清除列表中的所有字词。Use the following code to clear a list of all its terms.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

删除列表Delete a list

使用以下代码可删除自定义字词列表。Use the following code to delete a custom terms list.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

审查图像Moderate images

以下代码使用内容审查器客户端以及 ImageModerationOperations 对象在图像中分析成人内容和猥亵内容。The following code uses a Content Moderator client, along with an ImageModerationOperations object, to analyze images for adult and racy content.

获取示例图像Get sample images

定义对要分析的某些图像的引用。Define a reference to some images to analyze.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

然后添加以下代码来循环访问图像。Then add the following code to iterate through your images. 本部分的余下代码将进入此循环。The rest of the code in this section will go inside this loop.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

检查成人/猥亵内容Check for adult/racy content

以下代码在给定 URL 上的图像中检查成人内容或猥亵,然后将结果输出到控制台。The following code checks the image at the given URL for adult or racy content and prints results to the console. 有关这些术语的含义,请参阅 图像审查的概念 指南。See the Image moderation concepts guide for information on what these terms mean.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

检查可见文本Check for visible text

以下代码在图像中检查可见的文本内容,并将结果输出到控制台。The following code checks the image for visible text content and prints results to the console.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

检查人脸Check for faces

以下代码在图像中检查人脸,并将结果输出到控制台。The following code checks the image for human faces and prints results to the console.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

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

def image_lists():
    """ImageList.
    This will review an image using workflow and job.
    """

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

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

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

    # </snippet_imagelist_add>

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

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

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

    # <snippet_imagelist_refresh>
    #
    # 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)
    # </snippet_imagelist_refresh>

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

    # <snippet_imagelist_remove>
    #
    # 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]
    )
    # </snippet_imagelist_remove>

    #
    # Refresh the index
    #
    print("\nRefreshing the search index for list {}".format(list_id))
    client.list_management_image_lists.refresh_index_method(list_id=list_id)

    print("\nWaiting {} minutes to allow the server time to propagate the index changes.".format(
        LATENCY_DELAY))
    time.sleep(LATENCY_DELAY * 60)

    #
    # Re-match
    #
    print("\nMatching image. The removed image should not match")
    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())
    # <snippet_imagelist_removeall>
    #
    # 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)
    # </snippet_imagelist_removeall>

    # <snippet_imagelist_delete>
    #
    # Delete list
    #
    print("\nDelete the image list {}".format(list_id))
    client.list_management_image_lists.delete(list_id=list_id)
    # </snippet_imagelist_delete>

    #
    # Get all list ids
    #
    print("\nVerify that the list {} was deleted.".format(list_id))
    image_lists = client.list_management_image_lists.get_all_image_lists()
    assert not any(list_id == image_list.id for image_list in image_lists)

def image_review(subscription_key):
    """ImageReview.
    This will create a review for images.
    """
    # <snippet_imagereview_vars>
    # The name of the team to assign the job to.
    # This must be the team name you used to create your Content Moderator account. You can
    # retrieve your team name from the Review tool web site. Your team name is the Id
    # associated with your subscription.
    team_name = "<insert your team name here>"

    # An image to review
    image_url = "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"

    # Where you want to receive the approval/refuse event. This is the only way to get this information.
    call_back_endpoint = "https://requestb.in/qmsakwqm"
# </snippet_imagereview_vars>
# <snippet_imagereview_create>
    # Create review
    print("Create review for {}.\n".format(image_url))
    review_item = {
        "type": "Image",             # Possible values include: 'Image', 'Text'
        "content": image_url,        # How to download the image
        "content_id": uuid.uuid4(),  # Random id
        "callback_endpoint": call_back_endpoint,
        "metadata": [{
            "key": "sc",
            "value": True  # will be sent to Azure as "str" cast.
        }]
    }

    reviews = client.reviews.create_reviews(
        url_content_type="application/json",
        team_name=team_name,
        create_review_body=[review_item]  # As many review item as you need
    )

    # Get review ID
    review_id = reviews[0]  # Ordered list of string of review ID
    # </snippet_imagereview_create>

    # <snippet_imagereview_getdetails>
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())
    # </snippet_imagereview_getdetails>


    # wait for user input through the Review tool web portal
    input("\nPerform manual reviews on the Content Moderator Review Site, and hit enter here.")

    # Check the results of the human review
    print("\nGet review details")
    review_details = client.reviews.get_review(
        team_name=team_name, review_id=review_id)
    pprint(review_details.as_dict())

使用自定义图像列表Use a custom image list

以下代码演示如何管理用于图像审查的自定义图像列表。The following code shows how to manage a custom list of images for image moderation. 如果你的平台经常收到一组你要筛选出的相同图像的实例,则此功能很有用。维护这些特定图像的列表可以提高性能。This feature is useful if your platform frequently receives instances of the same set of images that you want to screen out. By maintaining a list of these specific images, you can improve performance. 使用 ListManagementImageListsOperations 类可以创建图像列表、管理该列表中的各个图像,并将这些图像与其他图像进行比较。The ListManagementImageListsOperations class allows you to create an image list, manage the individual images on the list, and compare other images against it.

创建以下文本变量用于存储此方案中使用的图像 URL。Create the following text variables to store the image URLs that you'll use in this scenario.

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

# <snippet_vars>
CONTENTMODERATOR_ENDPOINT = "<your API endpoint>"
subscription_key = "<your subscription key"
# </snippet_vars>

# <snippet_client>
client = ContentModeratorClient(
    endpoint=CONTENT_MODERATOR_ENDPOINT,
    credentials=CognitiveServicesCredentials(subscription_key)
)
# </snippet_client>

# <snippet_textfolder>
TEXT_FOLDER = os.path.join(os.path.dirname(
    os.path.realpath(__file__)), "text_files")
# </snippet_textfolder>

# <snippet_imagemodvars>
IMAGE_LIST = [
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample2.jpg",
    "https://moderatorsampleimages.blob.core.chinacloudapi.cn/samples/sample5.png"
]
# </snippet_imagemodvars>

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

def text_moderation():
    """TextModeration.
    This will moderate a given long text.
    """

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

def terms_lists():
    """TermsList.
    This will screen text using a term list.
    """

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

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

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

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

    # <snippet_termslist_refresh>
    #
    # 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)
    # </snippet_termslist_refresh>

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

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

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

    #
    # Re-Screen text
    #
    with open(os.path.join(TEXT_FOLDER, 'content_moderator_term_list.txt'), "rb") as text_fd:
        print('\nScreening text "{}" using term list {}'.format(text, list_id))
        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())

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

    # <snippet_termslist_deletelist>
    #
    # Delete list
    #
    print("\nDelete the term list {}".format(list_id))
    client.list_management_term_lists.delete(list_id=list_id)
    # </snippet_termslist_deletelist>


def image_moderation():
    """ImageModeration.
    This will review an image using workflow and job.
    """

    # <snippet_imagemod_iterate>
    for image_url in IMAGE_LIST:
        print("\nEvaluate image {}".format(image_url))
        # </snippet_imagemod_iterate>

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

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

        # <snip