Démarrage rapide : Utiliser Azure Content Understanding dans Les outils Foundry

Ce guide de démarrage rapide vous montre comment utiliser l’API REST Content Understanding pour obtenir des données structurées à partir de contenu modal dans des fichiers document, image, audio et vidéo.

Conditions préalables

  • Un abonnement actif Azure. Si vous n'avez pas de compte Azure, créez-en un gratuitement.
  • Ressource Microsoft Foundry créée dans une région prise en charge. Pour créer la ressource, vous avez besoin du rôle Contributeur ou supérieur sur l’abonnement ou le groupe de ressources cible.
  • Configurez les déploiements de modèles par défaut pour votre ressource Content Understanding. En définissant les valeurs par défaut, vous créez une connexion aux modèles Microsoft Foundry que vous utilisez pour les requêtes Content Understanding. Choisissez l’une des méthodes suivantes :
    1. Accédez à la page des paramètres Content Understanding.

    2. Sélectionnez le bouton + Ajouter une ressource en haut à gauche.

    3. Sélectionnez la ressource Foundry que vous souhaitez utiliser et sélectionnez Suivant>Enregistrer.

      Vérifiez que la case Activer le redéploiement automatique pour les modèles requis si aucune case par défaut n’est disponible est activée. Cette sélection garantit que votre ressource est entièrement configurée avec les modèles requis GPT-4.1, GPT-4.1-mini, et text-embedding-3-large. Différents analyseurs prédéfinis nécessitent différents modèles.

    En effectuant ces étapes, vous configurez une connexion entre les modèles Content Understanding et Foundry dans votre ressource Foundry.
  • cURL installé pour votre environnement de développement.

Mise en route d’un analyseur prédéfini

Ce guide de démarrage rapide utilise des analyseurs prédéfinis : aucune configuration n’est requise. Pour savoir comment personnaliser des analyseurs pour vos besoins, consultez les analyseurs prédéfinis.

Envoyer un fichier à des fins d’analyse

Avant d’exécuter la commande cURL suivante, apportez les modifications suivantes à la requête HTTP :

  • Remplacez {endpoint} et {key} par les valeurs correspondantes de votre instance Foundry dans le portail Azure.

Requête POST

Cet exemple utilise l’analyseur prebuilt-invoice pour extraire des données structurées à partir d’un document de facture.

curl -i -X POST "{endpoint}/contentunderstanding/analyzers/prebuilt-invoice:analyze?api-version=2025-11-01" \
  -H "Ocp-Apim-Subscription-Key: {key}" \
  -H "Content-Type: application/json" \
  -d '{
        "inputs":[{"url": "https://github.com/Azure-Samples/azure-ai-content-understanding-python/raw/refs/heads/main/data/invoice.pdf"}]
      }'  

Référence : Analyseurs de contenu - Analyser

Réponse POST

L’en-tête de réponse inclut un Operation-Location champ que vous utilisez pour récupérer les résultats de l’opération d’analyse asynchrone.

HTTP/1.1 202 Accepted
Transfer-Encoding: chunked
Content-Type: application/json
request-id: aaa-bbb-ccc-ddd
x-ms-request-id: aaa-bbb-ccc-ddd
Operation-Location: {endpoint}/contentunderstanding/analyzerResults/{request-id}?api-version=2025-11-01
api-supported-versions: 2024-12-01-preview,2025-05-01-preview,2025-11-01
x-envoy-upstream-service-time: 800
apim-request-id: {request-id}
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
x-content-type-options: nosniff
x-ms-region: West US
Date: Fri, 31 Oct 2025 05:30:17 GMT
Connection: close

Important

Copiez l’URL d’emplacement de l’opération à partir de l’en-tête de réponse. Vous allez utiliser cette URL à l’étape suivante pour récupérer les résultats de l’analyse.

Obtenir le résultat d’analyse

Utilisez la Operation-LocationPOST réponse et obtenez le résultat de l'analyse. Une réponse réussie renvoie status: "Succeeded" avec des champs extraits dans l’objet result.

Requête GET

curl -i -X GET "{endpoint}/contentunderstanding/analyzerResults/{request-id}?api-version=2025-11-01" \
  -H "Ocp-Apim-Subscription-Key: {key}"

Référence : Résultats de l’analyseur - Obtenir

Réponse GET

La réponse JSON 200 (OK) inclut un status champ. Si l’opération n’est pas terminée, status est Running ou NotStarted. Interrogez l’URL toutes les secondes ou deux jusqu’à ce que status soit Succeeded.

