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

快速入门:检测个人身份信息 (PII)

注意

本快速入门仅介绍文档中的 PII 检测。 若要详细了解如何检测对话中的 PII,请参阅如何检测和编辑对话中的 PII

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

借助本快速入门,使用 .NET 客户端库创建个人身份信息 (PII) 检测应用程序。 在以下示例中,你将创建可在文本中识别已识别的敏感信息的 C# 应用程序。

提示

可以使用 Language Studio 在文档中尝试 PII 检测,而无需编写代码。

先决条件

  • Azure 订阅 - 免费创建订阅
  • Visual Studio IDE
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。
  • 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。

设置

创建新的 .NET Core 应用程序

使用 Visual Studio IDE 创建新的 .NET Core 控制台应用。 这会创建包含单个 C# 源文件的“Hello World”项目:program.cs

右键单击解决方案资源管理器中的解决方案,然后选择“管理 NuGet 包”,以便安装客户端库。 在打开的包管理器中选择“浏览”,搜索 Azure.AI.TextAnalytics。 选择版本 5.2.0,然后选择“安装”。 也可使用包管理器控制台

代码示例

将以下代码复制到 program.cs 文件。 请记得将 key 变量替换为资源的密钥,并将 endpoint 变量替换为资源的终结点。

重要

转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。

重要

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

using Azure;
using System;
using Azure.AI.TextAnalytics;

namespace Example
{
    class Program
    {
        private static readonly AzureKeyCredential credentials = new AzureKeyCredential("replace-with-your-key-here");
        private static readonly Uri endpoint = new Uri("replace-with-your-endpoint-here");

        // Example method for detecting sensitive information (PII) from text 
        static void RecognizePIIExample(TextAnalyticsClient client)
        {
            string document = "Call our office at 312-555-1234, or send an email to support@contoso.com.";
        
            PiiEntityCollection entities = client.RecognizePiiEntities(document).Value;
        
            Console.WriteLine($"Redacted Text: {entities.RedactedText}");
            if (entities.Count > 0)
            {
                Console.WriteLine($"Recognized {entities.Count} PII entit{(entities.Count > 1 ? "ies" : "y")}:");
                foreach (PiiEntity entity in entities)
                {
                    Console.WriteLine($"Text: {entity.Text}, Category: {entity.Category}, SubCategory: {entity.SubCategory}, Confidence score: {entity.ConfidenceScore}");
                }
            }
            else
            {
                Console.WriteLine("No entities were found.");
            }
        }

        static void Main(string[] args)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            RecognizePIIExample(client);

            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }

    }
}

输出

Redacted Text: Call our office at ************, or send an email to *******************.
Recognized 2 PII entities:
Text: 312-555-1234, Category: PhoneNumber, SubCategory: , Confidence score: 0.8
Text: support@contoso.com, Category: Email, SubCategory: , Confidence score: 0.8

参考文档 | 其他示例 | 包 (Maven) | 库源代码

借助本快速入门,使用 Java 客户端库创建个人身份信息 (PII) 检测应用程序。 在以下示例中,你将创建可在文本中识别已识别的敏感信息的 Java 应用程序。

提示

可以使用 Language Studio 在文档中尝试 PII 检测,而无需编写代码。

先决条件

  • Azure 订阅 - 免费创建订阅
  • Java 开发工具包 (JDK) 版本 8 或更高版本
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。
  • 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。

设置

添加客户端库

在首选 IDE 或开发环境中创建 Maven 项目。 然后在项目的 pom.xml 文件中,添加以下依赖项。 可联机找到用于其他生成工具的实现语法。

<dependencies>
     <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-textanalytics</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

代码示例

创建名为 Example.java 的 Java 文件。 打开该文件,并复制以下代码。 请记得将 key 变量替换为资源的密钥,并将 endpoint 变量替换为资源的终结点。

重要

转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。

重要

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

import com.azure.core.credential.AzureKeyCredential;
import com.azure.ai.textanalytics.models.*;
import com.azure.ai.textanalytics.TextAnalyticsClientBuilder;
import com.azure.ai.textanalytics.TextAnalyticsClient;

public class Example {

    private static String KEY = "replace-with-your-key-here";
    private static String ENDPOINT = "replace-with-your-endpoint-here";

    public static void main(String[] args) {
        TextAnalyticsClient client = authenticateClient(KEY, ENDPOINT);
        recognizePiiEntitiesExample(client);
    }
    // Method to authenticate the client object with your key and endpoint
    static TextAnalyticsClient authenticateClient(String key, String endpoint) {
        return new TextAnalyticsClientBuilder()
                .credential(new AzureKeyCredential(key))
                .endpoint(endpoint)
                .buildClient();
    }

    // Example method for detecting sensitive information (PII) from text 
    static void recognizePiiEntitiesExample(TextAnalyticsClient client)
    {
        // The text that need be analyzed.
        String document = "My SSN is 859-98-0987";
        PiiEntityCollection piiEntityCollection = client.recognizePiiEntities(document);
        System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
        piiEntityCollection.forEach(entity -> System.out.printf(
            "Recognized Personally Identifiable Information entity: %s, entity category: %s, entity subcategory: %s,"
                + " confidence score: %f.%n",
            entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
    }
}

输出

Redacted Text: My SSN is ***********
Recognized Personally Identifiable Information entity: 859-98-0987, entity category: USSocialSecurityNumber, entity subcategory: null, confidence score: 0.650000.

参考文档 | 其他示例 | 包 (npm) | 库源代码

借助本快速入门,使用 Node.js 客户端库创建个人身份信息 (PII) 检测应用程序。 在以下示例中,你将创建可在文本中识别已识别的敏感信息的 JavaScript 应用程序。

提示

可以使用 Language Studio 在文档中尝试 PII 检测,而无需编写代码。

先决条件

  • Azure 订阅 - 免费创建订阅
  • Node.js v14 LTS 或更高版本
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。
  • 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。

设置

创建新的 Node.js 应用程序

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。

mkdir myapp 

cd myapp

运行 npm init 命令以使用 package.json 文件创建一个 node 应用程序。

npm init

安装客户端库

安装 npm 包:

npm install @azure/ai-text-analytics

代码示例

打开该文件,并复制以下代码。 请记得将 key 变量替换为资源的密钥,并将 endpoint 变量替换为资源的终结点。

重要

转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。

重要

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

"use strict";

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");
const key = '<paste-your-key-here>';
const endpoint = '<paste-your-endpoint-here>';

//an example document for pii recognition
const documents = [ "The employee's phone number is (555) 555-5555." ];

async function main() {
    console.log(`PII recognition sample`);
  
    const client = new TextAnalyticsClient(endpoint, new AzureKeyCredential(key));
  
    const documents = ["My phone number is 555-555-5555"];
  
    const [result] = await client.analyze("PiiEntityRecognition", documents, "en");
  
    if (!result.error) {
      console.log(`Redacted text: "${result.redactedText}"`);
      console.log("Pii Entities: ");
      for (const entity of result.entities) {
        console.log(`\t- "${entity.text}" of type ${entity.category}`);
      }
    }
}

main().catch((err) => {
console.error("The sample encountered an error:", err);
});

输出

PII recognition sample
Redacted text: "My phone number is ************"
Pii Entities:
        - "555-555-5555" of type PhoneNumber

参考文档 | 其他示例 | 包 (PyPi) | 库源代码

借助本快速入门,使用 Python 客户端库创建个人身份信息 (PII) 检测应用程序。 在以下示例中,你将创建可在文本中识别已识别的敏感信息的 Python 应用程序。

提示

可以使用 Language Studio 在文档中尝试 PII 检测,而无需编写代码。

先决条件

  • Azure 订阅 - 免费创建订阅
  • Python 3.8 或更高版本
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。
  • 若要使用“分析”功能,需要标准 (S) 定价层的“语言”资源。

设置

安装客户端库

在安装 Python 后,可以通过以下命令安装客户端库:

pip install azure-ai-textanalytics==5.2.0

代码示例

创建新的 Python 文件,并复制以下代码。 请记得将 key 变量替换为资源的密钥,并将 endpoint 变量替换为资源的终结点。

重要

转到 Azure 门户。 如果你在“先决条件”部分创建的语言资源部署成功,请单击“后续步骤”下的“转到资源”按钮 。 可以通过导航到资源的“密钥和终结点”页,在“资源管理”下找到你的密钥和终结点。

重要

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

key = "paste-your-key-here"
endpoint = "paste-your-endpoint-here"

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Authenticate the client using your key and endpoint 
def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint, 
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example method for detecting sensitive information (PII) from text 
def pii_recognition_example(client):
    documents = [
        "The employee's SSN is 859-98-0987.",
        "The employee's phone number is 555-555-5555."
    ]
    response = client.recognize_pii_entities(documents, language="en")
    result = [doc for doc in response if not doc.is_error]
    for doc in result:
        print("Redacted Text: {}".format(doc.redacted_text))
        for entity in doc.entities:
            print("Entity: {}".format(entity.text))
            print("\tCategory: {}".format(entity.category))
            print("\tConfidence Score: {}".format(entity.confidence_score))
            print("\tOffset: {}".format(entity.offset))
            print("\tLength: {}".format(entity.length))
pii_recognition_example(client)

输出

Redacted Text: The ********'s SSN is ***********.
Entity: employee
        Category: PersonType
        Confidence Score: 0.97
        Offset: 4
        Length: 8
Entity: 859-98-0987
        Category: USSocialSecurityNumber
        Confidence Score: 0.65
        Offset: 22
        Length: 11
Redacted Text: The ********'s phone number is ************.
Entity: employee
        Category: PersonType
        Confidence Score: 0.96
        Offset: 4
        Length: 8
Entity: 555-555-5555
        Category: PhoneNumber
        Confidence Score: 0.8
        Offset: 31
        Length: 12

参考文档

借助本快速入门,使用 REST API 发送个人身份信息 (PII) 检测请求。 在以下示例中,你将使用 cURL 在文本中识别已识别的敏感信息

提示

可以使用 Language Studio 在文档中尝试 PII 检测,而无需编写代码。

先决条件

  • 最新版本的 cURL
  • 拥有 Azure 订阅后,请在 Azure 门户中创建语言资源,以获取密钥和终结点。 部署后,选择”转到资源”。
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到 API。 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。
    • 可以使用免费定价层 (Free F0) 试用该服务,然后再升级到付费层进行生产。

注意

  • 以下 BASH 示例使用 \ 行继续符。 如果你的控制台或终端使用不同的行继续符,请使用该字符。
  • 可以在 GitHub 上找到特定于语言的示例。
  • 访问 Azure 门户,并找到之前在先决条件部分中创建的语言资源的密钥和终结点。 它们将位于资源的“密钥和终结点”页的“资源管理”下。 然后,将以下代码中的字符串替换为你的密钥和终结点。 若要调用 API,需要以下信息:
参数 (parameter) 说明
-X POST <endpoint> 指定用于访问 API 的终结点。
-H Content-Type: application/json 用于发送 JSON 数据的内容类型。
-H "Ocp-Apim-Subscription-Key:<key> 指定用于访问 API 的密钥。
-d <documents> 包含要发送的文档的 JSON。

以下 cURL 命令从 BASH shell 中执行。 请使用自己的资源名称、资源密钥和 JSON 值编辑这些命令。

个人身份信息 (PII) 检测

  1. 将命令复制到文本编辑器中。
  2. 必要时在命令中进行如下更改:
    1. 将值 <your-language-resource-key> 替换为你的值。
    2. 将请求 URL 的第一部分 (<your-language-resource-endpoint>) 替换为你的终结点 URL。
  3. 打开命令提示符窗口。
  4. 将文本编辑器中的命令粘贴到命令提示符窗口,然后运行命令。
curl -i -X POST https://<your-language-resource-endpoint>/language/:analyze-text?api-version=2022-05-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key:<your-language-resource-key>" \
-d \
'
{
    "kind": "PiiEntityRecognition",
    "parameters": {
        "modelVersion": "latest"
    },
    "analysisInput":{
        "documents":[
            {
                "id":"1",
                "language": "en",
                "text": "Call our office at 312-555-1234, or send an email to support@contoso.com"
            }
        ]
    }
}
'

JSON 响应

{
	"kind": "PiiEntityRecognitionResults",
	"results": {
		"documents": [{
			"redactedText": "Call our office at ************, or send an email to *******************",
			"id": "1",
			"entities": [{
				"text": "312-555-1234",
				"category": "PhoneNumber",
				"offset": 19,
				"length": 12,
				"confidenceScore": 0.8
			}, {
				"text": "support@contoso.com",
				"category": "Email",
				"offset": 53,
				"length": 19,
				"confidenceScore": 0.8
			}],
			"warnings": []
		}],
		"errors": [],
		"modelVersion": "2021-01-15"
	}
}

清理资源

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

后续步骤