Anteckning
Åtkomst till den här sidan kräver auktorisering. Du kan prova att logga in eller ändra kataloger.
Åtkomst till den här sidan kräver auktorisering. Du kan prova att ändra kataloger.
Extraherar innehåll, layout och strukturerade data från dokument.
Vi förlitar dig mycket på våra REST-klientdokument för att kunna använda det här biblioteket
Obs! Formulärigenkänning har bytt namn till Dokumentinformation. Kontrollera migreringsguiden för från
@azure/ai-form-recognizertill@azure-rest/ai-document-intelligence.
Nyckellänkar:
Den här versionen av klientbiblioteket är som standard den
"2024-11-30"versionen av tjänsten.
Den här tabellen visar relationen mellan SDK-versioner och API-versioner som stöds av tjänsten:
| SDK-version | API-version av tjänsten som stöds |
|---|---|
| 1.0.0 | 2024-11-30 |
Förlita dig på det äldre
@azure/ai-form-recognizer-biblioteket via de äldre tjänst-API-versionerna för tillbakadragna modeller, till exempel"prebuilt-businessCard"och"prebuilt-document". Mer information finns i Changelog.
Tabellen nedan beskriver relationen mellan varje klient och dess API-versioner som stöds:
| Tjänst-API-version | Klienter som stöds | Paket |
|---|---|---|
| 2024-11-30 | DocumentIntelligenceClient (på engelska) |
@azure-rest/ai-document-intelligence version ^1.0.0 |
| 2023-07-31 | DocumentAnalysisClient och DocumentModelAdministrationClient |
@azure/ai-form-recognizer version ^5.0.0 |
| 2022-08-01 | DocumentAnalysisClient och DocumentModelAdministrationClient |
@azure/ai-form-recognizer version ^4.0.0 |
Komma igång
Miljöer som stöds för närvarande
- LTS-versioner av Node.js
Förutsättningar
- Du måste ha en Azure-prenumeration för att kunna använda det här paketet.
Installera @azure-rest/ai-document-intelligence-paketet
Installera REST-klientbiblioteket för Rest-klienten i Azure DocumentIntelligence (tidigareFormRecognizer) för JavaScript med npm:
npm install @azure-rest/ai-document-intelligence
Skapa och autentisera en DocumentIntelligenceClient
Om du vill använda en AAD-tokenautentiseringsuppgifter (Azure Active Directory)anger du en instans av önskad typ av autentiseringsuppgifter som hämtats från @azure/identitetsbiblioteket.
Om du vill autentisera med AAD måste du först npm installera @azure/identity
Efter installationen kan du välja vilken typ av autentiseringsuppgifter från @azure/identity att använda.
Till exempel kan StandardAzureCredential användas för att autentisera klienten.
Ange värdena för klient-ID, klient-ID och klienthemlighet för AAD-programmet som miljövariabler: AZURE_CLIENT_ID, AZURE_TENANT_ID AZURE_CLIENT_SECRET
Använda en tokenautentiseringsuppgift
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
Använda en API-NYCKEL
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
const client = DocumentIntelligence(process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"], {
key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"],
});
Suveräna moln
Anslut till alternativa Azure-molnmiljöer (till exempel Azure China eller Azure Government) genom att ange fältet scopes i credentials alternativet och använd lämpligt värde från 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]
}
}
);
Om du inte anger scopeskommer klienten som standard att använda det offentliga Azure-molnet (https://cognitiveservices.azure.com).
Dokumentmodeller
Analysera fördefinierad layout (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" },
});
Analysera fördefinierad layout (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);
Batchanalys
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);
Markdown-innehållsformat
Stöder utdata med Markdown-innehållsformat tillsammans med standardformatet oformaterad text. För tillfället stöds detta endast för "fördefinierad layout". Markdown-innehållsformat anses vara ett mer användarvänligt format för LLM-förbrukning i ett chatt- eller automationsanvändningsscenario.
Tjänsten följer GFM-specifikationen (GitHub Flavored Markdown) för Markdown-formatet. Introducerar även en ny contentFormat-egenskap med värdet "text" eller "markdown" för att ange resultatinnehållsformatet.
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
});
Frågefält
När den här funktionsflaggan har angetts extraherar tjänsten ytterligare värdena för de fält som anges via frågeparametern queryFields för att komplettera befintliga fält som definieras av modellen som reserv.
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
});
Delningsalternativ
I de tidigare API-versionerna som stöds av det äldre @azure/ai-form-recognizer biblioteket försökte dokumentdelnings- och klassificeringsåtgärden ("/documentClassifiers/{classifierId}:analyze") alltid dela upp indatafilen i flera dokument.
För att aktivera en bredare uppsättning scenarier introducerar tjänsten en "delad" frågeparameter med den nya tjänstversionen "2023-10-31-preview". Följande värden stöds:
split: "auto"Låt tjänsten avgöra var du ska dela upp.
split: "none"Hela filen behandlas som ett enda dokument. Ingen delning utförs.
split: "perPage"Varje sida behandlas som ett separat dokument. Varje tom sida behålls som ett eget dokument.
Dokumentklassificerare #Build
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);
Hämta genererade PDF-utdata från dokumentanalys
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);
Hämta den genererade beskurna bilden av den angivna figuren från dokumentanalys
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);
Hämta information
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);
Lista dokumentmodeller
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);
}
Felsökning
Skogsavverkning
Aktivering av loggning kan hjälpa dig att hitta användbar information om fel. Om du vill se en logg med HTTP-begäranden och svar anger du AZURE_LOG_LEVEL miljövariabeln till info. Du kan också aktivera loggning vid körning genom att anropa setLogLevel i @azure/logger:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
Mer detaljerade anvisningar om hur du aktiverar loggar finns i @azure/logger-paketdokumenten.
Azure SDK for JavaScript