Azure AI Document Intelligence 是一项云服务,它使用机器学习来分析文档中的文本和结构化数据。 它包含以下主要功能:
- 布局 - 从文档中提取文本、表格结构和选择标记及其边界区域坐标。
- 文档 - 使用常规预构建文档模型分析文档中的实体、键值对、表和选择标记。
- 读取 - 读取有关文本元素的信息,例如页面单词和行以及文本语言信息。
- 预生成 - 使用预生成模型分析来自某些类型的常见文档(例如收据、发票、名片或身份文档)的数据。
- 自定义 - 构建自定义模型以从文档中提取文本、字段值、选择标记和表格数据。 自定义模型是使用您自己的数据构建的,因此它们是针对您的文档量身定制的。
- 分类器 - 构建自定义分类器以将文档分类到预定义的类别中。
源代码 | 包(NPM) | API 参考文档 | 产品文档 | 示例
注释
Document Intelligence 服务以前称为“Azure 表单识别器”。这些服务是相同的, @azure/ai-form-recognizer
JavaScript 的包是 Azure AI Document Intelligence 服务的 Azure SDK 包。 在撰写本文时,正在将 Azure 表单识别器重命名为 Azure AI Document Intelligence,因此在某些情况下,“表单识别器”和“Document Intelligence”可以互换使用。
安装 @azure/ai-form-recognizer
包
使用以下命令 npm
安装适用于 JavaScript 的 Azure Document Intelligence 客户端库:
npm install @azure/ai-form-recognizer
入门指南
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
import { createReadStream } from "node:fs";
const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
// Document Intelligence supports many different types of files.
const file = createReadStream("path/to/file.jpg");
const poller = await client.beginAnalyzeDocument("<model ID>", file);
const { pages, tables, styles, keyValuePairs, documents } = await poller.pollUntilDone();
当前支持的环境
- LTS 版本的 Node.js
- Safari、Chrome、Edge 和 Firefox 的最新版本。
有关详细信息,请参阅我们的 支持策略。
先决条件
- 一个 Azure 订阅
- 认知服务或表单识别器资源。 如果需要创建资源,可以使用 Azure 门户 或 Azure CLI。
创建表单识别器资源
注意:在撰写本文时,Azure 门户仍将资源称为“表单识别器”资源。 将来,这可能会更新为“Document Intelligence”资源。 目前,以下文档使用“表单识别器”名称。
Document Intelligence 支持 多服务和单服务访问。 如果计划在单个终结点/密钥下访问多个认知服务,请创建认知服务资源。 若要仅访问表单识别器,请创建表单识别器资源。
您可以使用
选项 1:Azure 门户
选项 2:Azure CLI。
下面是如何使用 CLI 创建表单识别器资源的示例:
# Create a new resource group to hold the Form Recognizer resource -
# if using an existing resource group, skip this step
az group create --name my-resource-group --___location westus2
如果使用 Azure CLI,请将 <your-resource-group-name>
和 <your-resource-name>
替换为自己的唯一名称:
az cognitiveservices account create --kind FormRecognizer --resource-group <your-resource-group-name> --name <your-resource-name> --sku <your-sku-name> --___location <your-___location>
创建客户端并进行身份验证
要与 Document Intelligence 服务交互,您需要选择 a DocumentAnalysisClient
或 a DocumentModelAdministrationClient
,并创建此类型的实例。 在以下示例中,我们将使用 DocumentAnalysisClient
. 要创建客户端实例以访问文档智能 API,您需要 endpoint
表单识别器资源的 credential
. 客户端可以使用具有资源的 API 密钥的 ,AzureKeyCredential
TokenCredential
也可以使用 Azure Active Directory RBAC 来授权客户端。
可以在 Azure 门户中 或使用下面的 Azure CLI 代码片段找到表单识别器资源的终结点:
az cognitiveservices account show --name <your-resource-name> --resource-group <your-resource-group-name> --query "properties.endpoint"
使用 API 密钥
使用 Azure 门户 浏览到表单识别器资源并检索 API 密钥,或使用下面的 Azure CLI 代码片段:
注意: 有时 API 密钥称为“订阅密钥”或“订阅 API 密钥”。
az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>
拥有 API 密钥和终端节点后,您可以按如下方式使用它:
import { AzureKeyCredential, DocumentAnalysisClient } from "@azure/ai-form-recognizer";
const credential = new AzureKeyCredential("<API key>");
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
使用 Azure Active Directory
大多数示例中都使用了 API 密钥授权,但您也可以使用 Azure 标识库通过 Azure Active Directory 对客户端进行身份验证。 要使用下面显示的 DefaultAzureCredential 提供程序或 Azure SDK 提供的其他凭据提供程序,请安装该 @azure/identity
包:
npm install @azure/identity
要使用服务主体进行身份验证,您还需要 注册一个 AAD 应用程序 ,并通过将 "Cognitive Services User"
角色分配给您的服务主体来授予对服务的访问权限(注意:其他角色(例如 "Owner"
不会授予必要的权限,仅 "Cognitive Services User"
足以运行示例和示例代码)。
将 AAD 应用程序的客户端 ID、租户 ID 和客户端机密的值设置为环境变量:AZURE_CLIENT_ID
、AZURE_TENANT_ID
、AZURE_CLIENT_SECRET
。
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
主权云
通过在创建客户端时指定 audience
选项,连接到备用 Azure 云环境(例如 Azure 中国或 Azure 政府)。
KnownFormRecognizerAudience
使用枚举为您的环境选择正确的值。
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient, KnownFormRecognizerAudience } from "@azure/ai-form-recognizer";
const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com", // endpoint
credential,
{
audience: KnownFormRecognizerAudience.AzureGovernment,
}
);
如果未指定该 audience
选项,则默认值适用于 Azure 公有云 (https://cognitiveservices.azure.com
)。
重要概念
DocumentAnalysisClient
DocumentAnalysisClient
提供使用自定义和预构建模型分析输入文档的作。 它有三种方法:
-
beginAnalyzeDocument
,它使用由其模型 ID 给定的自定义或预构建模型从输入文档文件流中提取数据。 有关所有资源支持的预构建模型及其模型 ID/输出的信息,请参阅 模型的服务文档。 -
beginAnalyzeDocumentFromUrl
,它执行与beginAnalyzeDocument
相同的功能,但提交的是文件的可公开访问的 URL,而不是文件流。
DocumentModelAdministrationClient
DocumentModelAdministrationClient
提供用于管理(创建、读取、列出和删除)资源中的模型的作:
-
beginBuildDocumentModel
启动一个作,以从您自己的训练数据集创建新的文档模型。 创建的模型可以根据自定义 schema 提取字段。 训练数据应位于 Azure 存储容器中,并根据特定约定进行组织。 有关将标签应用于训练数据集的更详细说明,请参阅 有关创建训练数据集的服务文档 。 -
beginComposeDocumentModel
启动将多个模型组合成单个模型的作。 当用于自定义表单识别时,新的组合模型将首先对输入文档进行分类,以确定其哪个子模型最合适。 -
beginCopyModelTo
启动一个作,将自定义模型从一个资源复制到另一个资源(甚至复制到同一资源)。 它需要一个CopyAuthorization
from the target 资源,该资源可以使用该方法getCopyAuthorization
生成。 -
getResourceDetails
检索有关资源限制的信息,例如自定义模型的数量和资源可以支持的最大模型数。 -
getDocumentModel
deleteDocumentModel
、listDocumentModels
和 启用管理资源中的模型。 -
getOperation
并允许listOperations
查看模型创建作的状态,甚至是那些正在进行或已失败的作。 作将保留 24 小时。
请注意,也可以使用 Document Intelligence 服务的图形用户界面创建模型: Document Intelligence Studio。
说明如何使用 of DocumentModelAdministrationClient
构建模型的示例代码片段可以在下面的“构建模型”示例部分找到。
长期运行的操作
长时间运行的作 (LRO) 是以下作:向服务发送初始请求以启动作,然后按特定间隔轮询结果,以确定作是否已完成以及作是失败还是成功。 最终,LRO 将因错误而失败或产生结果。
在 Azure AI Document Intelligence 中,创建模型的作(包括复制和撰写模型)以及分析/数据提取作都是 LRO。 SDK 客户端提供返回Promise<PollerLike>
对象的异步begin<operation-name>
方法。 该 PollerLike
对象表示作,该作在服务的基础设施上异步运行,程序可以通过调用并等待 pollUntilDone
从 begin<operation-name>
该方法返回的 Poller 上的方法来等待作完成。 在下一节中,将提供示例代码片段来说明如何使用长时间运行的作。
例子
以下部分提供了几个 JavaScript 代码片段,这些代码片段说明了 Document Intelligence 客户端库中使用的常见模式。
使用模型 ID 分析文档
该方法 beginAnalyzeDocument
可以从文档中提取字段和表数据。 分析可以使用使用您自己的数据训练的自定义模型,也可以使用服务提供的预生成模型(请参阅下面的 使用预生成模型 )。 自定义模型是针对您自己的文档量身定制的,因此它只能与模型中的某个文档类型具有相同结构的文档一起使用(可能有多个文档,例如在组合模型中)。
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
import { createReadStream } from "node:fs";
const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
const modelId = "<model id>";
const path = "<path to a document>";
const readStream = createReadStream(path);
const poller = await client.beginAnalyzeDocument(modelId, readStream, {
onProgress: ({ status }) => {
console.log(`status: ${status}`);
},
});
// There are more fields than just these three
const { documents, pages, tables } = await poller.pollUntilDone();
console.log("Documents:");
for (const document of documents || []) {
console.log(`Type: ${document.docType}`);
console.log("Fields:");
for (const [name, field] of Object.entries(document.fields)) {
console.log(
`Field ${name} has content '${field.content}' with a confidence score of ${field.confidence}`,
);
}
}
console.log("Pages:");
for (const page of pages || []) {
console.log(`Page number: ${page.pageNumber} (${page.width}x${page.height} ${page.unit})`);
}
console.log("Tables:");
for (const table of tables || []) {
console.log(`- Table (${table.columnCount}x${table.rowCount})`);
for (const cell of table.cells) {
console.log(` - cell (${cell.rowIndex},${cell.columnIndex}) "${cell.content}"`);
}
}
从 URL 分析文档
作为提供可读流的替代方法,可以改用该方法提供 beginAnalyzeDocumentFromUrl
可公开访问的 URL。 “可公开访问”意味着必须可从服务的基础架构访问 URL 源(换句话说,私有 Intranet URL 或使用基于标头或证书的密钥的 URL 将不起作用,因为 Document Intelligence 服务必须能够访问 URL)。 但是,URL 本身可以对机密进行编码,例如在查询参数中包含 SAS 令牌的 Azure 存储 blob URL。
使用预生成的文档模型
该方法 beginAnalyzeDocument
还支持使用 Document Intelligence 服务提供的预构建模型从某些类型的常见文档(如收据、发票、名片、身份文档等)中提取字段。 预生成模型可以作为模型 ID 字符串(与自定义文档模型相同 - 请参阅下面的 其他预生成模型 部分)或使用 DocumentModel
对象提供。 使用 DocumentModel
时,适用于 JavaScript 的 Document Intelligence SDK 会根据模型的架构为生成的提取文档提供更强的 TypeScript 类型,并且该类型将转换为使用 JavaScript 命名约定。
DocumentModel
当前服务 API 版本 ()2022-08-31
的示例对象可以在 samples 目录中找到prebuilt
。 在以下示例中,我们将使用 PrebuiltReceiptModel
该目录中的 from the [prebuilt-receipt.ts
] 文件。
由于基于 的分析的主要 DocumentModel
优点是更强的 TypeScript 类型约束,因此以下示例是使用 ECMAScript 模块语法用 TypeScript 编写的:
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
import { createReadStream } from "node:fs";
import { PrebuiltReceiptModel } from "../samples-dev/prebuilt/prebuilt-receipt.js";
const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
const path = "<path to a document>";
const readStream = createReadStream(path);
// The PrebuiltReceiptModel `DocumentModel` instance encodes both the model ID and a stronger return type for the operation
const poller = await client.beginAnalyzeDocument(PrebuiltReceiptModel, readStream, {
onProgress: ({ status }) => {
console.log(`status: ${status}`);
},
});
const {
documents: [receiptDocument],
} = await poller.pollUntilDone();
// The fields of the document constitute the extracted receipt data.
const receipt = receiptDocument.fields;
if (receipt === undefined) {
throw new Error("Expected at least one receipt in analysis result.");
}
console.log(`Receipt data (${receiptDocument.docType})`);
console.log(" Merchant Name:", receipt.merchantName?.value);
// The items of the receipt are an example of a `DocumentArrayValue`
if (receipt.items !== undefined) {
console.log("Items:");
for (const { properties: item } of receipt.items.values) {
console.log("- Description:", item.description?.value);
console.log(" Total Price:", item.totalPrice?.value);
}
}
console.log(" Total:", receipt.total?.value);
或者,如上所述,可以使用预构建收据的模型 ID(“prebuilt-receipt”),而不是使用 PrebuiltReceiptModel
产生更强返回类型的 ,但文档字段不会在 TypeScript 中强类型,并且字段名称通常为“PascalCase”而不是“camelCase”。
其他预生成模型
您不仅限于收据! 有一些预构建的模型可供选择,更多模型正在开发中。 每个预生成模型都有自己的一组受支持字段:
- 收据,使用
PrebuiltReceiptModel
(如上所述)或预构建的收据模型 ID"prebuilt-receipt"
。 - 名片, 使用
PrebuiltBusinessCardModel
或其型号 ID"prebuilt-businessCard"
。 - 发票,使用
PrebuiltInvoiceModel
或其型号 ID"prebuilt-invoice"
。 - 身份证明文件(如驾驶执照和护照),使用
PrebuiltIdDocumentModel
或其型号 ID"prebuilt-idDocument"
。 - W2 税表(美国),使用
PrebuiltTaxUsW2Model
或其型号 ID"prebuilt-tax.us.w2"
。 - 健康保险卡(美国),使用 [
PrebuiltHealthInsuranceCardUsModel
][samples-prebuilt-healthinsurancecard.us] 或其型号 ID"prebuilt-healthInsuranceCard.us"
。
上述每个预生成模型都会生成 documents
(提取模型的字段架构的实例)。 还有三个预构建模型没有字段架构,因此不会生成 documents
。 它们分别是:
- 预构建的布局模型(请参阅下面的 使用预构建的 “layout” ),它提取有关基本布局 (OCR) 元素(如页面和表格)的信息。
- 预构建的 General Document 模型(请参阅下面的 使用预构建的 “document” ),它将键值对(页面元素之间的定向关联,例如带标签的元素)添加到布局模型生成的信息中。
- 预构建的 Read 模型(请参阅下面的 使用“read”预构建 ),该模型仅提取文本元素,例如页面单词和行,以及有关文档语言的信息。
有关所有这些模型的字段的信息,请参阅 可用预构建模型的服务文档。
还可以使用方法(通过其模型 ID)DocumentModelAdministrationClient
以getDocumentModel
编程方式访问所有预生成模型的字段,并检查docTypes
结果中的字段。
使用预构建的 “layout”
该 "prebuilt-layout"
模型仅提取文档的基本元素,例如页面(由文本单词/行和选择标记组成)、表格和可视文本样式及其在输入文档的文本内容中的边界区域和跨度。 我们提供了一个名为 Strong-Typed DocumentModel
的实例来调用此模型,或者一如既往地可以直接使用其模型 ID"prebuilt-layout"
。PrebuiltLayoutModel
由于基于 的分析的主要 DocumentModel
优点是更强的 TypeScript 类型约束,因此以下示例是使用 ECMAScript 模块语法用 TypeScript 编写的:
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
import { createReadStream } from "node:fs";
import { PrebuiltLayoutModel } from "../samples-dev/prebuilt/prebuilt-layout.js";
const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
const path = "<path to a document>";
const readStream = createReadStream(path);
const poller = await client.beginAnalyzeDocument(PrebuiltLayoutModel, readStream);
const { pages, tables } = await poller.pollUntilDone();
for (const page of pages || []) {
console.log(`- Page ${page.pageNumber}: (${page.width}x${page.height} ${page.unit})`);
}
for (const table of tables || []) {
console.log(`- Table (${table.columnCount}x${table.rowCount})`);
for (const cell of table.cells) {
console.log(` cell [${cell.rowIndex},${cell.columnIndex}] "${cell.content}"`);
}
}
使用预构建的 “document”
除了布局提取方法生成的属性外,该 "prebuilt-document"
模型还提取有关键值对(页面元素之间的定向关联,如标记字段)的信息。 此预构建(常规)文档模型提供的功能与 Document Intelligence 服务先前迭代中在没有标签信息的情况下训练的自定义模型类似,但现在它作为预构建模型提供,可处理各种文档。 我们提供了一个名为 Strong-Typed DocumentModel
的实例来调用此模型,或者一如既往地可以直接使用其模型 ID"prebuilt-document"
。PrebuiltDocumentModel
由于基于 的分析的主要 DocumentModel
优点是更强的 TypeScript 类型约束,因此以下示例是使用 ECMAScript 模块语法用 TypeScript 编写的:
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
import { createReadStream } from "node:fs";
import { PrebuiltDocumentModel } from "../samples-dev/prebuilt/prebuilt-document.js";
const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
const path = "<path to a document>";
const readStream = createReadStream(path);
const poller = await client.beginAnalyzeDocument(PrebuiltDocumentModel, readStream);
// `pages`, `tables` and `styles` are also available as in the "layout" example above, but for the sake of this
// example we won't show them here.
const { keyValuePairs } = await poller.pollUntilDone();
if (!keyValuePairs || keyValuePairs.length <= 0) {
console.log("No key-value pairs were extracted from the document.");
} else {
console.log("Key-Value Pairs:");
for (const { key, value, confidence } of keyValuePairs) {
console.log("- Key :", `"${key.content}"`);
console.log(" Value:", `"${value?.content ?? "<undefined>"}" (${confidence})`);
}
}
使用 “read” 预构建
该 "prebuilt-read"
模型提取文档中的文本信息(如单词和段落),并分析该文本的语言和书写风格(例如手写与排版)。 我们提供了一个名为 Strong-Typed DocumentModel
的实例来调用此模型,或者一如既往地可以直接使用其模型 ID"prebuilt-read"
。PrebuiltReadModel
由于基于 的分析的主要 DocumentModel
优点是更强的 TypeScript 类型约束,因此以下示例是使用 ECMAScript 模块语法用 TypeScript 编写的:
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
import { createReadStream } from "node:fs";
import { PrebuiltReadModel } from "../samples-dev/prebuilt/prebuilt-read.js";
const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
const path = "<path to a document>";
const readStream = createReadStream(path);
const poller = await client.beginAnalyzeDocument(PrebuiltReadModel, readStream);
// The "prebuilt-read" model (`beginReadDocument` method) only extracts information about the textual content of the
// document, such as page text elements, text styles, and information about the language of the text.
const { content, pages, languages } = await poller.pollUntilDone();
if (!pages || pages.length <= 0) {
console.log("No pages were extracted from the document.");
} else {
console.log("Pages:");
for (const page of pages) {
console.log("- Page", page.pageNumber, `(unit: ${page.unit})`);
console.log(` ${page.width}x${page.height}, angle: ${page.angle}`);
console.log(
` ${page.lines && page.lines.length} lines, ${page.words && page.words.length} words`,
);
if (page.lines && page.lines.length > 0) {
console.log(" Lines:");
for (const line of page.lines) {
console.log(` - "${line.content}"`);
}
}
}
}
if (!languages || languages.length <= 0) {
console.log("No language spans were extracted from the document.");
} else {
console.log("Languages:");
for (const languageEntry of languages) {
console.log(
`- Found language: ${languageEntry.locale} (confidence: ${languageEntry.confidence})`,
);
for (const text of getTextOfSpans(content, languageEntry.spans)) {
const escapedText = text.replace(/\r?\n/g, "\\n").replace(/"/g, '\\"');
console.log(` - "${escapedText}"`);
}
}
}
function* getTextOfSpans(content, spans) {
for (const span of spans) {
yield content.slice(span.offset, span.offset + span.length);
}
}
对文档进行分类
Document Intelligence 服务支持自定义文档分类器,这些分类器可以根据定型数据集将文档分类为一组预定义的类别。 可以使用自定义分类器对文档进行分类,beginClassifyDocument
DocumentAnalysisClient
方法是使用 . 与上面一样 beginAnalyzeDocument
,此方法接受包含要分类的文档的文件或流,并且它有一个 beginClassifyDocumentFromUrl
对应的文件或流,该 URL 接受可公开访问的文档 URL。
以下示例演示如何使用自定义分类器对文档进行分类:
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
const documentUrl =
"https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/invoice/Invoice_1.pdf";
const poller = await client.beginClassifyDocumentFromUrl("<classifier id>", documentUrl);
const result = await poller.pollUntilDone();
if (result?.documents?.length === 0) {
throw new Error("Failed to extract any documents.");
}
for (const document of result.documents) {
console.log(
`Extracted a document with type '${document.docType}' on page ${document.boundingRegions?.[0].pageNumber} (confidence: ${document.confidence})`,
);
}
有关训练自定义分类器的信息,请参阅 下一节末尾的分类器训练部分。
构建模型
SDK 还支持使用 DocumentModelAdministrationClient
该类创建模型。 根据标记的训练数据构建模型会创建一个在您自己的文档上训练的新模型,生成的模型将能够识别这些文档结构中的值。 模型构建作接受 SAS 编码的 URL,该 URL 指向保存训练文档的 Azure 存储 Blob 容器。 Document Intelligence 服务的基础架构将读取容器中的文件,并根据其内容创建模型。 有关如何创建和构建培训数据容器的更多详细信息,请参阅 用于构建模型的 Document Intelligence 服务文档。
虽然我们提供了这些方法用于编程模型创建,但 Document Intelligence 服务团队创建了一个交互式 Web 应用程序 Document Intelligence Studio,该应用程序支持在 Web 上创建和管理模型。
例如,以下程序使用 SAS 编码的 URL 构建一个自定义文档模型,该 URL 指向预先存在的 Azure 存储容器:
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";
const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
const containerSasUrl = "<SAS url to the blob container storing training documents>";
// You must provide the model ID. It can be any text that does not start with "prebuilt-".
// For example, you could provide a randomly generated GUID using the "uuid" package.
// The second parameter is the SAS-encoded URL to an Azure Storage container with the training documents.
// The third parameter is the build mode: one of "template" (the only mode prior to 4.0.0-beta.3) or "neural".
// See https://aka.ms/azsdk/formrecognizer/buildmode for more information about build modes.
const poller = await client.beginBuildDocumentModel("<model ID>", containerSasUrl, "template", {
// The model description is optional and can be any text.
description: "This is my new model!",
onProgress: ({ status }) => {
console.log(`operation status: ${status}`);
},
});
const model = await poller.pollUntilDone();
console.log(`Model ID: ${model.modelId}`);
console.log(`Description: ${model.description}`);
console.log(`Created: ${model.createdOn}`);
// A model may contain several document types, which describe the possible object structures of fields extracted using
// this model
console.log("Document Types:");
for (const [docType, { description, fieldSchema: schema }] of Object.entries(
model.docTypes ?? {},
)) {
console.log(`- Name: "${docType}"`);
console.log(` Description: "${description}"`);
// For simplicity, this example will only show top-level field names
console.log(" Fields:");
for (const [fieldName, fieldSchema] of Object.entries(schema)) {
console.log(` - "${fieldName}" (${fieldSchema.type})`);
console.log(` ${fieldSchema.description ?? "<no description>"}`);
}
}
自定义分类器是使用 beginBuildDocumentClassifier
method 而不是 beginBuildDocumentModel
. 有关构建自定义分类器的更多信息,请参阅 构建分类器示例 ,因为输入训练数据以略有不同的格式提供。 有关为自定义分类器构建训练数据集的信息,请参阅 Document Intelligence 服务文档。
管理模型
DocumentModelAdministrationClient
还提供了几种访问和列出模型的方法。 以下示例演示如何循环访问资源中的模型(这将包括资源中的自定义模型以及所有资源通用的预生成模型)、按 ID 获取模型以及删除模型。
import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";
const credential = new DefaultAzureCredential();
const client = new DocumentModelAdministrationClient(
"https://<resource name>.cognitiveservices.azure.com",
credential,
);
// Produces an async iterable that supports paging (`PagedAsyncIterableIterator`). The `listDocumentModels` method will only
// iterate over model summaries, which do not include detailed schema information. Schema information is only returned
// from `getDocumentModel` as part of the full model information.
const models = client.listDocumentModels();
let i = 1;
for await (const summary of models) {
console.log(`Model ${i++}:`, summary);
}
// The iterable is paged, and the application can control the flow of paging if needed
i = 1;
for await (const page of client.listDocumentModels().byPage()) {
for (const summary of page) {
console.log(`Model ${i++}`, summary);
}
}
// We can also get a full ModelInfo by ID. Here we only show the basic information. See the documentation and the
// `getDocumentModel` sample program for information about the `docTypes` field, which contains the model's document type
// schemas.
const model = await client.getDocumentModel("<model ID>");
console.log(`ID ${model.modelId}`);
console.log(`Created: ${model.createdOn}`);
console.log(`Description: ${model.description ?? "<none>"}`);
// A model can also be deleted by its model ID. Once it is deleted, it CANNOT be recovered.
const modelIdToDelete = "<model ID that should be deleted forever>";
await client.deleteDocumentModel(modelIdToDelete);
类似的方法 listDocumentClassifiers
, getDocumentClassifier
除了用于删除自定义分类器外 deleteDocumentClassifier
,还可用于列出和获取有关自定义分类器的信息。
故障排除
有关故障排除的帮助,请参阅 故障排除指南。
伐木业
启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL
环境变量设置为 info
。 或者,可以通过在运行时调用 setLogLevel
以下项 @azure/logger
来启用日志记录:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
有关如何启用日志的更详细说明,可以查看 @azure/记录器包文档。
后续步骤
请查看 samples 目录,了解详细的代码示例,这些示例展示了如何使用此库,包括上面“示例”部分中未显示的几个功能和方法,例如复制和组合模型、列出模型管理作和删除模型。
贡献
若要参与此库,请阅读 贡献指南 了解有关如何生成和测试代码的详细信息。