共用方式為


適用於 JavaScript 的 Azure AI Document Intelligence 用戶端庫 - 版本 5.1.0

Azure AI Document Intelligence 是一項雲服務,它使用機器學習來分析文檔中的文本和結構化數據。 它包含下列主要功能:

  • 版面配置 - 從檔擷取文字、表格結構和選取標記及其周框區域座標。
  • 檔 - 使用一般預先建置的檔模型,分析來自文件的實體、索引鍵/值組、數據表和選取標記。
  • 閱讀 - 除了文字語言資訊之外,請閱讀文字元素的相關信息,例如頁面文字和行。
  • 預先建置 - 使用預先建置的模型,分析特定類型通用文件的數據(例如收據、發票、名片或身分識別檔)。
  • 自訂 - 建置自定義模型,以從檔擷取文字、域值、選取標記和數據表數據。 自定義模型是使用您自己的數據所建置,因此會針對您的檔量身打造。
  • 分類器 - 建置自定義分類器,將檔分類為預先定義的類別。

原始程式碼 | 套件 (NPM) | API 參考檔, | 產品檔 | 範例

注意

Document Intelligence 服務以前稱為“Azure 表單識別器”。這些服務是相同的, @azure/ai-form-recognizer JavaScript 的包是 Azure AI Document Intelligence 服務的 Azure SDK 包。 在撰寫本文時,Azure 窗體辨識器重新命名至 Azure AI 檔智慧正在進行中,因此在某些情況下,「表單辨識器」和「檔智慧」可能會交替使用。

安裝 @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();

目前支持的環境

如需詳細資訊,請參閱我們的支援原則

先決條件

建立表單辨識器資源

注意:在撰寫本文時,Azure 門戶仍將資源稱為“表單識別器”資源。 未來可能會更新為「檔智慧」資源。 目前,下列檔使用「表單辨識器」名稱。

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 金鑰的 ,AzureKeyCredentialTokenCredential也可以使用 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 應用程式的用戶端識別碼、租使用者識別碼和客戶端密碼的值設定為環境變數:AZURE_CLIENT_IDAZURE_TENANT_IDAZURE_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 啟動一個作,以從您自己的訓練數據集創建新的文檔模型。 建立的模型可以根據自定義架構擷取字段。 定型數據應位於 Azure 記憶體容器中,並根據特定慣例進行組織。 有關將標籤應用於訓練數據集的更詳細說明,請參閱 有關創建訓練數據集的服務文檔
  • beginComposeDocumentModel 啟動將多個模型組合成單個模型的作。 當用於自定義表單辨識時,新的撰寫模型會先執行輸入檔的分類,以判斷其子模型中哪一個最適合。
  • beginCopyModelTo 啟動一個作,將自定義模型從一個資源複製到另一個資源(甚至複製到同一資源)。 它需要一個 CopyAuthorization from the target資源,該資源可以使用該方法 getCopyAuthorization 生成。
  • getResourceDetails 檢索有關資源限制的資訊,例如自定義模型的數量和資源可以支援的最大模型數。
  • getDocumentModel deleteDocumentModellistDocumentModels和 啟用管理資源中的模型。
  • getOperation 並允許 listOperations 查看模型創建作的狀態,甚至是那些正在進行或已失敗的作。 作業會保留 24 小時。

請注意,也可以使用 Document Intelligence 服務的圖形使用者介面創建模型: Document Intelligence Studio

說明如何使用 of DocumentModelAdministrationClient 構建模型的範例代碼片段可以在下面的“構建模型”示例部分找到。

長時間執行的作業

長時間執行的作業 (LRO) 是作業,其中包含傳送至服務以啟動作業的初始要求,然後輪詢結果在特定間隔,以判斷作業是否已完成,以及作業是否失敗或成功。 最後,LRO 會失敗併產生錯誤或產生結果。

