Notatka
Dostęp do tej strony wymaga autoryzacji. Może spróbować zalogować się lub zmienić katalogi.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
"W tym przewodniku szybkiego startu pokazano, jak używać interfejsu API REST usługi Content Understanding do pobierania danych strukturyzowanych z zawartości wielomodalnej w dokumentach, obrazach, dźwiękach i plikach wideo."
Wskazówka
W przypadku scenariuszy interaktywnych, które wymagają natychmiastowej odpowiedzi z usługi Read lub Layout, zobacz Szybki start: używanie synchronicznych operacji usługi Content Understanding.
Wymagania wstępne
- Aktywna subskrypcja Azure. Jeśli nie masz konta Azure, utwórz je bezpłatnie.
- Zasób Microsoft Foundry utworzony w obsługiwanym regionie. Aby utworzyć zasób, musisz mieć rolę Współautor lub nowszą w docelowej subskrypcji lub grupie zasobów.
- Skonfiguruj domyślne wdrożenia modelu dla zasobu Content Understanding. Ustawiając domyślne wartości, tworzysz połączenie z modelami Microsoft Foundry używanymi do obsługi żądań związanych z rozumieniem treści. Wybierz jedną z następujących metod:
Przejdź do strony Ustawienia usługi Content Understanding.
Wybierz przycisk + Dodaj zasób w lewym górnym rogu.
Wybierz zasób foundry, którego chcesz użyć, a następnie wybierz pozycję Dalej>Zapisz.
Upewnij się, że pole wyboru Włącz automatyczne wdrażanie wymaganych modeli, jeśli żadne ustawienia domyślne nie są dostępne jest zaznaczone. Ten wybór umożliwia usłudze Content Understanding Studio wdrożenie modelu standardowego, modelu mini i modelu osadzeń dla tego zasobu. Różne analizatory wymagają różnych modeli. Aby zapoznać się z bieżącą listą, zobacz Obsługiwane modele generowania.
- Program cURL zainstalowany dla środowiska deweloperskiego.
Rozpocznij pracę z wstępnie utworzonym analizatorem
W tym szybkim przewodniku użyto wbudowanych analizatorów — nie jest wymagana żadna konfiguracja. Aby dowiedzieć się, jak dostosować analizatory do własnych potrzeb, zobacz wstępnie utworzone analizatory.
Wysyłanie pliku do analizy
Przed uruchomieniem następującego polecenia cURL wprowadź następujące zmiany w żądaniu HTTP:
- Zastąp
{endpoint}i{key}odpowiednimi wartościami z wystąpienia usługi Foundry w portalu Azure.
Żądanie POST
W tym przykładzie użyto analizatora prebuilt-invoice do wyodrębnienia danych strukturalnych z dokumentu faktury.
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"}]
}'
Dokumentacja: Analizatory zawartości — analizowanie
Odpowiedź POST
Nagłówek odpowiedzi zawiera Operation-Location pole, które służy do pobierania wyników operacji analizy asynchronicznej.
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
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
Ważne
Skopiuj adres URL lokalizacji operacji z nagłówka odpowiedzi. Użyjesz tego adresu URL w następnym kroku, aby pobrać wyniki analizy.
Uzyskiwanie wyniku analizy
Użyj Operation-Location z POST odpowiedzi i pobierz wynik analizy. Pomyślna odpowiedź zwraca dane z wyodrębnionymi polami w obiekcie status: "Succeeded"result.
Żądanie GET
curl -i -X GET "{endpoint}/contentunderstanding/analyzerResults/{request-id}?api-version=2025-11-01" \
-H "Ocp-Apim-Subscription-Key: {key}"
Dokumentacja: Wyniki analizatora — pobierz
Odpowiedź GET
Odpowiedź JSON 200 (OK) zawiera status pole. Jeśli operacja nie została ukończona, status jest Running lub NotStarted. Odpytywaj adres URL co 1–2 sekundy, aż status stanie się Succeeded.
Aby uwzględnić opcjonalne informacje o wywołaniu modelu i opóźnieniach w odpowiedzi GA, dodaj nagłówek x-ms-diagnostics: true do każdego żądania odpytywania. Informacje na temat różnic między wersjami i obsługi odpowiedzi można znaleźć w sekcji Pobieranie danych diagnostycznych analizy.
{
"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)"
],
"analyzerId": "prebuilt-invoice",
"mimeType": "application/pdf"
}
]
},
"usage": {
"documentPagesStandard": 1,
"contextualizationTokens": 2345,
"tokens": {
"gpt-5.2-input": 1234,
"gpt-5.2-output": 567
}
}
}
Wskazówka
W przypadku korzystania z analizatora wideo ramki kluczowe są zwracane jako adresy URL w odpowiedzi JSON (na przykład w obszarze result.contents.frames[]). Pobierz ramki kluczy przy użyciu standardowego żądania HTTP GET :
curl -O "<keyframeUrl>"
Biblioteka | klientaPrzykłady | Źródło zestawu SDK
Ten przewodnik szybkiego startu pokazuje, jak wyodrębnić ustrukturyzowane dane za pomocą zestawu SDK Content Understanding Python, korzystając z wstępnie zbudowanych analizatorów z plików dokumentów, obrazów, audio i wideo. Aby dowiedzieć się więcej na temat wstępnie utworzonych analizatorów i innych funkcji, zobacz dokumentację wstępnie utworzonych analizatorów.
Wymagania wstępne
- Aktywna subskrypcja Azure. Jeśli nie masz konta Azure, utwórz je bezpłatnie.
- Zasób Microsoft Foundry utworzony w obsługiwanym regionie.
- Punkt końcowy zasobu i klucz interfejsu API (znajdujący się w obszarze Klucze i punkt końcowy w portalu Azure).
- Domyślne ustawienia wdrożenia modelu skonfigurowane dla zasobu. Aby uzyskać instrukcje dotyczące konfiguracji, zobacz Models and deployments lub ten jednorazowy skrypt configuration.
- Python 3.9 lub nowszy.
Konfiguracja
Zainstaluj bibliotekę klienta Content Understanding dla Python za pomocą narzędzia pip:
pip install --pre azure-ai-contentunderstandingOpcjonalnie zainstaluj bibliotekę Azure Identity na potrzeby uwierzytelniania Microsoft Entra:
pip install azure-identity
Konfigurowanie zmiennych środowiskowych
Aby uwierzytelnić się w usłudze Content Understanding, przed uruchomieniem przykładu ustaw zmienne środowiskowe na własne wartości:
-
CONTENTUNDERSTANDING_ENDPOINT— punkt końcowy zasobu Content Understanding. -
CONTENTUNDERSTANDING_KEY— klucz interfejsu API usługi Content Understanding (opcjonalnie, jeśli używasz 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"
Tworzenie klienta
ContentUnderstandingClient jest głównym punktem wejścia do interakcji z usługą. Utwórz wystąpienie, podając punkt dostępowy i dane uwierzytelniające.
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))
Rozpocznij pracę z wstępnie utworzonym analizatorem
Analizatory definiują sposób przetwarzania zawartości oraz wyodrębniane szczegółowe informacje. Oferujemy gotowe do użycia analizatory dla typowych przypadków użycia. Możesz dostosować wstępnie utworzone analizatory , aby lepiej dopasować je do konkretnych potrzeb i przypadków użycia. Ten przewodnik szybkiego startu używa wstępnie zbudowanych analizatorów faktur, obrazów, dźwięku i wideo, aby ułatwić Ci rozpoczęcie pracy.
W tym przykładzie użyto analizatora prebuilt-invoice do wyodrębnienia danych strukturalnych z dokumentu faktury.
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}")
Spowoduje to wygenerowanie następujących danych wyjściowych:
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
Uwaga
Ten kod jest oparty na przykładzie sample_analyze_invoice.py w repozytorium zestawu SDK.
Biblioteka | klientaPrzykłady | Źródło zestawu SDK
W tym przewodniku szybkiego startu pokazano, jak za pomocą biblioteki SDK .NET dla usługi Content Understanding wyodrębnić dane ustrukturyzowane, używając wbudowanych analizatorów z plików dokumentów, obrazów, audio i wideo. Aby dowiedzieć się więcej na temat wstępnie utworzonych analizatorów i innych funkcji, zobacz dokumentację wstępnie utworzonych analizatorów.
Wymagania wstępne
- Aktywna subskrypcja Azure. Jeśli nie masz konta Azure, utwórz je bezpłatnie.
- Zasób Microsoft Foundry utworzony w obsługiwanym regionie.
- Punkt końcowy zasobu i klucz interfejsu API (znajdujący się w obszarze Klucze i punkt końcowy w portalu Azure).
- Domyślne ustawienia wdrożenia modelu skonfigurowane dla zasobu. Aby uzyskać instrukcje dotyczące konfiguracji, zobacz Models and deployments lub ten jednorazowy skrypt configuration.
- Bieżąca wersja .NET.
Konfiguracja
Utwórz nową aplikację konsolową .NET:
dotnet new console -n ContentUnderstandingQuickstart cd ContentUnderstandingQuickstartZainstaluj bibliotekę klienta usługi Content Understanding dla .NET:
dotnet add package Azure.AI.ContentUnderstanding --prereleaseOpcjonalnie zainstaluj bibliotekę Azure Identity na potrzeby uwierzytelniania Microsoft Entra:
dotnet add package Azure.Identity
Konfigurowanie zmiennych środowiskowych
Aby uwierzytelnić się w usłudze Content Understanding, przed uruchomieniem przykładu ustaw zmienne środowiskowe na własne wartości:
-
CONTENTUNDERSTANDING_ENDPOINT— punkt końcowy zasobu Content Understanding. -
CONTENTUNDERSTANDING_KEY— klucz interfejsu API usługi Content Understanding (opcjonalnie, jeśli używasz 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"
Tworzenie klienta
ContentUnderstandingClient jest głównym punktem wejścia do interakcji z usługą. Utwórz wystąpienie, podając punkt dostępowy i dane uwierzytelniające.
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)
);
Rozpocznij pracę z wstępnie utworzonym analizatorem
Analizatory definiują sposób przetwarzania zawartości oraz wyodrębniane szczegółowe informacje. Oferujemy gotowe do użycia analizatory dla typowych przypadków użycia. Możesz dostosować wstępnie utworzone analizatory , aby lepiej dopasować je do konkretnych potrzeb i przypadków użycia. Ten przewodnik szybkiego startu używa wstępnie zbudowanych analizatorów faktur, obrazów, dźwięku i wideo, aby ułatwić Ci rozpoczęcie pracy.
W tym przykładzie użyto analizatora prebuilt-invoice do wyodrębnienia danych strukturalnych z dokumentu faktury.
// 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"})");
}
}
}
Spowoduje to wygenerowanie następujących danych wyjściowych:
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)
Uwaga
Ten kod jest oparty na przykładzie AnalyzeInvoice w repozytorium zestawu SDK.
Biblioteka | klientaPrzykłady | Źródło zestawu SDK
W tym przewodniku Szybkiego startu pokazano, jak użyć zestawu SDK Content Understanding Java do wyodrębniania danych ustrukturyzowanych przy użyciu wstępnie skonfigurowanych analizatorów z plików dokumentów, obrazów, dźwięku i wideo. Aby dowiedzieć się więcej na temat wstępnie utworzonych analizatorów i innych funkcji, zobacz dokumentację wstępnie utworzonych analizatorów.
Wymagania wstępne
- Aktywna subskrypcja Azure. Jeśli nie masz konta Azure, utwórz je bezpłatnie.
- Zasób Microsoft Foundry utworzony w obsługiwanym regionie.
- Punkt końcowy zasobu i klucz interfejsu API (znajdujący się w obszarze Klucze i punkt końcowy w portalu Azure).
- Domyślne ustawienia wdrożenia modelu skonfigurowane dla zasobu. Aby uzyskać instrukcje dotyczące konfiguracji, zobacz Models and deployments lub ten jednorazowy skrypt configuration.
- Java Development Kit (JDK) w wersji 8 lub nowszej.
- Apache Maven.
Konfiguracja
Utwórz nowy projekt Maven:
mvn archetype:generate -DgroupId=com.example \ -DartifactId=content-understanding-quickstart \ -DarchetypeArtifactId=maven-archetype-quickstart \ -DinteractiveMode=false cd content-understanding-quickstartDodaj zależność usługi Content Understanding do pliku pom.xml w
<dependencies>sekcji:<dependency> <groupId>com.azure</groupId> <artifactId>azure-ai-contentunderstanding</artifactId> <version>1.1.0-beta.3</version> </dependency>Opcjonalnie dodaj bibliotekę Azure Identity na potrzeby uwierzytelniania Microsoft Entra:
<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.14.2</version> </dependency>
Konfigurowanie zmiennych środowiskowych
Aby uwierzytelnić się w usłudze Content Understanding, przed uruchomieniem przykładu ustaw zmienne środowiskowe na własne wartości:
-
CONTENTUNDERSTANDING_ENDPOINT— punkt końcowy zasobu Content Understanding. -
CONTENTUNDERSTANDING_KEY— klucz interfejsu API usługi Content Understanding (opcjonalnie, jeśli używasz 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"
Tworzenie klienta
ContentUnderstandingClient jest głównym punktem wejścia do interakcji z usługą. Utwórz wystąpienie, podając punkt dostępowy i dane uwierzytelniające.
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();
Rozpocznij pracę z wstępnie utworzonym analizatorem
Analizatory definiują sposób przetwarzania zawartości oraz wyodrębniane szczegółowe informacje. Oferujemy gotowe do użycia analizatory dla typowych przypadków użycia. Możesz dostosować wstępnie utworzone analizatory , aby lepiej dopasować je do konkretnych potrzeb i przypadków użycia. Ten przewodnik szybkiego startu używa wstępnie zbudowanych analizatorów faktur, obrazów, dźwięku i wideo, aby ułatwić Ci rozpoczęcie pracy.
W tym przykładzie użyto analizatora prebuilt-invoice do wyodrębnienia danych strukturalnych z dokumentu faktury.
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
}
}
Spowoduje to wygenerowanie następujących danych wyjściowych:
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
Uwaga
Ten kod jest oparty na przykładzie AnalyzeInvoice](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/contentunderstanding/azure-ai-contentunderstanding/src/samples/java/com/azure/ai/contentunderstanding/samples/Sample03_AnalyzeInvoice.java) w repozytorium zestawu SDK.
Biblioteka | klientaPrzykłady | Źródło zestawu SDK
Ten przewodnik pokazuje, jak użyć zestawu SDK JavaScript Content Understanding do wyodrębniania danych strukturalnych za pomocą wstępnie przygotowanych analizatorów z plików dokumentów, obrazów, dźwięku i wideo. Aby dowiedzieć się więcej na temat wstępnie utworzonych analizatorów i innych funkcji, zobacz dokumentację wstępnie utworzonych analizatorów.
Wymagania wstępne
- Aktywna subskrypcja Azure. Jeśli nie masz konta Azure, utwórz je bezpłatnie.
- Zasób Microsoft Foundry utworzony w obsługiwanym regionie.
- Punkt końcowy zasobu i klucz interfejsu API (znajdujący się w obszarze Klucze i punkt końcowy w portalu Azure).
- Domyślne ustawienia wdrożenia modelu skonfigurowane dla zasobu. Aby uzyskać instrukcje dotyczące konfiguracji, zobacz Models and deployments lub ten jednorazowy skrypt configuration.
- Node.js Wersja LTS.
Konfiguracja
Utwórz nowy projekt Node.js:
mkdir content-understanding-quickstart cd content-understanding-quickstart npm init -yZainstaluj bibliotekę klienta usługi Content Understanding:
npm install @azure/ai-content-understanding@nextOpcjonalnie zainstaluj bibliotekę Azure Identity na potrzeby uwierzytelniania Microsoft Entra:
npm install @azure/identity
Konfigurowanie zmiennych środowiskowych
Aby uwierzytelnić się w usłudze Content Understanding, przed uruchomieniem przykładu ustaw zmienne środowiskowe na własne wartości:
-
CONTENTUNDERSTANDING_ENDPOINT— punkt końcowy zasobu Content Understanding. -
CONTENTUNDERSTANDING_KEY— klucz interfejsu API usługi Content Understanding (opcjonalnie, jeśli używasz 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"
Tworzenie klienta
ContentUnderstandingClient jest głównym punktem wejścia do interakcji z usługą. Utwórz wystąpienie, podając punkt dostępowy i dane uwierzytelniające.
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)
);
Rozpocznij pracę z wstępnie utworzonym analizatorem
Analizatory definiują sposób przetwarzania zawartości oraz wyodrębniane szczegółowe informacje. Oferujemy gotowe do użycia analizatory dla typowych przypadków użycia. Możesz dostosować wstępnie utworzone analizatory , aby lepiej dopasować je do konkretnych potrzeb i przypadków użycia. Ten przewodnik szybkiego startu używa wstępnie zbudowanych analizatorów faktur, obrazów, dźwięku i wideo, aby ułatwić Ci rozpoczęcie pracy.
W tym przykładzie użyto analizatora prebuilt-invoice do wyodrębnienia danych strukturalnych z dokumentu faktury.
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);
});
Spowoduje to wygenerowanie następujących danych wyjściowych:
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
Uwaga
Ten kod jest oparty na przykładzie analyzeInvoice.js w repozytorium zestawu SDK.
Biblioteka | klientaPrzykłady | Źródło zestawu SDK
W tym szybkim starcie pokazano, jak używać zestawu SDK Content Understanding TypeScript do wyodrębniania danych ustrukturyzowanych przy użyciu wstępnie utworzonych analizatorów z plików dokumentów, obrazów, audio i wideo. Aby dowiedzieć się więcej na temat wstępnie utworzonych analizatorów i innych funkcji, zobacz dokumentację wstępnie utworzonych analizatorów.
Wymagania wstępne
- Aktywna subskrypcja Azure. Jeśli nie masz konta Azure, utwórz je bezpłatnie.
- Zasób Microsoft Foundry utworzony w obsługiwanym regionie.
- Punkt końcowy zasobu i klucz interfejsu API (znajdujący się w obszarze Klucze i punkt końcowy w portalu Azure).
- Domyślne ustawienia wdrożenia modelu skonfigurowane dla zasobu. Aby uzyskać instrukcje dotyczące konfiguracji, zobacz Models and deployments lub ten jednorazowy skrypt configuration.
- Node.js Wersja LTS.
- Typescript 5.x lub nowszy.
Konfiguracja
Utwórz nowy projekt Node.js:
mkdir content-understanding-quickstart cd content-understanding-quickstart npm init -yZainstaluj język TypeScript i bibliotekę klienta Content Understanding:
npm install typescript ts-node @azure/ai-content-understanding@nextOpcjonalnie zainstaluj bibliotekę Azure Identity na potrzeby uwierzytelniania Microsoft Entra:
npm install @azure/identity
Konfigurowanie zmiennych środowiskowych
Aby uwierzytelnić się w usłudze Content Understanding, przed uruchomieniem przykładu ustaw zmienne środowiskowe na własne wartości:
-
CONTENTUNDERSTANDING_ENDPOINT— punkt końcowy zasobu Content Understanding. -
CONTENTUNDERSTANDING_KEY— klucz interfejsu API usługi Content Understanding (opcjonalnie, jeśli używasz 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"
Tworzenie klienta
ContentUnderstandingClient jest głównym punktem wejścia do interakcji z usługą. Utwórz wystąpienie, podając punkt dostępowy i dane uwierzytelniające.
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)
);
Rozpocznij pracę z wstępnie utworzonym analizatorem
Analizatory definiują sposób przetwarzania zawartości oraz wyodrębniane szczegółowe informacje. Oferujemy gotowe do użycia analizatory dla typowych przypadków użycia. Możesz dostosować wstępnie utworzone analizatory , aby lepiej dopasować je do konkretnych potrzeb i przypadków użycia. Ten przewodnik szybkiego startu używa wstępnie zbudowanych analizatorów faktur, obrazów, dźwięku i wideo, aby ułatwić Ci rozpoczęcie pracy.
W tym przykładzie użyto analizatora prebuilt-invoice do wyodrębnienia danych strukturalnych z dokumentu faktury.
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);
});
Spowoduje to wygenerowanie następujących danych wyjściowych:
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
Uwaga
Ten kod jest oparty na przykładzie analyzeInvoice.ts w repozytorium zestawu SDK.
Następne kroki
- Zapoznaj się z więcej przykładów zestawu SDK Python
- Poznaj więcej przykładów zestawu .NET SDK
- Poznaj więcej przykładów zestawu SDK Java
- Zapoznaj się z więcej przykładów zestawu SDK JavaScript
- Poznaj więcej przykładów zestawu SDK TypeScript
- Tworzenie analizatora niestandardowego
- Wbudowane analizatory
- Obsługa języków i regionów