Share via


Python용 Azure Form Recognizer 클라이언트 라이브러리 - 버전 3.0.0

Azure Cognitive Services Form Recognizer 기계 학습을 사용하여 양식 문서에서 텍스트 및 테이블 데이터를 인식하는 클라우드 서비스입니다. 여기에는 다음과 같은 주요 기능이 포함됩니다.

  • 사용자 지정 모델 - 양식에서 필드 값 및 테이블 데이터를 인식합니다. 이러한 모델은 사용자 고유의 데이터로 학습되므로 사용자의 양식에 맞게 조정됩니다.
  • 콘텐츠 API - 문서에서 경계 상자 좌표와 함께 텍스트 및 테이블 구조를 인식합니다. REST 서비스의 레이아웃 API에 해당합니다.
  • 미리 빌드된 영수증 모델 - 미리 빌드된 모델을 사용하여 미국 판매 영수증의 데이터를 인식합니다.

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

시작

필수 조건

패키지 설치

Python용 Azure Form Recognizer 클라이언트 라이브러리 - pip를 사용하여 버전 3.0.0을 설치합니다.

pip install azure-ai-formrecognizer

참고: 이 버전의 클라이언트 라이브러리는 v2.0 버전의 Form Recognizer 서비스를 지원합니다.

Form Recognizer 리소스 만들기

Form Recognizer 다중 서비스 및 단일 서비스 액세스를 모두 지원합니다. 단일 엔드포인트/키에서 여러 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
# Create form recognizer
az cognitiveservices account create \
    --name form-recognizer-resource \
    --resource-group my-resource-group \
    --kind FormRecognizer \
    --sku F0 \
    --location westus2 \
    --yes

클라이언트 인증

Form Recognizer 서비스와 상호 작용하려면 클라이언트의 인스턴스를 만들어야 합니다. 클라이언트 개체를 인스턴스화하려면 엔드포인트자격 증명 이 필요합니다.

엔드포인트 조회

Azure Portal 또는 Azure CLI를 사용하여 Form Recognizer 리소스에 대한 엔드포인트를 찾을 수 있습니다.

# Get the endpoint for the form recognizer resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "endpoint"

API 키 가져오기

API 키는 Azure Portal에서 또는 다음 Azure CLI 명령을 실행하여 찾을 수 있습니다.

az cognitiveservices account keys list --name "resource-name" --resource-group "resource-group-name"

AzureKeyCredential을 사용하여 클라이언트 만들기

API 키를 매개 변수로 credential 사용하려면 AzureKeyCredential 인스턴스에 키를 문자열로 전달합니다.

from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import FormRecognizerClient

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")
form_recognizer_client = FormRecognizerClient(endpoint, credential)

Azure Active Directory 자격 증명을 사용하여 클라이언트 만들기

AzureKeyCredential 인증은 이 시작 가이드의 예제에서 사용되지만 azure-identity 라이브러리를 사용하여 Azure Active Directory로 인증할 수도 있습니다. 지역 엔드포인트는 AAD 인증을 지원하지 않습니다. 이 유형의 인증을 사용하기 위해 리소스에 대한 사용자 지정 하위 도메인 이름을 만듭니다.

아래에 표시된 DefaultAzureCredential 형식 또는 Azure SDK와 함께 제공되는 다른 자격 증명 형식을 사용하려면 패키지를 설치 azure-identity 하세요.

pip install azure-identity

또한 서비스 주체에 역할을 할당 "Cognitive Services User" 하여 새 AAD 애플리케이션을 등록하고 Form Recognizer 대한 액세스 권한을 부여해야 합니다.

완료되면 AAD 애플리케이션의 클라이언트 ID, 테넌트 ID 및 클라이언트 암호 값을 환경 변수로 설정합니다. AZURE_CLIENT_ID, , AZURE_TENANT_IDAZURE_CLIENT_SECRET.

from azure.identity import DefaultAzureCredential
from azure.ai.formrecognizer import FormRecognizerClient
credential = DefaultAzureCredential()

