DocumentModelAdministrationClient Class

DocumentModelAdministrationClient is the Form Recognizer interface to use for building and managing models.

It provides methods for building models, as well as methods for viewing and deleting models, viewing document model operations, accessing account information, copying models to another Form Recognizer resource, and composing a new model from a collection of existing models.

Note

DocumentModelAdministrationClient should be used with API versions

2021-09-30-preview and up. To use API versions <=v2.1, instantiate a FormTrainingClient.

New in version 2021-09-30-preview: The DocumentModelAdministrationClient and its client methods.

Inheritance
azure.ai.formrecognizer.aio._form_base_client_async.FormRecognizerClientBaseAsync
DocumentModelAdministrationClient

Constructor

DocumentModelAdministrationClient(endpoint: str, credential: Union[AzureKeyCredential, AsyncTokenCredential], **kwargs: Any)

Parameters

endpoint
str
Required

Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com).

credential
AzureKeyCredential or TokenCredential
Required

Credentials needed for the client to connect to Azure. This is an instance of AzureKeyCredential if using an API key or a token credential from identity.

api_version
str or DocumentAnalysisApiVersion

The API version of the service to use for requests. It defaults to the latest service version. Setting to an older version may result in reduced feature compatibility. To use API versions <=v2.1, instantiate a FormTrainingClient.

Examples

Creating the DocumentModelAdministrationClient with an endpoint and API key.


   from azure.core.credentials import AzureKeyCredential
   from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient

   endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
   key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]

   document_model_admin_client = DocumentModelAdministrationClient(endpoint, AzureKeyCredential(key))

Creating the DocumentModelAdministrationClient with a token credential.


   """DefaultAzureCredential will use the values from these environment
   variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
   """
   from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient
   from azure.identity.aio import DefaultAzureCredential

   endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
   credential = DefaultAzureCredential()

   document_model_admin_client = DocumentModelAdministrationClient(endpoint, credential)

Methods

begin_build_model

Build a custom model.

The request must include a source parameter that is an externally accessible Azure storage blob container URI (preferably a Shared Access Signature URI). Note that a container URI (without SAS) is accepted only when the container is public or has a managed identity configured, see more about configuring managed identities to work with Form Recognizer here: https://docs.microsoft.com/azure/applied-ai-services/form-recognizer/managed-identities. Models are built using documents that are of the following content type - 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff', or 'image/bmp'. Other types of content in the container is ignored.

New in version v2022-01-30-preview: The required build_mode parameter and tags keyword argument

begin_copy_model_to

Copy a model stored in this resource (the source) to the user specified target Form Recognizer resource.

This should be called with the source Form Recognizer resource (with the model that is intended to be copied). The target parameter should be supplied from the target resource's output from calling the get_copy_authorization method.

begin_create_composed_model

Creates a composed model from a collection of existing models.

A composed model allows multiple models to be called with a single model ID. When a document is submitted to be analyzed with a composed model ID, a classification step is first performed to route it to the correct custom model.

New in version v2022-01-30-preview: The tags keyword argument

close

Close the DocumentModelAdministrationClient session.

delete_model

Delete a custom model.

get_account_info

Get information about the models under the Form Recognizer resource.

get_copy_authorization

Generate authorization for copying a custom model into the target Form Recognizer resource.

This should be called by the target resource (where the model will be copied to) and the output can be passed as the target parameter into begin_copy_model_to.

New in version v2022-01-30-preview: The tags keyword argument

get_document_analysis_client

Get an instance of a DocumentAnalysisClient from DocumentModelAdministrationClient.

get_model

Get a model by its ID.

get_operation

Get a document model operation by its ID.

Get a document model operation associated with the Form Recognizer resource. Note that operation information only persists for 24 hours. If the operation was successful, the document model can be accessed using the get_model or list_models APIs.

list_models

List information for each model, including its model ID, description, and when it was created.

list_operations

List information for each document model operation.

Lists all document model operations associated with the Form Recognizer resource. Note that operation information only persists for 24 hours. If the operation was successful, the document model can be accessed using the get_model or list_models APIs.

begin_build_model

Build a custom model.

The request must include a source parameter that is an externally accessible Azure storage blob container URI (preferably a Shared Access Signature URI). Note that a container URI (without SAS) is accepted only when the container is public or has a managed identity configured, see more about configuring managed identities to work with Form Recognizer here: https://docs.microsoft.com/azure/applied-ai-services/form-recognizer/managed-identities. Models are built using documents that are of the following content type - 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff', or 'image/bmp'. Other types of content in the container is ignored.

New in version v2022-01-30-preview: The required build_mode parameter and tags keyword argument