在 Azure AI 檔智慧中,建立模型(包括複製和撰寫模型)以及分析/數據擷取作業的作業都是 RLO。 SDK 用戶端提供返回Promise<PollerLike>對象的異步begin<operation-name>方法。 該 PollerLike 物件表示作,該作在服務的基礎設施上異步運行,程式可以通過調用並等待 pollUntilDonebegin<operation-name> 該方法返回的Poller上的方法來等待作完成。 提供範例代碼段來說明在下一節中使用長時間執行的作業。

例子

下一節提供數個 JavaScript 代碼段,說明 Document Intelligence 用戶端連結庫中所使用的常見模式。

使用模型標識碼分析檔

該方法 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 來源(換句話說,私人內部網路 URL 或使用標頭或憑證型秘密的 URL,將無法運作,因為檔智慧服務必須能夠存取 URL)。 不過,URL 本身可以編碼秘密,例如 Azure 記憶體 Blob URL,其中包含查詢參數中的 SAS 令牌。

使用預先建置的檔模型

該方法 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)DocumentModelAdministrationClientgetDocumentModel程式設計方式訪問所有預生成模型的欄位,並檢查docTypes結果中的欄位。

使用「版面配置」預先建置

"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" 模型還提取有關鍵值對(頁面元素之間的定向關聯,如標記字段)的資訊。 此預先建置(一般)檔模型提供與先前檔智慧服務反覆專案中未加上標籤資訊而定型的自定義模型類似的功能,但現在會以預先建置的模型的形式提供,可與各種檔搭配使用。 我們提供了一個名為 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})`);
  }
}

使用「讀取」預先建置

"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 服務支援自定義檔分類器,可根據定型數據集,將檔分類成一組預先定義的類別。 可以使用自訂分類器對文件進行分類,beginClassifyDocumentDocumentAnalysisClient方法是使用 . 與上面一樣 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 該類創建模型。 從加上標籤的定型數據建置模型會建立一個新的模型,該模型會在您自己的檔上定型,而產生的模型將能夠辨識這些文件結構中的值。 模型建置作業會接受保存定型檔的 Azure 記憶體 Blob 容器的 SAS 編碼 URL。 Document Intelligence 服務的基礎結構會讀取容器中的檔案,並根據其內容建立模型。 有關如何創建和構建培訓數據容器的更多詳細資訊,請參閱 用於構建模型的 Document Intelligence 服務文件

雖然我們提供了這些方法用於程式設計模型創建,但 Document Intelligence 服務團隊創建了一個互動式 Web 應用程式 Document Intelligence Studio,該應用程式支援在 Web 上創建和管理模型。

例如,下列程式會使用 SAS 編碼的 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 還提供了幾種訪問和列出模型的方法。 下列範例示範如何逐一查看資源中的模型(這會在資源中包含自定義模型,以及所有資源通用的預先建置模型)、依標識符取得模型,以及刪除模型。

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);

類似的方法 listDocumentClassifiersgetDocumentClassifier 除了用於刪除自定義分類器外 deleteDocumentClassifier ,還可用於列出和獲取有關自定義分類器的資訊。

故障排除

如需疑難解答的協助,請參閱 疑難解答指南

伐木

啟用記錄可能有助於找出有關失敗的實用資訊。 若要檢視 HTTP 要求和回應的記錄,請將 AZURE_LOG_LEVEL 環境變數設定為 info。 或者,您可以在 執行時間呼叫 setLogLevel@azure/logger來啟用記錄:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

如需如何啟用記錄的詳細指示,您可以查看 @azure/記錄器套件檔

後續步驟

請查看 samples 目錄,瞭解詳細的代碼示例,這些範例展示了如何使用此庫,包括上面“示例”部分中未顯示的幾個功能和方法,例如複製和組合模型、列出模型管理作和刪除模型。

貢獻

如果您想要參與此連結庫,請閱讀 參與指南 ,以深入瞭解如何建置和測試程序代碼。