다음을 통해 공유


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

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

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

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

비고

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

@azure/ai-form-recognizer 패키지 설치

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

npm install @azure/ai-form-recognizer

시작하기

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

// Document Intelligence supports many different types of files.
const file = createReadStream("path/to/file.jpg");
const poller = await client.beginAnalyzeDocument("<model ID>", file);

const { pages, tables, styles, keyValuePairs, documents } = await poller.pollUntilDone();

현재 지원되는 환경

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

필수 조건

Form Recognizer 리소스 만들기

참고: 작성 당시 Azure Portal은 여전히 리소스를 "Form Recognizer" 리소스라고 합니다. 나중에 "Document Intelligence" 리소스로 업데이트될 수 있습니다. 현재 다음 설명서에서는 "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-group-name> 바꾸고 <your-resource-name> 고유한 이름으로 바꿉니다.

az cognitiveservices account create --kind FormRecognizer --resource-group <your-resource-group-name> --name <your-resource-name> --sku <your-sku-name> --location <your-location>

클라이언트 만들기 및 인증Create and authenticate a client

Document Intelligence 서비스와 상호 작용하려면 a DocumentAnalysisClient 또는 a DocumentModelAdministrationClient를 선택하고 이 유형의 인스턴스를 만들어야 합니다. 다음 예에서는 를 사용합니다 DocumentAnalysisClient. Document Intelligence API endpoint 에 액세스하기 위한 클라이언트 인스턴스를 만들려면 Form Recognizer 리소스와 credential. 클라이언트는 리소스 TokenCredential 의 API 키와 함께 사용하거나 AzureKeyCredential Azure Active Directory RBAC를 사용하여 클라이언트에 권한을 부여할 수 있습니다.

Form Recognizer 리소스의 엔드포인트는 Azure Portal 또는 아래 Azure CLI 코드 조각을 사용하여 찾을 수 있습니다.

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 키와 엔드포인트가 있으면 다음과 같이 사용할 수 있습니다.

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

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_ID, AZURE_CLIENT_SECRET)로 설정합니다.

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

소버린 클라우드

클라이언트를 만들 때 옵션을 지정하여 대체 Azure 클라우드 환경(예: Azure China 또는 Azure Government)에 audience 연결합니다. 열거형을 KnownFormRecognizerAudience 사용하여 환경에 적합한 값을 선택합니다.

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

const credential = new DefaultAzureCredential();
const client = new DocumentAnalysisClient(
  "https://<resource name>.cognitiveservices.azure.com", // endpoint
  credential,
  {
    audience: KnownFormRecognizerAudience.AzureGovernment,
  }
);

옵션을 audience 지정하지 않으면 기본값은 Azure 퍼블릭 클라우드()https://cognitiveservices.azure.com에 적합합니다.

주요 개념

DocumentAnalysisClient

DocumentAnalysisClient 사용자 지정 및 미리 빌드된 모델을 사용하여 입력 문서를 분석하기 위한 작업을 제공합니다. 세 가지 방법이 있습니다.

  • beginAnalyzeDocument- 모델 ID로 지정된 사용자 지정 또는 미리 빌드된 모델을 사용하여 입력 문서 파일 스트림에서 데이터를 추출합니다. 모든 리소스에서 지원되는 미리 빌드된 모델 및 해당 모델 ID/출력에 대한 자세한 내용은 모델의 서비스 설명서를 참조하세요.
  • beginAnalyzeDocumentFromUrl는 와 동일한 기능을 beginAnalyzeDocument수행하지만 파일 스트림 대신 공개적으로 액세스할 수 있는 파일의 URL을 제출합니다.

DocumentModelAdministrationClient

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

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

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

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

장기간 실행되는 작업

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

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

예시

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

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

beginAnalyzeDocument 방법은 문서에서 필드와 테이블 데이터를 추출할 수 있습니다. 분석은 사용자 고유의 데이터로 학습된 사용자 지정 모델 또는 서비스에서 제공하는 미리 빌드된 모델을 사용할 수 있습니다(아래의 미리 빌드된 모델 사용 참조). 사용자 지정 모델은 사용자 고유의 문서에 맞게 조정되므로 모델의 문서 유형 중 하나와 동일한 구조의 문서에만 사용해야 합니다(구성형 모델과 같이 여러 문서가 있을 수 있음).

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

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 content '${field.content}' 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}"`);
  }
}

