Bagikan melalui


DocumentAnalysisClient class

Klien untuk berinteraksi dengan fitur analisis layanan Form Recognizer.

Contoh:

Layanan Form Recognizer dan klien mendukung dua cara autentikasi:

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

Kunci API (Kunci Langganan)

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

Konstruktor

DocumentAnalysisClient(string, KeyCredential, DocumentAnalysisClientOptions)

Buat instans DocumentAnalysisClient dari titik akhir sumber daya dan kunci API statis (KeyCredential),

Contoh:

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)

Buat instans DocumentAnalysisClient dari titik akhir sumber daya dan Azure Identity TokenCredential.

Lihat paket @azure/identity untuk informasi selengkapnya tentang mengautentikasi dengan Azure Active Directory.

Contoh:

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

Metode

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

Ekstrak data dari input menggunakan model yang diberikan oleh ID uniknya.

Operasi ini mendukung model kustom serta bawaan. Misalnya, untuk menggunakan model faktur bawaan, berikan ID model "prebuilt-invoice", atau untuk menggunakan model tata letak bawaan yang lebih sederhana, berikan ID model "prebuilt-layout".

Bidang yang dihasilkan dalam AnalyzeResult bergantung pada model yang digunakan untuk analisis, dan nilai dalam bidang dokumen yang diekstrak bergantung pada jenis dokumen dalam model (jika ada) dan skema bidang yang sesuai.

Contoh

Metode ini mendukung badan permintaan yang dapat dialirkan (FormRecognizerRequestBody) seperti objek Node.JS ReadableStream, Blobbrowser, dan ArrayBuffers. Konten isi akan diunggah ke layanan untuk analisis.

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

Ekstrak data dari input menggunakan model yang memiliki skema dokumen yang diketahui dan diketik dengan kuat (DocumentModel ).

Bidang yang dihasilkan dalam AnalyzeResult bergantung pada model yang digunakan untuk analisis. Dalam TypeScript, jenis hasil untuk kelebihan beban metode ini disimpulkan dari jenis input DocumentModel.

Contoh

Metode ini mendukung badan permintaan yang dapat dialirkan (FormRecognizerRequestBody) seperti objek Node.JS ReadableStream, Blobbrowser, dan ArrayBuffers. Konten isi akan diunggah ke layanan untuk analisis.

Jika input yang disediakan adalah string, input akan diperlakukan sebagai URL ke lokasi dokumen yang akan dianalisis. Lihat metode beginAnalyzeDocumentFromUrl untuk informasi selengkapnya. Penggunaan metode tersebut lebih disukai saat menggunakan URL, dan dukungan URL hanya disediakan dalam metode ini untuk kompatibilitas mundur.

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

Ekstrak data dari input menggunakan model yang diberikan oleh ID uniknya.

Operasi ini mendukung model kustom serta bawaan. Misalnya, untuk menggunakan model faktur bawaan, berikan ID model "prebuilt-invoice", atau untuk menggunakan model tata letak bawaan yang lebih sederhana, berikan ID model "prebuilt-layout".

Bidang yang dihasilkan dalam AnalyzeResult bergantung pada model yang digunakan untuk analisis, dan nilai dalam bidang dokumen yang diekstrak bergantung pada jenis dokumen dalam model (jika ada) dan skema bidang yang sesuai.

Contoh

Metode ini mendukung ekstraksi data dari file di URL tertentu. Layanan Form Recognizer akan mencoba mengunduh file menggunakan URL yang dikirimkan, sehingga URL harus dapat diakses dari internet publik. Misalnya, token SAS dapat digunakan untuk memberikan akses baca ke blob di Azure Storage, dan layanan akan menggunakan URL yang dikodekan SAS untuk meminta file.

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

Ekstrak data dari input menggunakan model yang memiliki skema dokumen yang diketahui dan diketik dengan kuat (DocumentModel ).

Bidang yang dihasilkan dalam AnalyzeResult bergantung pada model yang digunakan untuk analisis. Dalam TypeScript, jenis hasil untuk kelebihan beban metode ini disimpulkan dari jenis input DocumentModel.

