azure.ai.translation.document.aio package

class azure.ai.translation.document.aio.AsyncDocumentTranslationLROPoller(client: Any, initial_response: Any, deserialization_callback: Callable, polling_method: azure.core.polling._async_poller.AsyncPollingMethod[PollingReturnType])[source]

An async custom poller implementation for Document Translation. Call result() on the poller to return a pageable of DocumentStatus.

continuation_token()str

Return a continuation token that allows to restart the poller later.

Returns

An opaque continuation token

Return type

str

done()bool

Check status of the long running operation.

Returns

‘True’ if the process has completed, else ‘False’.

Return type

bool

classmethod from_continuation_token(polling_method: azure.ai.translation.document.aio._async_polling.AsyncDocumentTranslationLROPollingMethod, continuation_token: str, **kwargs: Any)azure.ai.translation.document.aio._async_polling.AsyncDocumentTranslationLROPoller[source]
polling_method()azure.core.polling._async_poller.AsyncPollingMethod[PollingReturnType]

Return the polling method associated to this poller.

async result()PollingReturnType

Return the result of the long running operation.

Returns

The deserialized resource of the long running operation, if one is available.

Raises

HttpResponseError – Server problem with the query.

status()str

Returns the current status string.

Returns

The current status string

Return type

str

async wait()None

Wait on the long running operation.

Raises

HttpResponseError – Server problem with the query.

property details

The details for the translation operation

Return type

TranslationStatus

property id

The ID for the translation operation

Return type

str

class azure.ai.translation.document.aio.DocumentTranslationClient(endpoint: str, credential: Union[azure.core.credentials.AzureKeyCredential, AsyncTokenCredential], **kwargs: Any)[source]

DocumentTranslationClient is your interface to the Document Translation service. Use the client to translate whole documents while preserving source document structure and text formatting.

Parameters
  • endpoint (str) – Supported Document Translation endpoint (protocol and hostname, for example: https://<resource-name>.cognitiveservices.azure.com/).

  • credential (AzureKeyCredential or TokenCredential) – 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 azure.identity.

Keyword Arguments

api_version (str or DocumentTranslationApiVersion) – 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.

Example:

Creating the DocumentTranslationClient with an endpoint and API key.
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document.aio import DocumentTranslationClient

endpoint = os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"]
key = os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"]

document_translation_client = DocumentTranslationClient(endpoint, AzureKeyCredential(key))
Creating the DocumentTranslationClient with a token credential.
"""DefaultAzureCredential will use the values from these environment
variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
"""
from azure.identity.aio import DefaultAzureCredential
from azure.ai.translation.document.aio import DocumentTranslationClient

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

document_translation_client = DocumentTranslationClient(endpoint, credential)
async begin_translation(source_url: str, target_url: str, target_language_code: str, *, source_language_code: Optional[str] = 'None', prefix: Optional[str] = 'None', suffix: Optional[str] = 'None', storage_type: Optional[Union[str, StorageInputType]] = 'None', category_id: Optional[str] = 'None', glossaries: Optional[List[TranslationGlossary]] = 'None', **kwargs: Any)AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]][source]
async begin_translation(inputs: List[DocumentTranslationInput], **kwargs: Any)AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]]

Begin translating the document(s) in your source container to your target container in the given language. There are two ways to call this method:

1) To perform translation on documents from a single source container to a single target container, pass the source_url, target_url, and target_language_code parameters including any optional keyword arguments.

2) To pass multiple inputs for translation (multiple sources or targets), pass the inputs parameter as a list of DocumentTranslationInput.

For supported languages and document formats, see the service documentation: https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview

Parameters
Keyword Arguments
  • source_language_code (str) – Language code for the source documents. If none is specified, the source language will be auto-detected for each document.

  • prefix (str) – A case-sensitive prefix string to filter documents in the source path for translation. For example, when using a Azure storage blob Uri, use the prefix to restrict sub folders for translation.

  • suffix (str) – A case-sensitive suffix string to filter documents in the source path for translation. This is most often use for file extensions.

  • storage_type (str or StorageInputType) – Storage type of the input documents source string. Possible values include: “Folder”, “File”.

  • category_id (str) – Category / custom model ID for using custom translation.

  • glossaries (list[TranslationGlossary]) – Glossaries to apply to translation.

Returns

An instance of an AsyncDocumentTranslationLROPoller. Call result() on the poller object to return a pageable of DocumentStatus. A DocumentStatus will be returned for each translation on a document.

Return type

AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]]

Raises

HttpResponseError

Example:

Translate the documents in your storage container.
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document.aio import DocumentTranslationClient

endpoint = os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"]
key = os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"]
source_container_url = os.environ["AZURE_SOURCE_CONTAINER_URL"]
target_container_url = os.environ["AZURE_TARGET_CONTAINER_URL"]

client = DocumentTranslationClient(endpoint, AzureKeyCredential(key))

async with client:
    poller = await client.begin_translation(source_container_url, target_container_url, "fr")
    result = await poller.result()

    print(f"Status: {poller.status()}")
    print(f"Created on: {poller.details.created_on}")
    print(f"Last updated on: {poller.details.last_updated_on}")
    print(f"Total number of translations on documents: {poller.details.documents_total_count}")

    print("\nOf total documents...")
    print(f"{poller.details.documents_failed_count} failed")
    print(f"{poller.details.documents_succeeded_count} succeeded")

    async for document in result:
        print(f"Document ID: {document.id}")
        print(f"Document status: {document.status}")
        if document.status == "Succeeded":
            print(f"Source document location: {document.source_document_url}")
            print(f"Translated document location: {document.translated_document_url}")
            print(f"Translated to language: {document.translated_to}\n")
        else:
            print(f"Error Code: {document.error.code}, Message: {document.error.message}\n")
async cancel_translation(translation_id: str, **kwargs: Any)None[source]

Cancel a currently processing or queued translation operation.

A translation will not be canceled if it is already completed, failed, or canceling. All documents that have completed translation will not be canceled and will be charged. If possible, all pending documents will be canceled.

Parameters

translation_id (str) – The translation operation ID.

Returns

None

Return type

None

Raises

HttpResponseError or ResourceNotFoundError

async close()None[source]

Close the DocumentTranslationClient session.

async get_document_status(translation_id: str, document_id: str, **kwargs: Any)azure.ai.translation.document._models.DocumentStatus[source]

Get the status of an individual document within a translation operation.

Parameters
  • translation_id (str) – The translation operation ID.

  • document_id (str) – The ID for the document.

Returns

A DocumentStatus with information on the status of the document.

Return type

DocumentStatus

Raises

HttpResponseError or ResourceNotFoundError

async get_supported_document_formats(**kwargs: Any)List[azure.ai.translation.document._models.DocumentTranslationFileFormat][source]

Get the list of the document formats supported by the Document Translation service.

Returns

A list of supported document formats for translation.

Return type

List[DocumentTranslationFileFormat]

Raises

HttpResponseError

async get_supported_glossary_formats(**kwargs: Any)List[azure.ai.translation.document._models.DocumentTranslationFileFormat][source]

Get the list of the glossary formats supported by the Document Translation service.

Returns

A list of supported glossary formats.

Return type

List[DocumentTranslationFileFormat]

Raises

HttpResponseError

async get_translation_status(translation_id: str, **kwargs: Any)azure.ai.translation.document._models.TranslationStatus[source]

Gets the status of the translation operation.

Includes the overall status, as well as a summary of the documents that are being translated as part of that translation operation.

Parameters

translation_id (str) – The translation operation ID.

Returns

A TranslationStatus with information on the status of the translation operation.

Return type

TranslationStatus

Raises

HttpResponseError or ResourceNotFoundError

list_document_statuses(translation_id: str, *, top: Optional[int] = None, skip: Optional[int] = None, results_per_page: Optional[int] = None, document_ids: Optional[List[str]] = None, statuses: Optional[List[str]] = None, created_after: Optional[Union[str, datetime.datetime]] = None, created_before: Optional[Union[str, datetime.datetime]] = None, order_by: Optional[List[str]] = None, **kwargs: Any)azure.core.async_paging.AsyncItemPaged[azure.ai.translation.document._models.DocumentStatus][source]

List all the document statuses for a given translation operation.

Parameters

translation_id (str) – ID of translation operation to list documents for.

