Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
Extrai conteúdo, layout e dados estruturados de documentos.
Por favor, confie muito em nossos documentos de cliente REST para usar esta biblioteca
NOTA: O Form Recognizer foi renomeado para Document Intelligence. Consulte o Guia de Migração de de
@azure/ai-form-recognizer
para@azure-rest/ai-document-intelligence
.
Ligações principais:
- Código fonte
- Pacote (NPM)
- documentação de referência da API
- Amostras
- do Changelog
- Guia de migração do Form Recognizer
Esta versão da biblioteca de cliente assume como padrão a versão
"2024-11-30"
do serviço.
Esta tabela mostra a relação entre as versões do SDK e as versões de API suportadas do serviço:
Versão do SDK | Versão do serviço da API suportada |
---|---|
1.0.0 | 2024-11-30 |
Confie na biblioteca de
@azure/ai-form-recognizer
mais antiga por meio das versões mais antigas da API de serviço para modelos aposentados, como"prebuilt-businessCard"
e"prebuilt-document"
. Para obter mais informações, consulte Changelog.
A tabela abaixo descreve o relacionamento de cada cliente e sua(s) versão(ões) de API suportada(s):
Versão da API de serviço | Clientes suportados | Embalagem |
---|---|---|
2024-11-30 | DocumentIntelligenceClient |
@azure-rest/ai-document-intelligence versão ^1.0.0 |
2023-07-31 | DocumentAnalysisClient e DocumentModelAdministrationClient |
@azure/ai-form-recognizer versão ^5.0.0 |
2022-08-01 | DocumentAnalysisClient e DocumentModelAdministrationClient |
@azure/ai-form-recognizer versão ^4.0.0 |
Primeiros passos
Ambientes atualmente suportados
- Versões LTS do Node.js
Pré-requisitos
- Você deve ter um de assinatura do
Azure para usar este pacote.
Instalar o pacote @azure-rest/ai-document-intelligence
Instale a biblioteca de cliente REST do cliente REST do Azure DocumentIntelligence(formerlyFormRecognizer) para JavaScript com npm
:
npm install @azure-rest/ai-document-intelligence
Criar e autenticar um DocumentIntelligenceClient
Para usar uma credencial de token do
Para autenticar com o AAD, você deve primeiro npm
instalar o @azure/identity
Após a configuração, você pode escolher qual tipo de credencial de @azure/identity
usar.
Como exemplo, DefaultAzureCredential pode ser usado para autenticar o cliente.
Defina os valores do ID do cliente, ID do locatário e segredo do cliente do aplicativo AAD como variáveis de ambiente: AZURE_CLIENT_ID, AZURE_TENANT_ID AZURE_CLIENT_SECRET
Usando uma credencial de token
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
new DefaultAzureCredential(),
);
Usando uma chave de API
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
const client = DocumentIntelligence(process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"], {
key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"],
});
Nuvens Soberanas
Conecte-se a ambientes de nuvem alternativos do Azure (como Azure China ou Azure Government) especificando o scopes
credentials
campo na opção e use o valor apropriado de 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 você não especificar scopes
, o cliente assumirá como padrão a Nuvem Pública do Azure (https://cognitiveservices.azure.com
).
Modelos de Documentos
Analisar layout pré-construído (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" },
});
Analisar layout pré-construído (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);
Análise de lotes
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 de conteúdo Markdown
Suporta saída com o formato de conteúdo Markdown, juntamente com o texto simples padrão. Por enquanto, isso só é suportado para "layout pré-construído". O formato de conteúdo Markdown é considerado um formato mais amigável para o consumo de LLM em um cenário de uso de bate-papo ou automação.
O serviço segue a especificação GFM (GitHub Flavored Markdown) para o formato Markdown. Também introduz uma nova propriedade contentFormat com o valor "text" ou "markdown" para indicar o formato de conteúdo do resultado.
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
});
Campos de consulta
Quando esse sinalizador de recurso é especificado, o serviço extrai ainda mais os valores dos campos especificados por meio do parâmetro de consulta queryFields para complementar quaisquer campos existentes definidos pelo modelo como 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
});
Opções de divisão
Nas versões anteriores da API suportadas pela biblioteca de @azure/ai-form-recognizer
mais antiga, a operação de divisão e classificação de documentos ("/documentClassifiers/{classifierId}:analyze"
) sempre tentava dividir o arquivo de entrada em vários documentos.
Para permitir um conjunto mais amplo de cenários, o serviço introduz um parâmetro de consulta "dividido" com a nova versão do serviço "2023-10-31-preview". Os seguintes valores são suportados:
split: "auto"
Deixe o serviço determinar onde dividir.
split: "none"
Todo o ficheiro é tratado como um único documento. Nenhuma divisão é realizada.
split: "perPage"
Cada página é tratada como um documento separado. Cada página vazia é mantida como seu próprio documento.
Classificadores de documentos #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);
Obtenha a saída PDF gerada a partir da análise de documentos
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);
Obter a imagem cortada gerada da figura especificada a partir da análise do documento
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);
Obter informações
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);
Listar modelos de documentos
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);
}
Solução de problemas
Registo
Habilitar o registro em log pode ajudar a descobrir informações úteis sobre falhas. Para ver um log de solicitações e respostas HTTP, defina a variável de ambiente AZURE_LOG_LEVEL
como info
. Como alternativa, o registro em log pode ser habilitado em tempo de execução chamando setLogLevel
no @azure/logger
:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
Para obter instruções mais detalhadas sobre como habilitar logs, você pode consultar os documentos do pacote @azure/logger.
Azure SDK for JavaScript