Skip to main content

自定义文本词语列表

分类:  Azure认知服务 标签:  #Azure #人工智能 #内容审查 发布于: 2023-06-05 13:13:16

本章的源代码可以从下述地址下载:
[Demo Source Code]https://github.com/hylinux/azure-demo/tree/main/dotnet/cognitive-service/ContentModeratorCustomList)

内容审查服务提供几个工具来管理自定义的词语列表:

  • Term List API Console
  • Term List API

Term List API Console是微软提供的一个基于Web的工具,Azure China目前没有提供该工具,如果使用的是Azure China的订阅,只能通过Term List API和相应的SDK来完成Term List的管理。

通过Term List API Console来管理自定义的词语列表

下面我们来介绍如果使用Term List API Console来管理自定义的词语列表。
在使用这个console之前,先需要拿到必要的信息,这个包括:

关于如何拿到这两个信息,需要你访问Azure Portal, 找到你的内容审查的资源,找到上述的资源,如下图:


拿到必要的信息之后,通过如下的URL访问Term List API Console
Term List API Console

打开该URL之后,即可以访问到Term List API Console, 如下图:


选择左侧菜单的Create, 然后选择你的内容审查服务所在的区域:


例如我的服务在East Asia, 那么我就选择该区域,选择完了之后,在出现的界面上填充我们刚刚收集到的endpoint和key的信息,然后输入你需要创建的List的基本信息,注意MetaData根据你的需要自己定义就好了:


最后点击Send按钮就完成了创建


创建的结果图:


创建完成了hi后,您可以使用同样的步骤进行添加自己需要的词语,这些看看就明白怎么操作了,就不再赘述了, 管理term等操作也可以使用左侧的菜单来完成。

注意
创建完term custom list以及添加好自定义的term之后,要记得Refresh Search Index, 可以通过下图的菜单来操作:


使用Term List API来管理自定义的词语列表

由于Azure China并没有相应的工具可以使用,因此对于Azure China我们不得不暂时使用SDK或者API来完成自定义词语列表的管理,我们接下来的例子使用.net SDK来做下述操作:

  • 创建自定义的词语列表
  • 增加自定义词语到列表中
  • 使用自定义列表进行文本内容审查
  • 从列表中删除自定义词语
  • 删除自定义词语列表
  • 编辑列表信息
  • 刷新自定义词语列表的索引

先创建我们需要的应用, 并添加我们需要的包

dotnet new console -n ContentModeratorCustomList
cd ContentModeratorCustomList
dotnet add package Microsoft.Azure.CognitiveServices.ContentModerator
dotnet add package Microsoft.Rest.ClientRuntime
dotnet add package Microsoft.Rest.ClientRuntime.Azure
dotnet add package Newtonsoft.Json

添加完包之后,使用自己的编辑器或者IDE打开Program.cs添加包的引用

using Microsoft.Azure.CognitiveServices.ContentModerator;
using Microsoft.Azure.CognitiveServices.ContentModerator.Models;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Threading;

我们需要订一个内容审查服务的客户端,注意先要取得你得内容审查服务得终结点和你得KEY

//创建内容审查的客户端
public static class Clients
{
    //内容审查服务的Endpoint
    private static readonly string AzureEndpoint = "Your Endpoint URL";

    //内容审查的Key
    private static readonly string CMSubscriptionKey = "YOUR API KEY";

    //创建客户端
    public static ContentModeratorClient NewClient()
    {
        // Create and initialize an instance of the Content Moderator API wrapper.
        ContentModeratorClient client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(CMSubscriptionKey));

        client.Endpoint = AzureEndpoint;
        return client;
    }
}

然后我们再回到Program类中定义如下得内容,先定义三个字段,关于这些字段得意义请参考注释:

//指定自定义词语列表的语言
private const string lang = "eng";

//指定每次调用API的间隔事件,单位毫秒, 原因是api的call是有限制的
private const int throttleRate = 3000;

//指定使用自定义词语列表审查时,刷新index要等待的事件,单位分钟
private const double latencyDelay = 0.5;

定义创建自定义词语列表得方法

//创建自定义词语列表
static string CreateTermList(ContentModeratorClient client)
{
    Console.WriteLine("正在创建自定义词语列表.");

    Body body = new Body("MyFirstTextCustomList1", "My First Text Moderator Customer List");
    TermList list = client.ListManagementTermLists.Create("application/json", body);
    if (false == list.Id.HasValue)
    {
        throw new Exception("TermList.Id value missing.");
    }
    else
    {
        string list_id = list.Id.Value.ToString();
        Console.WriteLine("自定义词语列表创建成功 ID: {0}.", list_id);
        Thread.Sleep(throttleRate);
        return list_id;
    }
}

