Pustaka klien REST Azure DocumentIntelligence (sebelumnya FormRecognizer) untuk JavaScript - versi 1.0.0-beta.2

Mengekstrak konten, tata letak, dan data terstruktur dari dokumen.

Harap sangat bergantung pada dokumen klien REST kami untuk menggunakan pustaka ini

CATATAN: Form Recognizer telah berganti nama menjadi Kecerdasan Dokumen. Silakan periksa Panduan Migrasi dari @azure/ai-form-recognizer ke @azure-rest/ai-document-intelligence.

Tautan utama:

Versi pustaka klien ini default ke "2024-02-29-preview" versi layanan.

Tabel ini menunjukkan hubungan antara versi SDK dan versi API layanan yang didukung:

Versi SDK Versi API layanan yang didukung
1.0.0-beta.2 Pratinjau 2024-02-29
1.0.0-beta.1 Pratinjau 10-31-2023

Harap andalkan pustaka yang lebih @azure/ai-form-recognizer lama melalui versi API layanan yang lebih lama untuk model yang dihentikan, seperti "prebuilt-businessCard" dan "prebuilt-document". Untuk informasi selengkapnya, lihat Changelog.

Tabel di bawah ini menjelaskan hubungan setiap klien dan versi API yang didukung:

Versi API Layanan Klien yang didukung Paket
Pratinjau 2024-02-29 DocumentIntelligenceClient @azure-rest/ai-document-intelligence Versi 1.0.0-beta.2
Pratinjau 10-31-2023 DocumentIntelligenceClient @azure-rest/ai-document-intelligence Versi 1.0.0-beta.1
2023-07-31 DocumentAnalysisClient dan DocumentModelAdministrationClient @azure/ai-form-recognizer Versi ^5.0.0
01-08-2022 DocumentAnalysisClient dan DocumentModelAdministrationClient @azure/ai-form-recognizer Versi ^4.0.0

Memulai

Lingkungan yang didukung saat ini

  • Versi LTS dari Node.js

Prasyarat

Pasang paket @azure-rest/ai-document-intelligence

Instal pustaka klien REST klien REST Azure DocumentIntelligence(formerlyFormRecognizer) untuk JavaScript dengan npm:

npm install @azure-rest/ai-document-intelligence

Membuat dan mengautentikasi DocumentIntelligenceClient

Untuk menggunakan kredensial token Azure Active Directory (AAD), berikan instans jenis kredensial yang diinginkan yang diperoleh dari pustaka @azure/identitas .

Untuk mengautentikasi dengan AAD, Anda harus menginstal terlebih dahulu npm@azure/identity

Setelah penyiapan, Anda dapat memilih jenis kredensial@azure/identity mana yang akan digunakan. Sebagai contoh, DefaultAzureCredential dapat digunakan untuk mengautentikasi klien.

Atur nilai ID klien, ID penyewa, dan rahasia klien aplikasi AAD sebagai variabel lingkungan: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET

Menggunakan Kredensial Token

import DocumentIntelligence from "@azure-rest/ai-document-intelligence";

const client = DocumentIntelligence(
  process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"],
  new DefaultAzureCredential()
);

Menggunakan API KEY

import DocumentIntelligence from "@azure-rest/ai-document-intelligence";

const client = DocumentIntelligence(process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"], {
  key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"],
});

Model Dokumen

Menganalisis tata letak bawaan (urlSource)

const initialResponse = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-layout")
  .post({
    contentType: "application/json",
    body: {
      urlSource:
        "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/6704eff082aaaf2d97c1371a28461f512f8d748a/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf",
    },
    queryParameters: { locale: "en-IN" },
  });

Menganalisis tata letak bawaan (base64Source)

import fs from "fs";
import path from "path";

const filePath = path.join(ASSET_PATH, "forms", "Invoice_1.pdf");
const base64Source = fs.readFileSync(filePath, { encoding: "base64" });
const initialResponse = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-layout")
  .post({
    contentType: "application/json",
    body: {
      base64Source,
    },
    queryParameters: { locale: "en-IN" },
  });

Lanjutkan membuat poller dari respons awal

import {
  getLongRunningPoller,
  AnalyzeResultOperationOutput,
  isUnexpected,
} from "@azure-rest/ai-document-intelligence";

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}
const poller = await getLongRunningPoller(client, initialResponse);
const result = (await poller.pollUntilDone()).body as AnalyzeResultOperationOutput;
console.log(result);
// {
//   status: 'succeeded',
//   createdDateTime: '2023-11-10T13:31:31Z',
//   lastUpdatedDateTime: '2023-11-10T13:31:34Z',
//   analyzeResult: {
//     apiVersion: '2023-10-31-preview',
//     .
//     .
//     .
//     contentFormat: 'text'
//   }
// }

Format konten markdown

Mendukung output dengan format konten Markdown bersama dengan teks biasa default. Untuk saat ini, ini hanya didukung untuk "prebuilt-layout". Format konten markdown dianggap sebagai format yang lebih ramah untuk konsumsi LLM dalam skenario penggunaan obrolan atau otomatisasi.

