DocumentTranslationClient Class

Inheritance
builtins.object
DocumentTranslationClient

Constructor

DocumentTranslationClient(endpoint: str, credential: Union[azure.core.credentials.AzureKeyCredential, TokenCredential], **kwargs: Any)

Parameters

endpoint
credential

Methods

begin_translation

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

cancel_translation

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.

close

Close the DocumentTranslationClient session.

get_document_status

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

get_supported_document_formats

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

get_supported_glossary_formats

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

get_translation_status

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.

list_document_statuses

List all the document statuses for a given translation operation.

list_translation_statuses

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

begin_translation

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

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

Parameters

source_url
str
Required

The source URL to the Azure Blob container containing the documents to be translated. 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).

target_url
str
Required

The target URL to the Azure Blob container where the translated documents should be written. This can be a SAS URL (see the service documentation for the supported SAS permissions for accessing target 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).

target_language_code
str
Required

This is the language you want your documents to be translated to. See supported language codes here: https://docs.microsoft.com/azure/cognitive-services/translator/language-support#translate

inputs
<xref:List>[DocumentTranslationInput]
Required

A list of translation inputs. Each individual input has a single source URL to documents and can contain multiple TranslationTargets (one for each language) for the destination to write translated documents.

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

Exceptions

Examples

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

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.

cancel_translation(translation_id: str, **kwargs: Any) -> None

Parameters

translation_id
str
Required

The translation operation ID.

Returns

None

Return type

Exceptions

close

Close the DocumentTranslationClient session.

close() -> None

Exceptions

get_document_status

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

get_document_status(translation_id: str, document_id: str, **kwargs: Any) -> azure.ai.translation.document._models.DocumentStatus

Parameters

translation_id
str
Required

The translation operation ID.

document_id
str
Required

The ID for the document.

Returns

A DocumentStatus with information on the status of the document.

Return type

Exceptions

get_supported_document_formats

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

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

Returns

A list of supported document formats for translation.

Return type

Exceptions

get_supported_glossary_formats

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

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

Returns

A list of supported glossary formats.

Return type

Exceptions

get_translation_status

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.

get_translation_status(translation_id: str, **kwargs: Any) -> azure.ai.translation.document._models.TranslationStatus

Parameters

translation_id
str
Required

The translation operation ID.

Returns

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

Return type

Exceptions

list_document_statuses

List all the document statuses for a given translation operation.

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]

Parameters

translation_id
str
Required

ID of translation operation to list documents for.

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

Exceptions

Examples

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

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

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]

Parameters

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

Exceptions

Examples

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