適用于 JavaScript 的 Azure AI Document Intelligence 用戶端程式庫 - 5.0.0 版

Azure AI 檔智慧 是一項雲端服務,會使用機器學習來分析檔中的文字和結構化資料。 其中包含下列主要功能:

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

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

注意

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

安裝 @azure/ai-form-recognizer 套件

使用 npm 安裝適用于 JavaScript 的 Azure Document Intelligence 用戶端程式庫:

npm install @azure/ai-form-recognizer

開始使用

const { DocumentAnalysisClient } = require("@azure/ai-form-recognizer");
const { DefaultAzureCredential } = require("@azure/identity");

const fs = require("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 = fs.createReadStream("path/to/file.jpg");
const poller = await client.beginAnalyzeDocument("<model ID>", file);

const { pages, tables, styles, keyValuePairs, entities, documents } = await poller.pollUntilDone();

目前支援的環境

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

必要條件

建立表格辨識器資源

注意:在撰寫時,Azure 入口網站仍會將資源稱為「表格辨識器」資源。 未來可能會更新為「檔智慧」資源。 目前,下列檔會使用 「表格辨識器」 名稱。

檔智慧支援 多重服務和單一服務存取。 如果您打算在單一端點/金鑰下存取多個認知服務,請建立認知服務資源。 僅針對 Azure 表格辨識器的存取,請建立 Azure 表格辨識器資源。

您可以使用 建立資源

選項 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-name> 取代 <your-resource-group-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 服務互動,您必須選取 DocumentAnalysisClientDocumentModelAdministrationClient ,並建立此類型的實例。 在下列範例中,我們將使用 DocumentAnalysisClient 。 若要建立用戶端實例來存取 Document Intelligence API,您需要 endpoint 表格辨識器資源和 credential 的 。 用戶端可以使用 AzureKeyCredential 搭配您資源的 API 金鑰,或使用 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 金鑰和端點,就可以使用它,如下所示:

const { DocumentAnalysisClient, AzureKeyCredential } = require("@azure/ai-form-recognizer");

const client = new DocumentAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

使用 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_ID 、、 AZURE_TENANT_IDAZURE_CLIENT_SECRET

const { DocumentAnalysisClient } = require("@azure/ai-form-recognizer");
const { DefaultAzureCredential } = require("@azure/identity");

const client = new DocumentAnalysisClient("<endpoint>", new DefaultAzureCredential());

重要概念

DocumentAnalysisClient

DocumentAnalysisClient 提供使用自訂和預先建置模型分析輸入檔的作業。 它有三種方法:

  • beginAnalyzeDocument,其會使用其模型識別碼所提供的自訂或預先建置模型,從輸入檔檔案資料流程擷取資料。 如需所有資源及其模型識別碼/輸出中支援的預建模型相關資訊,請參閱 服務的模型檔
  • beginAnalyzeDocumentFromUrl,其會執行與 相同的函 beginAnalyzeDocument 式,但會提交檔案的可公開存取 URL,而不是檔案資料流程。

DocumentModelAdministrationClient

DocumentModelAdministrationClient 提供在資源中管理 (建立、讀取、列出和刪除) 模型的作業:

  • beginBuildDocumentModel 會啟動作業,從您自己的訓練資料集建立新的檔模型。 建立的模型可以根據自訂架構來擷取欄位。 定型資料應該位於 Azure 儲存體容器中,並根據特定慣例進行組織。 如需將標籤套用至訓練資料集的詳細說明,請參閱 有關建立訓練資料集的服務檔
  • beginComposeDocumentModel 會啟動作業,將多個模型組成單一模型。 用於自訂表單辨識時,新的撰寫模型會先執行輸入檔的分類,以判斷其子模型最適合哪一個。
  • beginCopyModelTo 會啟動作業,將自訂模型從某個資源複製到另一個資源 (,或甚至複製到相同的資源) 。 它需要 CopyAuthorization 來自目標資源的 ,這可以使用 方法產生 getCopyAuthorization
  • getResourceDetails 擷取資源限制的相關資訊,例如自訂模型數目,以及資源可支援的模型數目上限。
  • getDocumentModellistDocumentModels 、 和 deleteDocumentModel 可管理資源中的模型。
  • getOperationlistOperations 可讓您檢視模型建立作業的狀態,即使是進行中或失敗的作業也一樣。 作業會保留 24 小時。

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

您可以在範例一節中找到示範如何使用 DocumentModelAdministrationClient 來建置模型的範例程式碼片段。

長期執行作業

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

在 Azure AI Document Intelligence 中,建立模型的作業 (包括複製和撰寫模型) ,以及分析/資料擷取作業都是 LRO。 SDK 用戶端會提供傳回 Promise<PollerLike> 物件的非同步 begin<operation-name> 方法。 物件 PollerLike 代表以非同步方式在服務的基礎結構上執行的作業,而程式可以藉由在方法 begin<operation-name> 傳回的輪詢器上呼叫 並等候 pollUntilDone 方法完成作業。 提供範例程式碼片段,以說明在下一節中使用長時間執行的作業。

範例

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

使用模型識別碼分析檔

方法 beginAnalyzeDocument 可以從檔擷取欄位和資料表資料。 分析可能會使用自訂模型、使用您自己的資料定型,或服務所提供的預先建置模型 (請參閱) 下方 的使用預先建置模型 。 自訂模型是針對您自己的檔量身打造,因此它應該只與模型中其中一個檔案類型相同的結構使用, (可能會有多個檔案類型,例如在撰寫的模型中) 。

const { DocumentAnalysisClient, AzureKeyCredential } = require("@azure/ai-form-recognizer");

const fs = require("fs");

async function main() {
  const endpoint = "<cognitive services endpoint>";
  const apiKey = "<api key>";
  const modelId = "<model id>";
  const path = "<path to a document>";

  const readStream = fs.createReadStream(path);

  const client = new DocumentAnalysisClient(endpoint, new AzureKeyCredential(apiKey));
  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 value '${field.value}' 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}"`);
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

從 URL 分析檔

除了提供可讀取的資料流程,您也可以改用 方法來提供可公開存取的 beginAnalyzeDocumentFromUrl URL。 「可公開存取」表示 URL 來源必須可從服務的基礎結構 (存取,換句話說,私人內部網路 URL 或使用標頭或憑證型秘密的 URL 將無法運作,因為 Document Intelligence 服務必須能夠存取 URL) 。 不過,URL 本身可以編碼秘密,例如 Azure 儲存體 Blob URL,其中包含查詢參數中的 SAS 權杖。

使用預先建置的檔模型

此方法 beginAnalyzeDocument 也支援使用 Document Intelligence 服務所提供的預先建置模型,從特定類型的常見檔擷取欄位,例如收據、發票、名片、身分識別檔等等。 預先建置的模型可能會以模型識別碼字串的形式提供, (與自訂檔模型相同,請參閱下方 的其他預建模型 一節,) 或使用 DocumentModel 物件。 使用 DocumentModel 時,Document Intelligence SDK for JavaScript 會根據模型的架構,為產生的擷取檔提供更強大的 TypeScript 類型,並且會轉換成使用 JavaScript 命名慣例。

您可以在範例目錄中找到 prebuilt目前服務 API 版本的範例 DocumentModel 物件 (2022-08-31) 。 在下列範例中,我們將使用該 PrebuiltReceiptModel 目錄中 [ prebuilt-receipt.ts ] 檔案的 。

由於型分析的主要優點 DocumentModel 是更強的 TypeScript 類型條件約束,因此下列範例是使用 ECMAScript 模組語法以 TypeScript 撰寫:

import { DocumentAnalysisClient, AzureKeyCredential } from "@azure/ai-form-recognizer";

// Copy the file from the above-linked sample directory so that it can be imported in this module
import { PrebuiltReceiptModel } from "./prebuilt/prebuilt-receipt";

import fs from "fs";

async function main() {
  const endpoint = "<cognitive services endpoint>";
  const apiKey = "<api key>";
  const path = "<path to your receipt document>"; // pdf/jpeg/png/tiff formats

  const readStream = fs.createReadStream(path);

  const client = new DocumentAnalysisClient(endpoint, new AzureKeyCredential(apiKey));

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

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

或者,如前所述,而不是使用 PrebuiltReceiptModel 會產生較強的傳回型別,預建收據的模型識別碼 (「預建收據」) 可以使用,但檔欄位不會在 TypeScript 中強型別,而且功能變數名稱通常位於 「PascalCase」 而非 「camelCase」。

其他預先建置的模型

您不限於收據! 有一些預先建置的模型可供選擇,並提供更多相關資訊。 每個預建模型都有自己的一組支援欄位:

  • 回條,使用 PrebuiltReceiptModel (如上述) 或預建收據模型識別碼 "prebuilt-receipt"
  • 名片,使用 PrebuiltBusinessCardModel 或其模型識別碼 "prebuilt-businessCard"
  • 發票,使用 PrebuiltInvoiceModel 或其模型識別碼 "prebuilt-invoice"
  • 身分識別檔 (,例如驅動程式授權和 passport) ,使用 PrebuiltIdDocumentModel 或其模型識別碼 "prebuilt-idDocument"
  • W2 Tax Forms (美國) ,使用 PrebuiltTaxUsW2Model 或其模型識別碼 "prebuilt-tax.us.w2"
  • 使用 [ PrebuiltHealthInsuranceCardUsModel ][samples-prebuilt-healthinsurancecard.us] 或其模型識別碼 "prebuilt-healthInsuranceCard.us" (美國) 健康保險卡。

上述每個預建模型都會產生 documents (擷取模型欄位架構實例) 。 另外還有三個預先建置的模型沒有欄位架構,因此不會產生 documents 。 其中包括:

  • 預先建置的版面配置模型 (請參閱) 下方 的「版面配置」預先建置 ,它會擷取基本版面配置的相關資訊 (OCR) 元素,例如頁面和資料表。
  • 預先建置的一般檔模型 (請參閱 ) 下方使用「檔」預先建置 ,這會在頁面元素之間新增索引鍵/值組 (導向關聯,例如標籤元素) 版面配置模型所產生的資訊。
  • 預先建置的讀取模型 (請參閱 ) 下方的「讀取」預先建置 ,其中只會擷取文字元素,例如頁面字組和行,以及檔語言的相關資訊。

如需所有這些模型之欄位的相關資訊,請參閱 服務的可用預建模型檔

所有預先建置模型的欄位也可以透過其模型 DocumentModelAdministrationClient 識別碼) 和檢查 docTypes 結果中的欄位,以程式設計方式使用 getDocumentModel 方法 (存取。

使用「配置」預先建置

模型 "prebuilt-layout" 只會擷取檔的基本元素,例如頁面, (其中包含文字文字/行和選取標記) 、表格和視覺化文字樣式,以及輸入檔的文字內容內的周框區域和範圍。 我們提供名為 PrebuiltLayoutModel 的強型 DocumentModel 別實例,可叫用此模型,或一律直接使用其模型識別碼 "prebuilt-layout"

由於型分析的主要優點 DocumentModel 是更強的 TypeScript 類型條件約束,因此下列範例是使用 ECMAScript 模組語法以 TypeScript 撰寫:

import { DocumentAnalysisClient, AzureKeyCredential } from "@azure/ai-form-recognizer";

// Copy the above-linked `DocumentModel` file so that it may be imported in this module.
import { PrebuiltLayoutModel } from "./prebuilt/prebuilt-layout";

import fs from "fs";

async function main() {
  const endpoint = "<cognitive services endpoint>";
  const apiKey = "<api key>";
  const path = "<path to a document>"; // pdf/jpeg/png/tiff formats

  const readStream = fs.createReadStream(path);

  const client = new DocumentAnalysisClient(endpoint, new AzureKeyCredential(apiKey));
  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}"`);
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

使用預先建置的 「document」

除了 "prebuilt-document" 配置擷取方法所產生的屬性之外,模型還會擷取索引鍵/值組的相關資訊, (頁面元素之間的導向關聯,例如標記欄位) 。 此預先建置 (一般) 檔模型提供與在檔智慧服務先前反復專案中未加上標籤資訊的自訂模型類似的功能,但現在會以預建模型的形式提供,可與各種檔搭配使用。 我們提供名為 PrebuiltDocumentModel 的強型 DocumentModel 別實例,可叫用此模型,或一律直接使用其模型識別碼 "prebuilt-document"

由於型分析的主要優點 DocumentModel 是更強的 TypeScript 類型條件約束,因此下列範例是使用 ECMAScript 模組語法以 TypeScript 撰寫:

import { DocumentAnalysisClient, AzureKeyCredential } from "@azure/ai-form-recognizer";

// Copy the above-linked `DocumentModel` file so that it may be imported in this module.
import { PrebuiltDocumentModel } from "./prebuilt/prebuilt-document";

import fs from "fs";

async function main() {
  const endpoint = "<cognitive services endpoint>";
  const apiKey = "<api key>";
  const path = "<path to a document>"; // pdf/jpeg/png/tiff formats

  const readStream = fs.createReadStream(path);

  const client = new DocumentAnalysisClient(endpoint, new AzureKeyCredential(apiKey));
  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})`);
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

使用預先建置的「讀取」

模型 "prebuilt-read" 會擷取檔中的文字資訊,例如文字和段落,並分析語言和書寫樣式 (例如手寫與類型集) 該文字。 我們提供名為 PrebuiltReadModel 的強型 DocumentModel 別實例,可叫用此模型,或一律直接使用其模型識別碼 "prebuilt-read"

由於型分析的主要優點 DocumentModel 是更強的 TypeScript 類型條件約束,因此下列範例是使用 ECMAScript 模組語法以 TypeScript 撰寫:

import { DocumentAnalysisClient, AzureKeyCredential } from "@azure/ai-form-recognizer";

// Copy the above-linked `DocumentModel` file so that it may be imported in this module.
import { PrebuiltReadModel } from "./prebuilt/prebuilt-read";

// See the samples directory for a definition of this helper function.
import { getTextOfSpans } from "./utils";

import fs from "fs";

async function main() {
  const endpoint = "<cognitive services endpoint>";
  const apiKey = "<api key>";
  const path = "<path to a document>"; // pdf/jpeg/png/tiff formats

  const readStream = fs.createReadStream(path);

  const client = new DocumentAnalysisClient(endpoint, new AzureKeyCredential(apiKey));
  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}"`);
      }
    }
  }
}

main().catch((error) => {
  console.error("An error occurred:", error);
  process.exit(1);
});

分類檔

Document Intelligence 服務支援自訂檔分類器,可根據訓練資料集,將檔分類成一組預先定義的類別。 檔可以使用 的 方法來 DocumentAnalysisClient 分類自訂分類器 beginClassifyDocument 。 如同 beginAnalyzeDocument 上述,此方法會接受包含要分類之檔的檔案或資料流程,而且具有 beginClassifyDocumentFromUrl 可改為接受可公開存取之檔的 URL 的對應專案。

下列範例示範如何使用自訂分類器來分類檔:

const { AzureKeyCredential, DocumentAnalysisClient } = require("@azure/ai-form-recognizer");

async function main() {
  const endpoint = "<endpoint>";
  const credential = new AzureKeyCredential("<api key>");

  const documentUrl =
    "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/invoice/Invoice_1.pdf";

  const client = new DocumentAnalysisClient(endpoint, credential);

  const poller = await client.beginClassifyDocumentFromUrl("<classifier id>", documentUrl);

  const result = await poller.pollUntilDone();

  if (result.documents === undefined || 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})`
    );
  }
}

main().catch((error) => {
  console.error("An error occurred:", error);
  process.exit(1);
});

如需定型自訂分類器的資訊,請參閱 下一節結尾的分類器訓練一節

建置模型

SDK 也支援使用 DocumentModelAdministrationClient 類別建立模型。 從已加上標籤的定型資料建置模型會建立新的模型,該模型會在您自己的檔上定型,而產生的模型將能夠辨識這些檔結構中的值。 模型建置作業會接受 SAS 編碼的 URL 至保存訓練檔的 Azure 儲存體 Blob 容器。 Document Intelligence 服務的基礎結構會讀取容器中的檔案,並根據其內容建立模型。 如需如何建立及建構定型資料容器的詳細資訊,請參閱 檔智慧服務的檔來建置模型

雖然我們提供這些方法來建立程式設計模型,但 Document Intelligence 服務小組已建立互動式 Web 應用程式 Document Intelligence Studio,以在網路上建立和管理模型。

例如,下列程式會使用 SAS 編碼的 URL 建置自訂檔模型,以建立預先存在的 Azure 儲存體容器:

const {
  DocumentModelAdministrationClient,
  AzureKeyCredential,
} = require("@azure/ai-form-recognizer");

async function main() {
  const endpoint = "<cognitive services endpoint>";
  const apiKey = "<api key>";
  const containerSasUrl = "<SAS url to the blob container storing training documents>";

  const client = new DocumentModelAdministrationClient(endpoint, new AzureKeyCredential(apiKey));

  // 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>"}`);
    }
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

