次の方法で共有


DocumentAnalysisClient class

Form Recognizer サービスの分析機能を操作するためのクライアント。

例:

Form Recognizer サービスとクライアントは、次の 2 つの認証方法をサポートしています。

Azure Active Directory

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

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

コンストラクター

DocumentAnalysisClient(string, KeyCredential, DocumentAnalysisClientOptions)

リソース エンドポイントと静的 API キー (KeyCredential) から DocumentAnalysisClient インスタンスを作成する

例:

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,
);
DocumentAnalysisClient(string, TokenCredential, DocumentAnalysisClientOptions)

リソース エンドポイントと Azure ID TokenCredentialから DocumentAnalysisClient インスタンスを作成します。

Azure Active Directory での認証の詳細については、@azure/identity パッケージを参照してください。

例:

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

メソッド

beginAnalyzeDocument(string, FormRecognizerRequestBody, AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>)

一意の ID によって指定されたモデルを使用して、入力からデータを抽出します。

この操作では、カスタム モデルと事前構築済みモデルがサポートされます。 たとえば、事前構築済みの請求書モデルを使用するには、モデル ID "prebuilt-invoice" を指定するか、より単純な事前構築済みレイアウト モデルを使用するには、モデル ID "prebuilt-layout" を指定します。

AnalyzeResult で生成されるフィールドは、分析に使用されるモデルによって異なります。抽出されたドキュメントのフィールドの値は、モデル内のドキュメントの種類 (存在する場合) とそれに対応するフィールド スキーマによって異なります。

このメソッドは、Node.JS ReadableStream オブジェクト、ブラウザー BlobArrayBufferなど、ストリーミング可能な要求本文 (FormRecognizerRequestBody) をサポートします。 本文の内容は、分析のためにサービスにアップロードされます。

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);
beginAnalyzeDocument<Result>(DocumentModel<Result>, FormRecognizerRequestBody, AnalyzeDocumentOptions<Result>)

既知の厳密に型指定されたドキュメント スキーマ (DocumentModel) を持つモデルを使用して、入力からデータを抽出します。

AnalyzeResult で生成されるフィールドは、分析に使用されるモデルによって異なります。 TypeScript では、このメソッド オーバーロードの結果の型は、入力 DocumentModelの型から推論されます。

このメソッドは、Node.JS ReadableStream オブジェクト、ブラウザー BlobArrayBufferなど、ストリーミング可能な要求本文 (FormRecognizerRequestBody) をサポートします。 本文の内容は、分析のためにサービスにアップロードされます。

指定された入力が文字列の場合、分析するドキュメントの場所への URL として扱われます。 詳細については、beginAnalyzeDocumentFromUrl メソッド を参照してください。 URL を使用する場合は、そのメソッドを使用することをお勧めします。URL のサポートは、下位互換性のためにこのメソッドでのみ提供されます。

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);
beginAnalyzeDocumentFromUrl(string, string, AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>)

一意の ID によって指定されたモデルを使用して、入力からデータを抽出します。

この操作では、カスタム モデルと事前構築済みモデルがサポートされます。 たとえば、事前構築済みの請求書モデルを使用するには、モデル ID "prebuilt-invoice" を指定するか、より単純な事前構築済みレイアウト モデルを使用するには、モデル ID "prebuilt-layout" を指定します。

AnalyzeResult で生成されるフィールドは、分析に使用されるモデルによって異なります。抽出されたドキュメントのフィールドの値は、モデル内のドキュメントの種類 (存在する場合) とそれに対応するフィールド スキーマによって異なります。

このメソッドでは、特定の URL にあるファイルからデータを抽出できます。 Form Recognizer サービスは、送信された URL を使用してファイルのダウンロードを試みます。そのため、URL にはパブリック インターネットからアクセスできる必要があります。 たとえば、SAS トークンを使用して Azure Storage 内の BLOB への読み取りアクセスを許可し、サービスは SAS エンコード URL を使用してファイルを要求します。

import { DefaultAzureCredential } from "@azure/identity";
import {
  DocumentAnalysisClient,
  DocumentStringField,
  DocumentArrayField,
  DocumentObjectField,
} from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const poller = await client.beginAnalyzeDocumentFromUrl(
  "prebuilt-receipt",
  // The Document Intelligence service will access the following URL to a receipt image and extract data from it
  "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png",
);
poller.onProgress((state) => console.log("Operation:", state.modelId, state.status));

const { documents } = await poller.pollUntilDone();

const result = documents && documents[0];
if (result) {
  const receipt = result.fields;
  console.log("=== Receipt Information ===");
  console.log("Type:", result.docType);
  console.log("Merchant:", (receipt["MerchantName"] as DocumentStringField).value);

  console.log("Items:");
  for (const { properties: item } of ((receipt["Items"] as DocumentArrayField).values ||
    []) as DocumentObjectField[]) {
    console.log("- Description:", (item["Description"] as DocumentStringField).value);
    console.log("  Total Price:", (item["TotalPrice"] as DocumentStringField).value);
  }
} else {
  throw new Error("Expected at least one receipt in the result.");
}
beginAnalyzeDocumentFromUrl<Result>(DocumentModel<Result>, string, AnalyzeDocumentOptions<Result>)

既知の厳密に型指定されたドキュメント スキーマ (DocumentModel) を持つモデルを使用して、入力からデータを抽出します。

AnalyzeResult で生成されるフィールドは、分析に使用されるモデルによって異なります。 TypeScript では、このメソッド オーバーロードの結果の型は、入力 DocumentModelの型から推論されます。

このメソッドでは、特定の URL にあるファイルからデータを抽出できます。 Form Recognizer サービスは、送信された URL を使用してファイルのダウンロードを試みます。そのため、URL にはパブリック インターネットからアクセスできる必要があります。 たとえば、SAS トークンを使用して Azure Storage 内の BLOB への読み取りアクセスを許可し、サービスは SAS エンコード URL を使用してファイルを要求します。

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
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 poller = await client.beginAnalyzeDocumentFromUrl(
  PrebuiltReceiptModel,
  // The Document Intelligence service will access the following URL to a receipt image and extract data from it
  "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png",
);

const {
  documents: [document],
} = await poller.pollUntilDone();

// Use of PrebuiltModels.Receipt above (rather than the raw model ID), as it adds strong typing of the model's output
if (document) {
  const { merchantName, items, total } = document.fields;

  console.log("=== Receipt Information ===");
  console.log("Type:", document.docType);
  console.log("Merchant:", merchantName && merchantName.value);

  console.log("Items:");
  for (const item of (items && items.values) || []) {
    const { description, totalPrice } = item.properties;

    console.log("- Description:", description && description.value);
    console.log("  Total Price:", totalPrice && totalPrice.value);
  }

  console.log("Total:", total && total.value);
} else {
  throw new Error("Expected at least one receipt in the result.");
}
beginClassifyDocument(string, FormRecognizerRequestBody, ClassifyDocumentOptions)

ID で指定されたカスタム分類子を使用してドキュメントを分類します。

このメソッドは、最終的に AnalyzeResultを生成する実行時間の長い操作 (ポーリング) を生成します。 これは beginAnalyzeDocument および beginAnalyzeDocumentFromUrlと同じ型ですが、結果にはフィールドの小さなサブセットのみが含まれます。 documents フィールドと pages フィールドのみが設定され、最小限のページ情報のみが返されます。 documents フィールドには、識別されたすべてのドキュメントと、それらが分類された docType に関する情報が含まれます。

このメソッドは、Node.JS ReadableStream オブジェクト、ブラウザー BlobArrayBufferなど、ストリーミング可能な要求本文 (FormRecognizerRequestBody) をサポートします。 本文の内容は、分析のためにサービスにアップロードされます。

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 path = "<path to a document>";
const readStream = createReadStream(path);

const poller = await client.beginClassifyDocument("<classifier id>", readStream);

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})`,
  );
}
beginClassifyDocumentFromUrl(string, string, ClassifyDocumentOptions)

ID で指定されたカスタム分類子を使用して、URL からドキュメントを分類します。

このメソッドは、最終的に AnalyzeResultを生成する実行時間の長い操作 (ポーリング) を生成します。 これは beginAnalyzeDocument および beginAnalyzeDocumentFromUrlと同じ型ですが、結果にはフィールドの小さなサブセットのみが含まれます。 documents フィールドと pages フィールドのみが設定され、最小限のページ情報のみが返されます。 documents フィールドには、識別されたすべてのドキュメントと、それらが分類された docType に関する情報が含まれます。

このメソッドでは、特定の URL にあるファイルからデータを抽出できます。 Form Recognizer サービスは、送信された URL を使用してファイルのダウンロードを試みます。そのため、URL にはパブリック インターネットからアクセスできる必要があります。 たとえば、SAS トークンを使用して Azure Storage 内の BLOB への読み取りアクセスを許可し、サービスは SAS エンコード 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})`,
  );
}

コンストラクターの詳細

DocumentAnalysisClient(string, KeyCredential, DocumentAnalysisClientOptions)

リソース エンドポイントと静的 API キー (KeyCredential) から DocumentAnalysisClient インスタンスを作成する

例:

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,
);
new DocumentAnalysisClient(endpoint: string, credential: KeyCredential, options?: DocumentAnalysisClientOptions)

パラメーター

endpoint

string

Azure Cognitive Services インスタンスのエンドポイント URL

credential
KeyCredential

Cognitive Services インスタンスのサブスクリプション キーを含む KeyCredential

options
DocumentAnalysisClientOptions

クライアント内のすべてのメソッドを構成するためのオプションの設定

DocumentAnalysisClient(string, TokenCredential, DocumentAnalysisClientOptions)

リソース エンドポイントと Azure ID TokenCredentialから DocumentAnalysisClient インスタンスを作成します。

Azure Active Directory での認証の詳細については、@azure/identity パッケージを参照してください。

例:

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,
);
new DocumentAnalysisClient(endpoint: string, credential: TokenCredential, options?: DocumentAnalysisClientOptions)

パラメーター

endpoint

string

Azure Cognitive Services インスタンスのエンドポイント URL

credential
TokenCredential

@azure/identity パッケージからの TokenCredential インスタンス

options
DocumentAnalysisClientOptions

クライアント内のすべてのメソッドを構成するためのオプションの設定

メソッドの詳細

beginAnalyzeDocument(string, FormRecognizerRequestBody, AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>)

一意の ID によって指定されたモデルを使用して、入力からデータを抽出します。

この操作では、カスタム モデルと事前構築済みモデルがサポートされます。 たとえば、事前構築済みの請求書モデルを使用するには、モデル ID "prebuilt-invoice" を指定するか、より単純な事前構築済みレイアウト モデルを使用するには、モデル ID "prebuilt-layout" を指定します。

AnalyzeResult で生成されるフィールドは、分析に使用されるモデルによって異なります。抽出されたドキュメントのフィールドの値は、モデル内のドキュメントの種類 (存在する場合) とそれに対応するフィールド スキーマによって異なります。

このメソッドは、Node.JS ReadableStream オブジェクト、ブラウザー BlobArrayBufferなど、ストリーミング可能な要求本文 (FormRecognizerRequestBody) をサポートします。 本文の内容は、分析のためにサービスにアップロードされます。

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);
function beginAnalyzeDocument(modelId: string, document: FormRecognizerRequestBody, options?: AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>): Promise<AnalysisPoller<AnalyzeResult<AnalyzedDocument>>>

パラメーター

modelId

string

このクライアントのリソース内のモデルの一意の ID (名前)

document
FormRecognizerRequestBody

要求と共にアップロードされる FormRecognizerRequestBody

options

AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>

分析操作とポーリングツールの省略可能な設定

戻り値

最終的に AnalyzeResult を生成する実行時間の長い操作 (ポーリング)

beginAnalyzeDocument<Result>(DocumentModel<Result>, FormRecognizerRequestBody, AnalyzeDocumentOptions<Result>)

既知の厳密に型指定されたドキュメント スキーマ (DocumentModel) を持つモデルを使用して、入力からデータを抽出します。

AnalyzeResult で生成されるフィールドは、分析に使用されるモデルによって異なります。 TypeScript では、このメソッド オーバーロードの結果の型は、入力 DocumentModelの型から推論されます。

このメソッドは、Node.JS ReadableStream オブジェクト、ブラウザー BlobArrayBufferなど、ストリーミング可能な要求本文 (FormRecognizerRequestBody) をサポートします。 本文の内容は、分析のためにサービスにアップロードされます。

指定された入力が文字列の場合、分析するドキュメントの場所への URL として扱われます。 詳細については、beginAnalyzeDocumentFromUrl メソッド を参照してください。 URL を使用する場合は、そのメソッドを使用することをお勧めします。URL のサポートは、下位互換性のためにこのメソッドでのみ提供されます。

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);
function beginAnalyzeDocument<Result>(model: DocumentModel<Result>, document: FormRecognizerRequestBody, options?: AnalyzeDocumentOptions<Result>): Promise<AnalysisPoller<Result>>

パラメーター

model

DocumentModel<Result>

分析に使用するモデルと予想される出力の種類を表す DocumentModel

document
FormRecognizerRequestBody

要求と共にアップロードされる FormRecognizerRequestBody

options

AnalyzeDocumentOptions<Result>

分析操作とポーリングツールの省略可能な設定

戻り値

Promise<AnalysisPoller<Result>>

結果の種類が入力モデルに関連付けられているドキュメントで最終的に AnalyzeResult を生成する実行時間の長い操作 (ポーリング)

beginAnalyzeDocumentFromUrl(string, string, AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>)

一意の ID によって指定されたモデルを使用して、入力からデータを抽出します。

この操作では、カスタム モデルと事前構築済みモデルがサポートされます。 たとえば、事前構築済みの請求書モデルを使用するには、モデル ID "prebuilt-invoice" を指定するか、より単純な事前構築済みレイアウト モデルを使用するには、モデル ID "prebuilt-layout" を指定します。

AnalyzeResult で生成されるフィールドは、分析に使用されるモデルによって異なります。抽出されたドキュメントのフィールドの値は、モデル内のドキュメントの種類 (存在する場合) とそれに対応するフィールド スキーマによって異なります。

このメソッドでは、特定の URL にあるファイルからデータを抽出できます。 Form Recognizer サービスは、送信された URL を使用してファイルのダウンロードを試みます。そのため、URL にはパブリック インターネットからアクセスできる必要があります。 たとえば、SAS トークンを使用して Azure Storage 内の BLOB への読み取りアクセスを許可し、サービスは SAS エンコード URL を使用してファイルを要求します。

import { DefaultAzureCredential } from "@azure/identity";
import {
  DocumentAnalysisClient,
  DocumentStringField,
  DocumentArrayField,
  DocumentObjectField,
} from "@azure/ai-form-recognizer";

const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
  "https://<resource name>.cognitiveservices.azure.com",
  credential,
);

const poller = await client.beginAnalyzeDocumentFromUrl(
  "prebuilt-receipt",
  // The Document Intelligence service will access the following URL to a receipt image and extract data from it
  "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png",
);
poller.onProgress((state) => console.log("Operation:", state.modelId, state.status));

const { documents } = await poller.pollUntilDone();

const result = documents && documents[0];
if (result) {
  const receipt = result.fields;
  console.log("=== Receipt Information ===");
  console.log("Type:", result.docType);
  console.log("Merchant:", (receipt["MerchantName"] as DocumentStringField).value);

  console.log("Items:");
  for (const { properties: item } of ((receipt["Items"] as DocumentArrayField).values ||
    []) as DocumentObjectField[]) {
    console.log("- Description:", (item["Description"] as DocumentStringField).value);
    console.log("  Total Price:", (item["TotalPrice"] as DocumentStringField).value);
  }
} else {
  throw new Error("Expected at least one receipt in the result.");
}
function beginAnalyzeDocumentFromUrl(modelId: string, documentUrl: string, options?: AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>): Promise<AnalysisPoller<AnalyzeResult<AnalyzedDocument>>>

パラメーター

modelId

string

このクライアントのリソース内のモデルの一意の ID (名前)

documentUrl

string

パブリック インターネットからアクセスできる入力ドキュメントへの URL (文字列)

options

AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>

分析操作とポーリングツールの省略可能な設定

戻り値

最終的に AnalyzeResult を生成する実行時間の長い操作 (ポーリング)

beginAnalyzeDocumentFromUrl<Result>(DocumentModel<Result>, string, AnalyzeDocumentOptions<Result>)

既知の厳密に型指定されたドキュメント スキーマ (DocumentModel) を持つモデルを使用して、入力からデータを抽出します。

AnalyzeResult で生成されるフィールドは、分析に使用されるモデルによって異なります。 TypeScript では、このメソッド オーバーロードの結果の型は、入力 DocumentModelの型から推論されます。

このメソッドでは、特定の URL にあるファイルからデータを抽出できます。 Form Recognizer サービスは、送信された URL を使用してファイルのダウンロードを試みます。そのため、URL にはパブリック インターネットからアクセスできる必要があります。 たとえば、SAS トークンを使用して Azure Storage 内の BLOB への読み取りアクセスを許可し、サービスは SAS エンコード URL を使用してファイルを要求します。

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
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 poller = await client.beginAnalyzeDocumentFromUrl(
  PrebuiltReceiptModel,
  // The Document Intelligence service will access the following URL to a receipt image and extract data from it
  "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/main/sdk/formrecognizer/ai-form-recognizer/assets/receipt/contoso-receipt.png",
);

const {
  documents: [document],
} = await poller.pollUntilDone();

// Use of PrebuiltModels.Receipt above (rather than the raw model ID), as it adds strong typing of the model's output
if (document) {
  const { merchantName, items, total } = document.fields;

  console.log("=== Receipt Information ===");
  console.log("Type:", document.docType);
  console.log("Merchant:", merchantName && merchantName.value);

  console.log("Items:");
  for (const item of (items && items.values) || []) {
    const { description, totalPrice } = item.properties;

    console.log("- Description:", description && description.value);
    console.log("  Total Price:", totalPrice && totalPrice.value);
  }

  console.log("Total:", total && total.value);
} else {
  throw new Error("Expected at least one receipt in the result.");
}
function beginAnalyzeDocumentFromUrl<Result>(model: DocumentModel<Result>, documentUrl: string, options?: AnalyzeDocumentOptions<Result>): Promise<AnalysisPoller<Result>>

パラメーター

model

DocumentModel<Result>

分析に使用するモデルと予想される出力の種類を表す DocumentModel

documentUrl

string

パブリック インターネットからアクセスできる入力ドキュメントへの URL (文字列)

options

AnalyzeDocumentOptions<Result>

分析操作とポーリングツールの省略可能な設定

戻り値

Promise<AnalysisPoller<Result>>

最終的に AnalyzeResult を生成する実行時間の長い操作 (ポーリング)

beginClassifyDocument(string, FormRecognizerRequestBody, ClassifyDocumentOptions)

ID で指定されたカスタム分類子を使用してドキュメントを分類します。

このメソッドは、最終的に AnalyzeResultを生成する実行時間の長い操作 (ポーリング) を生成します。 これは beginAnalyzeDocument および beginAnalyzeDocumentFromUrlと同じ型ですが、結果にはフィールドの小さなサブセットのみが含まれます。 documents フィールドと pages フィールドのみが設定され、最小限のページ情報のみが返されます。 documents フィールドには、識別されたすべてのドキュメントと、それらが分類された docType に関する情報が含まれます。

このメソッドは、Node.JS ReadableStream オブジェクト、ブラウザー BlobArrayBufferなど、ストリーミング可能な要求本文 (FormRecognizerRequestBody) をサポートします。 本文の内容は、分析のためにサービスにアップロードされます。

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 path = "<path to a document>";
const readStream = createReadStream(path);

const poller = await client.beginClassifyDocument("<classifier id>", readStream);

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})`,
  );
}
function beginClassifyDocument(classifierId: string, document: FormRecognizerRequestBody, options?: ClassifyDocumentOptions): Promise<AnalysisPoller<AnalyzeResult<AnalyzedDocument>>>

パラメーター

classifierId

string

分析に使用するカスタム分類子の ID

document
FormRecognizerRequestBody

分類するドキュメント

options
ClassifyDocumentOptions

分類操作のオプション

戻り値

最終的に AnalyzeResult を生成する実行時間の長い操作 (ポーリング)

beginClassifyDocumentFromUrl(string, string, ClassifyDocumentOptions)

ID で指定されたカスタム分類子を使用して、URL からドキュメントを分類します。

このメソッドは、最終的に AnalyzeResultを生成する実行時間の長い操作 (ポーリング) を生成します。 これは beginAnalyzeDocument および beginAnalyzeDocumentFromUrlと同じ型ですが、結果にはフィールドの小さなサブセットのみが含まれます。 documents フィールドと pages フィールドのみが設定され、最小限のページ情報のみが返されます。 documents フィールドには、識別されたすべてのドキュメントと、それらが分類された docType に関する情報が含まれます。

このメソッドでは、特定の URL にあるファイルからデータを抽出できます。 Form Recognizer サービスは、送信された URL を使用してファイルのダウンロードを試みます。そのため、URL にはパブリック インターネットからアクセスできる必要があります。 たとえば、SAS トークンを使用して Azure Storage 内の BLOB への読み取りアクセスを許可し、サービスは SAS エンコード 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})`,
  );
}
function beginClassifyDocumentFromUrl(classifierId: string, documentUrl: string, options?: ClassifyDocumentOptions): Promise<AnalysisPoller<AnalyzeResult<AnalyzedDocument>>>

パラメーター

classifierId

string

分析に使用するカスタム分類子の ID

documentUrl

string

分類するドキュメントの URL

戻り値