azure.ai.translation.document package

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

Status information about a particular document within a translation operation.

characters_charged: int | None = None

Characters charged for the document.

created_on: datetime

The date time when the document was created.

error: DocumentTranslationError | None = None

Returned if there is an error with the particular document. Includes error code, message, target.

id: str

Document Id.

last_updated_on: datetime

The date time when the document’s status was last updated.

source_document_url: str

Location of the source document in the source container. Note that any SAS tokens are removed from this path.

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_document_url: str | None = None

Location of the translated document in the target container. Note that any SAS tokens are removed from this path.

translated_to: str

The language code of the language the document was translated to, if successful.

translation_progress: float

Progress of the translation if available. Value is between [0.0, 1.0].

class azure.ai.translation.document.DocumentTranslationApiVersion(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Document Translation API versions supported by this package

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

V2024_05_01 = '2024-05-01'

This is the default version

class azure.ai.translation.document.DocumentTranslationClient(endpoint: str, credential: 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: 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]][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 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 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")
    elif document.error:
        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) 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[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[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) 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: 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][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.

  • 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 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:

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" 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) ItemPaged[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:

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

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.

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 | None = None

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.

content_types: List[str]

Supported Content-Types for this format.

default_format_version: str | None = None

Default format version if none is specified.

file_extensions: List[str]

Supported file extension for this format.

file_format: str

Name of the format.

format_versions: List[str]

Supported Version.

class azure.ai.translation.document.DocumentTranslationInput(source_url: str, targets: List[TranslationTarget], *, source_language: str | None = None, storage_type: str | StorageInputType | None = None, storage_source: str | None = None, prefix: str | None = None, suffix: str | None = 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 (Optional[str]) – Language code for the source documents. If none is specified, the source language will be auto-detected for each document.

  • prefix (Optional[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 (Optional[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 (Optional[str or StorageInputType]) – Storage type of the input documents source string. Possible values include: “Folder”, “File”.

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

prefix: str | None = None

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.

source_language: str | None = None

Language code for the source documents. If none is specified, the source language will be auto-detected for each document.

source_url: str

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

storage_source: str | None = None

“AzureBlob”. Currently only “AzureBlob” is supported.

Type:

Storage Source. Default value

storage_type: str | StorageInputType | None = None

Storage type of the input documents source string. Possible values include: “Folder”, “File”.

suffix: str | None = None

A case-sensitive suffix string to filter documents in the source path for translation. This is most often use for file extensions.

targets: List[TranslationTarget]

Location of the destination for the output. This is a list of TranslationTargets. Note that a TranslationTarget is required for each language code specified.

class azure.ai.translation.document.DocumentTranslationLROPoller(client: Any, initial_response: Any, deserialization_callback: Callable[[Any], PollingReturnType_co], polling_method: PollingMethod[PollingReturnType_co])[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

polling_method() PollingMethod[PollingReturnType_co]

Return the polling method associated to this poller.

Returns:

The polling method

Return type:

PollingMethod

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: float | None = None) PollingReturnType_co

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

Parameters:

timeout (float) – Period of time to wait before getting back control.

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.

status() str

Returns the current status string.

Returns:

The current status string

Return type:

str

wait(timeout: float | None = 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: TranslationStatus

The details for the translation operation

Returns:

The details for the translation operation.

Return type:

TranslationStatus

property id: str

The ID for the translation operation

Returns:

The str ID for the translation operation.

Return type:

str

class azure.ai.translation.document.SingleDocumentTranslationClient(endpoint: str, credential: AzureKeyCredential | TokenCredential, **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 TokenCredential) – 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.

close() None[source]
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) Iterator[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:

Iterator[bytes]

Return type:

Iterator[bytes]

Raises:

HttpResponseError

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) HttpResponse[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 = client.send_request(request)
<HttpResponse: 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:

HttpResponse

class azure.ai.translation.document.StorageInputType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Storage type of the input documents source string.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

FILE = 'File'

File storage input type

FOLDER = 'Folder'

Folder storage input type

class azure.ai.translation.document.TranslationGlossary(glossary_url: str, file_format: str, *, format_version: str | None = None, storage_source: str | None = None)[source]

Glossary / translation memory to apply to the translation.

Parameters:
Keyword Arguments:
  • format_version (Optional[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 (Optional[str]) – Storage Source. Default value: “AzureBlob”. Currently only “AzureBlob” is supported.

file_format: str

Format of the glossary file. To see supported formats, call the get_supported_glossary_formats() client method.

format_version: str | None = None

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.

glossary_url: str

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.

storage_source: str | None = None

“AzureBlob”. Currently only “AzureBlob” is supported.

Type:

Storage Source. Default value

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

Status information about the translation operation.

created_on: datetime

The date time when the translation operation was created.

documents_canceled_count: int

Number of documents that were canceled for translation.

documents_failed_count: int

Number of documents that failed translation.

documents_in_progress_count: int

Number of translations on documents in progress.

documents_not_started_count: int

Number of documents that have not started being translated.

documents_succeeded_count: int

Number of successful translations on documents.

documents_total_count: int

Number of translations to be made on documents in the operation.

error: DocumentTranslationError | None = None

Returned if there is an error with the translation operation. Includes error code, message, target.

id: str

Id of the translation operation.

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.

total_characters_charged: int

Total characters charged across all documents within the translation operation.

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

Destination for the finished translated documents.

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

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

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

category_id: str | None = None

Category / custom model ID for using custom translation.

glossaries: List[TranslationGlossary] | None = None

Glossaries to apply to translation.

language: str

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

storage_source: str | None = None

“AzureBlob”. Currently only “AzureBlob” is supported.

Type:

Storage Source. Default value

target_url: str

The target location for your translated documents. 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).

Subpackages