JavaScript용 Azure AI Document Intelligence 클라이언트 라이브러리 - 버전 5.0.0

Azure AI 문서 인텔리전스 는 기계 학습을 사용하여 문서에서 텍스트 및 구조화된 데이터를 분석하는 클라우드 서비스입니다. 여기에는 다음과 같은 기본 기능이 포함됩니다.

  • 레이아웃 - 문서에서 경계 영역 좌표와 함께 텍스트, 테이블 구조 및 선택 표시를 추출합니다.
  • 문서 - 미리 빌드된 일반 문서 모델을 사용하여 문서에서 엔터티, 키-값 쌍, 테이블 및 선택 표시를 분석합니다.
  • 읽기 - 텍스트 언어 정보 외에도 페이지 단어 및 줄과 같은 텍스트 요소에 대한 정보를 읽습니다.
  • 미리 빌드 - 미리 빌드된 모델을 사용하여 특정 유형의 일반 문서(예: 영수증, 청구서, 명함 또는 ID 문서)의 데이터를 분석합니다.
  • 사용자 지정 - 문서에서 텍스트, 필드 값, 선택 표시 및 테이블 데이터를 추출하는 사용자 지정 모델을 빌드합니다. 사용자 지정 모델은 사용자 고유의 데이터로 빌드되므로 문서에 맞게 조정됩니다.
  • 분류자 - 문서를 미리 정의된 클래스로 분류하는 사용자 지정 분류자를 빌드합니다.

소스 코드 | 패키지(NPM) | API 참조 설명서 | 제품 설명서 | 샘플

참고

문서 인텔리전스 서비스는 이전에 "Azure Form Recognizer"로 알려졌습니다. 이러한 서비스는 하나와 동일하며 @azure/ai-form-recognizer JavaScript 패키지는 Azure AI Document Intelligence 서비스에 대한 Azure SDK 패키지입니다. 작성 시 Azure FORM RECOGNIZER Azure AI Document Intelligence로의 이름 바꾸기가 진행 중이므로 "Form Recognizer" 및 "문서 인텔리전스"를 경우에 따라 서로 바꿔 사용할 수 있습니다.

@azure/ai-form-recognizer 패키지를 설치합니다.

를 사용하여 JavaScript용 Azure Document Intelligence 클라이언트 라이브러리를 npm설치합니다.

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

현재 지원되는 환경

자세한 내용은 지원 정책을 참조하세요.

필수 구성 요소

Form Recognizer 리소스 만들기

참고: 작성 당시 Azure Portal 여전히 리소스를 "Form Recognizer" 리소스로 참조합니다. 나중에 "문서 인텔리전스" 리소스로 업데이트될 수 있습니다. 지금은 다음 설명서에서 "Form Recognizer" 이름을 사용합니다.

Document Intelligence는 다중 서비스 및 단일 서비스 액세스를 모두 지원합니다. 단일 엔드포인트/키에서 여러 Cognitive Services에 액세스하려는 경우 Cognitive Services 리소스를 만듭니다. Form Recognizer 리소스를 Form Recognizer 액세스 전용으로 만듭니다.

를 사용하여 리소스를 만들 수 있습니다.

옵션 1:Azure Portal

옵션 2:Azure CLI.

다음은 CLI를 사용하여 Form Recognizer 리소스를 만드는 방법의 예입니다.

# 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선택하고 이 유형의 instance 만들어야 합니다. 다음 예제에서는 를 사용합니다 DocumentAnalysisClient. Document Intelligence API에 액세스하기 위한 클라이언트 instance 만들려면 Form Recognizer 리소스 및 credential의 가 필요합니다endpoint. 클라이언트는 리소스의 API 키와 함께 또는 Azure Active Directory RBAC를 TokenCredential 사용하여 클라이언트에 권한을 부여하는 를 사용할 AzureKeyCredential 수 있습니다.

Azure Portal에서 또는 아래 AzureCLI 코드 조각을 사용하여 Form Recognizer 리소스에 대한 엔드포인트를 찾을 수 있습니다.

az cognitiveservices account show --name <your-resource-name> --resource-group <your-resource-group-name> --query "properties.endpoint"

API 키 사용

Azure Portal을 사용하여 Form Recognizer 리소스로 이동하고 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 ID 라이브러리를 사용하여 Azure Active Directory로 클라이언트를 인증할 수도 있습니다. 아래에 표시된 DefaultAzureCredential 공급자 또는 Azure SDK와 함께 제공되는 기타 자격 증명 공급자를 사용하려면 패키지를 설치 @azure/identity 하세요.

npm install @azure/identity

서비스 주체를 사용하여 인증하려면 AAD 애플리케이션을 등록 하고 서비스 주체에 역할을 할당하여 "Cognitive Services User" 서비스에 대한 액세스 권한을 부여해야 합니다(참고: 와 같은 "Owner" 다른 역할은 필요한 권한을 부여하지 않으며 예제 및 샘플 코드를 실행하는 데만 "Cognitive Services User" 충분함).

AAD 애플리케이션의 클라이언트 ID, 테넌트 ID 및 클라이언트 암호 값을 환경 변수로 설정합니다. 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- 모델 ID로 지정된 사용자 지정 또는 미리 빌드된 모델을 사용하여 입력 문서 파일 스트림에서 데이터를 추출합니다. 모든 리소스 및 해당 모델 ID/출력에서 지원되는 미리 빌드된 모델에 대한 자세한 내용은 모델의 서비스 설명서를 참조하세요.
  • beginAnalyzeDocumentFromUrl와 동일한 함수 beginAnalyzeDocument를 수행하지만 파일 스트림 대신 공개적으로 액세스할 수 있는 파일 URL을 제출합니다.

DocumentModelAdministrationClient

DocumentModelAdministrationClient 는 리소스에서 모델을 관리(만들기, 읽기, 나열 및 삭제)하는 작업을 제공합니다.

  • beginBuildDocumentModel 는 사용자 고유의 학습 데이터 집합에서 새 문서 모델을 만드는 작업을 시작합니다. 만든 모델은 사용자 지정 스키마에 따라 필드를 추출할 수 있습니다. 학습 데이터는 Azure Storage 컨테이너에 있고 특정 규칙에 따라 구성되어야 합니다. 학습 데이터 집합에 레이블을 적용하는 방법에 대한 자세한 설명은 학습 데이터 집합 만들기에 대한 서비스의 설명서를 참조하세요.
  • beginComposeDocumentModel 는 여러 모델을 단일 모델로 구성하는 작업을 시작합니다. 사용자 지정 양식 인식에 사용되는 경우 새 구성 모델은 먼저 입력 문서의 분류를 수행하여 가장 적합한 하위 모델 중 어느 것을 결정합니다.
  • beginCopyModelTo 는 사용자 지정 모델을 한 리소스에서 다른 리소스(또는 동일한 리소스로)로 복사하는 작업을 시작합니다. 메서드를 CopyAuthorization 사용하여 생성할 수 있는 대상 리소스의 가 getCopyAuthorization 필요합니다.
  • getResourceDetails 는 사용자 지정 모델 수 및 리소스에서 지원할 수 있는 최대 모델 수와 같은 리소스의 제한에 대한 정보를 검색합니다.
  • getDocumentModel, listDocumentModelsdeleteDocumentModel 리소스에서 모델 관리를 사용하도록 설정합니다.
  • getOperation진행 listOperations 중이거나 실패한 작업에서도 모델 만들기 작업의 상태 볼 수 있습니다. 작업은 24시간 동안 유지됩니다.

Document Intelligence 서비스의 그래픽 사용자 인터페이스인 Document Intelligence Studio를 사용하여 모델을 만들 수도 있습니다.

모델을 빌드하는 데 사용하는 DocumentModelAdministrationClient 방법을 보여 주는 샘플 코드 조각은 "모델 빌드" 예제 섹션에서 아래에 나와 있습니다.

장기 실행 작업

LLO(장기 실행 작업)는 작업을 시작하기 위해 서비스로 전송된 초기 요청으로 구성된 작업이며, 작업이 완료되었는지 여부와 실패 또는 성공 여부를 결정하기 위해 특정 간격으로 결과를 폴링합니다. 궁극적으로 LRO는 오류와 함께 실패하거나 결과를 생성합니다.

Azure AI 문서 인텔리전스에서 모델 복사 및 작성을 포함하여 모델을 만드는 작업과 분석/데이터 추출 작업은 LLO입니다. SDK 클라이언트는 개체를 반환 Promise<PollerLike> 하는 비동 begin<operation-name> 기 메서드를 제공합니다. 개체는 PollerLike 서비스의 인프라에서 비동기적으로 실행되는 작업을 나타내며 프로그램은 메서드에서 반환된 폴러에서 begin<operation-name> 메서드를 호출하고 대기하여 pollUntilDone 작업이 완료되기를 기다릴 수 있습니다. 다음 섹션에서 장기 실행 작업을 사용하는 방법을 설명하기 위해 샘플 코드 조각이 제공됩니다.

예제