{
  "id": "ce05fb5a-579e-4f0b-afb5-3532bcddeaee",
  "status": "Succeeded",
  "result": {
    "analyzerId": "prebuilt-invoice",
    "apiVersion": "2025-11-01",
    "createdAt": "2025-11-13T20:04:55Z",
    "warnings": [],
    "contents": [
      {
        "path": "input1",
        "markdown": "CONTOSO LTD.\n\n\n# INVOICE\n\nContoso Headquarters\n123 456th St\nNew York, NY, 10001\n\nINVOICE: INV-100\n\nINVOICE DATE: 11/15/2019\n\nDUE DATE: 12/15/2019\n\nCUSTOMER NAME: MICROSOFT CORPORATION...",
        "fields": {
          "AmountDue": {
            "type": "object",
            "valueObject": {
              "Amount": {
                "type": "number",
                "valueNumber": 610,
                "spans": [
                  {
                    "offset": 1522,
                    "length": 7
                  }
                ],
                "confidence": 0.773,
                "source": "D(1,7.3628,8.0459,7.9272,8.0459,7.9272,8.2070,7.3628,8.2070)"
              },
              "CurrencyCode": {
                "type": "string",
                "valueString": "USD"
              }
            }
          },
          "BalanceForward": {
            "type": "object",
            "valueObject": {
              "Amount": {
                "type": "number",
                "valueNumber": 500,
                "spans": [
                  {
                    "offset": 1474,
                    "length": 7
                  }
                ],
                "confidence": 0.901,
                "source": "D(1,7.3628,7.7445,7.9278,7.7467,7.9272,7.9092,7.3622,7.9070)"
              },
              "CurrencyCode": {
                "type": "string",
                "valueString": "USD"
              }
            }
          },
          "BillingAddress": {
            "type": "string",
            "valueString": "123 Bill St, Redmond WA, 98052",
            "spans": [
              {
                "offset": 325,
                "length": 12
              },
              "..."
            ],
            "confidence": 0.712,
            "source": "D(1,0.5805,3.9471,1.2858,3.9478,1.2856,4.1115,0.5803,4.1108);..."
          },
          "BillingAddressRecipient": {
            "type": "string",
            "valueString": "Microsoft Finance",
            "spans": [
              {
                "offset": 307,
                "length": 17
              }
            ],
            "confidence": 0.815,
            "source": "D(1,0.5734,3.7392,1.8060,3.7521,1.8043,3.9201,0.5717,3.9072)"
          },
          "CountryRegion": {
            "type": "string",
            "valueString": "USA"
          },
          "CustomerAddress": {
            "type": "string",
            "valueString": "123 Other St, Redmond WA, 98052",
            "spans": [
              "..."
            ],
            "confidence": 0.744,
            "source": "..."
          },
          "CustomerAddressRecipient": {
            "type": "string",
            "valueString": "Microsoft Corp",
            "spans": [
              "..."
            ],
            "confidence": 0.437,
            "source": "..."
          },
          "CustomerId": {
            "type": "string",
            "valueString": "CID-12345",
            "spans": [
              "..."
            ],
            "confidence": 0.936,
            "source": "..."
          },
          "CustomerName": {
            "type": "string",
            "valueString": "MICROSOFT CORPORATION",
            "spans": [
              "..."
            ],
            "confidence": 0.46,
            "source": "..."
          },
          "CustomerTaxId": {
            "type": "string",
            "confidence": 0.912
          },
          "DueDate": {
            "type": "date",
            "valueDate": "2019-12-15",
            "spans": [
              "..."
            ],
            "confidence": 0.97,
            "source": "..."
          },
          "InvoiceDate": {
            "type": "date",
            "valueDate": "2019-11-15",
            "spans": [
              "..."
            ],
            "confidence": 0.939,
            "source": "..."
          },
          "InvoiceId": {
            "type": "string",
            "valueString": "INV-100",
            "spans": [
              "..."
            ],
            "confidence": 0.733,
            "source": "..."
          },
          "LineItems": {
            "type": "array",
            "valueArray": [
              {
                "type": "object",
                "valueObject": {
                  "Date": {
                    "type": "date",
                    "valueDate": "2021-03-04",
                    "spans": [
                      "..."
                    ],
                    "confidence": 0.894,
                    "source": "..."
                  },
                  "Description": {
                    "type": "string",
                    "valueString": "Consulting Services",
                    "spans": [
                      "..."
                    ],
                    "confidence": 0.589,
                    "source": "..."
                  },
                  "ProductCode": {
                    "type": "string",
                    "valueString": "A123",
                    "spans": [
                      "..."
                    ],
                    "confidence": 0.879,
                    "source": "..."
                  },
                  "Quantity": {
                    "type": "number",
                    "valueNumber": 2,
                    "spans": [
                      "..."
                    ],
                    "confidence": 0.939,
                    "source": "..."
                  },
                  "QuantityUnit": {
                    "type": "string",
                    "valueString": "hours",
                    "spans": [
                      "..."
                    ],
                    "confidence": 0.85,
                    "source": "..."
                  },
                  "TaxAmount": {
                    "type": "object",
                    "valueObject": {
                      "Amount": {
                        "type": "number",
                        "valueNumber": 6,
                        "spans": [
                          "..."
                        ],
                        "confidence": 0.522,
                        "source": "..."
                      },
                      "CurrencyCode": {
                        "type": "string",
                        "valueString": "USD"
                      }
                    }
                  },
                  "TaxRate": {
                    "type": "number",
                    "confidence": 0.915
                  },
                  "TotalAmount": {
                    "type": "object",
                    "valueObject": {
                      "Amount": {
                        "type": "number",
                        "valueNumber": 60,
                        "spans": [
                          "..."
                        ],
                        "confidence": 0.972,
                        "source": "..."
                      },
                      "CurrencyCode": {
                        "type": "string",
                        "valueString": "USD"
                      }
                    }
                  },
                  "UnitPrice": {
                    "type": "object",
                    "valueObject": {
                      "Amount": {
                        "type": "number",
                        "valueNumber": 30,
                        "spans": [
                          "..."
                        ],
                        "confidence": 0.97,
                        "source": "..."
                      },
                      "CurrencyCode": {
                        "type": "string",
                        "valueString": "USD"
                      }
                    }
                  }
                }
              },
              "... (2 additional line items)"
            ]
          }
          /*additional fields omitted*/
        },
        "kind": "document",
        "startPageNumber": 1,
        "endPageNumber": 1,
        "unit": "inch",
        "pages": [
          {
            "pageNumber": 1,
            "angle": 0,
            "width": 8.5,
            "height": 11,
            "words": [
              "... (words omitted for brevity)"
            ],
            "selectionMarks": [],
            "lines": [
              "... (lines omitted for brevity)"
            ],
            "barcodes": [],
            "formulas": []
          }
        ],
        "tables": [
          "... (tables omitted for brevity)"
        ],
        "keyValuePairs": [
          "... (key-value pairs omitted for brevity)"
        ],
        "analyzerId": "prebuilt-invoice",
        "mimeType": "application/pdf"
      }
    ]
  },
  "usage": {
    "documentStandardPages": 1,
    "contextualizationTokens": 2345,
    "tokens": {
      "gpt-4.1-mini-input": 1234,
      "gpt-4.1-mini-output": 567
    }
  }
}

Conseil

Lorsque vous utilisez l’analyseur vidéo, les images clés sont renvoyées comme URL dans la réponse JSON (par exemple, sous result.contents.frames[]). Téléchargez des extraits de vidéo en utilisant une requête HTTP GET standard :

curl -O "<keyframeUrl>"

bibliothèque Client | Samples | SDK source

Ce guide de démarrage rapide vous montre comment utiliser le Kit de développement logiciel (SDK) Content Understanding Python pour extraire des données structurées à l’aide d’analyseurs prédéfinis à partir de fichiers document, image, audio et vidéo. Pour en savoir plus sur les analyseurs prédéfinis et d’autres fonctionnalités, consultez la documentation des analyseurs prédéfinis.

Conditions préalables

  • Un abonnement actif Azure. Si vous n'avez pas de compte Azure, créez-en un gratuitement.
  • Ressource Microsoft Foundry créée dans une région prise en charge.
  • Votre point de terminaison de ressource et votre clé API (trouvés sous Clés et Point de terminaison dans le portail Azure).
  • Modèles de déploiement par défaut configurés pour votre ressource. Consultez Modèles et déploiements ou ce script de configuration unique pour obtenir des instructions de configuration.
  • Python 3.9 ou version ultérieure.

Configuration

  1. Installez la bibliothèque cliente Content Understanding pour Python avec pip :

    pip install azure-ai-contentunderstanding
    
  2. Si vous le souhaitez, installez la bibliothèque Azure Identity pour l’authentification Microsoft Entra :

    pip install azure-identity
    

Configurer des variables d’environnement

Pour vous authentifier auprès du service Content Understanding, définissez les variables d’environnement avec vos propres valeurs avant d’exécuter l’exemple :

  • CONTENTUNDERSTANDING_ENDPOINT - point de terminaison de votre ressource Content Understanding.
  • CONTENTUNDERSTANDING_KEY - votre clé API Content Understanding (facultatif si vous utilisez Microsoft Entra ID DefaultAzureCredential).

Windows

setx CONTENTUNDERSTANDING_ENDPOINT "your-endpoint"
setx CONTENTUNDERSTANDING_KEY "your-key"

Linux / macOS

export CONTENTUNDERSTANDING_ENDPOINT="your-endpoint"
export CONTENTUNDERSTANDING_KEY="your-key"

Créer un client

Ce ContentUnderstandingClient est le point d’entrée principal pour interagir avec le service. Créez une instance en fournissant votre point de terminaison et vos informations d’identification.

import os
from azure.ai.contentunderstanding import ContentUnderstandingClient
from azure.core.credentials import AzureKeyCredential

endpoint = os.environ["CONTENTUNDERSTANDING_ENDPOINT"]
key = os.environ["CONTENTUNDERSTANDING_KEY"]

client = ContentUnderstandingClient(endpoint=endpoint, credential=AzureKeyCredential(key))

Mise en route d’un analyseur prédéfini

Les analyseurs définissent la façon dont votre contenu est traité et les insights extraits. Nous offrons des analyseurs prédéfinis pour les cas d’usage courants. Vous pouvez personnaliser des analyseurs prédéfinis pour mieux répondre à vos besoins et cas d’usage spécifiques. Ce guide de démarrage rapide utilise des analyseurs de facture, d’image, d’audio et de vidéo prédéfinis pour vous aider à commencer.

Cet exemple utilise l’analyseur prebuilt-invoice pour extraire des données structurées à partir d’un document de facture.

import sys
from azure.ai.contentunderstanding.models import (
    AnalysisInput,
    AnalysisResult,
    DocumentContent,
    ArrayField,
    ObjectField,
)

# Sample invoice
invoice_url = (
    "https://raw.githubusercontent.com/"
    "Azure-Samples/"
    "azure-ai-content-understanding-assets/"
    "main/document/invoice.pdf"
)

poller = client.begin_analyze(
    analyzer_id="prebuilt-invoice",
    inputs=[AnalysisInput(url=invoice_url)],
)
result: AnalysisResult = poller.result()

if not result.contents or len(result.contents) == 0:
    print("No content found in the analysis result.")
    sys.exit(0)

# Get the document content
document_content: DocumentContent = (
    result.contents[0]  # type: ignore
)

print(
    f"Document unit: {document_content.unit or 'unknown'}"
)
print(
    f"Pages: {document_content.start_page_number}"
    f" to {document_content.end_page_number}"
)

if not document_content.fields:
    print("No fields found in the analysis result.")
    sys.exit(0)

# Extract simple string fields
customer_name = document_content.fields.get("CustomerName")
if customer_name:
    print(f"Customer Name: {customer_name.value}")
    if customer_name.confidence:
        print(
            f"  Confidence: {customer_name.confidence:.2f}"
        )
    print(f"  Source: {customer_name.source or 'N/A'}")

# Extract date fields
invoice_date = document_content.fields.get("InvoiceDate")
if invoice_date:
    print(f"Invoice Date: {invoice_date.value}")
    if invoice_date.confidence:
        print(
            f"  Confidence: {invoice_date.confidence:.2f}"
        )

# Extract object fields (nested structures)
total_amount = document_content.fields.get("TotalAmount")
if (
    isinstance(total_amount, ObjectField)
    and total_amount.value
):
    amount_field = total_amount.value.get("Amount")
    currency_field = total_amount.value.get(
        "CurrencyCode"
    )
    amount = (
        amount_field.value if amount_field else None
    )
    currency = (
        currency_field.value
        if currency_field and currency_field.value
        else ""
    )
    if isinstance(amount, (int, float)):
        print(f"\nTotal: {currency}{amount:.2f}")
    else:
        print(f"\nTotal: {currency}{amount or '(None)'}")

# Extract array fields (line items)
line_items = document_content.fields.get("LineItems")
if (
    isinstance(line_items, ArrayField)
    and line_items.value
):
    print(f"\nLine Items ({len(line_items.value)}):")
    for i, item in enumerate(line_items.value, 1):
        if (
            isinstance(item, ObjectField)
            and item.value
        ):
            desc = item.value.get("Description")
            qty = item.value.get("Quantity")
            description = (
                desc.value
                if desc and desc.value
                else "N/A"
            )
            quantity = (
                qty.value
                if qty and qty.value
                else "N/A"
            )
            print(f"  Item {i}: {description}")
            print(f"    Quantity: {quantity}")

Cela génère la sortie suivante :

Document unit: LengthUnit.INCH
Pages: 1 to 1
Customer Name: MICROSOFT CORPORATION
  Confidence: 0.39
  Source: D(1,6.2250,2.0092,8.0020,2.0077,8.0021,2.1638,6.2251,2.1653)
Invoice Date: 2019-11-15
  Confidence: 0.91

Total: USD110.00

Line Items (3):
  Item 1: Consulting Services
    Quantity: 2.0
  Item 2: Document Fee
    Quantity: 3.0
  Item 3: Printing Fee
    Quantity: 10.0

Note

Ce code est basé sur l’exemple sample_analyze_invoice.py dans le référentiel sdk.

bibliothèque Client | Samples | SDK source

Ce guide de démarrage rapide vous montre comment utiliser le Kit de développement logiciel (SDK) Content Understanding .NET pour extraire des données structurées à l’aide d’analyseurs prédéfinis à partir de fichiers document, image, audio et vidéo. Pour en savoir plus sur les analyseurs prédéfinis et d’autres fonctionnalités, consultez la documentation des analyseurs prédéfinis.

Conditions préalables

  • Un abonnement actif Azure. Si vous n'avez pas de compte Azure, créez-en un gratuitement.
  • Ressource Microsoft Foundry créée dans une région prise en charge.
  • Votre point de terminaison de ressource et votre clé API (trouvés sous Clés et Point de terminaison dans le portail Azure).
  • Modèles de déploiement par défaut configurés pour votre ressource. Consultez Modèles et déploiements ou ce script de configuration unique pour obtenir des instructions de configuration.
  • Version actuelle de .NET.

Configuration

  1. Créez une application console .NET :

    dotnet new console -n ContentUnderstandingQuickstart
    cd ContentUnderstandingQuickstart
    
  2. Installez la bibliothèque cliente Content Understanding pour .NET :

    dotnet add package Azure.AI.ContentUnderstanding
    
  3. Si vous le souhaitez, installez la bibliothèque Azure Identity pour l’authentification Microsoft Entra :

    dotnet add package Azure.Identity
    