Keyword Arguments
  • top (int) – the total number of documents to return (across all pages).

  • skip (int) – the number of documents to skip (from beginning). By default, we sort by all documents in descending order by start time.

  • results_per_page (int) – is the number of documents returned per page.

  • document_ids (list[str]) – document IDs to filter by.

  • statuses (list[str]) – document statuses to filter by. Options include ‘NotStarted’, ‘Running’, ‘Succeeded’, ‘Failed’, ‘Canceled’, ‘Canceling’, and ‘ValidationFailed’.

  • created_after (str or datetime) – get document created after certain datetime.

  • created_before (str or datetime) – get document created before certain datetime.

  • order_by (list[str]) – the sorting query for the documents. Currently only ‘created_on’ is supported. format: [“param1 asc/desc”, “param2 asc/desc”, …] (ex: ‘created_on asc’, ‘created_on desc’).

Returns

A pageable of DocumentStatus.

Return type

AsyncItemPaged[DocumentStatus]

Raises

HttpResponseError

Example:

List all the document statuses as they are being translated.
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document.aio import DocumentTranslationClient

endpoint = os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"]
key = os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"]
source_container_url = os.environ["AZURE_SOURCE_CONTAINER_URL"]
target_container_url = os.environ["AZURE_TARGET_CONTAINER_URL"]

client = DocumentTranslationClient(endpoint, AzureKeyCredential(key))

async with client:
    poller = await client.begin_translation(source_container_url, target_container_url, "es")

    completed_docs = []
    while poller.status() in ["Running", "NotStarted"]:
        await asyncio.sleep(30)

        doc_statuses = client.list_document_statuses(poller.id)
        async for document in doc_statuses:
            if document.id not in completed_docs:
                if document.status == "Succeeded":
                    print(f"Document at {document.source_document_url} was translated to {document.translated_to} "
                          f"language. You can find translated document at {document.translated_document_url}")
                    completed_docs.append(document.id)
                if document.status == "Failed":
                    print(f"Document at {document.source_document_url} failed translation. "
                          f"Error Code: {document.error.code}, Message: {document.error.message}")
                    completed_docs.append(document.id)
                if document.status == "Running":
                    print(f"Document ID: {document.id}, translation progress is "
                          f"{document.translation_progress * 100} percent")

    print("\nTranslation completed.")
list_translation_statuses(*, top: Optional[int] = None, skip: Optional[int] = None, results_per_page: Optional[int] = None, translation_ids: Optional[List[str]] = None, statuses: Optional[List[str]] = None, created_after: Optional[Union[str, datetime.datetime]] = None, created_before: Optional[Union[str, datetime.datetime]] = None, order_by: Optional[List[str]] = None, **kwargs: Any)azure.core.async_paging.AsyncItemPaged[azure.ai.translation.document._models.TranslationStatus][source]

List all the submitted translation operations under the Document Translation resource.

Keyword Arguments
  • top (int) – the total number of operations to return (across all pages) from all submitted translations.

  • skip (int) – the number of operations to skip (from beginning of all submitted operations). By default, we sort by all submitted operations in descending order by start time.

  • results_per_page (int) – is the number of operations returned per page.

  • translation_ids (list[str]) – translation operations ids to filter by.

  • statuses (list[str]) – translation operation statuses to filter by. Options include ‘NotStarted’, ‘Running’, ‘Succeeded’, ‘Failed’, ‘Canceled’, ‘Canceling’, and ‘ValidationFailed’.

  • created_after (str or datetime) – get operations created after certain datetime.

  • created_before (str or datetime) – get operations created before certain datetime.

  • order_by (list[str]) – the sorting query for the operations returned. Currently only ‘created_on’ supported. format: [“param1 asc/desc”, “param2 asc/desc”, …] (ex: ‘created_on asc’, ‘created_on desc’).

Returns

A pageable of TranslationStatus.

Return type

AsyncItemPaged[TranslationStatus]

Raises

HttpResponseError

Example:

List all submitted translations under the resource.
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document.aio import DocumentTranslationClient

endpoint = os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"]
key = os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"]

client = DocumentTranslationClient(endpoint, AzureKeyCredential(key))
async with client:
    operations = client.list_translation_statuses()  # type: AsyncItemPaged[TranslationStatus]

    async for operation in operations:
        print(f"ID: {operation.id}")
        print(f"Status: {operation.status}")
        print(f"Created on: {operation.created_on}")
        print(f"Last updated on: {operation.last_updated_on}")
        print(f"Total number of operations on documents: {operation.documents_total_count}")
        print(f"Total number of characters charged: {operation.total_characters_charged}")

        print("\nOf total documents...")
        print(f"{operation.documents_failed_count} failed")
        print(f"{operation.documents_succeeded_count} succeeded")
        print(f"{operation.documents_canceled_count} canceled\n")