다음 섹션에서는 Document Intelligence 클라이언트 라이브러리에 사용되는 일반적인 패턴을 보여 주는 여러 JavaScript 코드 조각을 제공합니다.

모델 ID를 사용하여 문서 분석

메서드는 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에서 문서 분석

읽기 가능한 스트림을 제공하는 대신 메서드를 사용하여 공개적으로 액세스할 수 있는 URL을 beginAnalyzeDocumentFromUrl 제공할 수 있습니다. "공개적으로 액세스할 수 있음"은 URL 원본이 서비스의 인프라에서 액세스할 수 있어야 했음을 의미합니다(즉, 헤더 또는 인증서 기반 비밀을 사용하는 개인 인트라넷 URL 또는 URL은 Document Intelligence 서비스에서 URL에 액세스할 수 있어야 하므로 작동하지 않음). 그러나 URL 자체는 쿼리 매개 변수에 SAS 토큰을 포함하는 Azure Storage Blob URL과 같은 비밀을 인코딩할 수 있습니다.

미리 빌드된 문서 모델 사용

또한 이 메서드는 beginAnalyzeDocument 문서 인텔리전스 서비스에서 제공하는 미리 빌드된 모델을 사용하여 영수증, 청구서, 명함, ID 문서 등과 같은 특정 유형의 일반 문서에서 필드를 추출할 수 있습니다. 미리 빌드된 모델은 모델 ID 문자열(사용자 지정 문서 모델과 동일하며 아래의 다른 미리 빌드된 모델 섹션 참조)으로 제공되거나 개체를 DocumentModel 사용할 수 있습니다. 를 DocumentModel사용하는 경우 JavaScript용 Document Intelligence SDK는 모델의 스키마를 기반으로 추출된 문서에 훨씬 더 강력한 TypeScript 형식을 제공하며 JavaScript 명명 규칙을 사용하도록 변환됩니다.

현재 서비스 API 버전(2022-08-31)에 대한 예제 DocumentModel 개체는 샘플 디렉터리에서 prebuilt찾을 수 있습니다. 다음 예제에서는 해당 디렉터리의 [prebuilt-receipt.ts] 파일에서 를 사용합니다PrebuiltReceiptModel.

기반 분석의 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대신 미리 빌드된 영수증의 모델 ID("미리 빌드된 영수증")를 사용할 수 있지만 문서 필드는 TypeScript에 강하게 입력되지 않으며 필드 이름은 일반적으로 "camelCase" 대신 "PascalCase"에 있습니다.

기타 미리 빌드된 모델

당신은 영수증에 국한되지 않습니다! 몇 가지 미리 빌드된 모델 중에서 선택할 수 있으며 더 많은 모델을 선택할 수 있습니다. 미리 빌드된 각 모델에는 지원되는 고유한 필드 집합이 있습니다.

  • 영수증( 위와 같이) 또는 미리 빌드된 영수증 모델 ID "prebuilt-receipt"를 사용합니다 PrebuiltReceiptModel .
  • 또는 모델 ID "prebuilt-businessCard"를 사용하는 PrebuiltBusinessCardModel 명함.
  • 송장, 사용 PrebuiltInvoiceModel 또는 해당 모델 ID "prebuilt-invoice".
  • 또는 모델 ID "prebuilt-idDocument"를 사용하는 PrebuiltIdDocumentModel ID 문서(예: 운전 면허증 및 여권)입니다.
  • W2 Tax Forms(미국) 또는 모델 ID "prebuilt-tax.us.w2"를 사용합니다PrebuiltTaxUsW2Model.
  • [PrebuiltHealthInsuranceCardUsModel][samples-prebuilt-healthinsurancecard.us] 또는 모델 ID "prebuilt-healthInsuranceCard.us"를 사용하여 건강 보험 카드(미국)

위의 미리 빌드된 각 모델은 (모델 필드 스키마의 추출된 인스턴스)를 생성 documents 합니다. 필드 스키마가 없으므로 를 생성 documents하지 않는 세 가지 미리 빌드된 모델도 있습니다. 아래에 이 계정과 키의 예제가 나와 있습니다.

  • 페이지 및 테이블과 같은 OCR(기본 레이아웃) 요소에 대한 정보를 추출하는 미리 빌드된 레이아웃 모델(아래 의 "레이아웃" 사용 참조)입니다.
  • 미리 빌드된 일반 문서 모델(아래 의 "문서" 미리 빌드 사용 참조)은 레이아웃 모델에서 생성된 정보에 키-값 쌍(레이블이 지정된 요소와 같은 페이지 요소 간의 연결 지시)을 추가합니다.
  • 미리 빌드된 읽기 모델(아래 의 "읽기" 미리 빌드 사용 참조)은 문서 언어에 대한 정보와 함께 페이지 단어 및 줄과 같은 텍스트 요소만 추출합니다.

