跳转到主要内容

Microsoft Azure AI Content Safety客户端库 for Python

项目描述

Azure AI Content Safety客户端库 for Python

Azure AI Content Safety可检测应用程序和服务中的有害用户生成和AI生成内容。内容安全包括文本和图像API,允许您检测有害内容

  • 文本分析API:扫描文本中的性内容、暴力、仇恨和自残,具有多严重级别。
  • 图像分析API:扫描图像中的性内容、暴力、仇恨和自残,具有多严重级别。
  • 文本黑名单管理API:默认的AI分类器对于大多数内容安全需求是足够的;然而,您可能需要筛选特定于您用例的术语。您可以使用文本API创建术语的黑名单。

文档

提供各种文档以帮助您入门

入门

先决条件

安装软件包

pip install azure-ai-contentsafety

认证客户端

获取端点

您可以通过Azure门户Azure CLI使用Azure AI Content Safety服务资源的端点。

# Get the endpoint for the Azure AI Content Safety service resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint"

使用API密钥创建ContentSafetyClient/BlocklistClient

使用API密钥作为credential参数。

  • 步骤1:获取API密钥。API密钥可以在Azure门户中找到,或者通过运行以下Azure CLI命令获取:

    az cognitiveservices account keys list --name "<resource-name>" --resource-group "<resource-group-name>"
    
  • 步骤2:将密钥作为字符串传递给AzureKeyCredential实例。

    from azure.core.credentials import AzureKeyCredential
    from azure.ai.contentsafety import ContentSafetyClient, BlocklistClient
    
    endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
    credential = AzureKeyCredential("<api_key>")
    content_safety_client = ContentSafetyClient(endpoint, credential)
    blocklist_client = BlocklistClient(endpoint, credential)
    

使用Microsoft Entra ID令牌凭证创建ContentSafetyClient/BlocklistClient

  • 步骤1:为您的资源启用Microsoft Entra ID。请参阅此文档使用Microsoft Entra ID进行认证,了解如何为您的资源启用Microsoft Entra ID的步骤。

    主要步骤包括

    • 使用自定义子域创建资源。
    • 创建服务主体并将其分配给Cognitive Services用户角色。
  • 步骤2:将Microsoft Entra应用程序的客户端ID、租户ID和客户端密钥的值设置为环境变量:AZURE_CLIENT_IDAZURE_TENANT_IDAZURE_CLIENT_SECRET

    DefaultAzureCredential将使用这些环境变量的值。

    from azure.identity import DefaultAzureCredential
    from azure.ai.contentsafety import ContentSafetyClient, BlocklistClient
    
    endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
    credential = DefaultAzureCredential()
    content_safety_client = ContentSafetyClient(endpoint, credential)
    blocklist_client = BlocklistClient(endpoint, credential)
    

关键概念

可用功能

此服务提供不同类型的分析。以下表格描述了当前可用的API。

功能 描述
文本分析API 扫描文本中的性内容、暴力、仇恨和自残,具有多严重级别。
图像分析API 扫描图像中的性内容、暴力、仇恨和自残,具有多严重级别。
文本黑名单管理API 默认AI分类器足以满足大多数内容安全需求。但是,您可能需要筛选与您的特定用例相关的术语。您可以使用文本API创建术语黑名单。

伤害类别

内容安全识别四种不同类型的令人反感的内容。

类别 描述
仇恨 仇恨和公平相关的伤害指的是针对或使用贬义或歧视性语言攻击或提及基于某些区分这些群体的不同属性的人或身份群体,包括但不限于种族、民族、国籍、性别认同和表达、性取向、宗教、移民状态、能力状态、个人外观和体型。
性描述与解剖器官和生殖器、浪漫关系、以色情或亲切的术语描述的行为、怀孕、物理性行为,包括那些表现为对某人自愿进行的攻击或强迫性暴力行为的描述、卖淫、色情和虐待。
暴力 暴力描述与伤害、伤害、损害或杀害某人或某物的物理行为相关的语言;描述武器、枪支和相关实体,如制造商、协会、立法等。
自残 自残描述与故意伤害、伤害、损害自己的身体或自杀的物理行为相关的语言。