URL에서 문서 분석

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

사전 구축된 문서 모델 사용

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

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

기반 분석의 DocumentModel주요 이점은 더 강력한 TypeScript 유형 제약 조건이므로 다음 샘플은 ECMAScript 모듈 구문을 사용하여 TypeScript로 작성되었습니다.

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

또는 위에서 언급했듯이 더 강력한 반환 유형을 생성하는 를 사용하는 PrebuiltReceiptModel대신 미리 빌드된 영수증의 모델 ID("미리 빌드된 영수증")를 사용할 수 있지만 문서 필드는 TypeScript에서 강력하게 입력되지 않으며 필드 이름은 일반적으로 "camelCase" 대신 "PascalCase"입니다.

다른 사전 구축된 모델

영수증에만 국한되지 않습니다! 선택할 수 있는 몇 가지 사전 구축된 모델이 있으며 더 많은 모델이 출시될 예정입니다. 미리 빌드된 각 모델에는 고유한 지원 필드 집합이 있습니다.

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

위의 미리 빌드된 각 모델은 (모델의 필드 스키마의 추출된 인스턴스)를 생성합니다 documents . 또한 필드 스키마가 없으므로 생성 documents하지 않는 세 가지 사전 빌드된 모델이 있습니다. 그들은 다음과 같습니다.

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

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

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

사전 빌드된 "레이아웃" 사용

"prebuilt-layout" 모델은 페이지(텍스트 단어/선 및 선택 표시로 구성됨), 테이블 및 시각적 텍스트 스타일과 같은 문서의 기본 요소만 입력 문서의 텍스트 콘텐츠 내에 있는 경계 영역 및 범위와 함께 추출합니다. 이 모델을 호출하는 강력한 형식의 DocumentModel 인스턴스인 named PrebuiltLayoutModel 를 제공하거나, 항상 그렇듯이 해당 모델 ID "prebuilt-layout" 를 직접 사용할 수 있습니다.

기반 분석의 DocumentModel주요 이점은 더 강력한 TypeScript 유형 제약 조건이므로 다음 샘플은 ECMAScript 모듈 구문을 사용하여 TypeScript로 작성되었습니다.

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
import { createReadStream } from "node:fs";
import { PrebuiltLayoutModel } from "../samples-dev/prebuilt/prebuilt-layout.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);

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

미리 빌드된 "문서" 사용

"prebuilt-document" 모델은 레이아웃 추출 방법에서 생성된 속성 외에도 키-값 쌍(레이블이 지정된 필드와 같은 페이지 요소 간의 지시된 연결)에 대한 정보를 추출합니다. 이 미리 빌드된(일반) 문서 모델은 Document Intelligence 서비스의 이전 반복에서 레이블 정보 없이 학습된 사용자 지정 모델과 유사한 기능을 제공하지만 이제는 다양한 문서에서 작동하는 미리 빌드된 모델로 제공됩니다. 이 모델을 호출하는 강력한 형식의 DocumentModel 인스턴스인 named PrebuiltDocumentModel 를 제공하거나, 항상 그렇듯이 해당 모델 ID "prebuilt-document" 를 직접 사용할 수 있습니다.

기반 분석의 DocumentModel주요 이점은 더 강력한 TypeScript 유형 제약 조건이므로 다음 샘플은 ECMAScript 모듈 구문을 사용하여 TypeScript로 작성되었습니다.

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
import { createReadStream } from "node:fs";
import { PrebuiltDocumentModel } from "../samples-dev/prebuilt/prebuilt-document.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);

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

사전 빌드된 "읽기" 사용

"prebuilt-read" 모델은 문서에서 단어 및 단락과 같은 텍스트 정보를 추출하고 해당 텍스트의 언어와 문체(예: 손글씨 vs. 조판)를 분석합니다. 이 모델을 호출하는 강력한 형식의 DocumentModel 인스턴스인 named PrebuiltReadModel 를 제공하거나, 항상 그렇듯이 해당 모델 ID "prebuilt-read" 를 직접 사용할 수 있습니다.

기반 분석의 DocumentModel주요 이점은 더 강력한 TypeScript 유형 제약 조건이므로 다음 샘플은 ECMAScript 모듈 구문을 사용하여 TypeScript로 작성되었습니다.

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentAnalysisClient } from "@azure/ai-form-recognizer";
import { createReadStream } from "node:fs";
import { PrebuiltReadModel } from "../samples-dev/prebuilt/prebuilt-read.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);

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

function* getTextOfSpans(content, spans) {
  for (const span of spans) {
    yield content.slice(span.offset, span.offset + span.length);
  }
}

문서 분류

Document Intelligence 서비스는 학습 데이터 집합을 기반으로 문서를 미리 정의된 범주 집합으로 분류할 수 있는 사용자 지정 문서 분류자를 지원합니다. 문서는 의 DocumentAnalysisClient메소드를 사용하여 사용자 지정 분류자로 분류할 수 있습니다beginClassifyDocument. 위와 같이 beginAnalyzeDocument 이 메서드는 분류할 문서가 포함된 파일 또는 스트림을 허용하며, 대신 문서에 대한 공개적으로 액세스할 수 있는 URL을 허용하는 해당 항목이 있습니다 beginClassifyDocumentFromUrl .

다음 샘플에서는 사용자 지정 분류자를 사용하여 문서를 분류하는 방법을 보여 줍니다.

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

사용자 지정 분류자 학습에 대한 자세한 내용은 다음 섹션의 끝에 있는 분류자 학습 섹션을 참조하세요.

모델 빌드

SDK는 클래스를 사용하여 DocumentModelAdministrationClient 모델을 만드는 것도 지원합니다. 레이블이 지정된 학습 데이터에서 모델을 빌드하면 사용자 고유의 문서에서 학습된 새 모델이 만들어지고 결과 모델은 해당 문서의 구조에서 값을 인식할 수 있습니다. 모델 빌드 작업은 학습 문서를 포함하는 Azure Storage Blob 컨테이너에 대한 SAS로 인코딩된 URL을 허용합니다. Document Intelligence 서비스의 인프라는 컨테이너의 파일을 읽고 해당 내용을 기반으로 모델을 만듭니다. 학습 데이터 컨테이너를 만들고 구성하는 방법에 대한 자세한 내용은 모델 빌드에 대한 Document Intelligence 서비스 설명서를 참조하세요.

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

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

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

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

const containerSasUrl = "<SAS url to the blob container storing training documents>";

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

사용자 지정 분류자는 가 아닌 beginBuildDocumentModel메서드를 사용하여 beginBuildDocumentClassifier 유사한 방식으로 구축됩니다. 입력 훈련 데이터가 약간 다른 형식으로 제공되므로 사용자 지정 분류자를 빌드하는 방법에 대한 자세한 내용은 빌드 분류자 샘플을 참조하세요. 사용자 지정 분류자에 대한 학습 데이터 집합을 빌드하는 방법에 대한 자세한 내용은 Document Intelligence 서비스 설명서를 참조하세요.

모델 관리

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

import { DefaultAzureCredential } from "@azure/identity";
import { DocumentModelAdministrationClient } from "@azure/ai-form-recognizer";

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

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

유사한 메소드 listDocumentClassifiers 를 사용하여 getDocumentClassifier 사용자 지정 분류자를 삭제하는 것 외에도 deleteDocumentClassifier 사용자 지정 분류자에 대한 정보를 나열하고 가져올 수 있습니다.

문제 해결

문제 해결에 대한 지원은 문제 해결 가이드참조하세요.

로깅 (로그 기록)

로깅을 사용하도록 설정하면 오류에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 환경 변수AZURE_LOG_LEVELinfo .로 설정합니다. 또는 다음을 호출 setLogLevel 하여 런타임에 로깅을 @azure/logger사용하도록 설정할 수 있습니다.

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

로그를 사용하도록 설정하는 방법에 대한 자세한 지침은 @azure/로거 패키지 문서를 참조하세요.

다음 단계

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

기여하기

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