diff --git a/sdk/translation/azure-ai-translation-text/CHANGELOG.md b/sdk/translation/azure-ai-translation-text/CHANGELOG.md index a1cfabc1ffbd..2d6a9700cfad 100644 --- a/sdk/translation/azure-ai-translation-text/CHANGELOG.md +++ b/sdk/translation/azure-ai-translation-text/CHANGELOG.md @@ -1,18 +1,15 @@ # Release History -## 1.0.0b2 (Unreleased) +## 1.0.0 (2024-05-21) ### Features Added - - Added support for AAD authentication. + - Added support for Entra Id authentication. ### Breaking Changes - - All calls to the client using parameter 'content' have been changed to use parameter 'request_body'. + - All calls to the client using parameter `content` have been changed to use parameter `body`. - Users can call methods using just a string type instead of complex objects. - -### Bugs Fixed - -### Other Changes + - `get_languages` methods were changed to `get_supported_languages`. ## 1.0.0b1 (2023-04-19) diff --git a/sdk/translation/azure-ai-translation-text/README.md b/sdk/translation/azure-ai-translation-text/README.md index 0dc338f0bf76..796c6bc8b137 100644 --- a/sdk/translation/azure-ai-translation-text/README.md +++ b/sdk/translation/azure-ai-translation-text/README.md @@ -55,7 +55,7 @@ az cognitiveservices account keys list --resource-group ```python -credential = TranslatorCredential(apikey, region) -text_translator = TextTranslationClient(credential=credential, endpoint=endpoint) +credential = AzureKeyCredential(apikey) +text_translator = TextTranslationClient(credential=credential, endpoint=endpoint, region=region) ``` @@ -92,7 +92,7 @@ Gets the set of languages currently supported by other operations of the Transla ```python try: - response = text_translator.get_languages() + response = text_translator.get_supported_languages() print( f"Number of supported languages for translate operation: {len(response.translation) if response.translation is not None else 0}" @@ -140,10 +140,10 @@ Renders single source-language text to multiple target-language texts with a sin ```python try: - target_languages = ["cs", "es", "de"] + to = ["cs", "es", "de"] input_text_elements = ["This is a test"] - response = text_translator.translate(request_body=input_text_elements, to=target_languages) + response = text_translator.translate(body=input_text_elements, to=to) translation = response[0] if response else None if translation: @@ -182,7 +182,10 @@ try: input_text_elements = ["这是个测试。"] response = text_translator.transliterate( - request_body=input_text_elements, language=language, from_script=from_script, to_script=to_script + body=input_text_elements, + language=language, + from_script=from_script, + to_script=to_script, ) transliteration = response[0] if response else None @@ -212,11 +215,11 @@ Identifies the positioning of sentence boundaries in a piece of text. ```python try: include_sentence_length = True - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["The answer lies in machine translation. This is a test."] response = text_translator.translate( - request_body=input_text_elements, to=target_languages, include_sentence_length=include_sentence_length + body=input_text_elements, to=to, include_sentence_length=include_sentence_length ) translation = response[0] if response else None @@ -252,12 +255,12 @@ Returns equivalent words for the source term in the target language. ```python try: - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = ["fly"] response = text_translator.lookup_dictionary_entries( - request_body=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) dictionary_entry = response[0] if response else None @@ -288,12 +291,12 @@ Returns grammatical structure and context examples for the source term and targe ```python try: - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = [DictionaryExampleTextItem(text="fly", translation="volar")] response = text_translator.lookup_dictionary_examples( - content=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) dictionary_entry = response[0] if response else None diff --git a/sdk/translation/azure-ai-translation-text/assets.json b/sdk/translation/azure-ai-translation-text/assets.json index 56df30dbc113..4f0bd1f71741 100644 --- a/sdk/translation/azure-ai-translation-text/assets.json +++ b/sdk/translation/azure-ai-translation-text/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/translation/azure-ai-translation-text", - "Tag": "python/translation/azure-ai-translation-text_afde2bdc8c" + "Tag": "python/translation/azure-ai-translation-text_35ab9367d7" } 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 052ec7a7213e..4b66a9e2dde2 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 @@ -6,16 +6,15 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._patch import TextTranslationClient, TranslatorCredential, TranslatorAADCredential +from ._patch import TextTranslationClient from ._version import VERSION __version__ = VERSION + from ._patch import patch_sdk as _patch_sdk __all__ = [ - "TranslatorCredential", - "TranslatorAADCredential", "TextTranslationClient", ] 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/_model_base.py index 1ddc071517d6..5cf70733404d 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/_model_base.py @@ -6,6 +6,7 @@ # -------------------------------------------------------------------------- # pylint: disable=protected-access, arguments-differ, signature-differs, broad-except +import copy import calendar import decimal import functools @@ -13,7 +14,6 @@ import logging import base64 import re -import copy import typing import enum import email.utils @@ -339,7 +339,7 @@ def _get_model(module_name: str, model_name: str): class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object def __init__(self, data: typing.Dict[str, typing.Any]) -> None: - self._data = copy.deepcopy(data) + self._data = data def __contains__(self, key: typing.Any) -> bool: return key in self._data @@ -378,16 +378,13 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: return default @typing.overload - def pop(self, key: str) -> typing.Any: - ... + def pop(self, key: str) -> typing.Any: ... @typing.overload - def pop(self, key: str, default: _T) -> _T: - ... + def pop(self, key: str, default: _T) -> _T: ... @typing.overload - def pop(self, key: str, default: typing.Any) -> typing.Any: - ... + def pop(self, key: str, default: typing.Any) -> typing.Any: ... def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: if default is _UNSET: @@ -404,12 +401,10 @@ def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: self._data.update(*args, **kwargs) @typing.overload - def setdefault(self, key: str, default: None = None) -> None: - ... + 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: ... def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: if default is _UNSET: @@ -594,6 +589,64 @@ def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: typing.Dict[typing.Any, typing.Any], +): + if obj is None: + return obj + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: typing.List[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, R0912 annotation: typing.Any, module: typing.Optional[str], @@ -621,11 +674,6 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, if rf: rf._is_model = True - def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): - if _is_model(obj): - return obj - return _deserialize(model_deserializer, obj) - return functools.partial(_deserialize_model, annotation) # pyright: ignore except Exception: pass @@ -640,36 +688,27 @@ def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj # is it optional? try: if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore - if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore - ) - - def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): - if obj is None: - return obj - return _deserialize_with_callable(if_obj_deserializer, obj) - - return functools.partial(_deserialize_with_optional, if_obj_deserializer) + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass + # is it union? if getattr(annotation, "__origin__", None) is typing.Union: # initial ordering is we make `string` the last deserialization option, because it is often them most generic deserializers = [ _get_deserialize_callable_from_annotation(arg, module, rf) - for arg in sorted( - annotation.__args__, key=lambda x: hasattr(x, "__name__") and x.__name__ == "str" # pyright: ignore - ) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore ] - def _deserialize_with_union(deserializers, obj): - for deserializer in deserializers: - try: - return _deserialize(deserializer, obj) - except DeserializationError: - pass - raise DeserializationError() - return functools.partial(_deserialize_with_union, deserializers) try: @@ -678,17 +717,10 @@ def _deserialize_with_union(deserializers, obj): annotation.__args__[1], module, rf # pyright: ignore ) - def _deserialize_dict( - value_deserializer: typing.Optional[typing.Callable], - obj: typing.Dict[typing.Any, typing.Any], - ): - if obj is None: - return obj - return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} - return functools.partial( _deserialize_dict, value_deserializer, + module, ) except (AttributeError, IndexError): pass @@ -696,35 +728,16 @@ def _deserialize_dict( if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore if len(annotation.__args__) > 1: # pyright: ignore - def _deserialize_multiple_sequence( - entry_deserializers: typing.List[typing.Optional[typing.Callable]], - obj, - ): - if obj is None: - return obj - return type(obj)( - _deserialize(deserializer, entry, module) - for entry, deserializer in zip(obj, entry_deserializers) - ) - entry_deserializers = [ _get_deserialize_callable_from_annotation(dt, module, rf) for dt in annotation.__args__ # pyright: ignore ] - return functools.partial(_deserialize_multiple_sequence, entry_deserializers) + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) deserializer = _get_deserialize_callable_from_annotation( annotation.__args__[0], module, rf # pyright: ignore ) - def _deserialize_sequence( - deserializer: typing.Optional[typing.Callable], - obj, - ): - if obj is None: - return obj - return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) - - return functools.partial(_deserialize_sequence, deserializer) + return functools.partial(_deserialize_sequence, deserializer, module) except (TypeError, IndexError, AttributeError, SyntaxError): pass 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 2cad8d4badf9..968c088aa7aa 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 @@ -6,9 +6,11 @@ # 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 io import IOBase import json -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload +import sys +from typing import Any, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, overload from azure.core import MatchConditions from azure.core.exceptions import ( @@ -30,6 +32,10 @@ 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 T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -37,7 +43,7 @@ _SERIALIZER.client_side_validation = False -def build_text_translation_get_languages_request( # pylint: disable=name-too-long +def build_text_translation_get_supported_languages_request( # pylint: disable=name-too-long *, client_trace_id: Optional[str] = None, scope: Optional[str] = None, @@ -132,9 +138,9 @@ def build_text_translation_translate_request( # Construct headers if client_trace_id is not None: _headers["X-ClientTraceId"] = _SERIALIZER.header("client_trace_id", client_trace_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "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) @@ -161,9 +167,9 @@ def build_text_translation_transliterate_request( # pylint: disable=name-too-lo # Construct headers if client_trace_id is not None: _headers["X-ClientTraceId"] = _SERIALIZER.header("client_trace_id", client_trace_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "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) @@ -195,9 +201,9 @@ def build_text_translation_find_sentence_boundaries_request( # pylint: disable= # Construct headers if client_trace_id is not None: _headers["X-ClientTraceId"] = _SERIALIZER.header("client_trace_id", client_trace_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "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) @@ -223,9 +229,9 @@ def build_text_translation_lookup_dictionary_entries_request( # pylint: disable # Construct headers if client_trace_id is not None: _headers["X-ClientTraceId"] = _SERIALIZER.header("client_trace_id", client_trace_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "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) @@ -251,16 +257,17 @@ def build_text_translation_lookup_dictionary_examples_request( # pylint: disabl # Construct headers if client_trace_id is not None: _headers["X-ClientTraceId"] = _SERIALIZER.header("client_trace_id", client_trace_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "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): + @distributed_trace - def get_languages( + def get_supported_languages( self, *, client_trace_id: Optional[str] = None, @@ -269,7 +276,7 @@ def get_languages( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.GetLanguagesResult: + ) -> _models.GetSupportedLanguagesResult: # pylint: disable=line-too-long """Gets the set of languages currently supported by other operations of the Translator. @@ -279,7 +286,7 @@ def get_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 @@ -301,8 +308,9 @@ def get_languages( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: GetLanguagesResult. The GetLanguagesResult is compatible with MutableMapping - :rtype: ~azure.ai.translation.text.models.GetLanguagesResult + :return: GetSupportedLanguagesResult. The GetSupportedLanguagesResult is compatible with + MutableMapping + :rtype: ~azure.ai.translation.text.models.GetSupportedLanguagesResult :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -314,6 +322,7 @@ def get_languages( "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 @@ -324,7 +333,7 @@ def get_languages( the target language. Required. "dir": "str", # Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - Required. + Required. Known values are: "ltr" and "rtl". "name": "str", # Display name of the language in the locale requested via Accept-Language header. Required. @@ -338,6 +347,7 @@ def get_languages( "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 @@ -356,7 +366,7 @@ def get_languages( script. Required. "dir": "str", # Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - Required. + 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 @@ -367,7 +377,8 @@ def get_languages( identifying the script. Required. "dir": "str", # Directionality, which is rtl for right-to-left languages - or ltr for left-to-right languages. Required. + 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. @@ -382,7 +393,7 @@ def get_languages( } } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -399,9 +410,9 @@ def get_languages( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.GetLanguagesResult] = kwargs.pop("cls", None) + cls: ClsType[_models.GetSupportedLanguagesResult] = kwargs.pop("cls", None) - _request = build_text_translation_get_languages_request( + _request = build_text_translation_get_supported_languages_request( client_trace_id=client_trace_id, scope=scope, accept_language=accept_language, @@ -437,7 +448,7 @@ def get_languages( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.GetLanguagesResult, response.json()) + deserialized = _deserialize(_models.GetSupportedLanguagesResult, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -447,7 +458,7 @@ def get_languages( @overload def translate( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, to: List[str], client_trace_id: Optional[str] = None, @@ -470,8 +481,8 @@ def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.InputTextItem] :keyword to: 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. @@ -555,7 +566,7 @@ def translate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -623,7 +634,7 @@ def translate( @overload def translate( self, - request_body: IO[bytes], + body: IO[bytes], *, to: List[str], client_trace_id: Optional[str] = None, @@ -646,8 +657,8 @@ def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword to: 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. @@ -792,7 +803,7 @@ def translate( @distributed_trace def translate( self, - request_body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.InputTextItem], IO[bytes]], *, to: List[str], client_trace_id: Optional[str] = None, @@ -814,9 +825,9 @@ def translate( Translate Text. - :param request_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 [InputTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] + :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] :keyword to: 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. @@ -954,7 +965,7 @@ def translate( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -970,10 +981,10 @@ def translate( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_translate_request( to=to, @@ -1032,7 +1043,7 @@ def translate( @overload def transliterate( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, language: str, from_script: str, @@ -1045,8 +1056,8 @@ def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :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. @@ -1073,7 +1084,7 @@ def transliterate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -1093,7 +1104,7 @@ def transliterate( @overload def transliterate( self, - request_body: IO[bytes], + body: IO[bytes], *, language: str, from_script: str, @@ -1106,8 +1117,8 @@ def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :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. @@ -1147,7 +1158,7 @@ def transliterate( @distributed_trace def transliterate( self, - request_body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.InputTextItem], IO[bytes]], *, language: str, from_script: str, @@ -1159,9 +1170,9 @@ def transliterate( Transliterate Text. - :param request_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 [InputTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] + :type body: list[~azure.ai.translation.text.models.InputTextItem] or 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. @@ -1194,7 +1205,7 @@ def transliterate( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1210,10 +1221,10 @@ def transliterate( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_transliterate_request( language=language, @@ -1261,7 +1272,7 @@ def transliterate( @overload def find_sentence_boundaries( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -1274,8 +1285,8 @@ def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :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 @@ -1298,7 +1309,7 @@ def find_sentence_boundaries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -1326,7 +1337,7 @@ def find_sentence_boundaries( @overload def find_sentence_boundaries( self, - request_body: IO[bytes], + body: IO[bytes], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -1339,8 +1350,8 @@ def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :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 @@ -1384,7 +1395,7 @@ def find_sentence_boundaries( @distributed_trace def find_sentence_boundaries( self, - request_body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.InputTextItem], IO[bytes]], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -1396,9 +1407,9 @@ def find_sentence_boundaries( Find Sentence Boundaries. - :param request_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 [InputTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] + :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 @@ -1435,7 +1446,7 @@ def find_sentence_boundaries( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1451,10 +1462,10 @@ def find_sentence_boundaries( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _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, @@ -1501,7 +1512,7 @@ def find_sentence_boundaries( @overload def lookup_dictionary_entries( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, from_parameter: str, to: str, @@ -1514,8 +1525,8 @@ def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.InputTextItem] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1538,7 +1549,7 @@ def lookup_dictionary_entries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -1616,7 +1627,7 @@ def lookup_dictionary_entries( @overload def lookup_dictionary_entries( self, - request_body: IO[bytes], + body: IO[bytes], *, from_parameter: str, to: str, @@ -1629,8 +1640,8 @@ def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1724,7 +1735,7 @@ def lookup_dictionary_entries( @distributed_trace def lookup_dictionary_entries( self, - request_body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.InputTextItem], IO[bytes]], *, from_parameter: str, to: str, @@ -1736,9 +1747,9 @@ def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_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 [InputTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] + :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1825,7 +1836,7 @@ def lookup_dictionary_entries( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1841,10 +1852,10 @@ def lookup_dictionary_entries( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_lookup_dictionary_entries_request( from_parameter=from_parameter, @@ -1891,7 +1902,7 @@ def lookup_dictionary_entries( @overload def lookup_dictionary_examples( self, - request_body: List[_models.DictionaryExampleTextItem], + body: List[_models.DictionaryExampleTextItem], *, from_parameter: str, to: str, @@ -1904,8 +1915,8 @@ def lookup_dictionary_examples( Lookup Dictionary Examples. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1928,7 +1939,7 @@ def lookup_dictionary_examples( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str", # Text to translate. Required. "translation": "str" # A string specifying the translated text @@ -1978,7 +1989,7 @@ def lookup_dictionary_examples( @overload def lookup_dictionary_examples( self, - request_body: IO[bytes], + body: IO[bytes], *, from_parameter: str, to: str, @@ -1991,8 +2002,8 @@ def lookup_dictionary_examples( Lookup Dictionary Examples. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -2053,7 +2064,7 @@ def lookup_dictionary_examples( @distributed_trace def lookup_dictionary_examples( self, - request_body: Union[List[_models.DictionaryExampleTextItem], IO[bytes]], + body: Union[List[_models.DictionaryExampleTextItem], IO[bytes]], *, from_parameter: str, to: str, @@ -2065,10 +2076,9 @@ def lookup_dictionary_examples( Lookup Dictionary Examples. - :param request_body: Defines the content of the request. Is either a - [DictionaryExampleTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] or - IO[bytes] + :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_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -2122,7 +2132,7 @@ def lookup_dictionary_examples( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2138,10 +2148,10 @@ def lookup_dictionary_examples( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_lookup_dictionary_examples_request( from_parameter=from_parameter, 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 47dc2df2c1a0..ec03767f5bac 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 @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ +# pylint: disable=C0302 + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize @@ -15,7 +17,7 @@ class TextTranslationClientOperationsMixin(TextTranslationClientOperationsMixinG @overload def translate( self, - request_body: List[str], + body: List[str], *, to: List[str], client_trace_id: Optional[str] = None, @@ -38,8 +40,8 @@ def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[str] + :param body: Defines the content of the request. Required. + :type body: list[str] :keyword to: 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. @@ -123,7 +125,7 @@ def translate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ str" # Text to translate. Required. ] @@ -189,7 +191,7 @@ def translate( @overload def translate( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, to: List[str], client_trace_id: Optional[str] = None, @@ -212,8 +214,8 @@ def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.InputTextItem] :keyword to: 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. @@ -297,7 +299,7 @@ def translate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -365,7 +367,7 @@ def translate( @overload def translate( self, - request_body: IO[bytes], + body: IO[bytes], *, to: List[str], client_trace_id: Optional[str] = None, @@ -388,8 +390,8 @@ def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword to: 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. @@ -531,9 +533,9 @@ def translate( ] """ - def translate( + def translate( # pyright: ignore[reportIncompatibleMethodOverride] self, - request_body: Union[List[str], List[_models.InputTextItem], IO[bytes]], + body: Union[List[str], List[_models.InputTextItem], IO[bytes]], *, to: List[str], client_trace_id: Optional[str] = None, @@ -550,17 +552,17 @@ def translate( allow_fallback: Optional[bool] = None, **kwargs: Any ) -> List[_models.TranslatedTextItem]: - body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(request_body, list) and all(isinstance(item, str) for item in request_body): + 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 request_body: + for text in body: input_text_items.append(_models.InputTextItem(text=cast(str, text))) - body = input_text_items + request_body = input_text_items else: - body = cast(Union[List[_models.InputTextItem], IO[bytes]], request_body) + request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) return super().translate( - request_body=body, + body=request_body, to=to, client_trace_id=client_trace_id, from_parameter=from_parameter, @@ -580,7 +582,7 @@ def translate( @overload def transliterate( self, - request_body: List[str], + body: List[str], *, language: str, from_script: str, @@ -593,8 +595,8 @@ def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[str] + :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. @@ -621,7 +623,7 @@ def transliterate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -641,7 +643,7 @@ def transliterate( @overload def transliterate( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, language: str, from_script: str, @@ -654,8 +656,8 @@ def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :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. @@ -682,7 +684,7 @@ def transliterate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -702,7 +704,7 @@ def transliterate( @overload def transliterate( self, - request_body: IO[bytes], + body: IO[bytes], *, language: str, from_script: str, @@ -715,8 +717,8 @@ def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :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. @@ -753,9 +755,9 @@ def transliterate( ] """ - def transliterate( + def transliterate( # pyright: ignore[reportIncompatibleMethodOverride] self, - request_body: Union[List[str], List[_models.InputTextItem], IO[bytes]], + body: Union[List[str], List[_models.InputTextItem], IO[bytes]], *, language: str, from_script: str, @@ -763,17 +765,17 @@ def transliterate( client_trace_id: Optional[str] = None, **kwargs: Any ) -> List[_models.TransliteratedText]: - body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(request_body, list) and all(isinstance(item, str) for item in request_body): + 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 request_body: + for text in body: input_text_items.append(_models.InputTextItem(text=cast(str, text))) - body = input_text_items + request_body = input_text_items else: - body = cast(Union[List[_models.InputTextItem], IO[bytes]], request_body) + request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) return super().transliterate( - request_body=body, + body=request_body, language=language, from_script=from_script, to_script=to_script, @@ -784,7 +786,7 @@ def transliterate( @overload def find_sentence_boundaries( self, - request_body: List[str], + body: List[str], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -797,8 +799,8 @@ def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[str] + :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 @@ -821,7 +823,7 @@ def find_sentence_boundaries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -849,7 +851,7 @@ def find_sentence_boundaries( @overload def find_sentence_boundaries( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -862,8 +864,8 @@ def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :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 @@ -886,7 +888,7 @@ def find_sentence_boundaries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -914,7 +916,7 @@ def find_sentence_boundaries( @overload def find_sentence_boundaries( self, - request_body: IO[bytes], + body: IO[bytes], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -927,8 +929,8 @@ def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :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 @@ -969,33 +971,33 @@ def find_sentence_boundaries( ] """ - def find_sentence_boundaries( + def find_sentence_boundaries( # pyright: ignore[reportIncompatibleMethodOverride] self, - request_body: Union[List[str], List[_models.InputTextItem], IO[bytes]], + 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]: - body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(request_body, list) and all(isinstance(item, str) for item in request_body): + 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 request_body: + for text in body: input_text_items.append(_models.InputTextItem(text=cast(str, text))) - body = input_text_items + request_body = input_text_items else: - body = cast(Union[List[_models.InputTextItem], IO[bytes]], request_body) + request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) return super().find_sentence_boundaries( - request_body=body, language=language, script=script, client_trace_id=client_trace_id, **kwargs + body=request_body, language=language, script=script, client_trace_id=client_trace_id, **kwargs ) @overload def lookup_dictionary_entries( self, - request_body: List[str], + body: List[str], *, from_parameter: str, to: str, @@ -1008,8 +1010,8 @@ def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[str] + :param body: Defines the content of the request. Required. + :type body: list[str] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1032,7 +1034,7 @@ def lookup_dictionary_entries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -1078,7 +1080,7 @@ def lookup_dictionary_entries( "bad" examples. Required. } ], - "confidence": 0.0, # A value between 0.0 and 1.0 + "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 @@ -1110,7 +1112,7 @@ def lookup_dictionary_entries( @overload def lookup_dictionary_entries( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, from_parameter: str, to: str, @@ -1123,8 +1125,8 @@ def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.InputTextItem] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1147,7 +1149,7 @@ def lookup_dictionary_entries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -1193,7 +1195,7 @@ def lookup_dictionary_entries( "bad" examples. Required. } ], - "confidence": 0.0, # A value between 0.0 and 1.0 + "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 @@ -1225,7 +1227,7 @@ def lookup_dictionary_entries( @overload def lookup_dictionary_entries( self, - request_body: IO[bytes], + body: IO[bytes], *, from_parameter: str, to: str, @@ -1238,8 +1240,8 @@ def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1301,7 +1303,7 @@ def lookup_dictionary_entries( "bad" examples. Required. } ], - "confidence": 0.0, # A value between 0.0 and 1.0 + "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 @@ -1330,26 +1332,26 @@ def lookup_dictionary_entries( ] """ - def lookup_dictionary_entries( + def lookup_dictionary_entries( # pyright: ignore[reportIncompatibleMethodOverride] self, - request_body: Union[List[str], List[_models.InputTextItem], IO[bytes]], + body: Union[List[str], List[_models.InputTextItem], IO[bytes]], *, from_parameter: str, to: str, client_trace_id: Optional[str] = None, **kwargs: Any ) -> List[_models.DictionaryLookupItem]: - body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(request_body, list) and all(isinstance(item, str) for item in request_body): + 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 request_body: + for text in body: input_text_items.append(_models.InputTextItem(text=cast(str, text))) - body = input_text_items + request_body = input_text_items else: - body = cast(Union[List[_models.InputTextItem], IO[bytes]], request_body) + request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) return super().lookup_dictionary_entries( - request_body=body, from_parameter=from_parameter, to=to, client_trace_id=client_trace_id, **kwargs + body=request_body, from_parameter=from_parameter, to=to, client_trace_id=client_trace_id, **kwargs ) 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 ff215ce4fd24..a487ff800650 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 @@ -2,8 +2,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ +# pylint: disable=C4717, C4722, C4748 -from typing import Union, Optional, Any +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 @@ -11,6 +12,7 @@ from ._client import TextTranslationClient as ServiceClientGenerated DEFAULT_TOKEN_SCOPE = "https://api.microsofttranslator.com/" +DEFAULT_ENTRA_ID_SCOPE = "https://cognitiveservices.azure.com/.default" def patch_sdk(): @@ -22,74 +24,43 @@ def patch_sdk(): """ -class TranslatorCredential: - """Credential for Translator Service. It is using combination of Resource key and region.""" - - def __init__(self, key: str, region: str) -> None: - self.key = key - self.region = region - - def update(self, key: str) -> None: - """Update the key. - This can be used when you've regenerated your service key and want - to update long-lived clients. - :param str key: The key used to authenticate to an Azure service - :raises: ValueError or TypeError - """ - if not key: - raise ValueError("The key used for updating can not be None or empty") - if not isinstance(key, str): - raise TypeError("The key used for updating must be a string.") - self.key = key - - 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: TranslatorCredential): + 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.credential.region + request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.region -class TranslatorAADCredential: - """Credential for Translator Service when using AAD authentication. - :param tokenCredential: An object which can provide an access token for the Translator Resource, such as a credential from - :mod:`azure.identity` - :type tokenCredential: ~azure.core.credentials.TokenCredential - :param str resourceId: Azure Resource Id of the Translation Resource. - :param str region: Azure Region of the Translation Resource. - """ - - def __init__(self, tokenCredential: TokenCredential, resourceId: str, region: str) -> None: - self.tokenCredential = tokenCredential - self.resourceId = resourceId - self.region = region - -class TranslatorAADAuthenticationPolicy(BearerTokenCredentialPolicy): - """Translator AAD Authentication Policy. Adds headers that are required by Translator Service - when global endpoint is used with AAD policy. +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 AAD Credentials used to access Translator Resource for global Translator endpoint. - :type credential: ~azure.ai.translation.text.TranslatorAADCredential + :param credential: Translator Entra Id Credentials used to access Translator Resource for global endpoint. + :type credential: ~azure.core.credentials.TokenCredential """ - def __init__(self, credential: TranslatorAADCredential, **kwargs: Any)-> None: - super(TranslatorAADAuthenticationPolicy, self).__init__(credential.tokenCredential, "https://cognitiveservices.azure.com/.default", **kwargs) - self.translatorCredential = credential + def __init__(self, credential: TokenCredential, resource_id: str, region: str, scopes: str, **kwargs: Any) -> None: + super(TranslatorEntraIdAuthenticationPolicy, self).__init__(credential, scopes, **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.translatorCredential.resourceId - request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.translatorCredential.region + 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" @@ -104,22 +75,31 @@ def get_translation_endpoint(endpoint, api_version): def set_authentication_policy(credential, kwargs): - if isinstance(credential, TranslatorCredential): - if not kwargs.get("authentication_policy"): - kwargs["authentication_policy"] = TranslatorAuthenticationPolicy(credential) - elif isinstance(credential, TranslatorAADCredential): + if isinstance(credential, AzureKeyCredential): if not kwargs.get("authentication_policy"): - kwargs["authentication_policy"] = TranslatorAADAuthenticationPolicy(credential) - elif isinstance(credential, AzureKeyCredential): - if not kwargs.get("authentication_policy"): - kwargs["authentication_policy"] = AzureKeyCredentialPolicy( - name="Ocp-Apim-Subscription-Key", credential=credential - ) + 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"): - kwargs["authentication_policy"] = BearerTokenCredentialPolicy( - credential, *kwargs.pop("credential_scopes", [DEFAULT_TOKEN_SCOPE]), kwargs - ) + if kwargs.get("region") and kwargs.get("resource_id"): + kwargs["authentication_policy"] = TranslatorEntraIdAuthenticationPolicy( + credential, + kwargs["resource_id"], + kwargs["region"], + kwargs.pop("scopes", DEFAULT_ENTRA_ID_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 authentication." + ) + kwargs["authentication_policy"] = BearerTokenCredentialPolicy( + credential, *kwargs.pop("scopes", [DEFAULT_TOKEN_SCOPE]), kwargs + ) class TextTranslationClient(ServiceClientGenerated): @@ -148,36 +128,63 @@ class TextTranslationClient(ServiceClientGenerated): 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 + TranslatorCredential - used for National Clouds + str + None - used with text translation on-prem container None + AzureKeyCredential - used for global translator endpoint with global Translator resource - None + Token - general translator endpoint with token authentication - None + TranslatorCredential - general translator endpoint with regional Translator resource - - :param endpoint: Supported Text Translation endpoints (protocol and hostname, for example: - https://api.cognitive.microsofttranslator.com). Required. - :type endpoint: str - :param credential: Credential used to authenticate with the Translator service - :type credential: Union[AzureKeyCredential , TokenCredential , TranslatorCredential, TranslatorAADCredential] - :keyword api_version: Default value is "3.0". Note that overriding this default value may - result in unsupported behavior. - :paramtype api_version: str + 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 scopes: 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: Optional[Union[AzureKeyCredential, TokenCredential, TranslatorCredential, TranslatorAADCredential]] = None, + credential: TokenCredential, + region: Optional[str] = None, endpoint: Optional[str] = None, + resource_id: Optional[str] = None, + scopes: Optional[str] = None, api_version="3.0", **kwargs - ): - - set_authentication_policy(credential, kwargs) + ): ... - translation_endpoint = get_translation_endpoint(endpoint, api_version) + @overload + def __init__( + self, + *, + credential: AzureKeyCredential, + region: Optional[str] = None, + endpoint: Optional[str] = None, + api_version="3.0", + **kwargs + ): ... + @overload + def __init__( + self, + *, + endpoint: str, + api_version="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", "TranslatorCredential", "TranslatorAADCredential"] +__all__ = ["TextTranslationClient"] 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 bbcd28b4aa67..0ec13ea52bbf 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.0b2" +VERSION = "1.0.0" 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 65945cb3200f..0d279090135b 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 @@ -6,14 +6,13 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._patch import TextTranslationClient, AsyncTranslatorAADCredential +from ._patch import TextTranslationClient from ._patch import patch_sdk as _patch_sdk __all__ = [ "TextTranslationClient", - "AsyncTranslatorAADCredential" ] 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 343a01ff22e4..d1560bb354c8 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 @@ -6,9 +6,11 @@ # 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 io import IOBase import json -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload +import sys +from typing import Any, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, overload from azure.core import MatchConditions from azure.core.exceptions import ( @@ -29,7 +31,7 @@ from ..._model_base import SdkJSONEncoder, _deserialize from ..._operations._operations import ( build_text_translation_find_sentence_boundaries_request, - build_text_translation_get_languages_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, @@ -37,13 +39,18 @@ ) from .._vendor import TextTranslationClientMixinABC +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): + @distributed_trace_async - async def get_languages( + async def get_supported_languages( self, *, client_trace_id: Optional[str] = None, @@ -52,7 +59,7 @@ async def get_languages( etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any - ) -> _models.GetLanguagesResult: + ) -> _models.GetSupportedLanguagesResult: # pylint: disable=line-too-long """Gets the set of languages currently supported by other operations of the Translator. @@ -62,7 +69,7 @@ async def get_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 @@ -84,8 +91,9 @@ async def get_languages( :paramtype etag: str :keyword match_condition: The match condition to use upon the etag. Default value is None. :paramtype match_condition: ~azure.core.MatchConditions - :return: GetLanguagesResult. The GetLanguagesResult is compatible with MutableMapping - :rtype: ~azure.ai.translation.text.models.GetLanguagesResult + :return: GetSupportedLanguagesResult. The GetSupportedLanguagesResult is compatible with + MutableMapping + :rtype: ~azure.ai.translation.text.models.GetSupportedLanguagesResult :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -97,6 +105,7 @@ async def get_languages( "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 @@ -107,7 +116,7 @@ async def get_languages( the target language. Required. "dir": "str", # Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - Required. + Required. Known values are: "ltr" and "rtl". "name": "str", # Display name of the language in the locale requested via Accept-Language header. Required. @@ -121,6 +130,7 @@ async def get_languages( "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 @@ -139,7 +149,7 @@ async def get_languages( script. Required. "dir": "str", # Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - Required. + 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 @@ -150,7 +160,8 @@ async def get_languages( identifying the script. Required. "dir": "str", # Directionality, which is rtl for right-to-left languages - or ltr for left-to-right languages. Required. + 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. @@ -165,7 +176,7 @@ async def get_languages( } } """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -182,9 +193,9 @@ async def get_languages( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.GetLanguagesResult] = kwargs.pop("cls", None) + cls: ClsType[_models.GetSupportedLanguagesResult] = kwargs.pop("cls", None) - _request = build_text_translation_get_languages_request( + _request = build_text_translation_get_supported_languages_request( client_trace_id=client_trace_id, scope=scope, accept_language=accept_language, @@ -220,7 +231,7 @@ async def get_languages( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.GetLanguagesResult, response.json()) + deserialized = _deserialize(_models.GetSupportedLanguagesResult, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -230,7 +241,7 @@ async def get_languages( @overload async def translate( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, to: List[str], client_trace_id: Optional[str] = None, @@ -253,8 +264,8 @@ async def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.InputTextItem] :keyword to: 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. @@ -338,7 +349,7 @@ async def translate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -406,7 +417,7 @@ async def translate( @overload async def translate( self, - request_body: IO[bytes], + body: IO[bytes], *, to: List[str], client_trace_id: Optional[str] = None, @@ -429,8 +440,8 @@ async def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword to: 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. @@ -575,7 +586,7 @@ async def translate( @distributed_trace_async async def translate( self, - request_body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.InputTextItem], IO[bytes]], *, to: List[str], client_trace_id: Optional[str] = None, @@ -597,9 +608,9 @@ async def translate( Translate Text. - :param request_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 [InputTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] + :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] :keyword to: 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. @@ -737,7 +748,7 @@ async def translate( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -753,10 +764,10 @@ async def translate( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_translate_request( to=to, @@ -815,7 +826,7 @@ async def translate( @overload async def transliterate( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, language: str, from_script: str, @@ -828,8 +839,8 @@ async def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :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. @@ -856,7 +867,7 @@ async def transliterate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -876,7 +887,7 @@ async def transliterate( @overload async def transliterate( self, - request_body: IO[bytes], + body: IO[bytes], *, language: str, from_script: str, @@ -889,8 +900,8 @@ async def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :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. @@ -930,7 +941,7 @@ async def transliterate( @distributed_trace_async async def transliterate( self, - request_body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.InputTextItem], IO[bytes]], *, language: str, from_script: str, @@ -942,9 +953,9 @@ async def transliterate( Transliterate Text. - :param request_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 [InputTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] + :type body: list[~azure.ai.translation.text.models.InputTextItem] or 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. @@ -977,7 +988,7 @@ async def transliterate( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -993,10 +1004,10 @@ async def transliterate( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_transliterate_request( language=language, @@ -1044,7 +1055,7 @@ async def transliterate( @overload async def find_sentence_boundaries( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -1057,8 +1068,8 @@ async def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :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 @@ -1081,7 +1092,7 @@ async def find_sentence_boundaries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -1109,7 +1120,7 @@ async def find_sentence_boundaries( @overload async def find_sentence_boundaries( self, - request_body: IO[bytes], + body: IO[bytes], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -1122,8 +1133,8 @@ async def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :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 @@ -1167,7 +1178,7 @@ async def find_sentence_boundaries( @distributed_trace_async async def find_sentence_boundaries( self, - request_body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.InputTextItem], IO[bytes]], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -1179,9 +1190,9 @@ async def find_sentence_boundaries( Find Sentence Boundaries. - :param request_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 [InputTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] + :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 @@ -1218,7 +1229,7 @@ async def find_sentence_boundaries( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1234,10 +1245,10 @@ async def find_sentence_boundaries( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _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, @@ -1284,7 +1295,7 @@ async def find_sentence_boundaries( @overload async def lookup_dictionary_entries( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, from_parameter: str, to: str, @@ -1297,8 +1308,8 @@ async def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.InputTextItem] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1321,7 +1332,7 @@ async def lookup_dictionary_entries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -1399,7 +1410,7 @@ async def lookup_dictionary_entries( @overload async def lookup_dictionary_entries( self, - request_body: IO[bytes], + body: IO[bytes], *, from_parameter: str, to: str, @@ -1412,8 +1423,8 @@ async def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1507,7 +1518,7 @@ async def lookup_dictionary_entries( @distributed_trace_async async def lookup_dictionary_entries( self, - request_body: Union[List[_models.InputTextItem], IO[bytes]], + body: Union[List[_models.InputTextItem], IO[bytes]], *, from_parameter: str, to: str, @@ -1519,9 +1530,9 @@ async def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_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 [InputTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] + :type body: list[~azure.ai.translation.text.models.InputTextItem] or IO[bytes] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1608,7 +1619,7 @@ async def lookup_dictionary_entries( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1624,10 +1635,10 @@ async def lookup_dictionary_entries( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_lookup_dictionary_entries_request( from_parameter=from_parameter, @@ -1674,7 +1685,7 @@ async def lookup_dictionary_entries( @overload async def lookup_dictionary_examples( self, - request_body: List[_models.DictionaryExampleTextItem], + body: List[_models.DictionaryExampleTextItem], *, from_parameter: str, to: str, @@ -1687,8 +1698,8 @@ async def lookup_dictionary_examples( Lookup Dictionary Examples. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1711,7 +1722,7 @@ async def lookup_dictionary_examples( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str", # Text to translate. Required. "translation": "str" # A string specifying the translated text @@ -1761,7 +1772,7 @@ async def lookup_dictionary_examples( @overload async def lookup_dictionary_examples( self, - request_body: IO[bytes], + body: IO[bytes], *, from_parameter: str, to: str, @@ -1774,8 +1785,8 @@ async def lookup_dictionary_examples( Lookup Dictionary Examples. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1836,7 +1847,7 @@ async def lookup_dictionary_examples( @distributed_trace_async async def lookup_dictionary_examples( self, - request_body: Union[List[_models.DictionaryExampleTextItem], IO[bytes]], + body: Union[List[_models.DictionaryExampleTextItem], IO[bytes]], *, from_parameter: str, to: str, @@ -1848,10 +1859,9 @@ async def lookup_dictionary_examples( Lookup Dictionary Examples. - :param request_body: Defines the content of the request. Is either a - [DictionaryExampleTextItem] type or a IO[bytes] type. Required. - :type request_body: list[~azure.ai.translation.text.models.DictionaryExampleTextItem] or - IO[bytes] + :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_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1905,7 +1915,7 @@ async def lookup_dictionary_examples( } ] """ - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1921,10 +1931,10 @@ async def lookup_dictionary_examples( content_type = content_type or "application/json" _content = None - if isinstance(request_body, (IOBase, bytes)): - _content = request_body + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(request_body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_text_translation_lookup_dictionary_examples_request( from_parameter=from_parameter, 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 e3b46470f0aa..ca87b48dee97 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 @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ +# pylint: disable=C0302 + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize @@ -15,7 +17,7 @@ class TextTranslationClientOperationsMixin(TextTranslationClientOperationsMixinG @overload async def translate( self, - request_body: List[str], + body: List[str], *, to: List[str], client_trace_id: Optional[str] = None, @@ -38,8 +40,8 @@ async def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[str] + :param body: Defines the content of the request. Required. + :type body: list[str] :keyword to: 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. @@ -123,7 +125,7 @@ async def translate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ str" # Text to translate. Required. ] @@ -189,7 +191,7 @@ async def translate( @overload async def translate( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, to: List[str], client_trace_id: Optional[str] = None, @@ -212,8 +214,8 @@ async def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.InputTextItem] :keyword to: 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. @@ -297,7 +299,7 @@ async def translate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -365,7 +367,7 @@ async def translate( @overload async def translate( self, - request_body: IO[bytes], + body: IO[bytes], *, to: List[str], client_trace_id: Optional[str] = None, @@ -388,8 +390,8 @@ async def translate( Translate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword to: 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. @@ -531,9 +533,9 @@ async def translate( ] """ - async def translate( + async def translate( # pyright: ignore[reportIncompatibleMethodOverride] self, - request_body: Union[List[str], List[_models.InputTextItem], IO[bytes]], + body: Union[List[str], List[_models.InputTextItem], IO[bytes]], *, to: List[str], client_trace_id: Optional[str] = None, @@ -550,17 +552,17 @@ async def translate( allow_fallback: Optional[bool] = None, **kwargs: Any ) -> List[_models.TranslatedTextItem]: - body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(request_body, list) and all(isinstance(item, str) for item in request_body): + 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 request_body: + for text in body: input_text_items.append(_models.InputTextItem(text=cast(str, text))) - body = input_text_items + request_body = input_text_items else: - body = cast(Union[List[_models.InputTextItem], IO[bytes]], request_body) + request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) return await super().translate( - request_body=body, + body=request_body, to=to, client_trace_id=client_trace_id, from_parameter=from_parameter, @@ -580,7 +582,7 @@ async def translate( @overload async def transliterate( self, - request_body: List[str], + body: List[str], *, language: str, from_script: str, @@ -593,8 +595,8 @@ async def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[str] + :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. @@ -621,7 +623,7 @@ async def transliterate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -641,7 +643,7 @@ async def transliterate( @overload async def transliterate( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, language: str, from_script: str, @@ -654,8 +656,8 @@ async def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :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. @@ -682,7 +684,7 @@ async def transliterate( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -702,7 +704,7 @@ async def transliterate( @overload async def transliterate( self, - request_body: IO[bytes], + body: IO[bytes], *, language: str, from_script: str, @@ -715,8 +717,8 @@ async def transliterate( Transliterate Text. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :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. @@ -753,9 +755,9 @@ async def transliterate( ] """ - async def transliterate( + async def transliterate( # pyright: ignore[reportIncompatibleMethodOverride] self, - request_body: Union[List[str], List[_models.InputTextItem], IO[bytes]], + body: Union[List[str], List[_models.InputTextItem], IO[bytes]], *, language: str, from_script: str, @@ -763,17 +765,17 @@ async def transliterate( client_trace_id: Optional[str] = None, **kwargs: Any ) -> List[_models.TransliteratedText]: - body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(request_body, list) and all(isinstance(item, str) for item in request_body): + 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 request_body: + for text in body: input_text_items.append(_models.InputTextItem(text=cast(str, text))) - body = input_text_items + request_body = input_text_items else: - body = cast(Union[List[_models.InputTextItem], IO[bytes]], request_body) + request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) return await super().transliterate( - request_body=body, + body=request_body, language=language, from_script=from_script, to_script=to_script, @@ -784,7 +786,7 @@ async def transliterate( @overload async def find_sentence_boundaries( self, - request_body: List[str], + body: List[str], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -797,8 +799,8 @@ async def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[str] + :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 @@ -821,7 +823,7 @@ async def find_sentence_boundaries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -849,7 +851,7 @@ async def find_sentence_boundaries( @overload async def find_sentence_boundaries( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -862,8 +864,8 @@ async def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :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 @@ -886,7 +888,7 @@ async def find_sentence_boundaries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -914,7 +916,7 @@ async def find_sentence_boundaries( @overload async def find_sentence_boundaries( self, - request_body: IO[bytes], + body: IO[bytes], *, client_trace_id: Optional[str] = None, language: Optional[str] = None, @@ -927,8 +929,8 @@ async def find_sentence_boundaries( Find Sentence Boundaries. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :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 @@ -969,33 +971,33 @@ async def find_sentence_boundaries( ] """ - async def find_sentence_boundaries( + async def find_sentence_boundaries( # pyright: ignore[reportIncompatibleMethodOverride] self, - request_body: Union[List[str], List[_models.InputTextItem], IO[bytes]], + 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]: - body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(request_body, list) and all(isinstance(item, str) for item in request_body): + 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 request_body: + for text in body: input_text_items.append(_models.InputTextItem(text=cast(str, text))) - body = input_text_items + request_body = input_text_items else: - body = cast(Union[List[_models.InputTextItem], IO[bytes]], request_body) + request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) return await super().find_sentence_boundaries( - request_body=body, language=language, script=script, client_trace_id=client_trace_id, **kwargs + body=request_body, language=language, script=script, client_trace_id=client_trace_id, **kwargs ) @overload async def lookup_dictionary_entries( self, - request_body: List[str], + body: List[str], *, from_parameter: str, to: str, @@ -1008,8 +1010,8 @@ async def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[str] + :param body: Defines the content of the request. Required. + :type body: list[str] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1032,7 +1034,7 @@ async def lookup_dictionary_entries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -1078,7 +1080,7 @@ async def lookup_dictionary_entries( "bad" examples. Required. } ], - "confidence": 0.0, # A value between 0.0 and 1.0 + "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 @@ -1110,7 +1112,7 @@ async def lookup_dictionary_entries( @overload async def lookup_dictionary_entries( self, - request_body: List[_models.InputTextItem], + body: List[_models.InputTextItem], *, from_parameter: str, to: str, @@ -1123,8 +1125,8 @@ async def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: list[~azure.ai.translation.text.models.InputTextItem] + :param body: Defines the content of the request. Required. + :type body: list[~azure.ai.translation.text.models.InputTextItem] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1147,7 +1149,7 @@ async def lookup_dictionary_entries( .. code-block:: python # JSON input template you can fill out and use as your body input. - request_body = [ + body = [ { "text": "str" # Text to translate. Required. } @@ -1193,7 +1195,7 @@ async def lookup_dictionary_entries( "bad" examples. Required. } ], - "confidence": 0.0, # A value between 0.0 and 1.0 + "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 @@ -1225,7 +1227,7 @@ async def lookup_dictionary_entries( @overload async def lookup_dictionary_entries( self, - request_body: IO[bytes], + body: IO[bytes], *, from_parameter: str, to: str, @@ -1238,8 +1240,8 @@ async def lookup_dictionary_entries( Lookup Dictionary Entries. - :param request_body: Defines the content of the request. Required. - :type request_body: IO[bytes] + :param body: Defines the content of the request. Required. + :type body: IO[bytes] :keyword from_parameter: Specifies the language of the input text. The source language must be one of the supported languages included in the dictionary scope. Required. @@ -1301,7 +1303,7 @@ async def lookup_dictionary_entries( "bad" examples. Required. } ], - "confidence": 0.0, # A value between 0.0 and 1.0 + "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 @@ -1330,26 +1332,26 @@ async def lookup_dictionary_entries( ] """ - async def lookup_dictionary_entries( + async def lookup_dictionary_entries( # pyright: ignore[reportIncompatibleMethodOverride] self, - request_body: Union[List[str], List[_models.InputTextItem], IO[bytes]], + body: Union[List[str], List[_models.InputTextItem], IO[bytes]], *, from_parameter: str, to: str, client_trace_id: Optional[str] = None, **kwargs: Any ) -> List[_models.DictionaryLookupItem]: - body: Union[List[_models.InputTextItem], IO[bytes]] - if isinstance(request_body, list) and all(isinstance(item, str) for item in request_body): + 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 request_body: + for text in body: input_text_items.append(_models.InputTextItem(text=cast(str, text))) - body = input_text_items + request_body = input_text_items else: - body = cast(Union[List[_models.InputTextItem], IO[bytes]], request_body) + request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body) return await super().lookup_dictionary_entries( - request_body=body, from_parameter=from_parameter, to=to, client_trace_id=client_trace_id, **kwargs + body=request_body, from_parameter=from_parameter, to=to, client_trace_id=client_trace_id, **kwargs ) 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 a38265f74657..f08ab3618209 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 @@ -2,17 +2,23 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ +# pylint: disable=C4717, C4722, C4748 """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Union, Optional, Any +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 .._patch import DEFAULT_TOKEN_SCOPE, get_translation_endpoint, TranslatorAuthenticationPolicy, TranslatorCredential +from .._patch import ( + DEFAULT_TOKEN_SCOPE, + DEFAULT_ENTRA_ID_SCOPE, + get_translation_endpoint, + TranslatorAuthenticationPolicy, +) from ._client import TextTranslationClient as ServiceClientGenerated @@ -25,58 +31,57 @@ def patch_sdk(): https://aka.ms/azsdk/python/dpcodegen/python/customize """ -class AsyncTranslatorAADCredential: - """Credential for Translator Service when using AAD authentication. - :param tokenCredential: An object which can provide an access token for the Translator Resource, such as a credential from - :mod:`azure.identity` - :type tokenCredential: ~azure.core.credentials.TokenCredential - :param str resourceId: Azure Resource Id of the Translation Resource. - :param str region: Azure Region of the Translation Resource. - """ - - def __init__(self, tokenCredential: AsyncTokenCredential, resourceId: str, region: str) -> None: - self.tokenCredential = tokenCredential - self.resourceId = resourceId - self.region = region - -class AsyncTranslatorAADAuthenticationPolicy(AsyncBearerTokenCredentialPolicy): - """Translator AAD Authentication Policy. Adds headers that are required by Translator Service - when global endpoint is used with AAD policy. +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 AAD Credentials used to access Translator Resource for global Translator endpoint. - :type credential: ~azure.ai.translation.text.AsyncTranslatorAADCredential + :param credential: Translator Entra Id Credentials used to access Translator Resource for global endpoint. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential """ - def __init__(self, credential: AsyncTranslatorAADCredential, **kwargs: Any)-> None: - super(AsyncTranslatorAADAuthenticationPolicy, self).__init__(credential.tokenCredential, "https://cognitiveservices.azure.com/.default", **kwargs) - self.translatorCredential = credential + def __init__( + self, credential: AsyncTokenCredential, resource_id: str, region: str, scopes: str, **kwargs: Any + ) -> None: + super(AsyncTranslatorEntraIdAuthenticationPolicy, self).__init__(credential, scopes, **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.translatorCredential.resourceId - request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.translatorCredential.region + 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, TranslatorCredential): - if not kwargs.get("authentication_policy"): - kwargs["authentication_policy"] = TranslatorAuthenticationPolicy(credential) - elif isinstance(credential, AsyncTranslatorAADCredential): - if not kwargs.get("authentication_policy"): - kwargs["authentication_policy"] = AsyncTranslatorAADAuthenticationPolicy(credential) - elif isinstance(credential, AzureKeyCredential): + if isinstance(credential, AzureKeyCredential): if not kwargs.get("authentication_policy"): - kwargs["authentication_policy"] = AzureKeyCredentialPolicy( - name="Ocp-Apim-Subscription-Key", credential=credential - ) + 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"): - kwargs["authentication_policy"] = AsyncBearerTokenCredentialPolicy( - credential, *kwargs.pop("credential_scopes", [DEFAULT_TOKEN_SCOPE]), kwargs - ) + if kwargs.get("region") and kwargs.get("resource_id"): + kwargs["authentication_policy"] = AsyncTranslatorEntraIdAuthenticationPolicy( + credential, + kwargs["resource_id"], + kwargs["region"], + kwargs.pop("scopes", DEFAULT_ENTRA_ID_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 authentication." + ) + kwargs["authentication_policy"] = AsyncBearerTokenCredentialPolicy( + credential, *kwargs.pop("scopes", [DEFAULT_TOKEN_SCOPE]), kwargs + ) class TextTranslationClient(ServiceClientGenerated): @@ -105,36 +110,63 @@ class TextTranslationClient(ServiceClientGenerated): Combinations of endpoint and credential values: str + AzureKeyCredential - used custom domain translator endpoint - str + TokenCredential - used for regional endpoint with token authentication - str + TranslatorCredential - used for National Clouds + 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 + Token - general translator endpoint with token authentication - None + TranslatorCredential - general translator endpoint with regional Translator resource - - :param endpoint: Supported Text Translation endpoints (protocol and hostname, for example: - https://api.cognitive.microsofttranslator.com). Required. - :type endpoint: str - :param credential: Credential used to authenticate with the Translator service - :type credential: Union[AzureKeyCredential , AsyncTokenCredential , TranslatorCredential, AsyncTranslatorAADCredential] - :keyword api_version: Default value is "3.0". Note that overriding this default value may - result in unsupported behavior. - :paramtype api_version: str + 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 scopes: 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: Union[AzureKeyCredential, AsyncTokenCredential, TranslatorCredential, AsyncTranslatorAADCredential], *, + credential: AsyncTokenCredential, + region: Optional[str] = None, endpoint: Optional[str] = None, + resource_id: Optional[str] = None, + scopes: Optional[str] = None, api_version="3.0", **kwargs - ): + ): ... - set_authentication_policy(credential, kwargs) - - translation_endpoint = get_translation_endpoint(endpoint, api_version) + @overload + def __init__( + self, + *, + credential: AzureKeyCredential, + region: Optional[str] = None, + endpoint: Optional[str] = None, + api_version="3.0", + **kwargs + ): ... + @overload + def __init__( + self, + *, + endpoint: str, + api_version="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", "AsyncTranslatorAADCredential"] +__all__ = ["TextTranslationClient"] 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 3b2df9b8ca1f..9aae62f6f103 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 @@ -8,7 +8,6 @@ from ._models import BackTranslation from ._models import BreakSentenceItem -from ._models import CommonScriptModel from ._models import DetectedLanguage from ._models import DictionaryExample from ._models import DictionaryExampleItem @@ -17,20 +16,22 @@ from ._models import DictionaryTranslation from ._models import ErrorDetails from ._models import ErrorResponse -from ._models import GetLanguagesResult +from ._models import GetSupportedLanguagesResult from ._models import InputTextItem -from ._models import SentenceLength +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 Translation from ._models import TranslationLanguage +from ._models import TranslationText from ._models import TransliterableScript from ._models import TransliteratedText from ._models import TransliterationLanguage +from ._enums import LanguageDirectionality from ._enums import ProfanityAction from ._enums import ProfanityMarker from ._enums import TextType @@ -41,7 +42,6 @@ __all__ = [ "BackTranslation", "BreakSentenceItem", - "CommonScriptModel", "DetectedLanguage", "DictionaryExample", "DictionaryExampleItem", @@ -50,22 +50,24 @@ "DictionaryTranslation", "ErrorDetails", "ErrorResponse", - "GetLanguagesResult", + "GetSupportedLanguagesResult", "InputTextItem", - "SentenceLength", + "LanguageScript", + "SentenceBoundaries", "SourceDictionaryLanguage", "SourceText", "TargetDictionaryLanguage", "TranslatedTextAlignment", "TranslatedTextItem", - "Translation", "TranslationLanguage", + "TranslationText", "TransliterableScript", "TransliteratedText", "TransliterationLanguage", + "LanguageDirectionality", "ProfanityAction", "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[reportUnsupportedDunderAll] _patch_sdk() diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_enums.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_enums.py index 5eac3900be23..e5f1afb9af32 100644 --- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_enums.py +++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_enums.py @@ -10,23 +10,39 @@ from azure.core import CaseInsensitiveEnumMeta +class LanguageDirectionality(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Language Directionality.""" + + LEFT_TO_RIGHT = "ltr" + """Language is written left to right.""" + RIGHT_TO_LEFT = "rtl" + """Language is written right to left.""" + + class ProfanityAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Translator profanity actions.""" NO_ACTION = "NoAction" + """No Action is taken on profanity""" MARKED = "Marked" + """Profanity is marked.""" DELETED = "Deleted" + """Profanity is deleted from the translated text.""" class ProfanityMarker(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Translator profanity markers.""" ASTERISK = "Asterisk" + """Profanity is marked with asterisk.""" TAG = "Tag" + """Profanity is marked with the tags.""" class TextType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Translation text type.""" PLAIN = "Plain" + """Plain text.""" HTML = "Html" + """HTML-encoded text.""" 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 0cfaa8725737..e636f1f0a345 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 @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Dict, List, Mapping, Optional, TYPE_CHECKING, overload +from typing import Any, Dict, List, Mapping, Optional, TYPE_CHECKING, Union, overload from .. import _model_base from .._model_base import rest_field @@ -78,8 +78,7 @@ def __init__( display_text: str, num_examples: int, frequency_count: int, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -120,58 +119,7 @@ def __init__( *, 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 CommonScriptModel(_model_base.Model): - """Common properties of language script. - - 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. - Required. - :vartype name: str - :ivar native_name: Display name of the language in the locale native for the language. - Required. - :vartype native_name: str - :ivar dir: Directionality, which is rtl for right-to-left languages or ltr for left-to-right - languages. Required. - :vartype dir: str - """ - - code: str = rest_field() - """Code identifying the script. Required.""" - name: str = rest_field() - """Display name of the script in the locale requested via Accept-Language header. Required.""" - native_name: str = rest_field(name="nativeName") - """Display name of the language in the locale native for the language. Required.""" - dir: str = rest_field() - """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - Required.""" - - @overload - def __init__( - self, - *, - code: str, - name: str, - native_name: str, - dir: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -208,8 +156,7 @@ def __init__( *, language: str, score: float, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -279,8 +226,7 @@ def __init__( target_prefix: str, target_term: str, target_suffix: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -329,8 +275,7 @@ def __init__( normalized_source: str, normalized_target: str, examples: List["_models.DictionaryExample"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -360,8 +305,7 @@ def __init__( self, *, text: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -403,8 +347,7 @@ def __init__( *, text: str, translation: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -453,8 +396,7 @@ def __init__( normalized_source: str, display_source: str, translations: List["_models.DictionaryTranslation"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -543,8 +485,7 @@ def __init__( confidence: float, prefix_word: str, back_translations: List["_models.BackTranslation"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -579,8 +520,7 @@ def __init__( *, code: int, message: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -610,8 +550,7 @@ def __init__( self, *, error: "_models.ErrorDetails", - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -624,7 +563,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class GetLanguagesResult(_model_base.Model): +class GetSupportedLanguagesResult(_model_base.Model): """Response for the languages API. :ivar translation: Languages that support translate API. @@ -649,8 +588,56 @@ def __init__( translation: Optional[Dict[str, "_models.TranslationLanguage"]] = None, transliteration: Optional[Dict[str, "_models.TransliterationLanguage"]] = None, dictionary: Optional[Dict[str, "_models.SourceDictionaryLanguage"]] = 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 LanguageScript(_model_base.Model): + """Common properties of language script. + + 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. + Required. + :vartype name: str + :ivar native_name: Display name of the language in the locale native for the language. + Required. + :vartype native_name: str + :ivar dir: Directionality, which is rtl for right-to-left languages or ltr for left-to-right + languages. Required. Known values are: "ltr" and "rtl". + :vartype dir: str or ~azure.ai.translation.text.models.LanguageDirectionality + """ + + code: str = rest_field() + """Code identifying the script. Required.""" + name: str = rest_field() + """Display name of the script in the locale requested via Accept-Language header. Required.""" + native_name: str = rest_field(name="nativeName") + """Display name of the language in the locale native for the language. Required.""" + dir: Union[str, "_models.LanguageDirectionality"] = rest_field() + """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + Required. Known values are: \"ltr\" and \"rtl\".""" + + @overload + def __init__( + self, + *, + code: str, + name: str, + native_name: str, + dir: Union[str, "_models.LanguageDirectionality"], + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -663,7 +650,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class SentenceLength(_model_base.Model): +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. @@ -695,8 +682,7 @@ def __init__( *, src_sent_len: List[int], trans_sent_len: List[int], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -721,8 +707,8 @@ class SourceDictionaryLanguage(_model_base.Model): Required. :vartype native_name: str :ivar dir: Directionality, which is rtl for right-to-left languages or ltr for left-to-right - languages. Required. - :vartype dir: str + languages. Required. Known values are: "ltr" and "rtl". + :vartype dir: str or ~azure.ai.translation.text.models.LanguageDirectionality :ivar translations: List of languages with alterative translations and examples for the query expressed in the source language. Required. :vartype translations: list[~azure.ai.translation.text.models.TargetDictionaryLanguage] @@ -732,9 +718,9 @@ class SourceDictionaryLanguage(_model_base.Model): """Display name of the language in the locale requested via Accept-Language header. Required.""" native_name: str = rest_field(name="nativeName") """Display name of the language in the locale native for this language. Required.""" - dir: str = rest_field() + dir: Union[str, "_models.LanguageDirectionality"] = rest_field() """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - Required.""" + Required. Known values are: \"ltr\" and \"rtl\".""" translations: List["_models.TargetDictionaryLanguage"] = rest_field() """List of languages with alterative translations and examples for the query expressed in the source language. Required.""" @@ -745,10 +731,9 @@ def __init__( *, name: str, native_name: str, - dir: str, + dir: Union[str, "_models.LanguageDirectionality"], translations: List["_models.TargetDictionaryLanguage"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -778,8 +763,7 @@ def __init__( self, *, text: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -804,8 +788,8 @@ class TargetDictionaryLanguage(_model_base.Model): Required. :vartype native_name: str :ivar dir: Directionality, which is rtl for right-to-left languages or ltr for left-to-right - languages. Required. - :vartype dir: str + languages. Required. Known values are: "ltr" and "rtl". + :vartype dir: str or ~azure.ai.translation.text.models.LanguageDirectionality :ivar code: Language code identifying the target language. Required. :vartype code: str """ @@ -814,9 +798,9 @@ class TargetDictionaryLanguage(_model_base.Model): """Display name of the language in the locale requested via Accept-Language header. Required.""" native_name: str = rest_field(name="nativeName") """Display name of the language in the locale native for this language. Required.""" - dir: str = rest_field() + dir: Union[str, "_models.LanguageDirectionality"] = rest_field() """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - Required.""" + Required. Known values are: \"ltr\" and \"rtl\".""" code: str = rest_field() """Language code identifying the target language. Required.""" @@ -826,10 +810,9 @@ def __init__( *, name: str, native_name: str, - dir: str, + dir: Union[str, "_models.LanguageDirectionality"], code: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -876,8 +859,7 @@ def __init__( self, *, proj: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -901,7 +883,7 @@ class TranslatedTextItem(_model_base.Model): :ivar translations: An array of translation results. The size of the array matches the number of target languages specified through the to query parameter. Required. - :vartype translations: list[~azure.ai.translation.text.models.Translation] + :vartype translations: list[~azure.ai.translation.text.models.TranslationText] :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, @@ -914,7 +896,7 @@ class TranslatedTextItem(_model_base.Model): 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.""" - translations: List["_models.Translation"] = rest_field() + translations: List["_models.TranslationText"] = rest_field() """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") @@ -929,11 +911,56 @@ class TranslatedTextItem(_model_base.Model): def __init__( self, *, - translations: List["_models.Translation"], + translations: List["_models.TranslationText"], detected_language: Optional["_models.DetectedLanguage"] = None, source_text: Optional["_models.SourceText"] = 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 TranslationLanguage(_model_base.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 + :ivar native_name: Display name of the language in the locale native for this language. + Required. + :vartype native_name: str + :ivar dir: Directionality, which is rtl for right-to-left languages or ltr for left-to-right + languages. Required. Known values are: "ltr" and "rtl". + :vartype dir: str or ~azure.ai.translation.text.models.LanguageDirectionality + """ + + name: str = rest_field() + """Display name of the language in the locale requested via Accept-Language header. Required.""" + native_name: str = rest_field(name="nativeName") + """Display name of the language in the locale native for this language. Required.""" + dir: Union[str, "_models.LanguageDirectionality"] = rest_field() + """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + Required. Known values are: \"ltr\" and \"rtl\".""" + + @overload + def __init__( + self, + *, + name: str, + native_name: str, + dir: Union[str, "_models.LanguageDirectionality"], + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -946,7 +973,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class Translation(_model_base.Model): +class TranslationText(_model_base.Model): """Translation result. All required parameters must be populated in order to send to server. @@ -961,7 +988,7 @@ class Translation(_model_base.Model): :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.SentenceLength + :vartype sent_len: ~azure.ai.translation.text.models.SentenceBoundaries """ to: str = rest_field() @@ -972,7 +999,7 @@ class Translation(_model_base.Model): """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.SentenceLength"] = rest_field(name="sentLen") + sent_len: Optional["_models.SentenceBoundaries"] = rest_field(name="sentLen") """Sentence boundaries in the input and output texts.""" @overload @@ -983,56 +1010,8 @@ def __init__( text: str, transliteration: Optional["_models.TransliteratedText"] = None, alignment: Optional["_models.TranslatedTextAlignment"] = None, - sent_len: Optional["_models.SentenceLength"] = 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 TranslationLanguage(_model_base.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 - :ivar native_name: Display name of the language in the locale native for this language. - Required. - :vartype native_name: str - :ivar dir: Directionality, which is rtl for right-to-left languages or ltr for left-to-right - languages. Required. - :vartype dir: str - """ - - name: str = rest_field() - """Display name of the language in the locale requested via Accept-Language header. Required.""" - native_name: str = rest_field(name="nativeName") - """Display name of the language in the locale native for this language. Required.""" - dir: str = rest_field() - """Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - Required.""" - - @overload - def __init__( - self, - *, - name: str, - native_name: str, - dir: str, - ): - ... + sent_len: Optional["_models.SentenceBoundaries"] = None, + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1045,7 +1024,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useles super().__init__(*args, **kwargs) -class TransliterableScript(CommonScriptModel): +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. @@ -1059,13 +1038,13 @@ class TransliterableScript(CommonScriptModel): Required. :vartype native_name: str :ivar dir: Directionality, which is rtl for right-to-left languages or ltr for left-to-right - languages. Required. - :vartype dir: str + languages. Required. Known values are: "ltr" and "rtl". + :vartype dir: str or ~azure.ai.translation.text.models.LanguageDirectionality :ivar to_scripts: List of scripts available to convert text to. Required. - :vartype to_scripts: list[~azure.ai.translation.text.models.CommonScriptModel] + :vartype to_scripts: list[~azure.ai.translation.text.models.LanguageScript] """ - to_scripts: List["_models.CommonScriptModel"] = rest_field(name="toScripts") + to_scripts: List["_models.LanguageScript"] = rest_field(name="toScripts") """List of scripts available to convert text to. Required.""" @overload @@ -1075,10 +1054,9 @@ def __init__( code: str, name: str, native_name: str, - dir: str, - to_scripts: List["_models.CommonScriptModel"], - ): - ... + dir: Union[str, "_models.LanguageDirectionality"], + to_scripts: List["_models.LanguageScript"], + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1114,8 +1092,7 @@ def __init__( *, text: str, script: str, - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): @@ -1160,8 +1137,7 @@ def __init__( name: str, native_name: str, scripts: List["_models.TransliterableScript"], - ): - ... + ): ... @overload def __init__(self, mapping: Mapping[str, Any]): diff --git a/sdk/translation/azure-ai-translation-text/pyproject.toml b/sdk/translation/azure-ai-translation-text/pyproject.toml index 51e3830e1f50..07364590ca6f 100644 --- a/sdk/translation/azure-ai-translation-text/pyproject.toml +++ b/sdk/translation/azure-ai-translation-text/pyproject.toml @@ -1,8 +1,8 @@ [tool.azure-sdk-build] -pylint = false -type_check_samples = false -verifytypes = false -pyright = false +pylint = true +type_check_samples = true +verifytypes = true +pyright = true strict_sphinx = true [tool.generate] diff --git a/sdk/translation/azure-ai-translation-text/samples/README.md b/sdk/translation/azure-ai-translation-text/samples/README.md index 6d1482b726bb..4807efaa63aa 100644 --- a/sdk/translation/azure-ai-translation-text/samples/README.md +++ b/sdk/translation/azure-ai-translation-text/samples/README.md @@ -48,8 +48,8 @@ The appropriate constructor is invoked in each sample to create a `TextTranslati ```python -credential = TranslatorCredential(apikey, region) -text_translator = TextTranslationClient(credential=credential, endpoint=endpoint) +credential = AzureKeyCredential(apikey) +text_translator = TextTranslationClient(credential=credential, endpoint=endpoint, region=region) ``` @@ -66,7 +66,7 @@ This will return language metadata from all supported scopes. ```python try: - response = text_translator.get_languages() + response = text_translator.get_supported_languages() print( f"Number of supported languages for translate operation: {len(response.translation) if response.translation is not None else 0}" @@ -111,7 +111,7 @@ You can limit the scope of the response of the languages API by providing the op ```python try: scope = "translation" - response = text_translator.get_languages(scope=scope) + response = text_translator.get_supported_languages(scope=scope) print( f"Number of supported languages for translate operation: {len(response.translation) if response.translation is not None else 0}" @@ -157,7 +157,7 @@ Names are provided in the English language when a target language is not specifi ```python try: accept_language = "es" - response = text_translator.get_languages(accept_language=accept_language) + response = text_translator.get_supported_languages(accept_language=accept_language) print( f"Number of supported languages for translate operation: {len(response.translation) if response.translation is not None else 0}" @@ -203,13 +203,11 @@ Translate text from known source language to target language. ```python try: - source_language = "en" - target_languages = ["cs"] + from_parameter = "en" + to = ["cs"] input_text_elements = ["This is a test"] - response = text_translator.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = text_translator.translate(body=input_text_elements, to=to, from_parameter=from_parameter) translation = response[0] if response else None if translation: @@ -237,10 +235,10 @@ You can omit source language of the input text. In this case, API will try to au ```python try: - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test"] - response = text_translator.translate(request_body=input_text_elements, to=target_languages) + response = text_translator.translate(body=input_text_elements, to=to) translation = response[0] if response else None if translation: @@ -272,12 +270,12 @@ try: from_script = "Latn" from_language = "ar" to_script = "Latn" - target_languages = ["zh-Hans"] + to = ["zh-Hans"] input_text_elements = ["hudha akhtabar."] response = text_translator.translate( - request_body=input_text_elements, - to=target_languages, + body=input_text_elements, + to=to, from_script=from_script, from_parameter=from_language, to_script=to_script, @@ -311,14 +309,14 @@ You can translate multiple text elements with a various length. Each input eleme ```python try: - target_languages = ["cs"] + to = ["cs"] input_text_elements = [ "This is a test.", "Esto es una prueba.", "Dies ist ein Test.", ] - translations = text_translator.translate(request_body=input_text_elements, to=target_languages) + translations = text_translator.translate(body=input_text_elements, to=to) for translation in translations: print( @@ -344,10 +342,10 @@ You can provide multiple target languages which results to each input element be ```python try: - target_languages = ["cs", "es", "de"] + to = ["cs", "es", "de"] input_text_elements = ["This is a test"] - response = text_translator.translate(request_body=input_text_elements, to=target_languages) + response = text_translator.translate(body=input_text_elements, to=to) translation = response[0] if response else None if translation: @@ -376,10 +374,10 @@ You can select whether the translated text is plain text or HTML text. Any HTML ```python try: text_type = TextType.HTML - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test."] - response = text_translator.translate(request_body=input_text_elements, to=target_languages, text_type=text_type) + response = text_translator.translate(body=input_text_elements, to=to, text_type=text_type) translation = response[0] if response else None if translation: @@ -408,14 +406,17 @@ It's sometimes useful to exclude specific content from translation. You can use ```python try: text_type = TextType.HTML - source_language = "en" - target_languages = ["cs"] + from_parameter = "en" + to = ["cs"] input_text_elements = [ '
This will not be translated.
This will be translated.
' ] response = text_translator.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language, text_type=text_type + body=input_text_elements, + to=to, + from_parameter=from_parameter, + text_type=text_type, ) translation = response[0] if response else None @@ -441,15 +442,13 @@ If you already know the translation you want to apply to a word or a phrase, you ```python try: - source_language = "en" - target_languages = ["cs"] + from_parameter = "en" + to = ["cs"] input_text_elements = [ 'The word wordomatic is a dictionary entry.' ] - response = text_translator.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = text_translator.translate(body=input_text_elements, to=to, from_parameter=from_parameter) translation = response[0] if response else None if translation: @@ -476,12 +475,12 @@ If you want to avoid getting profanity in the translation, regardless of the pre try: profanity_action = ProfanityAction.MARKED profanity_maker = ProfanityMarker.ASTERISK - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is ***."] response = text_translator.translate( - request_body=input_text_elements, - to=target_languages, + body=input_text_elements, + to=to, profanity_action=profanity_action, profanity_marker=profanity_maker, ) @@ -513,12 +512,10 @@ You can ask translation service to include alignment projection from source text ```python try: include_alignment = True - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["The answer lies in machine translation."] - response = text_translator.translate( - request_body=input_text_elements, to=target_languages, include_alignment=include_alignment - ) + response = text_translator.translate(body=input_text_elements, to=to, include_alignment=include_alignment) translation = response[0] if response else None if translation: @@ -549,11 +546,11 @@ You can ask translator service to include sentence boundaries for the input text ```python try: include_sentence_length = True - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["The answer lies in machine translation. This is a test."] response = text_translator.translate( - request_body=input_text_elements, to=target_languages, include_sentence_length=include_sentence_length + body=input_text_elements, to=to, include_sentence_length=include_sentence_length ) translation = response[0] if response else None @@ -590,10 +587,10 @@ It is possible to set `allow_fallback` parameter. It specifies that the service ```python try: category = "<>" - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test"] - response = text_translator.translate(request_body=input_text_elements, to=target_languages, category=category) + response = text_translator.translate(body=input_text_elements, to=to, category=category) translation = response[0] if response else None if translation: @@ -629,7 +626,10 @@ try: input_text_elements = ["这是个测试。"] response = text_translator.transliterate( - request_body=input_text_elements, language=language, from_script=from_script, to_script=to_script + body=input_text_elements, + language=language, + from_script=from_script, + to_script=to_script, ) transliteration = response[0] if response else None @@ -657,12 +657,12 @@ When the input language is known, you can provide those to the service call. ```python try: - source_language = "zh-Hans" + from_parameter = "zh-Hans" source_script = "Latn" input_text_elements = ["zhè shì gè cè shì。"] response = text_translator.find_sentence_boundaries( - request_body=input_text_elements, language=source_language, script=source_script + body=input_text_elements, language=from_parameter, script=source_script ) sentence_boundaries = response[0] if response else None @@ -695,7 +695,7 @@ You can omit source language of the input text. In this case, API will try to au try: input_text_elements = ["This is a test. This is the second sentence."] - response = text_translator.find_sentence_boundaries(request_body=input_text_elements) + response = text_translator.find_sentence_boundaries(body=input_text_elements) sentence_boundaries = response[0] if response else None if sentence_boundaries: @@ -726,12 +726,12 @@ Returns equivalent words for the source term in the target language. ```python try: - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = ["fly"] response = text_translator.lookup_dictionary_entries( - request_body=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) dictionary_entry = response[0] if response else None @@ -758,12 +758,12 @@ Returns grammatical structure and context examples for the source term and targe ```python try: - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = [DictionaryExampleTextItem(text="fly", translation="volar")] response = text_translator.lookup_dictionary_examples( - content=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) dictionary_entry = response[0] if response else None 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 8e89ebaaa544..06a5fdf20e41 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 @@ -37,12 +37,12 @@ def get_text_sentence_boundaries(): # [START get_text_sentence_boundaries] try: - source_language = "zh-Hans" + from_parameter = "zh-Hans" source_script = "Latn" input_text_elements = ["zhè shì gè cè shì。"] response = text_translator.find_sentence_boundaries( - request_body=input_text_elements, language=source_language, script=source_script + body=input_text_elements, language=from_parameter, script=source_script ) sentence_boundaries = response[0] if response else None @@ -69,7 +69,7 @@ def get_text_sentence_boundaries_auto(): try: input_text_elements = ["This is a test. This is the second sentence."] - response = text_translator.find_sentence_boundaries(request_body=input_text_elements) + response = text_translator.find_sentence_boundaries(body=input_text_elements) sentence_boundaries = response[0] if response else None if sentence_boundaries: 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 121c71f2eba7..f6c546b70c20 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 @@ -26,6 +26,7 @@ import os + # ------------------------------------------------------------------------- # Text translation client # ------------------------------------------------------------------------- @@ -40,13 +41,14 @@ def create_text_translation_client_with_endpoint(): def create_text_translation_client_with_credential(): - from azure.ai.translation.text import TextTranslationClient, TranslatorCredential + from azure.ai.translation.text import TextTranslationClient + from azure.core.credentials import AzureKeyCredential endpoint = os.environ["AZURE_TEXT_TRANSLATION_ENDPOINT"] apikey = os.environ["AZURE_TEXT_TRANSLATION_APIKEY"] region = os.environ["AZURE_TEXT_TRANSLATION_REGION"] # [START create_text_translation_client_with_credential] - credential = TranslatorCredential(apikey, region) - text_translator = TextTranslationClient(credential=credential, endpoint=endpoint) + credential = AzureKeyCredential(apikey) + text_translator = TextTranslationClient(credential=credential, endpoint=endpoint, region=region) # [END create_text_translation_client_with_credential] return text_translator 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 bc86ce8105fc..59b033eb928e 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 @@ -33,18 +33,19 @@ text_translator = sample_text_translation_client.create_text_translation_client_with_credential() + # ------------------------------------------------------------------------- # Dictionary Lookup # ------------------------------------------------------------------------- def get_text_translation_dictionary_examples(): # [START get_text_translation_dictionary_examples] try: - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = [DictionaryExampleTextItem(text="fly", translation="volar")] response = text_translator.lookup_dictionary_examples( - content=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) dictionary_entry = response[0] if response else None 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 c517ab630184..875985d624d8 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 @@ -33,18 +33,19 @@ text_translator = sample_text_translation_client.create_text_translation_client_with_credential() + # ------------------------------------------------------------------------- # Dictionary Lookup # ------------------------------------------------------------------------- def get_text_translation_dictionary_lookup(): # [START get_text_translation_dictionary_lookup] try: - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = ["fly"] response = text_translator.lookup_dictionary_entries( - request_body=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) dictionary_entry = response[0] if response else None 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 6ab53599ec69..66f3cb8c0ee1 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 @@ -32,13 +32,14 @@ text_translator = sample_text_translation_client.create_text_translation_client_with_endpoint() + # ------------------------------------------------------------------------- # Get text translation languages # ------------------------------------------------------------------------- def get_text_translation_languages(): # [START get_text_translation_languages] try: - response = text_translator.get_languages() + response = text_translator.get_supported_languages() print( f"Number of supported languages for translate operation: {len(response.translation) if response.translation is not None else 0}" @@ -77,7 +78,7 @@ def get_text_translation_languages_scope(): # [START get_text_translation_languages_scope] try: scope = "translation" - response = text_translator.get_languages(scope=scope) + response = text_translator.get_supported_languages(scope=scope) print( f"Number of supported languages for translate operation: {len(response.translation) if response.translation is not None else 0}" @@ -116,7 +117,7 @@ def get_text_translation_languages_culture(): # [START get_text_translation_languages_culture] try: accept_language = "es" - response = text_translator.get_languages(accept_language=accept_language) + response = text_translator.get_supported_languages(accept_language=accept_language) print( f"Number of supported languages for translate operation: {len(response.translation) if response.translation is not None else 0}" 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 f3020bfea3af..027981ab6c0d 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 @@ -34,19 +34,18 @@ text_translator = sample_text_translation_client.create_text_translation_client_with_credential() + # ------------------------------------------------------------------------- # Get text translation # ------------------------------------------------------------------------- def get_text_translation(): # [START get_text_translation] try: - source_language = "en" - target_languages = ["cs"] + from_parameter = "en" + to = ["cs"] input_text_elements = ["This is a test"] - response = text_translator.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = text_translator.translate(body=input_text_elements, to=to, from_parameter=from_parameter) translation = response[0] if response else None if translation: @@ -64,10 +63,10 @@ def get_text_translation(): def get_text_translation_auto(): # [START get_text_translation_auto] try: - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test"] - response = text_translator.translate(request_body=input_text_elements, to=target_languages) + response = text_translator.translate(body=input_text_elements, to=to) translation = response[0] if response else None if translation: @@ -93,12 +92,12 @@ def get_text_translation_with_transliteration(): from_script = "Latn" from_language = "ar" to_script = "Latn" - target_languages = ["zh-Hans"] + to = ["zh-Hans"] input_text_elements = ["hudha akhtabar."] response = text_translator.translate( - request_body=input_text_elements, - to=target_languages, + body=input_text_elements, + to=to, from_script=from_script, from_parameter=from_language, to_script=to_script, @@ -126,14 +125,14 @@ def get_text_translation_with_transliteration(): def get_text_translation_multiple_inputs(): # [START get_text_translation_multiple_inputs] try: - target_languages = ["cs"] + to = ["cs"] input_text_elements = [ "This is a test.", "Esto es una prueba.", "Dies ist ein Test.", ] - translations = text_translator.translate(request_body=input_text_elements, to=target_languages) + translations = text_translator.translate(body=input_text_elements, to=to) for translation in translations: print( @@ -153,10 +152,10 @@ def get_text_translation_multiple_inputs(): def get_text_translation_multiple_languages(): # [START get_text_translation_multiple_languages] try: - target_languages = ["cs", "es", "de"] + to = ["cs", "es", "de"] input_text_elements = ["This is a test"] - response = text_translator.translate(request_body=input_text_elements, to=target_languages) + response = text_translator.translate(body=input_text_elements, to=to) translation = response[0] if response else None if translation: @@ -179,10 +178,10 @@ def get_text_translation_type(): # [START get_text_translation_type] try: text_type = TextType.HTML - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test."] - response = text_translator.translate(request_body=input_text_elements, to=target_languages, text_type=text_type) + response = text_translator.translate(body=input_text_elements, to=to, text_type=text_type) translation = response[0] if response else None if translation: @@ -205,14 +204,17 @@ def get_text_translation_exclude(): # [START get_text_translation_exclude] try: text_type = TextType.HTML - source_language = "en" - target_languages = ["cs"] + from_parameter = "en" + to = ["cs"] input_text_elements = [ '
This will not be translated.
This will be translated.
' ] response = text_translator.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language, text_type=text_type + body=input_text_elements, + to=to, + from_parameter=from_parameter, + text_type=text_type, ) translation = response[0] if response else None @@ -230,15 +232,13 @@ def get_text_translation_exclude(): def get_text_translation_entity(): # [START get_text_translation_entity] try: - source_language = "en" - target_languages = ["cs"] + from_parameter = "en" + to = ["cs"] input_text_elements = [ 'The word wordomatic is a dictionary entry.' ] - response = text_translator.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = text_translator.translate(body=input_text_elements, to=to, from_parameter=from_parameter) translation = response[0] if response else None if translation: @@ -257,12 +257,12 @@ def get_text_translation_profanity(): try: profanity_action = ProfanityAction.MARKED profanity_maker = ProfanityMarker.ASTERISK - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is ***."] response = text_translator.translate( - request_body=input_text_elements, - to=target_languages, + body=input_text_elements, + to=to, profanity_action=profanity_action, profanity_marker=profanity_maker, ) @@ -288,12 +288,10 @@ def get_text_translation_alignment(): # [START get_text_translation_alignment] try: include_alignment = True - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["The answer lies in machine translation."] - response = text_translator.translate( - request_body=input_text_elements, to=target_languages, include_alignment=include_alignment - ) + response = text_translator.translate(body=input_text_elements, to=to, include_alignment=include_alignment) translation = response[0] if response else None if translation: @@ -318,11 +316,11 @@ def get_text_translation_sentence_length(): # [START get_text_translation_sentence_length] try: include_sentence_length = True - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["The answer lies in machine translation. This is a test."] response = text_translator.translate( - request_body=input_text_elements, to=target_languages, include_sentence_length=include_sentence_length + body=input_text_elements, to=to, include_sentence_length=include_sentence_length ) translation = response[0] if response else None @@ -349,10 +347,10 @@ def get_text_translation_custom(): # [START get_text_translation_custom] try: category = "<>" - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test"] - response = text_translator.translate(request_body=input_text_elements, to=target_languages, category=category) + response = text_translator.translate(body=input_text_elements, to=to, category=category) translation = response[0] if response else None if translation: 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 50170ced1f83..14ea30724109 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 @@ -33,6 +33,7 @@ text_translator = sample_text_translation_client.create_text_translation_client_with_credential() + # ------------------------------------------------------------------------- # Text translation transliteration # ------------------------------------------------------------------------- @@ -45,7 +46,10 @@ def get_text_transliteration(): input_text_elements = ["这是个测试。"] response = text_translator.transliterate( - request_body=input_text_elements, language=language, from_script=from_script, to_script=to_script + body=input_text_elements, + language=language, + from_script=from_script, + to_script=to_script, ) transliteration = response[0] if response else None diff --git a/sdk/translation/azure-ai-translation-text/setup.py b/sdk/translation/azure-ai-translation-text/setup.py index 0188bfb2d400..fd168a300310 100644 --- a/sdk/translation/azure-ai-translation-text/setup.py +++ b/sdk/translation/azure-ai-translation-text/setup.py @@ -38,7 +38,7 @@ url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", keywords="azure, azure sdk", classifiers=[ - "Development Status :: 4 - Beta", + "Development Status :: 5 - Production/Stable", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", diff --git a/sdk/translation/azure-ai-translation-text/tests/preparer.py b/sdk/translation/azure-ai-translation-text/tests/preparer.py index 416e545b0207..01e6f4e4d1b8 100644 --- a/sdk/translation/azure-ai-translation-text/tests/preparer.py +++ b/sdk/translation/azure-ai-translation-text/tests/preparer.py @@ -16,5 +16,5 @@ text_translation_aadClientId="fakeAADClientId", text_translation_aadTenantId="fakeAADTenantId", text_translation_aadSecret="fakeAADSecret", - text_translation_aadResourceId="fakeResourceId" + text_translation_aadResourceId="fakeResourceId", ) 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 24c869d7cbdb..b0d0489983ff 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 @@ -18,7 +18,7 @@ def test_autodetect(self, **kwargs): client = self.create_client(endpoint, apikey, region) input_text_elements = ["Hello world"] - response = client.find_sentence_boundaries(request_body=input_text_elements) + 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.9 @@ -36,7 +36,7 @@ def test_with_language(self, **kwargs): "รวบรวมแผ่นคำตอบ ระยะเวลาของโครงการ วิธีเลือกชายในฝัน หมายเลขซีเรียลของระเบียน วันที่สิ้นสุดของโครงการเมื่อเสร็จสมบูรณ์ ปีที่มีการรวบรวม ทุกคนมีวัฒนธรรมและวิธีคิดเหมือนกัน ได้รับโทษจำคุกตลอดชีวิตใน ฉันลดได้ถึง 55 ปอนด์ได้อย่างไร ฉันคิดว่าใครๆ ก็ต้องการกำหนดเมนูอาหารส่วนบุคคล" ] - response = client.find_sentence_boundaries(request_body=input_text_elements, language="th") + response = client.find_sentence_boundaries(body=input_text_elements, language="th") assert response is not None expected_lengths = [78, 41, 110, 46] for i, expected_length in enumerate(expected_lengths): @@ -52,7 +52,7 @@ def test_with_language_script(self, **kwargs): input_text_elements = ["zhè shì gè cè shì。"] - response = client.find_sentence_boundaries(request_body=input_text_elements, language="zh-Hans", script="Latn") + response = client.find_sentence_boundaries(body=input_text_elements, language="zh-Hans", script="Latn") assert response is not None assert response[0].sent_len[0] == 18 @@ -69,7 +69,7 @@ def test_with_multiple_languages(self, **kwargs): "العالم هو مكان مثير جدا للاهتمام", ] - response = client.find_sentence_boundaries(request_body=input_text_elements) + response = client.find_sentence_boundaries(body=input_text_elements) assert response is not None assert response[0].detected_language.language == "en" assert response[1].detected_language.language == "ar" 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 d04f64279a46..6213bc9e431d 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 @@ -19,7 +19,7 @@ async def test_autodetect(self, **kwargs): input_text_elements = ["Hello world"] async with client: - response = await client.find_sentence_boundaries(request_body=input_text_elements) + 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.9 @@ -38,7 +38,7 @@ async def test_with_language(self, **kwargs): ] async with client: - response = await client.find_sentence_boundaries(request_body=input_text_elements, language="th") + response = await client.find_sentence_boundaries(body=input_text_elements, language="th") assert response is not None expected_lengths = [78, 41, 110, 46] for i, expected_length in enumerate(expected_lengths): @@ -56,7 +56,7 @@ async def test_with_language_script(self, **kwargs): async with client: response = await client.find_sentence_boundaries( - request_body=input_text_elements, language="zh-Hans", script="Latn" + body=input_text_elements, language="zh-Hans", script="Latn" ) assert response is not None assert response[0].sent_len[0] == 18 @@ -75,7 +75,7 @@ async def test_with_multiple_languages(self, **kwargs): ] async with client: - response = await client.find_sentence_boundaries(request_body=input_text_elements) + response = await client.find_sentence_boundaries(body=input_text_elements) assert response is not None assert response[0].detected_language.language == "en" assert response[1].detected_language.language == "ar" diff --git a/sdk/translation/azure-ai-translation-text/tests/test_dictionary_examples.py b/sdk/translation/azure-ai-translation-text/tests/test_dictionary_examples.py index 1d90e09fb667..bde073049195 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_dictionary_examples.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_dictionary_examples.py @@ -18,13 +18,11 @@ def test_single_input_element(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = [DictionaryExampleTextItem(text="fly", translation="volar")] - response = client.lookup_dictionary_examples( - request_body=input_text_elements, from_parameter=source_language, to=target_language - ) + response = client.lookup_dictionary_examples(body=input_text_elements, from_parameter=from_parameter, to=to) assert response is not None assert response[0].normalized_source == "fly" assert response[0].normalized_target == "volar" @@ -37,16 +35,14 @@ def test_multiple_input_elements(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = [ DictionaryExampleTextItem(text="fly", translation="volar"), DictionaryExampleTextItem(text="beef", translation="came"), ] - response = client.lookup_dictionary_examples( - request_body=input_text_elements, from_parameter=source_language, to=target_language - ) + response = client.lookup_dictionary_examples(body=input_text_elements, from_parameter=from_parameter, to=to) assert response is not None assert len(response) == 2 assert response[0].normalized_source == "fly" diff --git a/sdk/translation/azure-ai-translation-text/tests/test_dictionary_examples_async.py b/sdk/translation/azure-ai-translation-text/tests/test_dictionary_examples_async.py index 7a1a05760d7f..014d4e0040a1 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_dictionary_examples_async.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_dictionary_examples_async.py @@ -18,13 +18,13 @@ async def test_single_input_element(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = [DictionaryExampleTextItem(text="fly", translation="volar")] async with client: response = await client.lookup_dictionary_examples( - request_body=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) assert response is not None assert response[0].normalized_source == "fly" @@ -38,8 +38,8 @@ async def test_multiple_input_elements(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = [ DictionaryExampleTextItem(text="fly", translation="volar"), DictionaryExampleTextItem(text="beef", translation="came"), @@ -47,7 +47,7 @@ async def test_multiple_input_elements(self, **kwargs): async with client: response = await client.lookup_dictionary_examples( - request_body=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) assert response is not None assert len(response) == 2 diff --git a/sdk/translation/azure-ai-translation-text/tests/test_dictionary_lookup.py b/sdk/translation/azure-ai-translation-text/tests/test_dictionary_lookup.py index 13bf74f5fcc3..b1703ec3d45c 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_dictionary_lookup.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_dictionary_lookup.py @@ -17,13 +17,11 @@ def test_single_input_element(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = ["fly"] - response = client.lookup_dictionary_entries( - request_body=input_text_elements, from_parameter=source_language, to=target_language - ) + response = client.lookup_dictionary_entries(body=input_text_elements, from_parameter=from_parameter, to=to) assert response is not None assert response[0].normalized_source == "fly" assert response[0].display_source == "fly" @@ -36,13 +34,11 @@ def test_multiple_input_elements(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = ["fly", "fox"] - response = client.lookup_dictionary_entries( - request_body=input_text_elements, from_parameter=source_language, to=target_language - ) + response = client.lookup_dictionary_entries(body=input_text_elements, from_parameter=from_parameter, to=to) assert response is not None assert len(response) == 2 assert response[0].normalized_source == "fly" diff --git a/sdk/translation/azure-ai-translation-text/tests/test_dictionary_lookup_async.py b/sdk/translation/azure-ai-translation-text/tests/test_dictionary_lookup_async.py index 88a899033c33..aca8fc3a644c 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_dictionary_lookup_async.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_dictionary_lookup_async.py @@ -17,13 +17,13 @@ async def test_single_input_element(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = ["fly"] async with client: response = await client.lookup_dictionary_entries( - request_body=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) assert response is not None assert response[0].normalized_source == "fly" @@ -37,13 +37,13 @@ async def test_multiple_input_elements(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - source_language = "en" - target_language = "es" + from_parameter = "en" + to = "es" input_text_elements = ["fly", "fox"] async with client: response = await client.lookup_dictionary_entries( - request_body=input_text_elements, from_parameter=source_language, to=target_language + body=input_text_elements, from_parameter=from_parameter, to=to ) assert response is not None assert len(response) == 2 diff --git a/sdk/translation/azure-ai-translation-text/tests/test_get_languages.py b/sdk/translation/azure-ai-translation-text/tests/test_get_languages.py index 72a6436744dd..544a85c33006 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_get_languages.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_get_languages.py @@ -14,7 +14,7 @@ class TestGetLanguages(TextTranslationTest): def test_all_scopes(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_getlanguage_client(endpoint) - response = client.get_languages() + response = client.get_supported_languages() assert len(response.translation) > 0 assert len(response.transliteration) > 0 @@ -25,7 +25,7 @@ def test_all_scopes(self, **kwargs): def test_translation_scope(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_getlanguage_client(endpoint) - response = client.get_languages(scope="translation") + response = client.get_supported_languages(scope="translation") assert len(response.translation) > 0 translations = response.translation["af"] @@ -38,7 +38,7 @@ def test_translation_scope(self, **kwargs): def test_transliteration_scope(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_getlanguage_client(endpoint) - response = client.get_languages(scope="transliteration") + response = client.get_supported_languages(scope="transliteration") assert len(response.transliteration) > 0 transliterations = response.transliteration["be"] @@ -64,7 +64,7 @@ def test_transliteration_scope(self, **kwargs): def test_transliteration_multiple_scripts(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_getlanguage_client(endpoint) - response = client.get_languages(scope="transliteration") + response = client.get_supported_languages(scope="transliteration") assert len(response.transliteration) > 0 transliterations = response.transliteration["zh-Hant"] @@ -81,7 +81,7 @@ def test_transliteration_multiple_scripts(self, **kwargs): def test_dictionary_scope(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_getlanguage_client(endpoint) - response = client.get_languages(scope="dictionary") + response = client.get_supported_languages(scope="dictionary") assert len(response.dictionary) > 0 dictionaries = response.dictionary["de"] @@ -99,7 +99,7 @@ def test_dictionary_scope(self, **kwargs): def test_dictionary_multiple_translations(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_getlanguage_client(endpoint) - response = client.get_languages(scope="dictionary") + response = client.get_supported_languages(scope="dictionary") assert len(response.dictionary) > 0 dictionaries = response.dictionary["en"] @@ -117,7 +117,7 @@ def test_dictionary_multiple_translations(self, **kwargs): def test_with_culture(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_getlanguage_client(endpoint) - response = client.get_languages(accept_language="es") + response = client.get_supported_languages(accept_language="es") assert len(response.translation.items()) > 0 assert len(response.transliteration.items()) > 0 diff --git a/sdk/translation/azure-ai-translation-text/tests/test_get_languages_async.py b/sdk/translation/azure-ai-translation-text/tests/test_get_languages_async.py index 2bea4c6b2b5c..e7818325453d 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_get_languages_async.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_get_languages_async.py @@ -15,7 +15,7 @@ async def test_all_scopes(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_async_getlanguage_client(endpoint) async with client: - response = await client.get_languages() + response = await client.get_supported_languages() assert len(response.translation) > 0 assert len(response.transliteration) > 0 @@ -27,7 +27,7 @@ async def test_translation_scope(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_async_getlanguage_client(endpoint) async with client: - response = await client.get_languages(scope="translation") + response = await client.get_supported_languages(scope="translation") assert len(response.translation) > 0 translations = response.translation["af"] @@ -41,7 +41,7 @@ async def test_transliteration_scope(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_async_getlanguage_client(endpoint) async with client: - response = await client.get_languages(scope="transliteration") + response = await client.get_supported_languages(scope="transliteration") assert len(response.transliteration) > 0 transliterations = response.transliteration["be"] @@ -68,7 +68,7 @@ async def test_transliteration_multiple_scripts(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_async_getlanguage_client(endpoint) async with client: - response = await client.get_languages(scope="transliteration") + response = await client.get_supported_languages(scope="transliteration") assert len(response.transliteration) > 0 transliterations = response.transliteration["zh-Hant"] @@ -86,7 +86,7 @@ async def test_dictionary_scope(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_async_getlanguage_client(endpoint) async with client: - response = await client.get_languages(scope="dictionary") + response = await client.get_supported_languages(scope="dictionary") assert len(response.dictionary) > 0 dictionaries = response.dictionary["de"] @@ -105,7 +105,7 @@ async def test_dictionary_multiple_translations(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_async_getlanguage_client(endpoint) async with client: - response = await client.get_languages(scope="dictionary") + response = await client.get_supported_languages(scope="dictionary") assert len(response.dictionary) > 0 dictionaries = response.dictionary["en"] @@ -124,7 +124,7 @@ async def test_with_culture(self, **kwargs): endpoint = kwargs.get("text_translation_endpoint") client = self.create_async_getlanguage_client(endpoint) async with client: - response = await client.get_languages(accept_language="es") + response = await client.get_supported_languages(accept_language="es") assert len(response.translation.items()) > 0 assert len(response.transliteration.items()) > 0 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 ff669ae85f9d..fe0328337bb4 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_translation.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_translation.py @@ -19,12 +19,10 @@ def test_translate(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - source_language = "es" - target_languages = ["cs"] + from_parameter = "es" + to = ["cs"] input_text_elements = ["Hola mundo"] - response = client.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = client.translate(body=input_text_elements, to=to, from_parameter=from_parameter) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -39,9 +37,9 @@ def test_autodetect(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test."] - response = client.translate(request_body=input_text_elements, to=target_languages) + response = client.translate(body=input_text_elements, to=to) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -58,13 +56,13 @@ def test_no_translate_tag(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - source_language = "zh-chs" - target_languages = ["en"] + from_parameter = "zh-chs" + to = ["en"] input_text_elements = ["今天是怎么回事是非常可怕的"] response = client.translate( - request_body=input_text_elements, - to=target_languages, - from_parameter=source_language, + body=input_text_elements, + to=to, + from_parameter=from_parameter, text_type=TextType.HTML, ) @@ -80,14 +78,12 @@ def test_dictionary_tag(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - source_language = "en" - target_languages = ["es"] + from_parameter = "en" + to = ["es"] input_text_elements = [ 'The word < mstrans:dictionary translation ="wordomatic">wordomatic is a dictionary entry.' ] - response = client.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = client.translate(body=input_text_elements, to=to, from_parameter=from_parameter) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -102,13 +98,13 @@ def test_transliteration(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - source_language = "ar" - target_languages = ["zh-Hans"] + from_parameter = "ar" + to = ["zh-Hans"] input_text_elements = ["hudha akhtabar."] response = client.translate( - request_body=input_text_elements, - to=target_languages, - from_parameter=source_language, + body=input_text_elements, + to=to, + from_parameter=from_parameter, from_script="Latn", to_script="Latn", ) @@ -127,13 +123,13 @@ def test_from_to_latin(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - source_language = "hi" - target_languages = ["ta"] + from_parameter = "hi" + to = ["ta"] input_text_elements = ["ap kaise ho"] response = client.translate( - request_body=input_text_elements, - to=target_languages, - from_parameter=source_language, + body=input_text_elements, + to=to, + from_parameter=from_parameter, from_script="Latn", to_script="Latn", ) @@ -151,13 +147,13 @@ def test_multiple_input(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = [ "This is a test.", "Esto es una prueba.", "Dies ist ein Test.", ] - response = client.translate(request_body=input_text_elements, to=target_languages) + response = client.translate(body=input_text_elements, to=to) assert len(response) == 3 assert response[0].detected_language.language == "en" @@ -179,9 +175,9 @@ def test_multiple_target_languages(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - target_languages = ["cs", "es", "de"] + to = ["cs", "es", "de"] input_text_elements = ["This is a test."] - response = client.translate(request_body=input_text_elements, to=target_languages) + response = client.translate(body=input_text_elements, to=to) assert len(response) == 1 assert len(response[0].translations) == 3 @@ -199,9 +195,9 @@ def test_different_texttypes(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test."] - response = client.translate(request_body=input_text_elements, to=target_languages, text_type=TextType.HTML) + response = client.translate(body=input_text_elements, to=to, text_type=TextType.HTML) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -216,11 +212,11 @@ def test_profanity(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - target_languages = ["zh-cn"] + to = ["zh-cn"] input_text_elements = ["shit this is fucking crazy"] response = client.translate( - request_body=input_text_elements, - to=target_languages, + body=input_text_elements, + to=to, profanity_action=ProfanityAction.MARKED, profanity_marker=ProfanityMarker.ASTERISK, ) @@ -239,9 +235,9 @@ def test_alignment(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["It is a beautiful morning"] - response = client.translate(request_body=input_text_elements, to=target_languages, include_alignment=True) + response = client.translate(body=input_text_elements, to=to, include_alignment=True) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -257,11 +253,11 @@ def test_sentence_length(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - target_languages = ["fr"] + to = ["fr"] input_text_elements = [ "La réponse se trouve dans la traduction automatique. La meilleure technologie de traduction automatique ne peut pas toujours fournir des traductions adaptées à un site ou des utilisateurs comme un être humain. Il suffit de copier et coller un extrait de code n'importe où." ] - response = client.translate(request_body=input_text_elements, to=target_languages, include_sentence_length=True) + response = client.translate(body=input_text_elements, to=to, include_sentence_length=True) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -278,9 +274,9 @@ def test_custom_endpoint(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client(endpoint, apikey, region) - target_languages = ["fr"] + to = ["fr"] input_text_elements = ["It is a beautiful morning"] - response = client.translate(request_body=input_text_elements, to=target_languages) + response = client.translate(body=input_text_elements, to=to) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -296,9 +292,9 @@ def test_token(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_client_token(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test."] - response = client.translate(request_body=input_text_elements, to=target_languages) + response = client.translate(body=input_text_elements, to=to) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -314,12 +310,10 @@ def test_translate_aad(self, **kwargs): token_credential = self.get_mt_credential(False) client = self.create_text_translation_client_with_aad(token_credential, aadRegion, aadResourceId) - source_language = "es" - target_languages = ["cs"] + from_parameter = "es" + to = ["cs"] input_text_elements = ["Hola mundo"] - response = client.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = client.translate(body=input_text_elements, to=to, from_parameter=from_parameter) assert len(response) == 1 assert len(response[0].translations) == 1 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 b5f33bf04426..8f1501f0e203 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 @@ -20,13 +20,11 @@ async def test_translate(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - source_language = "es" - target_languages = ["cs"] + from_parameter = "es" + to = ["cs"] input_text_elements = ["Hola mundo"] async with client: - response = await client.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = await client.translate(body=input_text_elements, to=to, from_parameter=from_parameter) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -41,10 +39,10 @@ async def test_autodetect(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test."] async with client: - response = await client.translate(request_body=input_text_elements, to=target_languages) + response = await client.translate(body=input_text_elements, to=to) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -61,14 +59,14 @@ async def test_no_translate_tag(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - source_language = "zh-chs" - target_languages = ["en"] + from_parameter = "zh-chs" + to = ["en"] input_text_elements = ["今天是怎么回事是非常可怕的"] async with client: response = await client.translate( - request_body=input_text_elements, - to=target_languages, - from_parameter=source_language, + body=input_text_elements, + to=to, + from_parameter=from_parameter, text_type=TextType.HTML, ) @@ -84,15 +82,13 @@ async def test_dictionary_tag(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - source_language = "en" - target_languages = ["es"] + from_parameter = "en" + to = ["es"] input_text_elements = [ 'The word < mstrans:dictionary translation ="wordomatic">wordomatic is a dictionary entry.' ] async with client: - response = await client.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = await client.translate(body=input_text_elements, to=to, from_parameter=from_parameter) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -107,14 +103,14 @@ async def test_transliteration(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - source_language = "ar" - target_languages = ["zh-Hans"] + from_parameter = "ar" + to = ["zh-Hans"] input_text_elements = ["hudha akhtabar."] async with client: response = await client.translate( - request_body=input_text_elements, - to=target_languages, - from_parameter=source_language, + body=input_text_elements, + to=to, + from_parameter=from_parameter, from_script="Latn", to_script="Latn", ) @@ -133,14 +129,14 @@ async def test_from_to_latin(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - source_language = "hi" - target_languages = ["ta"] + from_parameter = "hi" + to = ["ta"] input_text_elements = ["ap kaise ho"] async with client: response = await client.translate( - request_body=input_text_elements, - to=target_languages, - from_parameter=source_language, + body=input_text_elements, + to=to, + from_parameter=from_parameter, from_script="Latn", to_script="Latn", ) @@ -158,14 +154,14 @@ async def test_multiple_input(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = [ "This is a test.", "Esto es una prueba.", "Dies ist ein Test.", ] async with client: - response = await client.translate(request_body=input_text_elements, to=target_languages) + response = await client.translate(body=input_text_elements, to=to) assert len(response) == 3 assert response[0].detected_language.language == "en" @@ -187,10 +183,10 @@ async def test_multiple_target_languages(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - target_languages = ["cs", "es", "de"] + to = ["cs", "es", "de"] input_text_elements = ["This is a test."] async with client: - response = await client.translate(request_body=input_text_elements, to=target_languages) + response = await client.translate(body=input_text_elements, to=to) assert len(response) == 1 assert len(response[0].translations) == 3 @@ -208,12 +204,10 @@ async def test_different_texttypes(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test."] async with client: - response = await client.translate( - request_body=input_text_elements, to=target_languages, text_type=TextType.HTML - ) + response = await client.translate(body=input_text_elements, to=to, text_type=TextType.HTML) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -228,12 +222,12 @@ async def test_profanity(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - target_languages = ["zh-cn"] + to = ["zh-cn"] input_text_elements = ["shit this is fucking crazy"] async with client: response = await client.translate( - request_body=input_text_elements, - to=target_languages, + body=input_text_elements, + to=to, profanity_action=ProfanityAction.MARKED, profanity_marker=ProfanityMarker.ASTERISK, ) @@ -252,12 +246,10 @@ async def test_alignment(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["It is a beautiful morning"] async with client: - response = await client.translate( - request_body=input_text_elements, to=target_languages, include_alignment=True - ) + response = await client.translate(body=input_text_elements, to=to, include_alignment=True) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -273,14 +265,12 @@ async def test_sentence_length(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - target_languages = ["fr"] + to = ["fr"] input_text_elements = [ "La réponse se trouve dans la traduction automatique. La meilleure technologie de traduction automatique ne peut pas toujours fournir des traductions adaptées à un site ou des utilisateurs comme un être humain. Il suffit de copier et coller un extrait de code n'importe où." ] async with client: - response = await client.translate( - request_body=input_text_elements, to=target_languages, include_sentence_length=True - ) + response = await client.translate(body=input_text_elements, to=to, include_sentence_length=True) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -297,10 +287,10 @@ async def test_custom_endpoint(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client(endpoint, apikey, region) - target_languages = ["fr"] + to = ["fr"] input_text_elements = ["It is a beautiful morning"] async with client: - response = await client.translate(request_body=input_text_elements, to=target_languages) + response = await client.translate(body=input_text_elements, to=to) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -316,10 +306,10 @@ async def test_token(self, **kwargs): region = kwargs.get("text_translation_region") client = self.create_async_client_token(endpoint, apikey, region) - target_languages = ["cs"] + to = ["cs"] input_text_elements = ["This is a test."] async with client: - response = await client.translate(request_body=input_text_elements, to=target_languages) + response = await client.translate(body=input_text_elements, to=to) assert len(response) == 1 assert len(response[0].translations) == 1 @@ -335,12 +325,10 @@ async def test_translate_aad(self, **kwargs): token_credential = self.get_mt_credential(True) client = self.create_async_text_translation_client_with_aad(token_credential, aadRegion, aadResourceId) - source_language = "es" - target_languages = ["cs"] + from_parameter = "es" + to = ["cs"] input_text_elements = ["Hola mundo"] - response = await client.translate( - request_body=input_text_elements, to=target_languages, from_parameter=source_language - ) + response = await client.translate(body=input_text_elements, to=to, from_parameter=from_parameter) assert len(response) == 1 assert len(response[0].translations) == 1 diff --git a/sdk/translation/azure-ai-translation-text/tests/test_transliteration.py b/sdk/translation/azure-ai-translation-text/tests/test_transliteration.py index 4e90d55641de..dca33ad14409 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_transliteration.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_transliteration.py @@ -20,7 +20,10 @@ def test_transliteration(self, **kwargs): input_text_elements = ["这里怎么一回事?"] response = client.transliterate( - request_body=input_text_elements, language="zh-Hans", from_script="Hans", to_script="Latn" + body=input_text_elements, + language="zh-Hans", + from_script="Hans", + to_script="Latn", ) assert response is not None @@ -36,7 +39,10 @@ def test_multiple_inputs(self, **kwargs): input_text_elements = ["यहएककसौटीहैयहएककसौटीहै", "यहएककसौटीहै"] response = client.transliterate( - request_body=input_text_elements, language="hi", from_script="Deva", to_script="Latn" + body=input_text_elements, + language="hi", + from_script="Deva", + to_script="Latn", ) assert response is not None @@ -57,7 +63,10 @@ def test_edit_distance(self, **kwargs): "hukkabar", ] response = client.transliterate( - request_body=input_text_elements, language="gu", from_script="Latn", to_script="Gujr" + body=input_text_elements, + language="gu", + from_script="Latn", + to_script="Gujr", ) assert response is not None diff --git a/sdk/translation/azure-ai-translation-text/tests/test_transliteration_async.py b/sdk/translation/azure-ai-translation-text/tests/test_transliteration_async.py index f1dd54e252a2..b8fa9e72837c 100644 --- a/sdk/translation/azure-ai-translation-text/tests/test_transliteration_async.py +++ b/sdk/translation/azure-ai-translation-text/tests/test_transliteration_async.py @@ -21,7 +21,10 @@ async def test_transliteration(self, **kwargs): input_text_elements = ["这里怎么一回事?"] async with client: response = await client.transliterate( - request_body=input_text_elements, language="zh-Hans", from_script="Hans", to_script="Latn" + body=input_text_elements, + language="zh-Hans", + from_script="Hans", + to_script="Latn", ) assert response is not None @@ -38,7 +41,10 @@ async def test_multiple_inputs(self, **kwargs): input_text_elements = ["यहएककसौटीहैयहएककसौटीहै", "यहएककसौटीहै"] async with client: response = await client.transliterate( - request_body=input_text_elements, language="hi", from_script="Deva", to_script="Latn" + body=input_text_elements, + language="hi", + from_script="Deva", + to_script="Latn", ) assert response is not None @@ -60,7 +66,10 @@ async def test_edit_distance(self, **kwargs): ] async with client: response = await client.transliterate( - request_body=input_text_elements, language="gu", from_script="Latn", to_script="Gujr" + body=input_text_elements, + language="gu", + from_script="Latn", + to_script="Gujr", ) assert response is not None diff --git a/sdk/translation/azure-ai-translation-text/tests/testcase.py b/sdk/translation/azure-ai-translation-text/tests/testcase.py index 31f37bc828b1..fcd987fa1638 100644 --- a/sdk/translation/azure-ai-translation-text/tests/testcase.py +++ b/sdk/translation/azure-ai-translation-text/tests/testcase.py @@ -5,30 +5,30 @@ import os from devtools_testutils.fake_credentials_async import AsyncFakeCredential -from azure.core.credentials import AccessToken +from azure.core.credentials import AzureKeyCredential from devtools_testutils import AzureRecordedTestCase -from azure.ai.translation.text import TextTranslationClient, TranslatorCredential, TranslatorAADCredential +from azure.ai.translation.text import TextTranslationClient from static_access_token_credential import StaticAccessTokenCredential + class TextTranslationTest(AzureRecordedTestCase): def create_getlanguage_client(self, endpoint): client = TextTranslationClient(endpoint=endpoint, credential=None) return client def create_client(self, endpoint, apikey, region): - credential = TranslatorCredential(apikey, region) - client = TextTranslationClient(endpoint=endpoint, credential=credential) + credential = AzureKeyCredential(apikey) + client = TextTranslationClient(endpoint=endpoint, credential=credential, region=region) return client def create_client_token(self, endpoint, apikey, region): credential = StaticAccessTokenCredential(apikey, region) client = TextTranslationClient(endpoint=endpoint, credential=credential) return client - + def create_text_translation_client_with_aad(self, innerCredential, aadRegion, aadResourceId): - credential = TranslatorAADCredential(innerCredential, aadResourceId, aadRegion) - text_translator = TextTranslationClient(credential=credential) + text_translator = TextTranslationClient(credential=innerCredential, resource_id=aadResourceId, region=aadRegion) return text_translator def create_async_getlanguage_client(self, endpoint): @@ -38,10 +38,10 @@ def create_async_getlanguage_client(self, endpoint): return client def create_async_client(self, endpoint, apikey, region): - credential = TranslatorCredential(apikey, region) + credential = AzureKeyCredential(apikey) from azure.ai.translation.text.aio import TextTranslationClient as TextTranslationClientAsync - client = TextTranslationClientAsync(endpoint=endpoint, credential=credential) + client = TextTranslationClientAsync(endpoint=endpoint, credential=credential, region=region) return client def create_async_client_token(self, endpoint, apikey, region): @@ -50,11 +50,13 @@ def create_async_client_token(self, endpoint, apikey, region): client = TextTranslationClientAsync(endpoint=endpoint, credential=credential) return client - + def create_async_text_translation_client_with_aad(self, innerCredential, aadRegion, aadResourceId): - from azure.ai.translation.text.aio import TextTranslationClient as TextTranslationClientAsync, AsyncTranslatorAADCredential - credential = AsyncTranslatorAADCredential(innerCredential, aadResourceId, aadRegion) - text_translator = TextTranslationClientAsync(credential=credential) + from azure.ai.translation.text.aio import TextTranslationClient as TextTranslationClientAsync + + text_translator = TextTranslationClientAsync( + credential=innerCredential, resource_id=aadResourceId, region=aadRegion + ) return text_translator def get_mt_credential(self, is_async, **kwargs): @@ -65,7 +67,6 @@ def get_mt_credential(self, is_async, **kwargs): if is_async: from azure.identity.aio import ClientSecretCredential - tenant_id = os.environ.get("AZURE_TENANT_ID", getattr(os.environ, "TENANT_ID", None)) client_id = os.environ.get("AZURE_CLIENT_ID", getattr(os.environ, "CLIENT_ID", None)) secret = os.environ.get("AZURE_CLIENT_SECRET", getattr(os.environ, "CLIENT_SECRET", None)) diff --git a/sdk/translation/azure-ai-translation-text/tsp-location.yaml b/sdk/translation/azure-ai-translation-text/tsp-location.yaml index 2870e7447ece..151e72c1cf9d 100644 --- a/sdk/translation/azure-ai-translation-text/tsp-location.yaml +++ b/sdk/translation/azure-ai-translation-text/tsp-location.yaml @@ -1,3 +1,3 @@ directory: specification/translation/Azure.AI.TextTranslation -commit: 7b097c7e91a72a8930b94282274158b71e604695 +commit: 9583ed6c26ce1f10bbea92346e28a46394a784b4 repo: Azure/azure-rest-api-specs