创建更新自定义列表得方法

//更新自定义列表的名称和描述
static void UpdateTermList(ContentModeratorClient client, string list_id, string name = null, string description = null)
{
    Console.WriteLine("更新自定义词语列表,列表ID {0}.", list_id);
    Body body = new Body(name, description);
    client.ListManagementTermLists.Update(list_id, "application/json", body);
    Thread.Sleep(throttleRate);
}

管理自定义列表的词语:

//向列表中添加词语
static void AddTerm(ContentModeratorClient client, string list_id, string term)
{
    Console.WriteLine("添加词语 \"{0}\" 到列表ID {1}.", term, list_id);
    client.ListManagementTerm.AddTerm(list_id, term, lang);
    Thread.Sleep(throttleRate);
}
//从列表中返回所有的自定义词语
static void GetAllTerms(ContentModeratorClient client, string list_id)
{
    Console.WriteLine("Getting terms in term list with ID {0}.", list_id);
    Terms terms = client.ListManagementTerm.GetAllTerms(list_id, lang);
    TermsData data = terms.Data;
    foreach (TermsInList term in data.Terms)
    {
        Console.WriteLine(term.Term);
    }
    Thread.Sleep(throttleRate);
}

//刷新自定义列表的索引
static void RefreshSearchIndex(ContentModeratorClient client, string list_id)
{
    Console.WriteLine("Refreshing search index for term list with ID {0}.", list_id);
    client.ListManagementTermLists.RefreshIndexMethod(list_id, lang);
    Thread.Sleep((int)(latencyDelay * 60 * 1000));
}

//删除一个自定义词语
static void DeleteTerm(ContentModeratorClient client, string list_id, string term)
{
    Console.WriteLine("Removed term \"{0}\" from term list with ID {1}.", term, list_id);
    client.ListManagementTerm.DeleteTerm(list_id, term, lang);
    Thread.Sleep(throttleRate);
}


//删除所有的自定义词语
static void DeleteAllTerms(ContentModeratorClient client, string list_id)
{
    Console.WriteLine("Removing all terms from term list with ID {0}.", list_id);
    client.ListManagementTerm.DeleteAllTerms(list_id, lang);
    Thread.Sleep(throttleRate);
}


//删除自定义词语列表
static void DeleteTermList(ContentModeratorClient client, string list_id)
{
    Console.WriteLine("Deleting term list with ID {0}.", list_id);
    client.ListManagementTermLists.Delete(list_id);
    Thread.Sleep(throttleRate);
}

使用自定义词语列表

//使用自定义列表
static void ScreenText(ContentModeratorClient client, string list_id, string text)
{
    Console.WriteLine("Screening text: \"{0}\" using term list with ID {1}.", text, list_id);
    Screen screen = client.TextModeration.ScreenText("text/plain", 
    new MemoryStream(Encoding.UTF8.GetBytes(text)), lang, false, false, list_id);
    if (null == screen.Terms)
    {
        Console.WriteLine("No terms from the term list were detected in the text.");
    }
    else
    {
        foreach (DetectedTerms term in screen.Terms)
        {
            Console.WriteLine(String.Format("Found term: \"{0}\" from list ID {1} at index {2}.", term.Term, term.ListId, term.Index));
        }
    }
    Thread.Sleep(throttleRate);
}

组合上述定义的方法在Main()方法中测试并使用

static void Main(string[] args)
{
    using (var client = Clients.NewClient())
    {
        string list_id = CreateTermList(client);

        UpdateTermList(client, list_id, "MyFirstNewCustomlistWasChanged", "Just put a description");
        AddTerm(client, list_id, "term1");
        AddTerm(client, list_id, "term2");

        GetAllTerms(client, list_id);

        // Always remember to refresh the search index of your list
        RefreshSearchIndex(client, list_id);

        string text = "This text contains the terms \"term1\" and \"term2\".";
        ScreenText(client, list_id, text);

        DeleteTerm(client, list_id, "term1");

        // Always remember to refresh the search index of your list
        RefreshSearchIndex(client, list_id);

        text = "This text contains the terms \"term1\" and \"term2\".";
        ScreenText(client, list_id, text);

        DeleteAllTerms(client, list_id);
        DeleteTermList(client, list_id);

        Console.WriteLine("Press ENTER to close the application.");
        Console.ReadLine();
    }

}

运行该项目,得到如下的运行结果: