Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Estrae contenuto, layout e dati strutturati dai documenti.
NOTA: Riconoscimento modulo è stato rinominato in Document Intelligence. Controllare la Guida alla migrazione di da
@azure/ai-form-recognizera@azure-rest/ai-document-intelligence.
Collegamenti chiave:
- codice sorgente
- del pacchetto
- documentazione di riferimento dell'API
- esempi di
- log delle modifiche
- Guida alla migrazione di da Riconoscimento modulo
Questa versione della libreria client usa per impostazione predefinita la versione
"2024-11-30"del servizio.
Questa tabella illustra la relazione tra le versioni dell'SDK e le versioni API supportate del servizio:
| Versione dell'SDK | Versione api supportata del servizio |
|---|---|
| 1.0.0 | 2024-11-30 |
Fare affidamento sulla libreria di
@azure/ai-form-recognizerprecedente tramite le versioni precedenti dell'API del servizio per i modelli ritirati, ad esempio"prebuilt-businessCard"e"prebuilt-document". Per altre informazioni, vedere Changelog.
La tabella seguente descrive la relazione tra ogni client e le relative versioni API supportate:
| Versione dell'API del servizio | Client supportati | Pacco |
|---|---|---|
| 2024-11-30 | DocumentIntelligenceClient |
@azure-rest/ai-document-intelligence versione ^1.0.0 |
| 2023-07-31 | DocumentAnalysisClient e DocumentModelAdministrationClient |
@azure/ai-form-recognizer versione ^5.0.0 |
| 2022-08-01 | DocumentAnalysisClient e DocumentModelAdministrationClient |
@azure/ai-form-recognizer versione ^4.0.0 |
Introduttiva
Ambienti attualmente supportati
- Versioni LTS di Node.js
Prerequisiti
Installare il pacchetto @azure-rest/ai-document-intelligence
Installare la libreria client REST client REST documentIntelligence(in precedenzaFormRecognizer) per JavaScript con npm:
npm install @azure-rest/ai-document-intelligence
Creare ed autenticare un DocumentIntelligenceClient
Per usare un
Per eseguire l'autenticazione con AAD, è prima necessario installare npm@azure/identity
Dopo l'installazione, è possibile scegliere il tipo di credenziali da @azure/identity da usare.
Ad esempio, è possibile usare DefaultAzureCredential per autenticare il client.
Impostare i valori dell'ID client, dell'ID tenant e del segreto client dell'applicazione AAD come variabili di ambiente: AZURE_CLIENT_ID, AZURE_TENANT_ID AZURE_CLIENT_SECRET
Uso di una credenziale token
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
Uso di una CHIAVE API
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
const client = DocumentIntelligence(process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"], {
key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"],
});
Cloud sovrani
Connettersi ad ambienti cloud Azure alternativi (ad esempio Azure Cina o Azure per enti pubblici) specificando il scopes campo nell'opzione credentials e utilizzare il valore appropriato da KnownDocumentIntelligenceAudience.
import DocumentIntelligence, { KnownDocumentIntelligenceAudience } from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
{
credentials: {
// Use the correct audience for your cloud environment
scopes: [KnownDocumentIntelligenceAudience.AzureGovernment]
}
}
);
Se non si specifica scopes, il client utilizzerà per impostazione predefinita il cloud pubblico di Azure (https://cognitiveservices.azure.com).
Modelli di documento
Analizzare il layout predefinito (urlSource)
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
const initialResponse = await client
.path("/documentModels/{modelId}:analyze", "prebuilt-layout")
.post({
contentType: "application/json",
body: {
urlSource:
"https://raw.githubusercontent.com/Azure/azure-sdk-for-js/6704eff082aaaf2d97c1371a28461f512f8d748a/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf",
},
queryParameters: { locale: "en-IN" },
});
Analizzare il layout predefinito (base64Source)
import DocumentIntelligence, {
isUnexpected,
getLongRunningPoller,
AnalyzeOperationOutput,
} from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
import { join } from "node:path";
import { readFile } from "node:fs/promises";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
const filePath = join("./assets", "forms", "Invoice_1.pdf");
const base64Source = await readFile(filePath, { encoding: "base64" });
const initialResponse = await client
.path("/documentModels/{modelId}:analyze", "prebuilt-layout")
.post({
contentType: "application/json",
body: {
base64Source,
},
queryParameters: { locale: "en-IN" },
});
if (isUnexpected(initialResponse)) {
throw initialResponse.body.error;
}
const poller = getLongRunningPoller(client, initialResponse);
const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;
console.log(result);
Analisi batch
import DocumentIntelligence, {
isUnexpected,
parseResultIdFromResponse,
} from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
// 1. Analyze a batch of documents
const initialResponse = await client
.path("/documentModels/{modelId}:analyzeBatch", "prebuilt-layout")
.post({
contentType: "application/json",
body: {
azureBlobSource: {
containerUrl: process.env["DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_CONTAINER_SAS_URL"],
},
resultContainerUrl:
process.env["DOCUMENT_INTELLIGENCE_BATCH_TRAINING_DATA_RESULT_CONTAINER_SAS_URL"],
resultPrefix: "result",
},
});
if (isUnexpected(initialResponse)) {
throw initialResponse.body.error;
}
const resultId = parseResultIdFromResponse(initialResponse);
console.log("resultId: ", resultId);
// (Optional) You can poll for the batch analysis result but be aware that a job may take unexpectedly long time, and polling could incur additional costs.
// const poller = getLongRunningPoller(client, initialResponse);
// await poller.pollUntilDone();
// 2. At a later time, you can retrieve the operation result using the resultId
const output = await client
.path("/documentModels/{modelId}/analyzeResults/{resultId}", "prebuilt-layout", resultId)
.get();
console.log(output);
Formato del contenuto Markdown
Supporta l'output con formato di contenuto Markdown insieme al testo normale predefinito . Per il momento, questa opzione è supportata solo per "precompilt-layout". Il formato di contenuto Markdown viene considerato un formato più descrittivo per l'utilizzo LLM in uno scenario di utilizzo di chat o automazione.
Il servizio segue la specifica GFM (GitHub Flavored Markdown) per il formato Markdown. Introduce anche una nuova proprietà contentFormat con valore "text" o "markdown" per indicare il formato del contenuto del risultato.
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
const initialResponse = await client
.path("/documentModels/{modelId}:analyze", "prebuilt-layout")
.post({
contentType: "application/json",
body: {
urlSource:
"https://raw.githubusercontent.com/Azure/azure-sdk-for-js/6704eff082aaaf2d97c1371a28461f512f8d748a/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf",
},
queryParameters: { outputContentFormat: "markdown" }, // <-- new query parameter
});
Campi di query
Quando si specifica questo flag di funzionalità, il servizio estrae ulteriormente i valori dei campi specificati tramite il parametro di query queryFields per integrare eventuali campi esistenti definiti dal modello come fallback.
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
await client.path("/documentModels/{modelId}:analyze", "prebuilt-layout").post({
contentType: "application/json",
body: { urlSource: "..." },
queryParameters: {
features: ["queryFields"],
queryFields: ["NumberOfGuests", "StoreNumber"],
}, // <-- new query parameter
});
Opzioni di divisione
Nelle versioni precedenti dell'API supportate dalla raccolta di @azure/ai-form-recognizer precedente, l'operazione di suddivisione e classificazione dei documenti ("/documentClassifiers/{classifierId}:analyze") ha sempre tentato di suddividere il file di input in più documenti.
Per abilitare un set più ampio di scenari, il servizio introduce un parametro di query "split" con la nuova versione del servizio "2023-10-31-preview". Sono supportati i valori seguenti:
split: "auto"Consentire al servizio di determinare dove suddividere.
split: "none"L'intero file viene considerato come un singolo documento. Non viene eseguita alcuna suddivisione.
split: "perPage"Ogni pagina viene considerata come un documento separato. Ogni pagina vuota viene mantenuta come documento.
#Build classificatori di documenti
import DocumentIntelligence, {
isUnexpected,
getLongRunningPoller,
DocumentClassifierBuildOperationDetailsOutput,
} from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
const containerSasUrl = (): string =>
process.env["DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL"];
const initialResponse = await client.path("/documentClassifiers:build").post({
body: {
classifierId: `customClassifier-12345`,
description: "Custom classifier description",
docTypes: {
foo: {
azureBlobSource: {
containerUrl: containerSasUrl(),
},
},
bar: {
azureBlobSource: {
containerUrl: containerSasUrl(),
},
},
},
},
});
if (isUnexpected(initialResponse)) {
throw initialResponse.body.error;
}
const poller = getLongRunningPoller(client, initialResponse);
const response = (await poller.pollUntilDone())
.body as DocumentClassifierBuildOperationDetailsOutput;
console.log(response);
Ottenere l'output PDF generato dall'analisi dei documenti
import DocumentIntelligence, {
isUnexpected,
getLongRunningPoller,
parseResultIdFromResponse,
streamToUint8Array,
} from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
import { join } from "node:path";
import { readFile, writeFile } from "node:fs/promises";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
const filePath = join("./assets", "layout-pageobject.pdf");
const base64Source = await readFile(filePath, { encoding: "base64" });
const initialResponse = await client
.path("/documentModels/{modelId}:analyze", "prebuilt-read")
.post({
contentType: "application/json",
body: {
base64Source,
},
queryParameters: { output: ["pdf"] },
});
if (isUnexpected(initialResponse)) {
throw initialResponse.body.error;
}
const poller = getLongRunningPoller(client, initialResponse);
await poller.pollUntilDone();
const output = await client
.path(
"/documentModels/{modelId}/analyzeResults/{resultId}/pdf",
"prebuilt-read",
parseResultIdFromResponse(initialResponse),
)
.get()
.asNodeStream(); // output.body would be NodeJS.ReadableStream
if (output.status !== "200" || !output.body) {
throw new Error("The response was unexpected, expected NodeJS.ReadableStream in the body.");
}
const pdfData = await streamToUint8Array(output.body);
await writeFile(`./output.pdf`, pdfData);
Ottenere l'immagine ritagliata generata della figura specificata dall'analisi dei documenti
import DocumentIntelligence, {
isUnexpected,
getLongRunningPoller,
AnalyzeOperationOutput,
parseResultIdFromResponse,
streamToUint8Array,
} from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
import { join } from "node:path";
import { readFile, writeFile } from "node:fs/promises";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
const filePath = join("./assets", "layout-pageobject.pdf");
const base64Source = await readFile(filePath, { encoding: "base64" });
const initialResponse = await client
.path("/documentModels/{modelId}:analyze", "prebuilt-layout")
.post({
contentType: "application/json",
body: {
base64Source,
},
queryParameters: { output: ["figures"] },
});
if (isUnexpected(initialResponse)) {
throw initialResponse.body.error;
}
const poller = getLongRunningPoller(client, initialResponse);
const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;
const figures = result.analyzeResult?.figures;
const figureId = figures?.[0].id || "";
const output = await client
.path(
"/documentModels/{modelId}/analyzeResults/{resultId}/figures/{figureId}",
"prebuilt-layout",
parseResultIdFromResponse(initialResponse),
figureId,
)
.get()
.asNodeStream(); // output.body would be NodeJS.ReadableStream
if (output.status !== "200" || !output.body) {
throw new Error("The response was unexpected, expected NodeJS.ReadableStream in the body.");
}
const imageData = await streamToUint8Array(output.body);
await writeFile(`./figures/${figureId}.png`, imageData);
Ottenere informazioni
import DocumentIntelligence, { isUnexpected } from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
const response = await client.path("/info").get();
if (isUnexpected(response)) {
throw response.body.error;
}
console.log(response.body.customDocumentModels.limit);
Elencare i modelli di documento
import DocumentIntelligence, { isUnexpected, paginate } from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
const response = await client.path("/documentModels").get();
if (isUnexpected(response)) {
throw response.body.error;
}
for await (const model of paginate(client, response)) {
console.log(model.modelId);
}
Risoluzione dei problemi
Registrazione
L'abilitazione della registrazione può aiutare a individuare informazioni utili sugli errori. Per visualizzare un log di richieste e risposte HTTP, impostare la variabile di ambiente AZURE_LOG_LEVEL su info. In alternativa, la registrazione può essere abilitata in fase di esecuzione chiamando setLogLevel nel @azure/logger:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
Per istruzioni più dettagliate su come abilitare i log, è possibile esaminare la documentazione del pacchetto @azure/logger.
Azure SDK for JavaScript