async begin_build_model(source: str, build_mode: Union[str, azure.ai.formrecognizer._models.DocumentBuildMode], **kwargs: Any) -> azure.ai.formrecognizer.aio._async_polling.AsyncDocumentModelAdministrationLROPoller[azure.ai.formrecognizer._models.DocumentModel]

Parameters

source
str
Required

An Azure Storage blob container's SAS URI. A container URI (without SAS) can be used if the container is public or has a managed identity configured. For more information on setting up a training data set, see: https://aka.ms/azsdk/formrecognizer/buildtrainingset.

build_mode
str or DocumentBuildMode
Required

The custom model build mode. Possible values include: "template", "neural". For more information about build modes, see: https://aka.ms/azsdk/formrecognizer/buildmode.

model_id
str

A unique ID for your model. If not specified, a model ID will be created for you.

description
str

An optional description to add to the model.

prefix
str

A case-sensitive prefix string to filter documents in the source path. For example, when using an Azure storage blob URI, use the prefix to restrict sub folders. prefix should end in '/' to avoid cases where filenames share the same prefix.

tags
dict[str, str]

List of user defined key-value tag attributes associated with the model.

continuation_token
str

A continuation token to restart a poller from a saved state.

Returns

An instance of an AsyncDocumentModelAdministrationLROPoller. Call result() on the poller object to return a DocumentModel.

Return type

Exceptions

Examples

Building a model from training files.


   from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient
   from azure.ai.formrecognizer import DocumentBuildMode
   from azure.core.credentials import AzureKeyCredential

   endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
   key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]
   container_sas_url = os.environ["CONTAINER_SAS_URL"]

   document_model_admin_client = DocumentModelAdministrationClient(endpoint, AzureKeyCredential(key))
   async with document_model_admin_client:
       poller = await document_model_admin_client.begin_build_model(
           container_sas_url, DocumentBuildMode.TEMPLATE, description="my model description"
       )
       model = await poller.result()

   print("Model ID: {}".format(model.model_id))
   print("Description: {}".format(model.description))
   print("Model created on: {}\n".format(model.created_on))
   print("Doc types the model can recognize:")
   for name, doc_type in model.doc_types.items():
       print("\nDoc Type: '{}' built with '{}' mode which has the following fields:".format(name, doc_type.build_mode))
       for field_name, field in doc_type.field_schema.items():
           print("Field: '{}' has type '{}' and confidence score {}".format(
               field_name, field["type"], doc_type.field_confidence[field_name]
           ))

begin_copy_model_to

Copy a model stored in this resource (the source) to the user specified target Form Recognizer resource.

This should be called with the source Form Recognizer resource (with the model that is intended to be copied). The target parameter should be supplied from the target resource's output from calling the get_copy_authorization method.

async begin_copy_model_to(model_id: str, target: dict, **kwargs: Any) -> azure.ai.formrecognizer.aio._async_polling.AsyncDocumentModelAdministrationLROPoller[azure.ai.formrecognizer._models.DocumentModel]

Parameters

model_id
str
Required

Model identifier of the model to copy to target resource.

target
dict
Required

The copy authorization generated from the target resource's call to get_copy_authorization.

continuation_token
str

A continuation token to restart a poller from a saved state.

Returns

An instance of a AsyncDocumentModelAdministrationLROPoller. Call result() on the poller object to return a DocumentModel.

Return type

Exceptions

Examples

Copy a model from the source resource to the target resource


   from azure.core.credentials import AzureKeyCredential
   from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient

   source_endpoint = os.environ["AZURE_FORM_RECOGNIZER_SOURCE_ENDPOINT"]
   source_key = os.environ["AZURE_FORM_RECOGNIZER_SOURCE_KEY"]
   target_endpoint = os.environ["AZURE_FORM_RECOGNIZER_TARGET_ENDPOINT"]
   target_key = os.environ["AZURE_FORM_RECOGNIZER_TARGET_KEY"]
   source_model_id = os.getenv("AZURE_SOURCE_MODEL_ID", custom_model_id)

   target_client = DocumentModelAdministrationClient(endpoint=target_endpoint, credential=AzureKeyCredential(target_key))
   async with target_client:
       target = await target_client.get_copy_authorization(
           description="model copied from other resource"
       )

   source_client = DocumentModelAdministrationClient(endpoint=source_endpoint, credential=AzureKeyCredential(source_key))
   async with source_client:
       poller = await source_client.begin_copy_model_to(
           model_id=source_model_id,
           target=target  # output from target client's call to get_copy_authorization()
       )
       copied_over_model = await poller.result()

   print("Model ID: {}".format(copied_over_model.model_id))
   print("Description: {}".format(copied_over_model.description))
   print("Model created on: {}\n".format(copied_over_model.created_on))
   print("Doc types the model can recognize:")
   for name, doc_type in copied_over_model.doc_types.items():
       print("\nDoc Type: '{}' which has the following fields:".format(name))
       for field_name, field in doc_type.field_schema.items():
           print("Field: '{}' has type '{}' and confidence score {}".format(
               field_name, field["type"], doc_type.field_confidence[field_name]
           ))