이러한 모든 모델의 필드에 대한 자세한 내용은 미리 빌드된 사용 가능한 모델의 서비스 설명서를 참조하세요.

미리 빌드된 모든 모델의 필드는 의 메서드(모델 IDDocumentModelAdministrationClient)를 사용하여 getDocumentModel 프로그래밍 방식으로 액세스하고 결과에서 필드를 검사할 docTypes 수도 있습니다.

미리 빌드된 "레이아웃" 사용

모델은 "prebuilt-layout" 입력 문서의 텍스트 콘텐츠 내에서 경계 영역 및 범위와 함께 페이지(텍스트 단어/선 및 선택 표시로 구성됨), 테이블 및 시각적 텍스트 스타일과 같은 문서의 기본 요소만 추출합니다. 이 모델을 호출하는 강력한 PrebuiltLayoutModel 형식 DocumentModel 의 instance 제공하거나 항상 모델 ID "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);
});

미리 빌드된 "문서" 사용

모델은 "prebuilt-document" 레이아웃 추출 메서드에서 생성된 속성 외에도 키-값 쌍(레이블이 지정된 필드와 같은 페이지 요소 간 연결)에 대한 정보를 추출합니다. 이 미리 빌드된(일반) 문서 모델은 문서 인텔리전스 서비스의 이전 반복에서 레이블 정보 없이 학습된 사용자 지정 모델과 유사한 기능을 제공하지만 이제는 다양한 문서에서 작동하는 미리 빌드된 모델로 제공됩니다. 이 모델을 호출하는 강력한 PrebuiltDocumentModel 형식 DocumentModel 의 instance 제공하거나 항상 모델 ID "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 의 instance 제공하거나 항상 모델 ID "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 지원합니다. 레이블이 지정된 학습 데이터에서 모델을 빌드하면 사용자 고유의 문서에 대해 학습된 새 모델이 만들어지고, 결과 모델은 해당 문서의 구조에서 값을 인식할 수 있습니다. 모델 빌드 작업은 학습 문서를 보유하는 Azure Storage Blob 컨테이너에 SAS로 인코딩된 URL을 허용합니다. Document Intelligence 서비스의 인프라는 컨테이너의 파일을 읽고 해당 내용을 기반으로 모델을 만듭니다. 학습 데이터 컨테이너를 만들고 구성하는 방법에 대한 자세한 내용은 모델 빌드를 위한 Document Intelligence 서비스의 설명서를 참조하세요.

프로그래밍 방식 모델 만들기를 위해 이러한 방법을 제공하지만 Document Intelligence 서비스 팀은 웹에서 모델을 만들고 관리할 수 있는 대화형 웹 애플리케이션 인 Document Intelligence Studio를 만들었습니다.

예를 들어 다음 프로그램은 SAS로 인코딩된 URL을 사용하여 기존 Azure Storage 컨테이너에 사용자 지정 문서 모델을 빌드합니다.

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

사용자 지정 분류자는 가 아닌 beginBuildDocumentModel메서드를 사용하여 beginBuildDocumentClassifier 비슷한 방식으로 빌드됩니다. 입력 학습 데이터가 약간 다른 형식으로 제공되기 때문에 사용자 지정 분류자를 빌드하는 방법에 대한 자세한 내용은 빌드 분류자 샘플을 참조하세요. 사용자 지정 분류자를 위한 학습 데이터 집합을 빌드하는 방법에 대한 자세한 내용은 문서 인텔리전스 서비스 설명서를 참조하세요.

모델 관리

DocumentModelAdministrationClient 모델 액세스 및 나열을 위한 여러 방법도 제공합니다. 다음 예제에서는 리소스의 모델을 반복하는 방법을 보여 줍니다(리소스의 사용자 지정 모델과 모든 리소스에 공통되는 미리 빌드된 모델 모두 포함), ID로 모델을 가져오고 모델을 삭제합니다.

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 package docs를 참조하세요.

다음 단계

위의 "예제" 섹션에 표시되지 않는 몇 가지 기능 및 메서드(예: 모델 복사 및 작성, 모델 관리 작업 나열 및 모델 삭제)를 포함하여 이 라이브러리를 사용하는 방법을 보여 주는 자세한 코드 샘플은 샘플 디렉터리를 살펴보세요.

참여

이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

Impressions