Skip to main content

Microsoft Azure Form Recognizer Client Library for Python

Project description

Azure Form Recognizer client library for Python

Azure Cognitive Services Form Recognizer is a cloud service that uses machine learning to recognize text and table data from form documents. It includes the following main functionalities:

  • Custom models - Recognize field values and table data from forms. These models are trained with your own data, so they're tailored to your forms. You can then take these custom models and recognize forms. You can also manage the custom models you've created and see how close you are to the limit of custom models your account can hold.
  • Content API - Recognize text and table structures, along with their bounding box coordinates, from documents. Corresponds to the REST service's Layout API.
  • Prebuilt receipt model - Recognize data from USA sales receipts using a prebuilt model.

Source code | Package (PyPI) | API reference documentation| Product documentation | Samples

Getting started

Prerequisites

Install the package

Install the Azure Form Recognizer client library for Python with pip:

pip install azure-ai-formrecognizer

Note: This version of the client library supports the v2.0-preview version of the Form Recognizer service

Create a Form Recognizer resource

Form Recognizer supports both multi-service and single-service access. Create a Cognitive Services resource if you plan to access multiple cognitive services under a single endpoint/key. For Form Recognizer access only, create a Form Recognizer resource.

You can create the resource using

Option 1: Azure Portal

Option 2: Azure CLI. Below is an example of how you can create a Form Recognizer resource using the CLI:

# 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

Authenticate the client

Looking up the endpoint

You can find the endpoint for your form recognizer resource using the Azure Portal or Azure CLI:

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

Types of credentials

The credential parameter may be provided as a AzureKeyCredential from azure.core, or as a credential type from Azure Active Directory. See the full details regarding authentication of cognitive services.

  1. To use an API key, pass the key as a string into an instance of AzureKeyCredential("<api_key>"). The API key can be found in the Azure Portal or by running the following Azure CLI command:

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

    Use the key as the credential parameter to authenticate the client:

    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)
    
  2. To use an Azure Active Directory (AAD) token credential, provide an instance of the desired credential type obtained from the azure-identity library. Note that regional endpoints do not support AAD authentication. Create a custom subdomain name for your resource in order to use this type of authentication.

    Authentication with AAD requires some initial setup:

    After setup, you can choose which type of credential from azure.identity to use. As an example, DefaultAzureCredential can be used to authenticate the client:

    Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET

    Use the returned token credential to authenticate the client:

    from azure.identity import DefaultAzureCredential
    from azure.ai.formrecognizer import FormRecognizerClient
    token_credential = DefaultAzureCredential()
    
    form_recognizer_client = FormRecognizerClient(
        endpoint="https://<my-custom-subdomain>.cognitiveservices.azure.com/",
        credential=token_credential
    )
    

Key concepts

FormRecognizerClient

FormRecognizerClient provides operations for:

  • Recognizing form fields and content using custom models trained to recognize your custom forms. These values are returned in a collection of RecognizedForm objects.
  • Recognizing common fields from US receipts, using a pre-trained receipt model on the Form Recognizer service. These fields and meta-data are returned in a collection of RecognizedForm objects.
  • Recognizing form content, including tables, lines and words, without the need to train a model. Form content is returned in a collection of FormPage objects.

Sample code snippets are provided to illustrate using a FormRecognizerClient here.

FormTrainingClient

FormTrainingClient provides operations for:

  • Training custom models to recognize all fields and values found in your custom forms. A CustomFormModel is returned indicating the form types the model will recognize, and the fields it will extract for each form type. See the service's documents for a more detailed explanation.
  • Training custom models to recognize specific fields and values you specify by labeling your custom forms. A CustomFormModel is returned indicating the fields the model will extract, as well as the estimated accuracy for each field. See the service's documents for a more detailed explanation.
  • Managing models created in your account.
  • Copying a custom model from one Form Recognizer resource to another.

Please note that models can also be trained using a graphical user interface such as the Form Recognizer Labeling Tool.

Sample code snippets are provided to illustrate using a FormTrainingClient here.

Long-Running Operations

Long-running operations are operations which consist of an initial request sent to the service to start an operation, followed by polling the service at intervals to determine whether the operation has completed or failed, and if it has succeeded, to get the result.

Methods that train models, recognize values from forms, or copy models are modeled as long-running operations. The client exposes a begin_<method-name> method that returns an LROPoller or AsyncLROPoller. Callers should wait for the operation to complete by calling result() on the operation returned from the begin_<method-name> method. Sample code snippets are provided to illustrate using long-running operations below.

Examples

The following section provides several code snippets covering some of the most common Form Recognizer tasks, including:

Recognize Forms Using a Custom Model