Configurer des variables d’environnement

Pour vous authentifier auprès du service Content Understanding, définissez les variables d’environnement avec vos propres valeurs avant d’exécuter l’exemple :

  • CONTENTUNDERSTANDING_ENDPOINT - point de terminaison de votre ressource Content Understanding.
  • CONTENTUNDERSTANDING_KEY - votre clé API Content Understanding (facultatif si vous utilisez Microsoft Entra ID DefaultAzureCredential).

Windows

setx CONTENTUNDERSTANDING_ENDPOINT "your-endpoint"
setx CONTENTUNDERSTANDING_KEY "your-key"

Linux / macOS

export CONTENTUNDERSTANDING_ENDPOINT="your-endpoint"
export CONTENTUNDERSTANDING_KEY="your-key"

Créer un client

Ce ContentUnderstandingClient est le point d’entrée principal pour interagir avec le service. Créez une instance en fournissant votre point de terminaison et vos informations d’identification.

using Azure;
using Azure.AI.ContentUnderstanding;

string endpoint = Environment.GetEnvironmentVariable("CONTENTUNDERSTANDING_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENTUNDERSTANDING_KEY");

var client = new ContentUnderstandingClient(
    new Uri(endpoint),
    new AzureKeyCredential(key)
);

Mise en route d’un analyseur prédéfini

Les analyseurs définissent la façon dont votre contenu est traité et les insights extraits. Nous offrons des analyseurs prédéfinis pour les cas d’usage courants. Vous pouvez personnaliser des analyseurs prédéfinis pour mieux répondre à vos besoins et cas d’usage spécifiques. Ce guide de démarrage rapide utilise des analyseurs de facture, d’image, d’audio et de vidéo prédéfinis pour vous aider à commencer.

Cet exemple utilise l’analyseur prebuilt-invoice pour extraire des données structurées à partir d’un document de facture.

// Sample invoice
Uri invoiceUrl = new Uri("https://raw.githubusercontent.com/Azure-Samples/azure-ai-content-understanding-assets/main/document/invoice.pdf");
Operation<AnalysisResult> operation = await client.AnalyzeAsync(
    WaitUntil.Completed,
    "prebuilt-invoice",
    inputs: new[] { new AnalysisInput { Uri = invoiceUrl } });

AnalysisResult result = operation.Value;

DocumentContent documentContent = (DocumentContent)result.Contents!.First();

// Print document unit information
// The unit indicates the measurement system used for coordinates in the source field
Console.WriteLine($"Document unit: {documentContent.Unit ?? "unknown"}");
Console.WriteLine($"Pages: {documentContent.StartPageNumber} to {documentContent.EndPageNumber}");
if (documentContent.Pages != null && documentContent.Pages.Count > 0)
{
    var page = documentContent.Pages[0];
    var unit = documentContent.Unit?.ToString() ?? "units";
    Console.WriteLine($"Page dimensions: {page.Width} x {page.Height} {unit}");
}
Console.WriteLine();

// Extract simple string fields
var customerNameField = documentContent.Fields["CustomerName"];
Console.WriteLine($"Customer Name: {customerNameField.Value ?? "(None)"}");
Console.WriteLine($"  Confidence: {customerNameField.Confidence?.ToString("F2") ?? "N/A"}");

if (customerNameField.Spans?.Count > 0)
{
    var span = customerNameField.Spans[0];
    Console.WriteLine($"  Position in markdown: offset={span.Offset}, length={span.Length}");
}

// Extract simple date field
var invoiceDateField = documentContent.Fields.GetFieldOrDefault("InvoiceDate");
Console.WriteLine($"Invoice Date: {invoiceDateField?.Value ?? "(None)"}");
Console.WriteLine($"  Confidence: {invoiceDateField?.Confidence?.ToString("F2") ?? "N/A"}");

// Access parsed sources for date field
if (invoiceDateField?.Sources != null)
{
    foreach (var source in invoiceDateField.Sources)
    {
        if (source is DocumentSource docSource)
        {
            Console.WriteLine($"  Page {docSource.PageNumber}");
            Console.WriteLine($"  BoundingBox: {docSource.BoundingBox}");
        }
    }
}

if (invoiceDateField?.Spans?.Count > 0)
{
    var span = invoiceDateField.Spans[0];
    Console.WriteLine($"  Position in markdown: offset={span.Offset}, length={span.Length}");
}

// Extract object fields (nested structures)
if (documentContent.Fields.GetFieldOrDefault("TotalAmount") is ContentObjectField totalAmountObj)
{
    var amount = totalAmountObj.Value?.GetFieldOrDefault("Amount")?.Value as double?;
    var currency = totalAmountObj.Value?.GetFieldOrDefault("CurrencyCode")?.Value;
    Console.WriteLine($"Total: {currency ?? "$"}{amount?.ToString("F2") ?? "(None)"}");

    // Access parsed sources for object field
    if (totalAmountObj.Sources != null)
    {
        foreach (var source in totalAmountObj.Sources)
        {
            if (source is DocumentSource docSource)
            {
                Console.WriteLine($"  Page {docSource.PageNumber}");
                Console.WriteLine($"  BoundingBox: {docSource.BoundingBox}");
            }
        }
    }
}

// Extract array fields (collections like line items)
if (documentContent.Fields.GetFieldOrDefault("LineItems") is ContentArrayField lineItems)
{
    Console.WriteLine($"Line Items ({lineItems.Count}):");
    for (int i = 0; i < lineItems.Count; i++)
    {
        if (lineItems[i] is ContentObjectField item)
        {
            var description = item.Value?.GetFieldOrDefault("Description")?.Value;
            var quantity = item.Value?.GetFieldOrDefault("Quantity")?.Value as double?;
            Console.WriteLine($"  Item {i + 1}: {description ?? "N/A"} (Qty: {quantity?.ToString() ?? "N/A"})");
        }
    }
}

Cela génère la sortie suivante :

Document unit: inch
Pages: 1 to 1
Page dimensions: 8.5 x 11 inch

Customer Name: MICROSOFT CORPORATION
  Confidence: 0.44
  Position in markdown: offset=162, length=21
Invoice Date: 11/15/2019 12:00:00 AM +00:00
  Confidence: 0.94
  Page 1
  BoundingBox: {X=7.2398,Y=1.5908,Width=0.7662997,Height=0.16179991}
  Position in markdown: offset=113, length=10
Total: USD110.00
Line Items (3):
  Item 1: Consulting Services (Qty: 2)
  Item 2: Document Fee (Qty: 3)
  Item 3: Printing Fee (Qty: 10)

Note

Ce code est basé sur l’exemple AnalyzeInvoice dans le référentiel sdk.

bibliothèque Client | Samples | SDK source

Ce guide de démarrage rapide vous montre comment utiliser le Kit de développement logiciel (SDK) Content Understanding Java pour extraire des données structurées à l’aide d’analyseurs prédéfinis à partir de fichiers document, image, audio et vidéo. Pour en savoir plus sur les analyseurs prédéfinis et d’autres fonctionnalités, consultez la documentation des analyseurs prédéfinis.

Conditions préalables

  • Un abonnement actif Azure. Si vous n'avez pas de compte Azure, créez-en un gratuitement.
  • Ressource Microsoft Foundry créée dans une région prise en charge.
  • Votre point de terminaison de ressource et votre clé API (trouvés sous Clés et Point de terminaison dans le portail Azure).
  • Modèles de déploiement par défaut configurés pour votre ressource. Consultez Modèles et déploiements ou ce script de configuration unique pour obtenir des instructions de configuration.
  • Java Kit de développement (JDK) version 8 ou ultérieure.
  • Apache Maven.

Configuration

  1. Créez un projet Maven :

    mvn archetype:generate -DgroupId=com.example \
        -DartifactId=content-understanding-quickstart \
        -DarchetypeArtifactId=maven-archetype-quickstart \
        -DinteractiveMode=false
    cd content-understanding-quickstart
    
  2. Ajoutez la dépendance Content Understanding à votre fichier pom.xml dans la <dependencies> section :

    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-contentunderstanding</artifactId>
        <version>1.0.0-beta.1</version>
    </dependency>
    
  3. Si vous le souhaitez, ajoutez la bibliothèque Azure Identity pour l’authentification Microsoft Entra :

    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-identity</artifactId>
        <version>1.14.2</version>
    </dependency>
    

Configurer des variables d’environnement

Pour vous authentifier auprès du service Content Understanding, définissez les variables d’environnement avec vos propres valeurs avant d’exécuter l’exemple :

  • CONTENTUNDERSTANDING_ENDPOINT - point de terminaison de votre ressource Content Understanding.
  • CONTENTUNDERSTANDING_KEY - votre clé API Content Understanding (facultatif si vous utilisez Microsoft Entra ID DefaultAzureCredential).

Windows

setx CONTENTUNDERSTANDING_ENDPOINT "your-endpoint"
setx CONTENTUNDERSTANDING_KEY "your-key"

Linux / macOS

export CONTENTUNDERSTANDING_ENDPOINT="your-endpoint"
export CONTENTUNDERSTANDING_KEY="your-key"

Créer un client

Ce ContentUnderstandingClient est le point d’entrée principal pour interagir avec le service. Créez une instance en fournissant votre point de terminaison et vos informations d’identification.

import com.azure.core.credential.AzureKeyCredential;
import com.azure.ai.contentunderstanding.ContentUnderstandingClient;
import com.azure.ai.contentunderstanding.ContentUnderstandingClientBuilder;

String endpoint = System.getenv("CONTENTUNDERSTANDING_ENDPOINT");
String key = System.getenv("CONTENTUNDERSTANDING_KEY");

ContentUnderstandingClient client =
    new ContentUnderstandingClientBuilder()
        .endpoint(endpoint)
        .credential(new AzureKeyCredential(key))
        .buildClient();

Mise en route d’un analyseur prédéfini

Les analyseurs définissent la façon dont votre contenu est traité et les insights extraits. Nous offrons des analyseurs prédéfinis pour les cas d’usage courants. Vous pouvez personnaliser des analyseurs prédéfinis pour mieux répondre à vos besoins et cas d’usage spécifiques. Ce guide de démarrage rapide utilise des analyseurs de facture, d’image, d’audio et de vidéo prédéfinis pour vous aider à commencer.

Cet exemple utilise l’analyseur prebuilt-invoice pour extraire des données structurées à partir d’un document de facture.

import java.util.Arrays;
import java.util.List;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;
import com.azure.ai.contentunderstanding.ContentUnderstandingClient;
import com.azure.ai.contentunderstanding.ContentUnderstandingClientBuilder;
import com.azure.ai.contentunderstanding.models.*;

public class test_document {

