azure-ai-contentunderstanding-py
microsoft/skills
Python용 Azure AI 콘텐츠 이해 SDK를 사용하여 문서, 이미지, 오디오 및 비디오에서 의미적 내용을 추출합니다.
...모든 것을 확장하십시오Python용 Azure AI 콘텐츠 이해 SDK
RAG 및 자동화된 워크플로를 위해 문서, 동영상, 오디오 및 이미지 파일에서 의미적 콘텐츠를 추출하는 다중 모달 AI 서비스입니다.
설치
pip install azure-ai-contentunderstanding
환경 변수
CONTENTUNDERSTANDING_ENDPOINT=https://.cognitiveservices.azure.com/ # 모든 인증 방법에 필수
AZURE_TOKEN_CREDENTIALS=prod # 프로덕션 환경에서 DefaultAzureCredential을 사용하는 경우에만 필수
인증 및 수명 주기
🔑 아래의 모든 코드 예제에는 다음 두 가지 규칙이 적용됩니다:
DefaultAzureCredential을우선적으로 사용하십시오. 코드 변경 없이 로컬(Azure CLI / VS Code / Developer CLI)과 Azure(관리형 ID, 워크로드 ID) 모두에서 작동합니다. 연결 문자열, 계정/API 키는 사용하지 마십시오. 이러한 방법은 Entra 감사 및 키 순환을 우회합니다.
- 로컬 개발:
DefaultAzureCredential은별도 설정 없이 바로 작동합니다.- 프로덕션:
AZURE_TOKEN_CREDENTIALS=prod(또는AZURE_TOKEN_CREDENTIALS=)를 설정하여 자격 증명 체인을 프로덕션 환경에서 안전한 자격 증명만 사용하도록 제한하십시오.- 모든 클라이언트를 컨텍스트 매니저로 감싸서 HTTP 전송, 소켓 및 토큰 캐시가 결정론적으로 해제되도록 하십시오:
- 동기식:
(...) as client: - 비동기:
및(...)을 클라이언트로 사용하는 async DefaultAzureCredential()을 자격 증명로 사용하는 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에서 구조화된 결과를 추출합니다
사전 구축된 분석기
| 분석기 | 콘텐츠 유형 | 목적 |
|---|---|---|
prebuilt-documentSearch |
문서 | RAG 애플리케이션을 위한 마크다운 추출 |
사전 구축된 이미지 검색 |
이미지 | 이미지에서 콘텐츠 추출 |
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"]
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()
# 마크다운 콘텐츠에 접근 (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 에서 파생됩니다.
모델 임포트
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을사용하는 경우에도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
복사





집
