diff --git a/sdk/translation/azure-ai-translation-document/MANIFEST.in b/sdk/translation/azure-ai-translation-document/MANIFEST.in index 094e4c15616f..881cd7ece367 100644 --- a/sdk/translation/azure-ai-translation-document/MANIFEST.in +++ b/sdk/translation/azure-ai-translation-document/MANIFEST.in @@ -5,5 +5,4 @@ recursive-include tests *.py recursive-include samples *.py *.md include azure/__init__.py include azure/ai/__init__.py -include azure/ai/translation/__init__.py -recursive-include doc *.rst +include azure/ai/translation/__init__.py \ No newline at end of file diff --git a/sdk/translation/azure-ai-translation-document/_meta.json b/sdk/translation/azure-ai-translation-document/_meta.json new file mode 100644 index 000000000000..76dc2f64d9a1 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "4c6a2da5b444995bfdce5caec88633e0c2c70475", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/translation/Azure.AI.DocumentTranslation", + "@azure-tools/typespec-python": "0.36.1" +} \ No newline at end of file diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/__init__.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/__init__.py index d4b4d4d35fa9..1731c5d4d5ee 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/__init__.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/__init__.py @@ -5,40 +5,30 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._patch import DocumentTranslationClient -from ._client import SingleDocumentTranslationClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import DocumentTranslationClient # type: ignore +from ._client import SingleDocumentTranslationClient # type: ignore from ._version import VERSION __version__ = VERSION - -from ._patch import DocumentTranslationApiVersion -from ._patch import DocumentTranslationLROPoller -from ._patch import TranslationGlossary -from ._patch import TranslationTarget -from ._patch import DocumentTranslationInput -from ._patch import TranslationStatus -from ._patch import DocumentStatus -from ._patch import DocumentTranslationError -from ._patch import DocumentTranslationFileFormat -from ._patch import StorageInputType +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] from ._patch import patch_sdk as _patch_sdk __all__ = [ - "DocumentTranslationApiVersion", - "DocumentTranslationLROPoller", - "TranslationGlossary", - "TranslationTarget", - "DocumentTranslationInput", - "TranslationStatus", - "DocumentStatus", - "DocumentTranslationError", - "DocumentTranslationFileFormat", - "StorageInputType", "DocumentTranslationClient", "SingleDocumentTranslationClient", ] - +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_client.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_client.py index 36fb2051321e..a74a5a465b3b 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_client.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_client.py @@ -33,8 +33,9 @@ class DocumentTranslationClient(DocumentTranslationClientOperationsMixin): AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword api_version: 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. + :keyword api_version: The API version to use for this operation. Default value is + "2024-11-15-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. @@ -113,8 +114,9 @@ class SingleDocumentTranslationClient(SingleDocumentTranslationClientOperationsM AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword api_version: 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. + :keyword api_version: The API version to use for this operation. Default value is + "2024-11-15-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_configuration.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_configuration.py index df7480f5c50e..6f463949bde6 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_configuration.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_configuration.py @@ -30,13 +30,14 @@ class DocumentTranslationClientConfiguration: # pylint: disable=too-many-instan AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword api_version: 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. + :keyword api_version: The API version to use for this operation. Default value is + "2024-11-15-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2024-05-01") + api_version: str = kwargs.pop("api_version", "2024-11-15-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -85,13 +86,14 @@ class SingleDocumentTranslationClientConfiguration: # pylint: disable=too-many- AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential - :keyword api_version: 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. + :keyword api_version: The API version to use for this operation. Default value is + "2024-11-15-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2024-05-01") + api_version: str = kwargs.pop("api_version", "2024-11-15-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/__init__.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/__init__.py index 9e327bba3bf1..82a231e9e834 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/__init__.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/__init__.py @@ -5,16 +5,23 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._patch import DocumentTranslationClientOperationsMixin -from ._patch import SingleDocumentTranslationClientOperationsMixin +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import +from ._operations import DocumentTranslationClientOperationsMixin # type: ignore +from ._operations import SingleDocumentTranslationClientOperationsMixin # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "DocumentTranslationClientOperationsMixin", "SingleDocumentTranslationClientOperationsMixin", ] - +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/_operations.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/_operations.py index e86f7ccb4210..5d58a109b0fb 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/_operations.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/_operations.py @@ -34,6 +34,7 @@ from .. import _model_base, models as _models from .._model_base import SdkJSONEncoder, _deserialize from .._serialization import Serializer +from .._validation import api_version_validation from .._vendor import ( DocumentTranslationClientMixinABC, SingleDocumentTranslationClientMixinABC, @@ -59,7 +60,7 @@ def build_document_translation__begin_translation_request( # pylint: disable=na _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -91,7 +92,7 @@ def build_document_translation_list_translation_statuses_request( # pylint: dis _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -132,7 +133,7 @@ def build_document_translation_get_document_status_request( # pylint: disable=n _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -159,7 +160,7 @@ def build_document_translation_get_translation_status_request( # pylint: disabl _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -185,7 +186,7 @@ def build_document_translation_cancel_translation_request( # pylint: disable=na _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -221,7 +222,7 @@ def build_document_translation_list_document_statuses_request( # pylint: disabl _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -267,7 +268,7 @@ def build_document_translation_get_supported_formats_request( # pylint: disable _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -290,12 +291,13 @@ def build_single_document_translation_translate_request( # pylint: disable=name source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, + translate_text_within_image: Optional[bool] = None, **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-11-15-preview")) accept = _headers.pop("Accept", "application/octet-stream") # Construct URL @@ -310,6 +312,10 @@ def build_single_document_translation_translate_request( # pylint: disable=name _params["category"] = _SERIALIZER.query("category", category, "str") if allow_fallback is not None: _params["allowFallback"] = _SERIALIZER.query("allow_fallback", allow_fallback, "bool") + if translate_text_within_image is not None: + _params["translateTextWithinImage"] = _SERIALIZER.query( + "translate_text_within_image", translate_text_within_image, "bool" + ) # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -1243,6 +1249,7 @@ def translate( source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, + translate_text_within_image: Optional[bool] = None, **kwargs: Any, ) -> Iterator[bytes]: """Submit a single document translation request to the Document Translation service. @@ -1273,6 +1280,9 @@ def translate( when a custom system doesn't exist. Possible values are: true (default) or false. Default value is None. :paramtype allow_fallback: bool + :keyword translate_text_within_image: Optional boolean parameter to translate text within an + image in the document. Default value is None. + :paramtype translate_text_within_image: bool :return: Iterator[bytes] :rtype: Iterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: @@ -1287,6 +1297,7 @@ def translate( source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, + translate_text_within_image: Optional[bool] = None, **kwargs: Any, ) -> Iterator[bytes]: """Submit a single document translation request to the Document Translation service. @@ -1317,12 +1328,18 @@ def translate( when a custom system doesn't exist. Possible values are: true (default) or false. Default value is None. :paramtype allow_fallback: bool + :keyword translate_text_within_image: Optional boolean parameter to translate text within an + image in the document. Default value is None. + :paramtype translate_text_within_image: bool :return: Iterator[bytes] :rtype: Iterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace + @api_version_validation( + params_added_on={"2024-11-15-preview": ["translate_text_within_image"]}, + ) def translate( self, body: Union[_models.DocumentTranslateContent, JSON], @@ -1331,6 +1348,7 @@ def translate( source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, + translate_text_within_image: Optional[bool] = None, **kwargs: Any, ) -> Iterator[bytes]: """Submit a single document translation request to the Document Translation service. @@ -1362,6 +1380,9 @@ def translate( when a custom system doesn't exist. Possible values are: true (default) or false. Default value is None. :paramtype allow_fallback: bool + :keyword translate_text_within_image: Optional boolean parameter to translate text within an + image in the document. Default value is None. + :paramtype translate_text_within_image: bool :return: Iterator[bytes] :rtype: Iterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: @@ -1389,6 +1410,7 @@ def translate( source_language=source_language, category=category, allow_fallback=allow_fallback, + translate_text_within_image=translate_text_within_image, api_version=self._config.api_version, files=_files, data=_data, @@ -1417,6 +1439,13 @@ def translate( raise HttpResponseError(response=response) response_headers = {} + response_headers["x-metered-usage"] = self._deserialize("int", response.headers.get("x-metered-usage")) + response_headers["x-metered-usage-image-scan-count-pass"] = self._deserialize( + "int", response.headers.get("x-metered-usage-image-scan-count-pass") + ) + response_headers["x-metered-usage-image-scan-count-fail"] = self._deserialize( + "int", response.headers.get("x-metered-usage-image-scan-count-fail") + ) response_headers["x-ms-client-request-id"] = self._deserialize( "str", response.headers.get("x-ms-client-request-id") ) diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/_patch.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/_patch.py index d597e1c2ed86..f7dd32510333 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/_patch.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_operations/_patch.py @@ -2,550 +2,13 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -# pylint: disable=too-many-lines,protected-access """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import List -import sys -from typing import Any, IO, Callable, Dict, Iterator, List, Optional, Type, TypeVar, Union, cast, overload, Tuple -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict -from azure.core.rest import HttpRequest, HttpResponse, AsyncHttpResponse -from azure.core.pipeline import PipelineResponse -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - ODataV4Format, - map_error, -) -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.polling.base_polling import ( - LROBasePolling, - OperationResourcePolling, - _is_empty, - _as_json, - BadResponse, - OperationFailed, - _raise_if_bad_http_status_and_method, -) -from .. import _model_base, models as _models -from ..models import ( - TranslationStatus, -) -from .._model_base import _deserialize -from ._operations import ( - DocumentTranslationClientOperationsMixin as GeneratedDocumentTranslationClientOperationsMixin, - SingleDocumentTranslationClientOperationsMixin as GeneratedSingleDocumentTranslationClientOperationsMixin, - JSON, - ClsType, - build_single_document_translation_translate_request, -) - -from .._vendor import prepare_multipart_form_data - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # type: ignore[misc] # pylint: disable=unsubscriptable-object -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] # type: ignore - - -ResponseType = Union[HttpResponse, AsyncHttpResponse] -PipelineResponseType = PipelineResponse[HttpRequest, ResponseType] -PollingReturnType_co = TypeVar("PollingReturnType_co", covariant=True) - -_FINISHED = frozenset(["succeeded", "cancelled", "cancelling", "failed"]) -_FAILED = frozenset(["validationfailed"]) - - -def convert_status(status, ll=False): - if ll is False: - if status == "Cancelled": - return "Canceled" - if status == "Cancelling": - return "Canceling" - elif ll is True: - if status == "Canceled": - return "Cancelled" - if status == "Canceling": - return "Cancelling" - return status - - -class DocumentTranslationLROPoller(LROPoller[PollingReturnType_co]): - """A custom poller implementation for Document Translation. Call `result()` on the poller to return - a pageable of :class:`~azure.ai.translation.document.DocumentStatus`.""" - - _polling_method: "DocumentTranslationLROPollingMethod" - - @property - def id(self) -> str: - """The ID for the translation operation - - :return: The str ID for the translation operation. - :rtype: str - """ - if self._polling_method._current_body: - return self._polling_method._current_body.id - return self._polling_method._get_id_from_headers() - - @property - def details(self) -> TranslationStatus: - """The details for the translation operation - - :return: The details for the translation operation. - :rtype: ~azure.ai.translation.document.TranslationStatus - """ - if self._polling_method._current_body: - return TranslationStatus(self._polling_method._current_body) - return TranslationStatus(id=self._polling_method._get_id_from_headers()) # type: ignore - - @classmethod - def from_continuation_token( # pylint: disable=docstring-missing-return,docstring-missing-param,docstring-missing-rtype - cls, polling_method, continuation_token, **kwargs: Any - ): - """ - :meta private: - """ - ( - client, - initial_response, - deserialization_callback, - ) = polling_method.from_continuation_token(continuation_token, **kwargs) - - return cls(client, initial_response, deserialization_callback, polling_method) - - -class DocumentTranslationLROPollingMethod(LROBasePolling): - """A custom polling method implementation for Document Translation.""" - - def __init__(self, *args, **kwargs): - self._cont_token_response = kwargs.pop("cont_token_response") - super().__init__(*args, **kwargs) - - @property - def _current_body(self) -> TranslationStatus: - try: - return TranslationStatus(self._pipeline_response.http_response.json()) - except Exception: # pylint: disable=broad-exception-caught - return TranslationStatus() # type: ignore[call-overload] - - def _get_id_from_headers(self) -> str: - return ( - self._initial_response.http_response.headers["Operation-Location"] - .split("/batches/")[1] - .split("?api-version")[0] - ) - - def finished(self) -> bool: - """Is this polling finished? - - :return: True/False for whether polling is complete. - :rtype: bool - """ - return self._finished(self.status()) - - @staticmethod - def _finished(status) -> bool: - if hasattr(status, "value"): - status = status.value - return str(status).lower() in _FINISHED - - @staticmethod - def _failed(status) -> bool: - if hasattr(status, "value"): - status = status.value - return str(status).lower() in _FAILED - - def get_continuation_token(self) -> str: - if self._current_body: - return self._current_body.id - return self._get_id_from_headers() - - # pylint: disable=arguments-differ - def from_continuation_token(self, continuation_token: str, **kwargs: Any) -> Tuple: # type: ignore[override] - try: - client = kwargs["client"] - except KeyError as exc: - raise ValueError("Need kwarg 'client' to be recreated from continuation_token") from exc - - try: - deserialization_callback = kwargs["deserialization_callback"] - except KeyError as exc: - raise ValueError("Need kwarg 'deserialization_callback' to be recreated from continuation_token") from exc - - return client, self._cont_token_response, deserialization_callback - - def _poll(self) -> None: - """Poll status of operation so long as operation is incomplete and - we have an endpoint to query. - - :raises: OperationFailed if operation status 'Failed' or 'Canceled'. - :raises: BadStatus if response status invalid. - :raises: BadResponse if response invalid. - """ - - if not self.finished(): - self.update_status() - while not self.finished(): - self._delay() - self.update_status() - - if self._failed(self.status()): - raise OperationFailed("Operation failed or canceled") - - final_get_url = self._operation.get_final_get_url(self._pipeline_response) - if final_get_url: - self._pipeline_response = self.request_status(final_get_url) - _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) - - -class TranslationPolling(OperationResourcePolling): - """Implements a Location polling.""" - - def can_poll(self, pipeline_response: PipelineResponseType) -> bool: - """Answer if this polling method could be used. - - :param pipeline_response: The PipelineResponse type - :type pipeline_response: PipelineResponseType - :return: Whether polling should be performed. - :rtype: bool - """ - response = pipeline_response.http_response - can_poll = self._operation_location_header in response.headers - if can_poll: - return True - - if not _is_empty(response): - body = _as_json(response) - status = body.get("status") - if status: - return True - return False - - def _set_async_url_if_present(self, response: ResponseType) -> None: - location_header = response.headers.get(self._operation_location_header) - if location_header: - self._async_url = location_header - else: - self._async_url = response.request.url - - def get_status(self, pipeline_response: PipelineResponseType) -> str: - """Process the latest status update retrieved from a 'location' header. - - :param azure.core.pipeline.PipelineResponse pipeline_response: latest REST call response. - :return: The current operation status - :rtype: str - :raises: BadResponse if response has no body and not status 202. - """ - response = pipeline_response.http_response - if not _is_empty(response): - body = _as_json(response) - status = body.get("status") - if status: - return self._map_nonstandard_statuses(status, body) - raise BadResponse("No status found in body") - raise BadResponse("The response from long running operation does not contain a body.") - - def _map_nonstandard_statuses(self, status: str, body: Dict[str, Any]) -> str: - """Map non-standard statuses. - - :param str status: lro process status. - :param str body: pipeline response body. - :return: The current operation status. - :rtype: str - """ - if status == "ValidationFailed": - self.raise_error(body) - return status - - def raise_error(self, body: Dict[str, Any]) -> None: - error = body["error"] - if body["error"].get("innerError", None): - error = body["error"]["innerError"] - http_response_error = HttpResponseError(message="({}): {}".format(error["code"], error["message"])) - http_response_error.error = ODataV4Format(error) # set error.code - raise http_response_error - - -class DocumentTranslationClientOperationsMixin(GeneratedDocumentTranslationClientOperationsMixin): - - @distributed_trace - def _begin_translation( # type: ignore[override] - self, body: Union[_models.StartTranslationDetails, JSON, IO[bytes]], **kwargs: Any - ) -> DocumentTranslationLROPoller[_models.TranslationStatus]: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.TranslationStatus] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self.__begin_translation_initial( # type: ignore[func-returns-value] - body=body, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.TranslationStatus, response.json()) - if cls: - return cls(pipeline_response, deserialized, response_headers) - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return DocumentTranslationLROPoller[_models.TranslationStatus].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return DocumentTranslationLROPoller[_models.TranslationStatus]( - self._client, raw_result, get_long_running_output, polling_method - ) - - -class SingleDocumentTranslationClientOperationsMixin( - GeneratedSingleDocumentTranslationClientOperationsMixin -): # pylint: disable=name-too-long - - @overload - def translate( - self, - body: _models.DocumentTranslateContent, - *, - target_language: str, - source_language: Optional[str] = None, - category: Optional[str] = None, - allow_fallback: Optional[bool] = 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. - - :param body: Required. - :type body: ~azure.ai.translation.document.models.DocumentTranslateContent - :keyword target_language: 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. - :paramtype target_language: str - :keyword source_language: 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. - :paramtype source_language: str - :keyword category: 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. - :paramtype category: str - :keyword allow_fallback: 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. - :paramtype allow_fallback: bool - :return: Iterator[bytes] - :rtype: Iterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "document": filetype, - "glossary": [filetype] - } - """ - - @overload - def translate( - self, - body: JSON, - *, - target_language: str, - source_language: Optional[str] = None, - category: Optional[str] = None, - allow_fallback: Optional[bool] = 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. - - :param body: Required. - :type body: JSON - :keyword target_language: 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. - :paramtype target_language: str - :keyword source_language: 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. - :paramtype source_language: str - :keyword category: 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. - :paramtype category: str - :keyword allow_fallback: 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. - :paramtype allow_fallback: bool - :return: Iterator[bytes] - :rtype: Iterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def translate( - self, - body: Union[_models.DocumentTranslateContent, JSON], - *, - target_language: str, - source_language: Optional[str] = None, - category: Optional[str] = None, - allow_fallback: Optional[bool] = 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. - - :param body: Is either a DocumentTranslateContent type or a JSON type. Required. - :type body: ~azure.ai.translation.document.models.DocumentTranslateContent or JSON - :keyword target_language: 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. - :paramtype target_language: str - :keyword source_language: 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. - :paramtype source_language: str - :keyword category: 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. - :paramtype category: str - :keyword allow_fallback: 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. - :paramtype allow_fallback: bool - :return: Iterator[bytes] - :rtype: Iterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "document": filetype, - "glossary": [filetype] - } - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _body = body.as_dict() if isinstance(body, _model_base.Model) else body - _file_fields: List[str] = ["document", "glossary"] - _data_fields: List[str] = [] - _files, _data = prepare_multipart_form_data(_body, _file_fields, _data_fields) - - _request = build_single_document_translation_translate_request( - target_language=target_language, - source_language=source_language, - category=category, - allow_fallback=allow_fallback, - api_version=self._config.api_version, - files=_files, - data=_data, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", True) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - # deserialized = response.iter_bytes() - - if cls: - # return cls(pipeline_response, deserialized, response_headers) - return cls(pipeline_response, response.read(), response_headers) # type: ignore - - return response.read() - - -__all__: List[str] = [ - "DocumentTranslationClientOperationsMixin", - "SingleDocumentTranslationClientOperationsMixin", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_patch.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_patch.py index 4eab449fd8c3..f7dd32510333 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_patch.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_patch.py @@ -2,670 +2,13 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -# mypy: disable-error-code="attr-defined" -# pylint: disable=too-many-lines +"""Customize generated code here. -from typing import Any, List, Union, overload, Optional, cast, Mapping, IO, MutableMapping -from enum import Enum -import json -import datetime -from io import IOBase -from azure.core import CaseInsensitiveEnumMeta -from azure.core.tracing.decorator import distributed_trace -from azure.core.paging import ItemPaged -from azure.core.credentials import AzureKeyCredential, TokenCredential -from azure.core.pipeline.policies import HttpLoggingPolicy +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List -from ._operations._patch import DocumentTranslationLROPoller, DocumentTranslationLROPollingMethod, TranslationPolling -from ._client import DocumentTranslationClient as GeneratedDocumentTranslationClient -from .models import ( - DocumentBatch, - SourceInput, - TranslationTarget, - DocumentFilter, - TranslationGlossary, - DocumentStatus, - StartTranslationDetails, - StorageInputType, - DocumentTranslationFileFormat, - TranslationStatus, - DocumentTranslationError, - DocumentTranslationInput, -) -from .models._patch import convert_status - -JSON = MutableMapping[str, Any] - -POLLING_INTERVAL = 1 - - -def convert_datetime(date_time: Union[str, datetime.datetime]) -> datetime.datetime: - if isinstance(date_time, datetime.datetime): - return date_time - if isinstance(date_time, str): - try: - return datetime.datetime.strptime(date_time, "%Y-%m-%d") - except ValueError: - try: - return datetime.datetime.strptime(date_time, "%Y-%m-%dT%H:%M:%SZ") - except ValueError: - return datetime.datetime.strptime(date_time, "%Y-%m-%d %H:%M:%S") - raise TypeError("Bad datetime type") - - -def convert_order_by(orderby: Optional[List[str]]) -> Optional[List[str]]: - if orderby: - orderby = [order.replace("created_on", "createdDateTimeUtc") for order in orderby] - return orderby - - -class DocumentTranslationApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Document Translation API versions supported by this package""" - - #: This is the default version - V2024_05_01 = "2024-05-01" - - -def get_translation_input(args, kwargs, continuation_token): - if continuation_token: - return None - - inputs = kwargs.pop("inputs", None) - if not inputs: - try: - inputs = args[0] - except IndexError: - inputs = args - - if isinstance(inputs, StartTranslationDetails): - request = inputs - elif isinstance(inputs, (Mapping, IOBase, bytes)): - request = inputs - # backcompatibility - elif len(inputs) > 0 and isinstance(inputs[0], DocumentTranslationInput): - # pylint: disable=protected-access - request = StartTranslationDetails(inputs=[input._to_generated() for input in inputs]) - else: - try: - source_url = kwargs.pop("source_url", None) - if not source_url: - source_url = args[0] - target_url = kwargs.pop("target_url", None) - if not target_url: - target_url = args[1] - target_language = kwargs.pop("target_language", None) - if not target_language: - target_language = args[2] - - # Additional kwargs - source_language = kwargs.pop("source_language", None) - prefix = kwargs.pop("prefix", None) - suffix = kwargs.pop("suffix", None) - storage_type = kwargs.pop("storage_type", None) - category_id = kwargs.pop("category_id", None) - glossaries = kwargs.pop("glossaries", None) - - request = StartTranslationDetails( - inputs=[ - DocumentBatch( - source=SourceInput( - source_url=source_url, - filter=DocumentFilter(prefix=prefix, suffix=suffix), - language=source_language, - ), - targets=[ - TranslationTarget( - target_url=target_url, - language=target_language, - glossaries=glossaries, - category_id=category_id, - ) - ], - storage_type=storage_type, - ) - ] - ) - except (AttributeError, TypeError, IndexError) as exc: - raise ValueError( - "Pass 'inputs' for multiple inputs or 'source_url', 'target_url', " - "and 'target_language' for a single input." - ) from exc - - return request - - -def get_http_logging_policy(**kwargs): - http_logging_policy = HttpLoggingPolicy(**kwargs) - http_logging_policy.allowed_header_names.update( - { - "Operation-Location", - "Content-Encoding", - "Vary", - "apim-request-id", - "X-RequestId", - "Set-Cookie", - "X-Powered-By", - "Strict-Transport-Security", - "x-content-type-options", - } - ) - http_logging_policy.allowed_query_params.update( - { - "top", - "skip", - "maxpagesize", - "ids", - "statuses", - "createdDateTimeUtcStart", - "createdDateTimeUtcEnd", - "orderby", - } - ) - return http_logging_policy - - -class DocumentTranslationClient(GeneratedDocumentTranslationClient): - def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, TokenCredential], **kwargs: Any) -> 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: 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 :mod:`azure.identity`. - :type credential: :class:`~azure.core.credentials.AzureKeyCredential` or - :class:`~azure.core.credentials.TokenCredential` - :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.translation.document.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. - - .. literalinclude:: ../samples/sample_authentication.py - :start-after: [START create_dt_client_with_aad] - :end-before: [END create_dt_client_with_aad] - :language: python - :dedent: 4 - :caption: Creating the DocumentTranslationClient with a token credential. - """ - try: - self._endpoint = endpoint.rstrip("/") - except AttributeError as exc: - raise ValueError("Parameter 'endpoint' must be a string.") from exc - self._credential = credential - polling_interval = kwargs.pop("polling_interval", POLLING_INTERVAL) - super().__init__( - endpoint=self._endpoint, - credential=credential, - http_logging_policy=kwargs.pop("http_logging_policy", get_http_logging_policy()), - polling_interval=polling_interval, - **kwargs - ) - - def __enter__(self) -> "DocumentTranslationClient": - self._client.__enter__() # pylint:disable=no-member - return self - - def __exit__(self, *args) -> None: - self._client.__exit__(*args) # pylint:disable=no-member - - def close(self) -> None: - """Close the :class:`~azure.ai.translation.document.DocumentTranslationClient` session.""" - return self._client.close() - - @overload - def begin_translation( - self, - source_url: str, - target_url: str, - target_language: str, - *, - source_language: Optional[str] = None, - prefix: Optional[str] = None, - suffix: Optional[str] = None, - storage_type: Optional[Union[str, StorageInputType]] = None, - category_id: Optional[str] = None, - glossaries: Optional[List[TranslationGlossary]] = None, - **kwargs: Any - ) -> DocumentTranslationLROPoller[ItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param str source_url: The source SAS URL to the Azure Blob container containing the documents - to be translated. See the service documentation for the supported SAS permissions for accessing - source storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions - :param str target_url: The target SAS URL to the Azure Blob container where the translated documents - should be written. See the service documentation for the supported SAS permissions for accessing - target storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions - :param str target_language: This is the language code you want your documents to be translated to. - See supported language codes here: - https://docs.microsoft.com/azure/cognitive-services/translator/language-support#translate - :keyword str source_language: 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. - :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. - :keyword storage_type: Storage type of the input documents source string. Possible values - include: "Folder", "File". - :paramtype storage_type: str or ~azure.ai.translation.document.StorageInputType - :keyword str category_id: Category / custom model ID for using custom translation. - :keyword glossaries: Glossaries to apply to translation. - :paramtype glossaries: list[~azure.ai.translation.document.TranslationGlossary] - :return: 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. - :rtype: DocumentTranslationLROPoller[~azure.core.paging.ItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_translation( - self, inputs: StartTranslationDetails, **kwargs: Any - ) -> DocumentTranslationLROPoller[ItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param inputs: A StartTranslationDetails including 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: ~azure.ai.translation.document.models.StartTranslationDetails - :return: 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. - :rtype: DocumentTranslationLROPoller[~azure.core.paging.ItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_translation(self, inputs: JSON, **kwargs: Any) -> DocumentTranslationLROPoller[ItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param inputs: JSON including translation inputs. Each individual input has a single - source URL to documents and can contain multiple targets (one for each language) - for the destination to write translated documents. - :type inputs: JSON - :return: 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. - :rtype: DocumentTranslationLROPoller[~azure.core.paging.ItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "inputs": [ - { - "source": { - "sourceUrl": "str", - "filter": { - "prefix": "str", - "suffix": "str" - }, - "language": "str", - "storageSource": "str" - }, - "targets": [ - { - "language": "str", - "targetUrl": "str", - "category": "str", - "glossaries": [ - { - "format": "str", - "glossaryUrl": "str", - "storageSource": "str", - "version": "str" - } - ], - "storageSource": "str" - } - ], - "storageType": "str" - } - ] - } - """ - - @overload - def begin_translation( - self, inputs: IO[bytes], **kwargs: Any - ) -> DocumentTranslationLROPoller[ItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param inputs: The translation inputs. Each individual input has a single - source URL to documents and can contain multiple targets (one for each language) - for the destination to write translated documents. - :type inputs: IO[bytes] - :return: 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. - :rtype: DocumentTranslationLROPoller[~azure.core.paging.ItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_translation( - self, 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. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :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.translation.document.DocumentTranslationInput] - :return: 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. - :rtype: DocumentTranslationLROPoller[~azure.core.paging.ItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_translation( # pylint: disable=docstring-missing-param,docstring-should-be-keyword - self, *args: Union[str, List[DocumentTranslationInput], StartTranslationDetails, IO[bytes], JSON], **kwargs: Any - ) -> DocumentTranslationLROPoller[ItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param inputs: The translation inputs. Each individual input has a single - source URL to documents and can contain multiple targets (one for each language) - for the destination to write translated documents. - :type inputs: List[~azure.ai.translation.document.DocumentTranslationInput] or - IO[bytes] or JSON or ~azure.ai.translation.document.models.StartTranslationDetails - :param str source_url: The source SAS URL to the Azure Blob container containing the documents - to be translated. See the service documentation for the supported SAS permissions for accessing - source storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions - :param str target_url: The target SAS URL to the Azure Blob container where the translated documents - should be written. See the service documentation for the supported SAS permissions for accessing - target storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions - :param str target_language: This is the language code you want your documents to be translated to. - See supported language codes here: - https://docs.microsoft.com/azure/cognitive-services/translator/language-support#translate - :keyword str source_language: 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. - :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. - :keyword storage_type: Storage type of the input documents source string. Possible values - include: "Folder", "File". - :paramtype storage_type: str or ~azure.ai.translation.document.StorageInputType - :keyword str category_id: Category / custom model ID for using custom translation. - :keyword glossaries: Glossaries to apply to translation. - :paramtype glossaries: list[~azure.ai.translation.document.TranslationGlossary] - :return: 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. - :rtype: DocumentTranslationLROPoller[~azure.core.paging.ItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_begin_translation.py - :start-after: [START begin_translation] - :end-before: [END begin_translation] - :language: python - :dedent: 4 - :caption: Translate the documents in your storage container. - """ - - continuation_token = kwargs.pop("continuation_token", None) - - inputs = get_translation_input(args, kwargs, continuation_token) - - def deserialization_callback(raw_response, _, headers): # pylint: disable=unused-argument - translation_status = json.loads(raw_response.http_response.text()) - return self.list_document_statuses(translation_status["id"]) - - polling_interval = kwargs.pop( - "polling_interval", - self._config.polling_interval, # pylint: disable=protected-access - ) - - pipeline_response = None - if continuation_token: - pipeline_response = self.get_translation_status( - continuation_token, - cls=lambda pipeline_response, _, response_headers: pipeline_response, - ) - - callback = kwargs.pop("cls", deserialization_callback) - return cast( - DocumentTranslationLROPoller[ItemPaged[DocumentStatus]], - super()._begin_translation( - body=inputs, - polling=DocumentTranslationLROPollingMethod( - timeout=polling_interval, - lro_algorithms=[TranslationPolling()], - cont_token_response=pipeline_response, - **kwargs - ), - cls=callback, - continuation_token=continuation_token, - **kwargs - ), - ) - - # pylint: disable=arguments-renamed - @distributed_trace - def cancel_translation(self, translation_id: str, **kwargs: Any) -> None: # type: ignore[override] - """Cancel a currently processing or queued translation operation. - A translation will not be canceled if it is already completed, failed, or canceling. - All documents that have completed translation will not be canceled and will be charged. - If possible, all pending documents will be canceled. - :param str translation_id: The translation operation ID. - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError or ~azure.core.exceptions.ResourceNotFoundError: - """ - - super().cancel_translation(translation_id, **kwargs) - - @distributed_trace - def list_translation_statuses( - self, - *, - top: Optional[int] = None, - skip: Optional[int] = None, - translation_ids: Optional[List[str]] = None, - statuses: Optional[List[str]] = None, - created_after: Optional[Union[str, datetime.datetime]] = None, - created_before: Optional[Union[str, datetime.datetime]] = None, - order_by: Optional[List[str]] = None, - **kwargs: Any - ) -> ItemPaged[TranslationStatus]: - """List all the submitted translation operations under the Document Translation resource. - - :keyword int top: The total number of operations to return (across all pages) from all submitted translations. - :keyword int skip: The number of operations to skip (from beginning of all submitted operations). - By default, we sort by all submitted operations in descending order by start time. - :keyword list[str] translation_ids: Translation operations ids to filter by. - :keyword list[str] statuses: Translation operation statuses to filter by. Options include - 'NotStarted', 'Running', 'Succeeded', 'Failed', 'Canceled', 'Canceling', - and 'ValidationFailed'. - :keyword created_after: Get operations created after a certain datetime. - :paramtype created_after: str or ~datetime.datetime - :keyword created_before: Get operations created before a certain datetime. - :paramtype created_before: str or ~datetime.datetime - :keyword list[str] order_by: The sorting query for the operations returned. Currently only - 'created_on' supported. - format: ["param1 asc/desc", "param2 asc/desc", ...] - (ex: 'created_on asc', 'created_on desc'). - :return: A pageable of TranslationStatus. - :rtype: ~azure.core.paging.ItemPaged[TranslationStatus] - :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_list_translations.py - :start-after: [START list_translations] - :end-before: [END list_translations] - :language: python - :dedent: 4 - :caption: List all submitted translations under the resource. - """ - - if statuses: - statuses = [convert_status(status, ll=True) for status in statuses] - order_by = convert_order_by(order_by) - created_after = convert_datetime(created_after) if created_after else None - created_before = convert_datetime(created_before) if created_before else None - - return cast( - ItemPaged[TranslationStatus], - super().list_translation_statuses( - created_date_time_utc_start=created_after, - created_date_time_utc_end=created_before, - translation_ids=translation_ids, - orderby=order_by, - statuses=statuses, - top=top, - skip=skip, - **kwargs - ), - ) - - # pylint: disable=arguments-renamed - @distributed_trace - def list_document_statuses( # type: ignore[override] - self, - translation_id: str, - *, - top: Optional[int] = None, - skip: Optional[int] = None, - document_ids: Optional[List[str]] = None, - statuses: Optional[List[str]] = None, - created_after: Optional[Union[str, datetime.datetime]] = None, - created_before: Optional[Union[str, datetime.datetime]] = None, - order_by: Optional[List[str]] = None, - **kwargs: Any - ) -> ItemPaged[DocumentStatus]: - """List all the document statuses for a given translation operation. - - :param str translation_id: ID of translation operation to list documents for. - :keyword int top: The total number of documents to return (across all pages). - :keyword int skip: The number of documents to skip (from beginning). - By default, we sort by all documents in descending order by start time. - :keyword list[str] document_ids: Document IDs to filter by. - :keyword list[str] statuses: Document statuses to filter by. Options include - 'NotStarted', 'Running', 'Succeeded', 'Failed', 'Canceled', 'Canceling', - and 'ValidationFailed'. - :keyword created_after: Get documents created after a certain datetime. - :paramtype created_after: str or ~datetime.datetime - :keyword created_before: Get documents created before a certain datetime. - :paramtype created_before: str or ~datetime.datetime - :keyword list[str] order_by: The sorting query for the documents. Currently only - 'created_on' is supported. - format: ["param1 asc/desc", "param2 asc/desc", ...] - (ex: 'created_on asc', 'created_on desc'). - :return: A pageable of DocumentStatus. - :rtype: ~azure.core.paging.ItemPaged[DocumentStatus] - :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_check_document_statuses.py - :start-after: [START list_document_statuses] - :end-before: [END list_document_statuses] - :language: python - :dedent: 4 - :caption: List all the document statuses as they are being translated. - """ - - if statuses: - statuses = [convert_status(status, ll=True) for status in statuses] - order_by = convert_order_by(order_by) - created_after = convert_datetime(created_after) if created_after else None - created_before = convert_datetime(created_before) if created_before else None - - return cast( - ItemPaged[DocumentStatus], - super().list_document_statuses( - translation_id=translation_id, - created_date_time_utc_start=created_after, - created_date_time_utc_end=created_before, - document_ids=document_ids, - orderby=order_by, - statuses=statuses, - top=top, - skip=skip, - **kwargs - ), - ) - - @distributed_trace - def get_supported_glossary_formats(self, **kwargs: Any) -> List[DocumentTranslationFileFormat]: - """Get the list of the glossary formats supported by the Document Translation service. - - :return: A list of supported glossary formats. - :rtype: List[DocumentTranslationFileFormat] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - return super()._get_supported_formats(type="glossary", **kwargs).value - - @distributed_trace - def get_supported_document_formats(self, **kwargs: Any) -> List[DocumentTranslationFileFormat]: - """Get the list of the document formats supported by the Document Translation service. - - :return: A list of supported document formats for translation. - :rtype: List[DocumentTranslationFileFormat] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - return super()._get_supported_formats(type="document", **kwargs).value - - -__all__: List[str] = [ - "DocumentTranslationClient", - "DocumentTranslationApiVersion", - "DocumentTranslationLROPoller", - # re-export models at this level for backwards compatibility - "TranslationGlossary", - "TranslationTarget", - "DocumentTranslationInput", - "TranslationStatus", - "DocumentStatus", - "DocumentTranslationError", - "DocumentTranslationFileFormat", - "StorageInputType", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_validation.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_validation.py new file mode 100644 index 000000000000..752b2822f9d3 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_validation.py @@ -0,0 +1,50 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools + + +def api_version_validation(**kwargs): + params_added_on = kwargs.pop("params_added_on", {}) + method_added_on = kwargs.pop("method_added_on", "") + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + # this assumes the client has an _api_version attribute + client = args[0] + client_api_version = client._config.api_version # pylint: disable=protected-access + except AttributeError: + return func(*args, **kwargs) + + if method_added_on > client_api_version: + raise ValueError( + f"'{func.__name__}' is not available in API version " + f"{client_api_version}. Pass service API version {method_added_on} or newer to your client." + ) + + unsupported = { + parameter: api_version + for api_version, parameters in params_added_on.items() + for parameter in parameters + if parameter in kwargs and api_version > client_api_version + } + if unsupported: + raise ValueError( + "".join( + [ + f"'{param}' is not available in API version {client_api_version}. " + f"Use service API version {version} or newer.\n" + for param, version in unsupported.items() + ] + ) + ) + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_version.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_version.py index f6cd39818b76..a1f432eddc4e 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_version.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.1.0b2" +VERSION = "1.1.0b1" diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/__init__.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/__init__.py index ddf8855b2d9b..b358b68ef553 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/__init__.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/__init__.py @@ -5,19 +5,27 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._patch import DocumentTranslationClient -from ._client import SingleDocumentTranslationClient +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import -from ._patch import AsyncDocumentTranslationLROPoller +from ._client import DocumentTranslationClient # type: ignore +from ._client import SingleDocumentTranslationClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AsyncDocumentTranslationLROPoller", "DocumentTranslationClient", "SingleDocumentTranslationClient", ] - +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_client.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_client.py index d8e017fc4f57..16b4e46ee03e 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_client.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_client.py @@ -33,8 +33,9 @@ class DocumentTranslationClient(DocumentTranslationClientOperationsMixin): AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: 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. + :keyword api_version: The API version to use for this operation. Default value is + "2024-11-15-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. @@ -117,8 +118,9 @@ class SingleDocumentTranslationClient(SingleDocumentTranslationClientOperationsM AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: 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. + :keyword api_version: The API version to use for this operation. Default value is + "2024-11-15-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_configuration.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_configuration.py index f0876e7f2d08..7454f1ac683b 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_configuration.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_configuration.py @@ -30,15 +30,16 @@ class DocumentTranslationClientConfiguration: # pylint: disable=too-many-instan AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: 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. + :keyword api_version: The API version to use for this operation. Default value is + "2024-11-15-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ def __init__( self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: - api_version: str = kwargs.pop("api_version", "2024-05-01") + api_version: str = kwargs.pop("api_version", "2024-11-15-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -87,15 +88,16 @@ class SingleDocumentTranslationClientConfiguration: # pylint: disable=too-many- AzureKeyCredential type or a TokenCredential type. Required. :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: 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. + :keyword api_version: The API version to use for this operation. Default value is + "2024-11-15-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ def __init__( self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: - api_version: str = kwargs.pop("api_version", "2024-05-01") + api_version: str = kwargs.pop("api_version", "2024-11-15-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/__init__.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/__init__.py index 9e327bba3bf1..82a231e9e834 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/__init__.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/__init__.py @@ -5,16 +5,23 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._patch import DocumentTranslationClientOperationsMixin -from ._patch import SingleDocumentTranslationClientOperationsMixin +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import +from ._operations import DocumentTranslationClientOperationsMixin # type: ignore +from ._operations import SingleDocumentTranslationClientOperationsMixin # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "DocumentTranslationClientOperationsMixin", "SingleDocumentTranslationClientOperationsMixin", ] - +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/_operations.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/_operations.py index 6b8361f2d71a..83a6e953139c 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/_operations.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/_operations.py @@ -44,6 +44,7 @@ build_document_translation_list_translation_statuses_request, build_single_document_translation_translate_request, ) +from ..._validation import api_version_validation from ..._vendor import prepare_multipart_form_data from .._vendor import DocumentTranslationClientMixinABC, SingleDocumentTranslationClientMixinABC @@ -989,6 +990,7 @@ async def translate( source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, + translate_text_within_image: Optional[bool] = None, **kwargs: Any ) -> AsyncIterator[bytes]: """Submit a single document translation request to the Document Translation service. @@ -1019,6 +1021,9 @@ async def translate( when a custom system doesn't exist. Possible values are: true (default) or false. Default value is None. :paramtype allow_fallback: bool + :keyword translate_text_within_image: Optional boolean parameter to translate text within an + image in the document. Default value is None. + :paramtype translate_text_within_image: bool :return: AsyncIterator[bytes] :rtype: AsyncIterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: @@ -1033,6 +1038,7 @@ async def translate( source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, + translate_text_within_image: Optional[bool] = None, **kwargs: Any ) -> AsyncIterator[bytes]: """Submit a single document translation request to the Document Translation service. @@ -1063,12 +1069,18 @@ async def translate( when a custom system doesn't exist. Possible values are: true (default) or false. Default value is None. :paramtype allow_fallback: bool + :keyword translate_text_within_image: Optional boolean parameter to translate text within an + image in the document. Default value is None. + :paramtype translate_text_within_image: bool :return: AsyncIterator[bytes] :rtype: AsyncIterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async + @api_version_validation( + params_added_on={"2024-11-15-preview": ["translate_text_within_image"]}, + ) async def translate( self, body: Union[_models.DocumentTranslateContent, JSON], @@ -1077,6 +1089,7 @@ async def translate( source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, + translate_text_within_image: Optional[bool] = None, **kwargs: Any ) -> AsyncIterator[bytes]: """Submit a single document translation request to the Document Translation service. @@ -1108,6 +1121,9 @@ async def translate( when a custom system doesn't exist. Possible values are: true (default) or false. Default value is None. :paramtype allow_fallback: bool + :keyword translate_text_within_image: Optional boolean parameter to translate text within an + image in the document. Default value is None. + :paramtype translate_text_within_image: bool :return: AsyncIterator[bytes] :rtype: AsyncIterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: @@ -1135,6 +1151,7 @@ async def translate( source_language=source_language, category=category, allow_fallback=allow_fallback, + translate_text_within_image=translate_text_within_image, api_version=self._config.api_version, files=_files, data=_data, @@ -1163,6 +1180,13 @@ async def translate( raise HttpResponseError(response=response) response_headers = {} + response_headers["x-metered-usage"] = self._deserialize("int", response.headers.get("x-metered-usage")) + response_headers["x-metered-usage-image-scan-count-pass"] = self._deserialize( + "int", response.headers.get("x-metered-usage-image-scan-count-pass") + ) + response_headers["x-metered-usage-image-scan-count-fail"] = self._deserialize( + "int", response.headers.get("x-metered-usage-image-scan-count-fail") + ) response_headers["x-ms-client-request-id"] = self._deserialize( "str", response.headers.get("x-ms-client-request-id") ) diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/_patch.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/_patch.py index e39a31e52645..f7dd32510333 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/_patch.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_operations/_patch.py @@ -2,463 +2,13 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -# pylint: disable=protected-access """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import sys -from typing import AsyncIterator, Callable, Dict, Type, TypeVar, overload, Any, IO, List, Optional, Union, cast, Tuple -from azure.core.polling import AsyncNoPolling, AsyncPollingMethod -from azure.core.polling.async_base_polling import AsyncLROBasePolling -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.utils import case_insensitive_dict -from azure.core.polling import AsyncLROPoller -from azure.core.polling.base_polling import ( - OperationFailed, - _raise_if_bad_http_status_and_method, -) -from ..._vendor import prepare_multipart_form_data -from ... import _model_base, models as _models +from typing import List -from ..._model_base import _deserialize -from ...models import ( - TranslationStatus, -) -from ._operations import ( - DocumentTranslationClientOperationsMixin as GeneratedDocumentTranslationClientOperationsMixin, - SingleDocumentTranslationClientOperationsMixin as GeneratedSingleDocumentTranslationClientOperationsMixin, - build_single_document_translation_translate_request, - JSON, - ClsType, -) - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # type: ignore[misc] # pylint: disable=unsubscriptable-object -T = TypeVar("T") -ClsType = Optional[ # type: ignore[misc] - Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any] -] - -PollingReturnType_co = TypeVar("PollingReturnType_co", covariant=True) -_FINISHED = frozenset(["succeeded", "cancelled", "cancelling", "failed"]) -_FAILED = frozenset(["validationfailed"]) - - -class AsyncDocumentTranslationLROPoller(AsyncLROPoller[PollingReturnType_co]): - """An async custom poller implementation for Document Translation. Call `result()` on the poller to return - a pageable of :class:`~azure.ai.translation.document.DocumentStatus`.""" - - _polling_method: "AsyncDocumentTranslationLROPollingMethod" - - @property - def id(self) -> str: - """The ID for the translation operation - - :return: The str ID for the translation operation. - :rtype: str - """ - if self._polling_method._current_body: - return self._polling_method._current_body.id - return self._polling_method._get_id_from_headers() - - @property - def details(self) -> TranslationStatus: - """The details for the translation operation - - :return: The details for the translation operation. - :rtype: ~azure.ai.translation.document.TranslationStatus - """ - if self._polling_method._current_body: - return TranslationStatus(self._polling_method._current_body) - return TranslationStatus(id=self._polling_method._get_id_from_headers()) # type: ignore - - @classmethod - def from_continuation_token( # pylint: disable=docstring-missing-return,docstring-missing-param,docstring-missing-rtype - cls, polling_method, continuation_token, **kwargs - ): - """ - :meta private: - """ - ( - client, - initial_response, - deserialization_callback, - ) = polling_method.from_continuation_token(continuation_token, **kwargs) - - return cls(client, initial_response, deserialization_callback, polling_method) - - -class AsyncDocumentTranslationLROPollingMethod(AsyncLROBasePolling): - """A custom polling method implementation for Document Translation.""" - - def __init__(self, *args, **kwargs): - self._cont_token_response = kwargs.pop("cont_token_response") - super().__init__(*args, **kwargs) - - @property - def _current_body(self) -> TranslationStatus: - try: - return TranslationStatus(self._pipeline_response.http_response.json()) - except Exception: # pylint: disable=broad-exception-caught - return TranslationStatus() # type: ignore[call-overload] - - def _get_id_from_headers(self) -> str: - return ( - self._initial_response.http_response.headers["Operation-Location"] - .split("/batches/")[1] - .split("?api-version")[0] - ) - - def finished(self) -> bool: - """Is this polling finished? - - :return: True/False for whether polling is complete. - :rtype: bool - """ - return self._finished(self.status()) - - @staticmethod - def _finished(status) -> bool: - if hasattr(status, "value"): - status = status.value - return str(status).lower() in _FINISHED - - @staticmethod - def _failed(status) -> bool: - if hasattr(status, "value"): - status = status.value - return str(status).lower() in _FAILED - - def get_continuation_token(self) -> str: - if self._current_body: - return self._current_body.id - return self._get_id_from_headers() - - # pylint: disable=arguments-differ - def from_continuation_token(self, continuation_token: str, **kwargs: Any) -> Tuple: # type: ignore[override] - try: - client = kwargs["client"] - except KeyError as exc: - raise ValueError("Need kwarg 'client' to be recreated from continuation_token") from exc - - try: - deserialization_callback = kwargs["deserialization_callback"] - except KeyError as exc: - raise ValueError("Need kwarg 'deserialization_callback' to be recreated from continuation_token") from exc - - return client, self._cont_token_response, deserialization_callback - - async def _poll(self) -> None: - """Poll status of operation so long as operation is incomplete and - we have an endpoint to query. - - :raises: OperationFailed if operation status 'Failed' or 'Canceled'. - :raises: BadStatus if response status invalid. - :raises: BadResponse if response invalid. - """ - if not self.finished(): - await self.update_status() - while not self.finished(): - await self._delay() - await self.update_status() - - if self._failed(self.status()): - raise OperationFailed("Operation failed or canceled") - - final_get_url = self._operation.get_final_get_url(self._pipeline_response) - if final_get_url: - self._pipeline_response = await self.request_status(final_get_url) - _raise_if_bad_http_status_and_method(self._pipeline_response.http_response) - - -class DocumentTranslationClientOperationsMixin(GeneratedDocumentTranslationClientOperationsMixin): - - @distributed_trace - async def _begin_translation( # type: ignore[override] - self, body: Union[_models.StartTranslationDetails, JSON, IO[bytes]], **kwargs: Any - ) -> AsyncDocumentTranslationLROPoller[_models.TranslationStatus]: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.TranslationStatus] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self.__begin_translation_initial( # type: ignore[func-returns-value] - body=body, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.TranslationStatus, response.json()) - if cls: - return cls(pipeline_response, deserialized, response_headers) - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncDocumentTranslationLROPoller[_models.TranslationStatus].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncDocumentTranslationLROPoller[_models.TranslationStatus]( - self._client, raw_result, get_long_running_output, polling_method - ) - - -class SingleDocumentTranslationClientOperationsMixin( - GeneratedSingleDocumentTranslationClientOperationsMixin -): # pylint: disable=name-too-long - - @overload - async def translate( - self, - body: _models.DocumentTranslateContent, - *, - target_language: str, - source_language: Optional[str] = None, - category: Optional[str] = None, - allow_fallback: Optional[bool] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: - """Submit a single document translation request to the Document Translation service. - - Use this API to submit a single translation request to the Document Translation Service. - - :param body: Required. - :type body: ~azure.ai.translation.document.models.DocumentTranslateContent - :keyword target_language: 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. - :paramtype target_language: str - :keyword source_language: 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. - :paramtype source_language: str - :keyword category: 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. - :paramtype category: str - :keyword allow_fallback: 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. - :paramtype allow_fallback: bool - :return: AsyncIterator[bytes] - :rtype: AsyncIterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "document": filetype, - "glossary": [filetype] - } - """ - - @overload - async def translate( - self, - body: JSON, - *, - target_language: str, - source_language: Optional[str] = None, - category: Optional[str] = None, - allow_fallback: Optional[bool] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: - """Submit a single document translation request to the Document Translation service. - - Use this API to submit a single translation request to the Document Translation Service. - - :param body: Required. - :type body: JSON - :keyword target_language: 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. - :paramtype target_language: str - :keyword source_language: 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. - :paramtype source_language: str - :keyword category: 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. - :paramtype category: str - :keyword allow_fallback: 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. - :paramtype allow_fallback: bool - :return: AsyncIterator[bytes] - :rtype: AsyncIterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def translate( - self, - body: Union[_models.DocumentTranslateContent, JSON], - *, - target_language: str, - source_language: Optional[str] = None, - category: Optional[str] = None, - allow_fallback: Optional[bool] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: - """Submit a single document translation request to the Document Translation service. - - Use this API to submit a single translation request to the Document Translation Service. - - :param body: Is either a DocumentTranslateContent type or a JSON type. Required. - :type body: ~azure.ai.translation.document.models.DocumentTranslateContent or JSON - :keyword target_language: 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. - :paramtype target_language: str - :keyword source_language: 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. - :paramtype source_language: str - :keyword category: 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. - :paramtype category: str - :keyword allow_fallback: 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. - :paramtype allow_fallback: bool - :return: AsyncIterator[bytes] - :rtype: AsyncIterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "document": filetype, - "glossary": [filetype] - } - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _body = body.as_dict() if isinstance(body, _model_base.Model) else body - _file_fields: List[str] = ["document", "glossary"] - _data_fields: List[str] = [] - _files, _data = prepare_multipart_form_data(_body, _file_fields, _data_fields) - - _request = build_single_document_translation_translate_request( - target_language=target_language, - source_language=source_language, - category=category, - allow_fallback=allow_fallback, - api_version=self._config.api_version, - files=_files, - data=_data, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", True) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - - # deserialized = response.iter_bytes() - - if cls: - # return cls(pipeline_response, deserialized, response_headers) # type: ignore - return cls(pipeline_response, response.read(), response_headers) # type: ignore - - return await response.read() - - -__all__: List[str] = [ - "DocumentTranslationClientOperationsMixin", - "SingleDocumentTranslationClientOperationsMixin", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_patch.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_patch.py index 6648cc16d6bc..f7dd32510333 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_patch.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_patch.py @@ -2,543 +2,13 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -# mypy: disable-error-code="attr-defined" +"""Customize generated code here. -import json -import datetime -from typing import Any, List, Union, overload, Optional, cast, IO, MutableMapping +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.tracing.decorator import distributed_trace -from azure.core.async_paging import AsyncItemPaged -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential - -from ._operations._patch import AsyncDocumentTranslationLROPoller, AsyncDocumentTranslationLROPollingMethod -from .._operations._patch import TranslationPolling -from ._client import DocumentTranslationClient as GeneratedDocumentTranslationClient -from ..models import ( - DocumentStatus, - TranslationStatus, - StartTranslationDetails, - StorageInputType, - TranslationGlossary, - DocumentTranslationInput, - DocumentTranslationFileFormat, -) -from ...document._patch import ( - get_http_logging_policy, - get_translation_input, - convert_datetime, - convert_order_by, - convert_status, -) - -JSON = MutableMapping[str, Any] -POLLING_INTERVAL = 1 - - -class DocumentTranslationClient(GeneratedDocumentTranslationClient): - """DocumentTranslationClient. - - :param endpoint: Supported document Translation endpoint, protocol and hostname, for example: - https://{TranslatorResourceName}.cognitiveservices.azure.com/translator. Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. Is either a - AzureKeyCredential type or a TokenCredential type. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential or - ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: 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. - :paramtype api_version: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - """ - - def __init__( - self, - endpoint: str, - credential: Union[AzureKeyCredential, AsyncTokenCredential], # pylint: disable=used-before-assignment - **kwargs: Any - ) -> 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: 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 :mod:`azure.identity`. - :type credential: :class:`~azure.core.credentials.AzureKeyCredential` or - :class:`~azure.core.credentials.TokenCredential` - :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.translation.document.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. - - .. literalinclude:: ../samples/async_samples/sample_authentication_async.py - :start-after: [START create_dt_client_with_aad_async] - :end-before: [END create_dt_client_with_aad_async] - :language: python - :dedent: 4 - :caption: Creating the DocumentTranslationClient with a token credential. - """ - try: - self._endpoint = endpoint.rstrip("/") - except AttributeError as exc: - raise ValueError("Parameter 'endpoint' must be a string.") from exc - self._credential = credential - polling_interval = kwargs.pop("polling_interval", POLLING_INTERVAL) - - super().__init__( - endpoint=self._endpoint, - credential=credential, - http_logging_policy=kwargs.pop("http_logging_policy", get_http_logging_policy()), - polling_interval=polling_interval, - **kwargs - ) - - async def __aenter__(self) -> "DocumentTranslationClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *args: "Any") -> None: - await self._client.__aexit__(*args) - - async def close(self) -> None: - """Close the :class:`~azure.ai.translation.document.aio.DocumentTranslationClient` session.""" - await self._client.__aexit__() - - @overload - async def begin_translation( - self, - source_url: str, - target_url: str, - target_language: str, - *, - source_language: Optional[str] = None, - prefix: Optional[str] = None, - suffix: Optional[str] = None, - storage_type: Optional[Union[str, StorageInputType]] = None, - category_id: Optional[str] = None, - glossaries: Optional[List[TranslationGlossary]] = None, - **kwargs: Any - ) -> AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param str source_url: The source SAS URL to the Azure Blob container containing the documents - to be translated. See the service documentation for the supported SAS permissions for accessing - source storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions - :param str target_url: The target SAS URL to the Azure Blob container where the translated documents - should be written. See the service documentation for the supported SAS permissions for accessing - target storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions - :param str target_language: This is the language code you want your documents to be translated to. - See supported language codes here: - https://docs.microsoft.com/azure/cognitive-services/translator/language-support#translate - :keyword str source_language: 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. - :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. - :keyword storage_type: Storage type of the input documents source string. Possible values - include: "Folder", "File". - :paramtype storage_type: str or ~azure.ai.translation.document.StorageInputType - :keyword str category_id: Category / custom model ID for using custom translation. - :keyword glossaries: Glossaries to apply to translation. - :paramtype glossaries: list[~azure.ai.translation.document.TranslationGlossary] - :return: An instance of an AsyncDocumentTranslationLROPoller. Call `result()` on the poller - object to return a pageable of DocumentStatus. A DocumentStatus will be - returned for each translation on a document. - :rtype: AsyncDocumentTranslationLROPoller[~azure.core.async_paging.AsyncItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_translation( - self, inputs: StartTranslationDetails, **kwargs: Any - ) -> AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param inputs: A StartTranslationDetails including 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: ~azure.ai.translation.document.models.StartTranslationDetails - :return: An instance of a AsyncDocumentTranslationLROPoller. Call `result()` on the poller - object to return a pageable of DocumentStatus. A DocumentStatus will be - returned for each translation on a document. - :rtype: AsyncDocumentTranslationLROPoller[~azure.core.async_paging.AsyncItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_translation( - self, inputs: JSON, **kwargs: Any - ) -> AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param inputs: JSON including translation inputs. Each individual input has a single - source URL to documents and can contain multiple targets (one for each language) - for the destination to write translated documents. - :type inputs: JSON - :return: An instance of a AsyncDocumentTranslationLROPoller. Call `result()` on the poller - object to return a pageable of DocumentStatus. A DocumentStatus will be - returned for each translation on a document. - :rtype: AsyncDocumentTranslationLROPoller[~azure.core.async_paging.AsyncItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = { - "inputs": [ - { - "source": { - "sourceUrl": "str", - "filter": { - "prefix": "str", - "suffix": "str" - }, - "language": "str", - "storageSource": "str" - }, - "targets": [ - { - "language": "str", - "targetUrl": "str", - "category": "str", - "glossaries": [ - { - "format": "str", - "glossaryUrl": "str", - "storageSource": "str", - "version": "str" - } - ], - "storageSource": "str" - } - ], - "storageType": "str" - } - ] - } - """ - - @overload - async def begin_translation( - self, inputs: IO[bytes], **kwargs: Any - ) -> AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param inputs: The translation inputs. Each individual input has a single - source URL to documents and can contain multiple targets (one for each language) - for the destination to write translated documents. - :type inputs: IO[bytes] - :return: An instance of a AsyncDocumentTranslationLROPoller. Call `result()` on the poller - object to return a pageable of DocumentStatus. A DocumentStatus will be - returned for each translation on a document. - :rtype: AsyncDocumentTranslationLROPoller[~azure.core.async_paging.AsyncItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_translation( - self, inputs: List[DocumentTranslationInput], **kwargs: Any - ) -> AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :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.translation.document.DocumentTranslationInput] - :return: An instance of a AsyncDocumentTranslationLROPoller. Call `result()` on the poller - object to return a pageable of DocumentStatus. A DocumentStatus will be - returned for each translation on a document. - :rtype: AsyncDocumentTranslationLROPoller[~azure.core.async_paging.AsyncItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_translation( # pylint: disable=docstring-missing-param,docstring-should-be-keyword - self, *args: Union[str, List[DocumentTranslationInput], IO[bytes], JSON], **kwargs: Any - ) -> AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]]: - """Begin translating the document(s) in your source container to your target container - in the given language. - - For supported languages and document formats, see the service documentation: - https://docs.microsoft.com/azure/cognitive-services/translator/document-translation/overview - - :param inputs: The translation inputs. Each individual input has a single - source URL to documents and can contain multiple targets (one for each language) - for the destination to write translated documents. - :type inputs: List[~azure.ai.translation.document.DocumentTranslationInput] or - IO[bytes] or JSON or ~azure.ai.translation.document.models.StartTranslationDetails - :param str source_url: The source SAS URL to the Azure Blob container containing the documents - to be translated. See the service documentation for the supported SAS permissions for accessing - source storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions - :param str target_url: The target SAS URL to the Azure Blob container where the translated documents - should be written. See the service documentation for the supported SAS permissions for accessing - target storage containers/blobs: https://aka.ms/azsdk/documenttranslation/sas-permissions - :param str target_language: This is the language code you want your documents to be translated to. - See supported language codes here: - https://docs.microsoft.com/azure/cognitive-services/translator/language-support#translate - :keyword str source_language: 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. - :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. - :keyword storage_type: Storage type of the input documents source string. Possible values - include: "Folder", "File". - :paramtype storage_type: str or ~azure.ai.translation.document.StorageInputType - :keyword str category_id: Category / custom model ID for using custom translation. - :keyword glossaries: Glossaries to apply to translation. - :paramtype glossaries: list[~azure.ai.translation.document.TranslationGlossary] - :return: 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. - :rtype: AsyncDocumentTranslationLROPoller[~azure.core.async_paging.AsyncItemPaged[DocumentStatus]] - :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_begin_translation_async.py - :start-after: [START begin_translation_async] - :end-before: [END begin_translation_async] - :language: python - :dedent: 4 - :caption: Translate the documents in your storage container. - """ - - continuation_token = kwargs.pop("continuation_token", None) - - inputs = get_translation_input(args, kwargs, continuation_token) - - def deserialization_callback(raw_response, _, headers): # pylint: disable=unused-argument - translation_status = json.loads(raw_response.http_response.text()) - return self.list_document_statuses(translation_status["id"]) - - polling_interval = kwargs.pop( - "polling_interval", - self._config.polling_interval, # pylint: disable=protected-access - ) - - pipeline_response = None - if continuation_token: - pipeline_response = await self.get_translation_status( - continuation_token, - cls=lambda pipeline_response, _, response_headers: pipeline_response, - ) - - callback = kwargs.pop("cls", deserialization_callback) - return cast( - AsyncDocumentTranslationLROPoller[AsyncItemPaged[DocumentStatus]], - await super()._begin_translation( - body=inputs, - polling=AsyncDocumentTranslationLROPollingMethod( - timeout=polling_interval, - lro_algorithms=[TranslationPolling()], - cont_token_response=pipeline_response, - **kwargs - ), - cls=callback, - continuation_token=continuation_token, - **kwargs - ), - ) - - @distributed_trace - def list_translation_statuses( - self, - *, - top: Optional[int] = None, - skip: Optional[int] = None, - translation_ids: Optional[List[str]] = None, - statuses: Optional[List[str]] = None, - created_after: Optional[Union[str, datetime.datetime]] = None, - created_before: Optional[Union[str, datetime.datetime]] = None, - order_by: Optional[List[str]] = None, - **kwargs: Any - ) -> AsyncItemPaged[TranslationStatus]: - """List all the submitted translation operations under the Document Translation resource. - - :keyword int top: The total number of operations to return (across all pages) from all submitted translations. - :keyword int skip: The number of operations to skip (from beginning of all submitted operations). - By default, we sort by all submitted operations in descending order by start time. - :keyword list[str] translation_ids: Translation operations ids to filter by. - :keyword list[str] statuses: Translation operation statuses to filter by. Options include - 'NotStarted', 'Running', 'Succeeded', 'Failed', 'Canceled', 'Canceling', - and 'ValidationFailed'. - :keyword created_after: Get operations created after a certain datetime. - :paramtype created_after: str or ~datetime.datetime - :keyword created_before: Get operations created before a certain datetime. - :paramtype created_before: str or ~datetime.datetime - :keyword list[str] order_by: The sorting query for the operations returned. Currently only - 'created_on' supported. - format: ["param1 asc/desc", "param2 asc/desc", ...] - (ex: 'created_on asc', 'created_on desc'). - :return: A pageable of TranslationStatus. - :rtype: ~azure.core.async_paging.AsyncItemPaged[TranslationStatus] - :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_list_translations_async.py - :start-after: [START list_translations_async] - :end-before: [END list_translations_async] - :language: python - :dedent: 4 - :caption: List all submitted translations under the resource. - """ - - if statuses: - statuses = [convert_status(status, ll=True) for status in statuses] - order_by = convert_order_by(order_by) - created_after = convert_datetime(created_after) if created_after else None - created_before = convert_datetime(created_before) if created_before else None - - return cast( - AsyncItemPaged[TranslationStatus], - super().list_translation_statuses( - created_date_time_utc_start=created_after, - created_date_time_utc_end=created_before, - translation_ids=translation_ids, - orderby=order_by, - statuses=statuses, - top=top, - skip=skip, - **kwargs - ), - ) - - # pylint: disable=arguments-renamed - @distributed_trace - def list_document_statuses( # type: ignore[override] - self, - translation_id: str, - *, - top: Optional[int] = None, - skip: Optional[int] = None, - document_ids: Optional[List[str]] = None, - statuses: Optional[List[str]] = None, - created_after: Optional[Union[str, datetime.datetime]] = None, - created_before: Optional[Union[str, datetime.datetime]] = None, - order_by: Optional[List[str]] = None, - **kwargs: Any - ) -> AsyncItemPaged[DocumentStatus]: - """List all the document statuses for a given translation operation. - - :param str translation_id: ID of translation operation to list documents for. - :keyword int top: The total number of documents to return (across all pages). - :keyword int skip: The number of documents to skip (from beginning). - By default, we sort by all documents in descending order by start time. - :keyword list[str] document_ids: Document IDs to filter by. - :keyword list[str] statuses: Document statuses to filter by. Options include - 'NotStarted', 'Running', 'Succeeded', 'Failed', 'Canceled', 'Canceling', - and 'ValidationFailed'. - :keyword created_after: Get documents created after a certain datetime. - :paramtype created_after: str or ~datetime.datetime - :keyword created_before: Get documents created before a certain datetime. - :paramtype created_before: str or ~datetime.datetime - :keyword list[str] order_by: The sorting query for the documents. Currently only - 'created_on' is supported. - format: ["param1 asc/desc", "param2 asc/desc", ...] - (ex: 'created_on asc', 'created_on desc'). - :return: A pageable of DocumentStatus. - :rtype: ~azure.core.async_paging.AsyncItemPaged[DocumentStatus] - :raises ~azure.core.exceptions.HttpResponseError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_check_document_statuses_async.py - :start-after: [START list_document_statuses_async] - :end-before: [END list_document_statuses_async] - :language: python - :dedent: 4 - :caption: List all the document statuses as they are being translated. - """ - - if statuses: - statuses = [convert_status(status, ll=True) for status in statuses] - order_by = convert_order_by(order_by) - created_after = convert_datetime(created_after) if created_after else None - created_before = convert_datetime(created_before) if created_before else None - - return cast( - AsyncItemPaged[DocumentStatus], - super().list_document_statuses( - translation_id=translation_id, - created_date_time_utc_start=created_after, - created_date_time_utc_end=created_before, - document_ids=document_ids, - orderby=order_by, - statuses=statuses, - top=top, - skip=skip, - **kwargs - ), - ) - - @distributed_trace_async - async def get_supported_glossary_formats(self, **kwargs: Any) -> List[DocumentTranslationFileFormat]: - """Get the list of the glossary formats supported by the Document Translation service. - - :return: A list of supported glossary formats. - :rtype: List[DocumentTranslationFileFormat] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - return (await super()._get_supported_formats(type="glossary", **kwargs)).value - - @distributed_trace_async - async def get_supported_document_formats(self, **kwargs: Any) -> List[DocumentTranslationFileFormat]: - """Get the list of the document formats supported by the Document Translation service. - - :return: A list of supported document formats for translation. - :rtype: List[DocumentTranslationFileFormat] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - return (await super()._get_supported_formats(type="document", **kwargs)).value - - -__all__: List[str] = [ - "DocumentTranslationClient", - "AsyncDocumentTranslationLROPoller", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/__init__.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/__init__.py index d14cd0756fdf..88fc8b6f56a0 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/__init__.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/__init__.py @@ -5,50 +5,64 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._models import DocumentBatch -from ._models import DocumentFilter -from ._patch import DocumentStatus -from ._models import DocumentTranslateContent -from ._models import DocumentTranslationFileFormat -from ._patch import TranslationGlossary -from ._models import InnerTranslationError -from ._models import SourceInput -from ._models import StartTranslationDetails -from ._models import TranslationStatusSummary -from ._patch import TranslationTarget -from ._models import DocumentTranslationError -from ._patch import TranslationStatus -from ._patch import DocumentTranslationInput +from typing import TYPE_CHECKING -from ._enums import FileFormatType -from ._enums import Status -from ._enums import StorageInputType -from ._enums import TranslationStorageSource -from ._enums import TranslationErrorCode +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._models import ( # type: ignore + BatchOptions, + DocumentBatch, + DocumentFilter, + DocumentStatus, + DocumentTranslateContent, + DocumentTranslationError, + DocumentTranslationFileFormat, + InnerTranslationError, + SourceInput, + StartTranslationDetails, + TranslationErrorResponse, + TranslationGlossary, + TranslationStatus, + TranslationStatusSummary, + TranslationTarget, +) + +from ._enums import ( # type: ignore + FileFormatType, + Status, + StorageInputType, + TranslationErrorCode, + TranslationStorageSource, +) +from ._patch import __all__ as _patch_all +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ + "BatchOptions", "DocumentBatch", "DocumentFilter", "DocumentStatus", "DocumentTranslateContent", + "DocumentTranslationError", "DocumentTranslationFileFormat", - "TranslationGlossary", "InnerTranslationError", "SourceInput", "StartTranslationDetails", + "TranslationErrorResponse", + "TranslationGlossary", + "TranslationStatus", "TranslationStatusSummary", "TranslationTarget", - "DocumentTranslationError", - "TranslationStatus", "FileFormatType", "Status", "StorageInputType", - "TranslationStorageSource", "TranslationErrorCode", - "DocumentTranslationInput", + "TranslationStorageSource", ] - +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/_models.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/_models.py index ab006704ffce..f1b5b67b9a04 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/_models.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/_models.py @@ -18,6 +18,34 @@ from .. import models as _models +class BatchOptions(_model_base.Model): + """Translation batch request options. + + :ivar translate_text_within_image: Translation text within an image option. + :vartype translate_text_within_image: bool + """ + + translate_text_within_image: Optional[bool] = rest_field(name="translateTextWithinImage") + """Translation text within an image option.""" + + @overload + def __init__( + self, + *, + translate_text_within_image: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class DocumentBatch(_model_base.Model): """Definition for the input batch translation request. @@ -129,6 +157,10 @@ class DocumentStatus(_model_base.Model): :vartype id: str :ivar characters_charged: Character charged by the API. :vartype characters_charged: int + :ivar total_image_scans_charged: Total image scans charged by the API. + :vartype total_image_scans_charged: int + :ivar total_image_scans_failed: Total image scans failed. + :vartype total_image_scans_failed: int """ translated_document_url: Optional[str] = rest_field(name="path") @@ -154,6 +186,10 @@ class DocumentStatus(_model_base.Model): """Document Id. Required.""" characters_charged: Optional[int] = rest_field(name="characterCharged") """Character charged by the API.""" + total_image_scans_charged: Optional[int] = rest_field(name="totalImageScansCharged") + """Total image scans charged by the API.""" + total_image_scans_failed: Optional[int] = rest_field(name="totalImageScansFailed") + """Total image scans failed.""" @overload def __init__( @@ -169,6 +205,8 @@ def __init__( translated_document_url: Optional[str] = None, error: Optional["_models.DocumentTranslationError"] = None, characters_charged: Optional[int] = None, + total_image_scans_charged: Optional[int] = None, + total_image_scans_failed: Optional[int] = None, ) -> None: ... @overload @@ -236,7 +274,7 @@ class DocumentTranslationError(_model_base.Model): :vartype target: str :ivar inner_error: New Inner Error format which conforms to Cognitive Services API Guidelines which is available at - https://microsoft.sharepoint.com/%3Aw%3A/t/CognitiveServicesPMO/EUoytcrjuJdKpeOKIK_QRC8BPtUYQpKBi8JsWyeDMRsWlQ?e=CPq8ow. + https://microsoft.sharepoint.com/%3Aw%3A/t/CognitiveServicesPMO/EUoytcrjuJdKpeOKIK_QRC8BPtUYQpKBi8JsWyeDMRsWlQ?e=CPq8ow. This contains required properties ErrorCode, message and optional properties target, details(key value pair), inner error(this can be nested). @@ -356,7 +394,7 @@ class InnerTranslationError(_model_base.Model): :vartype target: str :ivar inner_error: New Inner Error format which conforms to Cognitive Services API Guidelines which is available at - https://microsoft.sharepoint.com/%3Aw%3A/t/CognitiveServicesPMO/EUoytcrjuJdKpeOKIK_QRC8BPtUYQpKBi8JsWyeDMRsWlQ?e=CPq8ow. + https://microsoft.sharepoint.com/%3Aw%3A/t/CognitiveServicesPMO/EUoytcrjuJdKpeOKIK_QRC8BPtUYQpKBi8JsWyeDMRsWlQ?e=CPq8ow. This contains required properties ErrorCode, message and optional properties target, details(key value pair), inner error(this can be nested). @@ -454,16 +492,21 @@ class StartTranslationDetails(_model_base.Model): :ivar inputs: The input list of documents or folders containing documents. Required. :vartype inputs: list[~azure.ai.translation.document.models.DocumentBatch] + :ivar options: The batch operation options. + :vartype options: ~azure.ai.translation.document.models.BatchOptions """ inputs: List["_models.DocumentBatch"] = rest_field() """The input list of documents or folders containing documents. Required.""" + options: Optional["_models.BatchOptions"] = rest_field() + """The batch operation options.""" @overload def __init__( self, *, inputs: List["_models.DocumentBatch"], + options: Optional["_models.BatchOptions"] = None, ) -> None: ... @overload @@ -657,6 +700,8 @@ class TranslationStatusSummary(_model_base.Model): :vartype canceled: int :ivar total_characters_charged: Total characters charged by the API. Required. :vartype total_characters_charged: int + :ivar total_image_scans_charged: Total image scans charged by the API. + :vartype total_image_scans_charged: int """ total: int = rest_field() @@ -673,6 +718,8 @@ class TranslationStatusSummary(_model_base.Model): """Number of cancelled. Required.""" total_characters_charged: int = rest_field(name="totalCharacterCharged") """Total characters charged by the API. Required.""" + total_image_scans_charged: Optional[int] = rest_field(name="totalImageScansCharged") + """Total image scans charged by the API.""" @overload def __init__( @@ -685,6 +732,7 @@ def __init__( not_yet_started: int, canceled: int, total_characters_charged: int, + total_image_scans_charged: Optional[int] = None, ) -> None: ... @overload diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/_patch.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/_patch.py index 8f44b574aca5..f7dd32510333 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/_patch.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/models/_patch.py @@ -6,452 +6,9 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import List -from typing import Any, List, Mapping, Optional, Union, overload, TYPE_CHECKING -import datetime -from ._models import ( - DocumentStatus as GeneratedDocumentStatus, - TranslationStatus as GeneratedTranslationStatus, - TranslationGlossary as GeneratedTranslationGlossary, - TranslationTarget as GeneratedTranslationTarget, - DocumentBatch, - SourceInput, - DocumentFilter, -) -from ._enums import StorageInputType - - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from .. import models as _models - - -def convert_status(status, ll=False): - if ll is False: - if status.lower() == "cancelled": - return "Canceled" - if status.lower() == "cancelling": - return "Canceling" - elif ll is True: - if status.lower() == "canceled": - return "Cancelled" - if status.lower() == "canceling": - return "Cancelling" - return status - - -class DocumentTranslationInput: - """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. - - :param str source_url: Required. 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). - :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.translation.document.TranslationTarget] - :keyword Optional[str] source_language: Language code for the source documents. - If none is specified, the source language will be auto-detected for each document. - :keyword Optional[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. - :keyword Optional[str] suffix: A case-sensitive suffix string to filter documents in the source path for - 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". - :paramtype storage_type: Optional[str or ~azure.ai.translation.document.StorageInputType] - :keyword Optional[str] storage_source: Storage Source. Default value: "AzureBlob". - Currently only "AzureBlob" is supported. - """ - - 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).""" - 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.""" - source_language: Optional[str] = None - """Language code for the source documents. - If none is specified, the source language will be auto-detected for each document.""" - storage_type: Optional[Union[str, StorageInputType]] = None - """Storage type of the input documents source string. Possible values - include: "Folder", "File".""" - storage_source: Optional[str] = None - """Storage Source. Default value: "AzureBlob". - Currently only "AzureBlob" is supported.""" - prefix: Optional[str] = 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.""" - suffix: Optional[str] = None - """A case-sensitive suffix string to filter documents in the source path for - translation. This is most often use for file extensions.""" - - def __init__( - self, - source_url: str, - targets: List["TranslationTarget"], - *, - source_language: Optional[str] = None, - storage_type: Optional[Union[str, StorageInputType]] = None, - storage_source: Optional[str] = None, - prefix: Optional[str] = None, - suffix: Optional[str] = None, - ) -> None: - self.source_url = source_url - self.targets = targets - self.source_language = source_language - self.storage_type = storage_type - self.storage_source = storage_source - self.prefix = prefix - self.suffix = suffix - - def _to_generated(self): - return DocumentBatch( - source=SourceInput( - source_url=self.source_url, - filter=DocumentFilter(prefix=self.prefix, suffix=self.suffix), - language=self.source_language, - storage_source=self.storage_source, - ), - targets=self.targets, - storage_type=self.storage_type, - ) - - def __repr__(self) -> str: - return ( - "DocumentTranslationInput(source_url={}, targets={}, " - "source_language={}, storage_type={}, " - "storage_source={}, prefix={}, suffix={})".format( - self.source_url, - repr(self.targets), - self.source_language, - repr(self.storage_type), - self.storage_source, - self.prefix, - self.suffix, - )[:1024] - ) - - -class TranslationTarget(GeneratedTranslationTarget): - """Destination for the finished translated documents. - - All required parameters must be populated in order to send to server. - - :ivar target_url: Location of the folder / container with your documents. Required. - :vartype target_url: str - :ivar category_id: Category / custom system for translation request. - :vartype category_id: str - :ivar language: Target Language. Required. - :vartype language: str - :ivar glossaries: List of Glossary. - :vartype glossaries: list[~azure.ai.translation.document.models.TranslationGlossary] - :ivar storage_source: Storage Source. "AzureBlob" - :vartype storage_source: str or ~azure.ai.translation.document.models.TranslationStorageSource - """ - - target_url: str - """Location of the folder / container with your documents. Required.""" - category_id: Optional[str] - """Category / custom system for translation request.""" - language: str - """Target Language. Required.""" - glossaries: Optional[List["TranslationGlossary"]] - """List of Glossary.""" - storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] - """Storage Source. \"AzureBlob\"""" - - @overload - def __init__( - self, - target_url: str, - language: str, - *, - category_id: Optional[str] = None, - glossaries: Optional[List["TranslationGlossary"]] = None, - storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] = None, - ): ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - target = kwargs.get("mapping") - if not target and len(args) == 2: - kwargs["target_url"] = args[0] - kwargs["language"] = args[1] - - super().__init__(*args, **kwargs) - - -class TranslationGlossary(GeneratedTranslationGlossary): - """Glossary / translation memory for the request. - - All required parameters must be populated in order to send to server. - - :ivar glossary_url: 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. Required. - :vartype glossary_url: str - :ivar file_format: Format. Required. - :vartype file_format: str - :ivar format_version: Optional Version. If not specified, default is used. - :vartype format_version: str - :ivar storage_source: Storage Source. "AzureBlob" - :vartype storage_source: str or ~azure.ai.translation.document.models.TranslationStorageSource - """ - - glossary_url: str - """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. Required.""" - file_format: str - """Format. Required.""" - format_version: Optional[str] - """Optional Version. If not specified, default is used.""" - storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] - """Storage Source. \"AzureBlob\"""" - - @overload - def __init__( - self, - glossary_url: str, - file_format: str, - *, - format_version: Optional[str] = None, - storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] = None, - ): ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - glossary = kwargs.get("mapping") - if not glossary and len(args) == 2: - kwargs["glossary_url"] = args[0] - kwargs["file_format"] = args[1] - - super().__init__(*args, **kwargs) - - -class DocumentStatus(GeneratedDocumentStatus): - """Document Status Response. - - :ivar translated_document_url: Location of the document or folder. - :vartype translated_document_url: str - :ivar source_document_url: Location of the source document. Required. - :vartype source_document_url: str - :ivar created_on: Operation created date time. Required. - :vartype created_on: ~datetime.datetime - :ivar last_updated_on: Date time in which the operation's status has been updated. Required. - :vartype last_updated_on: ~datetime.datetime - :ivar status: List of possible statuses for job or document. Required. Known values are: - "NotStarted", "Running", "Succeeded", "Failed", "Cancelled", "Cancelling", and - "ValidationFailed". - :vartype status: str or ~azure.ai.translation.document.models.Status - :ivar translated_to: To language. Required. - :vartype translated_to: str - :ivar error: This contains an outer error with error code, message, details, target and an - inner error with more descriptive details. - :vartype error: ~azure.ai.translation.document.models.DocumentTranslationError - :ivar translation_progress: Progress of the translation if available. Required. - :vartype translation_progress: float - :ivar id: Document Id. Required. - :vartype id: str - :ivar characters_charged: Character charged by the API. - :vartype characters_charged: int - """ - - translated_document_url: Optional[str] - """Location of the document or folder.""" - source_document_url: str - """Location of the source document. Required.""" - created_on: datetime.datetime - """Operation created date time. Required.""" - last_updated_on: datetime.datetime - """Date time in which the operation's status has been updated. Required.""" - status: Union[str, "_models.Status"] - """List of possible statuses for job or document. Required. Known values are: \"NotStarted\", - \"Running\", \"Succeeded\", \"Failed\", \"Cancelled\", \"Cancelling\", and - \"ValidationFailed\".""" - translated_to: str - """To language. Required.""" - error: Optional["_models.DocumentTranslationError"] - """This contains an outer error with error code, message, details, target and an - inner error with more descriptive details.""" - translation_progress: float - """Progress of the translation if available. Required.""" - id: str - """Document Id. Required.""" - characters_charged: Optional[int] - """Character charged by the API.""" - - @overload - def __init__( - self, - *, - source_document_url: str, - created_on: datetime.datetime, - last_updated_on: datetime.datetime, - status: Union[str, "_models.Status"], - translated_to: str, - translation_progress: float, - id: str, # pylint: disable=redefined-builtin - translated_document_url: Optional[str] = None, - error: Optional["_models.DocumentTranslationError"] = None, - characters_charged: Optional[int] = None, - ): ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - status = kwargs.get("mapping") - if not status and args: - status = args[0] - else: - status = kwargs - - if status.get("status"): - status["status"] = convert_status(status["status"]) - if status.get("error"): - status["error"]["code"] = status["error"].get("innerError", {}).get("code") - super().__init__(*args, **kwargs) - - -class TranslationStatus(GeneratedTranslationStatus): - """Translation job status response. - - :ivar id: Id of the operation. Required. - :vartype id: str - :ivar created_on: Operation created date time. Required. - :vartype created_on: ~datetime.datetime - :ivar last_updated_on: Date time in which the operation's status has been updated. Required. - :vartype last_updated_on: ~datetime.datetime - :ivar status: List of possible statuses for job or document. Required. Known values are: - "NotStarted", "Running", "Succeeded", "Failed", "Cancelled", "Cancelling", and - "ValidationFailed". - :vartype status: str or ~azure.ai.translation.document.models.Status - :ivar error: This contains an outer error with error code, message, details, target and an - inner error with more descriptive details. - :vartype error: ~azure.ai.translation.document.models.DocumentTranslationError - :ivar summary: Status Summary. Required. - :vartype summary: ~azure.ai.translation.document.models.TranslationStatusSummary - """ - - id: str - """Id of the operation. Required.""" - created_on: datetime.datetime - """Operation created date time. Required.""" - last_updated_on: datetime.datetime - """Date time in which the operation's status has been updated. Required.""" - status: Union[str, "_models.Status"] - """List of possible statuses for job or document. Required. Known values are: \"NotStarted\", - \"Running\", \"Succeeded\", \"Failed\", \"Cancelled\", \"Cancelling\", and - \"ValidationFailed\".""" - error: Optional["_models.DocumentTranslationError"] - """This contains an outer error with error code, message, details, target and an - inner error with more descriptive details.""" - summary: "_models.TranslationStatusSummary" - """Status Summary. Required.""" - - # pylint: disable=too-many-return-statements,inconsistent-return-statements - def __getattr__(self, name: str) -> Any: - backcompat_attrs = [ - "documents_total_count", - "documents_failed_count", - "documents_in_progress_count", - "documents_succeeded_count", - "documents_not_started_count", - "documents_canceled_count", - "total_characters_charged", - ] - if name in backcompat_attrs: - try: - if name == "documents_succeeded_count": - return self.summary["success"] - if name == "documents_failed_count": - return self.summary["failed"] - if name == "documents_total_count": - return self.summary["total"] - if name == "documents_in_progress_count": - return self.summary["inProgress"] - if name == "documents_not_started_count": - return self.summary["notYetStarted"] - if name == "documents_canceled_count": - return self.summary["cancelled"] - if name == "total_characters_charged": - return self.summary["totalCharacterCharged"] - except KeyError: - return None - raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - created_on: datetime.datetime, - last_updated_on: datetime.datetime, - status: Union[str, "_models.Status"], - summary: "_models.TranslationStatusSummary", - error: Optional["_models.DocumentTranslationError"] = None, - ): ... - - @overload - def __init__(self, mapping: Mapping[str, Any]): - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - status = kwargs.get("mapping") - if not status and args: - status = args[0] - else: - status = kwargs - - if status.get("status"): - status["status"] = convert_status(status["status"]) - if status.get("error"): - status["error"]["code"] = status["error"].get("innerError", {}).get("code") - super().__init__(*args, **kwargs) - - -__all__: List[str] = [ - "DocumentStatus", - "TranslationStatus", - "DocumentTranslationInput", - "TranslationTarget", - "TranslationGlossary", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/translation/azure-ai-translation-document/tsp-location.yaml b/sdk/translation/azure-ai-translation-document/tsp-location.yaml index b2debc44a67a..262e6ee26ac8 100644 --- a/sdk/translation/azure-ai-translation-document/tsp-location.yaml +++ b/sdk/translation/azure-ai-translation-document/tsp-location.yaml @@ -1,3 +1,4 @@ -commit: 17a3ee0a2a03dbfbf1359a1370f994862e02925d -repo: Azure/azure-rest-api-specs directory: specification/translation/Azure.AI.DocumentTranslation +commit: 4c6a2da5b444995bfdce5caec88633e0c2c70475 +repo: Azure/azure-rest-api-specs +additionalDirectories: