Memeriksa teks terhadap daftar istilah kustom di C#

Daftar istilah global default di Azure Content Moderator cukup untuk sebagian besar kebutuhan moderasi konten. Namun, Anda mungkin perlu menyaring istilah yang khusus untuk organisasi Anda.

Anda dapat menggunakan SDK Content Moderator untuk .NET untuk membuat daftar istilah kustom untuk digunakan dengan Text Moderation API.

Artikel ini menyediakan informasi dan sampel kode untuk membantu Anda mulai menggunakan SDK Content Moderator untuk .NET untuk:

  • Membuat daftar.
  • Menambahkan istilah ke daftar.
  • Menyaring istilah terhadap istilah dalam daftar.
  • Menghapus istilah dari daftar.
  • Menghapus daftar.
  • Mengedit informasi daftar.
  • Merefresh indeks sehingga perubahan pada daftar disertakan dalam pemindaian baru.

Jika Anda tidak memiliki langganan Azure, buat akun gratis sebelum Anda memulai.

Mendaftar untuk layanan Moderator Konten

Sebelum dapat menggunakan layanan Content Moderator melalui REST API atau SDK, Anda memerlukan kunci langganan. Berlangganan layanan Content Moderator di portal Azure untuk mendapatkannya.

Membuat proyek Visual Studio

  1. Tambahkan proyek Aplikasi konsol (.NET Framework) baru ke solusi Anda.

  2. Beri nama proyek TermLists. Pilih proyek ini sebagai proyek permulaan tunggal untuk solusi.

Memasang paket yang diperlukan

Instal paket NuGet berikut untuk proyek TermLists:

  • Microsoft.Azure.CognitiveServices.ContentModerator
  • Microsoft.Rest.ClientRuntime
  • Microsoft.Rest.ClientRuntime.Azure
  • Newtonsoft.Json

Memperbarui program menggunakan pernyataan

Tambahkan pernyataan using berikut.

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.Threading;

Membuat klien Moderator Konten

Tambahkan kode berikut untuk membuat klien Moderator Konten untuk langganan Anda. Perbarui bidang AzureEndpoint dan CMSubscriptionKey dengan nilai URL titik akhir dan kunci langganan Anda. Anda dapat menemukan ini di tab Mulai cepat sumber daya Anda di portal Azure.

/// <summary>
/// Wraps the creation and configuration of a Content Moderator client.
/// </summary>
/// <remarks>This class library contains insecure code. If you adapt this 
/// code for use in production, use a secure method of storing and using
/// your Content Moderator subscription key.</remarks>
public static class Clients
{
    /// <summary>
    /// The base URL fragment for Content Moderator calls.
    /// </summary>
    private static readonly string AzureEndpoint = "YOUR ENDPOINT URL";

    /// <summary>
    /// Your Content Moderator subscription key.
    /// </summary>
    private static readonly string CMSubscriptionKey = "YOUR API KEY";

    /// <summary>
    /// Returns a new Content Moderator client for your subscription.
    /// </summary>
    /// <returns>The new client.</returns>
    /// <remarks>The <see cref="ContentModeratorClient"/> is disposable.
    /// When you have finished using the client,
    /// you should dispose of it either directly or indirectly. </remarks>
    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;
    }
}

Penting

Jangan lupa menghapus kunci dari kode setelah Anda selesai, dan jangan pernah mempostingnya secara publik. Untuk produksi, gunakan cara yang aman untuk menyimpan dan mengakses kredensial Anda seperti Azure Key Vault. Lihat artikel keamanan layanan Azure AI untuk informasi selengkapnya.

Tambahkan properti privat

Tambahkan properti privat berikut ini ke TermList namespace layanan, Program kelas.

/// <summary>
/// The language of the terms in the term lists.
/// </summary>
private const string lang = "eng";

/// <summary>
/// The minimum amount of time, in milliseconds, to wait between calls
/// to the Content Moderator APIs.
/// </summary>
private const int throttleRate = 3000;

/// <summary>
/// The number of minutes to delay after updating the search index before
/// performing image match operations against the list.
/// </summary>
private const double latencyDelay = 0.5;

Membuat daftar istilah

Anda membuat daftar istilah dengan ContentModeratorClient.ListManagementTermLists.Create. Parameter pertama untuk Create adalah string yang berisi jenis MIME, yang harus berupa "application/json". Untuk mengetahui informasi selengkapnya, lihat referensi API. Parameter kedua adalah objek Body yang berisi nama dan deskripsi untuk daftar istilah baru.

Catatan

Ada batas maksimum 5 daftar istilah dengan setiap daftar tidak melebihi 10.000 istilah.

Tambahkan definisi metode berikut ke namespace layanan TermLists, Program kelas.

Catatan

Kunci layanan Moderator Konten Anda memiliki batas tarif permintaan per detik (RPS), dan jika Anda melebihi batas, SDK akan memberikan pengecualian dengan kode kesalahan 429. Kunci tingkat gratis memiliki batas tarif satu RPS.

/// <summary>
/// Creates a new term list.
/// </summary>
/// <param name="client">The Content Moderator client.</param>
/// <returns>The term list ID.</returns>
static string CreateTermList (ContentModeratorClient client)
{
    Console.WriteLine("Creating term list.");

    Body body = new Body("Term list name", "Term list description");
    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("Term list created. ID: {0}.", list_id);
        Thread.Sleep(throttleRate);
        return list_id;
    }
}

Memperbarui nama dan deskripsi daftar istilah

Anda memperbarui informasi daftar istilah dengan ContentModeratorClient.ListManagementTermLists.Update. Parameter pertama untuk Update adalah ID daftar istilah. Parameter kedua adalah jenis MIME, yang harus berupa "application/json". Untuk mengetahui informasi selengkapnya, lihat referensi API. Parameter ketiga adalah objek Body, yang berisi nama dan deskripsi baru.

Tambahkan definisi metode berikut ke namespace layanan TermLists, Program kelas.

/// <summary>
/// Update the information for the indicated term list.
/// </summary>
/// <param name="client">The Content Moderator client.</param>
/// <param name="list_id">The ID of the term list to update.</param>
/// <param name="name">The new name for the term list.</param>
/// <param name="description">The new description for the term list.</param>
static void UpdateTermList (ContentModeratorClient client, string list_id, string name = null, string description = null)
{
    Console.WriteLine("Updating information for term list with ID {0}.", list_id);
    Body body = new Body(name, description);
    client.ListManagementTermLists.Update(list_id, "application/json", body);
    Thread.Sleep(throttleRate);
}

Menambahkan istilah ke daftar istilah

Tambahkan definisi metode berikut ke namespace layanan TermLists, Program kelas.

/// <summary>
/// Add a term to the indicated term list.
/// </summary>
/// <param name="client">The Content Moderator client.</param>
/// <param name="list_id">The ID of the term list to update.</param>
/// <param name="term">The term to add to the term list.</param>
static void AddTerm (ContentModeratorClient client, string list_id, string term)
{
    Console.WriteLine("Adding term \"{0}\" to term list with ID {1}.", term, list_id);
    client.ListManagementTerm.AddTerm(list_id, term, lang);
    Thread.Sleep(throttleRate);
}

Mendapatkan semua istilah dalam daftar istilah

Tambahkan definisi metode berikut ke namespace layanan TermLists, Program kelas.

/// <summary>
/// Get all terms in the indicated term list.
/// </summary>
/// <param name="client">The Content Moderator client.</param>
/// <param name="list_id">The ID of the term list from which to get all terms.</param>
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);
}

Menambahkan kode untuk merefresh indeks pencarian

Setelah Anda membuat perubahan pada daftar istilah, Anda merefresh indeks pencariannya agar perubahan disertakan saat berikutnya Anda menggunakan daftar istilah ke teks layar. Ini mirip dengan cara mesin cari di desktop Anda (jika diaktifkan) atau mesin cari web terus merefresh indeksnya untuk menyertakan file atau halaman baru.

Anda merefresh indeks pencarian daftar istilah dengan ContentModeratorClient.ListManagementTermLists.RefreshIndexMethod.

Tambahkan definisi metode berikut ke namespace layanan TermLists, Program kelas.

/// <summary>
/// Refresh the search index for the indicated term list.
/// </summary>
/// <param name="client">The Content Moderator client.</param>
/// <param name="list_id">The ID of the term list to refresh.</param>
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));
}

Teks layar yang menggunakan daftar istilah

Anda menyaring teks menggunakan daftar istilah dengan ContentModeratorClient.TextModeration.ScreenText, yang mengambil parameter berikut.

  • Bahasa istilah dalam daftar istilah.
  • Jenis MIME, yang dapat berupa "texs/html", "texs/xml", "texs/markdown", atau "texs/plain".
  • Teks ke layar.
  • Nilai boolean. Atur bidang ini ke true untuk mengoreksi otomatis teks sebelum menyaringnya.
  • Nilai boolean. Atur bidang ini ke true untuk mendeteksi data pribadi dalam teks.
  • ID daftar istilah.

Untuk mengetahui informasi selengkapnya, lihat referensi API.

ScreenText menampilkan objek Layar, yang memiliki properti Terms yang mencantumkan istilah apa pun yang terdeteksi Content Moderator dalam penyaringan. Perhatikan bahwa jika Content Moderator tidak mendeteksi istilah apa pun selama penyaringan, properti Terms memiliki nilai null.

Tambahkan definisi metode berikut ke namespace layanan TermLists, Program kelas.

/// <summary>
/// Screen the indicated text for terms in the indicated term list.
/// </summary>
/// <param name="client">The Content Moderator client.</param>
/// <param name="list_id">The ID of the term list to use to screen the text.</param>
/// <param name="text">The text to screen.</param>
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(lang, "text/plain", text, 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);
}

Menghapus istilah dan daftar

Menghapus istilah atau daftar sangat mudah. Anda menggunakan SDK untuk melakukan tugas berikut:

  • Hapus istilah. (ContentModeratorClient.ListManagementTerm.DeleteTerm)
  • Menghapus semua istilah dalam daftar tanpa menghapus daftar. (ContentModeratorClient.ListManagementTerm.DeleteAllTerms)
  • Menghapus daftar dan semua kontennya. (ContentModeratorClient.ListManagementTermLists.Delete)

Menghapus istilah

Tambahkan definisi metode berikut ke namespace layanan TermLists, Program kelas.

/// <summary>
/// Delete a term from the indicated term list.
/// </summary>
/// <param name="client">The Content Moderator client.</param>
/// <param name="list_id">The ID of the term list from which to delete the term.</param>
/// <param name="term">The term to delete.</param>
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);
}

Menghapus semua istilah dalam daftar istilah

Tambahkan definisi metode berikut ke namespace layanan TermLists, Program kelas.

/// <summary>
/// Delete all terms from the indicated term list.
/// </summary>
/// <param name="client">The Content Moderator client.</param>
/// <param name="list_id">The ID of the term list from which to delete all terms.</param>
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);
}

Menghapus daftar istilah

Tambahkan definisi metode berikut ke namespace layanan TermLists, Program kelas.

/// <summary>
/// Delete the indicated term list.
/// </summary>
/// <param name="client">The Content Moderator client.</param>
/// <param name="list_id">The ID of the term list to delete.</param>
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);
}

Membuat metode Utama

Tambahkan definisi metode Utama ke namespace layanan TermLists, Program kelas. Terakhir, tutup kelas Program dan namespace layanan TermLists.

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

        UpdateTermList(client, list_id, "name", "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();
    }
}

Jalankan aplikasi untuk melihat output

Output konsol Anda akan terlihat seperti berikut:

Creating term list.
Term list created. ID: 252.
Updating information for term list with ID 252.

Adding term "term1" to term list with ID 252.
Adding term "term2" to term list with ID 252.

Getting terms in term list with ID 252.
term1
term2

Refreshing search index for term list with ID 252.

Screening text: "This text contains the terms "term1" and "term2"." using term list with ID 252.
Found term: "term1" from list ID 252 at index 32.
Found term: "term2" from list ID 252 at index 46.

Removed term "term1" from term list with ID 252.

Refreshing search index for term list with ID 252.

Screening text: "This text contains the terms "term1" and "term2"." using term list with ID 252.
Found term: "term2" from list ID 252 at index 46.

Removing all terms from term list with ID 252.
Deleting term list with ID 252.
Press ENTER to close the application.

Langkah berikutnya

Dapatkan Content Moderator .NET SDK dan solusi Visual Studio untuk ini dan panduan memulai Moderator Konten lainnya untuk .NET, dan mulai integrasi Anda.