    public static void main(String[] args) {
        String endpoint = System.getenv("CONTENTUNDERSTANDING_ENDPOINT");
        String key = System.getenv("CONTENTUNDERSTANDING_KEY");

        ContentUnderstandingClient client =
            new ContentUnderstandingClientBuilder()
                .endpoint(endpoint)
                .credential(new AzureKeyCredential(key))
                .buildClient();

        // Sample invoice
        String invoiceUrl =
            "https://raw.githubusercontent.com/"
            + "Azure-Samples/"
            + "azure-ai-content-understanding-assets/"
            + "main/document/invoice.pdf";

        AnalysisInput input = new AnalysisInput();
        input.setUrl(invoiceUrl);

        SyncPoller<ContentAnalyzerAnalyzeOperationStatus, AnalysisResult> poller =
            client.beginAnalyze(
                "prebuilt-invoice",
                Arrays.asList(input)
            );
        AnalysisResult result = poller.getFinalResult();
        
        // BEGIN:ContentUnderstandingExtractInvoiceFields
        // Get the invoice document content
        AnalysisContent firstContent = result.getContents().get(0);
        if (firstContent instanceof DocumentContent) {
            DocumentContent documentContent = (DocumentContent) firstContent;

            // Print document unit information
            System.out.println("Document unit: "
                + (documentContent.getUnit() != null ? documentContent.getUnit().toString() : "unknown"));
            System.out.println(
                "Pages: " + documentContent.getStartPageNumber() + " to " + documentContent.getEndPageNumber());
            System.out.println();

            // Extract simple string fields using getValue() convenience method
            // getValue() returns the typed value regardless of field type (StringField, NumberField, DateField, etc.)
            ContentField customerNameField
                = documentContent.getFields() != null ? documentContent.getFields().get("CustomerName") : null;
            ContentField invoiceDateField
                = documentContent.getFields() != null ? documentContent.getFields().get("InvoiceDate") : null;

            // Use getValue() instead of casting to specific types
            // Note: getValue() returns the actual typed value - String, Number, LocalDate, etc.
            String customerName = customerNameField != null ? (String) customerNameField.getValue() : null;
            Object invoiceDateValue = invoiceDateField != null ? invoiceDateField.getValue() : null;
            String invoiceDate = invoiceDateValue != null ? invoiceDateValue.toString() : null;

            System.out.println("Customer Name: " + (customerName != null ? customerName : "(None)"));
            if (customerNameField != null) {
                System.out.println("  Confidence: " + (customerNameField.getConfidence() != null
                    ? String.format("%.2f", customerNameField.getConfidence())
                    : "N/A"));
                // Parse into DocumentSource for page number and bounding box
                List<ContentSource> sources = customerNameField.getSources();
                if (sources != null) {
                    for (ContentSource src : sources) {
                        if (src instanceof DocumentSource) {
                            DocumentSource docSrc = (DocumentSource) src;
                            System.out.println("  Source: page " + docSrc.getPageNumber()
                                + ", polygon " + docSrc.getPolygon()
                                + ", bounding box " + docSrc.getBoundingBox());
                        }
                    }
                }
                List<ContentSpan> spans = customerNameField.getSpans();
                if (spans != null && !spans.isEmpty()) {
                    ContentSpan span = spans.get(0);
                    System.out
                        .println("  Position in markdown: offset=" + span.getOffset() + ", length=" + span.getLength());
                }
            }

            System.out.println("Invoice Date: " + (invoiceDate != null ? invoiceDate : "(None)"));
            if (invoiceDateField != null) {
                System.out.println("  Confidence: " + (invoiceDateField.getConfidence() != null
                    ? String.format("%.2f", invoiceDateField.getConfidence())
                    : "N/A"));
                System.out.println(
                    "  Source: " + (invoiceDateField.getSources() != null ? invoiceDateField.getSources() : "N/A"));
                List<ContentSpan> spans = invoiceDateField.getSpans();
                if (spans != null && !spans.isEmpty()) {
                    ContentSpan span = spans.get(0);
                    System.out
                        .println("  Position in markdown: offset=" + span.getOffset() + ", length=" + span.getLength());
                }
            }

            // Extract object fields (nested structures) using getFieldOrDefault() convenience method
            ContentField totalAmountField
                = documentContent.getFields() != null ? documentContent.getFields().get("TotalAmount") : null;
            if (totalAmountField instanceof ContentObjectField) {
                ContentObjectField totalAmountObj = (ContentObjectField) totalAmountField;
                ContentField amountField = totalAmountObj.getFieldOrDefault("Amount");
                ContentField currencyField = totalAmountObj.getFieldOrDefault("CurrencyCode");

                Double amount = amountField != null ? (Double) amountField.getValue() : null;
                String currency = currencyField != null ? (String) currencyField.getValue() : null;

                System.out.println("Total: " + (currency != null ? currency : "")
                    + (amount != null ? String.format("%.2f", amount) : "(None)"));
                if (totalAmountObj.getConfidence() != null) {
                    System.out.println("  Confidence: " + String.format("%.2f", totalAmountObj.getConfidence()));
                }
                if (totalAmountObj.getSources() != null && !totalAmountObj.getSources().isEmpty()) {
                    System.out.println("  Source: " + totalAmountObj.getSources());
                }
            }

            // Extract array fields using size() and get() convenience methods
            ContentField lineItemsField
                = documentContent.getFields() != null ? documentContent.getFields().get("LineItems") : null;
            if (lineItemsField instanceof ContentArrayField) {
                ContentArrayField lineItems = (ContentArrayField) lineItemsField;

                System.out.println("Line Items (" + lineItems.size() + "):");

                for (int i = 0; i < lineItems.size(); i++) {
                    ContentField itemField = lineItems.get(i);
                    if (itemField instanceof ContentObjectField) {
                        ContentObjectField item = (ContentObjectField) itemField;
                        ContentField descField = item.getFieldOrDefault("Description");
                        ContentField qtyField = item.getFieldOrDefault("Quantity");
                        String description = descField != null ? (String) descField.getValue() : null;
                        Double quantity = qtyField != null ? (Double) qtyField.getValue() : null;

                        System.out.println("  Item " + (i + - + ": " + (description != null ? description : "N/A"));
                        System.out.println("    Quantity: " + (quantity != null ? quantity : "N/A"));
                        if (qtyField != null && qtyField.getConfidence() != null) {
                            System.out.println("    Quantity Confidence: " + String.format("%.2f", qtyField.getConfidence()));
                        } else {
                            System.out.println("    Quantity Confidence: N/A");
                        }
                    }
                }
            }
        } // END:ContentUnderstandingExtractInvoiceFields
    }
}
        

Cela génère la sortie suivante :

Document unit: inch
Pages: 1 to 1

Customer Name: MICROSOFT CORPORATION
  Confidence: 0.43
  Source: page 1, polygon [(6.225, 2.0092), (8.002, 2.0077), (8.0021, 2.1638), (6.2251, 2.1653)], bounding box [x=6.225, y=2.0077, width=1.7771001, height=0.15759993]
  Position in markdown: offset=162, length=21
Invoice Date: 2019-11-15
  Confidence: 0.94
  Source: [D(1,7.2399,1.5954,8.0061,1.5908,8.0061,1.7482,7.2398,1.7526)]
  Position in markdown: offset=113, length=10
Total: USD110.00
Line Items (3):
  Item 1: Consulting Services
    Quantity: 2.0
    Quantity Confidence: 0.96
  Item 2: Document Fee
    Quantity: 3.0
    Quantity Confidence: 0.90
  Item 3: Printing Fee
    Quantity: 10.0
    Quantity Confidence: 0.94

bibliothèque Client | Samples | SDK source

Ce guide de démarrage rapide vous montre comment utiliser le Kit de développement logiciel (SDK) JavaScript Content Understanding pour extraire des données structurées à l’aide d’analyseurs prédéfinis à partir de fichiers document, image, audio et vidéo. Pour en savoir plus sur les analyseurs prédéfinis et d’autres fonctionnalités, consultez la documentation des analyseurs prédéfinis.

Conditions préalables

  • Un abonnement actif Azure. Si vous n'avez pas de compte Azure, créez-en un gratuitement.
  • Ressource Microsoft Foundry créée dans une région prise en charge.
  • Votre point de terminaison de ressource et votre clé API (trouvés sous Clés et Point de terminaison dans le portail Azure).
  • Modèles de déploiement par défaut configurés pour votre ressource. Consultez Modèles et déploiements ou ce script de configuration unique pour obtenir des instructions de configuration.
  • Node.js Version LTS.

Configuration

  1. Créez un projet Node.js :

    mkdir content-understanding-quickstart
    cd content-understanding-quickstart
    npm init -y
    
  2. Installez la bibliothèque cliente Content Understanding :

    npm install @azure/ai-content-understanding
    
  3. Si vous le souhaitez, installez la bibliothèque Azure Identity pour l’authentification Microsoft Entra :

    npm install @azure/identity
    

Configurer des variables d’environnement

Pour vous authentifier auprès du service Content Understanding, définissez les variables d’environnement avec vos propres valeurs avant d’exécuter l’exemple :

