azure-ai-contentunderstanding-py
microsoft/skills
使用 Azure AI 內容理解 SDK(Python 版)從文件、圖片、音訊和影片中擷取語義內容。
...展開全部Azure AI 內容理解 SDK(Python 版)
一種多模態 AI 服務,可從文件、影片、音訊及影像檔案中萃取語義內容,以供 RAG 及自動化工作流程使用。
安裝
pip install azure-ai-contentunderstanding
環境變數
CONTENTUNDERSTANDING_ENDPOINT=https://.cognitiveservices.azure.com/ # 所有驗證方法皆需此設定
AZURE_TOKEN_CREDENTIALS=prod # 僅在生產環境中使用 DefaultAzureCredential 時才需此設定
驗證與生命週期
🔑 以下每個程式碼範例均適用以下兩項規則:
- 優先使用
DefaultAzureCredential。它可在本地端(Azure CLI / VS Code / 開發人員 CLI)及 Azure 環境(託管身分識別、工作負載身分識別)中運作,無需修改程式碼。請避免使用連線字串、帳戶/API 金鑰——這些會繞過 Entra 稽核與金鑰輪替機制。
- 本地開發:
DefaultAzureCredential可直接使用。- 生產環境:設定
AZURE_TOKEN_CREDENTIALS=prod(或AZURE_TOKEN_CREDENTIALS=),以將憑證鏈限制為符合生產環境安全標準的憑證。- 將每個客戶端封裝在上下文管理器中,以確保 HTTP 傳輸、套接字和令牌快取能以可預測的方式釋放:
- 同步模式:
使用 ``(...) as client: - 非同步:
使用 `,以及(...)` 作為 `client` 的 `async` 方法 使用 `DefaultAzureCredential()` 作為 `credential` 的 `async` 方法:(來自azure.identity.aio)程式碼片段可能簡化此設定,但生產環境的程式碼應始終遵循這兩項規則。
import os
from azure.ai.contentunderstanding import ContentUnderstandingClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
endpoint = os.environ["CONTENTUNDERSTANDING_ENDPOINT"]
# 本地開發環境:使用 DefaultAzureCredential。生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# 或者在生產環境中直接使用特定憑證:
# 請參閱 https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
with ContentUnderstandingClient(endpoint=endpoint, credential=credential) as client:
analyzers = list(client.list_analyzers())
核心工作流程
內容理解操作屬於非同步且長時間執行的操作:
- 開始分析— 透過
begin_analyze()啟動分析操作(回傳一個輪詢器) - 輪詢結果— 持續輪詢直至分析完成(SDK 透過
.result()處理此步驟) - 處理結果— 從 `
AnalyzeResult.contents` 擷取結構化結果
預建分析器
| 分析器 | 內容類型 | 用途 |
|---|---|---|
預建文件搜尋 |
文件 | 為 RAG 應用程式提取 Markdown 內容 |
預建式圖像搜尋 |
圖片 | 從圖片中擷取內容 |
預建式音訊搜尋 |
音訊 | 帶時間標記的音訊轉錄 |
預建影片搜尋 |
影片 | 擷取畫面、文字稿及摘要 |
預建發票 |
文件 | 擷取發票欄位 |
分析文件
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"]
with ContentUnderstandingClient(
endpoint=endpoint,
credential=DefaultAzureCredential()
) as client:
# 根據 URL 分析文件
poller = client.begin_analyze(
analyzer_id="prebuilt-documentSearch",
inputs=[AnalyzeInput(url="https://example.com/document.pdf")]
)
result = poller.result()
# 存取 Markdown 內容(contents 為一個清單)
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 # 類型:忽略
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()
# 存取影片內容 (AudioVisualContent)
content = result.contents[0]
# 取得帶有時間標記的轉錄片段
for phrase in content.transcript_phrases:
print(f"[{phrase.start_time} - {phrase.end_time}]: {phrase.text}")
# 取得關鍵幀(適用於影片)
for frame in content.key_frames:
print(f"幀時間為 {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()
# 取得音訊文字紀錄
content = result.contents[0]
for phrase in content.transcript_phrases:
print(f"[{phrase.start_time}] {phrase.text}")
自訂分析器
建立帶有欄位結構的自訂分析器,以進行專項資料擷取:
# 建立自訂分析器
analyzer = client.create_analyzer(
analyzer_id="my-invoice-analyzer",
analyzer={
"description": "自訂發票分析器",
"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"}
}
}
}
}
}
}
)
# 使用自訂分析器
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()
# 存取擷取的欄位
print(result.fields["vendor_name"])
print(result.fields["invoice_total"])
分析器管理
# 列出所有分析器
analyzers = client.list_analyzers()
for analyzer in analyzers:
print(f"{analyzer.analyzer_id}: {analyzer.description}")
# 取得特定分析器
analyzer = client.get_analyzer("prebuilt-documentSearch")
# 刪除自訂分析器
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"]
async with DefaultAzureCredential() as credential:
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())
內容類型
| 類別 | 適用於 | 提供 |
|---|---|---|
DocumentContent |
PDF、圖片、Office 文件 | 頁面、表格、圖表、段落 |
影音內容 |
音訊、影片檔案 | 字幕短語、時間碼、關鍵幀 |
兩者均繼承自MediaContent,該類別提供基本資訊與 Markdown 表示形式。
模型匯入
from azure.ai.contentunderstanding.models import (
AnalyzeInput,
AnalyzeResult,
MediaContentKind,
DocumentContent,
AudioVisualContent,
)
客戶端類型
| 客戶端 | 用途 |
|---|---|
ContentUnderstandingClient |
適用於所有操作的同步客戶端 |
ContentUnderstandingClient(aio) |
適用於所有操作的非同步客戶端 |
最佳實務
- 請選擇同步或非同步模式,並保持一致。請勿在同一個呼叫路徑中混合使用
azure.ai.contentunderstanding同步客戶端與azure.ai.contentunderstanding.aio非同步客戶端。每個模組應選擇一種模式。 - 請務必為客戶端和非同步憑證使用上下文管理器。將每個客戶端封裝
為 `ContentUnderstandingClient(...) as client:(sync)`(同步模式)或`ContentUnderstandingClient(...) as client:(async)`(非同步模式)。 對於來自azure.identity.aio的非同步DefaultAzureCredential,也請搭配 async 模式並使用credential:,以便妥善清理憑證和傳輸資料。 - 請搭配
AnalyzeInput使用begin_analyze— 這是正確的方法簽名 - 透過
result.contents[0]存取結果— 結果以清單形式傳回 - 針對常見情境(文件/圖片/音訊/影片搜尋)請使用預建分析器
- 僅在需要進行特定領域的欄位擷取時,才建立自訂分析器
- 在需要高吞吐量的情境中,請搭配
azure.identity.aio憑證使用非同步客戶端 - 處理長時間運行的操作— 影片/音訊分析可能需要數分鐘
- 在可行時使用 URL 來源,以避免上傳開銷
---
name: azure-ai-contentunderstanding-py
description: Extract semantic content from documents, images, audio, and video using Azure AI Content Understanding SDK for Python.
license: MIT
---
# Azure AI Content Understanding SDK for Python
Multimodal AI service that extracts semantic content from documents, video, audio, and image files for RAG and automated workflows.
## Installation
```bash
pip install azure-ai-contentunderstanding
```
## Environment Variables
```bash
CONTENTUNDERSTANDING_ENDPOINT=https://<resource>.cognitiveservices.azure.com/ # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
```python
import os
from azure.ai.contentunderstanding import ContentUnderstandingClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
endpoint = os.environ["CONTENTUNDERSTANDING_ENDPOINT"]
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
with ContentUnderstandingClient(endpoint=endpoint, credential=credential) as client:
analyzers = list(client.list_analyzers())
```
## Core Workflow
Content Understanding operations are asynchronous long-running operations:
1. **Begin Analysis** — Start the analysis operation with `begin_analyze()` (returns a poller)
2. **Poll for Results** — Poll until analysis completes (SDK handles this with `.result()`)
3. **Process Results** — Extract structured results from `AnalyzeResult.contents`
## Prebuilt Analyzers
| Analyzer | Content Type | Purpose |
|----------|--------------|---------|
| `prebuilt-documentSearch` | Documents | Extract markdown for RAG applications |
| `prebuilt-imageSearch` | Images | Extract content from images |
| `prebuilt-audioSearch` | Audio | Transcribe audio with timing |
| `prebuilt-videoSearch` | Video | Extract frames, transcripts, summaries |
| `prebuilt-invoice` | Documents | Extract invoice fields |
## Analyze Document
```python
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"]
with ContentUnderstandingClient(
endpoint=endpoint,
credential=DefaultAzureCredential()
) as client:
# 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)
```
## Access Document Content Details
```python
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)
```
## Analyze Image
```python
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)
```
## Analyze Video
```python
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}")
```
## Analyze Audio
```python
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}")
```
## Custom Analyzers
Create custom analyzers with field schemas for specialized extraction:
```python
# 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
print(result.fields["vendor_name"])
print(result.fields["invoice_total"])
```
## Analyzer Management
```python
# 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")
```
## Async Client
```python
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"]
async with DefaultAzureCredential() as credential:
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())
```
## Content Types
| Class | For | Provides |
|-------|-----|----------|
| `DocumentContent` | PDF, images, Office docs | Pages, tables, figures, paragraphs |
| `AudioVisualContent` | Audio, video files | Transcript phrases, timing, key frames |
Both derive from `MediaContent` which provides basic info and markdown representation.
## Model Imports
```python
from azure.ai.contentunderstanding.models import (
AnalyzeInput,
AnalyzeResult,
MediaContentKind,
DocumentContent,
AudioVisualContent,
)
```
## Client Types
| Client | Purpose |
|--------|---------|
| `ContentUnderstandingClient` | Sync client for all operations |
| `ContentUnderstandingClient` (aio) | Async client for all operations |
## Best Practices
1. **Pick sync OR async and stay consistent.** Do not mix `azure.ai.contentunderstanding` sync clients with `azure.ai.contentunderstanding.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with ContentUnderstandingClient(...) as client:` (sync) or `async with ContentUnderstandingClient(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use `begin_analyze` with `AnalyzeInput`** — this is the correct method signature
4. **Access results via `result.contents[0]`** — results are returned as a list
5. **Use prebuilt analyzers** for common scenarios (document/image/audio/video search)
6. **Create custom analyzers** only for domain-specific field extraction
7. **Use async client** for high-throughput scenarios with `azure.identity.aio` credentials
8. **Handle long-running operations** — video/audio analysis can take minutes
9. **Use URL sources** when possible to avoid upload overhead
所有檔案
1 個檔案安裝 azure-ai-contentunderstanding-py
請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-ai-contentunderstanding-py # Copy SKILL.md to your .claude/skills/ directory
複製





首頁
