option
MaisonMaison Skill Science des données et ML azure-ai-contentunderstanding-py

azure-ai-contentunderstanding-py

microsoft/skills microsoft/skills

Extrayez le contenu sémantique de documents, d'images, de fichiers audio et de vidéos à l'aide du SDK Azure AI Content Understanding pour Python.

...Développer tout
0
Heure mise à jour 16 septembre 2026

SDK Azure AI Content Understanding pour Python

Service d’IA multimodale qui extrait le contenu sémantique de documents, de fichiers vidéo, audio et d’images à des fins de RAG et de workflows automatisés.

Installation

pip install azure-ai-contentunderstanding

Variables d'environnement

CONTENTUNDERSTANDING_ENDPOINT=https://.cognitiveservices.azure.com/  # Requis pour toutes les méthodes d’authentification
AZURE_TOKEN_CREDENTIALS=prod # Requis uniquement si DefaultAzureCredential est utilisé en production

Authentification et cycle de vie

🔑 Deux règles s’appliquent à tous les exemples de code ci-dessous :

  1. Privilégiez DefaultAzureCredential. Il fonctionne en local (Azure CLI / VS Code / Developer CLI) et dans Azure (identité gérée, identité de charge de travail) sans modification du code. Évitez les chaînes de connexion, les identifiants de compte et les clés API : ils contournent l'audit et la rotation Entra.
    • Développement local : DefaultAzureCredential fonctionne tel quel.
    • Production : définissez AZURE_TOKEN_CREDENTIALS=prod (ou AZURE_TOKEN_CREDENTIALS=) pour limiter la chaîne d’identifiants à des identifiants sécurisés pour la production.
  2. Enveloppez chaque client dans un gestionnaire de contexte afin que les transports HTTP, les sockets et les caches de jetons soient libérés de manière déterministe :
    • Synchrone : avec (...) comme client :
    • Asynchrone : async avec (...) comme client : et async avec DefaultAzureCredential() comme identifiant : (de azure.identity.aio)

Les extraits de code peuvent simplifier cette configuration, mais le code de production doit toujours respecter ces deux règles.

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

endpoint = os.environ["CONTENTUNDERSTANDING_ENDPOINT"]
# Développement local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# Ou utilisez directement des identifiants spécifiques en production :
# Voir 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())

Workflow principal

Les opérations de Content Understanding sont des opérations asynchrones de longue durée :

  1. Lancer l’analyse — Lancez l’opération d’analyse avec begin_analyze() (renvoie un poller)
  2. Interroger les résultats — Interroger jusqu’à ce que l’analyse soit terminée (le SDK gère cette étape via .result())
  3. Traitement des résultats — Extraire les résultats structurés à partir de ` AnalyzeResult.contents`

Analyseurs prédéfinis

Analyseur Type de contenu Objectif
prebuilt-documentSearch Documents Extraction de Markdown pour les applications RAG
prebuilt-imageSearch Images Extraction de contenu à partir d'images
prebuilt-audioSearch Audio Transcrire l'audio avec synchronisation
prebuilt-videoSearch Vidéo Extraire des images, des transcriptions, des résumés
prebuilt-invoice Documents Extraire les champs des factures

Analyser un document

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:
    # Analyser un document à partir d’une URL
    poller = client.begin_analyze(
        analyzer_id="prebuilt-documentSearch",
        inputs=[AnalyzeInput(url="https://example.com/document.pdf")]
    )

    result = poller.result()

    # Accéder au contenu Markdown (contents est une liste)
    content = result.contents[0]
    print(content.markdown)

Accéder aux détails du contenu du document

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)

Analyser une image

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)

Analyser une vidéo

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()

# Accéder au contenu vidéo (AudioVisualContent)
content = result.contents[0]

# Récupérer les phrases de la transcription avec leur durée
for phrase in content.transcript_phrases:
    print(f"[{phrase.start_time} - {phrase.end_time}]: {phrase.text}")

# Récupérer les images clés (pour la vidéo)
for frame in content.key_frames:
    print(f"Image à {frame.time} : {frame.description}")

Analyser l'audio

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()

# Accéder à la transcription audio
content = result.contents[0]
for phrase in content.transcript_phrases:
    print(f"[{phrase.start_time}] {phrase.text}")

Analyseurs personnalisés

Créez des analyseurs personnalisés avec des schémas de champs pour une extraction spécialisée :

# Créer un analyseur personnalisé
analyzer = client.create_analyzer(
    analyzer_id="my-invoice-analyzer",
    analyzer={
        "description": "Analyseur de factures personnalisé",
        "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": "chaîne"},
                            "amount": {"type": "nombre"}
                        }
                    }
                }
            }
        }
    }
)

# Utilisation d’un analyseur personnalisé
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()

# Accéder aux champs extraits
print(result.fields["vendor_name"])
print(result.fields["invoice_total"])

Gestion des analyseurs

# Liste de tous les analyseurs
analyzers = client.list_analyzers()
for analyzer in analyzers:
    print(f"{analyzer.analyzer_id}: {analyzer.description}")

# Récupérer un analyseur spécifique
analyzer = client.get_analyzer("prebuilt-documentSearch")

# Supprimer un analyseur personnalisé
client.delete_analyzer("my-custom-analyzer")

Client asynchrone

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())

Types de contenu

Classe Pour Fournit
DocumentContent PDF, images, documents Office Pages, tableaux, figures, paragraphes
Contenu audiovisuel Fichiers audio et vidéo Transcription, phrases, timing, images clés

Les deux dérivent de MediaContent, qui fournit des informations de base et une représentation au format Markdown.

Importations de modèles

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

Types de clients

Client Objectif
ContentUnderstandingClient Client de synchronisation pour toutes les opérations
Client ContentUnderstanding (aio) Client asynchrone pour toutes les opérations

Meilleures pratiques

  1. Optez pour le mode synchrone OU asynchrone et restez cohérent. Ne mélangez pas les clients synchrones azure.ai.contentunderstanding avec les clients asynchrones azure.ai.contentunderstanding.aio dans le même chemin d'appel. Choisissez un seul mode par module.
  2. Utilisez toujours des gestionnaires de contexte pour les clients et les informations d’identification asynchrones. Enveloppez chaque client avec ContentUnderstandingClient(...) en spécifiant client: (synchrone) ou async avec ContentUnderstandingClient(...) en spécifiant client: (asynchrone). Pour les informations d’identification asynchrones DefaultAzureCredential issues de azure.identity.aio, utilisez également le mode asynchrone avec credential : afin que les jetons et les transports soient nettoyés.
  3. Utilisez ` begin_analyze `avec ` AnalyzeInput ` — il s’agit de la signature de méthode correcte
  4. Accédez aux résultats via result.contents[0] — les résultats sont renvoyés sous forme de liste
  5. Utilisez des analyseurs prédéfinis pour les scénarios courants (recherche dans des documents, des images, des fichiers audio ou vidéo)
  6. Créez des analyseurs personnalisés uniquement pour l’extraction de champs spécifiques à un domaine
  7. Utilisez le client asynchrone pour les scénarios à haut débit avec les informations d’identification azure.identity.aio
  8. Gérez les opérations de longue durée — l’analyse vidéo/audio peut prendre plusieurs minutes
  9. Utilisez des sources URL lorsque cela est possible pour éviter la surcharge liée au téléchargement
Voir sur GitHub
---
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

Tous les fichiers

1 fichiers

Installer azure-ai-contentunderstanding-py

Téléchargez et décompressez les fichiers de compétences dans votre répertoire .claude/skills/.

Télécharger le ZIP

Clonez le dépôt et copiez les fichiers de compétence dans votre projet.

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

Copier Copier
Configuration rapide: Copiez le dossier de la compétence dans .claude/skills/ Claude détectera automatiquement la compétence et l'utilisera

Compétences similaires

web-search
Heure mise à jour 29 juin 2026
webapp-testing
Heure mise à jour 29 juin 2026
agentmail
Heure mise à jour 29 juin 2026
lark-base
Heure mise à jour 5 juillet 2026
OR