diff --git a/sdk/translation/azure-ai-translation-text/MANIFEST.in b/sdk/translation/azure-ai-translation-text/MANIFEST.in index af6732a09e1e..195bc20eac46 100644 --- a/sdk/translation/azure-ai-translation-text/MANIFEST.in +++ b/sdk/translation/azure-ai-translation-text/MANIFEST.in @@ -5,4 +5,4 @@ recursive-include tests *.py recursive-include samples *.py *.md include azure/__init__.py include azure/ai/__init__.py -include azure/ai/translation/__init__.py \ No newline at end of file +include azure/ai/translation/__init__.py diff --git a/sdk/translation/azure-ai-translation-text/_meta.json b/sdk/translation/azure-ai-translation-text/_meta.json new file mode 100644 index 000000000000..842aad668371 --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "147495e1b6cfe5607d481278e31857dc929b42fa", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/translation/Azure.AI.TextTranslation", + "@azure-tools/typespec-python": "0.44.2" +} \ No newline at end of file diff --git a/sdk/translation/azure-ai-translation-text/apiview-properties.json b/sdk/translation/azure-ai-translation-text/apiview-properties.json new file mode 100644 index 000000000000..8c686aebee66 --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/apiview-properties.json @@ -0,0 +1,33 @@ +{ + "CrossLanguagePackageId": "TextTranslation", + "CrossLanguageDefinitionId": { + "azure.ai.translation.text.models.DetectedLanguage": "TextTranslation.DetectedLanguage", + "azure.ai.translation.text.models.ErrorDetails": "TextTranslation.ErrorDetails", + "azure.ai.translation.text.models.ErrorResponse": "TextTranslation.ErrorResponse", + "azure.ai.translation.text.models.GetSupportedLanguagesResult": "TextTranslation.GetSupportedLanguagesResult", + "azure.ai.translation.text.models.InputTextItem": "TextTranslation.InputTextItem", + "azure.ai.translation.text.models.LanguageScript": "TextTranslation.LanguageScript", + "azure.ai.translation.text.models.ReferenceSentencePair": "TextTranslation.ReferenceSentencePair", + "azure.ai.translation.text.models.SourceDictionaryLanguage": "TextTranslation.SourceDictionaryLanguage", + "azure.ai.translation.text.models.SourceText": "TextTranslation.SourceText", + "azure.ai.translation.text.models.TargetDictionaryLanguage": "TextTranslation.TargetDictionaryLanguage", + "azure.ai.translation.text.models.TranslateBody": "TextTranslation.TranslateBody", + "azure.ai.translation.text.models.TranslatedTextItem": "TextTranslation.TranslatedTextItem", + "azure.ai.translation.text.models.TranslateTarget": "TextTranslation.TranslateTarget", + "azure.ai.translation.text.models.TranslationLanguage": "TextTranslation.TranslationLanguage", + "azure.ai.translation.text.models.TranslationText": "TextTranslation.TranslationText", + "azure.ai.translation.text.models.TransliterableScript": "TextTranslation.TransliterableScript", + "azure.ai.translation.text.models.TransliteratedText": "TextTranslation.TransliteratedText", + "azure.ai.translation.text.models.TransliterationLanguage": "TextTranslation.TransliterationLanguage", + "azure.ai.translation.text.models.LanguageDirectionality": "TextTranslation.LanguageDirectionality", + "azure.ai.translation.text.models.TextType": "TextTranslation.TextType", + "azure.ai.translation.text.models.ProfanityAction": "TextTranslation.ProfanityAction", + "azure.ai.translation.text.models.ProfanityMarker": "TextTranslation.ProfanityMarker", + "azure.ai.translation.text.TextTranslationClient.get_supported_languages": "TextTranslation.getSupportedLanguages", + "azure.ai.translation.text.aio.TextTranslationClient.get_supported_languages": "TextTranslation.getSupportedLanguages", + "azure.ai.translation.text.TextTranslationClient.translate": "TextTranslation.translate", + "azure.ai.translation.text.aio.TextTranslationClient.translate": "TextTranslation.translate", + "azure.ai.translation.text.TextTranslationClient.transliterate": "TextTranslation.transliterate", + "azure.ai.translation.text.aio.TextTranslationClient.transliterate": "TextTranslation.transliterate" + } +} \ No newline at end of file diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/__init__.py index 4b66a9e2dde2..9222cec2fdae 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/__init__.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/__init__.py @@ -5,18 +5,28 @@ # 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 TextTranslationClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import TextTranslationClient # type: ignore from ._version import VERSION __version__ = VERSION - +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] from ._patch import patch_sdk as _patch_sdk __all__ = [ "TextTranslationClient", ] - +__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-text/azure/ai/translation/text/_client.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_client.py index c5ebee7ced4a..6069a03c40ed 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_client.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_client.py @@ -8,6 +8,7 @@ from copy import deepcopy from typing import Any +from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies @@ -15,10 +16,10 @@ from ._configuration import TextTranslationClientConfiguration from ._operations import TextTranslationClientOperationsMixin -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer -class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword +class TextTranslationClient(TextTranslationClientOperationsMixin): """Text translation is a cloud-based REST API feature of the Translator service that uses neural machine translation technology to enable quick and accurate source-to-target text translation in real time across all supported languages. @@ -37,16 +38,12 @@ class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: di Detect. Returns the source code language code and a boolean variable denoting whether the detected language is supported for text translation and transliteration. - Dictionary lookup. Returns equivalent words for the source term in the target language. - - Dictionary example Returns grammatical structure and context examples for the source term and - target term pair. - :param endpoint: Supported Text Translation endpoints (protocol and hostname, for example: - https://api.cognitive.microsofttranslator.com). Required. + `https://api.cognitive.microsofttranslator.com + `_). Required. :type endpoint: str - :keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that - overriding this default value may result in unsupported behavior. + :keyword api_version: Mandatory API version parameter. Default value is "2025-05-01-preview". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ @@ -55,6 +52,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ) -> None: _endpoint = "{Endpoint}" self._config = TextTranslationClientConfiguration(endpoint=endpoint, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -107,7 +105,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: def close(self) -> None: self._client.close() - def __enter__(self) -> "TextTranslationClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_configuration.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_configuration.py index 37b94a41e8a9..a41672f00c8a 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_configuration.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_configuration.py @@ -13,22 +13,23 @@ from ._version import VERSION -class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for TextTranslationClient. Note that all parameters used to create this instance are saved as instance attributes. :param endpoint: Supported Text Translation endpoints (protocol and hostname, for example: - https://api.cognitive.microsofttranslator.com). Required. + `https://api.cognitive.microsofttranslator.com + `_). Required. :type endpoint: str - :keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that - overriding this default value may result in unsupported behavior. + :keyword api_version: Mandatory API version parameter. Default value is "2025-05-01-preview". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "3.0") + api_version: str = kwargs.pop("api_version", "2025-05-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/__init__.py index 47ae0af6503a..dbcf8750add3 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/__init__.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/__init__.py @@ -5,14 +5,21 @@ # 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 TextTranslationClientOperationsMixin +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import +from ._operations import TextTranslationClientOperationsMixin # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "TextTranslationClientOperationsMixin", ] - +__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-text/azure/ai/translation/text/_operations/_operations.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_operations.py index 73eda75baff4..230ce3e91e9d 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_operations.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,13 +5,12 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: disable=R0914 +from collections.abc import MutableMapping from io import IOBase import json -import sys -from typing import Any, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload -from azure.core import MatchConditions +from azure.core import MatchConditions, PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,6 +18,8 @@ ResourceModifiedError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -28,14 +28,11 @@ from azure.core.utils import case_insensitive_dict from .. import models as _models -from .._model_base import SdkJSONEncoder, _deserialize -from .._serialization import Serializer -from .._vendor import TextTranslationClientMixinABC, prep_if_match, prep_if_none_match - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +from .._configuration import TextTranslationClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC, prep_if_match, prep_if_none_match + T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +52,7 @@ def build_text_translation_get_supported_languages_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", "3.0")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -82,57 +79,18 @@ def build_text_translation_get_supported_languages_request( # pylint: disable=n return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_text_translation_translate_request( - *, - to_language: List[str], - client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: +def build_text_translation_translate_request(*, client_trace_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: _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", "3.0")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/translate" # Construct parameters - _params["to"] = [_SERIALIZER.query("to_language", q, "str") if q is not None else "" for q in to_language] - if from_language is not None: - _params["from"] = _SERIALIZER.query("from_language", from_language, "str") - if text_type is not None: - _params["textType"] = _SERIALIZER.query("text_type", text_type, "str") - if category is not None: - _params["category"] = _SERIALIZER.query("category", category, "str") - if profanity_action is not None: - _params["profanityAction"] = _SERIALIZER.query("profanity_action", profanity_action, "str") - if profanity_marker is not None: - _params["profanityMarker"] = _SERIALIZER.query("profanity_marker", profanity_marker, "str") - if include_alignment is not None: - _params["includeAlignment"] = _SERIALIZER.query("include_alignment", include_alignment, "bool") - if include_sentence_length is not None: - _params["includeSentenceLength"] = _SERIALIZER.query("include_sentence_length", include_sentence_length, "bool") - if suggested_from is not None: - _params["suggestedFrom"] = _SERIALIZER.query("suggested_from", suggested_from, "str") - if from_script is not None: - _params["fromScript"] = _SERIALIZER.query("from_script", from_script, "str") - if to_script is not None: - _params["toScript"] = _SERIALIZER.query("to_script", to_script, "str") - if allow_fallback is not None: - _params["allowFallback"] = _SERIALIZER.query("allow_fallback", allow_fallback, "bool") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers @@ -152,7 +110,7 @@ def build_text_translation_transliterate_request( # pylint: disable=name-too-lo _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", "3.0")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -174,97 +132,9 @@ def build_text_translation_transliterate_request( # pylint: disable=name-too-lo return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_text_translation_find_sentence_boundaries_request( # pylint: disable=name-too-long - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _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", "3.0")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/breaksentence" - - # Construct parameters - if language is not None: - _params["language"] = _SERIALIZER.query("language", language, "str") - if script is not None: - _params["script"] = _SERIALIZER.query("script", script, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if client_trace_id is not None: - _headers["X-ClientTraceId"] = _SERIALIZER.header("client_trace_id", client_trace_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_text_translation_lookup_dictionary_entries_request( # pylint: disable=name-too-long - *, from_language: str, to_language: str, client_trace_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _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", "3.0")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/lookup" - - # Construct parameters - _params["from"] = _SERIALIZER.query("from_language", from_language, "str") - _params["to"] = _SERIALIZER.query("to_language", to_language, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if client_trace_id is not None: - _headers["X-ClientTraceId"] = _SERIALIZER.header("client_trace_id", client_trace_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_text_translation_lookup_dictionary_examples_request( # pylint: disable=name-too-long - *, from_language: str, to_language: str, client_trace_id: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - _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", "3.0")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/examples" - - # Construct parameters - _params["from"] = _SERIALIZER.query("from_language", from_language, "str") - _params["to"] = _SERIALIZER.query("to_language", to_language, "str") - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if client_trace_id is not None: - _headers["X-ClientTraceId"] = _SERIALIZER.header("client_trace_id", client_trace_id, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class TextTranslationClientOperationsMixin(TextTranslationClientMixinABC): +class TextTranslationClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], TextTranslationClientConfiguration] +): @distributed_trace def get_supported_languages( @@ -277,7 +147,6 @@ def get_supported_languages( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.GetSupportedLanguagesResult: - # pylint: disable=line-too-long """Gets the set of languages currently supported by other operations of the Translator. Gets the set of languages currently supported by other operations of the Translator. @@ -286,7 +155,7 @@ def get_supported_languages( value is None. :paramtype client_trace_id: str :keyword scope: A comma-separated list of names defining the group of languages to return. - Allowed group names are: ``translation``\\ , ``transliteration`` and ``dictionary``. + Allowed group names are: ``translation``, ``transliteration`` and ``dictionary``. If no scope is given, then all groups are returned, which is equivalent to passing ``scope=translation,transliteration,dictionary``. To decide which set of supported languages is appropriate for your scenario, see the description of the `response object @@ -312,88 +181,8 @@ def get_supported_languages( MutableMapping :rtype: ~azure.ai.translation.text.models.GetSupportedLanguagesResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "dictionary": { - "str": { - "dir": "str", # Directionality, which is rtl for - right-to-left languages or ltr for left-to-right languages. Required. - Known values are: "ltr" and "rtl". - "name": "str", # Display name of the language in the locale - requested via Accept-Language header. Required. - "nativeName": "str", # Display name of the language in the - locale native for this language. Required. - "translations": [ - { - "code": "str", # Language code identifying - the target language. Required. - "dir": "str", # Directionality, which is rtl - for right-to-left languages or ltr for left-to-right languages. - Required. Known values are: "ltr" and "rtl". - "name": "str", # Display name of the - language in the locale requested via Accept-Language header. - Required. - "nativeName": "str" # Display name of the - language in the locale native for this language. Required. - } - ] - } - }, - "translation": { - "str": { - "dir": "str", # Directionality, which is rtl for - right-to-left languages or ltr for left-to-right languages. Required. - Known values are: "ltr" and "rtl". - "name": "str", # Display name of the language in the locale - requested via Accept-Language header. Required. - "nativeName": "str" # Display name of the language in the - locale native for this language. Required. - } - }, - "transliteration": { - "str": { - "name": "str", # Display name of the language in the locale - requested via Accept-Language header. Required. - "nativeName": "str", # Display name of the language in the - locale native for this language. Required. - "scripts": [ - { - "code": "str", # Code identifying the - script. Required. - "dir": "str", # Directionality, which is rtl - for right-to-left languages or ltr for left-to-right languages. - Required. Known values are: "ltr" and "rtl". - "name": "str", # Display name of the script - in the locale requested via Accept-Language header. Required. - "nativeName": "str", # Display name of the - language in the locale native for the language. Required. - "toScripts": [ - { - "code": "str", # Code - identifying the script. Required. - "dir": "str", # - Directionality, which is rtl for right-to-left languages - or ltr for left-to-right languages. Required. Known - values are: "ltr" and "rtl". - "name": "str", # Display - name of the script in the locale requested via - Accept-Language header. Required. - "nativeName": "str" # - Display name of the language in the locale native for the - language. Required. - } - ] - } - ] - } - } - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -436,9 +225,12 @@ def get_supported_languages( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ErrorResponse, response.json()) + error = _failsafe_deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -458,177 +250,27 @@ def get_supported_languages( @overload def translate( self, - body: List[_models.InputTextItem], + body: List[_models.TranslateBody], *, - to_language: List[str], client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, content_type: str = "application/json", **kwargs: Any ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long """Translate Text. Translate Text. :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword to_language: Specifies the language of the output text. The target language must be - one of the supported languages included - in the translation scope. For example, use to=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to=de&to=it to translate to German and Italian. Required. - :paramtype to_language: list[str] + :type body: list[~azure.ai.translation.text.models.TranslateBody] :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default value is None. :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :return: list of TranslatedTextItem :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] """ @overload @@ -636,336 +278,50 @@ def translate( self, body: IO[bytes], *, - to_language: List[str], client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, content_type: str = "application/json", **kwargs: Any ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long """Translate Text. Translate Text. :param body: Defines the content of the request. Required. :type body: IO[bytes] - :keyword to_language: Specifies the language of the output text. The target language must be - one of the supported languages included - in the translation scope. For example, use to=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to=de&to=it to translate to German and Italian. Required. - :paramtype to_language: list[str] :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default value is None. :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :return: list of TranslatedTextItem :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] """ @distributed_trace def translate( self, - body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.TranslateBody], IO[bytes]], *, - to_language: List[str], client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, **kwargs: Any ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long """Translate Text. Translate Text. - :param body: Defines the content of the request. Is either a [InputTextItem] type or a + :param body: Defines the content of the request. Is either a [TranslateBody] type or a IO[bytes] type. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] - :keyword to_language: Specifies the language of the output text. The target language must be - one of the supported languages included - in the translation scope. For example, use to=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to=de&to=it to translate to German and Italian. Required. - :paramtype to_language: list[str] + :type body: list[~azure.ai.translation.text.models.TranslateBody] or IO[bytes] :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default value is None. :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool :return: list of TranslatedTextItem :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -987,19 +343,7 @@ def translate( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_translate_request( - to_language=to_language, client_trace_id=client_trace_id, - from_language=from_language, - text_type=text_type, - category=category, - profanity_action=profanity_action, - profanity_marker=profanity_marker, - include_alignment=include_alignment, - include_sentence_length=include_sentence_length, - suggested_from=suggested_from, - from_script=from_script, - to_script=to_script, - allow_fallback=allow_fallback, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -1020,9 +364,12 @@ def translate( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ErrorResponse, response.json()) + error = _failsafe_deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1079,26 +426,6 @@ def transliterate( :return: list of TransliteratedText :rtype: list[~azure.ai.translation.text.models.TransliteratedText] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] """ @overload @@ -1140,19 +467,6 @@ def transliterate( :return: list of TransliteratedText :rtype: list[~azure.ai.translation.text.models.TransliteratedText] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] """ @distributed_trace @@ -1191,21 +505,8 @@ def transliterate( :return: list of TransliteratedText :rtype: list[~azure.ai.translation.text.models.TransliteratedText] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1251,9 +552,12 @@ def transliterate( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ErrorResponse, response.json()) + error = _failsafe_deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1268,929 +572,3 @@ def transliterate( return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - - @overload - def find_sentence_boundaries( - self, - body: List[_models.InputTextItem], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - @overload - def find_sentence_boundaries( - self, - body: IO[bytes], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - @distributed_trace - def find_sentence_boundaries( - self, - body: Union[List[_models.InputTextItem], IO[bytes]], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Is either a [InputTextItem] type or a - IO[bytes] type. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _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[List[_models.BreakSentenceItem]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_text_translation_find_sentence_boundaries_request( - client_trace_id=client_trace_id, - language=language, - script=script, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - 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", False) - 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) - error = _deserialize(_models.ErrorResponse, response.json()) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["X-RequestId"] = self._deserialize("str", response.headers.get("X-RequestId")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(List[_models.BreakSentenceItem], response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def lookup_dictionary_entries( - self, - body: List[_models.InputTextItem], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "confidence": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - @overload - def lookup_dictionary_entries( - self, - body: IO[bytes], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "confidence": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - @distributed_trace - def lookup_dictionary_entries( - self, - body: Union[List[_models.InputTextItem], IO[bytes]], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Is either a [InputTextItem] type or a - IO[bytes] type. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "confidence": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _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[List[_models.DictionaryLookupItem]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_text_translation_lookup_dictionary_entries_request( - from_language=from_language, - to_language=to_language, - client_trace_id=client_trace_id, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - 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", False) - 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) - error = _deserialize(_models.ErrorResponse, response.json()) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["X-RequestId"] = self._deserialize("str", response.headers.get("X-RequestId")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(List[_models.DictionaryLookupItem], response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def lookup_dictionary_examples( - self, - body: List[_models.DictionaryExampleTextItem], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryExampleItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Examples. - - Lookup Dictionary Examples. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryExampleItem - :rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str", # Text to translate. Required. - "translation": "str" # A string specifying the translated text - previously returned by the Dictionary lookup operation. This should be the - value from the normalizedTarget field in the translations list of the - Dictionary lookup response. The service will return examples for the - specific source-target word-pair. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "examples": [ - { - "sourcePrefix": "str", # The string to concatenate - before the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceSuffix": "str", # The string to concatenate - after the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceTerm": "str", # A string equal to the actual - term looked up. The string is added with sourcePrefix and - sourceSuffix to form the complete example. Its value is separated so - it can be marked in a user interface, e.g., by bolding it. Required. - "targetPrefix": "str", # A string similar to - sourcePrefix but for the target. Required. - "targetSuffix": "str", # A string similar to - sourceSuffix but for the target. Required. - "targetTerm": "str" # A string similar to sourceTerm - but for the target. Required. - } - ], - "normalizedSource": "str", # A string giving the normalized form of - the source term. Generally, this should be identical to the value of the Text - field at the matching list index in the body of the request. Required. - "normalizedTarget": "str" # A string giving the normalized form of - the target term. Generally, this should be identical to the value of the - Translation field at the matching list index in the body of the request. - Required. - } - ] - """ - - @overload - def lookup_dictionary_examples( - self, - body: IO[bytes], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryExampleItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Examples. - - Lookup Dictionary Examples. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryExampleItem - :rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "examples": [ - { - "sourcePrefix": "str", # The string to concatenate - before the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceSuffix": "str", # The string to concatenate - after the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceTerm": "str", # A string equal to the actual - term looked up. The string is added with sourcePrefix and - sourceSuffix to form the complete example. Its value is separated so - it can be marked in a user interface, e.g., by bolding it. Required. - "targetPrefix": "str", # A string similar to - sourcePrefix but for the target. Required. - "targetSuffix": "str", # A string similar to - sourceSuffix but for the target. Required. - "targetTerm": "str" # A string similar to sourceTerm - but for the target. Required. - } - ], - "normalizedSource": "str", # A string giving the normalized form of - the source term. Generally, this should be identical to the value of the Text - field at the matching list index in the body of the request. Required. - "normalizedTarget": "str" # A string giving the normalized form of - the target term. Generally, this should be identical to the value of the - Translation field at the matching list index in the body of the request. - Required. - } - ] - """ - - @distributed_trace - def lookup_dictionary_examples( - self, - body: Union[List[_models.DictionaryExampleTextItem], IO[bytes]], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - **kwargs: Any - ) -> List[_models.DictionaryExampleItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Examples. - - Lookup Dictionary Examples. - - :param body: Defines the content of the request. Is either a [DictionaryExampleTextItem] type - or a IO[bytes] type. Required. - :type body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] or IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :return: list of DictionaryExampleItem - :rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "examples": [ - { - "sourcePrefix": "str", # The string to concatenate - before the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceSuffix": "str", # The string to concatenate - after the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceTerm": "str", # A string equal to the actual - term looked up. The string is added with sourcePrefix and - sourceSuffix to form the complete example. Its value is separated so - it can be marked in a user interface, e.g., by bolding it. Required. - "targetPrefix": "str", # A string similar to - sourcePrefix but for the target. Required. - "targetSuffix": "str", # A string similar to - sourceSuffix but for the target. Required. - "targetTerm": "str" # A string similar to sourceTerm - but for the target. Required. - } - ], - "normalizedSource": "str", # A string giving the normalized form of - the source term. Generally, this should be identical to the value of the Text - field at the matching list index in the body of the request. Required. - "normalizedTarget": "str" # A string giving the normalized form of - the target term. Generally, this should be identical to the value of the - Translation field at the matching list index in the body of the request. - Required. - } - ] - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _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[List[_models.DictionaryExampleItem]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_text_translation_lookup_dictionary_examples_request( - from_language=from_language, - to_language=to_language, - client_trace_id=client_trace_id, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - 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", False) - 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) - error = _deserialize(_models.ErrorResponse, response.json()) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["X-RequestId"] = self._deserialize("str", response.headers.get("X-RequestId")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(List[_models.DictionaryExampleItem], response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_patch.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_patch.py index 7506475e6478..8bcb627aa475 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_patch.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_patch.py @@ -1,1367 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint: disable=C0302 - +# 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 Any, cast, IO, List, Optional, overload, Union -from .. import models as _models -from ._operations import TextTranslationClientOperationsMixin as TextTranslationClientOperationsMixinGenerated - - -class TextTranslationClientOperationsMixin(TextTranslationClientOperationsMixinGenerated): - @overload - def translate( - self, - body: List[str], - *, - to_language: List[str], - client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long - """Translate Text. - - Translate Text. - - :param body: Defines the content of the request. Required. - :type body: list[str] - :keyword to_language: Specifies the language of the output text. The target language must be one of the - supported languages included - in the translation scope. For example, use to_language=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to_language=de&to_language=it to translate to German and Italian. Required. - :paramtype to_language: list[str] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TranslatedTextItem - :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - str" # Text to translate. Required. - ] - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] - """ - - @overload - def translate( - self, - body: List[_models.InputTextItem], - *, - to_language: List[str], - client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long - """Translate Text. - - Translate Text. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword to_language: Specifies the language of the output text. The target language must be one of the - supported languages included - in the translation scope. For example, use to_language=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to_language=de&to_language=it to translate to German and Italian. Required. - :paramtype to_language: list[str] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TranslatedTextItem - :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] - """ - - @overload - def translate( - self, - body: IO[bytes], - *, - to_language: List[str], - client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long - """Translate Text. - - Translate Text. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword to_language: Specifies the language of the output text. The target language must be one of the - supported languages included - in the translation scope. For example, use to_language=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to_language=de&to_language=it to translate to German and Italian. Required. - :paramtype to_language: list[str] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TranslatedTextItem - :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] - """ - - def translate( # pyright: ignore[reportIncompatibleMethodOverride] - self, - body: Union[List[str], List[_models.InputTextItem], IO[bytes]], - *, - to_language: List[str], - client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, - **kwargs: Any - ) -> List[_models.TranslatedTextItem]: - request_body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(body, list) and all(isinstance(item, str) for item in body): - input_text_items: List[_models.InputTextItem] = [] - for text in body: - input_text_items.append(_models.InputTextItem(text=cast(str, text))) - request_body = input_text_items - else: - request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) - - return super().translate( - body=request_body, - to_language=to_language, - client_trace_id=client_trace_id, - from_language=from_language, - text_type=text_type, - category=category, - profanity_action=profanity_action, - profanity_marker=profanity_marker, - include_alignment=include_alignment, - include_sentence_length=include_sentence_length, - suggested_from=suggested_from, - from_script=from_script, - to_script=to_script, - allow_fallback=allow_fallback, - **kwargs - ) - - @overload - def transliterate( - self, - body: List[str], - *, - language: str, - from_script: str, - to_script: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TransliteratedText]: - """Transliterate Text. - - Transliterate Text. - - :param body: Defines the content of the request. Required. - :type body: list[str] - :keyword language: Specifies the language of the text to convert from one script to another. - Possible languages are listed in the transliteration scope obtained by querying the service - for its supported languages. Required. - :paramtype language: str - :keyword from_script: Specifies the script used by the input text. Look up supported languages - using the transliteration scope, - to find input scripts available for the selected language. Required. - :paramtype from_script: str - :keyword to_script: Specifies the output script. Look up supported languages using the - transliteration scope, to find output - scripts available for the selected combination of input language and input script. Required. - :paramtype to_script: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TransliteratedText - :rtype: list[~azure.ai.translation.text.models.TransliteratedText] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] - """ - - @overload - def transliterate( - self, - body: List[_models.InputTextItem], - *, - language: str, - from_script: str, - to_script: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TransliteratedText]: - """Transliterate Text. - - Transliterate Text. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword language: Specifies the language of the text to convert from one script to another. - Possible languages are listed in the transliteration scope obtained by querying the service - for its supported languages. Required. - :paramtype language: str - :keyword from_script: Specifies the script used by the input text. Look up supported languages - using the transliteration scope, - to find input scripts available for the selected language. Required. - :paramtype from_script: str - :keyword to_script: Specifies the output script. Look up supported languages using the - transliteration scope, to find output - scripts available for the selected combination of input language and input script. Required. - :paramtype to_script: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TransliteratedText - :rtype: list[~azure.ai.translation.text.models.TransliteratedText] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] - """ - - @overload - def transliterate( - self, - body: IO[bytes], - *, - language: str, - from_script: str, - to_script: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TransliteratedText]: - """Transliterate Text. - - Transliterate Text. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword language: Specifies the language of the text to convert from one script to another. - Possible languages are listed in the transliteration scope obtained by querying the service - for its supported languages. Required. - :paramtype language: str - :keyword from_script: Specifies the script used by the input text. Look up supported languages - using the transliteration scope, - to find input scripts available for the selected language. Required. - :paramtype from_script: str - :keyword to_script: Specifies the output script. Look up supported languages using the - transliteration scope, to find output - scripts available for the selected combination of input language and input script. Required. - :paramtype to_script: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TransliteratedText - :rtype: list[~azure.ai.translation.text.models.TransliteratedText] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] - """ - - def transliterate( # pyright: ignore[reportIncompatibleMethodOverride] - self, - body: Union[List[str], List[_models.InputTextItem], IO[bytes]], - *, - language: str, - from_script: str, - to_script: str, - client_trace_id: Optional[str] = None, - **kwargs: Any - ) -> List[_models.TransliteratedText]: - request_body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(body, list) and all(isinstance(item, str) for item in body): - input_text_items: List[_models.InputTextItem] = [] - for text in body: - input_text_items.append(_models.InputTextItem(text=cast(str, text))) - request_body = input_text_items - else: - request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) - - return super().transliterate( - body=request_body, - language=language, - from_script=from_script, - to_script=to_script, - client_trace_id=client_trace_id, - **kwargs - ) - - @overload - def find_sentence_boundaries( - self, - body: List[str], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: list[str] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - @overload - def find_sentence_boundaries( - self, - body: List[_models.InputTextItem], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - @overload - def find_sentence_boundaries( - self, - body: IO[bytes], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - def find_sentence_boundaries( # pyright: ignore[reportIncompatibleMethodOverride] - self, - body: Union[List[str], List[_models.InputTextItem], IO[bytes]], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - request_body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(body, list) and all(isinstance(item, str) for item in body): - input_text_items: List[_models.InputTextItem] = [] - for text in body: - input_text_items.append(_models.InputTextItem(text=cast(str, text))) - request_body = input_text_items - - else: - request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) - - return super().find_sentence_boundaries( - body=request_body, language=language, script=script, client_trace_id=client_trace_id, **kwargs - ) - - @overload - def lookup_dictionary_entries( - self, - body: List[str], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: list[str] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "score": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - @overload - def lookup_dictionary_entries( - self, - body: List[_models.InputTextItem], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "score": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - @overload - def lookup_dictionary_entries( - self, - body: IO[bytes], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "score": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - def lookup_dictionary_entries( # pyright: ignore[reportIncompatibleMethodOverride] - self, - body: Union[List[str], List[_models.InputTextItem], IO[bytes]], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - request_body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(body, list) and all(isinstance(item, str) for item in body): - input_text_items: List[_models.InputTextItem] = [] - for text in body: - input_text_items.append(_models.InputTextItem(text=cast(str, text))) - request_body = input_text_items - else: - request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) - - return super().lookup_dictionary_entries( - body=request_body, - from_language=from_language, - to_language=to_language, - client_trace_id=client_trace_id, - **kwargs - ) - +from typing import List -__all__: List[str] = [ - "TextTranslationClientOperationsMixin" -] # 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-text/azure/ai/translation/text/_patch.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_patch.py index 104e2adda4ba..8bcb627aa475 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_patch.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_patch.py @@ -1,18 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint: disable=C4717, C4722, C4748 +# 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. -from typing import Optional, Any, overload -from azure.core.pipeline import PipelineRequest -from azure.core.pipeline.policies import SansIOHTTPPolicy, BearerTokenCredentialPolicy, AzureKeyCredentialPolicy -from azure.core.credentials import TokenCredential, AzureKeyCredential +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List -from ._client import TextTranslationClient as ServiceClientGenerated - -DEFAULT_ENTRA_ID_SCOPE = "https://cognitiveservices.azure.com" -DEFAULT_SCOPE = "/.default" +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): @@ -22,181 +19,3 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ - - -class TranslatorAuthenticationPolicy(SansIOHTTPPolicy): - """Translator Authentication Policy. Adds both authentication headers that are required. - Ocp-Apim-Subscription-Region header contains region of the Translator resource. - Ocp-Apim-Subscription-Key header contains API key of the Translator resource. - """ - - def __init__(self, credential: AzureKeyCredential, region: str): - self.credential = credential - self.region = region - - def on_request(self, request: PipelineRequest) -> None: - request.http_request.headers["Ocp-Apim-Subscription-Key"] = self.credential.key - request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.region - - -class TranslatorEntraIdAuthenticationPolicy(BearerTokenCredentialPolicy): - """Translator EntraId Authentication Policy. Adds headers that are required by Translator Service - when global endpoint is used with Entra Id policy. - Ocp-Apim-Subscription-Region header contains region of the Translator resource. - Ocp-Apim-ResourceId header contains Azure resource Id - Translator resource. - - :param credential: Translator Entra Id Credentials used to access Translator Resource for global endpoint. - :type credential: ~azure.core.credentials.TokenCredential - :keyword str region: Used for National Clouds. - :keyword str resource_id: Used with both a TokenCredential combined with a region. - :keyword str audience: Scopes of the credentials. - """ - - def __init__( - self, credential: TokenCredential, resource_id: str, region: str, audience: str, **kwargs: Any - ) -> None: - super(TranslatorEntraIdAuthenticationPolicy, self).__init__(credential, audience, **kwargs) - self.resource_id = resource_id - self.region = region - self.translator_credential = credential - - def on_request(self, request: PipelineRequest) -> None: - request.http_request.headers["Ocp-Apim-ResourceId"] = self.resource_id - request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.region - super().on_request(request) - - -def get_translation_endpoint(endpoint, api_version): - if not endpoint: - endpoint = "https://api.cognitive.microsofttranslator.com" - - translator_endpoint: str = "" - if "cognitiveservices" in endpoint: - translator_endpoint = endpoint + "/translator/text/v" + api_version - else: - translator_endpoint = endpoint - - return translator_endpoint - -def is_cognitive_services_scope(audience: str) -> bool: - if "microsofttranslator" in audience: - return True - - return False - - -def set_authentication_policy(credential, kwargs): - if isinstance(credential, AzureKeyCredential): - if not kwargs.get("authentication_policy"): - if kwargs.get("region"): - kwargs["authentication_policy"] = TranslatorAuthenticationPolicy(credential, kwargs["region"]) - else: - kwargs["authentication_policy"] = AzureKeyCredentialPolicy( - name="Ocp-Apim-Subscription-Key", credential=credential - ) - elif hasattr(credential, "get_token"): - if not kwargs.get("authentication_policy"): - if kwargs.get("region") and kwargs.get("resource_id"): - scope = kwargs.pop("audience", DEFAULT_ENTRA_ID_SCOPE).rstrip("/").rstrip(DEFAULT_SCOPE) + DEFAULT_SCOPE - kwargs["authentication_policy"] = TranslatorEntraIdAuthenticationPolicy( - credential, - kwargs["resource_id"], - kwargs["region"], - scope, - ) - else: - if kwargs.get("resource_id") or kwargs.get("region"): - raise ValueError( - """Both 'resource_id' and 'region' must be provided with a TokenCredential for - regional resource authentication.""" - ) - scope: str = kwargs.pop("audience", DEFAULT_ENTRA_ID_SCOPE) - if not is_cognitive_services_scope(scope): - scope = scope.rstrip("/").rstrip(DEFAULT_SCOPE) + DEFAULT_SCOPE - - kwargs["authentication_policy"] = BearerTokenCredentialPolicy( - credential, scope - ) - - -class TextTranslationClient(ServiceClientGenerated): - """Text translation is a cloud-based REST API feature of the Translator service that uses neural - machine translation technology to enable quick and accurate source-to-target text translation - in real time across all supported languages. - - The following methods are supported by the Text Translation feature: - - Languages. Returns a list of languages supported by Translate, Transliterate, and Dictionary - Lookup operations. - - Translate. Renders single source-language text to multiple target-language texts with a single - request. - - Transliterate. Converts characters or letters of a source language to the corresponding - characters or letters of a target language. - - Detect. Returns the source code language code and a boolean variable denoting whether the - detected language is supported for text translation and transliteration. - - Dictionary lookup. Returns equivalent words for the source term in the target language. - - Dictionary example Returns grammatical structure and context examples for the source term and - target term pair. - - Combinations of endpoint and credential values: - str + AzureKeyCredential - used custom domain translator endpoint - str + AzureKeyCredential + Region - used for global translator endpoint - str + TokenCredential - used for regional endpoint with token authentication - str + None - used with text translation on-prem container - None + AzureKeyCredential - used for global translator endpoint with global Translator resource - None + TokenCredential - general translator endpoint with token authentication - None + TokenCredential + Region - general translator endpoint with regional Translator resource - - :keyword str endpoint: Supported Text Translation endpoints (protocol and hostname, for example: - https://api.cognitive.microsofttranslator.com). If not provided, global translator endpoint will be used. - :keyword credential: Credential used to authenticate with the Translator service - :paramtype credential: Union[AzureKeyCredential, TokenCredential] - :keyword str region: Used for National Clouds. - :keyword str resource_id: Used with both a TokenCredential combined with a region. - :keyword str audience: Scopes of the credentials. - :keyword str api_version: Default value is "3.0". Note that overriding this default value may - result in unsupported behavior. - """ - - @overload - def __init__( - self, - *, - credential: TokenCredential, - region: Optional[str] = None, - endpoint: Optional[str] = None, - resource_id: Optional[str] = None, - audience: Optional[str] = None, - api_version: str = "3.0", - **kwargs - ): ... - - @overload - def __init__( - self, - *, - credential: AzureKeyCredential, - region: Optional[str] = None, - endpoint: Optional[str] = None, - api_version: str = "3.0", - **kwargs - ): ... - - @overload - def __init__(self, *, endpoint: str, api_version: str = "3.0", **kwargs): ... - - def __init__(self, **kwargs): - api_version = kwargs.get("api_version", "3.0") - set_authentication_policy(kwargs.get("credential"), kwargs) - translation_endpoint = get_translation_endpoint( - kwargs.pop("endpoint", "https://api.cognitive.microsofttranslator.com"), api_version - ) - super().__init__(endpoint=translation_endpoint, api_version=api_version, **kwargs) - - -__all__ = ["TextTranslationClient"] diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_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-text/azure/ai/translation/text/_model_base.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/model_base.py similarity index 62% rename from sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_model_base.py rename to sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/model_base.py index 5cf70733404d..49d5c7259389 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_model_base.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/model_base.py @@ -1,10 +1,12 @@ +# pylint: disable=too-many-lines # 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, arguments-differ, signature-differs, broad-except +# pylint: disable=protected-access, broad-except import copy import calendar @@ -19,6 +21,8 @@ import email.utils 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 @@ -26,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"] @@ -123,7 +122,7 @@ def _serialize_datetime(o, format: typing.Optional[str] = None): def _is_readonly(p): try: - return p._visibility == ["read"] # pylint: disable=protected-access + return p._visibility == ["read"] except AttributeError: return False @@ -286,6 +285,12 @@ def _deserialize_decimal(attr): return decimal.Decimal(str(attr)) +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + _DESERIALIZE_MAPPING = { datetime: _deserialize_datetime, date: _deserialize_date, @@ -307,9 +312,11 @@ def _deserialize_decimal(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) - return _DESERIALIZE_MAPPING.get(annotation) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore def _get_type_alias_type(module_name: str, alias_name: str): @@ -337,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 @@ -363,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) @@ -441,6 +495,10 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m return float(o) if isinstance(o, enum.Enum): return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o try: # First try datetime.datetime return _serialize_datetime(o, format) @@ -471,11 +529,16 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return value if rf._is_model: return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) return _serialize(value, rf._format) class Model(_MyMutableMapping): _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: typing.Set[str] = set() def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: class_name = self.__class__.__name__ @@ -486,10 +549,58 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: for rest_field in self._attr_to_rest_field.values() if rest_field._default is not _UNSET } - if args: - dict_to_pass.update( - {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} - ) + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) else: non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] if non_attr_kwargs: @@ -507,55 +618,70 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: def copy(self) -> "Model": return Model(self.__dict__) - def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: # pylint: disable=unused-argument - # we know the last three classes in mro are going to be 'Model', 'dict', and 'object' - mros = cls.__mro__[:-3][::-1] # ignore model, dict, and object parents, and reverse the mro order - attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property - k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") - } - annotations = { - k: v - for mro_class in mros - if hasattr(mro_class, "__annotations__") # pylint: disable=no-member - for k, v in mro_class.__annotations__.items() # pylint: disable=no-member - } - for attr, rf in attr_to_rest_field.items(): - rf._module = cls.__module__ - if not rf._type: - rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) - if not rf._rest_name_input: - rf._rest_name_input = attr - cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items()) - - return super().__new__(cls) # pylint: disable=no-value-for-parameter + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + 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) def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: for base in cls.__bases__: - if hasattr(base, "__mapping__"): # pylint: disable=no-member - base.__mapping__[discriminator or cls.__name__] = cls # type: ignore # pylint: disable=no-member + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore @classmethod - def _get_discriminator(cls, exist_discriminators) -> typing.Optional[str]: + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: for v in cls.__dict__.values(): - if ( - isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators - ): # pylint: disable=protected-access - return v._rest_name # pylint: disable=protected-access + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v return None @classmethod def _deserialize(cls, data, exist_discriminators): - if not hasattr(cls, "__mapping__"): # pylint: disable=no-member + if not hasattr(cls, "__mapping__"): return cls(data) discriminator = cls._get_discriminator(exist_discriminators) - exist_discriminators.append(discriminator) - mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) # pyright: ignore # pylint: disable=no-member - if mapped_cls == cls: + if discriminator is None: return cls(data) - return mapped_cls._deserialize(data, exist_discriminators) # pylint: disable=protected-access + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + 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 # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]: - """Return a dict that can be JSONify using json.dump. + """Return a dict that can be turned into json using json.dump. :keyword bool exclude_readonly: Whether to remove the readonly properties. :returns: A dict JSON compatible object @@ -563,6 +689,7 @@ def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing. """ result = {} + readonly_props = [] if exclude_readonly: readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] for k, v in self.items(): @@ -617,6 +744,8 @@ def _deserialize_dict( ): if obj is None: return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} @@ -637,6 +766,8 @@ def _deserialize_sequence( ): if obj is None: return obj + if isinstance(obj, ET.Element): + obj = list(obj) return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) @@ -647,12 +778,12 @@ def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.An ) -def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, R0912 +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-branches annotation: typing.Any, module: typing.Optional[str], rf: typing.Optional["_RestField"] = None, ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: - if not annotation or annotation in [int, float]: + if not annotation: return None # is it a type alias? @@ -667,7 +798,7 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, 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): @@ -727,7 +858,6 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, try: if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore if len(annotation.__args__) > 1: # pyright: ignore - entry_deserializers = [ _get_deserialize_callable_from_annotation(dt, module, rf) for dt in annotation.__args__ # pyright: ignore @@ -762,12 +892,23 @@ def _deserialize_default( def _deserialize_with_callable( deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], value: typing.Any, -): +): # pylint: disable=too-many-return-statements try: if value is None or isinstance(value, _Null): return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None if deserializer is None: return value + if deserializer in [int, float, bool]: + return deserializer(value) if isinstance(deserializer, CaseInsensitiveEnumMeta): try: return deserializer(value) @@ -797,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, @@ -808,6 +978,7 @@ def __init__( default: typing.Any = _UNSET, format: typing.Optional[str] = None, is_multipart_file_input: bool = False, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, ): self._type = type self._rest_name_input = name @@ -818,6 +989,7 @@ def __init__( self._default = default self._format = format self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} @property def _class_type(self) -> typing.Any: @@ -868,6 +1040,7 @@ def rest_field( default: typing.Any = _UNSET, format: typing.Optional[str] = None, is_multipart_file_input: bool = False, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, ) -> typing.Any: return _RestField( name=name, @@ -876,6 +1049,7 @@ def rest_field( default=default, format=format, is_multipart_file_input=is_multipart_file_input, + xml=xml, ) @@ -883,5 +1057,176 @@ def rest_discriminator( *, name: typing.Optional[str] = None, type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[typing.List[str]] = None, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[typing.Dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, typing.List[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[typing.Dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element(tag, prefix=None, ns=None): + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, ) -> typing.Any: - return _RestField(name=name, type=type, is_discriminator=True) + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: typing.Dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: typing.List[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_serialization.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/serialization.py similarity index 82% rename from sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_serialization.py rename to sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/serialization.py index 2f781d740827..eb86ea23c965 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_serialization.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/serialization.py @@ -1,30 +1,12 @@ +# 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. # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -48,11 +30,8 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, List, - Mapping, ) try: @@ -62,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] @@ -91,6 +70,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -112,7 +93,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -144,6 +125,8 @@ def _json_attemp(data): # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -153,6 +136,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -177,80 +165,31 @@ 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.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - 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): - 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"(? None: self.additional_properties: Optional[Dict[str, Any]] = {} - for k in kwargs: + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -298,13 +244,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) def __str__(self) -> str: @@ -324,7 +280,11 @@ def is_xml_model(cls) -> bool: @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -344,7 +304,9 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) def as_dict( self, @@ -378,12 +340,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -393,30 +358,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> 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 + :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 @@ -424,9 +390,11 @@ def from_dict( and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :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 + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -446,21 +414,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -499,11 +471,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -538,7 +512,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -558,13 +532,16 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None): self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - def _serialize(self, target_obj, data_type=None, **kwargs): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :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) keep_readonly = kwargs.get("keep_readonly", False) @@ -590,12 +567,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": @@ -631,7 +610,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. if "name" not in getattr(orig_attr, "_xml_map", {}): splitted_tag = new_attr.tag.split("}") if len(splitted_tag) == 2: # Namespace @@ -662,17 +642,17 @@ def _serialize(self, target_obj, data_type=None, **kwargs): except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) raise SerializationError(msg) from err - else: - return serialized + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :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 """ # Just in case this is a dict @@ -701,7 +681,7 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: raise SerializationError("Unable to build a model: " + str(err)) from err @@ -710,11 +690,13 @@ def body(self, data, data_type, **kwargs): def url(self, name, data, data_type, **kwargs): """Serialize data intended for a URL path. - :param data: The data to be serialized. + :param str name: The name of the URL path parameter. + :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 + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -726,21 +708,20 @@ def url(self, name, data, data_type, **kwargs): output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output def query(self, name, data, data_type, **kwargs): """Serialize data intended for a URL query. - :param data: The data to be serialized. + :param str name: The name of the query parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :keyword bool skip_quote: Whether to skip quote the serialized result. - Defaults to False. :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: # Treat the list aside, since we don't want to encode the div separator @@ -757,19 +738,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :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: if data_type in ["[str]"]: @@ -778,21 +760,20 @@ def header(self, name, data, data_type, **kwargs): output = self.serialize_data(data, data_type, **kwargs) if data_type == "bool": output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :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 """ if data is None: raise ValueError("No value for given attribute") @@ -803,7 +784,7 @@ def serialize_data(self, data, data_type, **kwargs): if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if data_type in self.serialize_type: return self.serialize_type[data_type](data, **kwargs) # If dependencies is empty, try with current data class @@ -819,11 +800,10 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." raise SerializationError(msg.format(data, data_type)) from err - else: - return self._serialize(data, **kwargs) + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -839,23 +819,26 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + return eval(data_type)(data) # nosec # pylint: disable=eval-used @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -869,8 +852,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -880,15 +862,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. - :keyword bool do_quote: Whether to quote the serialized result of each iterable element. Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -943,9 +923,8 @@ def serialize_dict(self, attr, dict_type, **kwargs): :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. :rtype: dict + :return: serialized dictionary """ serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} @@ -969,7 +948,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -977,6 +956,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -1001,7 +981,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1032,56 +1012,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: for enum_value in enum_obj: # type: ignore if enum_value.value.lower() == str(attr).lower(): return enum_value.value error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1089,11 +1074,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1103,30 +1089,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1139,12 +1127,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :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): attr = isodate.parse_datetime(attr) @@ -1170,13 +1159,14 @@ def serialize_iso(attr, **kwargs): raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into IntTime format. This is represented as seconds. :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): return attr @@ -1184,11 +1174,11 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data @@ -1209,7 +1199,9 @@ def rest_key_extractor(attr, attr_desc, data): return working_data.get(key) -def rest_key_case_insensitive_extractor(attr, attr_desc, data): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1230,17 +1222,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1277,7 +1281,7 @@ def _extract_name_from_internal_type(internal_type): return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1329,22 +1333,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # 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( - xml_name - ) + # 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( + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1352,7 +1355,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1361,9 +1364,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1399,27 +1402,29 @@ 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 """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree :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 """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1438,13 +1443,13 @@ def _deserialize(self, target_obj, data): if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1474,9 +1479,8 @@ def _deserialize(self, target_obj, data): except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore raise DeserializationError(msg) from err - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) def _build_additional_properties(self, attribute_map, data): if not self.additional_properties_detection: @@ -1503,6 +1507,8 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None @@ -1514,7 +1520,7 @@ def _classify_target(self, target, data): return target, target try: - target = target._classify(data, self.dependencies) # type: ignore + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1529,10 +1535,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1550,10 +1558,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1577,24 +1587,35 @@ def _unpack_content(raw_data, content_type=None): def _instantiate_model(self, response, attrs, additional_properties=None): """Instantiate a response model passing in deserialized args. - :param response: The response model class. - :param d_attrs: The deserialized response attributes. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] + readonly = [ + 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() # 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 - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1603,15 +1624,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :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 """ if data is None: return data @@ -1625,7 +1647,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1645,14 +1671,14 @@ def deserialize_data(self, data, data_type): msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) raise DeserializationError(msg) from err - else: - return self._deserialize(obj_type, data) + return self._deserialize(obj_type, data) def deserialize_iter(self, attr, iter_type): """Deserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1669,6 +1695,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1679,13 +1706,14 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :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 @@ -1718,11 +1746,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1730,8 +1757,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :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 @@ -1741,24 +1769,23 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, str): + if isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if attr.lower() in ["false", "0"]: return False raise TypeError("Invalid boolean value: {}".format(attr)) if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec + return eval(data_type)(attr) # nosec # pylint: disable=eval-used @staticmethod def deserialize_unicode(data): @@ -1766,6 +1793,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1779,8 +1807,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1792,6 +1819,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1802,9 +1830,9 @@ def deserialize_enum(data, enum_obj): # Workaround. We might consider remove it in the future. try: return list(enum_obj.__members__.values())[data] - except IndexError: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1820,8 +1848,9 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :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 @@ -1832,8 +1861,9 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :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 @@ -1847,8 +1877,9 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text @@ -1863,8 +1894,9 @@ def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :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 @@ -1875,8 +1907,9 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :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 @@ -1885,16 +1918,16 @@ def deserialize_duration(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." raise DeserializationError(msg) from err - else: - return duration + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :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 @@ -1908,8 +1941,9 @@ def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :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 @@ -1922,31 +1956,32 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :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) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :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 @@ -1974,8 +2009,7 @@ def deserialize_iso(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_unix(attr): @@ -1983,8 +2017,9 @@ def deserialize_unix(attr): This is represented as seconds. :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 @@ -1994,5 +2029,4 @@ def deserialize_unix(attr): except ValueError as err: msg = "Cannot deserialize to unix datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_vendor.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/utils.py similarity index 81% rename from sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_vendor.py rename to sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/utils.py index 6033fc36a5d1..927adb7c8ae2 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_vendor.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_utils/utils.py @@ -6,24 +6,23 @@ # -------------------------------------------------------------------------- from abc import ABC -from typing import Optional, TYPE_CHECKING +from typing import Generic, Optional, TYPE_CHECKING, TypeVar from azure.core import MatchConditions -from ._configuration import TextTranslationClientConfiguration - if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import PipelineClient + from .serialization import Deserializer, Serializer + - from ._serialization import Deserializer, Serializer +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") -class TextTranslationClientMixinABC(ABC): +class ClientMixinABC(ABC, Generic[TClient, TConfig]): """DO NOT use this class. It is for internal typing use only.""" - _client: "PipelineClient" - _config: TextTranslationClientConfiguration + _client: TClient + _config: TConfig _serialize: "Serializer" _deserialize: "Deserializer" diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_version.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_version.py index 8e44259d1a18..be71c81bd282 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_version.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/__init__.py index 0d279090135b..2887e29b8c63 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/__init__.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/__init__.py @@ -5,15 +5,25 @@ # 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 TextTranslationClient +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import +from ._client import TextTranslationClient # 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__ = [ "TextTranslationClient", ] - +__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-text/azure/ai/translation/text/aio/_client.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_client.py index 9b7f5d746e2f..bd1e6a22761f 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_client.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_client.py @@ -8,17 +8,18 @@ from copy import deepcopy from typing import Any, Awaitable +from typing_extensions import Self from azure.core import AsyncPipelineClient 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 TextTranslationClientConfiguration from ._operations import TextTranslationClientOperationsMixin -class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword +class TextTranslationClient(TextTranslationClientOperationsMixin): """Text translation is a cloud-based REST API feature of the Translator service that uses neural machine translation technology to enable quick and accurate source-to-target text translation in real time across all supported languages. @@ -37,16 +38,12 @@ class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: di Detect. Returns the source code language code and a boolean variable denoting whether the detected language is supported for text translation and transliteration. - Dictionary lookup. Returns equivalent words for the source term in the target language. - - Dictionary example Returns grammatical structure and context examples for the source term and - target term pair. - :param endpoint: Supported Text Translation endpoints (protocol and hostname, for example: - https://api.cognitive.microsofttranslator.com). Required. + `https://api.cognitive.microsofttranslator.com + `_). Required. :type endpoint: str - :keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that - overriding this default value may result in unsupported behavior. + :keyword api_version: Mandatory API version parameter. Default value is "2025-05-01-preview". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ @@ -55,6 +52,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential ) -> None: _endpoint = "{Endpoint}" self._config = TextTranslationClientConfiguration(endpoint=endpoint, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -109,7 +107,7 @@ def send_request( async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "TextTranslationClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_configuration.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_configuration.py index 1f4d5c1f10f9..f49ca327a900 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_configuration.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_configuration.py @@ -13,22 +13,23 @@ from .._version import VERSION -class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for TextTranslationClient. Note that all parameters used to create this instance are saved as instance attributes. :param endpoint: Supported Text Translation endpoints (protocol and hostname, for example: - https://api.cognitive.microsofttranslator.com). Required. + `https://api.cognitive.microsofttranslator.com + `_). Required. :type endpoint: str - :keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that - overriding this default value may result in unsupported behavior. + :keyword api_version: Mandatory API version parameter. Default value is "2025-05-01-preview". + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "3.0") + api_version: str = kwargs.pop("api_version", "2025-05-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/__init__.py index 47ae0af6503a..dbcf8750add3 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/__init__.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/__init__.py @@ -5,14 +5,21 @@ # 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 TextTranslationClientOperationsMixin +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import +from ._operations import TextTranslationClientOperationsMixin # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "TextTranslationClientOperationsMixin", ] - +__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-text/azure/ai/translation/text/aio/_operations/_operations.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_operations.py index 5b8d0cb5d9b5..04cc1218c701 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_operations.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines,too-many-statements +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,13 +6,12 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: disable=R0914 +from collections.abc import MutableMapping from io import IOBase import json -import sys -from typing import Any, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload -from azure.core import MatchConditions +from azure.core import AsyncPipelineClient, MatchConditions from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,6 +19,8 @@ ResourceModifiedError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -28,26 +29,22 @@ from azure.core.utils import case_insensitive_dict from ... import models as _models -from ..._model_base import SdkJSONEncoder, _deserialize from ..._operations._operations import ( - build_text_translation_find_sentence_boundaries_request, build_text_translation_get_supported_languages_request, - build_text_translation_lookup_dictionary_entries_request, - build_text_translation_lookup_dictionary_examples_request, build_text_translation_translate_request, build_text_translation_transliterate_request, ) -from .._vendor import TextTranslationClientMixinABC +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.utils import ClientMixinABC +from .._configuration import TextTranslationClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class TextTranslationClientOperationsMixin(TextTranslationClientMixinABC): +class TextTranslationClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], TextTranslationClientConfiguration] +): @distributed_trace_async async def get_supported_languages( @@ -60,7 +57,6 @@ async def get_supported_languages( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.GetSupportedLanguagesResult: - # pylint: disable=line-too-long """Gets the set of languages currently supported by other operations of the Translator. Gets the set of languages currently supported by other operations of the Translator. @@ -69,7 +65,7 @@ async def get_supported_languages( value is None. :paramtype client_trace_id: str :keyword scope: A comma-separated list of names defining the group of languages to return. - Allowed group names are: ``translation``\\ , ``transliteration`` and ``dictionary``. + Allowed group names are: ``translation``, ``transliteration`` and ``dictionary``. If no scope is given, then all groups are returned, which is equivalent to passing ``scope=translation,transliteration,dictionary``. To decide which set of supported languages is appropriate for your scenario, see the description of the `response object @@ -95,88 +91,8 @@ async def get_supported_languages( MutableMapping :rtype: ~azure.ai.translation.text.models.GetSupportedLanguagesResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "dictionary": { - "str": { - "dir": "str", # Directionality, which is rtl for - right-to-left languages or ltr for left-to-right languages. Required. - Known values are: "ltr" and "rtl". - "name": "str", # Display name of the language in the locale - requested via Accept-Language header. Required. - "nativeName": "str", # Display name of the language in the - locale native for this language. Required. - "translations": [ - { - "code": "str", # Language code identifying - the target language. Required. - "dir": "str", # Directionality, which is rtl - for right-to-left languages or ltr for left-to-right languages. - Required. Known values are: "ltr" and "rtl". - "name": "str", # Display name of the - language in the locale requested via Accept-Language header. - Required. - "nativeName": "str" # Display name of the - language in the locale native for this language. Required. - } - ] - } - }, - "translation": { - "str": { - "dir": "str", # Directionality, which is rtl for - right-to-left languages or ltr for left-to-right languages. Required. - Known values are: "ltr" and "rtl". - "name": "str", # Display name of the language in the locale - requested via Accept-Language header. Required. - "nativeName": "str" # Display name of the language in the - locale native for this language. Required. - } - }, - "transliteration": { - "str": { - "name": "str", # Display name of the language in the locale - requested via Accept-Language header. Required. - "nativeName": "str", # Display name of the language in the - locale native for this language. Required. - "scripts": [ - { - "code": "str", # Code identifying the - script. Required. - "dir": "str", # Directionality, which is rtl - for right-to-left languages or ltr for left-to-right languages. - Required. Known values are: "ltr" and "rtl". - "name": "str", # Display name of the script - in the locale requested via Accept-Language header. Required. - "nativeName": "str", # Display name of the - language in the locale native for the language. Required. - "toScripts": [ - { - "code": "str", # Code - identifying the script. Required. - "dir": "str", # - Directionality, which is rtl for right-to-left languages - or ltr for left-to-right languages. Required. Known - values are: "ltr" and "rtl". - "name": "str", # Display - name of the script in the locale requested via - Accept-Language header. Required. - "nativeName": "str" # - Display name of the language in the locale native for the - language. Required. - } - ] - } - ] - } - } - } """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -219,9 +135,12 @@ async def get_supported_languages( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ErrorResponse, response.json()) + error = _failsafe_deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -241,177 +160,27 @@ async def get_supported_languages( @overload async def translate( self, - body: List[_models.InputTextItem], + body: List[_models.TranslateBody], *, - to_language: List[str], client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, content_type: str = "application/json", **kwargs: Any ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long """Translate Text. Translate Text. :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword to_language: Specifies the language of the output text. The target language must be - one of the supported languages included - in the translation scope. For example, use to=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to=de&to=it to translate to German and Italian. Required. - :paramtype to_language: list[str] + :type body: list[~azure.ai.translation.text.models.TranslateBody] :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default value is None. :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :return: list of TranslatedTextItem :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] """ @overload @@ -419,336 +188,50 @@ async def translate( self, body: IO[bytes], *, - to_language: List[str], client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, content_type: str = "application/json", **kwargs: Any ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long """Translate Text. Translate Text. :param body: Defines the content of the request. Required. :type body: IO[bytes] - :keyword to_language: Specifies the language of the output text. The target language must be - one of the supported languages included - in the translation scope. For example, use to=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to=de&to=it to translate to German and Italian. Required. - :paramtype to_language: list[str] :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default value is None. :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :return: list of TranslatedTextItem :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] """ @distributed_trace_async async def translate( self, - body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.TranslateBody], IO[bytes]], *, - to_language: List[str], client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, **kwargs: Any ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long """Translate Text. Translate Text. - :param body: Defines the content of the request. Is either a [InputTextItem] type or a + :param body: Defines the content of the request. Is either a [TranslateBody] type or a IO[bytes] type. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] - :keyword to_language: Specifies the language of the output text. The target language must be - one of the supported languages included - in the translation scope. For example, use to=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to=de&to=it to translate to German and Italian. Required. - :paramtype to_language: list[str] + :type body: list[~azure.ai.translation.text.models.TranslateBody] or IO[bytes] :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default value is None. :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool :return: list of TranslatedTextItem :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -770,19 +253,7 @@ async def translate( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_translate_request( - to_language=to_language, client_trace_id=client_trace_id, - from_language=from_language, - text_type=text_type, - category=category, - profanity_action=profanity_action, - profanity_marker=profanity_marker, - include_alignment=include_alignment, - include_sentence_length=include_sentence_length, - suggested_from=suggested_from, - from_script=from_script, - to_script=to_script, - allow_fallback=allow_fallback, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -803,9 +274,12 @@ async def translate( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ErrorResponse, response.json()) + error = _failsafe_deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -862,26 +336,6 @@ async def transliterate( :return: list of TransliteratedText :rtype: list[~azure.ai.translation.text.models.TransliteratedText] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] """ @overload @@ -923,19 +377,6 @@ async def transliterate( :return: list of TransliteratedText :rtype: list[~azure.ai.translation.text.models.TransliteratedText] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] """ @distributed_trace_async @@ -974,21 +415,8 @@ async def transliterate( :return: list of TransliteratedText :rtype: list[~azure.ai.translation.text.models.TransliteratedText] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1034,9 +462,12 @@ async def transliterate( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _deserialize(_models.ErrorResponse, response.json()) + error = _failsafe_deserialize(_models.ErrorResponse, response.json()) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1051,929 +482,3 @@ async def transliterate( return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - - @overload - async def find_sentence_boundaries( - self, - body: List[_models.InputTextItem], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - @overload - async def find_sentence_boundaries( - self, - body: IO[bytes], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - @distributed_trace_async - async def find_sentence_boundaries( - self, - body: Union[List[_models.InputTextItem], IO[bytes]], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Is either a [InputTextItem] type or a - IO[bytes] type. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _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[List[_models.BreakSentenceItem]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_text_translation_find_sentence_boundaries_request( - client_trace_id=client_trace_id, - language=language, - script=script, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - 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", False) - 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) - error = _deserialize(_models.ErrorResponse, response.json()) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["X-RequestId"] = self._deserialize("str", response.headers.get("X-RequestId")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(List[_models.BreakSentenceItem], response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def lookup_dictionary_entries( - self, - body: List[_models.InputTextItem], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "confidence": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - @overload - async def lookup_dictionary_entries( - self, - body: IO[bytes], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "confidence": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - @distributed_trace_async - async def lookup_dictionary_entries( - self, - body: Union[List[_models.InputTextItem], IO[bytes]], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Is either a [InputTextItem] type or a - IO[bytes] type. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "confidence": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _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[List[_models.DictionaryLookupItem]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_text_translation_lookup_dictionary_entries_request( - from_language=from_language, - to_language=to_language, - client_trace_id=client_trace_id, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - 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", False) - 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) - error = _deserialize(_models.ErrorResponse, response.json()) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["X-RequestId"] = self._deserialize("str", response.headers.get("X-RequestId")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(List[_models.DictionaryLookupItem], response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def lookup_dictionary_examples( - self, - body: List[_models.DictionaryExampleTextItem], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryExampleItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Examples. - - Lookup Dictionary Examples. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryExampleItem - :rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str", # Text to translate. Required. - "translation": "str" # A string specifying the translated text - previously returned by the Dictionary lookup operation. This should be the - value from the normalizedTarget field in the translations list of the - Dictionary lookup response. The service will return examples for the - specific source-target word-pair. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "examples": [ - { - "sourcePrefix": "str", # The string to concatenate - before the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceSuffix": "str", # The string to concatenate - after the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceTerm": "str", # A string equal to the actual - term looked up. The string is added with sourcePrefix and - sourceSuffix to form the complete example. Its value is separated so - it can be marked in a user interface, e.g., by bolding it. Required. - "targetPrefix": "str", # A string similar to - sourcePrefix but for the target. Required. - "targetSuffix": "str", # A string similar to - sourceSuffix but for the target. Required. - "targetTerm": "str" # A string similar to sourceTerm - but for the target. Required. - } - ], - "normalizedSource": "str", # A string giving the normalized form of - the source term. Generally, this should be identical to the value of the Text - field at the matching list index in the body of the request. Required. - "normalizedTarget": "str" # A string giving the normalized form of - the target term. Generally, this should be identical to the value of the - Translation field at the matching list index in the body of the request. - Required. - } - ] - """ - - @overload - async def lookup_dictionary_examples( - self, - body: IO[bytes], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryExampleItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Examples. - - Lookup Dictionary Examples. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryExampleItem - :rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "examples": [ - { - "sourcePrefix": "str", # The string to concatenate - before the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceSuffix": "str", # The string to concatenate - after the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceTerm": "str", # A string equal to the actual - term looked up. The string is added with sourcePrefix and - sourceSuffix to form the complete example. Its value is separated so - it can be marked in a user interface, e.g., by bolding it. Required. - "targetPrefix": "str", # A string similar to - sourcePrefix but for the target. Required. - "targetSuffix": "str", # A string similar to - sourceSuffix but for the target. Required. - "targetTerm": "str" # A string similar to sourceTerm - but for the target. Required. - } - ], - "normalizedSource": "str", # A string giving the normalized form of - the source term. Generally, this should be identical to the value of the Text - field at the matching list index in the body of the request. Required. - "normalizedTarget": "str" # A string giving the normalized form of - the target term. Generally, this should be identical to the value of the - Translation field at the matching list index in the body of the request. - Required. - } - ] - """ - - @distributed_trace_async - async def lookup_dictionary_examples( - self, - body: Union[List[_models.DictionaryExampleTextItem], IO[bytes]], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - **kwargs: Any - ) -> List[_models.DictionaryExampleItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Examples. - - Lookup Dictionary Examples. - - :param body: Defines the content of the request. Is either a [DictionaryExampleTextItem] type - or a IO[bytes] type. Required. - :type body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] or IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :return: list of DictionaryExampleItem - :rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "examples": [ - { - "sourcePrefix": "str", # The string to concatenate - before the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceSuffix": "str", # The string to concatenate - after the value of sourceTerm to form a complete example. Do not add - a space character, since it is already there when it should be. This - value may be an empty string. Required. - "sourceTerm": "str", # A string equal to the actual - term looked up. The string is added with sourcePrefix and - sourceSuffix to form the complete example. Its value is separated so - it can be marked in a user interface, e.g., by bolding it. Required. - "targetPrefix": "str", # A string similar to - sourcePrefix but for the target. Required. - "targetSuffix": "str", # A string similar to - sourceSuffix but for the target. Required. - "targetTerm": "str" # A string similar to sourceTerm - but for the target. Required. - } - ], - "normalizedSource": "str", # A string giving the normalized form of - the source term. Generally, this should be identical to the value of the Text - field at the matching list index in the body of the request. Required. - "normalizedTarget": "str" # A string giving the normalized form of - the target term. Generally, this should be identical to the value of the - Translation field at the matching list index in the body of the request. - Required. - } - ] - """ - error_map: MutableMapping[int, Type[HttpResponseError]] = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _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[List[_models.DictionaryExampleItem]] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_text_translation_lookup_dictionary_examples_request( - from_language=from_language, - to_language=to_language, - client_trace_id=client_trace_id, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - 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", False) - 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) - error = _deserialize(_models.ErrorResponse, response.json()) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["X-RequestId"] = self._deserialize("str", response.headers.get("X-RequestId")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(List[_models.DictionaryExampleItem], response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_patch.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_patch.py index 3506e20e8701..8bcb627aa475 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_patch.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_patch.py @@ -1,1367 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint: disable=C0302 - +# 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 Any, cast, IO, List, Optional, overload, Union -from ... import models as _models -from ._operations import TextTranslationClientOperationsMixin as TextTranslationClientOperationsMixinGenerated - - -class TextTranslationClientOperationsMixin(TextTranslationClientOperationsMixinGenerated): - @overload - async def translate( - self, - body: List[str], - *, - to_language: List[str], - client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long - """Translate Text. - - Translate Text. - - :param body: Defines the content of the request. Required. - :type body: list[str] - :keyword to_language: Specifies the language of the output text. The target language must be one of the - supported languages included - in the translation scope. For example, use to_language=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to_language=de&to_language=it to translate to German and Italian. Required. - :paramtype to_language: list[str] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TranslatedTextItem - :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - str" # Text to translate. Required. - ] - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] - """ - - @overload - async def translate( - self, - body: List[_models.InputTextItem], - *, - to_language: List[str], - client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long - """Translate Text. - - Translate Text. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword to_language: Specifies the language of the output text. The target language must be one of the - supported languages included - in the translation scope. For example, use to_language=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to_language=de&to_language=it to translate to German and Italian. Required. - :paramtype to_language: list[str] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TranslatedTextItem - :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] - """ - - @overload - async def translate( - self, - body: IO[bytes], - *, - to_language: List[str], - client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TranslatedTextItem]: - # pylint: disable=line-too-long - """Translate Text. - - Translate Text. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword to_language: Specifies the language of the output text. The target language must be one of the - supported languages included - in the translation scope. For example, use to_language=de to translate to German. - It's possible to translate to multiple languages simultaneously by repeating the parameter in - the query string. - For example, use to_language=de&to_language=it to translate to German and Italian. Required. - :paramtype to_language: list[str] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword from_language: Specifies the language of the input text. Find which languages are - available to translate from by - looking up supported languages using the translation scope. If the from parameter isn't - specified, - automatic language detection is applied to determine the source language. - - You must use the from parameter rather than autodetection when using the dynamic dictionary - feature. - Note: the dynamic dictionary feature is case-sensitive. Default value is None. - :paramtype from_language: str - :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any - HTML needs to be a well-formed, - complete element. Possible values are: plain (default) or html. Known values are: "Plain" and - "Html". Default value is None. - :paramtype text_type: str or ~azure.ai.translation.text.models.TextType - :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 profanity_action: Specifies how profanities should be treated in translations. - Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", - "Marked", and "Deleted". Default value is None. - :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction - :keyword profanity_marker: Specifies how profanities should be marked in translations. - Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". - Default value is None. - :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker - :keyword include_alignment: Specifies whether to include alignment projection from source text - to translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_alignment: bool - :keyword include_sentence_length: Specifies whether to include sentence boundaries for the - input text and the translated text. - Possible values are: true or false (default). Default value is None. - :paramtype include_sentence_length: bool - :keyword suggested_from: Specifies a fallback language if the language of the input text can't - be identified. - Language autodetection is applied when the from parameter is omitted. If detection fails, - the suggestedFrom language will be assumed. Default value is None. - :paramtype suggested_from: str - :keyword from_script: Specifies the script of the input text. Default value is None. - :paramtype from_script: str - :keyword to_script: Specifies the script of the translated text. Default value is None. - :paramtype to_script: 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. - - allowFallback=false specifies that the translation should only use systems trained for the - category specified - by the request. If a translation for language X to language Y requires chaining through a - pivot language E, - then all the systems in the chain (X → E and E → Y) will need to be custom and have the same - category. - If no system is found with the specific category, the request will return a 400 status code. - allowFallback=true - specifies that the service is allowed to fall back to a general system when a custom system - doesn't exist. Default value is None. - :paramtype allow_fallback: bool - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TranslatedTextItem - :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "translations": [ - { - "text": "str", # A string giving the translated - text. Required. - "to": "str", # A string representing the language - code of the target language. Required. - "alignment": { - "proj": "str" # Maps input text to - translated text. The alignment information is only provided when - the request parameter includeAlignment is true. Alignment is - returned as a string value of the following format: - [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the - languages, and space separates the words. One word may align - with zero, one, or multiple words in the other language, and the - aligned words may be non-contiguous. When no alignment - information is available, the alignment element will be empty. - Required. - }, - "sentLen": { - "srcSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the input text. The length - of the array is the number of sentences, and the values are - the length of each sentence. Required. - ], - "transSentLen": [ - 0 # An integer array representing - the lengths of the sentences in the translated text. The - length of the array is the number of sentences, and the - values are the length of each sentence. Required. - ] - }, - "transliteration": { - "script": "str", # A string specifying the - script used in the output. Required. - "text": "str" # A string which is the result - of converting the input string to the output script. Required. - } - } - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - }, - "sourceText": { - "text": "str" # Input text in the default script of the - source language. Required. - } - } - ] - """ - - async def translate( # pyright: ignore[reportIncompatibleMethodOverride] - self, - body: Union[List[str], List[_models.InputTextItem], IO[bytes]], - *, - to_language: List[str], - client_trace_id: Optional[str] = None, - from_language: Optional[str] = None, - text_type: Optional[Union[str, _models.TextType]] = None, - category: Optional[str] = None, - profanity_action: Optional[Union[str, _models.ProfanityAction]] = None, - profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None, - include_alignment: Optional[bool] = None, - include_sentence_length: Optional[bool] = None, - suggested_from: Optional[str] = None, - from_script: Optional[str] = None, - to_script: Optional[str] = None, - allow_fallback: Optional[bool] = None, - **kwargs: Any - ) -> List[_models.TranslatedTextItem]: - request_body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(body, list) and all(isinstance(item, str) for item in body): - input_text_items: List[_models.InputTextItem] = [] - for text in body: - input_text_items.append(_models.InputTextItem(text=cast(str, text))) - request_body = input_text_items - else: - request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) - - return await super().translate( - body=request_body, - to_language=to_language, - client_trace_id=client_trace_id, - from_language=from_language, - text_type=text_type, - category=category, - profanity_action=profanity_action, - profanity_marker=profanity_marker, - include_alignment=include_alignment, - include_sentence_length=include_sentence_length, - suggested_from=suggested_from, - from_script=from_script, - to_script=to_script, - allow_fallback=allow_fallback, - **kwargs - ) - - @overload - async def transliterate( - self, - body: List[str], - *, - language: str, - from_script: str, - to_script: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TransliteratedText]: - """Transliterate Text. - - Transliterate Text. - - :param body: Defines the content of the request. Required. - :type body: list[str] - :keyword language: Specifies the language of the text to convert from one script to another. - Possible languages are listed in the transliteration scope obtained by querying the service - for its supported languages. Required. - :paramtype language: str - :keyword from_script: Specifies the script used by the input text. Look up supported languages - using the transliteration scope, - to find input scripts available for the selected language. Required. - :paramtype from_script: str - :keyword to_script: Specifies the output script. Look up supported languages using the - transliteration scope, to find output - scripts available for the selected combination of input language and input script. Required. - :paramtype to_script: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TransliteratedText - :rtype: list[~azure.ai.translation.text.models.TransliteratedText] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] - """ - - @overload - async def transliterate( - self, - body: List[_models.InputTextItem], - *, - language: str, - from_script: str, - to_script: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TransliteratedText]: - """Transliterate Text. - - Transliterate Text. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword language: Specifies the language of the text to convert from one script to another. - Possible languages are listed in the transliteration scope obtained by querying the service - for its supported languages. Required. - :paramtype language: str - :keyword from_script: Specifies the script used by the input text. Look up supported languages - using the transliteration scope, - to find input scripts available for the selected language. Required. - :paramtype from_script: str - :keyword to_script: Specifies the output script. Look up supported languages using the - transliteration scope, to find output - scripts available for the selected combination of input language and input script. Required. - :paramtype to_script: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TransliteratedText - :rtype: list[~azure.ai.translation.text.models.TransliteratedText] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] - """ - - @overload - async def transliterate( - self, - body: IO[bytes], - *, - language: str, - from_script: str, - to_script: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.TransliteratedText]: - """Transliterate Text. - - Transliterate Text. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword language: Specifies the language of the text to convert from one script to another. - Possible languages are listed in the transliteration scope obtained by querying the service - for its supported languages. Required. - :paramtype language: str - :keyword from_script: Specifies the script used by the input text. Look up supported languages - using the transliteration scope, - to find input scripts available for the selected language. Required. - :paramtype from_script: str - :keyword to_script: Specifies the output script. Look up supported languages using the - transliteration scope, to find output - scripts available for the selected combination of input language and input script. Required. - :paramtype to_script: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of TransliteratedText - :rtype: list[~azure.ai.translation.text.models.TransliteratedText] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "script": "str", # A string specifying the script used in the - output. Required. - "text": "str" # A string which is the result of converting the input - string to the output script. Required. - } - ] - """ - - async def transliterate( # pyright: ignore[reportIncompatibleMethodOverride] - self, - body: Union[List[str], List[_models.InputTextItem], IO[bytes]], - *, - language: str, - from_script: str, - to_script: str, - client_trace_id: Optional[str] = None, - **kwargs: Any - ) -> List[_models.TransliteratedText]: - request_body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(body, list) and all(isinstance(item, str) for item in body): - input_text_items: List[_models.InputTextItem] = [] - for text in body: - input_text_items.append(_models.InputTextItem(text=cast(str, text))) - request_body = input_text_items - else: - request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) - - return await super().transliterate( - body=request_body, - language=language, - from_script=from_script, - to_script=to_script, - client_trace_id=client_trace_id, - **kwargs - ) - - @overload - async def find_sentence_boundaries( - self, - body: List[str], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: list[str] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - @overload - async def find_sentence_boundaries( - self, - body: List[_models.InputTextItem], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - @overload - async def find_sentence_boundaries( - self, - body: IO[bytes], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - # pylint: disable=line-too-long - """Find Sentence Boundaries. - - Find Sentence Boundaries. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword language: Language tag identifying the language of the input text. - If a code isn't specified, automatic language detection will be applied. Default value is - None. - :paramtype language: str - :keyword script: Script tag identifying the script used by the input text. - If a script isn't specified, the default script of the language will be assumed. Default value - is None. - :paramtype script: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of BreakSentenceItem - :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "sentLen": [ - 0 # An integer array representing the lengths of the - sentences in the input text. The length of the array is the number of - sentences, and the values are the length of each sentence. Required. - ], - "detectedLanguage": { - "language": "str", # A string representing the code of the - detected language. Required. - "score": 0.0 # A float value indicating the confidence in - the result. The score is between zero and one and a low score indicates a - low confidence. Required. - } - } - ] - """ - - async def find_sentence_boundaries( # pyright: ignore[reportIncompatibleMethodOverride] - self, - body: Union[List[str], List[_models.InputTextItem], IO[bytes]], - *, - client_trace_id: Optional[str] = None, - language: Optional[str] = None, - script: Optional[str] = None, - **kwargs: Any - ) -> List[_models.BreakSentenceItem]: - request_body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(body, list) and all(isinstance(item, str) for item in body): - input_text_items: List[_models.InputTextItem] = [] - for text in body: - input_text_items.append(_models.InputTextItem(text=cast(str, text))) - request_body = input_text_items - - else: - request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) - - return await super().find_sentence_boundaries( - body=request_body, language=language, script=script, client_trace_id=client_trace_id, **kwargs - ) - - @overload - async def lookup_dictionary_entries( - self, - body: List[str], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: list[str] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "score": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - @overload - async def lookup_dictionary_entries( - self, - body: List[_models.InputTextItem], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: list[~azure.ai.translation.text.models.InputTextItem] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - body = [ - { - "text": "str" # Text to translate. Required. - } - ] - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "score": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - @overload - async def lookup_dictionary_entries( - self, - body: IO[bytes], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - # pylint: disable=line-too-long - """Lookup Dictionary Entries. - - Lookup Dictionary Entries. - - :param body: Defines the content of the request. Required. - :type body: IO[bytes] - :keyword from_language: Specifies the language of the input text. - The source language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype from_language: str - :keyword to_language: Specifies the language of the output text. - The target language must be one of the supported languages included in the dictionary scope. - Required. - :paramtype to_language: str - :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default - value is None. - :paramtype client_trace_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: list of DictionaryLookupItem - :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem] - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == [ - { - "displaySource": "str", # A string giving the source term in a form - best suited for end-user display. For example, if the input is "JOHN", the - display form will reflect the usual spelling of the name: "John". Required. - "normalizedSource": "str", # A string giving the normalized form of - the source term. For example, if the request is "JOHN", the normalized form - will be "john". The content of this field becomes the input to lookup - examples. Required. - "translations": [ - { - "backTranslations": [ - { - "displayText": "str", # A string - giving the source term that is a back-translation of the - target in a form best suited for end-user display. Required. - "frequencyCount": 0, # An integer - representing the frequency of this translation pair in the - data. The main purpose of this field is to provide a user - interface with a means to sort back-translations so the most - frequent terms are first. Required. - "normalizedText": "str", # A string - giving the normalized form of the source term that is a - back-translation of the target. This value should be used as - input to lookup examples. Required. - "numExamples": 0 # An integer - representing the number of examples that are available for - this translation pair. Actual examples must be retrieved with - a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user - interface may add a hyperlink to the back-translation if the - number of examples is greater than zero and show the - back-translation as plain text if there are no examples. Note - that the actual number of examples returned by a call to - lookup examples may be less than numExamples, because - additional filtering may be applied on the fly to remove - "bad" examples. Required. - } - ], - "score": 0.0, # A value between 0.0 and 1.0 - which represents the "confidence" (or perhaps more accurately, - "probability in the training data") of that translation pair. The - sum of confidence scores for one source word may or may not sum to - 1.0. Required. - "displayTarget": "str", # A string giving the term - in the target language and in a form best suited for end-user - display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" - will have normalizedTarget = "juan" and displayTarget = "Juan". - Required. - "normalizedTarget": "str", # A string giving the - normalized form of this term in the target language. This value - should be used as input to lookup examples. Required. - "posTag": "str", # A string associating this term - with a part-of-speech tag. Required. - "prefixWord": "str" # A string giving the word to - display as a prefix of the translation. Currently, this is the - gendered determiner of nouns, in languages that have gendered - determiners. For example, the prefix of the Spanish word "mosca" is - "la", since "mosca" is a feminine noun in Spanish. This is only - dependent on the translation, and not on the source. If there is no - prefix, it will be the empty string. Required. - } - ] - } - ] - """ - - async def lookup_dictionary_entries( # pyright: ignore[reportIncompatibleMethodOverride] - self, - body: Union[List[str], List[_models.InputTextItem], IO[bytes]], - *, - from_language: str, - to_language: str, - client_trace_id: Optional[str] = None, - **kwargs: Any - ) -> List[_models.DictionaryLookupItem]: - request_body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(body, list) and all(isinstance(item, str) for item in body): - input_text_items: List[_models.InputTextItem] = [] - for text in body: - input_text_items.append(_models.InputTextItem(text=cast(str, text))) - request_body = input_text_items - else: - request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) - - return await super().lookup_dictionary_entries( - body=request_body, - from_language=from_language, - to_language=to_language, - client_trace_id=client_trace_id, - **kwargs - ) - +from typing import List -__all__: List[str] = [ - "TextTranslationClientOperationsMixin" -] # 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-text/azure/ai/translation/text/aio/_patch.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_patch.py index 235e7539dd94..8bcb627aa475 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_patch.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_patch.py @@ -1,27 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint: disable=C4717, C4722, C4748 +# 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 Optional, Any, overload -from azure.core.pipeline import PipelineRequest -from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy, AzureKeyCredentialPolicy -from azure.core.credentials import AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential +from typing import List -from .._patch import ( - DEFAULT_ENTRA_ID_SCOPE, - DEFAULT_SCOPE, - get_translation_endpoint, - TranslatorAuthenticationPolicy, - is_cognitive_services_scope, -) - -from ._client import TextTranslationClient as ServiceClientGenerated +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): @@ -31,146 +19,3 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ - - -class AsyncTranslatorEntraIdAuthenticationPolicy(AsyncBearerTokenCredentialPolicy): # pylint: disable=name-too-long - """Translator Entra Id Authentication Policy. Adds headers that are required by Translator Service - when global endpoint is used with Entra Id policy. - Ocp-Apim-Subscription-Region header contains region of the Translator resource. - Ocp-Apim-ResourceId header contains Azure resource Id - Translator resource. - - :param credential: Translator Entra Id Credentials used to access Translator Resource for global endpoint. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword str region: Used for National Clouds. - :keyword str resource_id: Used with both a TokenCredential combined with a region. - :keyword str audience: Scopes of the credentials. - """ - - def __init__( - self, credential: AsyncTokenCredential, resource_id: str, region: str, audience: str, **kwargs: Any - ) -> None: - super(AsyncTranslatorEntraIdAuthenticationPolicy, self).__init__(credential, audience, **kwargs) - self.resource_id = resource_id - self.region = region - self.translator_credential = credential - - async def on_request(self, request: PipelineRequest) -> None: - request.http_request.headers["Ocp-Apim-ResourceId"] = self.resource_id - request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.region - await super().on_request(request) - - -def set_authentication_policy(credential, kwargs): - if isinstance(credential, AzureKeyCredential): - if not kwargs.get("authentication_policy"): - if kwargs.get("region"): - kwargs["authentication_policy"] = TranslatorAuthenticationPolicy(credential, kwargs["region"]) - else: - kwargs["authentication_policy"] = AzureKeyCredentialPolicy( - name="Ocp-Apim-Subscription-Key", credential=credential - ) - elif hasattr(credential, "get_token"): - if not kwargs.get("authentication_policy"): - if kwargs.get("region") and kwargs.get("resource_id"): - scope = kwargs.pop("audience", DEFAULT_ENTRA_ID_SCOPE).rstrip("/").rstrip(DEFAULT_SCOPE) + DEFAULT_SCOPE - kwargs["authentication_policy"] = AsyncTranslatorEntraIdAuthenticationPolicy( - credential, - kwargs["resource_id"], - kwargs["region"], - scope, - ) - else: - if kwargs.get("resource_id") or kwargs.get("region"): - raise ValueError( - """Both 'resource_id' and 'region' must be provided with a TokenCredential - for regional resource authentication.""" - ) - scope: str = kwargs.pop("audience", DEFAULT_ENTRA_ID_SCOPE) - if not is_cognitive_services_scope(scope): - scope = scope.rstrip("/").rstrip(DEFAULT_SCOPE) + DEFAULT_SCOPE - kwargs["authentication_policy"] = AsyncBearerTokenCredentialPolicy( - credential, scope - ) - - -class TextTranslationClient(ServiceClientGenerated): - """Text translation is a cloud-based REST API feature of the Translator service that uses neural - machine translation technology to enable quick and accurate source-to-target text translation - in real time across all supported languages. - - The following methods are supported by the Text Translation feature: - - Languages. Returns a list of languages supported by Translate, Transliterate, and Dictionary - Lookup operations. - - Translate. Renders single source-language text to multiple target-language texts with a single - request. - - Transliterate. Converts characters or letters of a source language to the corresponding - characters or letters of a target language. - - Detect. Returns the source code language code and a boolean variable denoting whether the - detected language is supported for text translation and transliteration. - - Dictionary lookup. Returns equivalent words for the source term in the target language. - - Dictionary example Returns grammatical structure and context examples for the source term and - target term pair. - - Combinations of endpoint and credential values: - str + AzureKeyCredential - used custom domain translator endpoint - str + AzureKeyCredential + Region - used for global translator endpoint - str + AsyncTokenCredential - used for regional endpoint with token authentication - str + None - used with text translation on-prem container - None + AzureKeyCredential - used for global translator endpoint with global Translator resource - None + AsyncTokenCredential - general translator endpoint with token authentication - None + AsyncTokenCredential + Region - general translator endpoint with regional Translator resource - - :keyword str endpoint: Supported Text Translation endpoints (protocol and hostname, for example: - https://api.cognitive.microsofttranslator.com). If not provided, global translator endpoint will be used. - :keyword credential: Credential used to authenticate with the Translator service - :paramtype credential: Union[AzureKeyCredential, AsyncTokenCredential] - :keyword str region: Used for National Clouds. - :keyword str resource_id: Used with both a TokenCredential combined with a region. - :keyword str audience: Scopes of the credentials. - :keyword str api_version: Default value is "3.0". Note that overriding this default value may - result in unsupported behavior. - """ - - @overload - def __init__( - self, - *, - credential: AsyncTokenCredential, - region: Optional[str] = None, - endpoint: Optional[str] = None, - resource_id: Optional[str] = None, - audience: Optional[str] = None, - api_version: str = "3.0", - **kwargs - ): ... - - @overload - def __init__( - self, - *, - credential: AzureKeyCredential, - region: Optional[str] = None, - endpoint: Optional[str] = None, - api_version: str = "3.0", - **kwargs - ): ... - - @overload - def __init__(self, *, endpoint: str, api_version: str = "3.0", **kwargs): ... - - def __init__(self, **kwargs): - api_version = kwargs.get("api_version", "3.0") - set_authentication_policy(kwargs.get("credential"), kwargs) - translation_endpoint = get_translation_endpoint( - kwargs.pop("endpoint", "https://api.cognitive.microsofttranslator.com"), api_version - ) - super().__init__(endpoint=translation_endpoint, api_version=api_version, **kwargs) - - -__all__ = ["TextTranslationClient"] diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_vendor.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_vendor.py deleted file mode 100644 index 28781d01428b..000000000000 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_vendor.py +++ /dev/null @@ -1,58 +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 Optional, TYPE_CHECKING - -from azure.core import MatchConditions - -from ._configuration import TextTranslationClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import AsyncPipelineClient - - from .._serialization import Deserializer, Serializer - - -class TextTranslationClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "AsyncPipelineClient" - _config: TextTranslationClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" - - -def quote_etag(etag: Optional[str]) -> Optional[str]: - if not etag or etag == "*": - return etag - if etag.startswith("W/"): - return etag - if etag.startswith('"') and etag.endswith('"'): - return etag - if etag.startswith("'") and etag.endswith("'"): - return etag - return '"' + etag + '"' - - -def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfNotModified: - if_match = quote_etag(etag) if etag else None - return if_match - if match_condition == MatchConditions.IfPresent: - return "*" - return None - - -def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfModified: - if_none_match = quote_etag(etag) if etag else None - return if_none_match - if match_condition == MatchConditions.IfMissing: - return "*" - return None diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/__init__.py index da99621bc1e2..5fc3ea070914 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/__init__.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/__init__.py @@ -5,59 +5,58 @@ # 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 BackTranslation -from ._models import BreakSentenceItem -from ._models import DetectedLanguage -from ._models import DictionaryExample -from ._models import DictionaryExampleItem -from ._models import DictionaryExampleTextItem -from ._models import DictionaryLookupItem -from ._models import DictionaryTranslation -from ._models import ErrorDetails -from ._models import ErrorResponse -from ._models import GetSupportedLanguagesResult -from ._models import InputTextItem -from ._models import LanguageScript -from ._models import SentenceBoundaries -from ._models import SourceDictionaryLanguage -from ._models import SourceText -from ._models import TargetDictionaryLanguage -from ._models import TranslatedTextAlignment -from ._models import TranslatedTextItem -from ._models import TranslationLanguage -from ._models import TranslationText -from ._models import TransliterableScript -from ._models import TransliteratedText -from ._models import TransliterationLanguage +from typing import TYPE_CHECKING -from ._enums import LanguageDirectionality -from ._enums import ProfanityAction -from ._enums import ProfanityMarker -from ._enums import TextType +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + DetectedLanguage, + ErrorDetails, + ErrorResponse, + GetSupportedLanguagesResult, + InputTextItem, + LanguageScript, + ReferenceSentencePair, + SourceDictionaryLanguage, + SourceText, + TargetDictionaryLanguage, + TranslateBody, + TranslateTarget, + TranslatedTextItem, + TranslationLanguage, + TranslationText, + TransliterableScript, + TransliteratedText, + TransliterationLanguage, +) + +from ._enums import ( # type: ignore + LanguageDirectionality, + ProfanityAction, + ProfanityMarker, + TextType, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "BackTranslation", - "BreakSentenceItem", "DetectedLanguage", - "DictionaryExample", - "DictionaryExampleItem", - "DictionaryExampleTextItem", - "DictionaryLookupItem", - "DictionaryTranslation", "ErrorDetails", "ErrorResponse", "GetSupportedLanguagesResult", "InputTextItem", "LanguageScript", - "SentenceBoundaries", + "ReferenceSentencePair", "SourceDictionaryLanguage", "SourceText", "TargetDictionaryLanguage", - "TranslatedTextAlignment", + "TranslateBody", + "TranslateTarget", "TranslatedTextItem", "TranslationLanguage", "TranslationText", @@ -69,5 +68,5 @@ "ProfanityMarker", "TextType", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__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-text/azure/ai/translation/text/models/_models.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_models.py index e636f1f0a345..a83ece60dae0 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_models.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_models.py @@ -1,142 +1,23 @@ # coding=utf-8 -# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # 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. # -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation from typing import Any, Dict, List, Mapping, Optional, TYPE_CHECKING, Union, overload -from .. import _model_base -from .._model_base import rest_field +from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models -class BackTranslation(_model_base.Model): - """Back Translation. - - All required parameters must be populated in order to send to server. - - :ivar normalized_text: A string giving the normalized form of the source term that is a - back-translation of the target. - This value should be used as input to lookup examples. Required. - :vartype normalized_text: str - :ivar display_text: A string giving the source term that is a back-translation of the target in - a form best - suited for end-user display. Required. - :vartype display_text: str - :ivar num_examples: An integer representing the number of examples that are available for this - translation pair. - Actual examples must be retrieved with a separate call to lookup examples. The number is - mostly - intended to facilitate display in a UX. For example, a user interface may add a hyperlink - to the back-translation if the number of examples is greater than zero and show the - back-translation - as plain text if there are no examples. Note that the actual number of examples returned - by a call to lookup examples may be less than numExamples, because additional filtering may be - applied on the fly to remove "bad" examples. Required. - :vartype num_examples: int - :ivar frequency_count: An integer representing the frequency of this translation pair in the - data. The main purpose of this - field is to provide a user interface with a means to sort back-translations so the most - frequent terms are first. Required. - :vartype frequency_count: int - """ - - normalized_text: str = rest_field(name="normalizedText") - """A string giving the normalized form of the source term that is a back-translation of the - target. - This value should be used as input to lookup examples. Required.""" - display_text: str = rest_field(name="displayText") - """A string giving the source term that is a back-translation of the target in a form best - suited for end-user display. Required.""" - num_examples: int = rest_field(name="numExamples") - """An integer representing the number of examples that are available for this translation pair. - Actual examples must be retrieved with a separate call to lookup examples. The number is mostly - intended to facilitate display in a UX. For example, a user interface may add a hyperlink - to the back-translation if the number of examples is greater than zero and show the - back-translation - as plain text if there are no examples. Note that the actual number of examples returned - by a call to lookup examples may be less than numExamples, because additional filtering may be - applied on the fly to remove \"bad\" examples. Required.""" - frequency_count: int = rest_field(name="frequencyCount") - """An integer representing the frequency of this translation pair in the data. The main purpose of - this - field is to provide a user interface with a means to sort back-translations so the most - frequent terms are first. Required.""" - - @overload - def __init__( - self, - *, - normalized_text: str, - display_text: str, - num_examples: int, - frequency_count: int, - ): ... - - @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: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class BreakSentenceItem(_model_base.Model): - """Item containing break sentence result. - - All required parameters must be populated in order to send to server. - - :ivar detected_language: The detectedLanguage property is only present in the result object - when language auto-detection is requested. - :vartype detected_language: ~azure.ai.translation.text.models.DetectedLanguage - :ivar sent_len: An integer array representing the lengths of the sentences in the input text. - The length of the array is the number of sentences, and the values are the length of each - sentence. Required. - :vartype sent_len: list[int] - """ - - detected_language: Optional["_models.DetectedLanguage"] = rest_field(name="detectedLanguage") - """The detectedLanguage property is only present in the result object when language auto-detection - is requested.""" - sent_len: List[int] = rest_field(name="sentLen") - """An integer array representing the lengths of the sentences in the input text. - The length of the array is the number of sentences, and the values are the length of each - sentence. Required.""" - - @overload - def __init__( - self, - *, - sent_len: List[int], - detected_language: Optional["_models.DetectedLanguage"] = 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: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class DetectedLanguage(_model_base.Model): +class DetectedLanguage(_Model): """An object describing the detected language. - All required parameters must be populated in order to send to server. - :ivar language: A string representing the code of the detected language. Required. :vartype language: str :ivar score: A float value indicating the confidence in the result. @@ -144,9 +25,9 @@ class DetectedLanguage(_model_base.Model): :vartype score: float """ - language: str = rest_field() + language: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A string representing the code of the detected language. Required.""" - score: float = rest_field() + score: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A float value indicating the confidence in the result. The score is between zero and one and a low score indicates a low confidence. Required.""" @@ -156,362 +37,31 @@ def __init__( *, language: str, score: float, - ): ... - - @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: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class DictionaryExample(_model_base.Model): - """Dictionary Example. - - All required parameters must be populated in order to send to server. - - :ivar source_prefix: The string to concatenate before the value of sourceTerm to form a - complete example. - Do not add a space character, since it is already there when it should be. - This value may be an empty string. Required. - :vartype source_prefix: str - :ivar source_term: A string equal to the actual term looked up. The string is added with - sourcePrefix - and sourceSuffix to form the complete example. Its value is separated so it can be - marked in a user interface, e.g., by bolding it. Required. - :vartype source_term: str - :ivar source_suffix: The string to concatenate after the value of sourceTerm to form a complete - example. - Do not add a space character, since it is already there when it should be. - This value may be an empty string. Required. - :vartype source_suffix: str - :ivar target_prefix: A string similar to sourcePrefix but for the target. Required. - :vartype target_prefix: str - :ivar target_term: A string similar to sourceTerm but for the target. Required. - :vartype target_term: str - :ivar target_suffix: A string similar to sourceSuffix but for the target. Required. - :vartype target_suffix: str - """ - - source_prefix: str = rest_field(name="sourcePrefix") - """The string to concatenate before the value of sourceTerm to form a complete example. - Do not add a space character, since it is already there when it should be. - This value may be an empty string. Required.""" - source_term: str = rest_field(name="sourceTerm") - """A string equal to the actual term looked up. The string is added with sourcePrefix - and sourceSuffix to form the complete example. Its value is separated so it can be - marked in a user interface, e.g., by bolding it. Required.""" - source_suffix: str = rest_field(name="sourceSuffix") - """The string to concatenate after the value of sourceTerm to form a complete example. - Do not add a space character, since it is already there when it should be. - This value may be an empty string. Required.""" - target_prefix: str = rest_field(name="targetPrefix") - """A string similar to sourcePrefix but for the target. Required.""" - target_term: str = rest_field(name="targetTerm") - """A string similar to sourceTerm but for the target. Required.""" - target_suffix: str = rest_field(name="targetSuffix") - """A string similar to sourceSuffix but for the target. Required.""" - - @overload - def __init__( - self, - *, - source_prefix: str, - source_term: str, - source_suffix: str, - target_prefix: str, - target_term: str, - target_suffix: str, - ): ... - - @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: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class DictionaryExampleItem(_model_base.Model): - """Dictionary Example element. - - All required parameters must be populated in order to send to server. - - :ivar normalized_source: A string giving the normalized form of the source term. Generally, - this should be identical - to the value of the Text field at the matching list index in the body of the request. - Required. - :vartype normalized_source: str - :ivar normalized_target: A string giving the normalized form of the target term. Generally, - this should be identical - to the value of the Translation field at the matching list index in the body of the request. - Required. - :vartype normalized_target: str - :ivar examples: A list of examples for the (source term, target term) pair. Required. - :vartype examples: list[~azure.ai.translation.text.models.DictionaryExample] - """ - - normalized_source: str = rest_field(name="normalizedSource") - """A string giving the normalized form of the source term. Generally, this should be identical - to the value of the Text field at the matching list index in the body of the request. Required.""" - normalized_target: str = rest_field(name="normalizedTarget") - """A string giving the normalized form of the target term. Generally, this should be identical - to the value of the Translation field at the matching list index in the body of the request. - Required.""" - examples: List["_models.DictionaryExample"] = rest_field() - """A list of examples for the (source term, target term) pair. Required.""" - - @overload - def __init__( - self, - *, - normalized_source: str, - normalized_target: str, - examples: List["_models.DictionaryExample"], - ): ... - - @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: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class InputTextItem(_model_base.Model): - """Element containing the text for translation. - - All required parameters must be populated in order to send to server. - - :ivar text: Text to translate. Required. - :vartype text: str - """ - - text: str = rest_field() - """Text to translate. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ): ... - - @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: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class DictionaryExampleTextItem(InputTextItem): - """Element containing the text with translation. - - All required parameters must be populated in order to send to server. - - :ivar text: Text to translate. Required. - :vartype text: str - :ivar translation: A string specifying the translated text previously returned by the - Dictionary lookup operation. - This should be the value from the normalizedTarget field in the translations list of the - Dictionary - lookup response. The service will return examples for the specific source-target word-pair. - Required. - :vartype translation: str - """ - - translation: str = rest_field() - """A string specifying the translated text previously returned by the Dictionary lookup operation. - This should be the value from the normalizedTarget field in the translations list of the - Dictionary - lookup response. The service will return examples for the specific source-target word-pair. - Required.""" - - @overload - def __init__( - self, - *, - text: str, - translation: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DictionaryLookupItem(_model_base.Model): - """Dictionary Lookup Element. - - All required parameters must be populated in order to send to server. - - :ivar normalized_source: A string giving the normalized form of the source term. - For example, if the request is "JOHN", the normalized form will be "john". - The content of this field becomes the input to lookup examples. Required. - :vartype normalized_source: str - :ivar display_source: A string giving the source term in a form best suited for end-user - display. - For example, if the input is "JOHN", the display form will reflect the usual - spelling of the name: "John". Required. - :vartype display_source: str - :ivar translations: A list of translations for the source term. Required. - :vartype translations: list[~azure.ai.translation.text.models.DictionaryTranslation] - """ - - normalized_source: str = rest_field(name="normalizedSource") - """A string giving the normalized form of the source term. - For example, if the request is \"JOHN\", the normalized form will be \"john\". - The content of this field becomes the input to lookup examples. Required.""" - display_source: str = rest_field(name="displaySource") - """A string giving the source term in a form best suited for end-user display. - For example, if the input is \"JOHN\", the display form will reflect the usual - spelling of the name: \"John\". Required.""" - translations: List["_models.DictionaryTranslation"] = rest_field() - """A list of translations for the source term. Required.""" - - @overload - def __init__( - self, - *, - normalized_source: str, - display_source: str, - translations: List["_models.DictionaryTranslation"], - ): ... - - @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: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class DictionaryTranslation(_model_base.Model): - """Translation source term. - - All required parameters must be populated in order to send to server. - - :ivar normalized_target: A string giving the normalized form of this term in the target - language. - This value should be used as input to lookup examples. Required. - :vartype normalized_target: str - :ivar display_target: A string giving the term in the target language and in a form best suited - for end-user display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like "Juan" will have - normalizedTarget = "juan" and displayTarget = "Juan". Required. - :vartype display_target: str - :ivar pos_tag: A string associating this term with a part-of-speech tag. Required. - :vartype pos_tag: str - :ivar confidence: A value between 0.0 and 1.0 which represents the "confidence" - (or perhaps more accurately, "probability in the training data") of that translation pair. - The sum of confidence scores for one source word may or may not sum to 1.0. Required. - :vartype confidence: float - :ivar prefix_word: A string giving the word to display as a prefix of the translation. - Currently, - this is the gendered determiner of nouns, in languages that have gendered determiners. - For example, the prefix of the Spanish word "mosca" is "la", since "mosca" is a feminine noun - in Spanish. - This is only dependent on the translation, and not on the source. - If there is no prefix, it will be the empty string. Required. - :vartype prefix_word: str - :ivar back_translations: A list of "back translations" of the target. For example, source words - that the target can translate to. - The list is guaranteed to contain the source word that was requested (e.g., if the source word - being - looked up is "fly", then it is guaranteed that "fly" will be in the backTranslations list). - However, it is not guaranteed to be in the first position, and often will not be. Required. - :vartype back_translations: list[~azure.ai.translation.text.models.BackTranslation] - """ - - normalized_target: str = rest_field(name="normalizedTarget") - """A string giving the normalized form of this term in the target language. - This value should be used as input to lookup examples. Required.""" - display_target: str = rest_field(name="displayTarget") - """A string giving the term in the target language and in a form best suited - for end-user display. Generally, this will only differ from the normalizedTarget - in terms of capitalization. For example, a proper noun like \"Juan\" will have - normalizedTarget = \"juan\" and displayTarget = \"Juan\". Required.""" - pos_tag: str = rest_field(name="posTag") - """A string associating this term with a part-of-speech tag. Required.""" - confidence: float = rest_field() - """A value between 0.0 and 1.0 which represents the \"confidence\" - (or perhaps more accurately, \"probability in the training data\") of that translation pair. - The sum of confidence scores for one source word may or may not sum to 1.0. Required.""" - prefix_word: str = rest_field(name="prefixWord") - """A string giving the word to display as a prefix of the translation. Currently, - this is the gendered determiner of nouns, in languages that have gendered determiners. - For example, the prefix of the Spanish word \"mosca\" is \"la\", since \"mosca\" is a feminine - noun in Spanish. - This is only dependent on the translation, and not on the source. - If there is no prefix, it will be the empty string. Required.""" - back_translations: List["_models.BackTranslation"] = rest_field(name="backTranslations") - """A list of \"back translations\" of the target. For example, source words that the target can - translate to. - The list is guaranteed to contain the source word that was requested (e.g., if the source word - being - looked up is \"fly\", then it is guaranteed that \"fly\" will be in the backTranslations list). - However, it is not guaranteed to be in the first position, and often will not be. Required.""" - - @overload - def __init__( - self, - *, - normalized_target: str, - display_target: str, - pos_tag: str, - confidence: float, - prefix_word: str, - back_translations: List["_models.BackTranslation"], - ): ... - - @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: # pylint: disable=useless-super-delegation - super().__init__(*args, **kwargs) - - -class ErrorDetails(_model_base.Model): +class ErrorDetails(_Model): """Error details as returned by Translator Service. - All required parameters must be populated in order to send to server. - :ivar code: Number identifier of the error. Required. :vartype code: int :ivar message: Human readable error description. Required. :vartype message: str """ - code: int = rest_field() + code: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Number identifier of the error. Required.""" - message: str = rest_field() + message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Human readable error description. Required.""" @overload @@ -520,29 +70,27 @@ def __init__( *, code: int, message: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ErrorResponse(_model_base.Model): +class ErrorResponse(_Model): """Representation of the Error Response from Translator Service. - All required parameters must be populated in order to send to server. - :ivar error: Error details. Required. :vartype error: ~azure.ai.translation.text.models.ErrorDetails """ - error: "_models.ErrorDetails" = rest_field() + error: "_models.ErrorDetails" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Error details. Required.""" @overload @@ -550,20 +98,20 @@ def __init__( self, *, error: "_models.ErrorDetails", - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class GetSupportedLanguagesResult(_model_base.Model): +class GetSupportedLanguagesResult(_Model): """Response for the languages API. :ivar translation: Languages that support translate API. @@ -574,11 +122,17 @@ class GetSupportedLanguagesResult(_model_base.Model): :vartype dictionary: dict[str, ~azure.ai.translation.text.models.SourceDictionaryLanguage] """ - translation: Optional[Dict[str, "_models.TranslationLanguage"]] = rest_field() + translation: Optional[Dict[str, "_models.TranslationLanguage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Languages that support translate API.""" - transliteration: Optional[Dict[str, "_models.TransliterationLanguage"]] = rest_field() + transliteration: Optional[Dict[str, "_models.TransliterationLanguage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Languages that support transliteration API.""" - dictionary: Optional[Dict[str, "_models.SourceDictionaryLanguage"]] = rest_field() + dictionary: Optional[Dict[str, "_models.SourceDictionaryLanguage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Languages that support dictionary API.""" @overload @@ -588,23 +142,49 @@ def __init__( translation: Optional[Dict[str, "_models.TranslationLanguage"]] = None, transliteration: Optional[Dict[str, "_models.TransliterationLanguage"]] = None, dictionary: Optional[Dict[str, "_models.SourceDictionaryLanguage"]] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class LanguageScript(_model_base.Model): - """Common properties of language script. +class InputTextItem(_Model): + """Element containing the text for translation. + + :ivar text: Text to translate. Required. + :vartype text: str + """ + + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Text to translate. Required.""" + + @overload + def __init__( + self, + *, + text: str, + ) -> 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 LanguageScript(_Model): + """Common properties of language script. :ivar code: Code identifying the script. Required. :vartype code: str @@ -619,13 +199,15 @@ class LanguageScript(_model_base.Model): :vartype dir: str or ~azure.ai.translation.text.models.LanguageDirectionality """ - code: str = rest_field() + code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Code identifying the script. Required.""" - name: str = rest_field() + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Display name of the script in the locale requested via Accept-Language header. Required.""" - native_name: str = rest_field(name="nativeName") + native_name: str = rest_field(name="nativeName", visibility=["read", "create", "update", "delete", "query"]) """Display name of the language in the locale native for the language. Required.""" - dir: Union[str, "_models.LanguageDirectionality"] = rest_field() + dir: Union[str, "_models.LanguageDirectionality"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. Required. Known values are: \"ltr\" and \"rtl\".""" @@ -637,69 +219,59 @@ def __init__( name: str, native_name: str, dir: Union[str, "_models.LanguageDirectionality"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class SentenceBoundaries(_model_base.Model): - """An object returning sentence boundaries in the input and output texts. - - All required parameters must be populated in order to send to server. +class ReferenceSentencePair(_Model): + """Reference sentence pair. - :ivar src_sent_len: An integer array representing the lengths of the sentences in the input - text. - The length of the array is the number of sentences, and the values are the length of each - sentence. Required. - :vartype src_sent_len: list[int] - :ivar trans_sent_len: An integer array representing the lengths of the sentences in the - translated text. - The length of the array is the number of sentences, and the values are the length of each - sentence. Required. - :vartype trans_sent_len: list[int] + :ivar reference_text_pairs_source: Source reference sentence. Required. + :vartype reference_text_pairs_source: str + :ivar reference_text_pairs_target: Target reference sentence. Required. + :vartype reference_text_pairs_target: str """ - src_sent_len: List[int] = rest_field(name="srcSentLen") - """An integer array representing the lengths of the sentences in the input text. - The length of the array is the number of sentences, and the values are the length of each - sentence. Required.""" - trans_sent_len: List[int] = rest_field(name="transSentLen") - """An integer array representing the lengths of the sentences in the translated text. - The length of the array is the number of sentences, and the values are the length of each - sentence. Required.""" + reference_text_pairs_source: str = rest_field( + name="referenceTextPairsSource", visibility=["read", "create", "update", "delete", "query"] + ) + """Source reference sentence. Required.""" + reference_text_pairs_target: str = rest_field( + name="referenceTextPairsTarget", visibility=["read", "create", "update", "delete", "query"] + ) + """Target reference sentence. Required.""" @overload def __init__( self, *, - src_sent_len: List[int], - trans_sent_len: List[int], - ): ... + reference_text_pairs_source: str, + reference_text_pairs_target: str, + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class SourceDictionaryLanguage(_model_base.Model): +class SourceDictionaryLanguage(_Model): """Properties ot the source dictionary language. - All required parameters must be populated in order to send to server. - :ivar name: Display name of the language in the locale requested via Accept-Language header. Required. :vartype name: str @@ -714,14 +286,18 @@ class SourceDictionaryLanguage(_model_base.Model): :vartype translations: list[~azure.ai.translation.text.models.TargetDictionaryLanguage] """ - name: str = rest_field() + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Display name of the language in the locale requested via Accept-Language header. Required.""" - native_name: str = rest_field(name="nativeName") + native_name: str = rest_field(name="nativeName", visibility=["read", "create", "update", "delete", "query"]) """Display name of the language in the locale native for this language. Required.""" - dir: Union[str, "_models.LanguageDirectionality"] = rest_field() + dir: Union[str, "_models.LanguageDirectionality"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. Required. Known values are: \"ltr\" and \"rtl\".""" - translations: List["_models.TargetDictionaryLanguage"] = rest_field() + translations: List["_models.TargetDictionaryLanguage"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """List of languages with alterative translations and examples for the query expressed in the source language. Required.""" @@ -733,29 +309,27 @@ def __init__( native_name: str, dir: Union[str, "_models.LanguageDirectionality"], translations: List["_models.TargetDictionaryLanguage"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class SourceText(_model_base.Model): +class SourceText(_Model): """Input text in the default script of the source language. - All required parameters must be populated in order to send to server. - :ivar text: Input text in the default script of the source language. Required. :vartype text: str """ - text: str = rest_field() + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Input text in the default script of the source language. Required.""" @overload @@ -763,24 +337,22 @@ def __init__( self, *, text: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TargetDictionaryLanguage(_model_base.Model): +class TargetDictionaryLanguage(_Model): """Properties of the target dictionary language. - All required parameters must be populated in order to send to server. - :ivar name: Display name of the language in the locale requested via Accept-Language header. Required. :vartype name: str @@ -794,14 +366,16 @@ class TargetDictionaryLanguage(_model_base.Model): :vartype code: str """ - name: str = rest_field() + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Display name of the language in the locale requested via Accept-Language header. Required.""" - native_name: str = rest_field(name="nativeName") + native_name: str = rest_field(name="nativeName", visibility=["read", "create", "update", "delete", "query"]) """Display name of the language in the locale native for this language. Required.""" - dir: Union[str, "_models.LanguageDirectionality"] = rest_field() + dir: Union[str, "_models.LanguageDirectionality"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. Required. Known values are: \"ltr\" and \"rtl\".""" - code: str = rest_field() + code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Language code identifying the target language. Required.""" @overload @@ -812,71 +386,89 @@ def __init__( native_name: str, dir: Union[str, "_models.LanguageDirectionality"], code: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TranslatedTextAlignment(_model_base.Model): - """Alignment information object. - - All required parameters must be populated in order to send to server. +class TranslateBody(InputTextItem): + """Element containing the text for translation. - :ivar proj: Maps input text to translated text. The alignment information is only provided when - the request - parameter includeAlignment is true. Alignment is returned as a string value of the following - format: [[SourceTextStartIndex]:[SourceTextEndIndex]–[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the languages, and space separates - the words. - One word may align with zero, one, or multiple words in the other language, and the aligned - words may - be non-contiguous. When no alignment information is available, the alignment element will be - empty. Required. - :vartype proj: str + :ivar text: Text to translate. Required. + :vartype text: str + :ivar script: Specifies the script of the input text. + :vartype script: str + :ivar language: Specifies the language of the input text. Find which languages are available to + translate by + looking up supported languages using the translation scope. If the language parameter isn't + specified, automatic language detection is applied to determine the source language. + + You must use the language parameter rather than autodetection when using the dynamic dictionary + feature. + Note: the dynamic dictionary feature is case-sensitive. + :vartype language: str + :ivar text_type: Defines whether the text being translated is plain text or HTML text. Any HTML + needs to be a well-formed, + complete element. Possible values are: plain (default) or html. Known values are: "Plain" and + "Html". + :vartype text_type: str or ~azure.ai.translation.text.models.TextType + :ivar targets: Translation target parameters. Required. + :vartype targets: list[~azure.ai.translation.text.models.TranslateTarget] """ - proj: str = rest_field() - """Maps input text to translated text. The alignment information is only provided when the request - parameter includeAlignment is true. Alignment is returned as a string value of the following - format: [[SourceTextStartIndex]:[SourceTextEndIndex]–[TgtTextStartIndex]:[TgtTextEndIndex]]. - The colon separates start and end index, the dash separates the languages, and space separates - the words. - One word may align with zero, one, or multiple words in the other language, and the aligned - words may - be non-contiguous. When no alignment information is available, the alignment element will be - empty. Required.""" + script: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Specifies the script of the input text.""" + language: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Specifies the language of the input text. Find which languages are available to translate by + looking up supported languages using the translation scope. If the language parameter isn't + specified, automatic language detection is applied to determine the source language. + + You must use the language parameter rather than autodetection when using the dynamic dictionary + feature. + Note: the dynamic dictionary feature is case-sensitive.""" + text_type: Optional[Union[str, "_models.TextType"]] = rest_field( + name="textType", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines whether the text being translated is plain text or HTML text. Any HTML needs to be a + well-formed, + complete element. Possible values are: plain (default) or html. Known values are: \"Plain\" and + \"Html\".""" + targets: List["_models.TranslateTarget"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Translation target parameters. Required.""" @overload def __init__( self, *, - proj: str, - ): ... + text: str, + targets: List["_models.TranslateTarget"], + script: Optional[str] = None, + language: Optional[str] = None, + text_type: Optional[Union[str, "_models.TextType"]] = None, + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TranslatedTextItem(_model_base.Model): +class TranslatedTextItem(_Model): """Element containing the translated text. - All required parameters must be populated in order to send to server. - :ivar detected_language: The detectedLanguage property is only present in the result object when language auto-detection is requested. :vartype detected_language: ~azure.ai.translation.text.models.DetectedLanguage @@ -887,19 +479,25 @@ class TranslatedTextItem(_model_base.Model): :ivar source_text: Input text in the default script of the source language. sourceText property is present only when the input is expressed in a script that's not the usual script for the language. For example, - if the input were Arabic written in Latin script, then sourceText.text would be the same - Arabic text + if the input were Arabic written in Latin script, then sourceText.text would be the same Arabic + text converted into Arab script. :vartype source_text: ~azure.ai.translation.text.models.SourceText """ - detected_language: Optional["_models.DetectedLanguage"] = rest_field(name="detectedLanguage") + detected_language: Optional["_models.DetectedLanguage"] = rest_field( + name="detectedLanguage", visibility=["read", "create", "update", "delete", "query"] + ) """The detectedLanguage property is only present in the result object when language auto-detection is requested.""" - translations: List["_models.TranslationText"] = rest_field() + translations: List["_models.TranslationText"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """An array of translation results. The size of the array matches the number of target languages specified through the to query parameter. Required.""" - source_text: Optional["_models.SourceText"] = rest_field(name="sourceText") + source_text: Optional["_models.SourceText"] = rest_field( + name="sourceText", visibility=["read", "create", "update", "delete", "query"] + ) """Input text in the default script of the source language. sourceText property is present only when the input is expressed in a script that's not the usual script for the language. For example, @@ -914,26 +512,179 @@ def __init__( translations: List["_models.TranslationText"], detected_language: Optional["_models.DetectedLanguage"] = None, source_text: Optional["_models.SourceText"] = None, - ): ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TranslateTarget(_Model): + """Translate targets parameters. + + :ivar language: Specifies the language of the output text. The target language must be one of + the supported languages included + in the translation scope. It's possible to translate to multiple languages simultaneously by + including + multiple string values in the targetsLanguage array. Required. + :vartype language: list[str] + :ivar script: Specifies the script of the translated text. + :vartype script: str + :ivar profanity_action: Specifies how profanities should be treated in translations. + Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction", + "Marked", and "Deleted". + :vartype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction + :ivar profanity_marker: Specifies how profanities should be marked in translations. + Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag". + :vartype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker + :ivar deployment_name_model: Default is ‘general’, which uses NMT system. + ‘abc-inc-gpt-4o’, and ‘abc-inc-gpt-4o-mini’ are examples of deployment names which use GPT-4o + uses or + GPT-4o-mini model. ‘gpt-4o’ uses GPT-4o model. + + ‘’ uses the custom NMT model tuned by customer. + ‘best’ system determines which is the best model to use for the request. This intelligence + could be introduced + in future. Customer should have deployed it in their resource. + :vartype deployment_name_model: str + :ivar allow_fallback: In the case where a custom system is being used, specifies that the + service is allowed to fall back to a + general system when a custom system doesn't exist. + In the case where a Large Language Model is being used, specifies that the service is allowed + to fall + back to a Small Language Model if an error occurs. + Possible values are: true (default) or false. + + allowFallback=false specifies that the translation should only use systems trained for the + category specified + by the request. If a translation for language X to language Y requires chaining through a pivot + language E, + then all the systems in the chain (X → E and E → Y) will need to be custom and have the same + category. + If no system is found with the specific category, the request will return a 400 status code. + allowFallback=true + specifies that the service is allowed to fall back to a general system when a custom system + doesn't exist. + :vartype allow_fallback: bool + :ivar grade: Defines complexity of LLM prompts to provide high accuracy translation. + :vartype grade: str + :ivar tone: Desired tone of target translation. + :vartype tone: str + :ivar gender: Desired gender of target translation. + :vartype gender: str + :ivar adaptive_dataset_id: Reference dataset ID having sentence pair to generate adaptive + customized translation. + :vartype adaptive_dataset_id: str + :ivar reference_text_pairs: Reference sentence pairs to generate adaptive results. + :vartype reference_text_pairs: list[~azure.ai.translation.text.models.ReferenceSentencePair] + """ + + language: List[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Specifies the language of the output text. The target language must be one of the supported + languages included + in the translation scope. It's possible to translate to multiple languages simultaneously by + including + multiple string values in the targetsLanguage array. Required.""" + script: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Specifies the script of the translated text.""" + profanity_action: Optional[Union[str, "_models.ProfanityAction"]] = rest_field( + name="profanityAction", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies how profanities should be treated in translations. + Possible values are: NoAction (default), Marked or Deleted. Known values are: \"NoAction\", + \"Marked\", and \"Deleted\".""" + profanity_marker: Optional[Union[str, "_models.ProfanityMarker"]] = rest_field( + name="profanityMarker", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies how profanities should be marked in translations. + Possible values are: Asterisk (default) or Tag. Known values are: \"Asterisk\" and \"Tag\".""" + deployment_name_model: Optional[str] = rest_field( + name="deploymentNameModel", visibility=["read", "create", "update", "delete", "query"] + ) + """Default is ‘general’, which uses NMT system. + ‘abc-inc-gpt-4o’, and ‘abc-inc-gpt-4o-mini’ are examples of deployment names which use GPT-4o + uses or + GPT-4o-mini model. ‘gpt-4o’ uses GPT-4o model. + + ‘’ uses the custom NMT model tuned by customer. + ‘best’ system determines which is the best model to use for the request. This intelligence + could be introduced + in future. Customer should have deployed it in their resource.""" + allow_fallback: Optional[bool] = rest_field( + name="allowFallback", visibility=["read", "create", "update", "delete", "query"] + ) + """In the case where a custom system is being used, specifies that the service is allowed to fall + back to a + general system when a custom system doesn't exist. + In the case where a Large Language Model is being used, specifies that the service is allowed + to fall + back to a Small Language Model if an error occurs. + Possible values are: true (default) or false. + + allowFallback=false specifies that the translation should only use systems trained for the + category specified + by the request. If a translation for language X to language Y requires chaining through a pivot + language E, + then all the systems in the chain (X → E and E → Y) will need to be custom and have the same + category. + If no system is found with the specific category, the request will return a 400 status code. + allowFallback=true + specifies that the service is allowed to fall back to a general system when a custom system + doesn't exist.""" + grade: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Defines complexity of LLM prompts to provide high accuracy translation.""" + tone: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Desired tone of target translation.""" + gender: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Desired gender of target translation.""" + adaptive_dataset_id: Optional[str] = rest_field( + name="adaptiveDatasetId", visibility=["read", "create", "update", "delete", "query"] + ) + """Reference dataset ID having sentence pair to generate adaptive customized translation.""" + reference_text_pairs: Optional[List["_models.ReferenceSentencePair"]] = rest_field( + name="referenceTextPairs", visibility=["read", "create", "update", "delete", "query"] + ) + """Reference sentence pairs to generate adaptive results.""" @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__( + self, + *, + language: List[str], + script: Optional[str] = None, + profanity_action: Optional[Union[str, "_models.ProfanityAction"]] = None, + profanity_marker: Optional[Union[str, "_models.ProfanityMarker"]] = None, + deployment_name_model: Optional[str] = None, + allow_fallback: Optional[bool] = None, + grade: Optional[str] = None, + tone: Optional[str] = None, + gender: Optional[str] = None, + adaptive_dataset_id: Optional[str] = None, + reference_text_pairs: Optional[List["_models.ReferenceSentencePair"]] = 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TranslationLanguage(_model_base.Model): +class TranslationLanguage(_Model): """The value of the translation property is a dictionary of (key, value) pairs. Each key is a BCP 47 language tag. A key identifies a language for which text can be translated to or translated from. - All required parameters must be populated in order to send to server. - :ivar name: Display name of the language in the locale requested via Accept-Language header. Required. :vartype name: str @@ -945,11 +696,13 @@ class TranslationLanguage(_model_base.Model): :vartype dir: str or ~azure.ai.translation.text.models.LanguageDirectionality """ - name: str = rest_field() + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Display name of the language in the locale requested via Accept-Language header. Required.""" - native_name: str = rest_field(name="nativeName") + native_name: str = rest_field(name="nativeName", visibility=["read", "create", "update", "delete", "query"]) """Display name of the language in the locale native for this language. Required.""" - dir: Union[str, "_models.LanguageDirectionality"] = rest_field() + dir: Union[str, "_models.LanguageDirectionality"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. Required. Known values are: \"ltr\" and \"rtl\".""" @@ -960,24 +713,22 @@ def __init__( name: str, native_name: str, dir: Union[str, "_models.LanguageDirectionality"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TranslationText(_model_base.Model): +class TranslationText(_Model): """Translation result. - All required parameters must be populated in order to send to server. - :ivar to: A string representing the language code of the target language. Required. :vartype to: str :ivar text: A string giving the translated text. Required. @@ -985,22 +736,16 @@ class TranslationText(_model_base.Model): :ivar transliteration: An object giving the translated text in the script specified by the toScript parameter. :vartype transliteration: ~azure.ai.translation.text.models.TransliteratedText - :ivar alignment: Alignment information. - :vartype alignment: ~azure.ai.translation.text.models.TranslatedTextAlignment - :ivar sent_len: Sentence boundaries in the input and output texts. - :vartype sent_len: ~azure.ai.translation.text.models.SentenceBoundaries """ - to: str = rest_field() + to: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A string representing the language code of the target language. Required.""" - text: str = rest_field() + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A string giving the translated text. Required.""" - transliteration: Optional["_models.TransliteratedText"] = rest_field() + transliteration: Optional["_models.TransliteratedText"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """An object giving the translated text in the script specified by the toScript parameter.""" - alignment: Optional["_models.TranslatedTextAlignment"] = rest_field() - """Alignment information.""" - sent_len: Optional["_models.SentenceBoundaries"] = rest_field(name="sentLen") - """Sentence boundaries in the input and output texts.""" @overload def __init__( @@ -1009,26 +754,22 @@ def __init__( to: str, text: str, transliteration: Optional["_models.TransliteratedText"] = None, - alignment: Optional["_models.TranslatedTextAlignment"] = None, - sent_len: Optional["_models.SentenceBoundaries"] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class TransliterableScript(LanguageScript): """Script definition with list of script into which given script can be translitered. - All required parameters must be populated in order to send to server. - :ivar code: Code identifying the script. Required. :vartype code: str :ivar name: Display name of the script in the locale requested via Accept-Language header. @@ -1044,7 +785,9 @@ class TransliterableScript(LanguageScript): :vartype to_scripts: list[~azure.ai.translation.text.models.LanguageScript] """ - to_scripts: List["_models.LanguageScript"] = rest_field(name="toScripts") + to_scripts: List["_models.LanguageScript"] = rest_field( + name="toScripts", visibility=["read", "create", "update", "delete", "query"] + ) """List of scripts available to convert text to. Required.""" @overload @@ -1056,24 +799,22 @@ def __init__( native_name: str, dir: Union[str, "_models.LanguageDirectionality"], to_scripts: List["_models.LanguageScript"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TransliteratedText(_model_base.Model): +class TransliteratedText(_Model): """Transliterated text element. - All required parameters must be populated in order to send to server. - :ivar text: A string which is the result of converting the input string to the output script. Required. :vartype text: str @@ -1081,9 +822,9 @@ class TransliteratedText(_model_base.Model): :vartype script: str """ - text: str = rest_field() + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A string which is the result of converting the input string to the output script. Required.""" - script: str = rest_field() + script: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A string specifying the script used in the output. Required.""" @overload @@ -1092,27 +833,25 @@ def __init__( *, text: str, script: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class TransliterationLanguage(_model_base.Model): +class TransliterationLanguage(_Model): """The value of the transliteration property is a dictionary of (key, value) pairs. Each key is a BCP 47 language tag. A key identifies a language for which text can be converted from one script to another script. - All required parameters must be populated in order to send to server. - :ivar name: Display name of the language in the locale requested via Accept-Language header. Required. :vartype name: str @@ -1123,11 +862,13 @@ class TransliterationLanguage(_model_base.Model): :vartype scripts: list[~azure.ai.translation.text.models.TransliterableScript] """ - name: str = rest_field() + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Display name of the language in the locale requested via Accept-Language header. Required.""" - native_name: str = rest_field(name="nativeName") + native_name: str = rest_field(name="nativeName", visibility=["read", "create", "update", "delete", "query"]) """Display name of the language in the locale native for this language. Required.""" - scripts: List["_models.TransliterableScript"] = rest_field() + scripts: List["_models.TransliterableScript"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """List of scripts to convert from. Required.""" @overload @@ -1137,14 +878,14 @@ def __init__( name: str, native_name: str, scripts: List["_models.TransliterableScript"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + 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: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_patch.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_patch.py index f7dd32510333..8bcb627aa475 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_patch.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_patch.py @@ -1,7 +1,8 @@ -# ------------------------------------ -# 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 diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_maximum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_maximum_set_gen.py new file mode 100644 index 000000000000..a93764801ae8 --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_maximum_set_gen.py @@ -0,0 +1,30 @@ +# 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.text import TextTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-text +# USAGE + python get_supported_languages_maximum_set_gen.py +""" + + +def main(): + client = TextTranslationClient( + endpoint="ENDPOINT", + ) + + response = client.get_supported_languages() + print(response) + + +# x-ms-original-file: 2025-05-01-preview/GetSupportedLanguages_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_minimum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_minimum_set_gen.py new file mode 100644 index 000000000000..27bddbf2821c --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_minimum_set_gen.py @@ -0,0 +1,30 @@ +# 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.text import TextTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-text +# USAGE + python get_supported_languages_minimum_set_gen.py +""" + + +def main(): + client = TextTranslationClient( + endpoint="ENDPOINT", + ) + + response = client.get_supported_languages() + print(response) + + +# x-ms-original-file: 2025-05-01-preview/GetSupportedLanguages_MinimumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/translate_maximum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/translate_maximum_set_gen.py new file mode 100644 index 000000000000..34d56f109b05 --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_samples/translate_maximum_set_gen.py @@ -0,0 +1,59 @@ +# 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.text import TextTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-text +# USAGE + python translate_maximum_set_gen.py +""" + + +def main(): + client = TextTranslationClient( + endpoint="ENDPOINT", + ) + + response = client.translate( + body=[ + { + "language": "en", + "script": "Latn", + "targets": [ + { + "adaptiveDatasetId": "21000", + "allowFallback": True, + "deploymentNameModel": "general", + "gender": "neutral", + "grade": "basic", + "language": ["cs"], + "profanityAction": "NoAction", + "profanityMarker": "Asterisk", + "referenceTextPairs": [ + { + "referenceTextPairsSource": "Please test this out.", + "referenceTextPairsTarget": "Vyzkoušejte si to.", + } + ], + "script": "Latn", + "tone": "formal", + } + ], + "text": "This is a test.", + "textType": "Plain", + } + ], + ) + print(response) + + +# x-ms-original-file: 2025-05-01-preview/Translate_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/translate_minimum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/translate_minimum_set_gen.py new file mode 100644 index 000000000000..2e5597cfc418 --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_samples/translate_minimum_set_gen.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.text import TextTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-text +# USAGE + python translate_minimum_set_gen.py +""" + + +def main(): + client = TextTranslationClient( + endpoint="ENDPOINT", + ) + + response = client.translate( + body=[{"targets": [{"language": ["cs"]}], "text": "This is a test."}], + ) + print(response) + + +# x-ms-original-file: 2025-05-01-preview/Translate_MinimumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_maximum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_maximum_set_gen.py new file mode 100644 index 000000000000..5310f8cc379c --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_maximum_set_gen.py @@ -0,0 +1,35 @@ +# 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.text import TextTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-text +# USAGE + python transliterate_maximum_set_gen.py +""" + + +def main(): + client = TextTranslationClient( + endpoint="ENDPOINT", + ) + + response = client.transliterate( + body=[{"text": "这是个测试。"}], + language="zh-Hans", + from_script="Hans", + to_script="Latn", + ) + print(response) + + +# x-ms-original-file: 2025-05-01-preview/Transliterate_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_minimum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_minimum_set_gen.py new file mode 100644 index 000000000000..dcad0fd9526f --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_minimum_set_gen.py @@ -0,0 +1,35 @@ +# 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.text import TextTranslationClient + +""" +# PREREQUISITES + pip install azure-ai-translation-text +# USAGE + python transliterate_minimum_set_gen.py +""" + + +def main(): + client = TextTranslationClient( + endpoint="ENDPOINT", + ) + + response = client.transliterate( + body=[{"text": "这是个测试。"}], + language="zh-Hans", + from_script="Hans", + to_script="Latn", + ) + print(response) + + +# x-ms-original-file: 2025-05-01-preview/Transliterate_MinimumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/translation/azure-ai-translation-text/generated_tests/conftest.py b/sdk/translation/azure-ai-translation-text/generated_tests/conftest.py new file mode 100644 index 000000000000..d2b8a8df43e7 --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_tests/conftest.py @@ -0,0 +1,39 @@ +# 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): + texttranslation_subscription_id = os.environ.get( + "TEXTTRANSLATION_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + texttranslation_tenant_id = os.environ.get("TEXTTRANSLATION_TENANT_ID", "00000000-0000-0000-0000-000000000000") + texttranslation_client_id = os.environ.get("TEXTTRANSLATION_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + texttranslation_client_secret = os.environ.get( + "TEXTTRANSLATION_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=texttranslation_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=texttranslation_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=texttranslation_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=texttranslation_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-text/generated_tests/test_text_translation.py b/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation.py new file mode 100644 index 000000000000..5cc75c70fa34 --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation.py @@ -0,0 +1,71 @@ +# 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 TextTranslationClientTestBase, TextTranslationPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestTextTranslation(TextTranslationClientTestBase): + @TextTranslationPreparer() + @recorded_by_proxy + def test_get_supported_languages(self, texttranslation_endpoint): + client = self.create_client(endpoint=texttranslation_endpoint) + response = client.get_supported_languages() + + # please add some check logic here by yourself + # ... + + @TextTranslationPreparer() + @recorded_by_proxy + def test_translate(self, texttranslation_endpoint): + client = self.create_client(endpoint=texttranslation_endpoint) + response = client.translate( + body=[ + { + "targets": [ + { + "language": ["str"], + "adaptiveDatasetId": "str", + "allowFallback": bool, + "deploymentNameModel": "str", + "gender": "str", + "grade": "str", + "profanityAction": "str", + "profanityMarker": "str", + "referenceTextPairs": [ + {"referenceTextPairsSource": "str", "referenceTextPairsTarget": "str"} + ], + "script": "str", + "tone": "str", + } + ], + "text": "str", + "language": "str", + "script": "str", + "textType": "str", + } + ], + ) + + # please add some check logic here by yourself + # ... + + @TextTranslationPreparer() + @recorded_by_proxy + def test_transliterate(self, texttranslation_endpoint): + client = self.create_client(endpoint=texttranslation_endpoint) + response = client.transliterate( + body=[{"text": "str"}], + language="str", + from_script="str", + to_script="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation_async.py b/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation_async.py new file mode 100644 index 000000000000..199e4e2842ff --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation_async.py @@ -0,0 +1,72 @@ +# 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 TextTranslationPreparer +from testpreparer_async import TextTranslationClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestTextTranslationAsync(TextTranslationClientTestBaseAsync): + @TextTranslationPreparer() + @recorded_by_proxy_async + async def test_get_supported_languages(self, texttranslation_endpoint): + client = self.create_async_client(endpoint=texttranslation_endpoint) + response = await client.get_supported_languages() + + # please add some check logic here by yourself + # ... + + @TextTranslationPreparer() + @recorded_by_proxy_async + async def test_translate(self, texttranslation_endpoint): + client = self.create_async_client(endpoint=texttranslation_endpoint) + response = await client.translate( + body=[ + { + "targets": [ + { + "language": ["str"], + "adaptiveDatasetId": "str", + "allowFallback": bool, + "deploymentNameModel": "str", + "gender": "str", + "grade": "str", + "profanityAction": "str", + "profanityMarker": "str", + "referenceTextPairs": [ + {"referenceTextPairsSource": "str", "referenceTextPairsTarget": "str"} + ], + "script": "str", + "tone": "str", + } + ], + "text": "str", + "language": "str", + "script": "str", + "textType": "str", + } + ], + ) + + # please add some check logic here by yourself + # ... + + @TextTranslationPreparer() + @recorded_by_proxy_async + async def test_transliterate(self, texttranslation_endpoint): + client = self.create_async_client(endpoint=texttranslation_endpoint) + response = await client.transliterate( + body=[{"text": "str"}], + language="str", + from_script="str", + to_script="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer.py b/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer.py new file mode 100644 index 000000000000..83a74beedfe2 --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer.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. +# -------------------------------------------------------------------------- +from azure.ai.translation.text import TextTranslationClient +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +import functools + + +class TextTranslationClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(TextTranslationClient) + return self.create_client_from_credential( + TextTranslationClient, + credential=credential, + endpoint=endpoint, + ) + + +TextTranslationPreparer = functools.partial( + PowerShellPreparer, "texttranslation", texttranslation_endpoint="https://fake_texttranslation_endpoint.com" +) diff --git a/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer_async.py b/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer_async.py new file mode 100644 index 000000000000..b8013a976e7c --- /dev/null +++ b/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer_async.py @@ -0,0 +1,20 @@ +# 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.text.aio import TextTranslationClient +from devtools_testutils import AzureRecordedTestCase + + +class TextTranslationClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(TextTranslationClient, is_async=True) + return self.create_client_from_credential( + TextTranslationClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_break_sentence.py b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_break_sentence.py index 86a0d4ca55b2..38ad7060a804 100644 --- a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_break_sentence.py +++ b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_break_sentence.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_client.py b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_client.py index 25e7004a4af7..b6e736155ff6 100644 --- a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_client.py +++ b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_client.py @@ -54,6 +54,7 @@ def create_text_translation_client_with_credential(): # [END create_text_translation_client_with_credential] return text_translator + def create_text_translation_client_custom_with_credential(): from azure.ai.translation.text import TextTranslationClient from azure.core.credentials import AzureKeyCredential @@ -66,6 +67,7 @@ def create_text_translation_client_custom_with_credential(): # [END create_text_translation_client_custom_with_credential] return text_translator + def create_text_translation_client_with_cognitive_services_token(): from azure.ai.translation.text import TextTranslationClient from azure.core.credentials import TokenCredential @@ -79,6 +81,7 @@ def create_text_translation_client_with_cognitive_services_token(): client = TextTranslationClient(credential=credential, audience="https://api.microsofttranslator.com/") # [END create_text_translation_client_with_cognitive_services_token] + def create_text_translation_client_with_entra_id_token(): from azure.ai.translation.text import TextTranslationClient from azure.identity import DefaultAzureCredential @@ -91,6 +94,7 @@ def create_text_translation_client_with_entra_id_token(): client = TextTranslationClient(credential=credential, region=region, resource_id=resource_id) # [END create_text_translation_client_with_entra_id_token] + def create_text_translation_client_custom_with_entra_id_token(): from azure.ai.translation.text import TextTranslationClient from azure.identity import DefaultAzureCredential diff --git a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_dictionary_examples.py b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_dictionary_examples.py index 5ffd4af66589..3e39eabc4631 100644 --- a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_dictionary_examples.py +++ b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_dictionary_examples.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_dictionary_lookup.py b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_dictionary_lookup.py index 2db0d329f1fa..6e6895216143 100644 --- a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_dictionary_lookup.py +++ b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_dictionary_lookup.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_languages.py b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_languages.py index 66f3cb8c0ee1..577f98d4060e 100644 --- a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_languages.py +++ b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_languages.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_translate.py b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_translate.py index 3f095a474f75..4a73977fcef2 100644 --- a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_translate.py +++ b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_translate.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_transliterate.py b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_transliterate.py index 14ea30724109..d0f15f9fd120 100644 --- a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_transliterate.py +++ b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_transliterate.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for diff --git a/sdk/translation/azure-ai-translation-text/setup.py b/sdk/translation/azure-ai-translation-text/setup.py index fd168a300310..a353b9c9f8ca 100644 --- a/sdk/translation/azure-ai-translation-text/setup.py +++ b/sdk/translation/azure-ai-translation-text/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,11 +38,10 @@ 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", @@ -68,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-text/tests/test_break_sentence.py b/sdk/translation/azure-ai-translation-text/tests/test_break_sentence.py index 5ea0659a5f22..1e706ffb4d58 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_break_sentence.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_break_sentence.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -21,7 +22,9 @@ def test_autodetect(self, **kwargs): response = client.find_sentence_boundaries(body=input_text_elements) assert response is not None assert response[0].detected_language.language == "en" - assert response[0].detected_language.score > 0.8 # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493 + assert ( + response[0].detected_language.score > 0.8 + ) # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493 assert response[0].sent_len[0] == 11 @TextTranslationPreparer() diff --git a/sdk/translation/azure-ai-translation-text/tests/test_break_sentence_async.py b/sdk/translation/azure-ai-translation-text/tests/test_break_sentence_async.py index cef2c50888d3..557a980ba922 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_break_sentence_async.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_break_sentence_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -22,7 +23,9 @@ async def test_autodetect(self, **kwargs): response = await client.find_sentence_boundaries(body=input_text_elements) assert response is not None assert response[0].detected_language.language == "en" - assert response[0].detected_language.score > 0.8 # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493 + assert ( + response[0].detected_language.score > 0.8 + ) # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493 assert response[0].sent_len[0] == 11 @TextTranslationPreparer() diff --git a/sdk/translation/azure-ai-translation-text/tests/test_translation.py b/sdk/translation/azure-ai-translation-text/tests/test_translation.py index ba4098075df8..f9dd62094048 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_translation.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_translation.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -225,7 +226,7 @@ def test_profanity(self, **kwargs): assert len(response[0].translations) == 1 assert response[0].detected_language.language == "en" assert response[0].detected_language.score == 1 - #assert "***" in response[0].translations[0].text # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493 + # assert "***" in response[0].translations[0].text # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493 @TextTranslationPreparer() @recorded_by_proxy diff --git a/sdk/translation/azure-ai-translation-text/tests/test_translation_async.py b/sdk/translation/azure-ai-translation-text/tests/test_translation_async.py index d2bff209f6d2..f48af7962cf3 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_translation_async.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_translation_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -242,7 +243,7 @@ async def test_profanity(self, **kwargs): assert len(response[0].translations) == 1 assert response[0].detected_language.language == "en" assert response[0].detected_language.score == 1 - #assert "***" in response[0].translations[0].text # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493 + # assert "***" in response[0].translations[0].text # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493 @TextTranslationPreparer() @recorded_by_proxy_async diff --git a/sdk/translation/azure-ai-translation-text/tsp-location.yaml b/sdk/translation/azure-ai-translation-text/tsp-location.yaml index 913c42604909..0451f5a6157c 100644 --- a/sdk/translation/azure-ai-translation-text/tsp-location.yaml +++ b/sdk/translation/azure-ai-translation-text/tsp-location.yaml @@ -1,3 +1,4 @@ directory: specification/translation/Azure.AI.TextTranslation -commit: 5656333510e6c6b8c4027c73933349f1f16a0fe6 +commit: 147495e1b6cfe5607d481278e31857dc929b42fa repo: Azure/azure-rest-api-specs +additionalDirectories: