DocumentAnalysisClient class
Form Recognizer 서비스의 분석 기능과 상호 작용하기 위한 클라이언트입니다.
예제:
Form Recognizer 서비스 및 클라이언트는 두 가지 인증 방법을 지원합니다.
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,
);
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,
);
생성자
| Document |
리소스 엔드포인트 및 정적 API 키( 본보기:
|
| Document |
리소스 엔드포인트 및 Azure ID Azure Active Directory 인증에 대한 자세한 내용은 본보기:
|
메서드
| begin |
고유 ID로 지정된 모델을 사용하여 입력에서 데이터를 추출합니다. 이 작업은 미리 빌드된 모델뿐만 아니라 사용자 지정도 지원합니다. 예를 들어 미리 빌드된 청구서 모델을 사용하려면 모델 ID "prebuilt-invoice"를 제공하거나 더 간단한 미리 빌드된 레이아웃 모델을 사용하려면 모델 ID "미리 빌드된 레이아웃"을 제공합니다.
예제이 메서드는 Node.JS 개체, 브라우저
|
| begin |
강력한 형식의 알려진 문서 스키마(DocumentModel)가 있는 모델을 사용하여 입력에서 데이터를 추출합니다.
예제이 메서드는 Node.JS 개체, 브라우저 제공된 입력이 문자열인 경우 분석할 문서의 위치에 대한 URL로 처리됩니다. 자세한 내용은 beginAnalyzeDocumentFromUrl 메서드를 참조하세요. URL을 사용할 때는 이 메서드를 사용하는 것이 좋습니다. URL 지원은 이전 버전과의 호환성을 위해 이 메서드에서만 제공됩니다.
|
| begin |
고유 ID로 지정된 모델을 사용하여 입력에서 데이터를 추출합니다. 이 작업은 미리 빌드된 모델뿐만 아니라 사용자 지정도 지원합니다. 예를 들어 미리 빌드된 청구서 모델을 사용하려면 모델 ID "prebuilt-invoice"를 제공하거나 더 간단한 미리 빌드된 레이아웃 모델을 사용하려면 모델 ID "미리 빌드된 레이아웃"을 제공합니다.
예제이 메서드는 지정된 URL의 파일에서 데이터 추출을 지원합니다. Form Recognizer 서비스는 제출된 URL을 사용하여 파일을 다운로드하려고 시도하므로 공용 인터넷에서 URL에 액세스할 수 있어야 합니다. 예를 들어 SAS 토큰을 사용하여 Azure Storage의 Blob에 대한 읽기 권한을 부여할 수 있으며, 서비스는 SAS로 인코딩된 URL을 사용하여 파일을 요청합니다.
|
| begin |
강력한 형식의 알려진 문서 스키마(DocumentModel)가 있는 모델을 사용하여 입력에서 데이터를 추출합니다.
예제이 메서드는 지정된 URL의 파일에서 데이터 추출을 지원합니다. Form Recognizer 서비스는 제출된 URL을 사용하여 파일을 다운로드하려고 시도하므로 공용 인터넷에서 URL에 액세스할 수 있어야 합니다. 예를 들어 SAS 토큰을 사용하여 Azure Storage의 Blob에 대한 읽기 권한을 부여할 수 있으며, 서비스는 SAS로 인코딩된 URL을 사용하여 파일을 요청합니다.
|
| begin |
ID로 지정된 사용자 지정 분류자를 사용하여 문서를 분류합니다. 이 메서드는 결국 본보기이 메서드는 Node.JS 개체, 브라우저
|
| begin |
ID로 지정된 사용자 지정 분류자를 사용하여 URL에서 문서를 분류합니다. 이 메서드는 결국 본보기이 메서드는 지정된 URL의 파일에서 데이터 추출을 지원합니다. Form Recognizer 서비스는 제출된 URL을 사용하여 파일을 다운로드하려고 시도하므로 공용 인터넷에서 URL에 액세스할 수 있어야 합니다. 예를 들어 SAS 토큰을 사용하여 Azure Storage의 Blob에 대한 읽기 권한을 부여할 수 있으며, 서비스는 SAS로 인코딩된 URL을 사용하여 파일을 요청합니다.
|
생성자 세부 정보
DocumentAnalysisClient(string, KeyCredential, DocumentAnalysisClientOptions)
리소스 엔드포인트 및 정적 API 키(DocumentAnalysisClient)에서 KeyCredential 인스턴스 만들기
본보기:
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)
매개 변수
- endpoint
-
string
Azure Cognitive Services 인스턴스의 엔드포인트 URL
- credential
- KeyCredential
Cognitive Services 인스턴스 구독 키를 포함하는 KeyCredential
- options
- DocumentAnalysisClientOptions
클라이언트의 모든 메서드를 구성하기 위한 선택적 설정
DocumentAnalysisClient(string, TokenCredential, DocumentAnalysisClientOptions)
리소스 엔드포인트 및 Azure ID DocumentAnalysisClientTokenCredential 인스턴스를 만듭니다.
Azure Active Directory 인증에 대한 자세한 내용은 @azure/identity 패키지를 참조하세요.
본보기:
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)
매개 변수
- endpoint
-
string
Azure Cognitive Services 인스턴스의 엔드포인트 URL
- credential
- TokenCredential
@azure/identity 패키지의 TokenCredential 인스턴스
- options
- DocumentAnalysisClientOptions
클라이언트의 모든 메서드를 구성하기 위한 선택적 설정
메서드 세부 정보
beginAnalyzeDocument(string, FormRecognizerRequestBody, AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>)
고유 ID로 지정된 모델을 사용하여 입력에서 데이터를 추출합니다.
이 작업은 미리 빌드된 모델뿐만 아니라 사용자 지정도 지원합니다. 예를 들어 미리 빌드된 청구서 모델을 사용하려면 모델 ID "prebuilt-invoice"를 제공하거나 더 간단한 미리 빌드된 레이아웃 모델을 사용하려면 모델 ID "미리 빌드된 레이아웃"을 제공합니다.
AnalyzeResult 생성된 필드는 분석에 사용되는 모델에 따라 달라지며 추출된 문서 필드의 값은 모델의 문서 형식(있는 경우)과 해당 필드 스키마에 따라 달라집니다.
예제
이 메서드는 Node.JS 개체, 브라우저 ReadableStream및 Blobs와 같은 스트리밍 가능한 요청 본문(ArrayBuffer)을 지원합니다. 본문의 내용은 분석을 위해 서비스에 업로드됩니다.
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>>>
매개 변수
- modelId
-
string
이 클라이언트의 리소스 내에서 모델의 고유 ID(이름)입니다.
- document
- FormRecognizerRequestBody
요청과 함께 업로드될 FormRecognizerRequestBody
분석 작업 및 폴러에 대한 선택적 설정
반환
Promise<AnalysisPoller<AnalyzeResult<AnalyzedDocument>>>
결국 AnalyzeResult 생성하는 장기 실행 작업(폴러)입니다.
beginAnalyzeDocument<Result>(DocumentModel<Result>, FormRecognizerRequestBody, AnalyzeDocumentOptions<Result>)
강력한 형식의 알려진 문서 스키마(DocumentModel)가 있는 모델을 사용하여 입력에서 데이터를 추출합니다.
AnalyzeResult 생성된 필드는 분석에 사용되는 모델에 따라 달라집니다. TypeScript에서 이 메서드 오버로드에 대한 결과의 형식은 입력 DocumentModel형식에서 유추됩니다.
예제
이 메서드는 Node.JS 개체, 브라우저 ReadableStream및 Blobs와 같은 스트리밍 가능한 요청 본문(ArrayBuffer)을 지원합니다. 본문의 내용은 분석을 위해 서비스에 업로드됩니다.
제공된 입력이 문자열인 경우 분석할 문서의 위치에 대한 URL로 처리됩니다. 자세한 내용은 beginAnalyzeDocumentFromUrl 메서드를 참조하세요. URL을 사용할 때는 이 메서드를 사용하는 것이 좋습니다. URL 지원은 이전 버전과의 호환성을 위해 이 메서드에서만 제공됩니다.
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>>
매개 변수
- model
-
DocumentModel<Result>
분석 및 예상 출력 형식에 사용할 모델을 나타내는 DocumentModel
- document
- FormRecognizerRequestBody
요청과 함께 업로드될 FormRecognizerRequestBody
- options
-
AnalyzeDocumentOptions<Result>
분석 작업 및 폴러에 대한 선택적 설정
반환
Promise<AnalysisPoller<Result>>
결과 형식이 입력 모델과 연결된 문서로 AnalyzeResult 생성하는 장기 실행 작업(폴러)입니다.
beginAnalyzeDocumentFromUrl(string, string, AnalyzeDocumentOptions<AnalyzeResult<AnalyzedDocument>>)
고유 ID로 지정된 모델을 사용하여 입력에서 데이터를 추출합니다.
이 작업은 미리 빌드된 모델뿐만 아니라 사용자 지정도 지원합니다. 예를 들어 미리 빌드된 청구서 모델을 사용하려면 모델 ID "prebuilt-invoice"를 제공하거나 더 간단한 미리 빌드된 레이아웃 모델을 사용하려면 모델 ID "미리 빌드된 레이아웃"을 제공합니다.
AnalyzeResult 생성된 필드는 분석에 사용되는 모델에 따라 달라지며 추출된 문서 필드의 값은 모델의 문서 형식(있는 경우)과 해당 필드 스키마에 따라 달라집니다.
예제
이 메서드는 지정된 URL의 파일에서 데이터 추출을 지원합니다. Form Recognizer 서비스는 제출된 URL을 사용하여 파일을 다운로드하려고 시도하므로 공용 인터넷에서 URL에 액세스할 수 있어야 합니다. 예를 들어 SAS 토큰을 사용하여 Azure Storage의 Blob에 대한 읽기 권한을 부여할 수 있으며, 서비스는 SAS로 인코딩된 URL을 사용하여 파일을 요청합니다.
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>>>
매개 변수
- modelId
-
string
이 클라이언트의 리소스 내에서 모델의 고유 ID(이름)입니다.
- documentUrl
-
string
공용 인터넷에서 액세스할 수 있는 입력 문서에 대한 URL(문자열)
분석 작업 및 폴러에 대한 선택적 설정
반환
Promise<AnalysisPoller<AnalyzeResult<AnalyzedDocument>>>
결국 AnalyzeResult 생성하는 장기 실행 작업(폴러)입니다.
beginAnalyzeDocumentFromUrl<Result>(DocumentModel<Result>, string, AnalyzeDocumentOptions<Result>)
강력한 형식의 알려진 문서 스키마(DocumentModel)가 있는 모델을 사용하여 입력에서 데이터를 추출합니다.
AnalyzeResult 생성된 필드는 분석에 사용되는 모델에 따라 달라집니다. TypeScript에서 이 메서드 오버로드에 대한 결과의 형식은 입력 DocumentModel형식에서 유추됩니다.
예제
이 메서드는 지정된 URL의 파일에서 데이터 추출을 지원합니다. Form Recognizer 서비스는 제출된 URL을 사용하여 파일을 다운로드하려고 시도하므로 공용 인터넷에서 URL에 액세스할 수 있어야 합니다. 예를 들어 SAS 토큰을 사용하여 Azure Storage의 Blob에 대한 읽기 권한을 부여할 수 있으며, 서비스는 SAS로 인코딩된 URL을 사용하여 파일을 요청합니다.
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>>
매개 변수
- model
-
DocumentModel<Result>
분석 및 예상 출력 형식에 사용할 모델을 나타내는 DocumentModel
- documentUrl
-
string
공용 인터넷에서 액세스할 수 있는 입력 문서에 대한 URL(문자열)
- options
-
AnalyzeDocumentOptions<Result>
분석 작업 및 폴러에 대한 선택적 설정
반환
Promise<AnalysisPoller<Result>>
결국 AnalyzeResult 생성하는 장기 실행 작업(폴러)입니다.
beginClassifyDocument(string, FormRecognizerRequestBody, ClassifyDocumentOptions)
ID로 지정된 사용자 지정 분류자를 사용하여 문서를 분류합니다.
이 메서드는 결국 AnalyzeResult생성하는 장기 실행 작업(폴러)을 생성합니다. 이 형식은 beginAnalyzeDocument 및 beginAnalyzeDocumentFromUrl동일한 형식이지만 결과에는 해당 필드의 작은 하위 집합만 포함됩니다.
documents 필드와 pages 필드만 채워지고 최소 페이지 정보만 반환됩니다.
documents 필드에는 식별된 모든 문서 및 분류된 docType 대한 정보가 포함됩니다.
본보기
이 메서드는 Node.JS 개체, 브라우저 ReadableStream및 Blobs와 같은 스트리밍 가능한 요청 본문(ArrayBuffer)을 지원합니다. 본문의 내용은 분석을 위해 서비스에 업로드됩니다.
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>>>
매개 변수
- classifierId
-
string
분석에 사용할 사용자 지정 분류자의 ID
- document
- FormRecognizerRequestBody
분류할 문서
- options
- ClassifyDocumentOptions
분류 작업에 대한 옵션
반환
Promise<AnalysisPoller<AnalyzeResult<AnalyzedDocument>>>
결국 AnalyzeResult 생성하는 장기 실행 작업(폴러)입니다.
beginClassifyDocumentFromUrl(string, string, ClassifyDocumentOptions)
ID로 지정된 사용자 지정 분류자를 사용하여 URL에서 문서를 분류합니다.
이 메서드는 결국 AnalyzeResult생성하는 장기 실행 작업(폴러)을 생성합니다. 이 형식은 beginAnalyzeDocument 및 beginAnalyzeDocumentFromUrl동일한 형식이지만 결과에는 해당 필드의 작은 하위 집합만 포함됩니다.
documents 필드와 pages 필드만 채워지고 최소 페이지 정보만 반환됩니다.
documents 필드에는 식별된 모든 문서 및 분류된 docType 대한 정보가 포함됩니다.
본보기
이 메서드는 지정된 URL의 파일에서 데이터 추출을 지원합니다. Form Recognizer 서비스는 제출된 URL을 사용하여 파일을 다운로드하려고 시도하므로 공용 인터넷에서 URL에 액세스할 수 있어야 합니다. 예를 들어 SAS 토큰을 사용하여 Azure Storage의 Blob에 대한 읽기 권한을 부여할 수 있으며, 서비스는 SAS로 인코딩된 URL을 사용하여 파일을 요청합니다.
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>>>
매개 변수
- classifierId
-
string
분석에 사용할 사용자 지정 분류자의 ID
- documentUrl
-
string
분류할 문서의 URL
- options
- ClassifyDocumentOptions
반환
Promise<AnalysisPoller<AnalyzeResult<AnalyzedDocument>>>