分类可以是多标签的。例如,当文本样本通过文本审查模型时,它可以被分类为性内容和暴力。

严重级别

服务应用的所有伤害类别都附带严重级别评分。严重级别旨在表示显示标记内容的后果的严重程度。

文本:当前版本的文本模型支持0-7的完整严重级别刻度。默认情况下,响应将输出4个值:0、2、4和6。每两个相邻级别映射到单个级别。用户可以在请求中使用“outputType”并将其设置为“EightSeverityLevels”以获取8个值输出:0、1、2、3、4、5、6、7。您可以参阅文本内容严重级别定义以获取详细信息。

  • [0,1] -> 0
  • [2,3] -> 2
  • [4,5] -> 4
  • [6,7] -> 6

图像:当前图像模型版本支持完整的0-7严重程度尺度的裁剪版本。分类器只返回严重程度0、2、4和6;每两个相邻级别映射到单个级别。您可以参考图像内容严重程度级别定义以获取详细信息。

  • [0,1] -> 0
  • [2,3] -> 2
  • [4,5] -> 4
  • [6,7] -> 6

文本黑名单管理

支持以下操作来管理您的文本黑名单

  • 创建或修改黑名单
  • 列出所有黑名单
  • 按黑名单名称获取黑名单
  • 将黑名单项目添加到黑名单
  • 从黑名单中删除黑名单项目
  • 按黑名单名称列出黑名单中的所有黑名单项目
  • 按黑名单项目ID和黑名单名称获取黑名单项目
  • 删除黑名单及其所有黑名单项目

您可以在分析文本时设置要使用的黑名单,然后您可以从返回的响应中获取黑名单匹配结果。

示例

以下部分提供了一些代码片段,涵盖了内容安全服务的一些最常见任务,包括

有关这里使用的数据,请参阅示例数据。有关更多示例,请参阅示例

分析文本

无黑名单分析文本

    import os
    from azure.ai.contentsafety import ContentSafetyClient
    from azure.ai.contentsafety.models import TextCategory
    from azure.core.credentials import AzureKeyCredential
    from azure.core.exceptions import HttpResponseError
    from azure.ai.contentsafety.models import AnalyzeTextOptions

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Content Safety client
    client = ContentSafetyClient(endpoint, AzureKeyCredential(key))

    # Construct a request
    request = AnalyzeTextOptions(text="You are an idiot")

    # Analyze text
    try:
        response = client.analyze_text(request)
    except HttpResponseError as e:
        print("Analyze text failed.")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

    hate_result = next(item for item in response.categories_analysis if item.category == TextCategory.HATE)
    self_harm_result = next(item for item in response.categories_analysis if item.category == TextCategory.SELF_HARM)
    sexual_result = next(item for item in response.categories_analysis if item.category == TextCategory.SEXUAL)
    violence_result = next(item for item in response.categories_analysis if item.category == TextCategory.VIOLENCE)

    if hate_result:
        print(f"Hate severity: {hate_result.severity}")
    if self_harm_result:
        print(f"SelfHarm severity: {self_harm_result.severity}")
    if sexual_result:
        print(f"Sexual severity: {sexual_result.severity}")
    if violence_result:
        print(f"Violence severity: {violence_result.severity}")

有黑名单分析文本

    import os
    from azure.ai.contentsafety import ContentSafetyClient
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.contentsafety.models import AnalyzeTextOptions
    from azure.core.exceptions import HttpResponseError

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Content Safety client
    client = ContentSafetyClient(endpoint, AzureKeyCredential(key))

    blocklist_name = "TestBlocklist"
    input_text = "I h*te you and I want to k*ll you."

    try:
        # After you edit your blocklist, it usually takes effect in 5 minutes, please wait some time before analyzing with blocklist after editing.
        analysis_result = client.analyze_text(
            AnalyzeTextOptions(text=input_text, blocklist_names=[blocklist_name], halt_on_blocklist_hit=False)
        )
        if analysis_result and analysis_result.blocklists_match:
            print("\nBlocklist match results: ")
            for match_result in analysis_result.blocklists_match:
                print(
                    f"BlocklistName: {match_result.blocklist_name}, BlockItemId: {match_result.blocklist_item_id}, "
                    f"BlockItemText: {match_result.blocklist_item_text}"
                )
    except HttpResponseError as e:
        print("\nAnalyze text failed: ")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

分析图像

    import os
    from azure.ai.contentsafety import ContentSafetyClient
    from azure.ai.contentsafety.models import ImageCategory
    from azure.core.credentials import AzureKeyCredential
    from azure.core.exceptions import HttpResponseError
    from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
    image_path = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "./sample_data/image.jpg"))

    # Create a Content Safety client
    client = ContentSafetyClient(endpoint, AzureKeyCredential(key))

    # Build request
    with open(image_path, "rb") as file:
        request = AnalyzeImageOptions(image=ImageData(content=file.read()))

    # Analyze image
    try:
        response = client.analyze_image(request)
    except HttpResponseError as e:
        print("Analyze image failed.")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

    hate_result = next(item for item in response.categories_analysis if item.category == ImageCategory.HATE)
    self_harm_result = next(item for item in response.categories_analysis if item.category == ImageCategory.SELF_HARM)
    sexual_result = next(item for item in response.categories_analysis if item.category == ImageCategory.SEXUAL)
    violence_result = next(item for item in response.categories_analysis if item.category == ImageCategory.VIOLENCE)

    if hate_result:
        print(f"Hate severity: {hate_result.severity}")
    if self_harm_result:
        print(f"SelfHarm severity: {self_harm_result.severity}")
    if sexual_result:
        print(f"Sexual severity: {sexual_result.severity}")
    if violence_result:
        print(f"Violence severity: {violence_result.severity}")

管理文本黑名单

创建或更新文本黑名单

    import os
    from azure.ai.contentsafety import BlocklistClient
    from azure.ai.contentsafety.models import TextBlocklist
    from azure.core.credentials import AzureKeyCredential
    from azure.core.exceptions import HttpResponseError

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Blocklist client
    client = BlocklistClient(endpoint, AzureKeyCredential(key))

    blocklist_name = "TestBlocklist"
    blocklist_description = "Test blocklist management."

    try:
        blocklist = client.create_or_update_text_blocklist(
            blocklist_name=blocklist_name,
            options=TextBlocklist(blocklist_name=blocklist_name, description=blocklist_description),
        )
        if blocklist:
            print("\nBlocklist created or updated: ")
            print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
    except HttpResponseError as e:
        print("\nCreate or update text blocklist failed: ")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

列出文本黑名单

    import os
    from azure.ai.contentsafety import BlocklistClient
    from azure.core.credentials import AzureKeyCredential
    from azure.core.exceptions import HttpResponseError

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Blocklist client
    client = BlocklistClient(endpoint, AzureKeyCredential(key))

    try:
        blocklists = client.list_text_blocklists()
        if blocklists:
            print("\nList blocklists: ")
            for blocklist in blocklists:
                print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
    except HttpResponseError as e:
        print("\nList text blocklists failed: ")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

获取文本黑名单

    import os
    from azure.ai.contentsafety import BlocklistClient
    from azure.core.credentials import AzureKeyCredential
    from azure.core.exceptions import HttpResponseError

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Blocklist client
    client = BlocklistClient(endpoint, AzureKeyCredential(key))

    blocklist_name = "TestBlocklist"

    try:
        blocklist = client.get_text_blocklist(blocklist_name=blocklist_name)
        if blocklist:
            print("\nGet blocklist: ")
            print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
    except HttpResponseError as e:
        print("\nGet text blocklist failed: ")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