Recognize name/value pairs and table data from forms. These models are trained with your own data, so they're tailored to your forms. You should only recognize forms of the same form type that the custom model was trained on.

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>"

# Make sure the form type is one of the types of forms your custom model can recognize
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 ID: {}".format(recognized_form.form_type))
    for label, field in recognized_form.fields.items():
        print("Field '{}' has value '{}' with a confidence score of {}".format(
            label, field.value, field.confidence
        ))

Alternatively, a form url can also be used to recognize custom forms using the begin_recognize_custom_forms_from_url method. The _from_url methods exist for all the recognize methods.

form_url_jpg = "<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()

Recognize Content

Recognize text and table structures, along with their bounding box coordinates, from documents.

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
for cell in table.cells:
    print(cell.text)
    print(cell.bounding_box)
    print(cell.confidence)

Recognize Receipts

Recognize data from USA sales receipts using a prebuilt model. Here are the fields the service returns for a recognized receipt.

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

Train a model

Train a machine-learned model on your own form type. The resulting model will be able to recognize values from the types of forms it was trained on. Provide a container SAS url to your Azure Storage Blob container where you're storing the training documents. If training files are within a subfolder in the container, use the prefix keyword argument to specify under which folder to train.

More details on setting up a container and required file structure can be found in the service quickstart documentation.

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("Recognized fields:")
# looping through the submodels, which contains the fields they were trained on
for submodel in model.submodels:
    print("The submodel with form type '{}' has recognized the following fields: {}".format(
        submodel.form_type,
        ", ".join([label for label in submodel.fields])
    ))

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

Manage Your Models

Manage the custom models attached to your account.

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

# Now we get the custom model 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))

Async APIs

This library also includes a complete async API supported on Python 3.5+. To use it, you must first install an async transport, such as aiohttp. See azure-core documentation for more information.

Optional Configuration

Optional keyword arguments can be passed in at the client and per-operation level. The azure-core reference documentation describes available configurations for retries, logging, transport protocols, and more.

Troubleshooting

General

Form Recognizer client library will raise exceptions defined in Azure Core.

Logging

This library uses the standard logging library for logging. Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.

Detailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the logging_enable keyword argument:

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)

Similarly, logging_enable can enable detailed logging for a single operation, even when it isn't enabled for the client:

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

Next steps

The following section provides several code snippets illustrating common patterns used in the Form Recognizer Python API.

More sample code

These code samples show common scenario operations with the Azure Form Recognizer client library. The async versions of the samples (the python sample files appended with _async) show asynchronous operations with Form Recognizer and require Python 3.5 or later.

Additional documentation

For more extensive documentation on Azure Cognitive Services Form Recognizer, see the Form Recognizer documentation on docs.microsoft.com.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Release History

1.0.0b4 (2020-07-07)

Breaking Changes

  • RecognizedReceipts class has been removed.
  • begin_recognize_receipts and begin_recognize_receipts_from_url now return RecognizedForm.
  • requested_on has been renamed to training_started_on and completed_on renamed to training_completed_on on CustomFormModel and CustomFormModelInfo
  • FieldText has been renamed to FieldData
  • FormContent has been renamed to FormElement
  • Parameter include_text_content has been renamed to include_field_elements for begin_recognize_receipts, begin_recognize_receipts_from_url, begin_recognize_custom_forms, and begin_recognize_custom_forms_from_url
  • text_content has been renamed to field_elements on FieldData and FormTableCell

Fixes and improvements

  • Fixes a bug where text_angle was being returned out of the specified interval (-180, 180]

1.0.0b3 (2020-06-10)

Breaking Changes

  • All asynchronous long running operation methods now return an instance of an AsyncLROPoller from azure-core
  • All asynchronous long running operation methods are renamed with the begin_ prefix to indicate that an AsyncLROPoller is returned:
    • train_model is renamed to begin_training
    • recognize_receipts is renamed to begin_recognize_receipts
    • recognize_receipts_from_url is renamed to begin_recognize_receipts_from_url
    • recognize_content is renamed to begin_recognize_content
    • recognize_content_from_url is renamed to begin_recognize_content_from_url
    • recognize_custom_forms is renamed to begin_recognize_custom_forms
    • recognize_custom_forms_from_url is renamed to begin_recognize_custom_forms_from_url
  • Sync method begin_train_model renamed to begin_training
  • training_files parameter of begin_training is renamed to training_files_url
  • use_labels parameter of begin_training is renamed to use_training_labels
  • list_model_infos method has been renamed to list_custom_models
  • Removed get_form_training_client from FormRecognizerClient
  • Added get_form_recognizer_client to FormTrainingClient
  • A HttpResponseError is now raised if a model with status=="invalid" is returned from the begin_training methods
  • PageRange is renamed to FormPageRange
  • first_page and last_page renamed to first_page_number and last_page_number, respectively on FormPageRange
  • FormField does not have a page_number
  • use_training_labels is now a required positional param in the begin_training APIs
  • stream and url parameters found on methods for FormRecognizerClient have been renamed to form and form_url, respectively
  • For begin_recognize_receipt methods, parameters have been renamed to receipt and receipt_url
  • created_on and last_modified are renamed to requested_on and completed_on in the CustomFormModel and CustomFormModelInfo models
  • models property of CustomFormModel is renamed to submodels
  • CustomFormSubModel is renamed to CustomFormSubmodel
  • begin_recognize_receipts APIs now return a list of RecognizedReceipt instead of USReceipt
  • Removed USReceipt. To see how to deal with the return value of begin_recognize_receipts, see the recognize receipt samples in the samples directory for details.
  • Removed USReceiptItem. To see how to access the individual items on a receipt, see the recognize receipt samples in the samples directory for details.
  • Removed USReceiptType and the receipt_type property from RecognizedReceipt. See the recognize receipt samples in the samples directory for details.

New features

  • Support to copy a custom model from one Form Recognizer resource to another
  • Authentication using azure-identity credentials now supported
  • page_number attribute has been added to FormTable
  • All long running operation methods now accept the keyword argument continuation_token to restart the poller from a saved state

Dependency updates

1.0.0b2 (2020-05-06)

Fixes and improvements

  • Bug fixed where confidence == 0.0 was erroneously getting set to 1.0
  • __repr__ has been added to all of the models

1.0.0b1 (2020-04-23)

Version (1.0.0b1) is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Form Recognizer. This library replaces the package found here: https://pypi-hypernode.com/project/azure-cognitiveservices-formrecognizer/

For more information about this, and preview releases of other Azure SDK libraries, please visit https://azure.github.io/azure-sdk/releases/latest/python.html.

Breaking changes: New API design

  • New namespace/package name:
    • The namespace/package name for the Form Recognizer client library has changed from azure.cognitiveservices.formrecognizer to azure.ai.formrecognizer
  • Two client design:
    • FormRecognizerClient to analyze fields/values on custom forms, receipts, and form content/layout
    • FormTrainingClient to train custom models (with/without labels), and manage the custom models on your account
  • Different analyze methods based on input type: file stream or URL.
    • URL input should use the method with suffix from_url
    • Stream methods will automatically detect content-type of the input file
  • Asynchronous APIs added under azure.ai.formrecognizer.aio namespace
  • Authentication with API key supported using AzureKeyCredential("<api_key>") from azure.core.credentials
  • New underlying REST pipeline implementation based on the azure-core library
  • Client and pipeline configuration is now available via keyword arguments at both the client level, and per-operation. See README for a link to optional configuration arguments
  • New error hierarchy:
    • All service errors will now use the base type: azure.core.exceptions.HttpResponseError

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure-ai-formrecognizer-1.0.0b4.zip (185.2 kB view details)

Uploaded Source

Built Distribution

azure_ai_formrecognizer-1.0.0b4-py2.py3-none-any.whl (71.1 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file azure-ai-formrecognizer-1.0.0b4.zip.

File metadata

  • Download URL: azure-ai-formrecognizer-1.0.0b4.zip
  • Upload date:
  • Size: 185.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.47.0 CPython/3.8.3

File hashes

Hashes for azure-ai-formrecognizer-1.0.0b4.zip
Algorithm Hash digest
SHA256 06f6335a56c69ff1aec32d07249dac04f8ca2f4d5fbbd21adf43457255de1ec7
MD5 fe782b2769ce78fa3555d748fae1ca8d
BLAKE2b-256 7b3e9cd9151f0afcf75891538275ca58ac262599fbfee06c5dfa64e66a8d53a8

See more details on using hashes here.

File details

Details for the file azure_ai_formrecognizer-1.0.0b4-py2.py3-none-any.whl.

File metadata

  • Download URL: azure_ai_formrecognizer-1.0.0b4-py2.py3-none-any.whl
  • Upload date:
  • Size: 71.1 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.47.0 CPython/3.8.3

File hashes

Hashes for azure_ai_formrecognizer-1.0.0b4-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 25ebeb0d65ff010a0212908f872bd8f4fa05b24e01cbda11e35f1b3b02100a06
MD5 c58ee54e8abe93d97599b33699f03e3c
BLAKE2b-256 a5a02129a905ed539d95c26b57a33bcd1cb54e590d869494bd4302e874f6a97b

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page