  • CONTENTUNDERSTANDING_ENDPOINT - point de terminaison de votre ressource Content Understanding.
  • CONTENTUNDERSTANDING_KEY - votre clé API Content Understanding (facultatif si vous utilisez Microsoft Entra ID DefaultAzureCredential).

Windows

setx CONTENTUNDERSTANDING_ENDPOINT "your-endpoint"
setx CONTENTUNDERSTANDING_KEY "your-key"

Linux / macOS

export CONTENTUNDERSTANDING_ENDPOINT="your-endpoint"
export CONTENTUNDERSTANDING_KEY="your-key"

Créer un client

Ce ContentUnderstandingClient est le point d’entrée principal pour interagir avec le service. Créez une instance en fournissant votre point de terminaison et vos informations d’identification.

const { AzureKeyCredential } = require("@azure/core-auth");
const {
    ContentUnderstandingClient,
} = require("@azure/ai-content-understanding");

const endpoint = process.env["CONTENTUNDERSTANDING_ENDPOINT"];
const key = process.env["CONTENTUNDERSTANDING_KEY"];

const client = new ContentUnderstandingClient(
    endpoint,
    new AzureKeyCredential(key)
);

Mise en route d’un analyseur prédéfini

Les analyseurs définissent la façon dont votre contenu est traité et les insights extraits. Nous offrons des analyseurs prédéfinis pour les cas d’usage courants. Vous pouvez personnaliser des analyseurs prédéfinis pour mieux répondre à vos besoins et cas d’usage spécifiques. Ce guide de démarrage rapide utilise des analyseurs de facture, d’image, d’audio et de vidéo prédéfinis pour vous aider à commencer.

Cet exemple utilise l’analyseur prebuilt-invoice pour extraire des données structurées à partir d’un document de facture.

async function main() {
    const client = new ContentUnderstandingClient(
        endpoint,
        new AzureKeyCredential(key)
    );

    // Sample invoice
    const invoiceUrl =
        "https://raw.githubusercontent.com/"
        + "Azure-Samples/"
        + "azure-ai-content-understanding-assets/"
        + "main/document/invoice.pdf";

    const poller = client.analyze(
        "prebuilt-invoice",
        [{ url: invoiceUrl }]
    );
    const result = await poller.pollUntilDone();

    if (
        !result.contents
        || result.contents.length === 0
    ) {
        console.log(
            "No content found in the analysis result."
        );
        return;
    }

    const content = result.contents[0];

    // Get the document content
    if (content.kind === "document") {
        const documentContent = content;

        console.log(
            `Document unit: `
            + `${documentContent.unit ?? "unknown"}`
        );
        console.log(
            `Pages: ${documentContent.startPageNumber}`
            + ` to ${documentContent.endPageNumber}`
        );

        if (!documentContent.fields) {
            console.log("No fields found.");
            return;
        }

        // Extract simple string fields
        const customerNameField =
            documentContent.fields["CustomerName"];
        if (customerNameField) {
            console.log(
                `Customer Name: `
                + `${customerNameField.value ?? "(None)"}`
            );
            if (
                customerNameField.confidence !== undefined
            ) {
                console.log(
                    `  Confidence: `
                    + `${customerNameField.confidence
                        .toFixed(2)}`
                );
            }
        }

        // Extract date fields
        const invoiceDateField =
            documentContent.fields["InvoiceDate"];
        if (invoiceDateField) {
            console.log(
                `Invoice Date: `
                + `${invoiceDateField.value ?? "(None)"}`
            );
            if (
                invoiceDateField.confidence !== undefined
            ) {
                console.log(
                    `  Confidence: `
                    + `${invoiceDateField.confidence
                        .toFixed(2)}`
                );
            }
        }

        // Extract object fields (nested structures)
        const totalAmountField =
            documentContent.fields["TotalAmount"];
        if (
            totalAmountField
            && totalAmountField.type === "object"
        ) {
            const objField = totalAmountField;
            if (objField.value) {
                const amountField =
                    objField.value["Amount"];
                const currencyField =
                    objField.value["CurrencyCode"];

                const amount =
                    amountField?.value ?? "(None)";
                const currency =
                    currencyField?.value ?? "";

                console.log(
                    `\nTotal: ${currency}${amount}`
                );
            }
        }

        // Extract array fields (line items)
        const lineItemsField =
            documentContent.fields["LineItems"];
        if (
            lineItemsField
            && lineItemsField.type === "array"
        ) {
            const arrField = lineItemsField;
            if (
                arrField.value
                && arrField.value.length > 0
            ) {
                console.log(
                    `\nLine Items `
                    + `(${arrField.value.length}):`
                );
                arrField.value.forEach((item, index) => {
                    if (item.type === "object") {
                        const itemObj = item;
                        if (itemObj.value) {
                            const descField =
                                itemObj.value[
                                    "Description"
                                ];
                            const qtyField =
                                itemObj.value["Quantity"];

                            const description =
                                descField?.value ?? "N/A";
                            const quantity =
                                qtyField?.value ?? "N/A";

                            console.log(
                                `  Item ${index + 1}: `
                                + `${description}`
                            );
                            console.log(
                                `    Quantity: ${quantity}`
                            );
                        }
                    }
                });
            }
        }
    }
}

main().catch((err) => {
    console.error("The sample encountered an error:", err);
});

Cela génère la sortie suivante :

Document unit: inch
Pages: 1 to 1
Customer Name: MICROSOFT CORPORATION
  Confidence: 0.44
Invoice Date: Thu Nov 14 2019 19:00:00 GMT-0500 (Eastern Standard Time)
  Confidence: 0.94

Total: USD110

Line Items (3):
  Item 1: Consulting Services
    Quantity: 2
  Item 2: Document Fee
    Quantity: 3
  Item 3: Printing Fee
    Quantity: 10

Note

Ce code est basé sur l’exemple analyzeInvoice.js dans le référentiel sdk.

bibliothèque Client | Samples | SDK source

Ce guide de démarrage rapide vous montre comment utiliser le Kit de développement logiciel (SDK) Content Understanding TypeScript pour extraire des données structurées à l’aide d’analyseurs prédéfinis à partir de fichiers document, image, audio et vidéo. Pour en savoir plus sur les analyseurs prédéfinis et d’autres fonctionnalités, consultez la documentation des analyseurs prédéfinis.

Conditions préalables

  • Un abonnement actif Azure. Si vous n'avez pas de compte Azure, créez-en un gratuitement.
  • Ressource Microsoft Foundry créée dans une région prise en charge.
  • Votre point de terminaison de ressource et votre clé API (trouvés sous Clés et Point de terminaison dans le portail Azure).
  • Modèles de déploiement par défaut configurés pour votre ressource. Consultez Modèles et déploiements ou ce script de configuration unique pour obtenir des instructions de configuration.
  • Node.js Version LTS.
  • TypeScript 5.x ou version ultérieure.

Configuration

  1. Créez un projet Node.js :

    mkdir content-understanding-quickstart
    cd content-understanding-quickstart
    npm init -y
    