删除文本黑名单

    import os
    from azure.ai.contentsafety import BlocklistClient
    from azure.core.credentials import AzureKeyCredential
    from azure.core.exceptions import HttpResponseError

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Blocklist client
    client = BlocklistClient(endpoint, AzureKeyCredential(key))

    blocklist_name = "TestBlocklist"

    try:
        client.delete_text_blocklist(blocklist_name=blocklist_name)
        print(f"\nDeleted blocklist: {blocklist_name}")
    except HttpResponseError as e:
        print("\nDelete blocklist failed:")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

添加黑名单项目

    import os
    from azure.ai.contentsafety import BlocklistClient
    from azure.ai.contentsafety.models import AddOrUpdateTextBlocklistItemsOptions, TextBlocklistItem
    from azure.core.credentials import AzureKeyCredential
    from azure.core.exceptions import HttpResponseError

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Blocklist client
    client = BlocklistClient(endpoint, AzureKeyCredential(key))

    blocklist_name = "TestBlocklist"
    block_item_text_1 = "k*ll"
    block_item_text_2 = "h*te"

    block_items = [TextBlocklistItem(text=block_item_text_1), TextBlocklistItem(text=block_item_text_2)]
    try:
        result = client.add_or_update_blocklist_items(
            blocklist_name=blocklist_name, options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=block_items)
        )
        for block_item in result.blocklist_items:
            print(
                f"BlockItemId: {block_item.blocklist_item_id}, Text: {block_item.text}, Description: {block_item.description}"
            )
    except HttpResponseError as e:
        print("\nAdd block items failed: ")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

列出黑名单项目

    import os
    from azure.ai.contentsafety import BlocklistClient
    from azure.core.credentials import AzureKeyCredential
    from azure.core.exceptions import HttpResponseError

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Blocklist client
    client = BlocklistClient(endpoint, AzureKeyCredential(key))

    blocklist_name = "TestBlocklist"

    try:
        block_items = client.list_text_blocklist_items(blocklist_name=blocklist_name)
        if block_items:
            print("\nList block items: ")
            for block_item in block_items:
                print(
                    f"BlockItemId: {block_item.blocklist_item_id}, Text: {block_item.text}, "
                    f"Description: {block_item.description}"
                )
    except HttpResponseError as e:
        print("\nList block items failed: ")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

获取黑名单项目

    import os
    from azure.ai.contentsafety import BlocklistClient
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.contentsafety.models import TextBlocklistItem, AddOrUpdateTextBlocklistItemsOptions
    from azure.core.exceptions import HttpResponseError

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Blocklist client
    client = BlocklistClient(endpoint, AzureKeyCredential(key))

    blocklist_name = "TestBlocklist"
    block_item_text_1 = "k*ll"

    try:
        # Add a blockItem
        add_result = client.add_or_update_blocklist_items(
            blocklist_name=blocklist_name,
            options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=[TextBlocklistItem(text=block_item_text_1)]),
        )
        if not add_result or not add_result.blocklist_items or len(add_result.blocklist_items) <= 0:
            raise RuntimeError("BlockItem not created.")
        block_item_id = add_result.blocklist_items[0].blocklist_item_id

        # Get this blockItem by blockItemId
        block_item = client.get_text_blocklist_item(blocklist_name=blocklist_name, blocklist_item_id=block_item_id)
        print("\nGet blockitem: ")
        print(
            f"BlockItemId: {block_item.blocklist_item_id}, Text: {block_item.text}, Description: {block_item.description}"
        )
    except HttpResponseError as e:
        print("\nGet block item failed: ")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

