azure.ai.translation.document.aio package¶
- class azure.ai.translation.document.aio.AsyncDocumentTranslationLROPoller(client: Any, initial_response: Any, deserialization_callback: Callable[[Any], PollingReturnType_co], polling_method: AsyncPollingMethod[PollingReturnType_co])[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:
- done() bool ¶
Check status of the long running operation.
- Returns:
‘True’ if the process has completed, else ‘False’.
- Return type:
- polling_method() AsyncPollingMethod[PollingReturnType_co] ¶
Return the polling method associated to this poller.
- Returns:
The polling method associated to this poller.
- Return type:
- async result() PollingReturnType_co ¶
Return the result of the long running operation.
- Returns:
The deserialized resource of the long running operation, if one is available.
- Return type:
any or None
- 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: TranslationStatus¶
The details for the translation operation
- Returns:
The details for the translation operation.
- Return type:
- class azure.ai.translation.document.aio.DocumentTranslationClient(endpoint: str, credential: AzureKeyCredential | AsyncTokenCredential, **kwargs: Any)[source]¶
DocumentTranslationClient.
- Parameters:
endpoint (str) – Supported document Translation endpoint, protocol and hostname, for example: https://{TranslatorResourceName}.cognitiveservices.azure.com/translator. Required.
credential (AzureKeyCredential or AsyncTokenCredential) – Credential used to authenticate requests to the service. Is either a AzureKeyCredential type or a TokenCredential type. Required.
- Keyword Arguments:
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(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) 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 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
- 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:
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(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") elif document.error: 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:
- async close() None [source]¶
Close the
DocumentTranslationClient
session.
- async get_document_status(translation_id: str, document_id: str, **kwargs: Any) DocumentStatus [source]¶
Get the status of an individual document within a translation operation.
- Parameters:
- Returns:
A DocumentStatus with information on the status of the document.
- Return type:
- Raises:
- async get_supported_document_formats(**kwargs: Any) List[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:
- Raises:
- async get_supported_glossary_formats(**kwargs: Any) List[DocumentTranslationFileFormat] [source]¶
Get the list of the glossary formats supported by the Document Translation service.
- Returns:
A list of supported glossary formats.
- Return type:
- Raises:
- async get_translation_status(translation_id: str, **kwargs: Any) 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:
- Raises:
- 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) AsyncItemPaged[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.
statuses (list[str]) – Document statuses to filter by. Options include ‘NotStarted’, ‘Running’, ‘Succeeded’, ‘Failed’, ‘Canceled’, ‘Canceling’, and ‘ValidationFailed’.
created_after (str or datetime) – Get documents created after a certain datetime.
created_before (str or datetime) – Get documents created before a 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:
- 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 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" 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(*, 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) AsyncItemPaged[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.
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 a certain datetime.
created_before (str or datetime) – Get operations created before a 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:
- 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_translation_statuses() 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")
- class azure.ai.translation.document.aio.SingleDocumentTranslationClient(endpoint: str, credential: AzureKeyCredential | AsyncTokenCredential, **kwargs: Any)[source]¶
SingleDocumentTranslationClient.
- Parameters:
endpoint (str) – Supported document Translation endpoint, protocol and hostname, for example: https://{TranslatorResourceName}.cognitiveservices.azure.com/translator. Required.
credential (AzureKeyCredential or AsyncTokenCredential) – Credential used to authenticate requests to the service. Is either a AzureKeyCredential type or a TokenCredential type. Required.
- Keyword Arguments:
api_version (str) – The API version to use for this operation. Default value is “2024-05-01”. Note that overriding this default value may result in unsupported behavior.
- async document_translate(body: DocumentTranslateContent | MutableMapping[str, Any], *, target_language: str, source_language: str | None = None, category: str | None = None, allow_fallback: bool | None = None, **kwargs: Any) AsyncIterator[bytes] ¶
Submit a single document translation request to the Document Translation service.
Use this API to submit a single translation request to the Document Translation Service.
- Parameters:
body (DocumentTranslateContent or JSON) – Is either a DocumentTranslateContent type or a JSON type. Required.
- Keyword Arguments:
target_language (str) – Specifies the language of the output document. The target language must be one of the supported languages included in the translation scope. For example if you want to translate the document in German language, then use targetLanguage=de. Required.
source_language (str) – Specifies source language of the input document. If this parameter isn’t specified, automatic language detection is applied to determine the source language. For example if the source document is written in English, then use sourceLanguage=en. Default value is None.
category (str) – A string specifying the category (domain) of the translation. This parameter is used to get translations from a customized system built with Custom Translator. Add the Category ID from your Custom Translator project details to this parameter to use your deployed customized system. Default value is: general. Default value is None.
allow_fallback (bool) – Specifies that the service is allowed to fall back to a general system when a custom system doesn’t exist. Possible values are: true (default) or false. Default value is None.
- Returns:
AsyncIterator[bytes]
- Return type:
AsyncIterator[bytes]
- Raises:
Example
# JSON input template you can fill out and use as your body input. body = { "document": filetype, "glossary": [filetype] }
- send_request(request: HttpRequest, *, stream: bool = False, **kwargs: Any) Awaitable[AsyncHttpResponse] [source]¶
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 = await client.send_request(request) <AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
- Parameters:
request (HttpRequest) – The network request you want to make. Required.
- Keyword Arguments:
stream (bool) – Whether the response payload will be streamed. Defaults to False.
- Returns:
The response of your network call. Does not do error handling on your response.
- Return type: