diff --git a/sdk/translation/azure-ai-translation-document/MANIFEST.in b/sdk/translation/azure-ai-translation-document/MANIFEST.in index 094e4c15616f..c2a75e806cf7 100644 --- a/sdk/translation/azure-ai-translation-document/MANIFEST.in +++ b/sdk/translation/azure-ai-translation-document/MANIFEST.in @@ -6,4 +6,3 @@ recursive-include samples *.py *.md include azure/__init__.py include azure/ai/__init__.py include azure/ai/translation/__init__.py -recursive-include doc *.rst 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..07653b8d8bd4 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "147495e1b6cfe5607d481278e31857dc929b42fa", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/translation/Azure.AI.DocumentTranslation", + "@azure-tools/typespec-python": "0.44.2" +} \ No newline at end of file diff --git a/sdk/translation/azure-ai-translation-document/apiview-properties.json b/sdk/translation/azure-ai-translation-document/apiview-properties.json new file mode 100644 index 000000000000..7da6792c36c5 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/apiview-properties.json @@ -0,0 +1,38 @@ +{ + "CrossLanguagePackageId": "DocumentTranslation", + "CrossLanguageDefinitionId": { + "azure.ai.translation.document.models.BatchOptions": "DocumentTranslation.BatchOptions", + "azure.ai.translation.document.models.DocumentBatch": "DocumentTranslation.BatchRequest", + "azure.ai.translation.document.models.DocumentFilter": "DocumentTranslation.DocumentFilter", + "azure.ai.translation.document.models.DocumentStatus": "DocumentTranslation.DocumentStatus", + "azure.ai.translation.document.models.DocumentTranslateContent": "DocumentTranslation.DocumentTranslateContent", + "azure.ai.translation.document.models.DocumentTranslationError": "DocumentTranslation.TranslationError", + "azure.ai.translation.document.models.DocumentTranslationFileFormat": "DocumentTranslation.FileFormat", + "azure.ai.translation.document.models.InnerTranslationError": "DocumentTranslation.InnerTranslationError", + "azure.ai.translation.document.models.SourceInput": "DocumentTranslation.SourceInput", + "azure.ai.translation.document.models.StartTranslationDetails": "DocumentTranslation.StartTranslationDetails", + "azure.ai.translation.document.models.TranslationGlossary": "DocumentTranslation.Glossary", + "azure.ai.translation.document.models.TranslationStatus": "DocumentTranslation.TranslationStatus", + "azure.ai.translation.document.models.TranslationStatusSummary": "DocumentTranslation.StatusSummary", + "azure.ai.translation.document.models.TranslationTarget": "DocumentTranslation.TargetInput", + "azure.ai.translation.document.models.Status": "DocumentTranslation.Status", + "azure.ai.translation.document.models.TranslationErrorCode": "DocumentTranslation.TranslationErrorCode", + "azure.ai.translation.document.models.TranslationStorageSource": "DocumentTranslation.StorageSource", + "azure.ai.translation.document.models.StorageInputType": "DocumentTranslation.StorageInputType", + "azure.ai.translation.document.models.FileFormatType": "DocumentTranslation.FileFormatType", + "azure.ai.translation.document.DocumentTranslationClient.begin_translation": "ClientCustomizations.DocumentTranslationClient.startTranslation", + "azure.ai.translation.document.aio.DocumentTranslationClient.begin_translation": "ClientCustomizations.DocumentTranslationClient.startTranslation", + "azure.ai.translation.document.DocumentTranslationClient.list_translation_statuses": "ClientCustomizations.DocumentTranslationClient.getTranslationsStatus", + "azure.ai.translation.document.aio.DocumentTranslationClient.list_translation_statuses": "ClientCustomizations.DocumentTranslationClient.getTranslationsStatus", + "azure.ai.translation.document.DocumentTranslationClient.get_document_status": "ClientCustomizations.DocumentTranslationClient.getDocumentStatus", + "azure.ai.translation.document.aio.DocumentTranslationClient.get_document_status": "ClientCustomizations.DocumentTranslationClient.getDocumentStatus", + "azure.ai.translation.document.DocumentTranslationClient.get_translation_status": "ClientCustomizations.DocumentTranslationClient.getTranslationStatus", + "azure.ai.translation.document.aio.DocumentTranslationClient.get_translation_status": "ClientCustomizations.DocumentTranslationClient.getTranslationStatus", + "azure.ai.translation.document.DocumentTranslationClient.cancel_translation": "ClientCustomizations.DocumentTranslationClient.cancelTranslation", + "azure.ai.translation.document.aio.DocumentTranslationClient.cancel_translation": "ClientCustomizations.DocumentTranslationClient.cancelTranslation", + "azure.ai.translation.document.DocumentTranslationClient.list_document_statuses": "ClientCustomizations.DocumentTranslationClient.getDocumentsStatus", + "azure.ai.translation.document.aio.DocumentTranslationClient.list_document_statuses": "ClientCustomizations.DocumentTranslationClient.getDocumentsStatus", + "azure.ai.translation.document.SingleDocumentTranslationClient.translate": "ClientCustomizations.SingleDocumentTranslationClient.documentTranslate", + "azure.ai.translation.document.aio.SingleDocumentTranslationClient.translate": "ClientCustomizations.SingleDocumentTranslationClient.documentTranslate" + } +} \ 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..31435a1fd2c7 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 @@ -17,7 +17,7 @@ from ._configuration import DocumentTranslationClientConfiguration, SingleDocumentTranslationClientConfiguration from ._operations import DocumentTranslationClientOperationsMixin, SingleDocumentTranslationClientOperationsMixin -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer if TYPE_CHECKING: from azure.core.credentials import TokenCredential @@ -29,12 +29,13 @@ class DocumentTranslationClient(DocumentTranslationClientOperationsMixin): :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. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential 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-01-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. @@ -43,6 +44,7 @@ class DocumentTranslationClient(DocumentTranslationClientOperationsMixin): def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any) -> None: _endpoint = "{endpoint}/translator" self._config = DocumentTranslationClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -109,18 +111,20 @@ class SingleDocumentTranslationClient(SingleDocumentTranslationClientOperationsM :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. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential 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-01-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: _endpoint = "{endpoint}/translator" self._config = SingleDocumentTranslationClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ 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..0183047e941f 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 @@ -26,17 +26,18 @@ class DocumentTranslationClientConfiguration: # pylint: disable=too-many-instan :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. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential 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-01-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-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -81,17 +82,18 @@ class SingleDocumentTranslationClientConfiguration: # pylint: disable=too-many- :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. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential 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-01-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-01-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..9cb6bea8c5b2 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 @@ -6,13 +6,14 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping import datetime from io import IOBase import json -import sys from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -31,20 +32,14 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import _model_base, models as _models -from .._model_base import SdkJSONEncoder, _deserialize -from .._serialization import Serializer -from .._vendor import ( - DocumentTranslationClientMixinABC, - SingleDocumentTranslationClientMixinABC, - prepare_multipart_form_data, -) +from .. import models as _models +from .._configuration import DocumentTranslationClientConfiguration, SingleDocumentTranslationClientConfiguration +from .._utils.model_base import Model as _Model, SdkJSONEncoder, _deserialize +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC, prepare_multipart_form_data +from .._validation import api_version_validation -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -52,14 +47,12 @@ _SERIALIZER.client_side_validation = False -def build_document_translation__begin_translation_request( # pylint: disable=name-too-long - **kwargs: Any, -) -> HttpRequest: +def build_document_translation_begin_translation_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _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-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -86,12 +79,12 @@ def build_document_translation_list_translation_statuses_request( # pylint: dis created_date_time_utc_start: Optional[datetime.datetime] = None, created_date_time_utc_end: Optional[datetime.datetime] = None, orderby: Optional[List[str]] = None, - **kwargs: Any, + **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-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -132,7 +125,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-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -159,7 +152,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-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -185,7 +178,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-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -216,12 +209,12 @@ def build_document_translation_list_document_statuses_request( # pylint: disabl created_date_time_utc_start: Optional[datetime.datetime] = None, created_date_time_utc_end: Optional[datetime.datetime] = None, orderby: Optional[List[str]] = None, - **kwargs: Any, + **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-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -267,7 +260,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-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -290,12 +283,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, - **kwargs: Any, + 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-01-preview")) accept = _headers.pop("Accept", "application/octet-stream") # Construct URL @@ -310,6 +304,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") @@ -317,9 +315,11 @@ def build_single_document_translation_translate_request( # pylint: disable=name return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -class DocumentTranslationClientOperationsMixin(DocumentTranslationClientMixinABC): +class DocumentTranslationClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], DocumentTranslationClientConfiguration] +): - def __begin_translation_initial( + def _begin_translation_initial( self, body: Union[_models.StartTranslationDetails, JSON, IO[bytes]], **kwargs: Any ) -> Iterator[bytes]: error_map: MutableMapping = { @@ -343,7 +343,7 @@ def __begin_translation_initial( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_document_translation__begin_translation_request( + _request = build_document_translation_begin_translation_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -381,7 +381,7 @@ def __begin_translation_initial( return deserialized # type: ignore @overload - def _begin_translation( + def begin_translation( self, body: _models.StartTranslationDetails, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.TranslationStatus]: """Submit a document translation request to the Document Translation service. @@ -418,7 +418,7 @@ def _begin_translation( """ @overload - def _begin_translation( + def begin_translation( self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.TranslationStatus]: """Submit a document translation request to the Document Translation service. @@ -455,7 +455,7 @@ def _begin_translation( """ @overload - def _begin_translation( + def begin_translation( self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.TranslationStatus]: """Submit a document translation request to the Document Translation service. @@ -492,7 +492,7 @@ def _begin_translation( """ @distributed_trace - def _begin_translation( + def begin_translation( self, body: Union[_models.StartTranslationDetails, JSON, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.TranslationStatus]: """Submit a document translation request to the Document Translation service. @@ -534,7 +534,7 @@ def _begin_translation( 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( + raw_result = self._begin_translation_initial( body=body, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) raw_result.http_response.read() # type: ignore @@ -586,7 +586,7 @@ def list_translation_statuses( created_date_time_utc_start: Optional[datetime.datetime] = None, created_date_time_utc_end: Optional[datetime.datetime] = None, orderby: Optional[List[str]] = None, - **kwargs: Any, + **kwargs: Any ) -> Iterable["_models.TranslationStatus"]: """Returns a list of batch requests submitted and the status for each request. @@ -615,6 +615,7 @@ def list_translation_statuses( requested via top (or top is not specified and there are more items to be returned), @nextLink will contain the link to the next page. + orderby query parameter can be used to sort the returned list (ex "orderby=createdDateTimeUtc asc" or "orderby=createdDateTimeUtc desc"). @@ -633,6 +634,7 @@ def list_translation_statuses( the values specified by the client. However, clients must be prepared to handle responses that contain a different page size or contain a continuation token. + When both top and skip are included, the server should first apply skip and then top on the collection. Note: If the server can't honor top @@ -746,7 +748,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.TranslationStatus], deserialized["value"]) + list_of_elem = _deserialize(List[_models.TranslationStatus], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -980,12 +982,13 @@ def list_document_statuses( created_date_time_utc_start: Optional[datetime.datetime] = None, created_date_time_utc_end: Optional[datetime.datetime] = None, orderby: Optional[List[str]] = None, - **kwargs: Any, + **kwargs: Any ) -> Iterable["_models.DocumentStatus"]: """Returns the status for all documents in a batch document translation request. Returns the status for all documents in a batch document translation request. + If the number of documents in the response exceeds our paging limit, server-side paging is used. Paginated responses indicate a partial result and @@ -1006,6 +1009,7 @@ def list_document_statuses( If more items are requested via top (or top is not specified and there are more items to be returned), @nextLink will contain the link to the next page. + orderby query parameter can be used to sort the returned list (ex "orderby=createdDateTimeUtc asc" or "orderby=createdDateTimeUtc desc"). @@ -1137,7 +1141,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DocumentStatus], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DocumentStatus], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -1231,7 +1235,7 @@ def _get_supported_formats( class SingleDocumentTranslationClientOperationsMixin( # pylint: disable=name-too-long - SingleDocumentTranslationClientMixinABC + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], SingleDocumentTranslationClientConfiguration] ): @overload @@ -1243,7 +1247,8 @@ def translate( source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, - **kwargs: Any, + translate_text_within_image: Optional[bool] = None, + **kwargs: Any ) -> Iterator[bytes]: """Submit a single document translation request to the Document Translation service. @@ -1273,6 +1278,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,7 +1295,8 @@ def translate( source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, - **kwargs: Any, + translate_text_within_image: Optional[bool] = None, + **kwargs: Any ) -> Iterator[bytes]: """Submit a single document translation request to the Document Translation service. @@ -1317,12 +1326,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-01-preview": ["translate_text_within_image"]}, + ) def translate( self, body: Union[_models.DocumentTranslateContent, JSON], @@ -1331,7 +1346,8 @@ def translate( source_language: Optional[str] = None, category: Optional[str] = None, allow_fallback: Optional[bool] = None, - **kwargs: Any, + translate_text_within_image: Optional[bool] = None, + **kwargs: Any ) -> Iterator[bytes]: """Submit a single document translation request to the Document Translation service. @@ -1362,6 +1378,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: @@ -1379,7 +1398,7 @@ def translate( cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _body = body.as_dict() if isinstance(body, _model_base.Model) else body + _body = body.as_dict() if isinstance(body, _Model) else body _file_fields: List[str] = ["document", "glossary"] _data_fields: List[str] = [] _files, _data = prepare_multipart_form_data(_body, _file_fields, _data_fields) @@ -1389,6 +1408,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 +1437,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["total-image-scans-succeeded"] = self._deserialize( + "int", response.headers.get("total-image-scans-succeeded") + ) + response_headers["total-image-scans-failed"] = self._deserialize( + "int", response.headers.get("total-image-scans-failed") + ) 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 0c597a6d71d5..8bcb627aa475 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 @@ -1,552 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """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 -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 - """ - # pylint: disable=protected-access - 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 - """ - # pylint: disable=protected-access - 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 # pylint: disable=possibly-used-before-assignment - ) - - -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 00f24ba7de30..8bcb627aa475 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 @@ -1,668 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# mypy: disable-error-code="attr-defined" - -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 - -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__() - return self - - def __exit__(self, *args) -> None: - self._client.__exit__(*args) - - 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,docstring-keyword-should-match-keyword-only - 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, - ) - - 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 - ), - ) - - @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 - ), - ) - - @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 +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__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/_utils/__init__.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_model_base.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/model_base.py similarity index 92% rename from sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_model_base.py rename to sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/model_base.py index e6a2730f9276..49d5c7259389 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_model_base.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/model_base.py @@ -2,8 +2,9 @@ # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# 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. # -------------------------------------------------------------------------- # pylint: disable=protected-access, broad-except @@ -21,6 +22,7 @@ from datetime import datetime, date, time, timedelta, timezone from json import JSONEncoder import xml.etree.ElementTree as ET +from collections.abc import MutableMapping from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError @@ -28,11 +30,6 @@ from azure.core.pipeline import PipelineResponse from azure.core.serialization import _Null -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping - _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -347,7 +344,7 @@ def _get_model(module_name: str, model_name: str): _UNSET = object() -class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object +class _MyMutableMapping(MutableMapping[str, typing.Any]): def __init__(self, data: typing.Dict[str, typing.Any]) -> None: self._data = data @@ -373,50 +370,97 @@ def __ne__(self, other: typing.Any) -> bool: return not self.__eq__(other) def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ return self._data.items() def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ try: return self[key] except KeyError: return default @typing.overload - def pop(self, key: str) -> typing.Any: ... + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ @typing.overload - def pop(self, key: str, default: _T) -> _T: ... + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs @typing.overload - def pop(self, key: str, default: typing.Any) -> typing.Any: ... + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ if default is _UNSET: return self._data.pop(key) return self._data.pop(key, default) def popitem(self) -> typing.Tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ return self._data.popitem() def clear(self) -> None: + """ + Remove all items from D. + """ self._data.clear() - def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ self._data.update(*args, **kwargs) @typing.overload def setdefault(self, key: str, default: None = None) -> None: ... @typing.overload - def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ if default is _UNSET: return self._data.setdefault(key) return self._data.setdefault(key, default) @@ -597,7 +641,7 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items()) cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") - return super().__new__(cls) # pylint: disable=no-value-for-parameter + return super().__new__(cls) def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: for base in cls.__bases__: @@ -633,7 +677,7 @@ def _deserialize(cls, data, exist_discriminators): discriminator_value = data.find(xml_name).text # pyright: ignore else: discriminator_value = data.get(discriminator._rest_name) - mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member return mapped_cls._deserialize(data, exist_discriminators) def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]: @@ -754,7 +798,7 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur except AttributeError: model_name = annotation if module is not None: - annotation = _get_model(module, model_name) + annotation = _get_model(module, model_name) # type: ignore try: if module and _is_model(annotation): @@ -894,6 +938,35 @@ def _deserialize( return _deserialize_with_callable(deserializer, value) +def _failsafe_deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, value, module, rf, format) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + value: typing.Any, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, value) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + class _RestField: def __init__( self, diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_serialization.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/serialization.py similarity index 93% rename from sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_serialization.py rename to sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/serialization.py index ce17d1798ce7..eb86ea23c965 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_serialization.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/serialization.py @@ -1,28 +1,10 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# 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. # -------------------------------------------------------------------------- # pyright: reportUnnecessaryTypeIgnoreComment=false @@ -48,9 +30,7 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, List, ) @@ -61,13 +41,13 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -ModelType = TypeVar("ModelType", bound="Model") JSON = MutableMapping[str, Any] @@ -185,73 +165,7 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], except NameError: _long_type = int - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0. - - :param datetime.datetime dt: The datetime - :returns: The offset - :rtype: datetime.timedelta - """ - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation. - - :param datetime.datetime dt: The datetime - :returns: The timestamp representation - :rtype: str - """ - return "Z" - - def dst(self, dt): - """No daylight saving for UTC. - - :param datetime.datetime dt: The datetime - :returns: The daylight saving time - :rtype: datetime.timedelta - """ - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset) -> None: - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? ModelType: + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong - :rtype: ModelType + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( - cls: Type[ModelType], + cls, data: Any, key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, - ) -> ModelType: + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -479,8 +393,8 @@ def from_dict( :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong - :rtype: ModelType + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -563,7 +477,7 @@ def _decode_attribute_map_key(key): return key.replace("\\.", ".") -class Serializer(object): # pylint: disable=too-many-public-methods +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -626,7 +540,7 @@ def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, to :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict - :raises: SerializationError if serialization fails. + :raises SerializationError: if serialization fails. :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) @@ -736,8 +650,8 @@ def body(self, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None :returns: The serialized request body """ @@ -781,8 +695,8 @@ def url(self, name, data, data_type, **kwargs): :param str data_type: The type to be serialized from. :rtype: str :returns: The serialized URL path - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -805,8 +719,8 @@ def query(self, name, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, list - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None :returns: The serialized query parameter """ try: @@ -835,8 +749,8 @@ def header(self, name, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None :returns: The serialized header """ try: @@ -855,9 +769,9 @@ def serialize_data(self, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. :returns: The serialized data. :rtype: str, int, float, bool, dict, list """ @@ -1192,7 +1106,7 @@ def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. :return: serialized rfc """ try: @@ -1218,7 +1132,7 @@ def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. :return: serialized iso """ if isinstance(attr, str): @@ -1251,7 +1165,7 @@ def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument :param Datetime attr: Object to be serialized. :rtype: int - :raises: SerializationError if format invalid + :raises SerializationError: if format invalid :return: serialied unix """ if isinstance(attr, int): @@ -1429,7 +1343,7 @@ def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument # Iter and wrapped, should have found one node only (the wrap one) if len(children) != 1: raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( # pylint: disable=line-too-long + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( xml_name ) ) @@ -1441,7 +1355,7 @@ def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1488,7 +1402,7 @@ def __call__(self, target_obj, response_data, content_type=None): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. :rtype: object """ @@ -1502,7 +1416,7 @@ def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. :rtype: object """ @@ -1683,17 +1597,21 @@ def _instantiate_model(self, response, attrs, additional_properties=None): subtype = getattr(response, "_subtype_map", {}) try: readonly = [ - k for k, v in response._validation.items() if v.get("readonly") # pylint: disable=protected-access + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") ] const = [ - k for k, v in response._validation.items() if v.get("constant") # pylint: disable=protected-access + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") ] kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: setattr(response_obj, attr, attrs.get(attr)) if additional_properties: - response_obj.additional_properties = additional_properties + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore @@ -1713,7 +1631,7 @@ def deserialize_data(self, data, data_type): # pylint: disable=too-many-return- :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. :rtype: object """ @@ -1795,7 +1713,7 @@ def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return :param dict attr: Dictionary to be deserialized. :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :raises TypeError: if non-builtin datatype encountered. """ if attr is None: return None @@ -1841,7 +1759,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1932,7 +1850,7 @@ def deserialize_bytearray(attr): :param str attr: response string to be deserialized. :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1945,7 +1863,7 @@ def deserialize_base64(attr): :param str attr: response string to be deserialized. :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1960,7 +1878,7 @@ def deserialize_decimal(attr): :param str attr: response string to be deserialized. :return: Deserialized decimal - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. :rtype: decimal """ if isinstance(attr, ET.Element): @@ -1978,7 +1896,7 @@ def deserialize_long(attr): :param str attr: response string to be deserialized. :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1991,7 +1909,7 @@ def deserialize_duration(attr): :param str attr: response string to be deserialized. :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -2009,7 +1927,7 @@ def deserialize_date(attr): :param str attr: response string to be deserialized. :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -2025,7 +1943,7 @@ def deserialize_time(attr): :param str attr: response string to be deserialized. :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -2040,14 +1958,14 @@ def deserialize_rfc(attr): :param str attr: response string to be deserialized. :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) @@ -2063,7 +1981,7 @@ def deserialize_iso(attr): :param str attr: response string to be deserialized. :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -2101,7 +2019,7 @@ def deserialize_unix(attr): :param int attr: Object to be serialized. :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore diff --git a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_vendor.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/utils.py similarity index 72% rename from sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_vendor.py rename to sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/utils.py index 37e545b1c5a4..89abe90d9245 100644 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_vendor.py +++ b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/_utils/utils.py @@ -7,31 +7,23 @@ from abc import ABC import json -from typing import Any, Dict, IO, List, Mapping, Optional, TYPE_CHECKING, Tuple, Union +from typing import Any, Dict, Generic, IO, List, Mapping, Optional, TYPE_CHECKING, Tuple, TypeVar, Union -from ._configuration import DocumentTranslationClientConfiguration, SingleDocumentTranslationClientConfiguration -from ._model_base import Model, SdkJSONEncoder +from .._utils.model_base import Model, SdkJSONEncoder if TYPE_CHECKING: - from azure.core import PipelineClient + from .serialization import Deserializer, Serializer - from ._serialization import Deserializer, Serializer - -class DocumentTranslationClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "PipelineClient" - _config: DocumentTranslationClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") -class SingleDocumentTranslationClientMixinABC(ABC): +class ClientMixinABC(ABC, Generic[TClient, TConfig]): """DO NOT use this class. It is for internal typing use only.""" - _client: "PipelineClient" - _config: SingleDocumentTranslationClientConfiguration + _client: TClient + _config: TConfig _serialize: "Serializer" _deserialize: "Deserializer" 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 3dcc33575aad..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.1" +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..de163afe1a25 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 @@ -15,7 +15,7 @@ from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import DocumentTranslationClientConfiguration, SingleDocumentTranslationClientConfiguration from ._operations import DocumentTranslationClientOperationsMixin, SingleDocumentTranslationClientOperationsMixin @@ -29,12 +29,13 @@ class DocumentTranslationClient(DocumentTranslationClientOperationsMixin): :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. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential 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-01-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. @@ -45,6 +46,7 @@ def __init__( ) -> None: _endpoint = "{endpoint}/translator" self._config = DocumentTranslationClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -113,12 +115,13 @@ class SingleDocumentTranslationClient(SingleDocumentTranslationClientOperationsM :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. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential 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-01-preview". Note that overriding this default value may result in unsupported + behavior. :paramtype api_version: str """ @@ -127,6 +130,7 @@ def __init__( ) -> None: _endpoint = "{endpoint}/translator" self._config = SingleDocumentTranslationClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ 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..e7c9ce12428f 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 @@ -26,19 +26,20 @@ class DocumentTranslationClientConfiguration: # pylint: disable=too-many-instan :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. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential 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-01-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-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -83,19 +84,20 @@ class SingleDocumentTranslationClientConfiguration: # pylint: disable=too-many- :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. + :param credential: Credential used to authenticate requests to the service. Is either a key + credential type or a token credential 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-01-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-01-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..96840d0450da 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 @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,13 +6,14 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping import datetime from io import IOBase import json -import sys from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -32,10 +33,9 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import _model_base, models as _models -from ..._model_base import SdkJSONEncoder, _deserialize +from ... import models as _models from ..._operations._operations import ( - build_document_translation__begin_translation_request, + build_document_translation_begin_translation_request, build_document_translation_cancel_translation_request, build_document_translation_get_document_status_request, build_document_translation_get_supported_formats_request, @@ -44,21 +44,21 @@ build_document_translation_list_translation_statuses_request, build_single_document_translation_translate_request, ) -from ..._vendor import prepare_multipart_form_data -from .._vendor import DocumentTranslationClientMixinABC, SingleDocumentTranslationClientMixinABC - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +from ..._utils.model_base import Model as _Model, SdkJSONEncoder, _deserialize +from ..._utils.utils import ClientMixinABC, prepare_multipart_form_data +from ..._validation import api_version_validation +from .._configuration import DocumentTranslationClientConfiguration, SingleDocumentTranslationClientConfiguration + +JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DocumentTranslationClientOperationsMixin(DocumentTranslationClientMixinABC): +class DocumentTranslationClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], DocumentTranslationClientConfiguration] +): - async def __begin_translation_initial( + async def _begin_translation_initial( self, body: Union[_models.StartTranslationDetails, JSON, IO[bytes]], **kwargs: Any ) -> AsyncIterator[bytes]: error_map: MutableMapping = { @@ -82,7 +82,7 @@ async def __begin_translation_initial( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_document_translation__begin_translation_request( + _request = build_document_translation_begin_translation_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -120,7 +120,7 @@ async def __begin_translation_initial( return deserialized # type: ignore @overload - async def _begin_translation( + async def begin_translation( self, body: _models.StartTranslationDetails, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.TranslationStatus]: """Submit a document translation request to the Document Translation service. @@ -158,7 +158,7 @@ async def _begin_translation( """ @overload - async def _begin_translation( + async def begin_translation( self, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.TranslationStatus]: """Submit a document translation request to the Document Translation service. @@ -196,7 +196,7 @@ async def _begin_translation( """ @overload - async def _begin_translation( + async def begin_translation( self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.TranslationStatus]: """Submit a document translation request to the Document Translation service. @@ -234,7 +234,7 @@ async def _begin_translation( """ @distributed_trace_async - async def _begin_translation( + async def begin_translation( self, body: Union[_models.StartTranslationDetails, JSON, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.TranslationStatus]: """Submit a document translation request to the Document Translation service. @@ -277,7 +277,7 @@ async def _begin_translation( 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( + raw_result = await self._begin_translation_initial( body=body, content_type=content_type, cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) await raw_result.http_response.read() # type: ignore @@ -359,6 +359,7 @@ def list_translation_statuses( requested via top (or top is not specified and there are more items to be returned), @nextLink will contain the link to the next page. + orderby query parameter can be used to sort the returned list (ex "orderby=createdDateTimeUtc asc" or "orderby=createdDateTimeUtc desc"). @@ -377,6 +378,7 @@ def list_translation_statuses( the values specified by the client. However, clients must be prepared to handle responses that contain a different page size or contain a continuation token. + When both top and skip are included, the server should first apply skip and then top on the collection. Note: If the server can't honor top @@ -491,7 +493,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.TranslationStatus], deserialized["value"]) + list_of_elem = _deserialize(List[_models.TranslationStatus], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -731,6 +733,7 @@ def list_document_statuses( Returns the status for all documents in a batch document translation request. + If the number of documents in the response exceeds our paging limit, server-side paging is used. Paginated responses indicate a partial result and @@ -751,6 +754,7 @@ def list_document_statuses( If more items are requested via top (or top is not specified and there are more items to be returned), @nextLink will contain the link to the next page. + orderby query parameter can be used to sort the returned list (ex "orderby=createdDateTimeUtc asc" or "orderby=createdDateTimeUtc desc"). @@ -883,7 +887,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DocumentStatus], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DocumentStatus], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -977,7 +981,7 @@ async def _get_supported_formats( class SingleDocumentTranslationClientOperationsMixin( # pylint: disable=name-too-long - SingleDocumentTranslationClientMixinABC + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], SingleDocumentTranslationClientConfiguration] ): @overload @@ -989,6 +993,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 +1024,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 +1041,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 +1072,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-01-preview": ["translate_text_within_image"]}, + ) async def translate( self, body: Union[_models.DocumentTranslateContent, JSON], @@ -1077,6 +1092,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 +1124,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: @@ -1125,7 +1144,7 @@ async def translate( cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _body = body.as_dict() if isinstance(body, _model_base.Model) else body + _body = body.as_dict() if isinstance(body, _Model) else body _file_fields: List[str] = ["document", "glossary"] _data_fields: List[str] = [] _files, _data = prepare_multipart_form_data(_body, _file_fields, _data_fields) @@ -1135,6 +1154,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 +1183,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["total-image-scans-succeeded"] = self._deserialize( + "int", response.headers.get("total-image-scans-succeeded") + ) + response_headers["total-image-scans-failed"] = self._deserialize( + "int", response.headers.get("total-image-scans-failed") + ) 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 1961b4fee008..8bcb627aa475 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 @@ -1,464 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint: disable=protected-access +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """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 -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 # pylint: disable=possibly-used-before-assignment - ) - - -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 e4d7ef70cc73..8bcb627aa475 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 @@ -1,543 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# mypy: disable-error-code="attr-defined" - -import json -import datetime -from typing import Any, List, Union, overload, Optional, cast, IO, MutableMapping - -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], - **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,docstring-keyword-should-match-keyword-only - 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, - ) - - 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 - ), - ) - - @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 +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__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/_vendor.py b/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_vendor.py deleted file mode 100644 index d8c06c99fb96..000000000000 --- a/sdk/translation/azure-ai-translation-document/azure/ai/translation/document/aio/_vendor.py +++ /dev/null @@ -1,34 +0,0 @@ -# -------------------------------------------------------------------------- -# 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. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import TYPE_CHECKING - -from ._configuration import DocumentTranslationClientConfiguration, SingleDocumentTranslationClientConfiguration - -if TYPE_CHECKING: - from azure.core import AsyncPipelineClient - - from .._serialization import Deserializer, Serializer - - -class DocumentTranslationClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "AsyncPipelineClient" - _config: DocumentTranslationClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" - - -class SingleDocumentTranslationClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "AsyncPipelineClient" - _config: SingleDocumentTranslationClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" 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..c70008c02424 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,62 @@ # 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, + 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", + "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..5e46b61b3027 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 @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -10,18 +11,45 @@ import datetime from typing import Any, List, Mapping, Optional, TYPE_CHECKING, Union, overload -from .. import _model_base -from .._model_base import rest_field -from .._vendor import FileType +from .._utils.model_base import Model as _Model, rest_field +from .._utils.utils import FileType if TYPE_CHECKING: from .. import models as _models -class DocumentBatch(_model_base.Model): - """Definition for the input batch translation request. +class BatchOptions(_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", visibility=["read", "create", "update", "delete", "query"] + ) + """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) + - All required parameters must be populated in order to send to server. +class DocumentBatch(_Model): + """Definition for the input batch translation request. :ivar source: Source of the input documents. Required. :vartype source: ~azure.ai.translation.document.models.SourceInput @@ -32,11 +60,13 @@ class DocumentBatch(_model_base.Model): :vartype storage_type: str or ~azure.ai.translation.document.models.StorageInputType """ - source: "_models.SourceInput" = rest_field() + source: "_models.SourceInput" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Source of the input documents. Required.""" - targets: List["_models.TranslationTarget"] = rest_field() + targets: List["_models.TranslationTarget"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Location of the destination for the output. Required.""" - storage_type: Optional[Union[str, "_models.StorageInputType"]] = rest_field(name="storageType") + storage_type: Optional[Union[str, "_models.StorageInputType"]] = rest_field( + name="storageType", visibility=["read", "create", "update", "delete", "query"] + ) """Storage type of the input documents source string. Known values are: \"Folder\" and \"File\".""" @overload @@ -59,7 +89,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DocumentFilter(_model_base.Model): +class DocumentFilter(_Model): """Document filter. :ivar prefix: A case-sensitive prefix string to filter documents in the source path for @@ -73,12 +103,12 @@ class DocumentFilter(_model_base.Model): :vartype suffix: str """ - prefix: Optional[str] = rest_field() + prefix: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """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] = rest_field() + suffix: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A case-sensitive suffix string to filter documents in the source path for translation. This is most often use for file extensions.""" @@ -102,10 +132,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DocumentStatus(_model_base.Model): +class DocumentStatus(_Model): """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. @@ -129,31 +158,55 @@ class DocumentStatus(_model_base.Model): :vartype id: str :ivar characters_charged: Character charged by the API. :vartype characters_charged: int + :ivar total_image_scans_succeeded: Total image scans charged by the API. + :vartype total_image_scans_succeeded: 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") + translated_document_url: Optional[str] = rest_field( + name="path", visibility=["read", "create", "update", "delete", "query"] + ) """Location of the document or folder.""" - source_document_url: str = rest_field(name="sourcePath") + source_document_url: str = rest_field(name="sourcePath", visibility=["read", "create", "update", "delete", "query"]) """Location of the source document. Required.""" - created_on: datetime.datetime = rest_field(name="createdDateTimeUtc", format="rfc3339") + created_on: datetime.datetime = rest_field( + name="createdDateTimeUtc", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Operation created date time. Required.""" - last_updated_on: datetime.datetime = rest_field(name="lastActionDateTimeUtc", format="rfc3339") + last_updated_on: datetime.datetime = rest_field( + name="lastActionDateTimeUtc", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Date time in which the operation's status has been updated. Required.""" - status: Union[str, "_models.Status"] = rest_field() + status: Union[str, "_models.Status"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """List of possible statuses for job or document. Required. Known values are: \"NotStarted\", \"Running\", \"Succeeded\", \"Failed\", \"Cancelled\", \"Cancelling\", and \"ValidationFailed\".""" - translated_to: str = rest_field(name="to") + translated_to: str = rest_field(name="to", visibility=["read", "create", "update", "delete", "query"]) """To language. Required.""" - error: Optional["_models.DocumentTranslationError"] = rest_field() + error: Optional["_models.DocumentTranslationError"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """This contains an outer error with error code, message, details, target and an inner error with more descriptive details.""" - translation_progress: float = rest_field(name="progress") + translation_progress: float = rest_field( + name="progress", visibility=["read", "create", "update", "delete", "query"] + ) """Progress of the translation if available. Required.""" - id: str = rest_field() + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Document Id. Required.""" - characters_charged: Optional[int] = rest_field(name="characterCharged") + characters_charged: Optional[int] = rest_field( + name="characterCharged", visibility=["read", "create", "update", "delete", "query"] + ) """Character charged by the API.""" + total_image_scans_succeeded: Optional[int] = rest_field( + name="totalImageScansSucceeded", visibility=["read", "create", "update", "delete", "query"] + ) + """Total image scans charged by the API.""" + total_image_scans_failed: Optional[int] = rest_field( + name="totalImageScansFailed", visibility=["read", "create", "update", "delete", "query"] + ) + """Total image scans failed.""" @overload def __init__( @@ -169,6 +222,8 @@ def __init__( translated_document_url: Optional[str] = None, error: Optional["_models.DocumentTranslationError"] = None, characters_charged: Optional[int] = None, + total_image_scans_succeeded: Optional[int] = None, + total_image_scans_failed: Optional[int] = None, ) -> None: ... @overload @@ -182,20 +237,22 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DocumentTranslateContent(_model_base.Model): +class DocumentTranslateContent(_Model): """Document Translate Request Content. - All required parameters must be populated in order to send to server. - :ivar document: Document to be translated in the form. Required. - :vartype document: ~azure.ai.translation.document._vendor.FileType + :vartype document: ~azure.ai.translation.document._utils.utils.FileType :ivar glossary: Glossary-translation memory will be used during translation in the form. - :vartype glossary: list[~azure.ai.translation.document._vendor.FileType] + :vartype glossary: list[~azure.ai.translation.document._utils.utils.FileType] """ - document: FileType = rest_field(is_multipart_file_input=True) + document: FileType = rest_field( + visibility=["read", "create", "update", "delete", "query"], is_multipart_file_input=True + ) """Document to be translated in the form. Required.""" - glossary: Optional[List[FileType]] = rest_field(is_multipart_file_input=True) + glossary: Optional[List[FileType]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], is_multipart_file_input=True + ) """Glossary-translation memory will be used during translation in the form.""" @overload @@ -217,13 +274,10 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DocumentTranslationError(_model_base.Model): +class DocumentTranslationError(_Model): """This contains an outer error with error code, message, details, target and an inner error with more descriptive details. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Enums containing high level error codes. Required. Known values are: "InvalidRequest", "InvalidArgument", "InternalServerError", "ServiceUnavailable", "ResourceNotFound", "Unauthorized", and "RequestRateTooHigh". @@ -236,27 +290,33 @@ 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). :vartype inner_error: ~azure.ai.translation.document.models.InnerTranslationError """ - code: Union[str, "_models.TranslationErrorCode"] = rest_field() + code: Union[str, "_models.TranslationErrorCode"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Enums containing high level error codes. Required. Known values are: \"InvalidRequest\", \"InvalidArgument\", \"InternalServerError\", \"ServiceUnavailable\", \"ResourceNotFound\", \"Unauthorized\", and \"RequestRateTooHigh\".""" - message: str = rest_field() + message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Gets high level error message. Required.""" target: Optional[str] = rest_field(visibility=["read"]) """Gets the source of the error. For example it would be \"documents\" or \"document id\" in case of invalid document.""" - inner_error: Optional["_models.InnerTranslationError"] = rest_field(name="innerError") + inner_error: Optional["_models.InnerTranslationError"] = rest_field( + name="innerError", visibility=["read", "create", "update", "delete", "query"] + ) """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. # pylint: disable=line-too-long + `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).""" @@ -281,10 +341,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DocumentTranslationFileFormat(_model_base.Model): +class DocumentTranslationFileFormat(_Model): """File Format. - :ivar file_format: Name of the format. Required. :vartype file_format: str :ivar file_extensions: Supported file extension for this format. Required. @@ -299,17 +358,27 @@ class DocumentTranslationFileFormat(_model_base.Model): :vartype type: str or ~azure.ai.translation.document.models.FileFormatType """ - file_format: str = rest_field(name="format") + file_format: str = rest_field(name="format", visibility=["read", "create", "update", "delete", "query"]) """Name of the format. Required.""" - file_extensions: List[str] = rest_field(name="fileExtensions") + file_extensions: List[str] = rest_field( + name="fileExtensions", visibility=["read", "create", "update", "delete", "query"] + ) """Supported file extension for this format. Required.""" - content_types: List[str] = rest_field(name="contentTypes") + content_types: List[str] = rest_field( + name="contentTypes", visibility=["read", "create", "update", "delete", "query"] + ) """Supported Content-Types for this format. Required.""" - default_format_version: Optional[str] = rest_field(name="defaultVersion") + default_format_version: Optional[str] = rest_field( + name="defaultVersion", visibility=["read", "create", "update", "delete", "query"] + ) """Default version if none is specified.""" - format_versions: Optional[List[str]] = rest_field(name="versions") + format_versions: Optional[List[str]] = rest_field( + name="versions", visibility=["read", "create", "update", "delete", "query"] + ) """Supported Version.""" - type: Optional[Union[str, "_models.FileFormatType"]] = rest_field() + type: Optional[Union[str, "_models.FileFormatType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Supported Type for this format. Known values are: \"document\" and \"glossary\".""" @overload @@ -335,17 +404,15 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class InnerTranslationError(_model_base.Model): +class InnerTranslationError(_Model): """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). - Readonly variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Gets code error string. Required. :vartype code: str :ivar message: Gets high level error message. Required. @@ -356,25 +423,29 @@ 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). :vartype inner_error: ~azure.ai.translation.document.models.InnerTranslationError """ - code: str = rest_field() + code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Gets code error string. Required.""" - message: str = rest_field() + message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Gets high level error message. Required.""" target: Optional[str] = rest_field(visibility=["read"]) """Gets the source of the error. For example it would be \"documents\" or \"document id\" in case of invalid document.""" - inner_error: Optional["_models.InnerTranslationError"] = rest_field(name="innerError") + inner_error: Optional["_models.InnerTranslationError"] = rest_field( + name="innerError", visibility=["read", "create", "update", "delete", "query"] + ) """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. # pylint: disable=line-too-long + `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).""" @@ -399,11 +470,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class SourceInput(_model_base.Model): +class SourceInput(_Model): """Source of the input documents. - All required parameters must be populated in order to send to server. - :ivar source_url: Location of the folder / container or single file with your documents. Required. :vartype source_url: str @@ -416,14 +485,16 @@ class SourceInput(_model_base.Model): :vartype storage_source: str or ~azure.ai.translation.document.models.TranslationStorageSource """ - source_url: str = rest_field(name="sourceUrl") + source_url: str = rest_field(name="sourceUrl", visibility=["read", "create", "update", "delete", "query"]) """Location of the folder / container or single file with your documents. Required.""" - filter: Optional["_models.DocumentFilter"] = rest_field() + filter: Optional["_models.DocumentFilter"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Document filter.""" - language: Optional[str] = rest_field() + language: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Language code If none is specified, we will perform auto detect on the document.""" - storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] = rest_field(name="storageSource") + storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] = rest_field( + name="storageSource", visibility=["read", "create", "update", "delete", "query"] + ) """Storage Source. \"AzureBlob\"""" @overload @@ -447,23 +518,26 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class StartTranslationDetails(_model_base.Model): +class StartTranslationDetails(_Model): """Translation job submission batch request. - All required parameters must be populated in order to send to server. - :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() + inputs: List["_models.DocumentBatch"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The input list of documents or folders containing documents. Required.""" + options: Optional["_models.BatchOptions"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The batch operation options.""" @overload def __init__( self, *, inputs: List["_models.DocumentBatch"], + options: Optional["_models.BatchOptions"] = None, ) -> None: ... @overload @@ -477,40 +551,23 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class SupportedFileFormats(_model_base.Model): +class SupportedFileFormats(_Model): """List of supported file formats. - :ivar value: list of objects. Required. :vartype value: list[~azure.ai.translation.document.models.DocumentTranslationFileFormat] """ - value: List["_models.DocumentTranslationFileFormat"] = rest_field() + value: List["_models.DocumentTranslationFileFormat"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """list of objects. Required.""" - -class TranslationErrorResponse(_model_base.Model): - """Contains unified error information used for HTTP responses across any Cognitive - Service. Instances - can be created either through - Microsoft.CloudAI.Containers.HttpStatusExceptionV2 or by returning it directly - from - a controller. - - :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 - """ - - error: Optional["_models.DocumentTranslationError"] = rest_field() - """This contains an outer error with error code, message, details, target and an - inner error with more descriptive details.""" - @overload def __init__( self, *, - error: Optional["_models.DocumentTranslationError"] = None, + value: List["_models.DocumentTranslationFileFormat"], ) -> None: ... @overload @@ -524,11 +581,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TranslationGlossary(_model_base.Model): +class TranslationGlossary(_Model): """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. @@ -544,18 +599,22 @@ class TranslationGlossary(_model_base.Model): :vartype storage_source: str or ~azure.ai.translation.document.models.TranslationStorageSource """ - glossary_url: str = rest_field(name="glossaryUrl") + glossary_url: str = rest_field(name="glossaryUrl", visibility=["read", "create", "update", "delete", "query"]) """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 = rest_field(name="format") + file_format: str = rest_field(name="format", visibility=["read", "create", "update", "delete", "query"]) """Format. Required.""" - format_version: Optional[str] = rest_field(name="version") + format_version: Optional[str] = rest_field( + name="version", visibility=["read", "create", "update", "delete", "query"] + ) """Optional Version. If not specified, default is used.""" - storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] = rest_field(name="storageSource") + storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] = rest_field( + name="storageSource", visibility=["read", "create", "update", "delete", "query"] + ) """Storage Source. \"AzureBlob\"""" @overload @@ -579,10 +638,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TranslationStatus(_model_base.Model): +class TranslationStatus(_Model): """Translation job status response. - :ivar id: Id of the translation operation. Required. :vartype id: str :ivar created_on: Operation created date time. Required. @@ -600,20 +658,26 @@ class TranslationStatus(_model_base.Model): :vartype summary: ~azure.ai.translation.document.models.TranslationStatusSummary """ - id: str = rest_field() + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Id of the translation operation. Required.""" - created_on: datetime.datetime = rest_field(name="createdDateTimeUtc", format="rfc3339") + created_on: datetime.datetime = rest_field( + name="createdDateTimeUtc", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Operation created date time. Required.""" - last_updated_on: datetime.datetime = rest_field(name="lastActionDateTimeUtc", format="rfc3339") + last_updated_on: datetime.datetime = rest_field( + name="lastActionDateTimeUtc", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Date time in which the operation's status has been updated. Required.""" - status: Union[str, "_models.Status"] = rest_field() + status: Union[str, "_models.Status"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """List of possible statuses for job or document. Required. Known values are: \"NotStarted\", \"Running\", \"Succeeded\", \"Failed\", \"Cancelled\", \"Cancelling\", and \"ValidationFailed\".""" - error: Optional["_models.DocumentTranslationError"] = rest_field() + error: Optional["_models.DocumentTranslationError"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """This contains an outer error with error code, message, details, target and an inner error with more descriptive details.""" - summary: "_models.TranslationStatusSummary" = rest_field() + summary: "_models.TranslationStatusSummary" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Status Summary. Required.""" @overload @@ -639,10 +703,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TranslationStatusSummary(_model_base.Model): +class TranslationStatusSummary(_Model): """Status Summary. - :ivar total: Total count. Required. :vartype total: int :ivar failed: Failed count. Required. @@ -657,22 +720,36 @@ 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_succeeded: Total image scans charged by the API. + :vartype total_image_scans_succeeded: int + :ivar total_image_scans_failed: Total image scans failed. + :vartype total_image_scans_failed: int """ - total: int = rest_field() + total: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Total count. Required.""" - failed: int = rest_field() + failed: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Failed count. Required.""" - success: int = rest_field() + success: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Number of Success. Required.""" - in_progress: int = rest_field(name="inProgress") + in_progress: int = rest_field(name="inProgress", visibility=["read", "create", "update", "delete", "query"]) """Number of in progress. Required.""" - not_yet_started: int = rest_field(name="notYetStarted") + not_yet_started: int = rest_field(name="notYetStarted", visibility=["read", "create", "update", "delete", "query"]) """Count of not yet started. Required.""" - canceled: int = rest_field(name="cancelled") + canceled: int = rest_field(name="cancelled", visibility=["read", "create", "update", "delete", "query"]) """Number of cancelled. Required.""" - total_characters_charged: int = rest_field(name="totalCharacterCharged") + total_characters_charged: int = rest_field( + name="totalCharacterCharged", visibility=["read", "create", "update", "delete", "query"] + ) """Total characters charged by the API. Required.""" + total_image_scans_succeeded: Optional[int] = rest_field( + name="totalImageScansSucceeded", visibility=["read", "create", "update", "delete", "query"] + ) + """Total image scans charged by the API.""" + total_image_scans_failed: Optional[int] = rest_field( + name="totalImageScansFailed", visibility=["read", "create", "update", "delete", "query"] + ) + """Total image scans failed.""" @overload def __init__( @@ -685,6 +762,8 @@ def __init__( not_yet_started: int, canceled: int, total_characters_charged: int, + total_image_scans_succeeded: Optional[int] = None, + total_image_scans_failed: Optional[int] = None, ) -> None: ... @overload @@ -698,11 +777,9 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TranslationTarget(_model_base.Model): +class TranslationTarget(_Model): """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. @@ -715,15 +792,19 @@ class TranslationTarget(_model_base.Model): :vartype storage_source: str or ~azure.ai.translation.document.models.TranslationStorageSource """ - target_url: str = rest_field(name="targetUrl") + target_url: str = rest_field(name="targetUrl", visibility=["read", "create", "update", "delete", "query"]) """Location of the folder / container with your documents. Required.""" - category_id: Optional[str] = rest_field(name="category") + category_id: Optional[str] = rest_field(name="category", visibility=["read", "create", "update", "delete", "query"]) """Category / custom system for translation request.""" - language: str = rest_field() + language: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Target Language. Required.""" - glossaries: Optional[List["_models.TranslationGlossary"]] = rest_field() + glossaries: Optional[List["_models.TranslationGlossary"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """List of Glossary.""" - storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] = rest_field(name="storageSource") + storage_source: Optional[Union[str, "_models.TranslationStorageSource"]] = rest_field( + name="storageSource", visibility=["read", "create", "update", "delete", "query"] + ) """Storage Source. \"AzureBlob\"""" @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 fc95f5ceb09d..8bcb627aa475 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 @@ -1,456 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. 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: - 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 - 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/generated_samples/batch.py b/sdk/translation/azure-ai-translation-document/generated_samples/batch.py new file mode 100644 index 000000000000..59aad26f1ef9 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_samples/batch.py @@ -0,0 +1,66 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- + +from azure.ai.translation.document import DocumentTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-document +# USAGE + python batch.py +""" + + +def main(): + client = DocumentTranslationClient( + endpoint="{endpoint}", + credential="CREDENTIAL", + ) + + response = client.begin_translation( + body={ + "inputs": [ + { + "source": { + "filter": {"prefix": "pre", "suffix": ".txt"}, + "language": "en", + "sourceUrl": "https://myblob.blob.core.windows.net/sourceContainer", + "storageSource": "AzureBlob", + }, + "storageType": "Folder", + "targets": [ + { + "category": "general", + "glossaries": [ + { + "format": "XLIFF", + "glossaryUrl": "https://myblob.blob.core.windows.net/myglossary/en_fr_glossary.xlf", + "storageSource": "AzureBlob", + } + ], + "language": "fr", + "storageSource": "AzureBlob", + "targetUrl": "https://myblob.blob.core.windows.net/destinationContainer1", + }, + { + "category": "general", + "language": "es", + "storageSource": "AzureBlob", + "targetUrl": "https://myblob.blob.core.windows.net/destinationContainer2", + }, + ], + } + ] + }, + ).result() + print(response) + + +# x-ms-original-file: 2024-11-01-preview/batch.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-document/generated_samples/cancel.py b/sdk/translation/azure-ai-translation-document/generated_samples/cancel.py new file mode 100644 index 000000000000..120757467a00 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_samples/cancel.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- + +from azure.ai.translation.document import DocumentTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-document +# USAGE + python cancel.py +""" + + +def main(): + client = DocumentTranslationClient( + endpoint="{endpoint}", + credential="CREDENTIAL", + ) + + response = client.cancel_translation( + translation_id="727BF148-F327-47A0-9481-ABAE6362F11E", + ) + print(response) + + +# x-ms-original-file: 2024-11-01-preview/cancel.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-document/generated_samples/document.py b/sdk/translation/azure-ai-translation-document/generated_samples/document.py new file mode 100644 index 000000000000..9423019a11ed --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_samples/document.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- + +from azure.ai.translation.document import DocumentTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-document +# USAGE + python document.py +""" + + +def main(): + client = DocumentTranslationClient( + endpoint="{endpoint}", + credential="CREDENTIAL", + ) + + response = client.get_document_status( + translation_id="727BF148-F327-47A0-9481-ABAE6362F11E", + document_id="727BF148-F327-47A0-9481-ABAE6362F12F", + ) + print(response) + + +# x-ms-original-file: 2024-11-01-preview/document.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-document/generated_samples/documents.py b/sdk/translation/azure-ai-translation-document/generated_samples/documents.py new file mode 100644 index 000000000000..e0f95a648fe0 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_samples/documents.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- + +from azure.ai.translation.document import DocumentTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-document +# USAGE + python documents.py +""" + + +def main(): + client = DocumentTranslationClient( + endpoint="{endpoint}", + credential="CREDENTIAL", + ) + + response = client.list_document_statuses( + translation_id="727BF148-F327-47A0-9481-ABAE6362F11E", + ) + for item in response: + print(item) + + +# x-ms-original-file: 2024-11-01-preview/documents.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-document/generated_samples/operation.py b/sdk/translation/azure-ai-translation-document/generated_samples/operation.py new file mode 100644 index 000000000000..afc71b2b2e14 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_samples/operation.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- + +from azure.ai.translation.document import DocumentTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-document +# USAGE + python operation.py +""" + + +def main(): + client = DocumentTranslationClient( + endpoint="{endpoint}", + credential="CREDENTIAL", + ) + + response = client.get_translation_status( + translation_id="727BF148-F327-47A0-9481-ABAE6362F11E", + ) + print(response) + + +# x-ms-original-file: 2024-11-01-preview/operation.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-document/generated_samples/operations.py b/sdk/translation/azure-ai-translation-document/generated_samples/operations.py new file mode 100644 index 000000000000..46997ef3c760 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_samples/operations.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- + +from azure.ai.translation.document import DocumentTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-document +# USAGE + python operations.py +""" + + +def main(): + client = DocumentTranslationClient( + endpoint="{endpoint}", + credential="CREDENTIAL", + ) + + response = client.list_translation_statuses() + for item in response: + print(item) + + +# x-ms-original-file: 2024-11-01-preview/operations.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-document/generated_tests/conftest.py b/sdk/translation/azure-ai-translation-document/generated_tests/conftest.py new file mode 100644 index 000000000000..5af5f93c5057 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_tests/conftest.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + documenttranslation_subscription_id = os.environ.get( + "DOCUMENTTRANSLATION_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + documenttranslation_tenant_id = os.environ.get( + "DOCUMENTTRANSLATION_TENANT_ID", "00000000-0000-0000-0000-000000000000" + ) + documenttranslation_client_id = os.environ.get( + "DOCUMENTTRANSLATION_CLIENT_ID", "00000000-0000-0000-0000-000000000000" + ) + documenttranslation_client_secret = os.environ.get( + "DOCUMENTTRANSLATION_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=documenttranslation_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=documenttranslation_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=documenttranslation_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=documenttranslation_client_secret, value="00000000-0000-0000-0000-000000000000") + + singledocumenttranslation_subscription_id = os.environ.get( + "SINGLEDOCUMENTTRANSLATION_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + singledocumenttranslation_tenant_id = os.environ.get( + "SINGLEDOCUMENTTRANSLATION_TENANT_ID", "00000000-0000-0000-0000-000000000000" + ) + singledocumenttranslation_client_id = os.environ.get( + "SINGLEDOCUMENTTRANSLATION_CLIENT_ID", "00000000-0000-0000-0000-000000000000" + ) + singledocumenttranslation_client_secret = os.environ.get( + "SINGLEDOCUMENTTRANSLATION_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=singledocumenttranslation_subscription_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=singledocumenttranslation_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=singledocumenttranslation_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer( + regex=singledocumenttranslation_client_secret, value="00000000-0000-0000-0000-000000000000" + ) + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/translation/azure-ai-translation-document/generated_tests/test_document_translation.py b/sdk/translation/azure-ai-translation-document/generated_tests/test_document_translation.py new file mode 100644 index 000000000000..48d448d716a0 --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_tests/test_document_translation.py @@ -0,0 +1,102 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import DocumentTranslationClientTestBase, DocumentTranslationPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDocumentTranslation(DocumentTranslationClientTestBase): + @DocumentTranslationPreparer() + @recorded_by_proxy + def test_begin_translation(self, documenttranslation_endpoint): + client = self.create_client(endpoint=documenttranslation_endpoint) + response = client.begin_translation( + 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", + } + ], + "options": {"translateTextWithinImage": bool}, + }, + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy + def test_list_translation_statuses(self, documenttranslation_endpoint): + client = self.create_client(endpoint=documenttranslation_endpoint) + response = client.list_translation_statuses() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy + def test_get_document_status(self, documenttranslation_endpoint): + client = self.create_client(endpoint=documenttranslation_endpoint) + response = client.get_document_status( + translation_id="str", + document_id="str", + ) + + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy + def test_get_translation_status(self, documenttranslation_endpoint): + client = self.create_client(endpoint=documenttranslation_endpoint) + response = client.get_translation_status( + translation_id="str", + ) + + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy + def test_cancel_translation(self, documenttranslation_endpoint): + client = self.create_client(endpoint=documenttranslation_endpoint) + response = client.cancel_translation( + translation_id="str", + ) + + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy + def test_list_document_statuses(self, documenttranslation_endpoint): + client = self.create_client(endpoint=documenttranslation_endpoint) + response = client.list_document_statuses( + translation_id="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/translation/azure-ai-translation-document/generated_tests/test_document_translation_async.py b/sdk/translation/azure-ai-translation-document/generated_tests/test_document_translation_async.py new file mode 100644 index 000000000000..beeb075424be --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_tests/test_document_translation_async.py @@ -0,0 +1,110 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import DocumentTranslationPreparer +from testpreparer_async import DocumentTranslationClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestDocumentTranslationAsync(DocumentTranslationClientTestBaseAsync): + @DocumentTranslationPreparer() + @recorded_by_proxy_async + async def test_begin_translation(self, documenttranslation_endpoint): + client = self.create_async_client(endpoint=documenttranslation_endpoint) + response = await ( + await client.begin_translation( + 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", + } + ], + "options": {"translateTextWithinImage": bool}, + }, + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy_async + async def test_list_translation_statuses(self, documenttranslation_endpoint): + client = self.create_async_client(endpoint=documenttranslation_endpoint) + response = client.list_translation_statuses() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy_async + async def test_get_document_status(self, documenttranslation_endpoint): + client = self.create_async_client(endpoint=documenttranslation_endpoint) + response = await client.get_document_status( + translation_id="str", + document_id="str", + ) + + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy_async + async def test_get_translation_status(self, documenttranslation_endpoint): + client = self.create_async_client(endpoint=documenttranslation_endpoint) + response = await client.get_translation_status( + translation_id="str", + ) + + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy_async + async def test_cancel_translation(self, documenttranslation_endpoint): + client = self.create_async_client(endpoint=documenttranslation_endpoint) + response = await client.cancel_translation( + translation_id="str", + ) + + # please add some check logic here by yourself + # ... + + @DocumentTranslationPreparer() + @recorded_by_proxy_async + async def test_list_document_statuses(self, documenttranslation_endpoint): + client = self.create_async_client(endpoint=documenttranslation_endpoint) + response = client.list_document_statuses( + translation_id="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/translation/azure-ai-translation-document/generated_tests/test_single_document_translation.py b/sdk/translation/azure-ai-translation-document/generated_tests/test_single_document_translation.py new file mode 100644 index 000000000000..d747dbecd19e --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_tests/test_single_document_translation.py @@ -0,0 +1,25 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import SingleDocumentTranslationClientTestBase, SingleDocumentTranslationPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSingleDocumentTranslation(SingleDocumentTranslationClientTestBase): + @SingleDocumentTranslationPreparer() + @recorded_by_proxy + def test_translate(self, singledocumenttranslation_endpoint): + client = self.create_client(endpoint=singledocumenttranslation_endpoint) + response = client.translate( + body={"document": "filetype", "glossary": ["filetype"]}, + target_language="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/translation/azure-ai-translation-document/generated_tests/test_single_document_translation_async.py b/sdk/translation/azure-ai-translation-document/generated_tests/test_single_document_translation_async.py new file mode 100644 index 000000000000..7c736ec3f62b --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_tests/test_single_document_translation_async.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import SingleDocumentTranslationPreparer +from testpreparer_async import SingleDocumentTranslationClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestSingleDocumentTranslationAsync(SingleDocumentTranslationClientTestBaseAsync): + @SingleDocumentTranslationPreparer() + @recorded_by_proxy_async + async def test_translate(self, singledocumenttranslation_endpoint): + client = self.create_async_client(endpoint=singledocumenttranslation_endpoint) + response = await client.translate( + body={"document": "filetype", "glossary": ["filetype"]}, + target_language="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/translation/azure-ai-translation-document/generated_tests/testpreparer.py b/sdk/translation/azure-ai-translation-document/generated_tests/testpreparer.py new file mode 100644 index 000000000000..7ea092bef09f --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_tests/testpreparer.py @@ -0,0 +1,46 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- +from azure.ai.translation.document import DocumentTranslationClient, SingleDocumentTranslationClient +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +import functools + + +class DocumentTranslationClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(DocumentTranslationClient) + return self.create_client_from_credential( + DocumentTranslationClient, + credential=credential, + endpoint=endpoint, + ) + + +DocumentTranslationPreparer = functools.partial( + PowerShellPreparer, + "documenttranslation", + documenttranslation_endpoint="https://fake_documenttranslation_endpoint.com", +) + + +class SingleDocumentTranslationClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(SingleDocumentTranslationClient) + return self.create_client_from_credential( + SingleDocumentTranslationClient, + credential=credential, + endpoint=endpoint, + ) + + +SingleDocumentTranslationPreparer = functools.partial( + PowerShellPreparer, + "singledocumenttranslation", + singledocumenttranslation_endpoint="https://fake_singledocumenttranslation_endpoint.com", +) diff --git a/sdk/translation/azure-ai-translation-document/generated_tests/testpreparer_async.py b/sdk/translation/azure-ai-translation-document/generated_tests/testpreparer_async.py new file mode 100644 index 000000000000..61fce0b0b7eb --- /dev/null +++ b/sdk/translation/azure-ai-translation-document/generated_tests/testpreparer_async.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- +from azure.ai.translation.document.aio import DocumentTranslationClient, SingleDocumentTranslationClient +from devtools_testutils import AzureRecordedTestCase + + +class DocumentTranslationClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(DocumentTranslationClient, is_async=True) + return self.create_client_from_credential( + DocumentTranslationClient, + credential=credential, + endpoint=endpoint, + ) + + +class SingleDocumentTranslationClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(SingleDocumentTranslationClient, is_async=True) + return self.create_client_from_credential( + SingleDocumentTranslationClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/sdk/translation/azure-ai-translation-document/samples/async_samples/sample_begin_translation_async.py b/sdk/translation/azure-ai-translation-document/samples/async_samples/sample_begin_translation_async.py index 4dad31b85b77..960a7d336e2c 100644 --- a/sdk/translation/azure-ai-translation-document/samples/async_samples/sample_begin_translation_async.py +++ b/sdk/translation/azure-ai-translation-document/samples/async_samples/sample_begin_translation_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. diff --git a/sdk/translation/azure-ai-translation-document/samples/async_samples/sample_begin_translation_with_filters_async.py b/sdk/translation/azure-ai-translation-document/samples/async_samples/sample_begin_translation_with_filters_async.py index 4fa3d844e478..43adaa2b7a51 100644 --- a/sdk/translation/azure-ai-translation-document/samples/async_samples/sample_begin_translation_with_filters_async.py +++ b/sdk/translation/azure-ai-translation-document/samples/async_samples/sample_begin_translation_with_filters_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. diff --git a/sdk/translation/azure-ai-translation-document/samples/sample_begin_translation_with_filters.py b/sdk/translation/azure-ai-translation-document/samples/sample_begin_translation_with_filters.py index 5fca65452a8f..cae5f1852a67 100644 --- a/sdk/translation/azure-ai-translation-document/samples/sample_begin_translation_with_filters.py +++ b/sdk/translation/azure-ai-translation-document/samples/sample_begin_translation_with_filters.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. diff --git a/sdk/translation/azure-ai-translation-document/setup.py b/sdk/translation/azure-ai-translation-document/setup.py index 8464b676cfe9..e2ac8e8f2514 100644 --- a/sdk/translation/azure-ai-translation-document/setup.py +++ b/sdk/translation/azure-ai-translation-document/setup.py @@ -5,7 +5,7 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# coding: utf-8 + import os import re @@ -29,7 +29,7 @@ setup( name=PACKAGE_NAME, version=version, - description="Microsoft {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + description="Microsoft Corporation {} Client Library for Python".format(PACKAGE_PPRINT_NAME), long_description=open("README.md", "r").read(), long_description_content_type="text/markdown", license="MIT License", @@ -38,16 +38,14 @@ url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", keywords="azure, azure sdk", classifiers=[ - "Development Status :: 5 - Production/Stable", + "Development Status :: 4 - Beta", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", "License :: OSI Approved :: MIT License", ], zip_safe=False, @@ -69,5 +67,5 @@ "azure-core>=1.30.0", "typing-extensions>=4.6.0", ], - python_requires=">=3.8", + python_requires=">=3.9", ) diff --git a/sdk/translation/azure-ai-translation-document/tsp-location.yaml b/sdk/translation/azure-ai-translation-document/tsp-location.yaml index bb4b6ef00eab..0334d2c58708 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: ccc08b40afbff1abe17c8250ed03a87e81fbf673 -repo: Azure/azure-rest-api-specs directory: specification/translation/Azure.AI.DocumentTranslation +commit: 147495e1b6cfe5607d481278e31857dc929b42fa +repo: Azure/azure-rest-api-specs +additionalDirectories: