azure.ai.translation.document package

class azure.ai.translation.document.DocumentStatus(**kwargs: Any)[source]

Status information about a particular document within a translation operation.

Variables
  • source_document_url (str) – Location of the source document in the source container. Note that any SAS tokens are removed from this path.

  • translated_document_url (str) – Location of the translated document in the target container. Note that any SAS tokens are removed from this path.

  • created_on (datetime) – The date time when the document was created.

  • last_updated_on (datetime) – The date time when the document’s status was last updated.

  • status (str) –

    Status for a document.

    • NotStarted - the document has not been translated yet.

    • Running - translation is in progress for document

    • Succeeded - translation succeeded for the document

    • Failed - the document failed to translate. Check the error property.

    • Canceled - the operation was canceled, the document was not translated.

    • Canceling - the operation is canceling, the document will not be translated.

  • translated_to (str) – The language code of the language the document was translated to, if successful.

  • error (DocumentTranslationError) – Returned if there is an error with the particular document. Includes error code, message, target.

  • translation_progress (float) – Progress of the translation if available. Value is between [0.0, 1.0].

  • id (str) – Document Id.

  • characters_charged (int) – Characters charged for the document.

class azure.ai.translation.document.DocumentTranslationApiVersion(value)[source]

Document Translation API versions supported by this package

V1_0 = '1.0'

This is the default version

class azure.ai.translation.document.DocumentTranslationClient(endpoint: str, credential: Union[azure.core.credentials.AzureKeyCredential, TokenCredential], **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 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 import DefaultAzureCredential
from azure.ai.translation.document import DocumentTranslationClient

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

document_translation_client = DocumentTranslationClient(endpoint, credential)
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)DocumentTranslationLROPoller[ItemPaged[DocumentStatus]][source]
begin_translation(inputs: List[DocumentTranslationInput], **kwargs: Any)DocumentTranslationLROPoller[ItemPaged[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 a DocumentTranslationLROPoller. 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

DocumentTranslationLROPoller[ItemPaged[DocumentStatus]]

Raises

HttpResponseError

Example:

Translate the documents in your storage container.
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document 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))

poller = client.begin_translation(source_container_url, target_container_url, "fr")
result = 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")

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

close()None[source]

Close the DocumentTranslationClient session.

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

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

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

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.paging.ItemPaged[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

ItemPaged[DocumentStatus]

Raises

HttpResponseError

Example:

List all the document statuses as they are being translated.
import os
import time
from azure.core.credentials import AzureKeyCredential
from azure.ai.translation.document 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))

poller = client.begin_translation(source_container_url, target_container_url, "es")

completed_docs = []
while not poller.done():
    time.sleep(30)

    doc_statuses = client.list_document_statuses(poller.id)
    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.paging.ItemPaged[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

ItemPaged[TranslationStatus]

Raises

HttpResponseError

Example:

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


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

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

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

class azure.ai.translation.document.DocumentTranslationError(**kwargs: Any)[source]

This contains the error code, message, and target with descriptive details on why a translation operation or particular document failed.

Variables
  • code (str) – The error code. Possible high level values include: “InvalidRequest”, “InvalidArgument”, “InternalServerError”, “ServiceUnavailable”, “ResourceNotFound”, “Unauthorized”, “RequestRateTooHigh”.

  • message (str) – The error message associated with the failure.

  • target (str) – The source of the error. For example it would be “documents” or “document id” in case of invalid document.

class azure.ai.translation.document.DocumentTranslationFileFormat(**kwargs: Any)[source]

Possible file formats supported by the Document Translation service.

Variables
  • file_format (str) – Name of the format.

  • file_extensions (list[str]) – Supported file extension for this format.

  • content_types (list[str]) – Supported Content-Types for this format.

  • format_versions (list[str]) – Supported Version.

  • default_format_version (str) – Default format version if none is specified.

class azure.ai.translation.document.DocumentTranslationInput(source_url: str, targets: List[azure.ai.translation.document._models.TranslationTarget], *, source_language_code: Optional[str] = None, storage_type: Optional[Union[str, azure.ai.translation.document._generated.models._batch_document_translation_client_enums.StorageInputType]] = None, storage_source: Optional[str] = None, prefix: Optional[str] = None, suffix: Optional[str] = None)[source]

Input for translation. This requires that you have your source document or documents in an Azure Blob Storage container. Provide a URL to the source file or source container containing the documents for translation. The source document(s) are translated and written to the location provided by the TranslationTargets.

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”.

  • storage_source (str) – Storage Source. Default value: “AzureBlob”. Currently only “AzureBlob” is supported.

Variables
  • source_url (str) – Required. Location of the folder / container or single file with your documents. This can be a SAS URL (see the service documentation for the supported SAS permissions for accessing source storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions) or a managed identity can be created and used to access documents in your storage account (see https://aka.ms/azsdk/documenttranslation/managed-identity).

  • targets (list[TranslationTarget]) – Required. Location of the destination for the output. This is a list of TranslationTargets. Note that a TranslationTarget is required for each language code specified.

  • 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”.

  • storage_source (str) – Storage Source. Default value: “AzureBlob”. Currently only “AzureBlob” is supported.

class azure.ai.translation.document.DocumentTranslationLROPoller(client: Any, initial_response: Any, deserialization_callback: Callable, polling_method: PollingMethod[PollingReturnType])[source]

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

add_done_callback(func: Callable)None

Add callback function to be run once the long running operation has completed - regardless of the status of the operation.

Parameters

func (callable) – Callback function that takes at least one argument, a completed LongRunningOperation.

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._polling.DocumentTranslationLROPollingMethod, continuation_token: str, **kwargs: Any)azure.ai.translation.document._polling.DocumentTranslationLROPoller[source]
polling_method()azure.core.polling._poller.PollingMethod[PollingReturnType]

Return the polling method associated to this poller.

remove_done_callback(func: Callable)None

Remove a callback from the long running operation.

Parameters

func (callable) – The function to be removed from the callbacks.

Raises

ValueError – if the long running operation has already completed.

result(timeout: Optional[int] = None)PollingReturnType

Return the result of the long running operation, or the result available after the specified timeout.

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

wait(timeout: Optional[float] = None)None

Wait on the long running operation for a specified length of time. You can check if this call as ended with timeout with the “done()” method.

Parameters

timeout (float) – Period of time to wait for the long running operation to complete (in seconds).

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.StorageInputType(value)[source]

Storage type of the input documents source string

FILE = 'File'
FOLDER = 'Folder'
class azure.ai.translation.document.TranslationGlossary(glossary_url: str, file_format: str, *, format_version: Optional[str] = None, storage_source: Optional[str] = None)[source]

Glossary / translation memory to apply to the translation.

Parameters
Keyword Arguments
  • format_version (str) – File format version. If not specified, the service will use the default_version for the file format returned from the get_supported_glossary_formats() client method.

  • storage_source (str) – Storage Source. Default value: “AzureBlob”. Currently only “AzureBlob” is supported.

Variables
  • glossary_url (str) – Required. Location of the glossary file. This should be a URL to the glossary file in the storage blob container. The URL can be a SAS URL (see the service documentation for the supported SAS permissions for accessing storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions) or a managed identity can be created and used to access documents in your storage account (see https://aka.ms/azsdk/documenttranslation/managed-identity). Note that if the translation language pair is not present in the glossary, it will not be applied.

  • file_format (str) – Required. Format of the glossary file. To see supported formats, call the get_supported_glossary_formats() client method.

  • format_version (str) – File format version. If not specified, the service will use the default_version for the file format returned from the get_supported_glossary_formats() client method.

  • storage_source (str) – Storage Source. Default value: “AzureBlob”. Currently only “AzureBlob” is supported.

class azure.ai.translation.document.TranslationStatus(**kwargs: Any)[source]

Status information about the translation operation.

Variables
  • id (str) – Id of the translation operation.

  • created_on (datetime) – The date time when the translation operation was created.

  • last_updated_on (datetime) – The date time when the translation operation’s status was last updated.

  • status (str) –

    Status for a translation operation.

    • NotStarted - the operation has not begun yet.

    • Running - translation is in progress.

    • Succeeded - at least one document translated successfully within the operation.

    • Canceled - the operation was canceled.

    • Canceling - the operation is being canceled.

    • ValidationFailed - the input failed validation. E.g. there was insufficient permissions on blob containers.

    • Failed - all the documents within the operation failed.

  • error (DocumentTranslationError) – Returned if there is an error with the translation operation. Includes error code, message, target.

  • documents_total_count (int) – Number of translations to be made on documents in the operation.

  • documents_failed_count (int) – Number of documents that failed translation.

  • documents_succeeded_count (int) – Number of successful translations on documents.

  • documents_in_progress_count (int) – Number of translations on documents in progress.

  • documents_not_yet_started_count (int) – Number of documents that have not yet started being translated.

  • documents_canceled_count (int) – Number of documents that were canceled for translation.

  • total_characters_charged (int) – Total characters charged across all documents within the translation operation.

class azure.ai.translation.document.TranslationTarget(target_url: str, language_code: str, *, category_id: Optional[str] = None, glossaries: Optional[List[azure.ai.translation.document._models.TranslationGlossary]] = None, storage_source: Optional[str] = None)[source]

Destination for the finished translated documents.

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

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

  • storage_source (str) – Storage Source. Default value: “AzureBlob”. Currently only “AzureBlob” is supported.

Variables