begin_create_composed_model

Creates a composed model from a collection of existing models.

A composed model allows multiple models to be called with a single model ID. When a document is submitted to be analyzed with a composed model ID, a classification step is first performed to route it to the correct custom model.

New in version v2022-01-30-preview: The tags keyword argument

async begin_create_composed_model(component_model_ids: List[str], **kwargs: Any) -> azure.ai.formrecognizer.aio._async_polling.AsyncDocumentModelAdministrationLROPoller[azure.ai.formrecognizer._models.DocumentModel]

Parameters

component_model_ids
list[str]
Required

List of model IDs to use in the composed model.

model_id
str

A unique ID for your composed model. If not specified, a model ID will be created for you.

description
str

An optional description to add to the model.

tags
dict[str, str]

List of user defined key-value tag attributes associated with the model.

continuation_token
str

A continuation token to restart a poller from a saved state.

Returns

An instance of an AsyncDocumentModelAdministrationLROPoller. Call result() on the poller object to return a DocumentModel.

Return type

Exceptions

Examples

Creating a composed model with existing models.


   from azure.core.credentials import AzureKeyCredential
   from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient
   from azure.ai.formrecognizer import DocumentBuildMode

   endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
   key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]
   po_supplies = os.environ['PURCHASE_ORDER_OFFICE_SUPPLIES_SAS_URL']
   po_equipment = os.environ['PURCHASE_ORDER_OFFICE_EQUIPMENT_SAS_URL']
   po_furniture = os.environ['PURCHASE_ORDER_OFFICE_FURNITURE_SAS_URL']
   po_cleaning_supplies = os.environ['PURCHASE_ORDER_OFFICE_CLEANING_SUPPLIES_SAS_URL']

   document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key))
   async with document_model_admin_client:
       supplies_poller = await document_model_admin_client.begin_build_model(
           po_supplies, DocumentBuildMode.TEMPLATE, description="Purchase order-Office supplies"
       )
       equipment_poller = await document_model_admin_client.begin_build_model(
           po_equipment, DocumentBuildMode.TEMPLATE, description="Purchase order-Office Equipment"
       )
       furniture_poller = await document_model_admin_client.begin_build_model(
           po_furniture, DocumentBuildMode.TEMPLATE, description="Purchase order-Furniture"
       )
       cleaning_supplies_poller = await document_model_admin_client.begin_build_model(
           po_cleaning_supplies, DocumentBuildMode.TEMPLATE, description="Purchase order-Cleaning Supplies"
       )
       supplies_model = await supplies_poller.result()
       equipment_model = await equipment_poller.result()
       furniture_model = await furniture_poller.result()
       cleaning_supplies_model = await cleaning_supplies_poller.result()

       purchase_order_models = [
           supplies_model.model_id,
           equipment_model.model_id,
           furniture_model.model_id,
           cleaning_supplies_model.model_id
       ]

       poller = await document_model_admin_client.begin_create_composed_model(
           purchase_order_models, description="Office Supplies Composed Model"
       )
       model = await poller.result()

   print("Office Supplies Composed Model Info:")
   print("Model ID: {}".format(model.model_id))
   print("Description: {}".format(model.description))
   print("Model created on: {}\n".format(model.created_on))
   print("Doc types the model can recognize:")
   for name, doc_type in model.doc_types.items():
       print("\nDoc Type: '{}' which has the following fields:".format(name))
       for field_name, field in doc_type.field_schema.items():
           print("Field: '{}' has type '{}' and confidence score {}".format(
               field_name, field["type"], doc_type.field_confidence[field_name]
           ))

close

Close the DocumentModelAdministrationClient session.

async close() -> None

Exceptions

delete_model

Delete a custom model.

async delete_model(model_id: str, **kwargs: Any) -> None

Parameters

model_id
str
Required

Model identifier.

Return type

Exceptions

Examples

Delete a model.


   await document_model_admin_client.delete_model(model_id=my_model.model_id)

   try:
       await document_model_admin_client.get_model(model_id=my_model.model_id)
   except ResourceNotFoundError:
       print("Successfully deleted model with ID {}".format(my_model.model_id))

get_account_info

Get information about the models under the Form Recognizer resource.

async get_account_info(**kwargs: Any) -> azure.ai.formrecognizer._models.AccountInfo

Returns

Summary of models under the resource - model count and limit.

Return type

Exceptions

