diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/README.md b/sdk/documenttranslation/azure-ai-documenttranslation/README.md index dee698827fa2..aaaeb1ab4a49 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/README.md +++ b/sdk/documenttranslation/azure-ai-documenttranslation/README.md @@ -383,20 +383,18 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [sdk_logging_docs]: https://docs.microsoft.com/azure/developer/python/azure-sdk-logging - +[sample_translation_with_azure_blob_async]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_translation_with_azure_blob_async.py [cla]: https://cla.microsoft.com [code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/__init__.py b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/__init__.py index 2b6a6f21ac62..1304889fdc6c 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/__init__.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/__init__.py @@ -9,7 +9,7 @@ from ._generated.models import ( StorageInputType, ) -from ._api_version import DocumentTranslationVersion +from ._api_version import DocumentTranslationApiVersion from ._models import ( TranslationTarget, JobStatusResult, @@ -25,7 +25,7 @@ __all__ = [ "DocumentTranslationClient", - "DocumentTranslationVersion", + "DocumentTranslationApiVersion", "DocumentTranslationInput", "TranslationGlossary", "StorageInputType", diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_api_version.py b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_api_version.py index 0f162daff872..ca048343218f 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_api_version.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_api_version.py @@ -6,7 +6,7 @@ from enum import Enum -class DocumentTranslationVersion(str, Enum): +class DocumentTranslationApiVersion(str, Enum): """Document Translation API versions supported by this package""" #: This is the default version @@ -20,9 +20,9 @@ def validate_api_version(api_version): return try: - api_version = DocumentTranslationVersion(api_version) + api_version = DocumentTranslationApiVersion(api_version) except ValueError: raise ValueError( "Unsupported API version '{}'. Please select from:\n{}".format( - api_version, ", ".join(v.value for v in DocumentTranslationVersion)) + api_version, ", ".join(v.value for v in DocumentTranslationApiVersion)) ) diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_client.py b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_client.py index fc8115aa066a..93bdd6adbabb 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_client.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_client.py @@ -27,18 +27,31 @@ class DocumentTranslationClient(object): # pylint: disable=r0205 - """DocumentTranslationClient - - """ def __init__(self, endpoint, credential, **kwargs): # type: (str, AzureKeyCredential, **Any) -> None - """ - - :param str endpoint: - :param credential: - :type credential: AzureKeyCredential - :keyword str api_version: + """DocumentTranslationClient is your interface to the Document Translation service. + Use the client to translate whole documents while preserving source document + structure and text formatting. + + :param str endpoint: Supported Document Translation endpoint (protocol and hostname, for example: + https://.cognitiveservices.azure.com/). + :param credential: Credential needed for the client to connect to Azure. + Currently only API key authentication is supported. + :type credential: :class:`~azure.core.credentials.AzureKeyCredential` + :keyword 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. + :paramtype api_version: str or ~azure.ai.documenttranslation.DocumentTranslationApiVersion + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_authentication.py + :start-after: [START create_dt_client_with_key] + :end-before: [END create_dt_client_with_key] + :language: python + :dedent: 4 + :caption: Creating the DocumentTranslationClient with an endpoint and API key. """ self._endpoint = endpoint self._credential = credential @@ -75,12 +88,28 @@ def close(self): @distributed_trace def create_translation_job(self, inputs, **kwargs): # type: (List[DocumentTranslationInput], **Any) -> JobStatusResult - """ + """Create a document translation job which translates the document(s) in your source container + to your TranslationTarget(s) 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 - :param inputs: + :param inputs: 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. :type inputs: List[~azure.ai.documenttranslation.DocumentTranslationInput] - :return: JobStatusResult - :rtype: JobStatusResult + :return: A JobStatusResult with information on the status of the translation job. + :rtype: ~azure.ai.documenttranslation.JobStatusResult + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_check_document_statuses.py + :start-after: [START create_translation_job] + :end-before: [END create_translation_job] + :language: python + :dedent: 4 + :caption: Create a translation job. """ # submit translation job @@ -104,11 +133,15 @@ def get_job_id(response_headers): @distributed_trace def get_job_status(self, job_id, **kwargs): # type: (str, **Any) -> JobStatusResult - """ + """Gets the status of a translation job. - :param job_id: guid id for job - :type job_id: str + The status includes the overall job status, as well as a summary of + the documents that are being translated as part of that translation job. + + :param str job_id: The translation job ID. + :return: A JobStatusResult with information on the status of the translation job. :rtype: ~azure.ai.documenttranslation.JobStatusResult + :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: """ job_status = self._client.document_translation.get_operation_status(job_id, **kwargs) @@ -117,11 +150,16 @@ def get_job_status(self, job_id, **kwargs): @distributed_trace def cancel_job(self, job_id, **kwargs): # type: (str, **Any) -> None - """ + """Cancel a currently processing or queued job. + + A job 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. - :param job_id: guid id for job - :type job_id: str + :param str job_id: The translation job ID. + :return: None :rtype: None + :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: """ self._client.document_translation.cancel_operation(job_id, **kwargs) @@ -129,12 +167,25 @@ def cancel_job(self, job_id, **kwargs): @distributed_trace def wait_until_done(self, job_id, **kwargs): # type: (str, **Any) -> JobStatusResult - """ + """Wait until the translation job is done. + + A job is considered "done" when it reaches a terminal state like + Succeeded, Failed, Cancelled. + + :param str job_id: The translation job ID. + :return: A JobStatusResult with information on the status of the translation job. + :rtype: ~azure.ai.documenttranslation.JobStatusResult + :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: + Will raise if validation fails on the input. E.g. insufficient permissions on the blob containers. + + .. admonition:: Example: - :param job_id: guid id for job - :type job_id: str - :return: JobStatusResult - :rtype: JobStatusResult + .. literalinclude:: ../samples/sample_create_translation_job.py + :start-after: [START wait_until_done] + :end-before: [END wait_until_done] + :language: python + :dedent: 4 + :caption: Create a translation job and wait until it is done. """ pipeline_response = self._client.document_translation.get_operation_status( @@ -161,11 +212,27 @@ def callback(raw_response): @distributed_trace def list_submitted_jobs(self, **kwargs): # type: (**Any) -> ItemPaged[JobStatusResult] - """ - - :keyword int results_per_page: - :keyword int skip: - :rtype: ~azure.core.polling.ItemPaged[JobStatusResult] + """List all the submitted translation jobs under the Document Translation resource. + + :keyword int top: Use top to indicate the total number of results you want + to be returned across all pages. + :keyword int skip: Use skip to indicate the number of results to skip from the list + of jobs held by the server based on the sorting method specified. By default, + this is sorted by descending start time. + :keyword int results_per_page: Use results_per_page to indicate the maximum number + of results returned in a page. + :return: ~azure.core.paging.ItemPaged[:class:`~azure.ai.documenttranslation.JobStatusResult`] + :rtype: ~azure.core.paging.ItemPaged + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_list_all_submitted_jobs.py + :start-after: [START list_all_jobs] + :end-before: [END list_all_jobs] + :language: python + :dedent: 4 + :caption: List all submitted jobs under the resource. """ skip = kwargs.pop('skip', None) @@ -190,13 +257,28 @@ def _convert_from_generated_model(generated_model): # pylint: disable=protected @distributed_trace def list_all_document_statuses(self, job_id, **kwargs): # type: (str, **Any) -> ItemPaged[DocumentStatusResult] - """ - - :param job_id: guid id for job - :type job_id: str - :keyword int results_per_page: - :keyword int skip: - :rtype: ~azure.core.paging.ItemPaged[DocumentStatusResult] + """List all the document statuses under a translation job. + + :param str job_id: The translation job ID. + :keyword int top: Use top to indicate the total number of results you want + to be returned across all pages. + :keyword int skip: Use skip to indicate the number of results to skip from the list + of document statuses held by the server based on the sorting method specified. By default, + this is sorted by descending start time. + :keyword int results_per_page: Use results_per_page to indicate the maximum number + of results returned in a page. + :return: ~azure.core.paging.ItemPaged[:class:`~azure.ai.documenttranslation.DocumentStatusResult`] + :rtype: ~azure.core.paging.ItemPaged + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/sample_create_translation_job.py + :start-after: [START list_all_document_statuses] + :end-before: [END list_all_document_statuses] + :language: python + :dedent: 4 + :caption: List all the document statuses under the translation job. """ skip = kwargs.pop('skip', None) @@ -223,13 +305,13 @@ def _convert_from_generated_model(generated_model): @distributed_trace def get_document_status(self, job_id, document_id, **kwargs): # type: (str, str, **Any) -> DocumentStatusResult - """ + """Get the status of an individual document within a translation job. - :param job_id: guid id for job - :type job_id: str - :param document_id: guid id for document - :type document_id: str + :param str job_id: The translation job ID. + :param str document_id: The ID for the document. + :return: A DocumentStatusResult with information on the status of the document. :rtype: ~azure.ai.documenttranslation.DocumentStatusResult + :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: """ document_status = self._client.document_translation.get_document_status( @@ -241,9 +323,11 @@ def get_document_status(self, job_id, document_id, **kwargs): @distributed_trace def get_glossary_formats(self, **kwargs): # type: (**Any) -> List[FileFormat] - """ + """Get the list of the glossary formats supported by the Document Translation service. + :return: A list of supported glossary formats. :rtype: List[FileFormat] + :raises ~azure.core.exceptions.HttpResponseError: """ glossary_formats = self._client.document_translation.get_glossary_formats(**kwargs) @@ -252,9 +336,11 @@ def get_glossary_formats(self, **kwargs): @distributed_trace def get_document_formats(self, **kwargs): # type: (**Any) -> List[FileFormat] - """ + """Get the list of the document formats supported by the Document Translation service. + :return: A list of supported document formats for translation. :rtype: List[FileFormat] + :raises ~azure.core.exceptions.HttpResponseError: """ document_formats = self._client.document_translation.get_document_formats(**kwargs) diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_models.py b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_models.py index c1e3ed16cb9f..661924541dcd 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_models.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/_models.py @@ -6,7 +6,6 @@ # pylint: disable=unused-import from typing import Any, List -import six from ._generated.models import ( BatchRequest as _BatchRequest, SourceInput as _SourceInput, @@ -15,18 +14,31 @@ Glossary as _Glossary ) + class TranslationGlossary(object): # pylint: disable=useless-object-inheritance - """Glossary / translation memory for the request. - - :param glossary_url: Required. Location of the glossary. - We will use the file extension to extract the formatting if the format parameter is not - supplied. - If the translation language pair is not present in the glossary, it will not be applied. - :type glossary_url: str - :param str file_format: Format. - :keyword str format_version: Format version. - :keyword storage_source: Storage Source. Default value: "AzureBlob". - :paramtype storage_source: str + """Glossary / translation memory to apply to the translation. + + :param str glossary_url: Required. Location of the glossary file. This should be a SAS URL to + the glossary file in the storage blob container. If the translation language pair is + not present in the glossary, it will not be applied. + :param str file_format: Required. Format of the glossary file. To see supported formats, + call the :func:`~DocumentTranslationClient.get_glossary_formats()` client method. + :keyword str format_version: File format version. If not specified, the service will + use the default_version for the file format returned from the + :func:`~DocumentTranslationClient.get_glossary_formats()` client method. + :keyword str storage_source: Storage Source. Default value: "AzureBlob". + Currently only "AzureBlob" is supported. + + :ivar str glossary_url: Required. Location of the glossary file. This should be a SAS URL to + the glossary file in the storage blob container. If the translation language pair is + not present in the glossary, it will not be applied. + :ivar str file_format: Required. Format of the glossary file. To see supported formats, + call the :func:`~DocumentTranslationClient.get_glossary_formats()` client method. + :ivar str format_version: File format version. If not specified, the service will + use the default_version for the file format returned from the + :func:`~DocumentTranslationClient.get_glossary_formats()` client method. + :ivar str storage_source: Storage Source. Default value: "AzureBlob". + Currently only "AzureBlob" is supported. """ def __init__( @@ -57,15 +69,27 @@ def _to_generated_list(glossaries): class TranslationTarget(object): # pylint: disable=useless-object-inheritance """Destination for the finished translated documents. - :param target_url: Required. Location of the folder / container with your documents. - :type target_url: str - :param language_code: Required. Target Language Code. - :type language_code: str - :keyword str category_id: Category / custom system for translation request. - :keyword glossaries: List of TranslationGlossary. + :param str target_url: Required. The target location for your translated documents. + This should be a container SAS URL to your target container. + :param str language_code: Required. 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 + :keyword str category_id: Category / custom model ID for using custom translation. + :keyword glossaries: Glossaries to apply to translation. :paramtype glossaries: list[~azure.ai.documenttranslation.TranslationGlossary] - :keyword storage_source: Storage Source. Default value: "AzureBlob". - :paramtype storage_source: str + :keyword str storage_source: Storage Source. Default value: "AzureBlob". + Currently only "AzureBlob" is supported. + + :ivar str target_url: Required. The target location for your translated documents. + This should be a container SAS URL to your target container. + :ivar str language_code: Required. 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 + :ivar str category_id: Category / custom model ID for using custom translation. + :ivar glossaries: Glossaries to apply to translation. + :vartype glossaries: list[~azure.ai.documenttranslation.TranslationGlossary] + :ivar str storage_source: Storage Source. Default value: "AzureBlob". + Currently only "AzureBlob" is supported. """ def __init__( @@ -98,24 +122,46 @@ def _to_generated_list(targets): class DocumentTranslationInput(object): # pylint: disable=useless-object-inheritance # pylint: disable=C0301 - """Definition for the input batch translation request. - - :param source_url: Required. Location of the folder / container or single file with your - documents. - :type source_url: str - :param targets: Required. Location of the destination for the output. - :type targets: list[TranslationTarget] - :keyword str source_language_code: Language code - If none is specified, we will perform auto detect on the document. + """Input for translation. This requires that you have your source document or + documents in an Azure Blob Storage container. Provide a SAS 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. + + :param str source_url: Required. Location of the folder / container or single file with your + documents. + :param targets: Required. Location of the destination for the output. This is a list of + TranslationTargets. Note that a TranslationTarget is required for each language code specified. + :type targets: list[~azure.ai.documenttranslation.TranslationTarget] + :keyword str source_language_code: Language code for the source documents. + If none is specified, the source language will be auto-detected for each document. :keyword str 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. + translation. For example, when using a Azure storage blob Uri, use the prefix to restrict + sub folders for translation. :keyword str suffix: A case-sensitive suffix string to filter documents in the source path for - translation. This is most often use for file extensions. + translation. This is most often use for file extensions. :keyword storage_type: Storage type of the input documents source string. Possible values - include: "Folder", "File". + include: "Folder", "File". :paramtype storage_type: str or ~azure.ai.documenttranslation.StorageInputType :keyword str storage_source: Storage Source. Default value: "AzureBlob". + Currently only "AzureBlob" is supported. + + :ivar str source_url: Required. Location of the folder / container or single file with your + documents. + :ivar targets: Required. Location of the destination for the output. This is a list of + TranslationTargets. Note that a TranslationTarget is required for each language code specified. + :vartype targets: list[~azure.ai.documenttranslation.TranslationTarget] + :ivar str source_language_code: Language code for the source documents. + If none is specified, the source language will be auto-detected for each document. + :ivar str 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. + :ivar str suffix: A case-sensitive suffix string to filter documents in the source path for + translation. This is most often use for file extensions. + :ivar storage_type: Storage type of the input documents source string. Possible values + include: "Folder", "File". + :vartype storage_type: str or ~azure.ai.documenttranslation.StorageInputType + :ivar str storage_source: Storage Source. Default value: "AzureBlob". + Currently only "AzureBlob" is supported. """ def __init__( @@ -157,30 +203,36 @@ def _to_generated_list(batch_document_inputs): class JobStatusResult(object): # pylint: disable=useless-object-inheritance, too-many-instance-attributes - """Job status response. + """Status information about the translation job. - :ivar id: Required. Id of the job. - :vartype id: str - :ivar created_on: Required. Operation created date time. + :ivar str id: Id of the job. + :ivar created_on: The date time when the translation job was created. :vartype created_on: ~datetime.datetime - :ivar last_updated_on: Required. Date time in which the operation's status has been - updated. + :ivar last_updated_on: The date time when the translation job's status was last updated. :vartype last_updated_on: ~datetime.datetime - :ivar status: Required. List of possible statuses for job or document. Possible values - include: "NotStarted", "Running", "Succeeded", "Failed", "Cancelled", "Cancelling", - "ValidationFailed". - :vartype status: str - :ivar error: This contains an outer error with error code, message, details, target and an - inner error with more descriptive details. + :ivar str status: Status for a job. + + * `NotStarted` - the job has not begun yet. + * `Running` - translation is in progress. + * `Succeeded` - at least one document translated successfully within the job. + * `Cancelled` - the job was cancelled. + * `Cancelling` - the job is being cancelled. + * `ValidationFailed` - the input failed validation. E.g. there was insufficient permissions on blob containers. + * `Failed` - all the documents within the job failed. To understand the reason for each document failure, + call the :func:`~DocumentTranslationClient.list_all_document_statuses()` client method and inspect the error. + + :ivar error: Returned if there is an error with the translation job. + Includes error code, message, target. :vartype error: ~azure.ai.documenttranslation.DocumentTranslationError - :ivar int documents_total_count: Total count. - :ivar int documents_failed_count: Failed count. - :ivar int documents_succeeded_count: Number of Success. - :ivar int documents_in_progress_count: Number of in progress. - :ivar int documents_not_yet_started_count: Count of not yet started. - :ivar int documents_cancelled_count: Number of cancelled. - :ivar int total_characters_charged: Required. Total characters charged by the API. - + :ivar int documents_total_count: Number of translations to be made on documents in the job. + :ivar int documents_failed_count: Number of documents that failed translation. + More details can be found by calling the :func:`~DocumentTranslationClient.list_all_document_statuses` + client method. + :ivar int documents_succeeded_count: Number of successful translations on documents. + :ivar int documents_in_progress_count: Number of translations on documents in progress. + :ivar int documents_not_yet_started_count: Number of documents that have not yet started being translated. + :ivar int documents_cancelled_count: Number of documents that were cancelled for translation. + :ivar int total_characters_charged: Total characters charged across all documents within the job. """ def __init__( @@ -221,29 +273,31 @@ def _from_generated(cls, batch_status_details): class DocumentStatusResult(object): # pylint: disable=useless-object-inheritance, R0903 - """DocumentStatusResult. + """Status information about a particular document within a translation job. - :ivar translated_document_url: Required. Location of the translated document. - :vartype translated_document_url: str - :ivar created_on: Required. Operation created date time. + :ivar str translated_document_url: Location of the translated document in the target + container. Note that any SAS tokens are removed from this path. + :ivar created_on: The date time when the document was created. :vartype created_on: ~datetime.datetime - :ivar last_updated_on: Required. Date time in which the operation's status has been - updated. + :ivar last_updated_on: The date time when the document's status was last updated. :vartype last_updated_on: ~datetime.datetime - :ivar status: Required. List of possible statuses for job or document. Possible values - include: "NotStarted", "Running", "Succeeded", "Failed", "Cancelled", "Cancelling", - "ValidationFailed". - :vartype status: str - :ivar translate_to: Required. To language. - :vartype translate_to: str - :ivar error: This contains an outer error with error code, message, details, target and an - inner error with more descriptive details. + :ivar str status: 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. + * `Cancelled` - the job was cancelled, the document was not translated. + * `Cancelling` - the job is cancelling, the document will not be translated. + :ivar str translate_to: The language code of the language the document was translated to, + if successful. + :ivar error: Returned if there is an error with the particular document. + Includes error code, message, target. :vartype error: ~azure.ai.documenttranslation.DocumentTranslationError - :ivar translation_progress: Progress of the translation if available. - :vartype translation_progress: float - :ivar id: Document Id. - :vartype id: str - :ivar int characters_charged: Character charged by the API. + :ivar float translation_progress: Progress of the translation if available. + Value is between [0.0, 1.0]. + :ivar str id: Document Id. + :ivar int characters_charged: Characters charged for the document. """ def __init__( @@ -278,18 +332,15 @@ def _from_generated(cls, doc_status): class DocumentTranslationError(object): # pylint: disable=useless-object-inheritance, R0903 - """This contains an outer error with error code, message, details, target and an - inner error with more descriptive details. - - :ivar code: Enums containing high level error codes. Possible values include: - "InvalidRequest", "InvalidArgument", "InternalServerError", "ServiceUnavailable", - "ResourceNotFound", "Unauthorized", "RequestRateTooHigh". - :vartype code: str - :ivar message: Gets high level error message. - :vartype message: str - :ivar target: Gets the source of the error. - For example it would be "documents" or "document id" in case of invalid document. - :vartype target: str + """This contains the error code, message, and target with descriptive details on why + a translation job or particular document failed. + + :ivar str code: The error code. Possible high level values include: + "InvalidRequest", "InvalidArgument", "InternalServerError", "ServiceUnavailable", + "ResourceNotFound", "Unauthorized", "RequestRateTooHigh". + :ivar str message: The error message associated with the failure. + :ivar str target: The source of the error. + For example it would be "documents" or "document id" in case of invalid document. """ def __init__( @@ -318,7 +369,7 @@ def _from_generated(cls, error): class FileFormat(object): # pylint: disable=useless-object-inheritance, R0903 - """FileFormat. + """Possible file formats supported by the Document Translation service. :ivar file_format: Name of the format. :vartype file_format: str diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/aio/_client_async.py b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/aio/_client_async.py index c6692c96edab..c18a7b736947 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/aio/_client_async.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/azure/ai/documenttranslation/aio/_client_async.py @@ -28,20 +28,32 @@ class DocumentTranslationClient(object): - """DocumentTranslationClient - - """ def __init__( self, endpoint: str, credential: "AzureKeyCredential", **kwargs: Any ) -> None: - """ - - :param str endpoint: - :param credential: - :type credential: AzureKeyCredential - :keyword str api_version: - :rtype: None + """DocumentTranslationClient is your interface to the Document Translation service. + Use the client to translate whole documents while preserving source document + structure and text formatting. + + :param str endpoint: Supported Document Translation endpoint (protocol and hostname, for example: + https://.cognitiveservices.azure.com/). + :param credential: Credential needed for the client to connect to Azure. + Currently only API key authentication is supported. + :type credential: :class:`~azure.core.credentials.AzureKeyCredential` + :keyword 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. + :paramtype api_version: str or ~azure.ai.documenttranslation.DocumentTranslationApiVersion + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_authentication_async.py + :start-after: [START create_dt_client_with_key_async] + :end-before: [END create_dt_client_with_key_async] + :language: python + :dedent: 4 + :caption: Creating the DocumentTranslationClient with an endpoint and API key. """ self._endpoint = endpoint self._credential = credential @@ -75,12 +87,28 @@ async def close(self) -> None: @distributed_trace_async async def create_translation_job(self, inputs, **kwargs): # type: (List[DocumentTranslationInput], **Any) -> JobStatusResult - """ + """Create a document translation job which translates the document(s) in your source container + to your TranslationTarget(s) 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 - :param inputs: + :param inputs: 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. :type inputs: List[~azure.ai.documenttranslation.DocumentTranslationInput] - :return: JobStatusResult - :rtype: JobStatusResult + :return: A JobStatusResult with information on the status of the translation job. + :rtype: ~azure.ai.documenttranslation.JobStatusResult + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_check_document_statuses_async.py + :start-after: [START create_translation_job_async] + :end-before: [END create_translation_job_async] + :language: python + :dedent: 4 + :caption: Create a translation job. """ # submit translation job @@ -106,11 +134,15 @@ def get_job_id(response_headers): @distributed_trace_async async def get_job_status(self, job_id, **kwargs): # type: (str, **Any) -> JobStatusResult - """ + """Gets the status of a translation job. - :param job_id: guid id for job - :type job_id: str + The status includes the overall job status, as well as a summary of + the documents that are being translated as part of that translation job. + + :param str job_id: The translation job ID. + :return: A JobStatusResult with information on the status of the translation job. :rtype: ~azure.ai.documenttranslation.JobStatusResult + :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: """ job_status = await self._client.document_translation.get_operation_status(job_id, **kwargs) @@ -120,11 +152,16 @@ async def get_job_status(self, job_id, **kwargs): @distributed_trace_async async def cancel_job(self, job_id, **kwargs): # type: (str, **Any) -> None - """ + """Cancel a currently processing or queued job. + + A job 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. - :param job_id: guid id for job - :type job_id: str + :param str job_id: The translation job ID. + :return: None :rtype: None + :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: """ await self._client.document_translation.cancel_operation(job_id, **kwargs) @@ -132,12 +169,25 @@ async def cancel_job(self, job_id, **kwargs): @distributed_trace_async async def wait_until_done(self, job_id, **kwargs): # type: (str, **Any) -> JobStatusResult - """ + """Wait until the translation job is done. + + A job is considered "done" when it reaches a terminal state like + Succeeded, Failed, Cancelled. + + :param str job_id: The translation job ID. + :return: A JobStatusResult with information on the status of the translation job. + :rtype: ~azure.ai.documenttranslation.JobStatusResult + :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: + Will raise if validation fails on the input. E.g. insufficient permissions on the blob containers. + + .. admonition:: Example: - :param job_id: guid id for job - :type job_id: str - :return: JobStatusResult - :rtype: JobStatusResult + .. literalinclude:: ../samples/async_samples/sample_create_translation_job_async.py + :start-after: [START wait_until_done_async] + :end-before: [END wait_until_done_async] + :language: python + :dedent: 4 + :caption: Create a translation job and wait until it is done. """ pipeline_response = await self._client.document_translation.get_operation_status( job_id, @@ -163,11 +213,27 @@ def callback(raw_response): @distributed_trace def list_submitted_jobs(self, **kwargs): # type: (**Any) -> AsyncItemPaged[JobStatusResult] - """ - - :keyword int results_per_page: - :keyword int skip: - :rtype: ~azure.core.polling.AsyncItemPaged[JobStatusResult] + """List all the submitted translation jobs under the Document Translation resource. + + :keyword int top: Use top to indicate the total number of results you want + to be returned across all pages. + :keyword int skip: Use skip to indicate the number of results to skip from the list + of jobs held by the server based on the sorting method specified. By default, + this is sorted by descending start time. + :keyword int results_per_page: Use results_per_page to indicate the maximum number + of results returned in a page. + :return: ~azure.core.paging.AsyncItemPaged[:class:`~azure.ai.documenttranslation.JobStatusResult`] + :rtype: ~azure.core.paging.AsyncItemPaged + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_list_all_submitted_jobs_async.py + :start-after: [START list_all_jobs_async] + :end-before: [END list_all_jobs_async] + :language: python + :dedent: 4 + :caption: List all submitted jobs under the resource. """ skip = kwargs.pop('skip', None) results_per_page = kwargs.pop('results_per_page', None) @@ -191,13 +257,28 @@ def _convert_from_generated_model(generated_model): @distributed_trace def list_all_document_statuses(self, job_id, **kwargs): # type: (str, **Any) -> AsyncItemPaged[DocumentStatusResult] - """ - - :param job_id: guid id for job - :type job_id: str - :keyword int results_per_page: - :keyword int skip: - :rtype: ~azure.core.paging.AsyncItemPaged[DocumentStatusResult] + """List all the document statuses under a translation job. + + :param str job_id: The translation job ID. + :keyword int top: Use top to indicate the total number of results you want + to be returned across all pages. + :keyword int skip: Use skip to indicate the number of results to skip from the list + of document statuses held by the server based on the sorting method specified. By default, + this is sorted by descending start time. + :keyword int results_per_page: Use results_per_page to indicate the maximum number + of results returned in a page. + :return: ~azure.core.paging.AsyncItemPaged[:class:`~azure.ai.documenttranslation.DocumentStatusResult`] + :rtype: ~azure.core.paging.AsyncItemPaged + :raises ~azure.core.exceptions.HttpResponseError: + + .. admonition:: Example: + + .. literalinclude:: ../samples/async_samples/sample_create_translation_job_async.py + :start-after: [START list_all_document_statuses_async] + :end-before: [END list_all_document_statuses_async] + :language: python + :dedent: 8 + :caption: List all the document statuses under the translation job. """ skip = kwargs.pop('skip', None) results_per_page = kwargs.pop('results_per_page', None) @@ -223,13 +304,13 @@ def _convert_from_generated_model(generated_model): @distributed_trace_async async def get_document_status(self, job_id, document_id, **kwargs): # type: (str, str, **Any) -> DocumentStatusResult - """ + """Get the status of an individual document within a translation job. - :param job_id: guid id for job - :type job_id: str - :param document_id: guid id for document - :type document_id: str + :param str job_id: The translation job ID. + :param str document_id: The ID for the document. + :return: A DocumentStatusResult with information on the status of the document. :rtype: ~azure.ai.documenttranslation.DocumentStatusResult + :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: """ document_status = await self._client.document_translation.get_document_status(job_id, document_id, **kwargs) # pylint: disable=protected-access @@ -239,9 +320,11 @@ async def get_document_status(self, job_id, document_id, **kwargs): @distributed_trace_async async def get_glossary_formats(self, **kwargs): # type: (**Any) -> List[FileFormat] - """ + """Get the list of the glossary formats supported by the Document Translation service. - :rtype: list[FileFormat] + :return: A list of supported glossary formats. + :rtype: List[FileFormat] + :raises ~azure.core.exceptions.HttpResponseError: """ glossary_formats = await self._client.document_translation.get_glossary_formats(**kwargs) # pylint: disable=protected-access @@ -250,9 +333,11 @@ async def get_glossary_formats(self, **kwargs): @distributed_trace_async async def get_document_formats(self, **kwargs): # type: (**Any) -> List[FileFormat] - """ + """Get the list of the document formats supported by the Document Translation service. - :rtype: list[FileFormat] + :return: A list of supported document formats for translation. + :rtype: List[FileFormat] + :raises ~azure.core.exceptions.HttpResponseError: """ document_formats = await self._client.document_translation.get_document_formats(**kwargs) # pylint: disable=protected-access diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_authentication_async.py b/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_authentication_async.py index 3ce90e19c2d8..ae7cb84817d4 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_authentication_async.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_authentication_async.py @@ -31,6 +31,7 @@ async def sample_authentication_api_key_async(): + # [START create_dt_client_with_key_async] from azure.core.credentials import AzureKeyCredential from azure.ai.documenttranslation.aio import DocumentTranslationClient @@ -38,6 +39,7 @@ async def sample_authentication_api_key_async(): key = os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"] document_translation_client = DocumentTranslationClient(endpoint, AzureKeyCredential(key)) + # [END create_dt_client_with_key_async] # make calls with authenticated client async with document_translation_client: diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_check_document_statuses_async.py b/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_check_document_statuses_async.py index c2d6dc3726a3..f25a48c964e6 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_check_document_statuses_async.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_check_document_statuses_async.py @@ -31,6 +31,7 @@ async def sample_document_status_checks_async(): import os + # [START create_translation_job_async] from azure.core.credentials import AzureKeyCredential from azure.ai.documenttranslation.aio import DocumentTranslationClient from azure.ai.documenttranslation import ( @@ -57,6 +58,7 @@ async def sample_document_status_checks_async(): ) ] ) # type: JobStatusResult + # [END create_translation_job_async] completed_docs = [] while not job_result.has_completed: diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_create_translation_job_async.py b/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_create_translation_job_async.py index c61ca29145d6..99b0c0196718 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_create_translation_job_async.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_create_translation_job_async.py @@ -32,6 +32,7 @@ async def sample_translation_async(): import os + # [START wait_until_done_async] from azure.core.credentials import AzureKeyCredential from azure.ai.documenttranslation.aio import DocumentTranslationClient from azure.ai.documenttranslation import ( @@ -70,7 +71,9 @@ async def sample_translation_async(): print("\nOf total documents...") print("{} failed".format(job_result.documents_failed_count)) print("{} succeeded".format(job_result.documents_succeeded_count)) + # [END wait_until_done_async] + # [START list_all_document_statuses_async] doc_results = client.list_all_document_statuses(job_result.id) # type: AsyncItemPaged[DocumentStatusResult] async for document in doc_results: print("Document ID: {}".format(document.id)) @@ -80,6 +83,7 @@ async def sample_translation_async(): print("Translated to language: {}\n".format(document.translate_to)) else: print("Error Code: {}, Message: {}\n".format(document.error.code, document.error.message)) + # [END list_all_document_statuses_async] async def main(): diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_list_all_submitted_jobs_async.py b/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_list_all_submitted_jobs_async.py index dbb24c154629..abe22a9b3237 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_list_all_submitted_jobs_async.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/samples/async_samples/sample_list_all_submitted_jobs_async.py @@ -27,6 +27,7 @@ async def sample_list_all_submitted_jobs_async(): import os + # [START list_all_jobs_async] from azure.core.credentials import AzureKeyCredential from azure.ai.documenttranslation.aio import DocumentTranslationClient @@ -52,6 +53,7 @@ async def sample_list_all_submitted_jobs_async(): print("{} failed".format(job.documents_failed_count)) print("{} succeeded".format(job.documents_succeeded_count)) print("{} cancelled\n".format(job.documents_cancelled_count)) + # [END list_all_jobs_async] async def main(): diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_authentication.py b/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_authentication.py index 987f91886c1b..ee1ac99f3bcd 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_authentication.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_authentication.py @@ -30,6 +30,7 @@ def sample_authentication_api_key(): + # [START create_dt_client_with_key] from azure.core.credentials import AzureKeyCredential from azure.ai.documenttranslation import DocumentTranslationClient @@ -37,6 +38,7 @@ def sample_authentication_api_key(): key = os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"] document_translation_client = DocumentTranslationClient(endpoint, AzureKeyCredential(key)) + # [END create_dt_client_with_key] # make calls with authenticated client result = document_translation_client.get_document_formats() diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_check_document_statuses.py b/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_check_document_statuses.py index 655d66491609..f8da18a04fbf 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_check_document_statuses.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_check_document_statuses.py @@ -30,6 +30,7 @@ def sample_document_status_checks(): import os import time + # [START create_translation_job] from azure.core.credentials import AzureKeyCredential from azure.ai.documenttranslation import ( DocumentTranslationClient, @@ -56,6 +57,7 @@ def sample_document_status_checks(): ) ] ) # type: JobStatusResult + # [END create_translation_job] completed_docs = [] while not job_result.has_completed: diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_create_translation_job.py b/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_create_translation_job.py index ab24503a6d59..a8acd1eb5aa9 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_create_translation_job.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_create_translation_job.py @@ -29,6 +29,7 @@ def sample_translation(): import os + # [START wait_until_done] from azure.core.credentials import AzureKeyCredential from azure.ai.documenttranslation import ( DocumentTranslationClient, @@ -66,7 +67,9 @@ def sample_translation(): print("\nOf total documents...") print("{} failed".format(job_result.documents_failed_count)) print("{} succeeded".format(job_result.documents_succeeded_count)) + # [END wait_until_done] + # [START list_all_document_statuses] doc_results = client.list_all_document_statuses(job_result.id) # type: ItemPaged[DocumentStatusResult] for document in doc_results: print("Document ID: {}".format(document.id)) @@ -76,7 +79,7 @@ def sample_translation(): print("Translated to language: {}\n".format(document.translate_to)) else: print("Error Code: {}, Message: {}\n".format(document.error.code, document.error.message)) - + # [END list_all_document_statuses] if __name__ == '__main__': sample_translation() diff --git a/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_list_all_submitted_jobs.py b/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_list_all_submitted_jobs.py index 67e2e8858ee1..54574f8960d2 100644 --- a/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_list_all_submitted_jobs.py +++ b/sdk/documenttranslation/azure-ai-documenttranslation/samples/sample_list_all_submitted_jobs.py @@ -25,6 +25,7 @@ def sample_list_all_submitted_jobs(): import os + # [START list_all_jobs] from azure.core.credentials import AzureKeyCredential from azure.ai.documenttranslation import ( DocumentTranslationClient, @@ -52,6 +53,8 @@ def sample_list_all_submitted_jobs(): print("{} succeeded".format(job.documents_succeeded_count)) print("{} cancelled\n".format(job.documents_cancelled_count)) + # [END list_all_jobs] + if __name__ == '__main__': sample_list_all_submitted_jobs()