Contoh

Metode ini mendukung ekstraksi data dari file di URL tertentu. Layanan Form Recognizer akan mencoba mengunduh file menggunakan URL yang dikirimkan, sehingga URL harus dapat diakses dari internet publik. Misalnya, token SAS dapat digunakan untuk memberikan akses baca ke blob di Azure Storage, dan layanan akan menggunakan URL yang dikodekan SAS untuk meminta file.

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)

Mengklasifikasikan dokumen menggunakan pengklasifikasi kustom yang diberikan oleh ID-nya.

Metode ini menghasilkan operasi jangka panjang (poller) yang akhirnya akan menghasilkan AnalyzeResult. Ini adalah jenis yang sama dengan beginAnalyzeDocument dan beginAnalyzeDocumentFromUrl, tetapi hasilnya hanya akan berisi subset kecil bidangnya. Hanya bidang documents dan bidang pages yang akan diisi, dan hanya informasi halaman minimal yang akan dikembalikan. Bidang documents akan berisi informasi tentang semua dokumen yang diidentifikasi dan docType yang diklasifikasikan sebagai.

Contoh

Metode ini mendukung badan permintaan yang dapat dialirkan (FormRecognizerRequestBody) seperti objek Node.JS ReadableStream, Blobbrowser, dan ArrayBuffers. Konten isi akan diunggah ke layanan untuk analisis.

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)

Mengklasifikasikan dokumen dari URL menggunakan pengklasifikasi kustom yang diberikan oleh ID-nya.

Metode ini menghasilkan operasi jangka panjang (poller) yang akhirnya akan menghasilkan AnalyzeResult. Ini adalah jenis yang sama dengan beginAnalyzeDocument dan beginAnalyzeDocumentFromUrl, tetapi hasilnya hanya akan berisi subset kecil bidangnya. Hanya bidang documents dan bidang pages yang akan diisi, dan hanya informasi halaman minimal yang akan dikembalikan. Bidang documents akan berisi informasi tentang semua dokumen yang diidentifikasi dan docType yang diklasifikasikan sebagai.

Contoh

Metode ini mendukung ekstraksi data dari file di URL tertentu. Layanan Form Recognizer akan mencoba mengunduh file menggunakan URL yang dikirimkan, sehingga URL harus dapat diakses dari internet publik. Misalnya, token SAS dapat digunakan untuk memberikan akses baca ke blob di Azure Storage, dan layanan akan menggunakan URL yang dikodekan SAS untuk meminta file.

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

Detail Konstruktor

DocumentAnalysisClient(string, KeyCredential, DocumentAnalysisClientOptions)

Buat instans DocumentAnalysisClient dari titik akhir sumber daya dan kunci API statis (KeyCredential),

Contoh:

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)

Parameter

endpoint

string

URL titik akhir instans Azure Cognitive Services

credential
KeyCredential

KeyCredential yang berisi kunci langganan instans Cognitive Services

options
DocumentAnalysisClientOptions

pengaturan opsional untuk mengonfigurasi semua metode di klien

DocumentAnalysisClient(string, TokenCredential, DocumentAnalysisClientOptions)

Buat instans DocumentAnalysisClient dari titik akhir sumber daya dan Azure Identity TokenCredential.

Lihat paket @azure/identity untuk informasi selengkapnya tentang mengautentikasi dengan Azure Active Directory.

Contoh:

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)

Parameter

endpoint

string

URL titik akhir instans Azure Cognitive Services

credential
TokenCredential

instans TokenCredential dari paket @azure/identity

options
DocumentAnalysisClientOptions

pengaturan opsional untuk mengonfigurasi semua metode di klien

Detail Metode

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

Ekstrak data dari input menggunakan model yang diberikan oleh ID uniknya.

Operasi ini mendukung model kustom serta bawaan. Misalnya, untuk menggunakan model faktur bawaan, berikan ID model "prebuilt-invoice", atau untuk menggunakan model tata letak bawaan yang lebih sederhana, berikan ID model "prebuilt-layout".