form_recognizer_client = FormRecognizerClient(
    endpoint="https://<my-custom-subdomain>.cognitiveservices.azure.com/",
    credential=credential
)

주요 개념

FormRecognizerClient

FormRecognizerClient는 다음에 대한 작업을 제공합니다.

  • 사용자 지정 양식을 인식하도록 학습된 사용자 지정 모델을 사용하여 양식 필드 및 콘텐츠를 인식합니다. 이러한 값은 RecognizedForm 개체의 컬렉션에서 반환됩니다.
  • 미리 학습된 영수증 모델을 사용하여 미국 영수증의 공통 필드를 인식합니다. 이러한 필드와 메타데이터는 개체 컬렉션 RecognizedForm 에 반환됩니다.
  • 모델을 학습하지 않고도 테이블, 줄 및 단어를 비롯한 양식 콘텐츠를 인식합니다. 양식 콘텐츠는 FormPage 개체의 컬렉션에서 반환됩니다.

샘플 코드 조각은 여기에서 사용자 지정 모델을 사용하여 FormRecognizerClient 방법을 설명하기 위해 제공됩니다.

FormTrainingClient

FormTrainingClient는 다음에 대한 작업을 제공합니다.

  • 레이블이 없는 사용자 지정 모델을 학습하여 사용자 지정 양식에 있는 모든 필드와 값을 인식합니다. 모델이 인식할 양식 유형과 각 양식 유형에 대해 추출할 필드를 나타내는 CustomFormModel이 반환됩니다. 자세한 설명은 서비스 설명서를 참조하세요.
  • 사용자 지정 양식에 레이블을 지정하여 지정한 특정 필드와 값을 인식하도록 레이블을 사용하여 사용자 지정 모델을 학습합니다. 모델이 추출하는 필드와 각 필드에 대한 예상 정확도를 나타내는 CustomFormModel이 반환됩니다. 자세한 설명은 서비스 설명서를 참조하세요.
  • 계정에서 생성된 모델을 관리합니다.
  • 하나의 Form Recognizer 리소스에서 다른 리소스로 사용자 지정 모델을 복사합니다.

Form Recognizer 레이블 지정 도구와 같은 그래픽 사용자 인터페이스를 사용하여 모델을 학습할 수도 있습니다.

샘플 코드 조각은 여기에서 FormTrainingClient 을 사용하는 방법을 설명하기 위해 제공됩니다.

Long-Running 작업

장기 실행 작업은 작업을 시작하기 위해 서비스에 전송된 초기 요청으로 구성된 작업이며, 그 다음에는 간격으로 서비스를 폴링하여 작업이 완료되었는지 또는 실패했는지, 그리고 성공했는지 여부를 확인하여 결과를 가져옵니다.

모델을 학습하거나, 양식에서 값을 인식하거나, 모델을 복사하는 메서드는 장기 실행 작업으로 모델링됩니다. 클라이언트는 또는 AsyncLROPollerbegin_<method-name> 반환하는 메서드를 LROPoller 노출합니다. 호출자는 메서드에서 begin_<method-name> 반환된 폴러 개체를 호출 result() 하여 작업이 완료되기를 기다려야 합니다. 샘플 코드 조각은 아래의 장기 실행 작업 를 사용하여 설명하기 위해 제공됩니다.

예제

다음 섹션에서는 다음을 포함하여 가장 일반적인 Form Recognizer 작업 중 일부를 다루는 몇 가지 코드 조각을 제공합니다.

사용자 지정 모델을 사용하여 양식 인식

양식에서 이름/값 쌍 및 테이블 데이터를 인식합니다. 이러한 모델은 사용자 고유의 데이터로 학습되므로 사용자의 양식에 맞게 조정됩니다. 최상의 결과를 얻으려면 사용자 지정 모델이 학습된 것과 동일한 양식 형식의 양식만 인식해야 합니다.

from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_recognizer_client = FormRecognizerClient(endpoint, credential)
model_id = "<your custom model id>"

with open("<path to your form>", "rb") as fd:
    form = fd.read()

poller = form_recognizer_client.begin_recognize_custom_forms(model_id=model_id, form=form)
result = poller.result()

for recognized_form in result:
    print("Form type: {}".format(recognized_form.form_type))
    for name, field in recognized_form.fields.items():
        print("Field '{}' has label '{}' with value '{}' and a confidence score of {}".format(
            name,
            field.label_data.text if field.label_data else name,
            field.value,
            field.confidence
        ))

또는 양식 URL을 사용하여 메서드를 사용하여 begin_recognize_custom_forms_from_url 사용자 지정 양식을 인식할 수도 있습니다. _from_url 모든 인식 메서드에 대한 메서드가 있습니다.

form_url = "<url_of_the_form>"
poller = form_recognizer_client.begin_recognize_custom_forms_from_url(model_id=model_id, form_url=form_url)
result = poller.result()

콘텐츠 인식

문서에서 경계 상자 좌표와 함께 텍스트 및 테이블 구조를 인식합니다.

from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_recognizer_client = FormRecognizerClient(endpoint, credential)

with open("<path to your form>", "rb") as fd:
    form = fd.read()

poller = form_recognizer_client.begin_recognize_content(form)
page = poller.result()

table = page[0].tables[0] # page 1, table 1
print("Table found on page {}:".format(table.page_number))
for cell in table.cells:
    print("Cell text: {}".format(cell.text))
    print("Location: {}".format(cell.bounding_box))
    print("Confidence score: {}\n".format(cell.confidence))

영수증 인식

미리 빌드된 모델을 사용하여 미국 판매 영수증의 데이터를 인식합니다. 서비스에서 인식되는 영수증 필드는 여기에서 찾을 수 있습니다.

from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_recognizer_client = FormRecognizerClient(endpoint, credential)

with open("<path to your receipt>", "rb") as fd:
    receipt = fd.read()

poller = form_recognizer_client.begin_recognize_receipts(receipt)
result = poller.result()

for receipt in result:
    for name, field in receipt.fields.items():
        if name == "Items":
            print("Receipt Items:")
            for idx, items in enumerate(field.value):
                print("...Item #{}".format(idx+1))
                for item_name, item in items.value.items():
                    print("......{}: {} has confidence {}".format(item_name, item.value, item.confidence))
        else:
            print("{}: {} has confidence {}".format(name, field.value, field.confidence))

모델 학습

사용자 지정 모델을 고유한 양식 형식으로 학습합니다. 결과 모델을 사용하여 학습된 양식 형식의 값을 인식할 수 있습니다. 학습 문서를 저장하는 Azure Storage Blob 컨테이너에 컨테이너 SAS URL을 제공합니다. 학습 파일이 컨테이너의 하위 폴더 내에 있는 경우 접두사 키워드 인수를 사용하여 학습할 폴더를 지정합니다.

컨테이너 및 필수 파일 구조 설정에 대한 자세한 내용은 서비스 설명서에서 확인할 수 있습니다.

from azure.ai.formrecognizer import FormTrainingClient
from azure.core.credentials import AzureKeyCredential

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_training_client = FormTrainingClient(endpoint, credential)

container_sas_url = "<container-sas-url>"  # training documents uploaded to blob storage
poller = form_training_client.begin_training(
    container_sas_url, use_training_labels=False
)
model = poller.result()

# Custom model information
print("Model ID: {}".format(model.model_id))
print("Status: {}".format(model.status))
print("Training started on: {}".format(model.training_started_on))
print("Training completed on: {}".format(model.training_completed_on))

print("\nRecognized fields:")
for submodel in model.submodels:
    print(
        "The submodel with form type '{}' has recognized the following fields: {}".format(
            submodel.form_type,
            ", ".join(
                [
                    field.label if field.label else name
                    for name, field in submodel.fields.items()
                ]
            ),
        )
    )

# Training result information
for doc in model.training_documents:
    print("Document name: {}".format(doc.name))
    print("Document status: {}".format(doc.status))
    print("Document page count: {}".format(doc.page_count))
    print("Document errors: {}".format(doc.errors))

모델 관리

계정에 연결된 사용자 지정 모델을 관리합니다.

from azure.ai.formrecognizer import FormTrainingClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import ResourceNotFoundError

endpoint = "https://<region>.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("<api_key>")

form_training_client = FormTrainingClient(endpoint, credential)

account_properties = form_training_client.get_account_properties()
print("Our account has {} custom models, and we can have at most {} custom models".format(
    account_properties.custom_model_count, account_properties.custom_model_limit
))

# Here we get a paged list of all of our custom models
custom_models = form_training_client.list_custom_models()
print("We have models with the following ids: {}".format(
    ", ".join([m.model_id for m in custom_models])
))

# Replace with the custom model ID from the "Train a model" sample
model_id = "<model_id from the Train a Model sample>"

custom_model = form_training_client.get_custom_model(model_id=model_id)
print("Model ID: {}".format(custom_model.model_id))
print("Status: {}".format(custom_model.status))
print("Training started on: {}".format(custom_model.training_started_on))
print("Training completed on: {}".format(custom_model.training_completed_on))

# Finally, we will delete this model by ID
form_training_client.delete_model(model_id=custom_model.model_id)

try:
    form_training_client.get_custom_model(model_id=custom_model.model_id)
except ResourceNotFoundError:
    print("Successfully deleted model with id {}".format(custom_model.model_id))

문제 해결

일반

Form Recognizer 클라이언트 라이브러리는 Azure Core에 정의된 예외를 발생합니다.

로깅

이 라이브러리는 로깅에 표준 로깅 라이브러리를 사용합니다. HTTP 세션(URL, 헤더 등)에 대한 기본 정보는 INFO 수준에서 기록됩니다.

logging_enable 키워드 인수를 통해 클라이언트에서 요청/응답 본문 및 미작성 헤더를 포함한 상세 디버그 수준 로깅을 사용할 수 있습니다.

import sys
import logging
from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api_key>")

# This client will log detailed information about its HTTP sessions, at DEBUG level
form_recognizer_client = FormRecognizerClient(endpoint, credential, logging_enable=True)

마찬가지로 logging_enable은 클라이언트에 대해 상세 로깅을 사용하지 않는 경우에도 한 작업에만 사용하게 설정할 수 있습니다.

poller = form_recognizer_client.begin_recognize_receipts(receipt, logging_enable=True)

선택적 구성

선택적 키워드 인수는 클라이언트 및 작업별 수준에서 전달할 수 있습니다. azure-core 참조 설명서 에서는 재시도, 로깅, 전송 프로토콜 등에 사용할 수 있는 구성에 대해 설명합니다.

다음 단계

다음 섹션에서는 Form Recognizer Python API에서 사용되는 일반적인 패턴을 보여 주는 몇 가지 코드 조각을 제공합니다.

추가 샘플 코드

이러한 코드 샘플은 Azure Form Recognizer 클라이언트 라이브러리를 사용하는 일반적인 시나리오 작업을 보여 줍니다.

비동기 API

이 라이브러리에는 Python 3.5 이상에서 지원되는 완전한 비동기 API도 포함되어 있습니다. 이를 사용하려면 먼저 aiohttp와 같은 비동기 전송을 설치해야 합니다. 비동기 클라이언트는 네임스페이 azure.ai.formrecognizer.aio 스 아래에 있습니다.

추가 설명서

Azure Cognitive Services Form Recognizer 대한 보다 광범위한 설명서는 docs.microsoft.com 대한 Form Recognizer 설명서를 참조하세요.

참여

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 cla.microsoft.com.

끌어오기 요청을 제출하면 CLA-bot은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 설명). 봇에서 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하여 모든 리포지토리에서 한 번만 수행하면 됩니다.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.