自訂分類器是使用 beginBuildDocumentClassifier 方法 beginBuildDocumentModel 而非 ,以類似的方式建置。 如需建置自訂分類器的詳細資訊,請參閱 組建分類器範例 ,因為輸入訓練資料是以稍微不同的格式提供。 如需為自訂分類器建置訓練資料集的相關資訊,請參閱 Document Intelligence 服務檔

管理模型

DocumentModelAdministrationClient 也提供數種方法來存取和列出模型。 下列範例示範如何逐一查看資源中的模型 (這會將自訂模型同時包含在資源中,以及所有資源通用的預先建置模型) 、依識別碼取得模型,以及刪除模型。

const {
  DocumentModelAdministrationClient,
  AzureKeyCredential,
} = require("@azure/ai-form-recognizer");

async function main() {
  const endpoint = "<cognitive services endpoint>";
  const apiKey = "<api key>";
  const client = new DocumentModelAdministrationClient(endpoint, new AzureKeyCredential(apiKey));

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

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

除了刪除自訂分類器之外,也提供類似的方法和 listDocumentClassifiersgetDocumentClassifier 取得自訂分類器 deleteDocumentClassifier 的相關資訊。

疑難排解

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

記錄

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

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

如需如何啟用記錄的詳細指示,可參閱 @azure/logger 套件文件

後續步驟

請參閱 範例 目錄,以取得詳細的程式碼範例,示範如何使用此程式庫,包括上述一節未顯示的數個功能和方法,例如複製和撰寫模型、列出模型管理作業,以及刪除模型。

參與

如果您希望向此程式庫投稿,請參閱投稿指南,深入瞭解如何組建與測試程式碼。

曝光數