Examples

Get model counts and limits under the Form Recognizer resource.


   document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key))

   async with document_model_admin_client:
       account_info = await document_model_admin_client.get_account_info()
       print("Our account has {} custom models, and we can have at most {} custom models\n".format(
           account_info.document_model_count, account_info.document_model_limit
       ))

get_copy_authorization

Generate authorization for copying a custom model into the target Form Recognizer resource.

This should be called by the target resource (where the model will be copied to) and the output can be passed as the target parameter into begin_copy_model_to.

New in version v2022-01-30-preview: The tags keyword argument

async get_copy_authorization(**kwargs: Any) -> Dict[str, str]

Parameters

model_id
str

A unique ID for your copied model. If not specified, a model ID will be created for you.

description
str

An optional description to add to the model.

tags
dict[str, str]

List of user defined key-value tag attributes associated with the model.

Returns

A dictionary with values necessary for the copy authorization.

Return type

<xref:Dict>[str, str]

Exceptions

get_document_analysis_client

Get an instance of a DocumentAnalysisClient from DocumentModelAdministrationClient.

get_document_analysis_client(**kwargs: Any) -> azure.ai.formrecognizer.aio._document_analysis_client_async.DocumentAnalysisClient

Returns

A DocumentAnalysisClient

Return type

Exceptions

get_model

Get a model by its ID.

async get_model(model_id: str, **kwargs: Any) -> azure.ai.formrecognizer._models.DocumentModel

Parameters

model_id
str
Required

Model identifier.

Returns

DocumentModel

Return type

Exceptions

Examples

Get a model by its ID.


   my_model = await document_model_admin_client.get_model(model_id=model.model_id)
   print("\nModel ID: {}".format(my_model.model_id))
   print("Description: {}".format(my_model.description))
   print("Model created on: {}".format(my_model.created_on))

get_operation

Get a document model operation by its ID.

Get a document model operation associated with the Form Recognizer resource. Note that operation information only persists for 24 hours. If the operation was successful, the document model can be accessed using the get_model or list_models APIs.

async get_operation(operation_id: str, **kwargs: Any) -> azure.ai.formrecognizer._models.ModelOperation

Parameters

operation_id
str
Required

The operation ID.

Returns

ModelOperation

Return type

Exceptions

Examples

Get a document model operation by its ID.


   # Get an operation by ID
   try:
       first_operation = await operations.__anext__()

       print("\nGetting operation info by ID: {}".format(first_operation.operation_id))
       operation_info = await document_model_admin_client.get_operation(first_operation.operation_id)
       if operation_info.status == "succeeded":
           print("My {} operation is completed.".format(operation_info.kind))
           result = operation_info.result
           print("Model ID: {}".format(result.model_id))
       elif operation_info.status == "failed":
           print("My {} operation failed.".format(operation_info.kind))
           error = operation_info.error
           print("{}: {}".format(error.code, error.message))
       else:
           print("My operation status is {}".format(operation_info.status))
   except StopAsyncIteration:
       print("No operations found.")

list_models

List information for each model, including its model ID, description, and when it was created.

list_models(**kwargs: Any) -> azure.core.async_paging.AsyncItemPaged[azure.ai.formrecognizer._models.DocumentModelInfo]

Returns

Pageable of DocumentModelInfo.

Return type

Exceptions

Examples

List all models that were built successfully under the Form Recognizer resource.


   models = document_model_admin_client.list_models()

   print("We have the following 'ready' models with IDs and descriptions:")
   async for model in models:
       print("{} | {}".format(model.model_id, model.description))

list_operations

List information for each document model operation.

Lists all document model operations associated with the Form Recognizer resource. Note that operation information only persists for 24 hours. If the operation was successful, the document model can be accessed using the get_model or list_models APIs.

list_operations(**kwargs: Any) -> azure.core.async_paging.AsyncItemPaged[azure.ai.formrecognizer._models.ModelOperationInfo]

Returns

A pageable of ModelOperationInfo.

Return type

Exceptions

Examples

List all document model operations in the past 24 hours.


   from azure.core.credentials import AzureKeyCredential
   from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient

   endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
   key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]

   document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key))

   async with document_model_admin_client:
       operations = document_model_admin_client.list_operations()

       print("The following document model operations exist under my resource:")
       async for operation in operations:
           print("\nOperation ID: {}".format(operation.operation_id))
           print("Operation kind: {}".format(operation.kind))
           print("Operation status: {}".format(operation.status))
           print("Operation percent completed: {}".format(operation.percent_completed))
           print("Operation created on: {}".format(operation.created_on))
           print("Operation last updated on: {}".format(operation.last_updated_on))
           print("Resource location of successful operation: {}".format(operation.resource_location))