mcpField
A
azure-ai-contentunderstanding-py

azure-ai-contentunderstanding-py

github.com/sickn33数据与数据库48.7k69 次安装今天更新
代码仓库

关于 azure-ai-contentunderstanding-py

azure-ai-contentunderstanding-py 是用于从文档、图像、音频和视频中提取结构化语义内容的 Python SDK 技能,提供预置分析器和自定义字段架构,适用于 RAG 与自动化工作流。

主要功能

  1. 01分析文档、图像、音频和视频
  2. 02使用预置内容分析器
  3. 03定义自定义提取架构
  4. 04运行同步或异步分析

适用场景

  1. 01提取文档内容用于 RAG
  2. 02转录音频并标注时间
  3. 03获取视频帧和摘要
  4. 04提取发票字段

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-ai-contentunderstanding-py

安装后在 Claude Code 中输入/azure-ai-contentunderstanding-py确认已加载。

详细介绍

Python 版 Azure AI Content Understanding SDK

多模态 AI 服务,可从文档、视频、音频和图像文件中提取语义内容,用于 RAG 和自动化工作流。

安装

pip install azure-ai-contentunderstanding

环境变量

CONTENTUNDERSTANDING_ENDPOINT=https://<resource>.cognitiveservices.azure.com/

身份验证

import os
from azure.ai.contentunderstanding import ContentUnderstandingClient
from azure.identity import DefaultAzureCredential

endpoint = os.environ["CONTENTUNDERSTANDING_ENDPOINT"]
credential = DefaultAzureCredential()
client = ContentUnderstandingClient(endpoint=endpoint, credential=credential)

核心工作流

Content Understanding 操作是异步长时间运行的操作:

  1. 开始分析 — 使用 begin_analyze() 启动分析操作(返回一个轮询器)
  2. 轮询结果 — 持续轮询,直到分析完成(SDK 通过 .result() 处理此操作)
  3. 处理结果 — 从 AnalyzeResult.contents 中提取结构化结果

预构建分析器

分析器内容类型用途
prebuilt-documentSearch文档提取 Markdown,供 RAG 应用使用
prebuilt-imageSearch图像从图像中提取内容
prebuilt-audioSearch音频转录音频并提供时间信息
prebuilt-videoSearch视频提取帧、转录文本和摘要
prebuilt-invoice文档提取发票字段

分析文档

import os
from azure.ai.contentunderstanding import ContentUnderstandingClient
from azure.ai.contentunderstanding.models import AnalyzeInput
from azure.identity import DefaultAzureCredential

endpoint = os.environ["CONTENTUNDERSTANDING_ENDPOINT"]
client = ContentUnderstandingClient(
    endpoint=endpoint,
    credential=DefaultAzureCredential()
)

# Analyze document from URL
poller = client.begin_analyze(
    analyzer_id="prebuilt-documentSearch",
    inputs=[AnalyzeInput(url="https://example.com/document.pdf")]
)

result = poller.result()

# Access markdown content (contents is a list)
content = result.contents[0]
print(content.markdown)

访问文档内容详情

from azure.ai.contentunderstanding.models import MediaContentKind, DocumentContent

content = result.contents[0]
if content.kind == MediaContentKind.DOCUMENT:
    document_content: DocumentContent = content  # type: ignore
    print(document_content.start_page_number)

分析图像

from azure.ai.contentunderstanding.models import AnalyzeInput

poller = client.begin_analyze(
    analyzer_id="prebuilt-imageSearch",
    inputs=[AnalyzeInput(url="https://example.com/image.jpg")]
)
result = poller.result()
content = result.contents[0]
print(content.markdown)

分析视频

from azure.ai.contentunderstanding.models import AnalyzeInput

poller = client.begin_analyze(
    analyzer_id="prebuilt-videoSearch",
    inputs=[AnalyzeInput(url="https://example.com/video.mp4")]
)

result = poller.result()

# Access video content (AudioVisualContent)
content = result.contents[0]

# Get transcript phrases with timing
for phrase in content.transcript_phrases:
    print(f"[{phrase.start_time} - {phrase.end_time}]: {phrase.text}")

# Get key frames (for video)
for frame in content.key_frames:
    print(f"Frame at {frame.time}: {frame.description}")

分析音频

from azure.ai.contentunderstanding.models import AnalyzeInput

poller = client.begin_analyze(
    analyzer_id="prebuilt-audioSearch",
    inputs=[AnalyzeInput(url="https://example.com/audio.mp3")]
)

