azure-ai-contentunderstanding-py
microsoft/skills
Azure AI Content Understanding SDK for Python を使用して、ドキュメント、画像、音声、動画から意味的なコンテンツを抽出します。
...すべて拡張しますPython用 Azure AI コンテンツ理解 SDK
RAG や自動化されたワークフロー向けに、ドキュメント、動画、音声、画像ファイルから意味的なコンテンツを抽出するマルチモーダル AI サービス。
インストール
pip install azure-ai-contentunderstanding
環境変数
CONTENTUNDERSTANDING_ENDPOINT=https://.cognitiveservices.azure.com/ # すべての認証方法で必要
AZURE_TOKEN_CREDENTIALS=prod # 本番環境で DefaultAzureCredential を使用する場合にのみ必要
認証とライフサイクル
🔑 以下のすべてのコードサンプルには、2つのルールが適用されます:
DefaultAzureCredential を優先してください。コードを変更することなく、ローカル(Azure CLI / VS Code / Developer CLI)および Azure(マネージド ID、ワークロード ID)で動作します。接続文字列やアカウント/API キーの使用は避けてください。これらは Entra の監査およびローテーションの対象外となります。
- ローカル開発:
DefaultAzureCredentialはそのまま使用可能です。- 本番環境:
AZURE_TOKEN_CREDENTIALS=prod(またはAZURE_TOKEN_CREDENTIALS=)を設定し、資格情報のチェーンを本番環境に適した資格情報に制限してください。- すべてのクライアントをコンテキストマネージャーでラップし、HTTPトランスポート、ソケット、トークンキャッシュが確定的に解放されるようにします:
- 同期:
(...) as client: - 非同期:
`async with` および(...) as client: `async with DefaultAzureCredential() as credential:` (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から構造化された結果を抽出します
事前構築済みアナライザー
| アナライザー | コンテンツタイプ | 目的 |
|---|---|---|
prebuilt-documentSearch |
ドキュメント | RAGアプリケーション向けのMarkdownを抽出する |
prebuilt-imageSearch |
画像 | 画像からコンテンツを抽出 |
prebuilt-audioSearch |
音声 | タイミング情報を付加して音声を文字起こしする |
prebuilt-videoSearch |
動画 | フレーム、文字起こし、要約の抽出 |
prebuilt-invoice |
Documents | 請求書のフィールドを抽出 |
ドキュメントの分析
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 # 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()
# 動画コンテンツにアクセス (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を継承しています。
モデルのインポート
from azure.ai.contentunderstanding.models import (
AnalyzeInput,
AnalyzeResult,
MediaContentKind,
DocumentContent,
AudioVisualContent,
)
クライアントの種類
| クライアント | 目的 |
|---|---|
ContentUnderstandingClient |
すべての操作に対応する同期クライアント |
ContentUnderstandingClient(aio) |
すべての操作に対応した非同期クライアント |
ベストプラクティス
- 同期または非同期のいずれかを選択し、一貫性を保ってください。同じ呼び出しパス内で、
azure.ai.contentunderstandingの同期クライアントとazure.ai.contentunderstanding.aioの非同期クライアントを混在させないでください。モジュールごとに 1 つのモードを選択してください。 - クライアントおよび非同期認証情報には、常にコンテキストマネージャーを使用してください。すべてのクライアントを
、(同期) の場合は ContentUnderstandingClient(...) as client:(sync)、(非同期) の場合は ContentUnderstandingClient(...) as client:(async)でラップしてください。azure.identity.aioの async 版DefaultAzureCredentialを使用する場合は、credential: とともに asyncを使用してください。これにより、トークンとトランスポートが適切にクリーンアップされます。 -
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
コピー





家