  2. Installez TypeScript et la bibliothèque cliente Content Understanding :

    npm install typescript ts-node @azure/ai-content-understanding
    
  3. Si vous le souhaitez, installez la bibliothèque Azure Identity pour l’authentification Microsoft Entra :

    npm install @azure/identity
    

Configurer des variables d’environnement

Pour vous authentifier auprès du service Content Understanding, définissez les variables d’environnement avec vos propres valeurs avant d’exécuter l’exemple :

  • CONTENTUNDERSTANDING_ENDPOINT - point de terminaison de votre ressource Content Understanding.
  • CONTENTUNDERSTANDING_KEY - votre clé API Content Understanding (facultatif si vous utilisez Microsoft Entra ID DefaultAzureCredential).

Windows

setx CONTENTUNDERSTANDING_ENDPOINT "your-endpoint"
setx CONTENTUNDERSTANDING_KEY "your-key"

Linux / macOS

export CONTENTUNDERSTANDING_ENDPOINT="your-endpoint"
export CONTENTUNDERSTANDING_KEY="your-key"

Créer un client

Ce ContentUnderstandingClient est le point d’entrée principal pour interagir avec le service. Créez une instance en fournissant votre point de terminaison et vos informations d’identification.

import { AzureKeyCredential } from "@azure/core-auth";
import {
    ContentUnderstandingClient,
} from "@azure/ai-content-understanding";

const endpoint = process.env["CONTENTUNDERSTANDING_ENDPOINT"];
const key = process.env["CONTENTUNDERSTANDING_KEY"];

const client = new ContentUnderstandingClient(
    endpoint,
    new AzureKeyCredential(key)
);

Mise en route d’un analyseur prédéfini

Les analyseurs définissent la façon dont votre contenu est traité et les insights extraits. Nous offrons des analyseurs prédéfinis pour les cas d’usage courants. Vous pouvez personnaliser des analyseurs prédéfinis pour mieux répondre à vos besoins et cas d’usage spécifiques. Ce guide de démarrage rapide utilise des analyseurs de facture, d’image, d’audio et de vidéo prédéfinis pour vous aider à commencer.

Cet exemple utilise l’analyseur prebuilt-invoice pour extraire des données structurées à partir d’un document de facture.

import {
    type DocumentContent,
    type ArrayField,
    type ObjectField,
} from "@azure/ai-content-understanding";

async function main(): Promise<void> {
    const client = new ContentUnderstandingClient(
        endpoint,
        new AzureKeyCredential(key)
    );

    // Sample invoice
    const invoiceUrl =
        "https://raw.githubusercontent.com/"
        + "Azure-Samples/"
        + "azure-ai-content-understanding-assets/"
        + "main/document/invoice.pdf";

    const poller = client.analyze(
        "prebuilt-invoice",
        [{ url: invoiceUrl }]
    );
    const result = await poller.pollUntilDone();

    if (
        !result.contents
        || result.contents.length === 0
    ) {
        console.log(
            "No content found in the analysis result."
        );
        return;
    }

    const content = result.contents[0];

    // Get the document content
    if (content.kind === "document") {
        const documentContent =
            content as DocumentContent;

        console.log(
            `Document unit: `
            + `${documentContent.unit ?? "unknown"}`
        );
        console.log(
            `Pages: ${documentContent.startPageNumber}`
            + ` to ${documentContent.endPageNumber}`
        );

        if (!documentContent.fields) {
            console.log("No fields found.");
            return;
        }

        // Extract simple string fields
        const customerNameField =
            documentContent.fields["CustomerName"];
        if (customerNameField) {
            console.log(
                `Customer Name: `
                + `${customerNameField.value ?? "(None)"}`
            );
            if (
                customerNameField.confidence !== undefined
            ) {
                console.log(
                    `  Confidence: `
                    + `${customerNameField.confidence
                        .toFixed(2)}`
                );
            }
        }

        // Extract date fields
        const invoiceDateField =
            documentContent.fields["InvoiceDate"];
        if (invoiceDateField) {
            console.log(
                `Invoice Date: `
                + `${invoiceDateField.value ?? "(None)"}`
            );
            if (
                invoiceDateField.confidence !== undefined
            ) {
                console.log(
                    `  Confidence: `
                    + `${invoiceDateField.confidence
                        .toFixed(2)}`
                );
            }
        }

        // Extract object fields (nested structures)
        const totalAmountField =
            documentContent.fields["TotalAmount"];
        if (
            totalAmountField
            && totalAmountField.type === "object"
        ) {
            const objField =
                totalAmountField as ObjectField;
            if (objField.value) {
                const amountField =
                    objField.value["Amount"];
                const currencyField =
                    objField.value["CurrencyCode"];

                const amount =
                    amountField?.value ?? "(None)";
                const currency =
                    currencyField?.value ?? "";

                console.log(
                    `\nTotal: ${currency}${amount}`
                );
            }
        }

        // Extract array fields (line items)
        const lineItemsField =
            documentContent.fields["LineItems"];
        if (
            lineItemsField
            && lineItemsField.type === "array"
        ) {
            const arrField =
                lineItemsField as ArrayField;
            if (
                arrField.value
                && arrField.value.length > 0
            ) {
                console.log(
                    `\nLine Items `
                    + `(${arrField.value.length}):`
                );
                arrField.value.forEach(
                    (item, index) => {
                        if (item.type === "object") {
                            const itemObj =
                                item as ObjectField;
                            if (itemObj.value) {
                                const descField =
                                    itemObj.value[
                                        "Description"
                                    ];
                                const qtyField =
                                    itemObj.value[
                                        "Quantity"
                                    ];

                                const description =
                                    descField?.value
                                    ?? "N/A";
                                const quantity =
                                    qtyField?.value
                                    ?? "N/A";

                                console.log(
                                    `  Item `
                                    + `${index + 1}: `
                                    + `${description}`
                                );
                                console.log(
                                    `    Quantity: `
                                    + `${quantity}`
                                );
                            }
                        }
                    }
                );
            }
        }
    }
}

main().catch((err) => {
    console.error("The sample encountered an error:", err);
});

Cela génère la sortie suivante :

Document unit: inch
Pages: 1 to 1
Customer Name: MICROSOFT CORPORATION
  Confidence: 0.39
Invoice Date: Thu Nov 14 2019 19:00:00 GMT-0500 (Eastern Standard Time)
  Confidence: 0.94

Total: USD110

Line Items (3):
  Item 1: Consulting Services
    Quantity: 2
  Item 2: Document Fee
    Quantity: 3
  Item 3: Printing Fee
    Quantity: 10

Note

Ce code est basé sur l’exemple analyzeInvoice.ts dans le référentiel sdk.

Étapes suivantes