Bidang yang dihasilkan dalam AnalyzeResult bergantung pada model yang digunakan untuk analisis, dan nilai dalam bidang dokumen yang diekstrak bergantung pada jenis dokumen dalam model (jika ada) dan skema bidang yang sesuai.

Contoh

Metode ini mendukung badan permintaan yang dapat dialirkan (FormRecognizerRequestBody) seperti objek Node.JS ReadableStream, Blobbrowser, dan ArrayBuffers. Konten isi akan diunggah ke layanan untuk analisis.

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

Parameter

modelId

string

ID unik (nama) model dalam sumber daya klien ini

document
FormRecognizerRequestBody

FormRecognizerRequestBody yang akan diunggah dengan permintaan

options

AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>

pengaturan opsional untuk operasi analisis dan poller

Mengembalikan

operasi jangka panjang (poller) yang pada akhirnya akan menghasilkan AnalyzeResult

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

Ekstrak data dari input menggunakan model yang memiliki skema dokumen yang diketahui dan diketik dengan kuat (DocumentModel ).

Bidang yang dihasilkan dalam AnalyzeResult bergantung pada model yang digunakan untuk analisis. Dalam TypeScript, jenis hasil untuk kelebihan beban metode ini disimpulkan dari jenis input DocumentModel.

Contoh

Metode ini mendukung badan permintaan yang dapat dialirkan (FormRecognizerRequestBody) seperti objek Node.JS ReadableStream, Blobbrowser, dan ArrayBuffers. Konten isi akan diunggah ke layanan untuk analisis.

Jika input yang disediakan adalah string, input akan diperlakukan sebagai URL ke lokasi dokumen yang akan dianalisis. Lihat metode beginAnalyzeDocumentFromUrl untuk informasi selengkapnya. Penggunaan metode tersebut lebih disukai saat menggunakan URL, dan dukungan URL hanya disediakan dalam metode ini untuk kompatibilitas mundur.

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

Parameter

model

DocumentModel<Result>

DocumentModel mewakili model yang akan digunakan untuk analisis dan jenis output yang diharapkan

document
FormRecognizerRequestBody

FormRecognizerRequestBody yang akan diunggah dengan permintaan

options

AnalyzeDocumentOptions<Result>

pengaturan opsional untuk operasi analisis dan poller

Mengembalikan

Promise<AnalysisPoller<Result>>

operasi jangka panjang (poller) yang pada akhirnya akan menghasilkan AnalyzeResult dengan dokumen yang memiliki jenis hasil yang terkait dengan model input

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

Ekstrak data dari input menggunakan model yang diberikan oleh ID uniknya.

Operasi ini mendukung model kustom serta bawaan. Misalnya, untuk menggunakan model faktur bawaan, berikan ID model "prebuilt-invoice", atau untuk menggunakan model tata letak bawaan yang lebih sederhana, berikan ID model "prebuilt-layout".

Bidang yang dihasilkan dalam AnalyzeResult bergantung pada model yang digunakan untuk analisis, dan nilai dalam bidang dokumen yang diekstrak bergantung pada jenis dokumen dalam model (jika ada) dan skema bidang yang sesuai.

Contoh

Metode ini mendukung ekstraksi data dari file di URL tertentu. Layanan Form Recognizer akan mencoba mengunduh file menggunakan URL yang dikirimkan, sehingga URL harus dapat diakses dari internet publik. Misalnya, token SAS dapat digunakan untuk memberikan akses baca ke blob di Azure Storage, dan layanan akan menggunakan URL yang dikodekan SAS untuk meminta file.

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

Parameter

modelId

string

ID unik (nama) model dalam sumber daya klien ini

documentUrl

string

URL (string) ke dokumen input yang dapat diakses dari internet publik

options

AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>

pengaturan opsional untuk operasi analisis dan poller

Mengembalikan

operasi jangka panjang (poller) yang pada akhirnya akan menghasilkan AnalyzeResult

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

Ekstrak data dari input menggunakan model yang memiliki skema dokumen yang diketahui dan diketik dengan kuat (DocumentModel ).

Bidang yang dihasilkan dalam AnalyzeResult bergantung pada model yang digunakan untuk analisis. Dalam TypeScript, jenis hasil untuk kelebihan beban metode ini disimpulkan dari jenis input DocumentModel.

Contoh

Metode ini mendukung ekstraksi data dari file di URL tertentu. Layanan Form Recognizer akan mencoba mengunduh file menggunakan URL yang dikirimkan, sehingga URL harus dapat diakses dari internet publik. Misalnya, token SAS dapat digunakan untuk memberikan akses baca ke blob di Azure Storage, dan layanan akan menggunakan URL yang dikodekan SAS untuk meminta file.

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

Parameter

model

DocumentModel<Result>

DocumentModel mewakili model yang akan digunakan untuk analisis dan jenis output yang diharapkan

documentUrl

string

URL (string) ke dokumen input yang dapat diakses dari internet publik

options

AnalyzeDocumentOptions<Result>

pengaturan opsional untuk operasi analisis dan poller

Mengembalikan

Promise<AnalysisPoller<Result>>

operasi jangka panjang (poller) yang pada akhirnya akan menghasilkan AnalyzeResult

beginClassifyDocument(string, FormRecognizerRequestBody, ClassifyDocumentOptions)

Mengklasifikasikan dokumen menggunakan pengklasifikasi kustom yang diberikan oleh ID-nya.

Metode ini menghasilkan operasi jangka panjang (poller) yang akhirnya akan menghasilkan AnalyzeResult. Ini adalah jenis yang sama dengan beginAnalyzeDocument dan beginAnalyzeDocumentFromUrl, tetapi hasilnya hanya akan berisi subset kecil bidangnya. Hanya bidang documents dan bidang pages yang akan diisi, dan hanya informasi halaman minimal yang akan dikembalikan. Bidang documents akan berisi informasi tentang semua dokumen yang diidentifikasi dan docType yang diklasifikasikan sebagai.

Contoh

Metode ini mendukung badan permintaan yang dapat dialirkan (FormRecognizerRequestBody) seperti objek Node.JS ReadableStream, Blobbrowser, dan ArrayBuffers. Konten isi akan diunggah ke layanan untuk analisis.

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

Parameter

classifierId

string

ID pengklasifikasi kustom yang akan digunakan untuk analisis

document
FormRecognizerRequestBody

dokumen yang akan diklasifikasikan

options
ClassifyDocumentOptions

opsi untuk operasi klasifikasi

Mengembalikan

operasi jangka panjang (poller) yang pada akhirnya akan menghasilkan AnalyzeResult

beginClassifyDocumentFromUrl(string, string, ClassifyDocumentOptions)

Mengklasifikasikan dokumen dari URL menggunakan pengklasifikasi kustom yang diberikan oleh ID-nya.

Metode ini menghasilkan operasi jangka panjang (poller) yang akhirnya akan menghasilkan AnalyzeResult. Ini adalah jenis yang sama dengan beginAnalyzeDocument dan beginAnalyzeDocumentFromUrl, tetapi hasilnya hanya akan berisi subset kecil bidangnya. Hanya bidang documents dan bidang pages yang akan diisi, dan hanya informasi halaman minimal yang akan dikembalikan. Bidang documents akan berisi informasi tentang semua dokumen yang diidentifikasi dan docType yang diklasifikasikan sebagai.

Contoh

Metode ini mendukung ekstraksi data dari file di URL tertentu. Layanan Form Recognizer akan mencoba mengunduh file menggunakan URL yang dikirimkan, sehingga URL harus dapat diakses dari internet publik. Misalnya, token SAS dapat digunakan untuk memberikan akses baca ke blob di Azure Storage, dan layanan akan menggunakan URL yang dikodekan SAS untuk meminta file.

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

Parameter

classifierId

string

ID pengklasifikasi kustom yang akan digunakan untuk analisis

documentUrl

string

URL dokumen yang akan diklasifikasikan

Mengembalikan