Layanan mengikuti spesifikasi GFM (GitHub Flavored Markdown) untuk format Markdown. Juga memperkenalkan properti contentFormat baru dengan nilai "teks" atau "markdown" untuk menunjukkan format konten hasil.

import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
const client = DocumentIntelligence(process.env["DOCUMENT_INTELLIGENCE_ENDPOINT"], {
  key: process.env["DOCUMENT_INTELLIGENCE_API_KEY"],
});

const initialResponse = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-layout")
  .post({
    contentType: "application/json",
    body: {
      urlSource:
        "https://raw.githubusercontent.com/Azure/azure-sdk-for-js/6704eff082aaaf2d97c1371a28461f512f8d748a/sdk/formrecognizer/ai-form-recognizer/assets/forms/Invoice_1.pdf",
    },
    queryParameters: { outputContentFormat: "markdown" }, // <-- new query parameter
  });

Bidang Kueri

Ketika bendera fitur ini ditentukan, layanan akan lebih mengekstrak nilai bidang yang ditentukan melalui parameter kueri queryFields untuk melengkapi bidang yang ada yang ditentukan oleh model sebagai fallback.

await client.path("/documentModels/{modelId}:analyze", "prebuilt-layout").post({
  contentType: "application/json",
  body: { urlSource: "..." },
  queryParameters: {
    features: ["queryFields"],
    queryFields: ["NumberOfGuests", "StoreNumber"],
  }, // <-- new query parameter
});

Opsi Pemisahan

Dalam versi API sebelumnya yang didukung oleh pustaka yang lebih @azure/ai-form-recognizer lama, pemisahan dokumen dan operasi klasifikasi ("/documentClassifiers/{classifierId}:analyze") selalu mencoba membagi file input menjadi beberapa dokumen.

Untuk mengaktifkan serangkaian skenario yang lebih luas, layanan memperkenalkan parameter kueri "pisahkan" dengan versi layanan "pratinjau 10-10-31" baru. Nilai berikut ini didukung:

  • split: "auto"

    Biarkan layanan menentukan tempat untuk memisahkan.

  • split: "none"

    Seluruh file diperlakukan sebagai satu dokumen. Tidak ada pemisahan yang dilakukan.

  • split: "perPage"

    Setiap halaman diperlakukan sebagai dokumen terpisah. Setiap halaman kosong disimpan sebagai dokumennya sendiri.

#Build Pengklasifikasi Dokumen

import {
  DocumentClassifierBuildOperationDetailsOutput,
  getLongRunningPoller,
  isUnexpected,
} from "@azure-rest/ai-document-intelligence";

const containerSasUrl = (): string =>
  process.env["DOCUMENT_INTELLIGENCE_TRAINING_CONTAINER_SAS_URL"];
const initialResponse = await client.path("/documentClassifiers:build").post({
  body: {
    classifierId: `customClassifier${getRandomNumber()}`,
    description: "Custom classifier description",
    docTypes: {
      foo: {
        azureBlobSource: {
          containerUrl: containerSasUrl(),
        },
      },
      bar: {
        azureBlobSource: {
          containerUrl: containerSasUrl(),
        },
      },
    },
  },
});

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}
const poller = await getLongRunningPoller(client, initialResponse);
const response = (await poller.pollUntilDone())
  .body as DocumentClassifierBuildOperationDetailsOutput;
console.log(response);
//  {
//    operationId: '31466834048_f3ee629e-73fb-48ab-993b-1d55d73ca460',
//    kind: 'documentClassifierBuild',
//    status: 'succeeded',
//    .
//    .
//    result: {
//      classifierId: 'customClassifier10978',
//      createdDateTime: '2023-11-09T12:45:56Z',
//      .
//      .
//      description: 'Custom classifier description'
//    },
//    apiVersion: '2023-10-31-preview'
//  }

Dapatkan Info

const response = await client.path("/info").get();
if (isUnexpected(response)) {
  throw response.body.error;
}
console.log(response.body.customDocumentModels.limit);
// 20000

Mencantumkan Model Dokumen

import { paginate } from "@azure-rest/ai-document-intelligence";
const response = await client.path("/documentModels").get();
if (isUnexpected(response)) {
  throw response.body.error;
}

const modelsInAccount: string[] = [];
for await (const model of paginate(client, response)) {
  console.log(model.modelId);
}

Pemecahan Masalah

Pencatatan

Mengaktifkan pengelogan dapat membantu menemukan informasi yang berguna tentang kegagalan. Untuk melihat log permintaan dan respons HTTP, atur variabel lingkungan AZURE_LOG_LEVEL ke info. Atau, pengelogan dapat diaktifkan saat runtime dengan memanggil setLogLevel di @azure/logger:

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

setLogLevel("info");

Untuk instruksi lebih rinci tentang cara mengaktifkan log, Anda dapat melihat dokumen paket @azure/pencatat.