result = poller.result()

# Access audio transcript
content = result.contents[0]
for phrase in content.transcript_phrases:
    print(f"[{phrase.start_time}] {phrase.text}")

自定义分析器

使用字段架构创建自定义分析器,以执行专门的提取:

# Create custom analyzer
analyzer = client.create_analyzer(
    analyzer_id="my-invoice-analyzer",
    analyzer={
        "description": "Custom invoice analyzer",
        "base_analyzer_id": "prebuilt-documentSearch",
        "field_schema": {
            "fields": {
                "vendor_name": {"type": "string"},
                "invoice_total": {"type": "number"},
                "line_items": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "description": {"type": "string"},
                            "amount": {"type": "number"}
                        }
                    }
                }
            }
        }
    }
)

# Use custom analyzer
from azure.ai.contentunderstanding.models import AnalyzeInput

poller = client.begin_analyze(
    analyzer_id="my-invoice-analyzer",
    inputs=[AnalyzeInput(url="https://example.com/invoice.pdf")]
)

result = poller.result()

# Access extracted fields
for content in result.contents or []:
    fields = content.fields or {}
    print(fields.get("vendor_name"))
    print(fields.get("invoice_total"))

分析器管理

# List all analyzers
analyzers = client.list_analyzers()
for analyzer in analyzers:
    print(f"{analyzer.analyzer_id}: {analyzer.description}")

# Get specific analyzer
analyzer = client.get_analyzer("prebuilt-documentSearch")

# Delete custom analyzer
client.delete_analyzer("my-custom-analyzer")

异步客户端

import asyncio
import os
from azure.ai.contentunderstanding.aio import ContentUnderstandingClient
from azure.ai.contentunderstanding.models import AnalyzeInput
from azure.identity.aio import DefaultAzureCredential

async def analyze_document():
    endpoint = os.environ["CONTENTUNDERSTANDING_ENDPOINT"]
    credential = DefaultAzureCredential()
    
    async with ContentUnderstandingClient(
        endpoint=endpoint,
        credential=credential
    ) as client:
        poller = await client.begin_analyze(
            analyzer_id="prebuilt-documentSearch",
            inputs=[AnalyzeInput(url="https://example.com/doc.pdf")]
        )
        result = await poller.result()
        content = result.contents[0]
        return content.markdown

asyncio.run(analyze_document())

内容类型

类用途提供内容
DocumentContentPDF、图像、Office 文档页面、表格、图表、段落
AudioVisualContent音频、视频文件转录短语、时间信息、关键帧

两者都继承自 MediaContent,后者提供基本信息和 Markdown 表示形式。

模型导入

from azure.ai.contentunderstanding.models import (
    AnalyzeInput,
    AnalyzeResult,
    MediaContentKind,
    DocumentContent,
    AudioVisualContent,
)

客户端类型

客户端用途
ContentUnderstandingClient用于所有操作的同步客户端
ContentUnderstandingClient (aio)用于所有操作的异步客户端

最佳实践

  1. 将 begin_analyze 与 AnalyzeInput 搭配使用 — 这是正确的方法签名
  2. 通过 result.contents[0] 访问结果 — 结果以列表形式返回
  3. 常见场景使用预构建分析器(文档/图像/音频/视频搜索)
  4. 仅针对特定领域的字段提取创建自定义分析器
  5. 高吞吐量场景使用异步客户端,并搭配 azure.identity.aio 凭据
  6. 处理长时间运行的操作 — 视频/音频分析可能需要数分钟
  7. 尽可能使用 URL 源,以避免上传开销

适用场景

当需要执行概述中描述的工作流或操作时,可使用此技能。

限制

  • 仅当任务明确符合上述范围时,才使用此技能。
  • 不要将输出视为环境特定验证、测试或专家审查的替代品。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请暂停并请求澄清。

SDK/服务版本各不相同:请根据固定的程序包版本验证分析器架构和结果字段;索引前检查 contents 是否为空,使用前检查提取的字段是否缺失。这些只是代码片段,并非完整的分析器生命周期。请使用上下文管理器关闭异步客户端和凭据,限制轮询时长并报告失败。文档/音频/视频会离开本地环境;传输敏感内容前请先获得授权,对提取的字段进行脱敏,并在用于财务/法律决策前验证输出。请参阅官方 SDK 指南。

评论

支持 Markdown