azure.ai.translation.document.aio package¶
-
class
azure.ai.translation.document.aio.
DocumentTranslationClient
(endpoint: str, credential: Union[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
orTokenCredential
) – Credentials needed for the client to connect to Azure. This is an instance of AzureKeyCredential if using an API key or a token credential fromazure.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:
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))
"""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
(*args, **kwargs)[source]¶ Begin translating the document(s) in your source container to your target container in the given language. To perform a single translation from source to target, pass the source_url, target_url, and target_language_code parameters. To pass multiple inputs for translation, including other translation options, 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
source_url (str) – The source SAS URL to the Azure Blob container containing the documents to be translated. Requires read and list permissions at the minimum.
target_url (str) – The target SAS URL to the Azure Blob container where the translated documents should be written. Requires write and list permissions at the minimum.
target_language_code (str) – 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 (List[DocumentTranslationInput]) – 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.
- Returns
An instance of an AsyncDocumentTranslationLROPoller. Call result() on the poller object to return a pageable of DocumentStatusResult. A DocumentStatusResult will be returned for each translation on a document.
- Return type
AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatusResult]]
- Raises
Example:
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("Status: {}".format(poller.status())) print("Created on: {}".format(poller.details.created_on)) print("Last updated on: {}".format(poller.details.last_updated_on)) print("Total number of translations on documents: {}".format(poller.details.documents_total_count)) print("\nOf total documents...") print("{} failed".format(poller.details.documents_failed_count)) print("{} succeeded".format(poller.details.documents_succeeded_count)) async for document in result: print("Document ID: {}".format(document.id)) print("Document status: {}".format(document.status)) if document.status == "Succeeded": print("Source document location: {}".format(document.source_document_url)) print("Translated document location: {}".format(document.translated_document_url)) print("Translated to language: {}\n".format(document.translated_to)) else: print("Error Code: {}, Message: {}\n".format(document.error.code, document.error.message))
-
async
cancel_translation
(translation_id: str, **kwargs: Any) → None[source]¶ Cancel a currently processing or queued translation operation.
A translation will not be cancelled if it is already completed, failed, or cancelling. All documents that have completed translation will not be cancelled and will be charged. If possible, all pending documents will be cancelled.
- Parameters
translation_id (str) – The translation operation ID.
- Returns
None
- Return type
- Raises
-
async
close
() → None[source]¶ Close the
DocumentTranslationClient
session.
-
async
get_document_formats
(**kwargs: Any) → List[azure.ai.translation.document._models.FileFormat][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[FileFormat]
- Raises
-
async
get_document_status
(translation_id: str, document_id: str, **kwargs: Any) → azure.ai.translation.document._models.DocumentStatusResult[source]¶ Get the status of an individual document within a translation operation.
- Parameters
- Returns
A DocumentStatusResult with information on the status of the document.
- Return type
- Raises
-
async
get_glossary_formats
(**kwargs: Any) → List[azure.ai.translation.document._models.FileFormat][source]¶ Get the list of the glossary formats supported by the Document Translation service.
- Returns
A list of supported glossary formats.
- Return type
List[FileFormat]
- Raises
-
async
get_translation_status
(translation_id: str, **kwargs: Any) → azure.ai.translation.document._models.TranslationStatusResult[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 TranslationStatusResult with information on the status of the translation operation.
- Return type
- Raises
-
list_all_document_statuses
(translation_id: str, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[azure.ai.translation.document._models.DocumentStatusResult][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 descendingly by start time.
results_per_page (int) – is the number of documents returned per page.
translated_after (Union[str, datetime.datetime]) – get document translated after certain datetime.
translated_before (Union[str, datetime.datetime]) – get document translated before certain datetime.
order_by (list[str]) – the sorting query for the documents. format: [“parm1 asc/desc”, “parm2 asc/desc”, …] (ex: ‘createdDateTimeUtc asc’, ‘createdDateTimeUtc desc’).
- Returns
A pageable of DocumentStatusResult.
- Return type
- Raises
Example:
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 not poller.done(): await asyncio.sleep(30) doc_statuses = client.list_all_document_statuses(poller.id) async for document in doc_statuses: if document.id not in completed_docs: if document.status == "Succeeded": print("Document at {} was translated to {} language. You can find translated document at {}".format( document.source_document_url, document.translated_to, document.translated_document_url )) completed_docs.append(document.id) if document.status == "Failed": print("Document at {} failed translation. Error Code: {}, Message: {}".format( document.source_document_url, document.error.code, document.error.message )) completed_docs.append(document.id) if document.status == "Running": print("Document ID: {}, translation progress is {} percent".format( document.id, document.translation_progress * 100 )) print("\nTranslation completed.")
-
list_all_translation_statuses
(**kwargs: Any) → azure.core.async_paging.AsyncItemPaged[azure.ai.translation.document._models.TranslationStatusResult][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 descendingly 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.
created_after (Union[str, datetime.datetime]) – get operations created after certain datetime.
created_before (Union[str, datetime.datetime]) – get operations created before certain datetime.
order_by (list[str]) – the sorting query for the operations returned. format: [“parm1 asc/desc”, “parm2 asc/desc”, …] (ex: ‘createdDateTimeUtc asc’, ‘createdDateTimeUtc desc’).
- Returns
A pageable of TranslationStatusResult.
- Return type
- Raises
Example:
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_all_translation_statuses() # type: AsyncItemPaged[TranslationStatusResult] async for operation in operations: print("ID: {}".format(operation.id)) print("Status: {}".format(operation.status)) print("Created on: {}".format(operation.created_on)) print("Last updated on: {}".format(operation.last_updated_on)) print("Total number of operations on documents: {}".format(operation.documents_total_count)) print("Total number of characters charged: {}".format(operation.total_characters_charged)) print("\nOf total documents...") print("{} failed".format(operation.documents_failed_count)) print("{} succeeded".format(operation.documents_succeeded_count)) print("{} cancelled\n".format(operation.documents_cancelled_count))
-
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
DocumentStatusResult
.-
continuation_token
() → str¶ Return a continuation token that allows to restart the poller later.
- Returns
An opaque continuation token
- Return type
-
done
() → bool¶ Check status of the long running operation.
- Returns
‘True’ if the process has completed, else ‘False’.
- Return type
-
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.
-
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
-