DocumentTranslationClient Class
DocumentTranslationClient is your interface to the Document Translation service. Use the client to translate whole documents while preserving source document structure and text formatting.
Constructor
DocumentTranslationClient(endpoint: str, credential: AzureKeyCredential | TokenCredential, **kwargs: Any)
Parameters
| Name | Description |
|---|---|
|
endpoint
Required
|
Supported Document Translation endpoint (protocol and hostname, for example: https://<resource-name>.cognitiveservices.azure.com/). |
|
credential
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. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
api_version
|
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. |
Examples
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)
Methods
| begin_translation |
Begin translating the document(s) in your source container to your target container in the given language. 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. :param str translation_id: The translation operation ID. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: |
| close |
Close the DocumentTranslationClient session. |
| get_document_status |
Returns the status for a specific document. Returns the translation status for a specific document based on the request Id and document Id. |
| 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 |
Returns the status for a document translation request. Returns the status for a document translation request. The status includes the overall request status, as well as the status for documents that are being translated as part of that request. |
| 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. |
| send_request |
Runs the network request through the client's chained policies.
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request |
begin_translation
Begin translating the document(s) in your source container to your target container in the given language.
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: str, *, source_language: str | None = None, prefix: str | None = None, suffix: str | None = None, storage_type: str | StorageInputType | None = None, category_id: str | None = None, glossaries: List[TranslationGlossary] | None = None, **kwargs: Any) -> DocumentTranslationLROPoller[ItemPaged[DocumentStatus]]
Parameters
| Name | Description |
|---|---|
|
inputs
Required
|
The translation inputs. Each individual input has a single source URL to documents and can contain multiple targets (one for each language) for the destination to write translated documents. |
|
source_url
Required
|
The source SAS URL to the Azure Blob container containing the documents to be translated. See the service documentation for the supported SAS permissions for accessing source storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions |
|
target_url
Required
|
The target SAS URL to the Azure Blob container where the translated documents should be written. See the service documentation for the supported SAS permissions for accessing target storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions |
|
target_language
Required
|
This is the language code you want your documents to be translated to. See supported language codes here: https://docs.microsoft.com/azure/cognitive-services/translator/language-support#translate |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
source_language
|
Language code for the source documents. If none is specified, the source language will be auto-detected for each document. |
|
prefix
|
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
|
A case-sensitive suffix string to filter documents in the source path for translation. This is most often use for file extensions. |
|
storage_type
|
Storage type of the input documents source string. Possible values include: "Folder", "File". |
|
category_id
|
Category / custom model ID for using custom translation. |
|
glossaries
|
Glossaries to apply to translation. |
Returns
| Type | Description |
|---|---|
|
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. |
Exceptions
| Type | Description |
|---|---|
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")
elif document.error:
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. :param str translation_id: The translation operation ID. :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError:
cancel_translation(translation_id: str, **kwargs: Any) -> None
Parameters
| Name | Description |
|---|---|
|
translation_id
Required
|
|
close
Close the DocumentTranslationClient session.
close() -> None
get_document_status
Returns the status for a specific document.
Returns the translation status for a specific document based on the request Id and document Id.
get_document_status(translation_id: str, document_id: str, **kwargs: Any) -> DocumentStatus
Parameters
| Name | Description |
|---|---|
|
translation_id
Required
|
Format - uuid. The batch id. Required. |
|
document_id
Required
|
Format - uuid. The document id. Required. |
Returns
| Type | Description |
|---|---|
|
DocumentStatus. The DocumentStatus is compatible with MutableMapping |
Exceptions
| Type | Description |
|---|---|
get_supported_document_formats
Get the list of the document formats supported by the Document Translation service.
get_supported_document_formats(**kwargs: Any) -> List[DocumentTranslationFileFormat]
Returns
| Type | Description |
|---|---|
|
A list of supported document formats for translation. |
Exceptions
| Type | Description |
|---|---|
get_supported_glossary_formats
Get the list of the glossary formats supported by the Document Translation service.
get_supported_glossary_formats(**kwargs: Any) -> List[DocumentTranslationFileFormat]
Returns
| Type | Description |
|---|---|
|
A list of supported glossary formats. |
Exceptions
| Type | Description |
|---|---|
get_translation_status
Returns the status for a document translation request.
Returns the status for a document translation request. The status includes the overall request status, as well as the status for documents that are being translated as part of that request.
get_translation_status(translation_id: str, **kwargs: Any) -> TranslationStatus
Parameters
| Name | Description |
|---|---|
|
translation_id
Required
|
Format - uuid. The operation id. Required. |
Returns
| Type | Description |
|---|---|
|
TranslationStatus. The TranslationStatus is compatible with MutableMapping |
Exceptions
| Type | Description |
|---|---|
list_document_statuses
List all the document statuses for a given translation operation.
list_document_statuses(translation_id: str, *, top: int | None = None, skip: int | None = None, document_ids: List[str] | None = None, statuses: List[str] | None = None, created_after: str | datetime | None = None, created_before: str | datetime | None = None, order_by: List[str] | None = None, **kwargs: Any) -> ItemPaged[DocumentStatus]
Parameters
| Name | Description |
|---|---|
|
translation_id
Required
|
ID of translation operation to list documents for. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
top
|
The total number of documents to return (across all pages). Default value: None
|
|
skip
|
The number of documents to skip (from beginning). By default, we sort by all documents in descending order by start time. Default value: None
|
|
document_ids
|
Document IDs to filter by. Default value: None
|
|
statuses
|
Document statuses to filter by. Options include 'NotStarted', 'Running', 'Succeeded', 'Failed', 'Canceled', 'Canceling', and 'ValidationFailed'. Default value: None
|
|
created_after
|
Get documents created after a certain datetime. Default value: None
|
|
created_before
|
Get documents created before a certain datetime. Default value: None
|
|
order_by
|
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'). Default value: None
|
Returns
| Type | Description |
|---|---|
|
A pageable of DocumentStatus. |
Exceptions
| Type | Description |
|---|---|
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" and document.error:
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: int | None = None, skip: int | None = None, translation_ids: List[str] | None = None, statuses: List[str] | None = None, created_after: str | datetime | None = None, created_before: str | datetime | None = None, order_by: List[str] | None = None, **kwargs: Any) -> ItemPaged[TranslationStatus]
Keyword-Only Parameters
| Name | Description |
|---|---|
|
top
|
The total number of operations to return (across all pages) from all submitted translations. Default value: None
|
|
skip
|
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. Default value: None
|
|
translation_ids
|
Translation operations ids to filter by. Default value: None
|
|
statuses
|
Translation operation statuses to filter by. Options include 'NotStarted', 'Running', 'Succeeded', 'Failed', 'Canceled', 'Canceling', and 'ValidationFailed'. Default value: None
|
|
created_after
|
Get operations created after a certain datetime. Default value: None
|
|
created_before
|
Get operations created before a certain datetime. Default value: None
|
|
order_by
|
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'). Default value: None
|
Returns
| Type | Description |
|---|---|
|
A pageable of TranslationStatus. |
Exceptions
| Type | Description |
|---|---|
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()
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")
send_request
Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
send_request(request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse
Parameters
| Name | Description |
|---|---|
|
request
Required
|
The network request you want to make. Required. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
stream
|
Whether the response payload will be streamed. Defaults to False. Default value: False
|
Returns
| Type | Description |
|---|---|
|
The response of your network call. Does not do error handling on your response. |