删除黑名单项目

    import os
    from azure.ai.contentsafety import BlocklistClient
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.contentsafety.models import (
        TextBlocklistItem,
        AddOrUpdateTextBlocklistItemsOptions,
        RemoveTextBlocklistItemsOptions,
    )
    from azure.core.exceptions import HttpResponseError

    key = os.environ["CONTENT_SAFETY_KEY"]
    endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]

    # Create a Blocklist client
    client = BlocklistClient(endpoint, AzureKeyCredential(key))

    blocklist_name = "TestBlocklist"
    block_item_text_1 = "k*ll"

    try:
        # Add a blockItem
        add_result = client.add_or_update_blocklist_items(
            blocklist_name=blocklist_name,
            options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=[TextBlocklistItem(text=block_item_text_1)]),
        )
        if not add_result or not add_result.blocklist_items or len(add_result.blocklist_items) <= 0:
            raise RuntimeError("BlockItem not created.")
        block_item_id = add_result.blocklist_items[0].blocklist_item_id

        # Remove this blockItem by blockItemId
        client.remove_blocklist_items(
            blocklist_name=blocklist_name, options=RemoveTextBlocklistItemsOptions(blocklist_item_ids=[block_item_id])
        )
        print(f"\nRemoved blockItem: {add_result.blocklist_items[0].blocklist_item_id}")
    except HttpResponseError as e:
        print("\nRemove block item failed: ")
        if e.error:
            print(f"Error code: {e.error.code}")
            print(f"Error message: {e.error.message}")
            raise
        print(e)
        raise

故障排除

一般

Azure AI 内容安全客户端库将引发在Azure Core中定义的异常。错误代码如下

错误代码 可能原因 建议
InvalidRequestBody 请求体中的字段之一或多个与API定义不匹配。 1. 检查您在API调用中指定的API版本。
2. 检查您所选的API版本的相应API定义。
InvalidResourceName 您在URL中指定的资源名称不满足要求,例如黑名单名称、黑名单术语ID等。 1. 检查您在API调用中指定的API版本。
2. 检查给定的名称是否根据API定义包含无效字符。
ResourceNotFound 您在URL中指定的资源可能不存在,例如黑名单名称。 1. 检查您在API调用中指定的API版本。
2. 请再次确认URL中指定的资源是否存在。
InternalError 在服务器端触发了某些意外情况。 1. 您可能希望在小间隔后重试几次,看看问题是否再次出现。
2. 如果问题持续存在,请联系Azure支持。
ServerBusy 服务器端无法暂时处理请求。 1. 您可能希望在小间隔后重试几次,看看问题是否再次出现。
2. 如果问题持续存在,请联系Azure支持。
TooManyRequests 当前的RPS已超过当前SKU的配额。 1. 检查定价表以了解RPS配额。
2. 如果您需要更多的QPS,请联系Azure支持。

日志记录

此库使用标准的logging库进行日志记录。

HTTP会话的基本信息(URL、标题等)以INFO级别进行日志记录。

详细的DEBUG级别日志记录,包括请求/响应体和未脱密标题,可以通过客户端或操作级别使用logging_enable关键字参数启用。

有关示例,请参阅完整的SDK日志记录文档此处

可选配置

可以在客户端和操作级别传递可选关键字参数。azure-core 参考文档描述了重试、日志记录、传输协议等可用配置。

下一步

附加文档

有关 Azure 内容安全的更详细文档,请参阅 docs.microsoft.com 上的 Azure AI 内容安全

贡献

本项目欢迎贡献和建议。大多数贡献需要您同意一份贡献者许可协议(CLA),声明您有权并且实际上确实授予我们使用您贡献的权利。有关详细信息,请访问 https://cla.microsoft.com

当您提交拉取请求时,CLA-bot 将自动确定您是否需要提供 CLA,并适当装饰 PR(例如,标签,注释)。只需遵循机器人提供的说明。您只需要在整个使用我们 CLA 的所有存储库中这样做一次。

本项目已采用 Microsoft 开源行为准则。有关更多信息,请参阅行为准则常见问题解答或联系 opencode@microsoft.com,提出任何额外的问题或评论。

项目详情


下载文件

下载适用于您的平台文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

azure-ai-contentsafety-1.0.0.tar.gz (63.8 kB 查看哈希值)

上传时间

构建分布

azure_ai_contentsafety-1.0.0-py3-none-any.whl (61.3 kB 查看哈希值)

上传时间 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面