İngilizce dilinde oku

Aracılığıyla paylaş


JavaScript için Azure DocumentIntelligence (eski adıyla FormRecognizer) REST istemci kitaplığı - sürüm 1.0.0

Belgelerden içerik, düzen ve yapılandırılmış verileri ayıklar.

Bu kitaplığı kullanmak için REST istemci belgelerimize

NOT: Form Tanıma, Belge Zekası olarak yeniden markalandı. lütfen 'den Geçiş Kılavuzu'na bakın.

Önemli bağlantılar:

İstemci kitaplığının bu sürümü varsayılan olarak hizmetin "2024-11-30" sürümüdür.

Bu tabloda SDK sürümleri ile hizmetin desteklenen API sürümleri arasındaki ilişki gösterilmektedir:

SDK sürümü Hizmetin desteklenen API sürümü
1.0.0 2024-11-30

Lütfen "prebuilt-businessCard" ve "prebuilt-document"gibi kullanımdan kaldırılacak modeller için eski hizmet API'si sürümleri aracılığıyla eski @azure/ai-form-recognizer kitaplığına güvenin. Daha fazla bilgi için bkz. changelog.

Aşağıdaki tabloda her istemcinin ve desteklenen API sürümlerinin ilişkisi açıklanmaktadır:

Hizmet API'si sürümü Desteklenen istemciler Paket
2024-11-30 DocumentIntelligenceClient @azure-rest/ai-document-intelligence sürüm 1.0.0
2023-07-31 DocumentAnalysisClient ve DocumentModelAdministrationClient @azure/ai-form-recognizer sürüm ^5.0.0
2022-08-01 DocumentAnalysisClient ve DocumentModelAdministrationClient @azure/ai-form-recognizer sürüm ^4.0.0

Başlarken

Şu anda desteklenen ortamlar

  • Node.js LTS sürümleri

Önkoşullar

@azure-rest/ai-document-intelligence paketini yükleme

npmile JavaScript için Azure DocumentIntelligence(eski adıFormRecognizer) REST istemcisi REST istemci kitaplığını yükleyin:

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

DocumentIntelligenceClient oluşturma ve kimlik doğrulaması

Azure Active Directory (AAD) belirteci kimlik bilgilerini kullanmak için, @azure/kimlik kitaplığından alınan istenen kimlik bilgisi türünün bir örneğini sağlayın.

AAD ile kimlik doğrulaması yapmak için önce npm yüklemeniz @azure/identity

Kurulumdan sonra, @azure/identity hangi tür kimlik bilgisi kullanılacağını seçebilirsiniz. Örneğin, istemcinin kimliğini doğrulamak için DefaultAzureCredential kullanılabilir.

AAD uygulamasının istemci kimliği, kiracı kimliği ve istemci gizli dizisi değerlerini ortam değişkenleri olarak ayarlayın: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET

Belirteç Kimlik Bilgisi Kullanma

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

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

API KEY kullanma

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

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

Belge Modelleri

Önceden oluşturulmuş düzeni analiz etme (urlSource)

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

Önceden oluşturulmuş düzeni analiz etme (base64Source)

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

İlk yanıttan poller oluşturmaya devam edin

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

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}
const poller = 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'
//   }
// }

Toplu iş analizi

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

// 1. Analyze a batch of documents
const initialResponse = await client
  .path("/documentModels/{modelId}:analyzeBatch", "prebuilt-layout")
  .post({
    contentType: "application/json",
    body: {
      azureBlobSource: {
        containerUrl: batchTrainingFilesContainerUrl(),
      },
      resultContainerUrl: batchTrainingFilesResultContainerUrl(),
      resultPrefix: "result",
    },
  });

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}
const resultId = parseResultIdFromResponse(initialResponse);
console.log("resultId: ", resultId);

// (Optional) You can poll for the batch analysis result but be aware that a job may take unexpectedly long time, and polling could incur additional costs.
// const poller = getLongRunningPoller(client, initialResponse);
// await poller.pollUntilDone();

// 2. At a later time, you can retrieve the operation result using the resultId
const output = await client
  .path("/documentModels/{modelId}/analyzeResults/{resultId}", "prebuilt-layout", resultId)
  .get();
console.log(output);

Markdown içerik biçimi

Varsayılan düz metinmarkdown içerik biçimiyle çıktıyı destekler. Şimdilik bu yalnızca "önceden oluşturulmuş düzen" için desteklenmektedir. Markdown içerik biçimi, bir sohbet veya otomasyon kullanım senaryosunda LLM tüketimi için daha kolay bir biçim olarak kabul edilir.

Hizmet, Markdown biçimi için GFM belirtimini (GitHub Flavored Markdown) izler. Ayrıca sonuç içerik biçimini belirtmek için "text" veya "markdown" değerine sahip yeni bir contentFormat özelliği sunar.

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

Sorgu Alanları

Bu özellik bayrağı belirtildiğinde, hizmet model tarafından geri dönüş olarak tanımlanan mevcut alanları desteklemek için queryFields sorgu parametresi aracılığıyla belirtilen alanların değerlerini daha fazla ayıklar.

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

Bölme Seçenekleri

Eski @azure/ai-form-recognizer kitaplığı tarafından desteklenen önceki API sürümlerinde, belge bölme ve sınıflandırma işlemi ("/documentClassifiers/{classifierId}:analyze") her zaman giriş dosyasını birden çok belgeye bölmeyi denedi.

Daha geniş bir senaryo kümesini etkinleştirmek için hizmet, yeni "2023-10-31-preview" hizmet sürümüne sahip bir "split" sorgu parametresi sunar. Aşağıdaki değerler desteklenir:

  • split: "auto"

    Hizmetin nereye bölüneceğini belirlemesine izin verin.

  • split: "none"

    Dosyanın tamamı tek bir belge olarak değerlendirilir. Bölme işlemi yapılmaz.

  • split: "perPage"

    Her sayfa ayrı bir belge olarak değerlendirilir. Her boş sayfa kendi belgesi olarak tutulur.

Belge Sınıflandırıcıları #Build

ts
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 = 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'
//  }

Belge analizinden oluşturulan PDF çıkışını alma

ts
const filePath = path.join(ASSET_PATH, "layout-pageobject.pdf");

const base64Source = await fs.readFile(filePath, { encoding: "base64" });

const initialResponse = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-read")
  .post({
    contentType: "application/json",
    body: {
      base64Source,
    },
    queryParameters: { output: ["pdf"] },
  });

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}

const poller = getLongRunningPoller(client, initialResponse);

await poller.pollUntilDone();

const output = await client
  .path(
    "/documentModels/{modelId}/analyzeResults/{resultId}/pdf",
    "prebuilt-read",
    parseResultIdFromResponse(initialResponse)
  )
  .get()
  .asNodeStream(); // output.body would be NodeJS.ReadableStream

if (output.status !== "200" || !output.body) {
  throw new Error("The response was unexpected, expected NodeJS.ReadableStream in the body.");
}

const pdfData = await streamToUint8Array(output.body);
fs.promises.writeFile(`./output.pdf`, pdfData);
// Or you can consume the NodeJS.ReadableStream directly

Belge analizinden belirtilen şeklin oluşturulan kırpılmış görüntüsünü alma

ts
const filePath = path.join(ASSET_PATH, "layout-pageobject.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: { output: ["figures"] },
  });

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}

const poller = getLongRunningPoller(client, initialResponse, { ...testPollingOptions });

const result = (await poller.pollUntilDone()).body as AnalyzeResultOperationOutput;
const figures = result.analyzeResult?.figures;
assert.isArray(figures);
assert.isNotEmpty(figures?.[0]);
const figureId = figures?.[0].id || "";
assert.isDefined(figureId);

const output = await client
  .path(
    "/documentModels/{modelId}/analyzeResults/{resultId}/figures/{figureId}",
    "prebuilt-layout",
    parseResultIdFromResponse(initialResponse),
    figureId
  )
  .get()
  .asNodeStream(); // output.body would be NodeJS.ReadableStream

if (output.status !== "200" || !output.body) {
  throw new Error("The response was unexpected, expected NodeJS.ReadableStream in the body.");
}

const imageData = await streamToUint8Array(output.body);
fs.promises.writeFile(`./figures/${figureId}.png`, imageData);
// Or you can consume the NodeJS.ReadableStream directly

Bilgi Al

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

Belge Modellerini Listele

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

Sorun giderme

Günlük tutmak

Günlüğe kaydetmeyi etkinleştirmek, hatalarla ilgili yararlı bilgilerin ortaya çıkmasına yardımcı olabilir. HTTP isteklerinin ve yanıtlarının günlüğünü görmek için AZURE_LOG_LEVEL ortam değişkenini infoolarak ayarlayın. Alternatif olarak, @azure/loggersetLogLevel çağrılarak günlükler çalışma zamanında etkinleştirilebilir:

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

setLogLevel("info");

Günlükleri etkinleştirme hakkında daha ayrıntılı yönergeler için@azure/günlükçü paketi belgelerine bakabilirsiniz.