diff --git a/sdk/translation/azure-ai-translation-text/_meta.json b/sdk/translation/azure-ai-translation-text/_meta.json
new file mode 100644
index 000000000000..830245e4424d
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/_meta.json
@@ -0,0 +1,6 @@
+{
+ "commit": "3480bf363db32d50e520b62e201758acf287753c",
+ "repository_url": "https://github.com/Azure/azure-rest-api-specs",
+ "typespec_src": "specification/translation/Azure.AI.TextTranslation",
+ "@azure-tools/typespec-python": "0.36.1"
+}
\ No newline at end of file
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/__init__.py
index 4b66a9e2dde2..9222cec2fdae 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/__init__.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/__init__.py
@@ -5,18 +5,28 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._patch import TextTranslationClient
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+
+from ._client import TextTranslationClient # type: ignore
from ._version import VERSION
__version__ = VERSION
-
+try:
+ from ._patch import __all__ as _patch_all
+ from ._patch import *
+except ImportError:
+ _patch_all = []
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"TextTranslationClient",
]
-
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_client.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_client.py
index c5ebee7ced4a..8205916b633f 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_client.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_client.py
@@ -8,6 +8,7 @@
from copy import deepcopy
from typing import Any
+from typing_extensions import Self
from azure.core import PipelineClient
from azure.core.pipeline import policies
@@ -18,7 +19,7 @@
from ._serialization import Deserializer, Serializer
-class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword
+class TextTranslationClient(TextTranslationClientOperationsMixin):
"""Text translation is a cloud-based REST API feature of the Translator service that uses neural
machine translation technology to enable quick and accurate source-to-target text translation
in real time across all supported languages.
@@ -107,7 +108,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs:
def close(self) -> None:
self._client.close()
- def __enter__(self) -> "TextTranslationClient":
+ def __enter__(self) -> Self:
self._client.__enter__()
return self
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_configuration.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_configuration.py
index 37b94a41e8a9..ae307004749f 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_configuration.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_configuration.py
@@ -13,7 +13,7 @@
from ._version import VERSION
-class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long
+class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes
"""Configuration for TextTranslationClient.
Note that all parameters used to create this instance are saved as instance
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 5cf70733404d..e6a2730f9276 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
@@ -1,10 +1,11 @@
+# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
-# pylint: disable=protected-access, arguments-differ, signature-differs, broad-except
+# pylint: disable=protected-access, broad-except
import copy
import calendar
@@ -19,6 +20,7 @@
import email.utils
from datetime import datetime, date, time, timedelta, timezone
from json import JSONEncoder
+import xml.etree.ElementTree as ET
from typing_extensions import Self
import isodate
from azure.core.exceptions import DeserializationError
@@ -123,7 +125,7 @@ def _serialize_datetime(o, format: typing.Optional[str] = None):
def _is_readonly(p):
try:
- return p._visibility == ["read"] # pylint: disable=protected-access
+ return p._visibility == ["read"]
except AttributeError:
return False
@@ -286,6 +288,12 @@ def _deserialize_decimal(attr):
return decimal.Decimal(str(attr))
+def _deserialize_int_as_str(attr):
+ if isinstance(attr, int):
+ return attr
+ return int(attr)
+
+
_DESERIALIZE_MAPPING = {
datetime: _deserialize_datetime,
date: _deserialize_date,
@@ -307,9 +315,11 @@ def _deserialize_decimal(attr):
def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None):
+ if annotation is int and rf and rf._format == "str":
+ return _deserialize_int_as_str
if rf and rf._format:
return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format)
- return _DESERIALIZE_MAPPING.get(annotation)
+ return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore
def _get_type_alias_type(module_name: str, alias_name: str):
@@ -441,6 +451,10 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m
return float(o)
if isinstance(o, enum.Enum):
return o.value
+ if isinstance(o, int):
+ if format == "str":
+ return str(o)
+ return o
try:
# First try datetime.datetime
return _serialize_datetime(o, format)
@@ -471,11 +485,16 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin
return value
if rf._is_model:
return _deserialize(rf._type, value)
+ if isinstance(value, ET.Element):
+ value = _deserialize(rf._type, value)
return _serialize(value, rf._format)
class Model(_MyMutableMapping):
_is_model = True
+ # label whether current class's _attr_to_rest_field has been calculated
+ # could not see _attr_to_rest_field directly because subclass inherits it from parent class
+ _calculated: typing.Set[str] = set()
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
class_name = self.__class__.__name__
@@ -486,10 +505,58 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
for rest_field in self._attr_to_rest_field.values()
if rest_field._default is not _UNSET
}
- if args:
- dict_to_pass.update(
- {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()}
- )
+ if args: # pylint: disable=too-many-nested-blocks
+ if isinstance(args[0], ET.Element):
+ existed_attr_keys = []
+ model_meta = getattr(self, "_xml", {})
+
+ for rf in self._attr_to_rest_field.values():
+ prop_meta = getattr(rf, "_xml", {})
+ xml_name = prop_meta.get("name", rf._rest_name)
+ xml_ns = prop_meta.get("ns", model_meta.get("ns", None))
+ if xml_ns:
+ xml_name = "{" + xml_ns + "}" + xml_name
+
+ # attribute
+ if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None:
+ existed_attr_keys.append(xml_name)
+ dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name))
+ continue
+
+ # unwrapped element is array
+ if prop_meta.get("unwrapped", False):
+ # unwrapped array could either use prop items meta/prop meta
+ if prop_meta.get("itemsName"):
+ xml_name = prop_meta.get("itemsName")
+ xml_ns = prop_meta.get("itemNs")
+ if xml_ns:
+ xml_name = "{" + xml_ns + "}" + xml_name
+ items = args[0].findall(xml_name) # pyright: ignore
+ if len(items) > 0:
+ existed_attr_keys.append(xml_name)
+ dict_to_pass[rf._rest_name] = _deserialize(rf._type, items)
+ continue
+
+ # text element is primitive type
+ if prop_meta.get("text", False):
+ if args[0].text is not None:
+ dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text)
+ continue
+
+ # wrapped element could be normal property or array, it should only have one element
+ item = args[0].find(xml_name)
+ if item is not None:
+ existed_attr_keys.append(xml_name)
+ dict_to_pass[rf._rest_name] = _deserialize(rf._type, item)
+
+ # rest thing is additional properties
+ for e in args[0]:
+ if e.tag not in existed_attr_keys:
+ dict_to_pass[e.tag] = _convert_element(e)
+ else:
+ dict_to_pass.update(
+ {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()}
+ )
else:
non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field]
if non_attr_kwargs:
@@ -507,55 +574,70 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
def copy(self) -> "Model":
return Model(self.__dict__)
- def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: # pylint: disable=unused-argument
- # we know the last three classes in mro are going to be 'Model', 'dict', and 'object'
- mros = cls.__mro__[:-3][::-1] # ignore model, dict, and object parents, and reverse the mro order
- attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property
- k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type")
- }
- annotations = {
- k: v
- for mro_class in mros
- if hasattr(mro_class, "__annotations__") # pylint: disable=no-member
- for k, v in mro_class.__annotations__.items() # pylint: disable=no-member
- }
- for attr, rf in attr_to_rest_field.items():
- rf._module = cls.__module__
- if not rf._type:
- rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None))
- if not rf._rest_name_input:
- rf._rest_name_input = attr
- cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items())
+ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self:
+ if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated:
+ # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping',
+ # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object'
+ mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order
+ attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property
+ k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type")
+ }
+ annotations = {
+ k: v
+ for mro_class in mros
+ if hasattr(mro_class, "__annotations__")
+ for k, v in mro_class.__annotations__.items()
+ }
+ for attr, rf in attr_to_rest_field.items():
+ rf._module = cls.__module__
+ if not rf._type:
+ rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None))
+ if not rf._rest_name_input:
+ rf._rest_name_input = attr
+ cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items())
+ cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}")
return super().__new__(cls) # pylint: disable=no-value-for-parameter
def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None:
for base in cls.__bases__:
- if hasattr(base, "__mapping__"): # pylint: disable=no-member
- base.__mapping__[discriminator or cls.__name__] = cls # type: ignore # pylint: disable=no-member
+ if hasattr(base, "__mapping__"):
+ base.__mapping__[discriminator or cls.__name__] = cls # type: ignore
@classmethod
- def _get_discriminator(cls, exist_discriminators) -> typing.Optional[str]:
+ def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]:
for v in cls.__dict__.values():
- if (
- isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators
- ): # pylint: disable=protected-access
- return v._rest_name # pylint: disable=protected-access
+ if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators:
+ return v
return None
@classmethod
def _deserialize(cls, data, exist_discriminators):
- if not hasattr(cls, "__mapping__"): # pylint: disable=no-member
+ if not hasattr(cls, "__mapping__"):
return cls(data)
discriminator = cls._get_discriminator(exist_discriminators)
- exist_discriminators.append(discriminator)
- mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) # pyright: ignore # pylint: disable=no-member
- if mapped_cls == cls:
+ if discriminator is None:
return cls(data)
- return mapped_cls._deserialize(data, exist_discriminators) # pylint: disable=protected-access
+ exist_discriminators.append(discriminator._rest_name)
+ if isinstance(data, ET.Element):
+ model_meta = getattr(cls, "_xml", {})
+ prop_meta = getattr(discriminator, "_xml", {})
+ xml_name = prop_meta.get("name", discriminator._rest_name)
+ xml_ns = prop_meta.get("ns", model_meta.get("ns", None))
+ if xml_ns:
+ xml_name = "{" + xml_ns + "}" + xml_name
+
+ if data.get(xml_name) is not None:
+ discriminator_value = data.get(xml_name)
+ else:
+ discriminator_value = data.find(xml_name).text # pyright: ignore
+ else:
+ discriminator_value = data.get(discriminator._rest_name)
+ mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore
+ return mapped_cls._deserialize(data, exist_discriminators)
def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]:
- """Return a dict that can be JSONify using json.dump.
+ """Return a dict that can be turned into json using json.dump.
:keyword bool exclude_readonly: Whether to remove the readonly properties.
:returns: A dict JSON compatible object
@@ -563,6 +645,7 @@ def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.
"""
result = {}
+ readonly_props = []
if exclude_readonly:
readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)]
for k, v in self.items():
@@ -617,6 +700,8 @@ def _deserialize_dict(
):
if obj is None:
return obj
+ if isinstance(obj, ET.Element):
+ obj = {child.tag: child for child in obj}
return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()}
@@ -637,6 +722,8 @@ def _deserialize_sequence(
):
if obj is None:
return obj
+ if isinstance(obj, ET.Element):
+ obj = list(obj)
return type(obj)(_deserialize(deserializer, entry, module) for entry in obj)
@@ -647,12 +734,12 @@ def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.An
)
-def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, R0912
+def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-branches
annotation: typing.Any,
module: typing.Optional[str],
rf: typing.Optional["_RestField"] = None,
) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]:
- if not annotation or annotation in [int, float]:
+ if not annotation:
return None
# is it a type alias?
@@ -727,7 +814,6 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915,
try:
if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore
if len(annotation.__args__) > 1: # pyright: ignore
-
entry_deserializers = [
_get_deserialize_callable_from_annotation(dt, module, rf)
for dt in annotation.__args__ # pyright: ignore
@@ -762,12 +848,23 @@ def _deserialize_default(
def _deserialize_with_callable(
deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]],
value: typing.Any,
-):
+): # pylint: disable=too-many-return-statements
try:
if value is None or isinstance(value, _Null):
return None
+ if isinstance(value, ET.Element):
+ if deserializer is str:
+ return value.text or ""
+ if deserializer is int:
+ return int(value.text) if value.text else None
+ if deserializer is float:
+ return float(value.text) if value.text else None
+ if deserializer is bool:
+ return value.text == "true" if value.text else None
if deserializer is None:
return value
+ if deserializer in [int, float, bool]:
+ return deserializer(value)
if isinstance(deserializer, CaseInsensitiveEnumMeta):
try:
return deserializer(value)
@@ -808,6 +905,7 @@ def __init__(
default: typing.Any = _UNSET,
format: typing.Optional[str] = None,
is_multipart_file_input: bool = False,
+ xml: typing.Optional[typing.Dict[str, typing.Any]] = None,
):
self._type = type
self._rest_name_input = name
@@ -818,6 +916,7 @@ def __init__(
self._default = default
self._format = format
self._is_multipart_file_input = is_multipart_file_input
+ self._xml = xml if xml is not None else {}
@property
def _class_type(self) -> typing.Any:
@@ -868,6 +967,7 @@ def rest_field(
default: typing.Any = _UNSET,
format: typing.Optional[str] = None,
is_multipart_file_input: bool = False,
+ xml: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> typing.Any:
return _RestField(
name=name,
@@ -876,6 +976,7 @@ def rest_field(
default=default,
format=format,
is_multipart_file_input=is_multipart_file_input,
+ xml=xml,
)
@@ -883,5 +984,176 @@ def rest_discriminator(
*,
name: typing.Optional[str] = None,
type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin
+ visibility: typing.Optional[typing.List[str]] = None,
+ xml: typing.Optional[typing.Dict[str, typing.Any]] = None,
+) -> typing.Any:
+ return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml)
+
+
+def serialize_xml(model: Model, exclude_readonly: bool = False) -> str:
+ """Serialize a model to XML.
+
+ :param Model model: The model to serialize.
+ :param bool exclude_readonly: Whether to exclude readonly properties.
+ :returns: The XML representation of the model.
+ :rtype: str
+ """
+ return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore
+
+
+def _get_element(
+ o: typing.Any,
+ exclude_readonly: bool = False,
+ parent_meta: typing.Optional[typing.Dict[str, typing.Any]] = None,
+ wrapped_element: typing.Optional[ET.Element] = None,
+) -> typing.Union[ET.Element, typing.List[ET.Element]]:
+ if _is_model(o):
+ model_meta = getattr(o, "_xml", {})
+
+ # if prop is a model, then use the prop element directly, else generate a wrapper of model
+ if wrapped_element is None:
+ wrapped_element = _create_xml_element(
+ model_meta.get("name", o.__class__.__name__),
+ model_meta.get("prefix"),
+ model_meta.get("ns"),
+ )
+
+ readonly_props = []
+ if exclude_readonly:
+ readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)]
+
+ for k, v in o.items():
+ # do not serialize readonly properties
+ if exclude_readonly and k in readonly_props:
+ continue
+
+ prop_rest_field = _get_rest_field(o._attr_to_rest_field, k)
+ if prop_rest_field:
+ prop_meta = getattr(prop_rest_field, "_xml").copy()
+ # use the wire name as xml name if no specific name is set
+ if prop_meta.get("name") is None:
+ prop_meta["name"] = k
+ else:
+ # additional properties will not have rest field, use the wire name as xml name
+ prop_meta = {"name": k}
+
+ # if no ns for prop, use model's
+ if prop_meta.get("ns") is None and model_meta.get("ns"):
+ prop_meta["ns"] = model_meta.get("ns")
+ prop_meta["prefix"] = model_meta.get("prefix")
+
+ if prop_meta.get("unwrapped", False):
+ # unwrapped could only set on array
+ wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta))
+ elif prop_meta.get("text", False):
+ # text could only set on primitive type
+ wrapped_element.text = _get_primitive_type_value(v)
+ elif prop_meta.get("attribute", False):
+ xml_name = prop_meta.get("name", k)
+ if prop_meta.get("ns"):
+ ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore
+ xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore
+ # attribute should be primitive type
+ wrapped_element.set(xml_name, _get_primitive_type_value(v))
+ else:
+ # other wrapped prop element
+ wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta))
+ return wrapped_element
+ if isinstance(o, list):
+ return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore
+ if isinstance(o, dict):
+ result = []
+ for k, v in o.items():
+ result.append(
+ _get_wrapped_element(
+ v,
+ exclude_readonly,
+ {
+ "name": k,
+ "ns": parent_meta.get("ns") if parent_meta else None,
+ "prefix": parent_meta.get("prefix") if parent_meta else None,
+ },
+ )
+ )
+ return result
+
+ # primitive case need to create element based on parent_meta
+ if parent_meta:
+ return _get_wrapped_element(
+ o,
+ exclude_readonly,
+ {
+ "name": parent_meta.get("itemsName", parent_meta.get("name")),
+ "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")),
+ "ns": parent_meta.get("itemsNs", parent_meta.get("ns")),
+ },
+ )
+
+ raise ValueError("Could not serialize value into xml: " + o)
+
+
+def _get_wrapped_element(
+ v: typing.Any,
+ exclude_readonly: bool,
+ meta: typing.Optional[typing.Dict[str, typing.Any]],
+) -> ET.Element:
+ wrapped_element = _create_xml_element(
+ meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None
+ )
+ if isinstance(v, (dict, list)):
+ wrapped_element.extend(_get_element(v, exclude_readonly, meta))
+ elif _is_model(v):
+ _get_element(v, exclude_readonly, meta, wrapped_element)
+ else:
+ wrapped_element.text = _get_primitive_type_value(v)
+ return wrapped_element
+
+
+def _get_primitive_type_value(v) -> str:
+ if v is True:
+ return "true"
+ if v is False:
+ return "false"
+ if isinstance(v, _Null):
+ return ""
+ return str(v)
+
+
+def _create_xml_element(tag, prefix=None, ns=None):
+ if prefix and ns:
+ ET.register_namespace(prefix, ns)
+ if ns:
+ return ET.Element("{" + ns + "}" + tag)
+ return ET.Element(tag)
+
+
+def _deserialize_xml(
+ deserializer: typing.Any,
+ value: str,
) -> typing.Any:
- return _RestField(name=name, type=type, is_discriminator=True)
+ element = ET.fromstring(value) # nosec
+ return _deserialize(deserializer, element)
+
+
+def _convert_element(e: ET.Element):
+ # dict case
+ if len(e.attrib) > 0 or len({child.tag for child in e}) > 1:
+ dict_result: typing.Dict[str, typing.Any] = {}
+ for child in e:
+ if dict_result.get(child.tag) is not None:
+ if isinstance(dict_result[child.tag], list):
+ dict_result[child.tag].append(_convert_element(child))
+ else:
+ dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)]
+ else:
+ dict_result[child.tag] = _convert_element(child)
+ dict_result.update(e.attrib)
+ return dict_result
+ # array case
+ if len(e) > 0:
+ array_result: typing.List[typing.Any] = []
+ for child in e:
+ array_result.append(_convert_element(child))
+ return array_result
+ # primitive case
+ return e.text
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/__init__.py
index 47ae0af6503a..dbcf8750add3 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/__init__.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/__init__.py
@@ -5,14 +5,21 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._patch import TextTranslationClientOperationsMixin
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+from ._operations import TextTranslationClientOperationsMixin # type: ignore
+
+from ._patch import __all__ as _patch_all
+from ._patch import *
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"TextTranslationClientOperationsMixin",
]
-
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_operations.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_operations.py
index 73eda75baff4..80fe106111f9 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_operations.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_operations.py
@@ -1,4 +1,4 @@
-# pylint: disable=too-many-lines,too-many-statements
+# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
@@ -6,11 +6,10 @@
# 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
import sys
-from typing import Any, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, overload
+from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload
from azure.core import MatchConditions
from azure.core.exceptions import (
@@ -20,6 +19,8 @@
ResourceModifiedError,
ResourceNotFoundError,
ResourceNotModifiedError,
+ StreamClosedError,
+ StreamConsumedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
@@ -35,7 +36,7 @@
if sys.version_info >= (3, 9):
from collections.abc import MutableMapping
else:
- from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports
+ from typing import MutableMapping # type: ignore
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
@@ -277,7 +278,6 @@ def get_supported_languages(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.GetSupportedLanguagesResult:
- # pylint: disable=line-too-long
"""Gets the set of languages currently supported by other operations of the Translator.
Gets the set of languages currently supported by other operations of the Translator.
@@ -312,88 +312,8 @@ def get_supported_languages(
MutableMapping
:rtype: ~azure.ai.translation.text.models.GetSupportedLanguagesResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "dictionary": {
- "str": {
- "dir": "str", # Directionality, which is rtl for
- right-to-left languages or ltr for left-to-right languages. Required.
- Known values are: "ltr" and "rtl".
- "name": "str", # Display name of the language in the locale
- requested via Accept-Language header. Required.
- "nativeName": "str", # Display name of the language in the
- locale native for this language. Required.
- "translations": [
- {
- "code": "str", # Language code identifying
- the target language. Required.
- "dir": "str", # Directionality, which is rtl
- for right-to-left languages or ltr for left-to-right languages.
- Required. Known values are: "ltr" and "rtl".
- "name": "str", # Display name of the
- language in the locale requested via Accept-Language header.
- Required.
- "nativeName": "str" # Display name of the
- language in the locale native for this language. Required.
- }
- ]
- }
- },
- "translation": {
- "str": {
- "dir": "str", # Directionality, which is rtl for
- right-to-left languages or ltr for left-to-right languages. Required.
- Known values are: "ltr" and "rtl".
- "name": "str", # Display name of the language in the locale
- requested via Accept-Language header. Required.
- "nativeName": "str" # Display name of the language in the
- locale native for this language. Required.
- }
- },
- "transliteration": {
- "str": {
- "name": "str", # Display name of the language in the locale
- requested via Accept-Language header. Required.
- "nativeName": "str", # Display name of the language in the
- locale native for this language. Required.
- "scripts": [
- {
- "code": "str", # Code identifying the
- script. Required.
- "dir": "str", # Directionality, which is rtl
- for right-to-left languages or ltr for left-to-right languages.
- Required. Known values are: "ltr" and "rtl".
- "name": "str", # Display name of the script
- in the locale requested via Accept-Language header. Required.
- "nativeName": "str", # Display name of the
- language in the locale native for the language. Required.
- "toScripts": [
- {
- "code": "str", # Code
- identifying the script. Required.
- "dir": "str", #
- Directionality, which is rtl for right-to-left languages
- or ltr for left-to-right languages. Required. Known
- values are: "ltr" and "rtl".
- "name": "str", # Display
- name of the script in the locale requested via
- Accept-Language header. Required.
- "nativeName": "str" #
- Display name of the language in the locale native for the
- language. Required.
- }
- ]
- }
- ]
- }
- }
- }
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -436,7 +356,10 @@ def get_supported_languages(
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -476,7 +399,6 @@ def translate(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
"""Translate Text.
Translate Text.
@@ -561,74 +483,6 @@ def translate(
:return: list of TranslatedTextItem
:rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
"""
@overload
@@ -652,7 +506,6 @@ def translate(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
"""Translate Text.
Translate Text.
@@ -737,67 +590,6 @@ def translate(
:return: list of TranslatedTextItem
:rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
"""
@distributed_trace
@@ -820,7 +612,6 @@ def translate(
allow_fallback: Optional[bool] = None,
**kwargs: Any
) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
"""Translate Text.
Translate Text.
@@ -903,69 +694,8 @@ def translate(
:return: list of TranslatedTextItem
:rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1020,7 +750,10 @@ def translate(
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -1079,26 +812,6 @@ def transliterate(
:return: list of TransliteratedText
:rtype: list[~azure.ai.translation.text.models.TransliteratedText]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
"""
@overload
@@ -1140,19 +853,6 @@ def transliterate(
:return: list of TransliteratedText
:rtype: list[~azure.ai.translation.text.models.TransliteratedText]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
"""
@distributed_trace
@@ -1191,21 +891,8 @@ def transliterate(
:return: list of TransliteratedText
:rtype: list[~azure.ai.translation.text.models.TransliteratedText]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1251,7 +938,10 @@ def transliterate(
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -1280,7 +970,6 @@ def find_sentence_boundaries(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
"""Find Sentence Boundaries.
Find Sentence Boundaries.
@@ -1304,34 +993,6 @@ def find_sentence_boundaries(
:return: list of BreakSentenceItem
:rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
"""
@overload
@@ -1345,7 +1006,6 @@ def find_sentence_boundaries(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
"""Find Sentence Boundaries.
Find Sentence Boundaries.
@@ -1369,27 +1029,6 @@ def find_sentence_boundaries(
:return: list of BreakSentenceItem
:rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
"""
@distributed_trace
@@ -1402,7 +1041,6 @@ def find_sentence_boundaries(
script: Optional[str] = None,
**kwargs: Any
) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
"""Find Sentence Boundaries.
Find Sentence Boundaries.
@@ -1424,29 +1062,8 @@ def find_sentence_boundaries(
:return: list of BreakSentenceItem
:rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1491,7 +1108,10 @@ def find_sentence_boundaries(
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -1520,7 +1140,6 @@ def lookup_dictionary_entries(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Entries.
Lookup Dictionary Entries.
@@ -1544,84 +1163,6 @@ def lookup_dictionary_entries(
:return: list of DictionaryLookupItem
:rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "confidence": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
"""
@overload
@@ -1635,7 +1176,6 @@ def lookup_dictionary_entries(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Entries.
Lookup Dictionary Entries.
@@ -1659,77 +1199,6 @@ def lookup_dictionary_entries(
:return: list of DictionaryLookupItem
:rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "confidence": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
"""
@distributed_trace
@@ -1742,7 +1211,6 @@ def lookup_dictionary_entries(
client_trace_id: Optional[str] = None,
**kwargs: Any
) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Entries.
Lookup Dictionary Entries.
@@ -1764,79 +1232,8 @@ def lookup_dictionary_entries(
:return: list of DictionaryLookupItem
:rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "confidence": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1881,7 +1278,10 @@ def lookup_dictionary_entries(
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -1910,7 +1310,6 @@ def lookup_dictionary_examples(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.DictionaryExampleItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Examples.
Lookup Dictionary Examples.
@@ -1934,56 +1333,6 @@ def lookup_dictionary_examples(
:return: list of DictionaryExampleItem
:rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str", # Text to translate. Required.
- "translation": "str" # A string specifying the translated text
- previously returned by the Dictionary lookup operation. This should be the
- value from the normalizedTarget field in the translations list of the
- Dictionary lookup response. The service will return examples for the
- specific source-target word-pair. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "examples": [
- {
- "sourcePrefix": "str", # The string to concatenate
- before the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceSuffix": "str", # The string to concatenate
- after the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceTerm": "str", # A string equal to the actual
- term looked up. The string is added with sourcePrefix and
- sourceSuffix to form the complete example. Its value is separated so
- it can be marked in a user interface, e.g., by bolding it. Required.
- "targetPrefix": "str", # A string similar to
- sourcePrefix but for the target. Required.
- "targetSuffix": "str", # A string similar to
- sourceSuffix but for the target. Required.
- "targetTerm": "str" # A string similar to sourceTerm
- but for the target. Required.
- }
- ],
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. Generally, this should be identical to the value of the Text
- field at the matching list index in the body of the request. Required.
- "normalizedTarget": "str" # A string giving the normalized form of
- the target term. Generally, this should be identical to the value of the
- Translation field at the matching list index in the body of the request.
- Required.
- }
- ]
"""
@overload
@@ -1997,7 +1346,6 @@ def lookup_dictionary_examples(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.DictionaryExampleItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Examples.
Lookup Dictionary Examples.
@@ -2021,44 +1369,6 @@ def lookup_dictionary_examples(
:return: list of DictionaryExampleItem
:rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "examples": [
- {
- "sourcePrefix": "str", # The string to concatenate
- before the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceSuffix": "str", # The string to concatenate
- after the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceTerm": "str", # A string equal to the actual
- term looked up. The string is added with sourcePrefix and
- sourceSuffix to form the complete example. Its value is separated so
- it can be marked in a user interface, e.g., by bolding it. Required.
- "targetPrefix": "str", # A string similar to
- sourcePrefix but for the target. Required.
- "targetSuffix": "str", # A string similar to
- sourceSuffix but for the target. Required.
- "targetTerm": "str" # A string similar to sourceTerm
- but for the target. Required.
- }
- ],
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. Generally, this should be identical to the value of the Text
- field at the matching list index in the body of the request. Required.
- "normalizedTarget": "str" # A string giving the normalized form of
- the target term. Generally, this should be identical to the value of the
- Translation field at the matching list index in the body of the request.
- Required.
- }
- ]
"""
@distributed_trace
@@ -2071,7 +1381,6 @@ def lookup_dictionary_examples(
client_trace_id: Optional[str] = None,
**kwargs: Any
) -> List[_models.DictionaryExampleItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Examples.
Lookup Dictionary Examples.
@@ -2093,46 +1402,8 @@ def lookup_dictionary_examples(
:return: list of DictionaryExampleItem
:rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "examples": [
- {
- "sourcePrefix": "str", # The string to concatenate
- before the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceSuffix": "str", # The string to concatenate
- after the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceTerm": "str", # A string equal to the actual
- term looked up. The string is added with sourcePrefix and
- sourceSuffix to form the complete example. Its value is separated so
- it can be marked in a user interface, e.g., by bolding it. Required.
- "targetPrefix": "str", # A string similar to
- sourcePrefix but for the target. Required.
- "targetSuffix": "str", # A string similar to
- sourceSuffix but for the target. Required.
- "targetTerm": "str" # A string similar to sourceTerm
- but for the target. Required.
- }
- ],
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. Generally, this should be identical to the value of the Text
- field at the matching list index in the body of the request. Required.
- "normalizedTarget": "str" # A string giving the normalized form of
- the target term. Generally, this should be identical to the value of the
- Translation field at the matching list index in the body of the request.
- Required.
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -2177,7 +1448,10 @@ def lookup_dictionary_examples(
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_patch.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_operations/_patch.py
index 7506475e6478..f7dd32510333 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,1366 +2,13 @@
# 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
"""
-from typing import Any, cast, IO, List, Optional, overload, Union
-from .. import models as _models
-from ._operations import TextTranslationClientOperationsMixin as TextTranslationClientOperationsMixinGenerated
-
-
-class TextTranslationClientOperationsMixin(TextTranslationClientOperationsMixinGenerated):
- @overload
- def translate(
- self,
- body: List[str],
- *,
- to_language: List[str],
- client_trace_id: Optional[str] = None,
- from_language: Optional[str] = None,
- text_type: Optional[Union[str, _models.TextType]] = None,
- category: Optional[str] = None,
- profanity_action: Optional[Union[str, _models.ProfanityAction]] = None,
- profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None,
- include_alignment: Optional[bool] = None,
- include_sentence_length: Optional[bool] = None,
- suggested_from: Optional[str] = None,
- from_script: Optional[str] = None,
- to_script: Optional[str] = None,
- allow_fallback: Optional[bool] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
- """Translate Text.
-
- Translate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: list[str]
- :keyword to_language: Specifies the language of the output text. The target language must be one of the
- supported languages included
- in the translation scope. For example, use to_language=de to translate to German.
- It's possible to translate to multiple languages simultaneously by repeating the parameter in
- the query string.
- For example, use to_language=de&to_language=it to translate to German and Italian. Required.
- :paramtype to_language: list[str]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword from_language: Specifies the language of the input text. Find which languages are
- available to translate from by
- looking up supported languages using the translation scope. If the from parameter isn't
- specified,
- automatic language detection is applied to determine the source language.
-
- You must use the from parameter rather than autodetection when using the dynamic dictionary
- feature.
- Note: the dynamic dictionary feature is case-sensitive. Default value is None.
- :paramtype from_language: str
- :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any
- HTML needs to be a well-formed,
- complete element. Possible values are: plain (default) or html. Known values are: "Plain" and
- "Html". Default value is None.
- :paramtype text_type: str or ~azure.ai.translation.text.models.TextType
- :keyword category: A string specifying the category (domain) of the translation. This parameter
- is used to get translations
- from a customized system built with Custom Translator. Add the Category ID from your Custom
- Translator
- project details to this parameter to use your deployed customized system. Default value is:
- general. Default value is None.
- :paramtype category: str
- :keyword profanity_action: Specifies how profanities should be treated in translations.
- Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction",
- "Marked", and "Deleted". Default value is None.
- :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction
- :keyword profanity_marker: Specifies how profanities should be marked in translations.
- Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag".
- Default value is None.
- :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker
- :keyword include_alignment: Specifies whether to include alignment projection from source text
- to translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_alignment: bool
- :keyword include_sentence_length: Specifies whether to include sentence boundaries for the
- input text and the translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_sentence_length: bool
- :keyword suggested_from: Specifies a fallback language if the language of the input text can't
- be identified.
- Language autodetection is applied when the from parameter is omitted. If detection fails,
- the suggestedFrom language will be assumed. Default value is None.
- :paramtype suggested_from: str
- :keyword from_script: Specifies the script of the input text. Default value is None.
- :paramtype from_script: str
- :keyword to_script: Specifies the script of the translated text. Default value is None.
- :paramtype to_script: str
- :keyword allow_fallback: Specifies that the service is allowed to fall back to a general system
- when a custom system doesn't exist.
- Possible values are: true (default) or false.
-
- allowFallback=false specifies that the translation should only use systems trained for the
- category specified
- by the request. If a translation for language X to language Y requires chaining through a
- pivot language E,
- then all the systems in the chain (X → E and E → Y) will need to be custom and have the same
- category.
- If no system is found with the specific category, the request will return a 400 status code.
- allowFallback=true
- specifies that the service is allowed to fall back to a general system when a custom system
- doesn't exist. Default value is None.
- :paramtype allow_fallback: bool
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TranslatedTextItem
- :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- str" # Text to translate. Required.
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
- """
-
- @overload
- def translate(
- self,
- body: List[_models.InputTextItem],
- *,
- to_language: List[str],
- client_trace_id: Optional[str] = None,
- from_language: Optional[str] = None,
- text_type: Optional[Union[str, _models.TextType]] = None,
- category: Optional[str] = None,
- profanity_action: Optional[Union[str, _models.ProfanityAction]] = None,
- profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None,
- include_alignment: Optional[bool] = None,
- include_sentence_length: Optional[bool] = None,
- suggested_from: Optional[str] = None,
- from_script: Optional[str] = None,
- to_script: Optional[str] = None,
- allow_fallback: Optional[bool] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
- """Translate Text.
-
- Translate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: list[~azure.ai.translation.text.models.InputTextItem]
- :keyword to_language: Specifies the language of the output text. The target language must be one of the
- supported languages included
- in the translation scope. For example, use to_language=de to translate to German.
- It's possible to translate to multiple languages simultaneously by repeating the parameter in
- the query string.
- For example, use to_language=de&to_language=it to translate to German and Italian. Required.
- :paramtype to_language: list[str]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword from_language: Specifies the language of the input text. Find which languages are
- available to translate from by
- looking up supported languages using the translation scope. If the from parameter isn't
- specified,
- automatic language detection is applied to determine the source language.
-
- You must use the from parameter rather than autodetection when using the dynamic dictionary
- feature.
- Note: the dynamic dictionary feature is case-sensitive. Default value is None.
- :paramtype from_language: str
- :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any
- HTML needs to be a well-formed,
- complete element. Possible values are: plain (default) or html. Known values are: "Plain" and
- "Html". Default value is None.
- :paramtype text_type: str or ~azure.ai.translation.text.models.TextType
- :keyword category: A string specifying the category (domain) of the translation. This parameter
- is used to get translations
- from a customized system built with Custom Translator. Add the Category ID from your Custom
- Translator
- project details to this parameter to use your deployed customized system. Default value is:
- general. Default value is None.
- :paramtype category: str
- :keyword profanity_action: Specifies how profanities should be treated in translations.
- Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction",
- "Marked", and "Deleted". Default value is None.
- :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction
- :keyword profanity_marker: Specifies how profanities should be marked in translations.
- Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag".
- Default value is None.
- :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker
- :keyword include_alignment: Specifies whether to include alignment projection from source text
- to translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_alignment: bool
- :keyword include_sentence_length: Specifies whether to include sentence boundaries for the
- input text and the translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_sentence_length: bool
- :keyword suggested_from: Specifies a fallback language if the language of the input text can't
- be identified.
- Language autodetection is applied when the from parameter is omitted. If detection fails,
- the suggestedFrom language will be assumed. Default value is None.
- :paramtype suggested_from: str
- :keyword from_script: Specifies the script of the input text. Default value is None.
- :paramtype from_script: str
- :keyword to_script: Specifies the script of the translated text. Default value is None.
- :paramtype to_script: str
- :keyword allow_fallback: Specifies that the service is allowed to fall back to a general system
- when a custom system doesn't exist.
- Possible values are: true (default) or false.
-
- allowFallback=false specifies that the translation should only use systems trained for the
- category specified
- by the request. If a translation for language X to language Y requires chaining through a
- pivot language E,
- then all the systems in the chain (X → E and E → Y) will need to be custom and have the same
- category.
- If no system is found with the specific category, the request will return a 400 status code.
- allowFallback=true
- specifies that the service is allowed to fall back to a general system when a custom system
- doesn't exist. Default value is None.
- :paramtype allow_fallback: bool
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TranslatedTextItem
- :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
- """
-
- @overload
- def translate(
- self,
- body: IO[bytes],
- *,
- to_language: List[str],
- client_trace_id: Optional[str] = None,
- from_language: Optional[str] = None,
- text_type: Optional[Union[str, _models.TextType]] = None,
- category: Optional[str] = None,
- profanity_action: Optional[Union[str, _models.ProfanityAction]] = None,
- profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None,
- include_alignment: Optional[bool] = None,
- include_sentence_length: Optional[bool] = None,
- suggested_from: Optional[str] = None,
- from_script: Optional[str] = None,
- to_script: Optional[str] = None,
- allow_fallback: Optional[bool] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
- """Translate Text.
-
- Translate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: IO[bytes]
- :keyword to_language: Specifies the language of the output text. The target language must be one of the
- supported languages included
- in the translation scope. For example, use to_language=de to translate to German.
- It's possible to translate to multiple languages simultaneously by repeating the parameter in
- the query string.
- For example, use to_language=de&to_language=it to translate to German and Italian. Required.
- :paramtype to_language: list[str]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword from_language: Specifies the language of the input text. Find which languages are
- available to translate from by
- looking up supported languages using the translation scope. If the from parameter isn't
- specified,
- automatic language detection is applied to determine the source language.
-
- You must use the from parameter rather than autodetection when using the dynamic dictionary
- feature.
- Note: the dynamic dictionary feature is case-sensitive. Default value is None.
- :paramtype from_language: str
- :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any
- HTML needs to be a well-formed,
- complete element. Possible values are: plain (default) or html. Known values are: "Plain" and
- "Html". Default value is None.
- :paramtype text_type: str or ~azure.ai.translation.text.models.TextType
- :keyword category: A string specifying the category (domain) of the translation. This parameter
- is used to get translations
- from a customized system built with Custom Translator. Add the Category ID from your Custom
- Translator
- project details to this parameter to use your deployed customized system. Default value is:
- general. Default value is None.
- :paramtype category: str
- :keyword profanity_action: Specifies how profanities should be treated in translations.
- Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction",
- "Marked", and "Deleted". Default value is None.
- :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction
- :keyword profanity_marker: Specifies how profanities should be marked in translations.
- Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag".
- Default value is None.
- :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker
- :keyword include_alignment: Specifies whether to include alignment projection from source text
- to translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_alignment: bool
- :keyword include_sentence_length: Specifies whether to include sentence boundaries for the
- input text and the translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_sentence_length: bool
- :keyword suggested_from: Specifies a fallback language if the language of the input text can't
- be identified.
- Language autodetection is applied when the from parameter is omitted. If detection fails,
- the suggestedFrom language will be assumed. Default value is None.
- :paramtype suggested_from: str
- :keyword from_script: Specifies the script of the input text. Default value is None.
- :paramtype from_script: str
- :keyword to_script: Specifies the script of the translated text. Default value is None.
- :paramtype to_script: str
- :keyword allow_fallback: Specifies that the service is allowed to fall back to a general system
- when a custom system doesn't exist.
- Possible values are: true (default) or false.
-
- allowFallback=false specifies that the translation should only use systems trained for the
- category specified
- by the request. If a translation for language X to language Y requires chaining through a
- pivot language E,
- then all the systems in the chain (X → E and E → Y) will need to be custom and have the same
- category.
- If no system is found with the specific category, the request will return a 400 status code.
- allowFallback=true
- specifies that the service is allowed to fall back to a general system when a custom system
- doesn't exist. Default value is None.
- :paramtype allow_fallback: bool
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TranslatedTextItem
- :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
- """
-
- def translate( # pyright: ignore[reportIncompatibleMethodOverride]
- self,
- body: Union[List[str], List[_models.InputTextItem], IO[bytes]],
- *,
- to_language: List[str],
- client_trace_id: Optional[str] = None,
- from_language: Optional[str] = None,
- text_type: Optional[Union[str, _models.TextType]] = None,
- category: Optional[str] = None,
- profanity_action: Optional[Union[str, _models.ProfanityAction]] = None,
- profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None,
- include_alignment: Optional[bool] = None,
- include_sentence_length: Optional[bool] = None,
- suggested_from: Optional[str] = None,
- from_script: Optional[str] = None,
- to_script: Optional[str] = None,
- allow_fallback: Optional[bool] = None,
- **kwargs: Any
- ) -> List[_models.TranslatedTextItem]:
- request_body: Union[List[_models.InputTextItem], IO[bytes]]
- if isinstance(body, list) and all(isinstance(item, str) for item in body):
- input_text_items: List[_models.InputTextItem] = []
- for text in body:
- input_text_items.append(_models.InputTextItem(text=cast(str, text)))
- request_body = input_text_items
- else:
- request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body)
-
- return super().translate(
- body=request_body,
- to_language=to_language,
- client_trace_id=client_trace_id,
- from_language=from_language,
- text_type=text_type,
- category=category,
- profanity_action=profanity_action,
- profanity_marker=profanity_marker,
- include_alignment=include_alignment,
- include_sentence_length=include_sentence_length,
- suggested_from=suggested_from,
- from_script=from_script,
- to_script=to_script,
- allow_fallback=allow_fallback,
- **kwargs
- )
-
- @overload
- def transliterate(
- self,
- body: List[str],
- *,
- language: str,
- from_script: str,
- to_script: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TransliteratedText]:
- """Transliterate Text.
-
- Transliterate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: list[str]
- :keyword language: Specifies the language of the text to convert from one script to another.
- Possible languages are listed in the transliteration scope obtained by querying the service
- for its supported languages. Required.
- :paramtype language: str
- :keyword from_script: Specifies the script used by the input text. Look up supported languages
- using the transliteration scope,
- to find input scripts available for the selected language. Required.
- :paramtype from_script: str
- :keyword to_script: Specifies the output script. Look up supported languages using the
- transliteration scope, to find output
- scripts available for the selected combination of input language and input script. Required.
- :paramtype to_script: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TransliteratedText
- :rtype: list[~azure.ai.translation.text.models.TransliteratedText]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
- """
-
- @overload
- def transliterate(
- self,
- body: List[_models.InputTextItem],
- *,
- language: str,
- from_script: str,
- to_script: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TransliteratedText]:
- """Transliterate Text.
-
- Transliterate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: list[~azure.ai.translation.text.models.InputTextItem]
- :keyword language: Specifies the language of the text to convert from one script to another.
- Possible languages are listed in the transliteration scope obtained by querying the service
- for its supported languages. Required.
- :paramtype language: str
- :keyword from_script: Specifies the script used by the input text. Look up supported languages
- using the transliteration scope,
- to find input scripts available for the selected language. Required.
- :paramtype from_script: str
- :keyword to_script: Specifies the output script. Look up supported languages using the
- transliteration scope, to find output
- scripts available for the selected combination of input language and input script. Required.
- :paramtype to_script: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TransliteratedText
- :rtype: list[~azure.ai.translation.text.models.TransliteratedText]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
- """
-
- @overload
- def transliterate(
- self,
- body: IO[bytes],
- *,
- language: str,
- from_script: str,
- to_script: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TransliteratedText]:
- """Transliterate Text.
-
- Transliterate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: IO[bytes]
- :keyword language: Specifies the language of the text to convert from one script to another.
- Possible languages are listed in the transliteration scope obtained by querying the service
- for its supported languages. Required.
- :paramtype language: str
- :keyword from_script: Specifies the script used by the input text. Look up supported languages
- using the transliteration scope,
- to find input scripts available for the selected language. Required.
- :paramtype from_script: str
- :keyword to_script: Specifies the output script. Look up supported languages using the
- transliteration scope, to find output
- scripts available for the selected combination of input language and input script. Required.
- :paramtype to_script: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TransliteratedText
- :rtype: list[~azure.ai.translation.text.models.TransliteratedText]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
- """
-
- def transliterate( # pyright: ignore[reportIncompatibleMethodOverride]
- self,
- body: Union[List[str], List[_models.InputTextItem], IO[bytes]],
- *,
- language: str,
- from_script: str,
- to_script: str,
- client_trace_id: Optional[str] = None,
- **kwargs: Any
- ) -> List[_models.TransliteratedText]:
- request_body: Union[List[_models.InputTextItem], IO[bytes]]
- if isinstance(body, list) and all(isinstance(item, str) for item in body):
- input_text_items: List[_models.InputTextItem] = []
- for text in body:
- input_text_items.append(_models.InputTextItem(text=cast(str, text)))
- request_body = input_text_items
- else:
- request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body)
-
- return super().transliterate(
- body=request_body,
- language=language,
- from_script=from_script,
- to_script=to_script,
- client_trace_id=client_trace_id,
- **kwargs
- )
-
- @overload
- def find_sentence_boundaries(
- self,
- body: List[str],
- *,
- client_trace_id: Optional[str] = None,
- language: Optional[str] = None,
- script: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
- """Find Sentence Boundaries.
-
- Find Sentence Boundaries.
-
- :param body: Defines the content of the request. Required.
- :type body: list[str]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword language: Language tag identifying the language of the input text.
- If a code isn't specified, automatic language detection will be applied. Default value is
- None.
- :paramtype language: str
- :keyword script: Script tag identifying the script used by the input text.
- If a script isn't specified, the default script of the language will be assumed. Default value
- is None.
- :paramtype script: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of BreakSentenceItem
- :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
- """
-
- @overload
- def find_sentence_boundaries(
- self,
- body: List[_models.InputTextItem],
- *,
- client_trace_id: Optional[str] = None,
- language: Optional[str] = None,
- script: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
- """Find Sentence Boundaries.
-
- Find Sentence Boundaries.
-
- :param body: Defines the content of the request. Required.
- :type body: list[~azure.ai.translation.text.models.InputTextItem]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword language: Language tag identifying the language of the input text.
- If a code isn't specified, automatic language detection will be applied. Default value is
- None.
- :paramtype language: str
- :keyword script: Script tag identifying the script used by the input text.
- If a script isn't specified, the default script of the language will be assumed. Default value
- is None.
- :paramtype script: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of BreakSentenceItem
- :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
- """
-
- @overload
- def find_sentence_boundaries(
- self,
- body: IO[bytes],
- *,
- client_trace_id: Optional[str] = None,
- language: Optional[str] = None,
- script: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
- """Find Sentence Boundaries.
-
- Find Sentence Boundaries.
-
- :param body: Defines the content of the request. Required.
- :type body: IO[bytes]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword language: Language tag identifying the language of the input text.
- If a code isn't specified, automatic language detection will be applied. Default value is
- None.
- :paramtype language: str
- :keyword script: Script tag identifying the script used by the input text.
- If a script isn't specified, the default script of the language will be assumed. Default value
- is None.
- :paramtype script: str
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of BreakSentenceItem
- :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
- """
-
- def find_sentence_boundaries( # pyright: ignore[reportIncompatibleMethodOverride]
- self,
- body: Union[List[str], List[_models.InputTextItem], IO[bytes]],
- *,
- client_trace_id: Optional[str] = None,
- language: Optional[str] = None,
- script: Optional[str] = None,
- **kwargs: Any
- ) -> List[_models.BreakSentenceItem]:
- request_body: Union[List[_models.InputTextItem], IO[bytes]]
- if isinstance(body, list) and all(isinstance(item, str) for item in body):
- input_text_items: List[_models.InputTextItem] = []
- for text in body:
- input_text_items.append(_models.InputTextItem(text=cast(str, text)))
- request_body = input_text_items
-
- else:
- request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body)
-
- return super().find_sentence_boundaries(
- body=request_body, language=language, script=script, client_trace_id=client_trace_id, **kwargs
- )
-
- @overload
- def lookup_dictionary_entries(
- self,
- body: List[str],
- *,
- from_language: str,
- to_language: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
- """Lookup Dictionary Entries.
-
- Lookup Dictionary Entries.
-
- :param body: Defines the content of the request. Required.
- :type body: list[str]
- :keyword from_language: Specifies the language of the input text.
- The source language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype from_language: str
- :keyword to_language: Specifies the language of the output text.
- The target language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype to_language: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of DictionaryLookupItem
- :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "score": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
- """
-
- @overload
- def lookup_dictionary_entries(
- self,
- body: List[_models.InputTextItem],
- *,
- from_language: str,
- to_language: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
- """Lookup Dictionary Entries.
-
- Lookup Dictionary Entries.
-
- :param body: Defines the content of the request. Required.
- :type body: list[~azure.ai.translation.text.models.InputTextItem]
- :keyword from_language: Specifies the language of the input text.
- The source language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype from_language: str
- :keyword to_language: Specifies the language of the output text.
- The target language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype to_language: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of DictionaryLookupItem
- :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "score": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
- """
-
- @overload
- def lookup_dictionary_entries(
- self,
- body: IO[bytes],
- *,
- from_language: str,
- to_language: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
- """Lookup Dictionary Entries.
-
- Lookup Dictionary Entries.
-
- :param body: Defines the content of the request. Required.
- :type body: IO[bytes]
- :keyword from_language: Specifies the language of the input text.
- The source language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype from_language: str
- :keyword to_language: Specifies the language of the output text.
- The target language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype to_language: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of DictionaryLookupItem
- :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "score": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
- """
-
- def lookup_dictionary_entries( # pyright: ignore[reportIncompatibleMethodOverride]
- self,
- body: Union[List[str], List[_models.InputTextItem], IO[bytes]],
- *,
- from_language: str,
- to_language: str,
- client_trace_id: Optional[str] = None,
- **kwargs: Any
- ) -> List[_models.DictionaryLookupItem]:
- request_body: Union[List[_models.InputTextItem], IO[bytes]]
- if isinstance(body, list) and all(isinstance(item, str) for item in body):
- input_text_items: List[_models.InputTextItem] = []
- for text in body:
- input_text_items.append(_models.InputTextItem(text=cast(str, text)))
- request_body = input_text_items
- else:
- request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body)
-
- return super().lookup_dictionary_entries(
- body=request_body,
- from_language=from_language,
- to_language=to_language,
- client_trace_id=client_trace_id,
- **kwargs
- )
-
+from typing import List
-__all__: List[str] = [
- "TextTranslationClientOperationsMixin"
-] # Add all objects you want publicly available to users at this package level
+__all__: List[str] = [] # Add all objects you want publicly available to users at this package level
def patch_sdk():
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_patch.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_patch.py
index 104e2adda4ba..f7dd32510333 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,17 +2,13 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
-# pylint: disable=C4717, C4722, C4748
+"""Customize generated code here.
-from typing import Optional, Any, overload
-from azure.core.pipeline import PipelineRequest
-from azure.core.pipeline.policies import SansIOHTTPPolicy, BearerTokenCredentialPolicy, AzureKeyCredentialPolicy
-from azure.core.credentials import TokenCredential, AzureKeyCredential
+Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize
+"""
+from typing import List
-from ._client import TextTranslationClient as ServiceClientGenerated
-
-DEFAULT_ENTRA_ID_SCOPE = "https://cognitiveservices.azure.com"
-DEFAULT_SCOPE = "/.default"
+__all__: List[str] = [] # Add all objects you want publicly available to users at this package level
def patch_sdk():
@@ -22,181 +18,3 @@ def patch_sdk():
you can't accomplish using the techniques described in
https://aka.ms/azsdk/python/dpcodegen/python/customize
"""
-
-
-class TranslatorAuthenticationPolicy(SansIOHTTPPolicy):
- """Translator Authentication Policy. Adds both authentication headers that are required.
- Ocp-Apim-Subscription-Region header contains region of the Translator resource.
- Ocp-Apim-Subscription-Key header contains API key of the Translator resource.
- """
-
- def __init__(self, credential: AzureKeyCredential, region: str):
- self.credential = credential
- self.region = region
-
- def on_request(self, request: PipelineRequest) -> None:
- request.http_request.headers["Ocp-Apim-Subscription-Key"] = self.credential.key
- request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.region
-
-
-class TranslatorEntraIdAuthenticationPolicy(BearerTokenCredentialPolicy):
- """Translator EntraId Authentication Policy. Adds headers that are required by Translator Service
- when global endpoint is used with Entra Id policy.
- Ocp-Apim-Subscription-Region header contains region of the Translator resource.
- Ocp-Apim-ResourceId header contains Azure resource Id - Translator resource.
-
- :param credential: Translator Entra Id Credentials used to access Translator Resource for global endpoint.
- :type credential: ~azure.core.credentials.TokenCredential
- :keyword str region: Used for National Clouds.
- :keyword str resource_id: Used with both a TokenCredential combined with a region.
- :keyword str audience: Scopes of the credentials.
- """
-
- def __init__(
- self, credential: TokenCredential, resource_id: str, region: str, audience: str, **kwargs: Any
- ) -> None:
- super(TranslatorEntraIdAuthenticationPolicy, self).__init__(credential, audience, **kwargs)
- self.resource_id = resource_id
- self.region = region
- self.translator_credential = credential
-
- def on_request(self, request: PipelineRequest) -> None:
- request.http_request.headers["Ocp-Apim-ResourceId"] = self.resource_id
- request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.region
- super().on_request(request)
-
-
-def get_translation_endpoint(endpoint, api_version):
- if not endpoint:
- endpoint = "https://api.cognitive.microsofttranslator.com"
-
- translator_endpoint: str = ""
- if "cognitiveservices" in endpoint:
- translator_endpoint = endpoint + "/translator/text/v" + api_version
- else:
- translator_endpoint = endpoint
-
- return translator_endpoint
-
-def is_cognitive_services_scope(audience: str) -> bool:
- if "microsofttranslator" in audience:
- return True
-
- return False
-
-
-def set_authentication_policy(credential, kwargs):
- if isinstance(credential, AzureKeyCredential):
- if not kwargs.get("authentication_policy"):
- if kwargs.get("region"):
- kwargs["authentication_policy"] = TranslatorAuthenticationPolicy(credential, kwargs["region"])
- else:
- kwargs["authentication_policy"] = AzureKeyCredentialPolicy(
- name="Ocp-Apim-Subscription-Key", credential=credential
- )
- elif hasattr(credential, "get_token"):
- if not kwargs.get("authentication_policy"):
- if kwargs.get("region") and kwargs.get("resource_id"):
- scope = kwargs.pop("audience", DEFAULT_ENTRA_ID_SCOPE).rstrip("/").rstrip(DEFAULT_SCOPE) + DEFAULT_SCOPE
- kwargs["authentication_policy"] = TranslatorEntraIdAuthenticationPolicy(
- credential,
- kwargs["resource_id"],
- kwargs["region"],
- scope,
- )
- else:
- if kwargs.get("resource_id") or kwargs.get("region"):
- raise ValueError(
- """Both 'resource_id' and 'region' must be provided with a TokenCredential for
- regional resource authentication."""
- )
- scope: str = kwargs.pop("audience", DEFAULT_ENTRA_ID_SCOPE)
- if not is_cognitive_services_scope(scope):
- scope = scope.rstrip("/").rstrip(DEFAULT_SCOPE) + DEFAULT_SCOPE
-
- kwargs["authentication_policy"] = BearerTokenCredentialPolicy(
- credential, scope
- )
-
-
-class TextTranslationClient(ServiceClientGenerated):
- """Text translation is a cloud-based REST API feature of the Translator service that uses neural
- machine translation technology to enable quick and accurate source-to-target text translation
- in real time across all supported languages.
-
- The following methods are supported by the Text Translation feature:
-
- Languages. Returns a list of languages supported by Translate, Transliterate, and Dictionary
- Lookup operations.
-
- Translate. Renders single source-language text to multiple target-language texts with a single
- request.
-
- Transliterate. Converts characters or letters of a source language to the corresponding
- characters or letters of a target language.
-
- Detect. Returns the source code language code and a boolean variable denoting whether the
- detected language is supported for text translation and transliteration.
-
- Dictionary lookup. Returns equivalent words for the source term in the target language.
-
- Dictionary example Returns grammatical structure and context examples for the source term and
- target term pair.
-
- Combinations of endpoint and credential values:
- str + AzureKeyCredential - used custom domain translator endpoint
- str + AzureKeyCredential + Region - used for global translator endpoint
- str + TokenCredential - used for regional endpoint with token authentication
- str + None - used with text translation on-prem container
- None + AzureKeyCredential - used for global translator endpoint with global Translator resource
- None + TokenCredential - general translator endpoint with token authentication
- None + TokenCredential + Region - general translator endpoint with regional Translator resource
-
- :keyword str endpoint: Supported Text Translation endpoints (protocol and hostname, for example:
- https://api.cognitive.microsofttranslator.com). If not provided, global translator endpoint will be used.
- :keyword credential: Credential used to authenticate with the Translator service
- :paramtype credential: Union[AzureKeyCredential, TokenCredential]
- :keyword str region: Used for National Clouds.
- :keyword str resource_id: Used with both a TokenCredential combined with a region.
- :keyword str audience: Scopes of the credentials.
- :keyword str api_version: Default value is "3.0". Note that overriding this default value may
- result in unsupported behavior.
- """
-
- @overload
- def __init__(
- self,
- *,
- credential: TokenCredential,
- region: Optional[str] = None,
- endpoint: Optional[str] = None,
- resource_id: Optional[str] = None,
- audience: Optional[str] = None,
- api_version: str = "3.0",
- **kwargs
- ): ...
-
- @overload
- def __init__(
- self,
- *,
- credential: AzureKeyCredential,
- region: Optional[str] = None,
- endpoint: Optional[str] = None,
- api_version: str = "3.0",
- **kwargs
- ): ...
-
- @overload
- def __init__(self, *, endpoint: str, api_version: str = "3.0", **kwargs): ...
-
- def __init__(self, **kwargs):
- api_version = kwargs.get("api_version", "3.0")
- set_authentication_policy(kwargs.get("credential"), kwargs)
- translation_endpoint = get_translation_endpoint(
- kwargs.pop("endpoint", "https://api.cognitive.microsofttranslator.com"), api_version
- )
- super().__init__(endpoint=translation_endpoint, api_version=api_version, **kwargs)
-
-
-__all__ = ["TextTranslationClient"]
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_serialization.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_serialization.py
index 2f781d740827..ce17d1798ce7 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_serialization.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_serialization.py
@@ -1,3 +1,4 @@
+# pylint: disable=too-many-lines
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
@@ -24,7 +25,6 @@
#
# --------------------------------------------------------------------------
-# pylint: skip-file
# pyright: reportUnnecessaryTypeIgnoreComment=false
from base64 import b64decode, b64encode
@@ -52,7 +52,6 @@
MutableMapping,
Type,
List,
- Mapping,
)
try:
@@ -91,6 +90,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type:
:param data: Input, could be bytes or stream (will be decoded with UTF8) or text
:type data: str or bytes or IO
:param str content_type: The content type.
+ :return: The deserialized data.
+ :rtype: object
"""
if hasattr(data, "read"):
# Assume a stream
@@ -112,7 +113,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type:
try:
return json.loads(data_as_str)
except ValueError as err:
- raise DeserializationError("JSON is invalid: {}".format(err), err)
+ raise DeserializationError("JSON is invalid: {}".format(err), err) from err
elif "xml" in (content_type or []):
try:
@@ -144,6 +145,8 @@ def _json_attemp(data):
# context otherwise.
_LOGGER.critical("Wasn't XML not JSON, failing")
raise DeserializationError("XML is invalid") from err
+ elif content_type.startswith("text/"):
+ return data_as_str
raise DeserializationError("Cannot deserialize content-type: {}".format(content_type))
@classmethod
@@ -153,6 +156,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]],
Use bytes and headers to NOT use any requests/aiohttp or whatever
specific implementation.
Headers will tested for "content-type"
+
+ :param bytes body_bytes: The body of the response.
+ :param dict headers: The headers of the response.
+ :returns: The deserialized data.
+ :rtype: object
"""
# Try to use content-type from headers if available
content_type = None
@@ -182,15 +190,30 @@ class UTC(datetime.tzinfo):
"""Time Zone info for handling UTC"""
def utcoffset(self, dt):
- """UTF offset for UTC is 0."""
+ """UTF offset for UTC is 0.
+
+ :param datetime.datetime dt: The datetime
+ :returns: The offset
+ :rtype: datetime.timedelta
+ """
return datetime.timedelta(0)
def tzname(self, dt):
- """Timestamp representation."""
+ """Timestamp representation.
+
+ :param datetime.datetime dt: The datetime
+ :returns: The timestamp representation
+ :rtype: str
+ """
return "Z"
def dst(self, dt):
- """No daylight saving for UTC."""
+ """No daylight saving for UTC.
+
+ :param datetime.datetime dt: The datetime
+ :returns: The daylight saving time
+ :rtype: datetime.timedelta
+ """
return datetime.timedelta(hours=1)
@@ -204,7 +227,7 @@ class _FixedOffset(datetime.tzinfo): # type: ignore
:param datetime.timedelta offset: offset in timedelta format
"""
- def __init__(self, offset):
+ def __init__(self, offset) -> None:
self.__offset = offset
def utcoffset(self, dt):
@@ -233,24 +256,26 @@ def __getinitargs__(self):
_FLATTEN = re.compile(r"(? None:
self.additional_properties: Optional[Dict[str, Any]] = {}
- for k in kwargs:
+ for k in kwargs: # pylint: disable=consider-using-dict-items
if k not in self._attribute_map:
_LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__)
elif k in self._validation and self._validation[k].get("readonly", False):
@@ -298,13 +330,23 @@ def __init__(self, **kwargs: Any) -> None:
setattr(self, k, kwargs[k])
def __eq__(self, other: Any) -> bool:
- """Compare objects by comparing all attributes."""
+ """Compare objects by comparing all attributes.
+
+ :param object other: The object to compare
+ :returns: True if objects are equal
+ :rtype: bool
+ """
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
return False
def __ne__(self, other: Any) -> bool:
- """Compare objects by comparing all attributes."""
+ """Compare objects by comparing all attributes.
+
+ :param object other: The object to compare
+ :returns: True if objects are not equal
+ :rtype: bool
+ """
return not self.__eq__(other)
def __str__(self) -> str:
@@ -324,7 +366,11 @@ def is_xml_model(cls) -> bool:
@classmethod
def _create_xml_node(cls):
- """Create XML node."""
+ """Create XML node.
+
+ :returns: The XML node
+ :rtype: xml.etree.ElementTree.Element
+ """
try:
xml_map = cls._xml_map # type: ignore
except AttributeError:
@@ -344,7 +390,9 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON:
:rtype: dict
"""
serializer = Serializer(self._infer_class_models())
- return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore
+ return serializer._serialize( # type: ignore # pylint: disable=protected-access
+ self, keep_readonly=keep_readonly, **kwargs
+ )
def as_dict(
self,
@@ -378,12 +426,15 @@ def my_key_transformer(key, attr_desc, value):
If you want XML serialization, you can pass the kwargs is_xml=True.
+ :param bool keep_readonly: If you want to serialize the readonly attributes
:param function key_transformer: A key transformer function.
:returns: A dict JSON compatible object
:rtype: dict
"""
serializer = Serializer(self._infer_class_models())
- return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore
+ return serializer._serialize( # type: ignore # pylint: disable=protected-access
+ self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs
+ )
@classmethod
def _infer_class_models(cls):
@@ -393,7 +444,7 @@ def _infer_class_models(cls):
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
if cls.__name__ not in client_models:
raise ValueError("Not Autorest generated code")
- except Exception:
+ except Exception: # pylint: disable=broad-exception-caught
# Assume it's not Autorest generated (tests?). Add ourselves as dependencies.
client_models = {cls.__name__: cls}
return client_models
@@ -406,6 +457,7 @@ def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = N
:param str content_type: JSON by default, set application/xml if XML.
:returns: An instance of this model
:raises: DeserializationError if something went wrong
+ :rtype: ModelType
"""
deserializer = Deserializer(cls._infer_class_models())
return deserializer(cls.__name__, data, content_type=content_type) # type: ignore
@@ -424,9 +476,11 @@ def from_dict(
and last_rest_key_case_insensitive_extractor)
:param dict data: A dict using RestAPI structure
+ :param function key_extractors: A key extractor function.
:param str content_type: JSON by default, set application/xml if XML.
:returns: An instance of this model
:raises: DeserializationError if something went wrong
+ :rtype: ModelType
"""
deserializer = Deserializer(cls._infer_class_models())
deserializer.key_extractors = ( # type: ignore
@@ -446,21 +500,25 @@ def _flatten_subtype(cls, key, objects):
return {}
result = dict(cls._subtype_map[key])
for valuetype in cls._subtype_map[key].values():
- result.update(objects[valuetype]._flatten_subtype(key, objects))
+ result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access
return result
@classmethod
def _classify(cls, response, objects):
"""Check the class _subtype_map for any child classes.
We want to ignore any inherited _subtype_maps.
- Remove the polymorphic key from the initial data.
+
+ :param dict response: The initial data
+ :param dict objects: The class objects
+ :returns: The class to be used
+ :rtype: class
"""
for subtype_key in cls.__dict__.get("_subtype_map", {}).keys():
subtype_value = None
if not isinstance(response, ET.Element):
rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1]
- subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None)
+ subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None)
else:
subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response)
if subtype_value:
@@ -499,11 +557,13 @@ def _decode_attribute_map_key(key):
inside the received data.
:param str key: A key string from the generated code
+ :returns: The decoded key
+ :rtype: str
"""
return key.replace("\\.", ".")
-class Serializer(object):
+class Serializer(object): # pylint: disable=too-many-public-methods
"""Request object model serializer."""
basic_types = {str: "str", int: "int", bool: "bool", float: "float"}
@@ -538,7 +598,7 @@ class Serializer(object):
"multiple": lambda x, y: x % y != 0,
}
- def __init__(self, classes: Optional[Mapping[str, type]] = None):
+ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None:
self.serialize_type = {
"iso-8601": Serializer.serialize_iso,
"rfc-1123": Serializer.serialize_rfc,
@@ -558,13 +618,16 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None):
self.key_transformer = full_restapi_key_transformer
self.client_side_validation = True
- def _serialize(self, target_obj, data_type=None, **kwargs):
+ def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals
+ self, target_obj, data_type=None, **kwargs
+ ):
"""Serialize data into a string according to type.
- :param target_obj: The data to be serialized.
+ :param object target_obj: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str, dict
:raises: SerializationError if serialization fails.
+ :returns: The serialized data.
"""
key_transformer = kwargs.get("key_transformer", self.key_transformer)
keep_readonly = kwargs.get("keep_readonly", False)
@@ -590,12 +653,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs):
serialized = {}
if is_xml_model_serialization:
- serialized = target_obj._create_xml_node()
+ serialized = target_obj._create_xml_node() # pylint: disable=protected-access
try:
- attributes = target_obj._attribute_map
+ attributes = target_obj._attribute_map # pylint: disable=protected-access
for attr, attr_desc in attributes.items():
attr_name = attr
- if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False):
+ if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access
+ attr_name, {}
+ ).get("readonly", False):
continue
if attr_name == "additional_properties" and attr_desc["key"] == "":
@@ -631,7 +696,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs):
if isinstance(new_attr, list):
serialized.extend(new_attr) # type: ignore
elif isinstance(new_attr, ET.Element):
- # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces.
+ # If the down XML has no XML/Name,
+ # we MUST replace the tag with the local tag. But keeping the namespaces.
if "name" not in getattr(orig_attr, "_xml_map", {}):
splitted_tag = new_attr.tag.split("}")
if len(splitted_tag) == 2: # Namespace
@@ -662,17 +728,17 @@ def _serialize(self, target_obj, data_type=None, **kwargs):
except (AttributeError, KeyError, TypeError) as err:
msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj))
raise SerializationError(msg) from err
- else:
- return serialized
+ return serialized
def body(self, data, data_type, **kwargs):
"""Serialize data intended for a request body.
- :param data: The data to be serialized.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: dict
:raises: SerializationError if serialization fails.
:raises: ValueError if data is None
+ :returns: The serialized request body
"""
# Just in case this is a dict
@@ -701,7 +767,7 @@ def body(self, data, data_type, **kwargs):
attribute_key_case_insensitive_extractor,
last_rest_key_case_insensitive_extractor,
]
- data = deserializer._deserialize(data_type, data)
+ data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access
except DeserializationError as err:
raise SerializationError("Unable to build a model: " + str(err)) from err
@@ -710,9 +776,11 @@ def body(self, data, data_type, **kwargs):
def url(self, name, data, data_type, **kwargs):
"""Serialize data intended for a URL path.
- :param data: The data to be serialized.
+ :param str name: The name of the URL path parameter.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
+ :returns: The serialized URL path
:raises: TypeError if serialization fails.
:raises: ValueError if data is None
"""
@@ -726,21 +794,20 @@ def url(self, name, data, data_type, **kwargs):
output = output.replace("{", quote("{")).replace("}", quote("}"))
else:
output = quote(str(output), safe="")
- except SerializationError:
- raise TypeError("{} must be type {}.".format(name, data_type))
- else:
- return output
+ except SerializationError as exc:
+ raise TypeError("{} must be type {}.".format(name, data_type)) from exc
+ return output
def query(self, name, data, data_type, **kwargs):
"""Serialize data intended for a URL query.
- :param data: The data to be serialized.
+ :param str name: The name of the query parameter.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
- :keyword bool skip_quote: Whether to skip quote the serialized result.
- Defaults to False.
:rtype: str, list
:raises: TypeError if serialization fails.
:raises: ValueError if data is None
+ :returns: The serialized query parameter
"""
try:
# Treat the list aside, since we don't want to encode the div separator
@@ -757,19 +824,20 @@ def query(self, name, data, data_type, **kwargs):
output = str(output)
else:
output = quote(str(output), safe="")
- except SerializationError:
- raise TypeError("{} must be type {}.".format(name, data_type))
- else:
- return str(output)
+ except SerializationError as exc:
+ raise TypeError("{} must be type {}.".format(name, data_type)) from exc
+ return str(output)
def header(self, name, data, data_type, **kwargs):
"""Serialize data intended for a request header.
- :param data: The data to be serialized.
+ :param str name: The name of the header.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
:raises: TypeError if serialization fails.
:raises: ValueError if data is None
+ :returns: The serialized header
"""
try:
if data_type in ["[str]"]:
@@ -778,21 +846,20 @@ def header(self, name, data, data_type, **kwargs):
output = self.serialize_data(data, data_type, **kwargs)
if data_type == "bool":
output = json.dumps(output)
- except SerializationError:
- raise TypeError("{} must be type {}.".format(name, data_type))
- else:
- return str(output)
+ except SerializationError as exc:
+ raise TypeError("{} must be type {}.".format(name, data_type)) from exc
+ return str(output)
def serialize_data(self, data, data_type, **kwargs):
"""Serialize generic data according to supplied data type.
- :param data: The data to be serialized.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
- :param bool required: Whether it's essential that the data not be
- empty or None
:raises: AttributeError if required data is None.
:raises: ValueError if data is None
:raises: SerializationError if serialization fails.
+ :returns: The serialized data.
+ :rtype: str, int, float, bool, dict, list
"""
if data is None:
raise ValueError("No value for given attribute")
@@ -803,7 +870,7 @@ def serialize_data(self, data, data_type, **kwargs):
if data_type in self.basic_types.values():
return self.serialize_basic(data, data_type, **kwargs)
- elif data_type in self.serialize_type:
+ if data_type in self.serialize_type:
return self.serialize_type[data_type](data, **kwargs)
# If dependencies is empty, try with current data class
@@ -819,11 +886,10 @@ def serialize_data(self, data, data_type, **kwargs):
except (ValueError, TypeError) as err:
msg = "Unable to serialize value: {!r} as type: {!r}."
raise SerializationError(msg.format(data, data_type)) from err
- else:
- return self._serialize(data, **kwargs)
+ return self._serialize(data, **kwargs)
@classmethod
- def _get_custom_serializers(cls, data_type, **kwargs):
+ def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements
custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type)
if custom_serializer:
return custom_serializer
@@ -839,23 +905,26 @@ def serialize_basic(cls, data, data_type, **kwargs):
- basic_types_serializers dict[str, callable] : If set, use the callable as serializer
- is_xml bool : If set, use xml_basic_types_serializers
- :param data: Object to be serialized.
+ :param obj data: Object to be serialized.
:param str data_type: Type of object in the iterable.
+ :rtype: str, int, float, bool
+ :return: serialized object
"""
custom_serializer = cls._get_custom_serializers(data_type, **kwargs)
if custom_serializer:
return custom_serializer(data)
if data_type == "str":
return cls.serialize_unicode(data)
- return eval(data_type)(data) # nosec
+ return eval(data_type)(data) # nosec # pylint: disable=eval-used
@classmethod
def serialize_unicode(cls, data):
"""Special handling for serializing unicode strings in Py2.
Encode to UTF-8 if unicode, otherwise handle as a str.
- :param data: Object to be serialized.
+ :param str data: Object to be serialized.
:rtype: str
+ :return: serialized object
"""
try: # If I received an enum, return its value
return data.value
@@ -869,8 +938,7 @@ def serialize_unicode(cls, data):
return data
except NameError:
return str(data)
- else:
- return str(data)
+ return str(data)
def serialize_iter(self, data, iter_type, div=None, **kwargs):
"""Serialize iterable.
@@ -880,15 +948,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs):
serialization_ctxt['type'] should be same as data_type.
- is_xml bool : If set, serialize as XML
- :param list attr: Object to be serialized.
+ :param list data: Object to be serialized.
:param str iter_type: Type of object in the iterable.
- :param bool required: Whether the objects in the iterable must
- not be None or empty.
:param str div: If set, this str will be used to combine the elements
in the iterable into a combined string. Default is 'None'.
- :keyword bool do_quote: Whether to quote the serialized result of each iterable element.
Defaults to False.
:rtype: list, str
+ :return: serialized iterable
"""
if isinstance(data, str):
raise SerializationError("Refuse str type as a valid iter type.")
@@ -943,9 +1009,8 @@ def serialize_dict(self, attr, dict_type, **kwargs):
:param dict attr: Object to be serialized.
:param str dict_type: Type of object in the dictionary.
- :param bool required: Whether the objects in the dictionary must
- not be None or empty.
:rtype: dict
+ :return: serialized dictionary
"""
serialization_ctxt = kwargs.get("serialization_ctxt", {})
serialized = {}
@@ -969,7 +1034,7 @@ def serialize_dict(self, attr, dict_type, **kwargs):
return serialized
- def serialize_object(self, attr, **kwargs):
+ def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements
"""Serialize a generic object.
This will be handled as a dictionary. If object passed in is not
a basic type (str, int, float, dict, list) it will simply be
@@ -977,6 +1042,7 @@ def serialize_object(self, attr, **kwargs):
:param dict attr: Object to be serialized.
:rtype: dict or str
+ :return: serialized object
"""
if attr is None:
return None
@@ -1001,7 +1067,7 @@ def serialize_object(self, attr, **kwargs):
return self.serialize_decimal(attr)
# If it's a model or I know this dependency, serialize as a Model
- elif obj_type in self.dependencies.values() or isinstance(attr, Model):
+ if obj_type in self.dependencies.values() or isinstance(attr, Model):
return self._serialize(attr)
if obj_type == dict:
@@ -1032,56 +1098,61 @@ def serialize_enum(attr, enum_obj=None):
try:
enum_obj(result) # type: ignore
return result
- except ValueError:
+ except ValueError as exc:
for enum_value in enum_obj: # type: ignore
if enum_value.value.lower() == str(attr).lower():
return enum_value.value
error = "{!r} is not valid value for enum {!r}"
- raise SerializationError(error.format(attr, enum_obj))
+ raise SerializationError(error.format(attr, enum_obj)) from exc
@staticmethod
- def serialize_bytearray(attr, **kwargs):
+ def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize bytearray into base-64 string.
- :param attr: Object to be serialized.
+ :param str attr: Object to be serialized.
:rtype: str
+ :return: serialized base64
"""
return b64encode(attr).decode()
@staticmethod
- def serialize_base64(attr, **kwargs):
+ def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize str into base-64 string.
- :param attr: Object to be serialized.
+ :param str attr: Object to be serialized.
:rtype: str
+ :return: serialized base64
"""
encoded = b64encode(attr).decode("ascii")
return encoded.strip("=").replace("+", "-").replace("/", "_")
@staticmethod
- def serialize_decimal(attr, **kwargs):
+ def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Decimal object to float.
- :param attr: Object to be serialized.
+ :param decimal attr: Object to be serialized.
:rtype: float
+ :return: serialized decimal
"""
return float(attr)
@staticmethod
- def serialize_long(attr, **kwargs):
+ def serialize_long(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize long (Py2) or int (Py3).
- :param attr: Object to be serialized.
+ :param int attr: Object to be serialized.
:rtype: int/long
+ :return: serialized long
"""
return _long_type(attr)
@staticmethod
- def serialize_date(attr, **kwargs):
+ def serialize_date(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Date object into ISO-8601 formatted string.
:param Date attr: Object to be serialized.
:rtype: str
+ :return: serialized date
"""
if isinstance(attr, str):
attr = isodate.parse_date(attr)
@@ -1089,11 +1160,12 @@ def serialize_date(attr, **kwargs):
return t
@staticmethod
- def serialize_time(attr, **kwargs):
+ def serialize_time(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Time object into ISO-8601 formatted string.
:param datetime.time attr: Object to be serialized.
:rtype: str
+ :return: serialized time
"""
if isinstance(attr, str):
attr = isodate.parse_time(attr)
@@ -1103,30 +1175,32 @@ def serialize_time(attr, **kwargs):
return t
@staticmethod
- def serialize_duration(attr, **kwargs):
+ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize TimeDelta object into ISO-8601 formatted string.
:param TimeDelta attr: Object to be serialized.
:rtype: str
+ :return: serialized duration
"""
if isinstance(attr, str):
attr = isodate.parse_duration(attr)
return isodate.duration_isoformat(attr)
@staticmethod
- def serialize_rfc(attr, **kwargs):
+ def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Datetime object into RFC-1123 formatted string.
:param Datetime attr: Object to be serialized.
:rtype: str
:raises: TypeError if format invalid.
+ :return: serialized rfc
"""
try:
if not attr.tzinfo:
_LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
utc = attr.utctimetuple()
- except AttributeError:
- raise TypeError("RFC1123 object must be valid Datetime object.")
+ except AttributeError as exc:
+ raise TypeError("RFC1123 object must be valid Datetime object.") from exc
return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format(
Serializer.days[utc.tm_wday],
@@ -1139,12 +1213,13 @@ def serialize_rfc(attr, **kwargs):
)
@staticmethod
- def serialize_iso(attr, **kwargs):
+ def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Datetime object into ISO-8601 formatted string.
:param Datetime attr: Object to be serialized.
:rtype: str
:raises: SerializationError if format invalid.
+ :return: serialized iso
"""
if isinstance(attr, str):
attr = isodate.parse_datetime(attr)
@@ -1170,13 +1245,14 @@ def serialize_iso(attr, **kwargs):
raise TypeError(msg) from err
@staticmethod
- def serialize_unix(attr, **kwargs):
+ def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Datetime object into IntTime format.
This is represented as seconds.
:param Datetime attr: Object to be serialized.
:rtype: int
:raises: SerializationError if format invalid
+ :return: serialied unix
"""
if isinstance(attr, int):
return attr
@@ -1184,11 +1260,11 @@ def serialize_unix(attr, **kwargs):
if not attr.tzinfo:
_LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
return int(calendar.timegm(attr.utctimetuple()))
- except AttributeError:
- raise TypeError("Unix time object must be valid Datetime object.")
+ except AttributeError as exc:
+ raise TypeError("Unix time object must be valid Datetime object.") from exc
-def rest_key_extractor(attr, attr_desc, data):
+def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument
key = attr_desc["key"]
working_data = data
@@ -1209,7 +1285,9 @@ def rest_key_extractor(attr, attr_desc, data):
return working_data.get(key)
-def rest_key_case_insensitive_extractor(attr, attr_desc, data):
+def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements
+ attr, attr_desc, data
+):
key = attr_desc["key"]
working_data = data
@@ -1230,17 +1308,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data):
return attribute_key_case_insensitive_extractor(key, None, working_data)
-def last_rest_key_extractor(attr, attr_desc, data):
- """Extract the attribute in "data" based on the last part of the JSON path key."""
+def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument
+ """Extract the attribute in "data" based on the last part of the JSON path key.
+
+ :param str attr: The attribute to extract
+ :param dict attr_desc: The attribute description
+ :param dict data: The data to extract from
+ :rtype: object
+ :returns: The extracted attribute
+ """
key = attr_desc["key"]
dict_keys = _FLATTEN.split(key)
return attribute_key_extractor(dict_keys[-1], None, data)
-def last_rest_key_case_insensitive_extractor(attr, attr_desc, data):
+def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument
"""Extract the attribute in "data" based on the last part of the JSON path key.
This is the case insensitive version of "last_rest_key_extractor"
+ :param str attr: The attribute to extract
+ :param dict attr_desc: The attribute description
+ :param dict data: The data to extract from
+ :rtype: object
+ :returns: The extracted attribute
"""
key = attr_desc["key"]
dict_keys = _FLATTEN.split(key)
@@ -1277,7 +1367,7 @@ def _extract_name_from_internal_type(internal_type):
return xml_name
-def xml_key_extractor(attr, attr_desc, data):
+def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements
if isinstance(data, dict):
return None
@@ -1329,22 +1419,21 @@ def xml_key_extractor(attr, attr_desc, data):
if is_iter_type:
if is_wrapped:
return None # is_wrapped no node, we want None
- else:
- return [] # not wrapped, assume empty list
+ return [] # not wrapped, assume empty list
return None # Assume it's not there, maybe an optional node.
# If is_iter_type and not wrapped, return all found children
if is_iter_type:
if not is_wrapped:
return children
- else: # Iter and wrapped, should have found one node only (the wrap one)
- if len(children) != 1:
- raise DeserializationError(
- "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format(
- xml_name
- )
+ # Iter and wrapped, should have found one node only (the wrap one)
+ if len(children) != 1:
+ raise DeserializationError(
+ "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( # pylint: disable=line-too-long
+ xml_name
)
- return list(children[0]) # Might be empty list and that's ok.
+ )
+ return list(children[0]) # Might be empty list and that's ok.
# Here it's not a itertype, we should have found one element only or empty
if len(children) > 1:
@@ -1361,9 +1450,9 @@ class Deserializer(object):
basic_types = {str: "str", int: "int", bool: "bool", float: "float"}
- valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?")
+ valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?")
- def __init__(self, classes: Optional[Mapping[str, type]] = None):
+ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None:
self.deserialize_type = {
"iso-8601": Deserializer.deserialize_iso,
"rfc-1123": Deserializer.deserialize_rfc,
@@ -1401,11 +1490,12 @@ def __call__(self, target_obj, response_data, content_type=None):
:param str content_type: Swagger "produces" if available.
:raises: DeserializationError if deserialization fails.
:return: Deserialized object.
+ :rtype: object
"""
data = self._unpack_content(response_data, content_type)
return self._deserialize(target_obj, data)
- def _deserialize(self, target_obj, data):
+ def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements
"""Call the deserializer on a model.
Data needs to be already deserialized as JSON or XML ElementTree
@@ -1414,12 +1504,13 @@ def _deserialize(self, target_obj, data):
:param object data: Object to deserialize.
:raises: DeserializationError if deserialization fails.
:return: Deserialized object.
+ :rtype: object
"""
# This is already a model, go recursive just in case
if hasattr(data, "_attribute_map"):
constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")]
try:
- for attr, mapconfig in data._attribute_map.items():
+ for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access
if attr in constants:
continue
value = getattr(data, attr)
@@ -1438,13 +1529,13 @@ def _deserialize(self, target_obj, data):
if isinstance(response, str):
return self.deserialize_data(data, response)
- elif isinstance(response, type) and issubclass(response, Enum):
+ if isinstance(response, type) and issubclass(response, Enum):
return self.deserialize_enum(data, response)
- if data is None:
+ if data is None or data is CoreNull:
return data
try:
- attributes = response._attribute_map # type: ignore
+ attributes = response._attribute_map # type: ignore # pylint: disable=protected-access
d_attrs = {}
for attr, attr_desc in attributes.items():
# Check empty string. If it's not empty, someone has a real "additionalProperties"...
@@ -1474,9 +1565,8 @@ def _deserialize(self, target_obj, data):
except (AttributeError, TypeError, KeyError) as err:
msg = "Unable to deserialize to object: " + class_name # type: ignore
raise DeserializationError(msg) from err
- else:
- additional_properties = self._build_additional_properties(attributes, data)
- return self._instantiate_model(response, d_attrs, additional_properties)
+ additional_properties = self._build_additional_properties(attributes, data)
+ return self._instantiate_model(response, d_attrs, additional_properties)
def _build_additional_properties(self, attribute_map, data):
if not self.additional_properties_detection:
@@ -1503,6 +1593,8 @@ def _classify_target(self, target, data):
:param str target: The target object type to deserialize to.
:param str/dict data: The response data to deserialize.
+ :return: The classified target object and its class name.
+ :rtype: tuple
"""
if target is None:
return None, None
@@ -1514,7 +1606,7 @@ def _classify_target(self, target, data):
return target, target
try:
- target = target._classify(data, self.dependencies) # type: ignore
+ target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access
except AttributeError:
pass # Target is not a Model, no classify
return target, target.__class__.__name__ # type: ignore
@@ -1529,10 +1621,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None):
:param str target_obj: The target object type to deserialize to.
:param str/dict data: The response data to deserialize.
:param str content_type: Swagger "produces" if available.
+ :return: Deserialized object.
+ :rtype: object
"""
try:
return self(target_obj, data, content_type=content_type)
- except:
+ except: # pylint: disable=bare-except
_LOGGER.debug(
"Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True
)
@@ -1550,10 +1644,12 @@ def _unpack_content(raw_data, content_type=None):
If raw_data is something else, bypass all logic and return it directly.
- :param raw_data: Data to be processed.
- :param content_type: How to parse if raw_data is a string/bytes.
+ :param obj raw_data: Data to be processed.
+ :param str content_type: How to parse if raw_data is a string/bytes.
:raises JSONDecodeError: If JSON is requested and parsing is impossible.
:raises UnicodeDecodeError: If bytes is not UTF8
+ :rtype: object
+ :return: Unpacked content.
"""
# Assume this is enough to detect a Pipeline Response without importing it
context = getattr(raw_data, "context", {})
@@ -1577,14 +1673,21 @@ def _unpack_content(raw_data, content_type=None):
def _instantiate_model(self, response, attrs, additional_properties=None):
"""Instantiate a response model passing in deserialized args.
- :param response: The response model class.
- :param d_attrs: The deserialized response attributes.
+ :param Response response: The response model class.
+ :param dict attrs: The deserialized response attributes.
+ :param dict additional_properties: Additional properties to be set.
+ :rtype: Response
+ :return: The instantiated response model.
"""
if callable(response):
subtype = getattr(response, "_subtype_map", {})
try:
- readonly = [k for k, v in response._validation.items() if v.get("readonly")]
- const = [k for k, v in response._validation.items() if v.get("constant")]
+ readonly = [
+ k for k, v in response._validation.items() if v.get("readonly") # pylint: disable=protected-access
+ ]
+ const = [
+ k for k, v in response._validation.items() if v.get("constant") # pylint: disable=protected-access
+ ]
kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const}
response_obj = response(**kwargs)
for attr in readonly:
@@ -1594,7 +1697,7 @@ def _instantiate_model(self, response, attrs, additional_properties=None):
return response_obj
except TypeError as err:
msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore
- raise DeserializationError(msg + str(err))
+ raise DeserializationError(msg + str(err)) from err
else:
try:
for attr, value in attrs.items():
@@ -1603,15 +1706,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None):
except Exception as exp:
msg = "Unable to populate response model. "
msg += "Type: {}, Error: {}".format(type(response), exp)
- raise DeserializationError(msg)
+ raise DeserializationError(msg) from exp
- def deserialize_data(self, data, data_type):
+ def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements
"""Process data for deserialization according to data type.
:param str data: The response string to be deserialized.
:param str data_type: The type to deserialize to.
:raises: DeserializationError if deserialization fails.
:return: Deserialized object.
+ :rtype: object
"""
if data is None:
return data
@@ -1625,7 +1729,11 @@ def deserialize_data(self, data, data_type):
if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())):
return data
- is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"]
+ is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment
+ "object",
+ "[]",
+ r"{}",
+ ]
if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text:
return None
data_val = self.deserialize_type[data_type](data)
@@ -1645,14 +1753,14 @@ def deserialize_data(self, data, data_type):
msg = "Unable to deserialize response data."
msg += " Data: {}, {}".format(data, data_type)
raise DeserializationError(msg) from err
- else:
- return self._deserialize(obj_type, data)
+ return self._deserialize(obj_type, data)
def deserialize_iter(self, attr, iter_type):
"""Deserialize an iterable.
:param list attr: Iterable to be deserialized.
:param str iter_type: The type of object in the iterable.
+ :return: Deserialized iterable.
:rtype: list
"""
if attr is None:
@@ -1669,6 +1777,7 @@ def deserialize_dict(self, attr, dict_type):
:param dict/list attr: Dictionary to be deserialized. Also accepts
a list of key, value pairs.
:param str dict_type: The object type of the items in the dictionary.
+ :return: Deserialized dictionary.
:rtype: dict
"""
if isinstance(attr, list):
@@ -1679,11 +1788,12 @@ def deserialize_dict(self, attr, dict_type):
attr = {el.tag: el.text for el in attr}
return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()}
- def deserialize_object(self, attr, **kwargs):
+ def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements
"""Deserialize a generic object.
This will be handled as a dictionary.
:param dict attr: Dictionary to be deserialized.
+ :return: Deserialized object.
:rtype: dict
:raises: TypeError if non-builtin datatype encountered.
"""
@@ -1718,11 +1828,10 @@ def deserialize_object(self, attr, **kwargs):
pass
return deserialized
- else:
- error = "Cannot deserialize generic object with type: "
- raise TypeError(error + str(obj_type))
+ error = "Cannot deserialize generic object with type: "
+ raise TypeError(error + str(obj_type))
- def deserialize_basic(self, attr, data_type):
+ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements
"""Deserialize basic builtin data type from string.
Will attempt to convert to str, int, float and bool.
This function will also accept '1', '0', 'true' and 'false' as
@@ -1730,6 +1839,7 @@ def deserialize_basic(self, attr, data_type):
:param str attr: response string to be deserialized.
:param str data_type: deserialization data type.
+ :return: Deserialized basic type.
:rtype: str, int, float or bool
:raises: TypeError if string format is not valid.
"""
@@ -1741,24 +1851,23 @@ def deserialize_basic(self, attr, data_type):
if data_type == "str":
# None or '', node is empty string.
return ""
- else:
- # None or '', node with a strong type is None.
- # Don't try to model "empty bool" or "empty int"
- return None
+ # None or '', node with a strong type is None.
+ # Don't try to model "empty bool" or "empty int"
+ return None
if data_type == "bool":
if attr in [True, False, 1, 0]:
return bool(attr)
- elif isinstance(attr, str):
+ if isinstance(attr, str):
if attr.lower() in ["true", "1"]:
return True
- elif attr.lower() in ["false", "0"]:
+ if attr.lower() in ["false", "0"]:
return False
raise TypeError("Invalid boolean value: {}".format(attr))
if data_type == "str":
return self.deserialize_unicode(attr)
- return eval(data_type)(attr) # nosec
+ return eval(data_type)(attr) # nosec # pylint: disable=eval-used
@staticmethod
def deserialize_unicode(data):
@@ -1766,6 +1875,7 @@ def deserialize_unicode(data):
as a string.
:param str data: response string to be deserialized.
+ :return: Deserialized string.
:rtype: str or unicode
"""
# We might be here because we have an enum modeled as string,
@@ -1779,8 +1889,7 @@ def deserialize_unicode(data):
return data
except NameError:
return str(data)
- else:
- return str(data)
+ return str(data)
@staticmethod
def deserialize_enum(data, enum_obj):
@@ -1792,6 +1901,7 @@ def deserialize_enum(data, enum_obj):
:param str data: Response string to be deserialized. If this value is
None or invalid it will be returned as-is.
:param Enum enum_obj: Enum object to deserialize to.
+ :return: Deserialized enum object.
:rtype: Enum
"""
if isinstance(data, enum_obj) or data is None:
@@ -1802,9 +1912,9 @@ def deserialize_enum(data, enum_obj):
# Workaround. We might consider remove it in the future.
try:
return list(enum_obj.__members__.values())[data]
- except IndexError:
+ except IndexError as exc:
error = "{!r} is not a valid index for enum {!r}"
- raise DeserializationError(error.format(data, enum_obj))
+ raise DeserializationError(error.format(data, enum_obj)) from exc
try:
return enum_obj(str(data))
except ValueError:
@@ -1820,6 +1930,7 @@ def deserialize_bytearray(attr):
"""Deserialize string into bytearray.
:param str attr: response string to be deserialized.
+ :return: Deserialized bytearray
:rtype: bytearray
:raises: TypeError if string format invalid.
"""
@@ -1832,6 +1943,7 @@ def deserialize_base64(attr):
"""Deserialize base64 encoded string into string.
:param str attr: response string to be deserialized.
+ :return: Deserialized base64 string
:rtype: bytearray
:raises: TypeError if string format invalid.
"""
@@ -1847,8 +1959,9 @@ def deserialize_decimal(attr):
"""Deserialize string into Decimal object.
:param str attr: response string to be deserialized.
- :rtype: Decimal
+ :return: Deserialized decimal
:raises: DeserializationError if string format invalid.
+ :rtype: decimal
"""
if isinstance(attr, ET.Element):
attr = attr.text
@@ -1863,6 +1976,7 @@ def deserialize_long(attr):
"""Deserialize string into long (Py2) or int (Py3).
:param str attr: response string to be deserialized.
+ :return: Deserialized int
:rtype: long or int
:raises: ValueError if string format invalid.
"""
@@ -1875,6 +1989,7 @@ def deserialize_duration(attr):
"""Deserialize ISO-8601 formatted string into TimeDelta object.
:param str attr: response string to be deserialized.
+ :return: Deserialized duration
:rtype: TimeDelta
:raises: DeserializationError if string format invalid.
"""
@@ -1885,14 +2000,14 @@ def deserialize_duration(attr):
except (ValueError, OverflowError, AttributeError) as err:
msg = "Cannot deserialize duration object."
raise DeserializationError(msg) from err
- else:
- return duration
+ return duration
@staticmethod
def deserialize_date(attr):
"""Deserialize ISO-8601 formatted string into Date object.
:param str attr: response string to be deserialized.
+ :return: Deserialized date
:rtype: Date
:raises: DeserializationError if string format invalid.
"""
@@ -1908,6 +2023,7 @@ def deserialize_time(attr):
"""Deserialize ISO-8601 formatted string into time object.
:param str attr: response string to be deserialized.
+ :return: Deserialized time
:rtype: datetime.time
:raises: DeserializationError if string format invalid.
"""
@@ -1922,6 +2038,7 @@ def deserialize_rfc(attr):
"""Deserialize RFC-1123 formatted string into Datetime object.
:param str attr: response string to be deserialized.
+ :return: Deserialized RFC datetime
:rtype: Datetime
:raises: DeserializationError if string format invalid.
"""
@@ -1937,14 +2054,14 @@ def deserialize_rfc(attr):
except ValueError as err:
msg = "Cannot deserialize to rfc datetime object."
raise DeserializationError(msg) from err
- else:
- return date_obj
+ return date_obj
@staticmethod
def deserialize_iso(attr):
"""Deserialize ISO-8601 formatted string into Datetime object.
:param str attr: response string to be deserialized.
+ :return: Deserialized ISO datetime
:rtype: Datetime
:raises: DeserializationError if string format invalid.
"""
@@ -1974,8 +2091,7 @@ def deserialize_iso(attr):
except (ValueError, OverflowError, AttributeError) as err:
msg = "Cannot deserialize datetime object."
raise DeserializationError(msg) from err
- else:
- return date_obj
+ return date_obj
@staticmethod
def deserialize_unix(attr):
@@ -1983,6 +2099,7 @@ def deserialize_unix(attr):
This is represented as seconds.
:param int attr: Object to be serialized.
+ :return: Deserialized datetime
:rtype: Datetime
:raises: DeserializationError if format invalid
"""
@@ -1994,5 +2111,4 @@ def deserialize_unix(attr):
except ValueError as err:
msg = "Cannot deserialize to unix datetime object."
raise DeserializationError(msg) from err
- else:
- return date_obj
+ return date_obj
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_vendor.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_vendor.py
index 6033fc36a5d1..d0ceaeb5e4ea 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_vendor.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_vendor.py
@@ -13,7 +13,6 @@
from ._configuration import TextTranslationClientConfiguration
if TYPE_CHECKING:
- # pylint: disable=unused-import,ungrouped-imports
from azure.core import PipelineClient
from ._serialization import Deserializer, Serializer
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_version.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_version.py
index 8e44259d1a18..be71c81bd282 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_version.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/_version.py
@@ -6,4 +6,4 @@
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
-VERSION = "1.0.2"
+VERSION = "1.0.0b1"
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/__init__.py
index 0d279090135b..2887e29b8c63 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/__init__.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/__init__.py
@@ -5,15 +5,25 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._patch import TextTranslationClient
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+from ._client import TextTranslationClient # type: ignore
+
+try:
+ from ._patch import __all__ as _patch_all
+ from ._patch import *
+except ImportError:
+ _patch_all = []
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"TextTranslationClient",
]
-
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_client.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_client.py
index 9b7f5d746e2f..cab5f6b52b9b 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_client.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_client.py
@@ -8,6 +8,7 @@
from copy import deepcopy
from typing import Any, Awaitable
+from typing_extensions import Self
from azure.core import AsyncPipelineClient
from azure.core.pipeline import policies
@@ -18,7 +19,7 @@
from ._operations import TextTranslationClientOperationsMixin
-class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword
+class TextTranslationClient(TextTranslationClientOperationsMixin):
"""Text translation is a cloud-based REST API feature of the Translator service that uses neural
machine translation technology to enable quick and accurate source-to-target text translation
in real time across all supported languages.
@@ -109,7 +110,7 @@ def send_request(
async def close(self) -> None:
await self._client.close()
- async def __aenter__(self) -> "TextTranslationClient":
+ async def __aenter__(self) -> Self:
await self._client.__aenter__()
return self
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_configuration.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_configuration.py
index 1f4d5c1f10f9..bc728b448194 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_configuration.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_configuration.py
@@ -13,7 +13,7 @@
from .._version import VERSION
-class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long
+class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes
"""Configuration for TextTranslationClient.
Note that all parameters used to create this instance are saved as instance
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/__init__.py
index 47ae0af6503a..dbcf8750add3 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/__init__.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/__init__.py
@@ -5,14 +5,21 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._patch import TextTranslationClientOperationsMixin
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+from ._operations import TextTranslationClientOperationsMixin # type: ignore
+
+from ._patch import __all__ as _patch_all
+from ._patch import *
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"TextTranslationClientOperationsMixin",
]
-
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_operations.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_operations.py
index 5b8d0cb5d9b5..9e044406bfa5 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_operations.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_operations.py
@@ -1,4 +1,4 @@
-# pylint: disable=too-many-lines,too-many-statements
+# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
@@ -6,11 +6,10 @@
# 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
import sys
-from typing import Any, Callable, Dict, IO, List, Optional, Type, TypeVar, Union, overload
+from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload
from azure.core import MatchConditions
from azure.core.exceptions import (
@@ -20,6 +19,8 @@
ResourceModifiedError,
ResourceNotFoundError,
ResourceNotModifiedError,
+ StreamClosedError,
+ StreamConsumedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
@@ -42,7 +43,7 @@
if sys.version_info >= (3, 9):
from collections.abc import MutableMapping
else:
- from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports
+ from typing import MutableMapping # type: ignore
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
@@ -60,7 +61,6 @@ async def get_supported_languages(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.GetSupportedLanguagesResult:
- # pylint: disable=line-too-long
"""Gets the set of languages currently supported by other operations of the Translator.
Gets the set of languages currently supported by other operations of the Translator.
@@ -95,88 +95,8 @@ async def get_supported_languages(
MutableMapping
:rtype: ~azure.ai.translation.text.models.GetSupportedLanguagesResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "dictionary": {
- "str": {
- "dir": "str", # Directionality, which is rtl for
- right-to-left languages or ltr for left-to-right languages. Required.
- Known values are: "ltr" and "rtl".
- "name": "str", # Display name of the language in the locale
- requested via Accept-Language header. Required.
- "nativeName": "str", # Display name of the language in the
- locale native for this language. Required.
- "translations": [
- {
- "code": "str", # Language code identifying
- the target language. Required.
- "dir": "str", # Directionality, which is rtl
- for right-to-left languages or ltr for left-to-right languages.
- Required. Known values are: "ltr" and "rtl".
- "name": "str", # Display name of the
- language in the locale requested via Accept-Language header.
- Required.
- "nativeName": "str" # Display name of the
- language in the locale native for this language. Required.
- }
- ]
- }
- },
- "translation": {
- "str": {
- "dir": "str", # Directionality, which is rtl for
- right-to-left languages or ltr for left-to-right languages. Required.
- Known values are: "ltr" and "rtl".
- "name": "str", # Display name of the language in the locale
- requested via Accept-Language header. Required.
- "nativeName": "str" # Display name of the language in the
- locale native for this language. Required.
- }
- },
- "transliteration": {
- "str": {
- "name": "str", # Display name of the language in the locale
- requested via Accept-Language header. Required.
- "nativeName": "str", # Display name of the language in the
- locale native for this language. Required.
- "scripts": [
- {
- "code": "str", # Code identifying the
- script. Required.
- "dir": "str", # Directionality, which is rtl
- for right-to-left languages or ltr for left-to-right languages.
- Required. Known values are: "ltr" and "rtl".
- "name": "str", # Display name of the script
- in the locale requested via Accept-Language header. Required.
- "nativeName": "str", # Display name of the
- language in the locale native for the language. Required.
- "toScripts": [
- {
- "code": "str", # Code
- identifying the script. Required.
- "dir": "str", #
- Directionality, which is rtl for right-to-left languages
- or ltr for left-to-right languages. Required. Known
- values are: "ltr" and "rtl".
- "name": "str", # Display
- name of the script in the locale requested via
- Accept-Language header. Required.
- "nativeName": "str" #
- Display name of the language in the locale native for the
- language. Required.
- }
- ]
- }
- ]
- }
- }
- }
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -219,7 +139,10 @@ async def get_supported_languages(
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -259,7 +182,6 @@ async def translate(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
"""Translate Text.
Translate Text.
@@ -344,74 +266,6 @@ async def translate(
:return: list of TranslatedTextItem
:rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
"""
@overload
@@ -435,7 +289,6 @@ async def translate(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
"""Translate Text.
Translate Text.
@@ -520,67 +373,6 @@ async def translate(
:return: list of TranslatedTextItem
:rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
"""
@distributed_trace_async
@@ -603,7 +395,6 @@ async def translate(
allow_fallback: Optional[bool] = None,
**kwargs: Any
) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
"""Translate Text.
Translate Text.
@@ -686,69 +477,8 @@ async def translate(
:return: list of TranslatedTextItem
:rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -803,7 +533,10 @@ async def translate(
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -862,26 +595,6 @@ async def transliterate(
:return: list of TransliteratedText
:rtype: list[~azure.ai.translation.text.models.TransliteratedText]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
"""
@overload
@@ -923,19 +636,6 @@ async def transliterate(
:return: list of TransliteratedText
:rtype: list[~azure.ai.translation.text.models.TransliteratedText]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
"""
@distributed_trace_async
@@ -974,21 +674,8 @@ async def transliterate(
:return: list of TransliteratedText
:rtype: list[~azure.ai.translation.text.models.TransliteratedText]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1034,7 +721,10 @@ async def transliterate(
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -1063,7 +753,6 @@ async def find_sentence_boundaries(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
"""Find Sentence Boundaries.
Find Sentence Boundaries.
@@ -1087,34 +776,6 @@ async def find_sentence_boundaries(
:return: list of BreakSentenceItem
:rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
"""
@overload
@@ -1128,7 +789,6 @@ async def find_sentence_boundaries(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
"""Find Sentence Boundaries.
Find Sentence Boundaries.
@@ -1152,27 +812,6 @@ async def find_sentence_boundaries(
:return: list of BreakSentenceItem
:rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
"""
@distributed_trace_async
@@ -1185,7 +824,6 @@ async def find_sentence_boundaries(
script: Optional[str] = None,
**kwargs: Any
) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
"""Find Sentence Boundaries.
Find Sentence Boundaries.
@@ -1207,29 +845,8 @@ async def find_sentence_boundaries(
:return: list of BreakSentenceItem
:rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1274,7 +891,10 @@ async def find_sentence_boundaries(
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -1303,7 +923,6 @@ async def lookup_dictionary_entries(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Entries.
Lookup Dictionary Entries.
@@ -1327,84 +946,6 @@ async def lookup_dictionary_entries(
:return: list of DictionaryLookupItem
:rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "confidence": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
"""
@overload
@@ -1418,7 +959,6 @@ async def lookup_dictionary_entries(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Entries.
Lookup Dictionary Entries.
@@ -1442,77 +982,6 @@ async def lookup_dictionary_entries(
:return: list of DictionaryLookupItem
:rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "confidence": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
"""
@distributed_trace_async
@@ -1525,7 +994,6 @@ async def lookup_dictionary_entries(
client_trace_id: Optional[str] = None,
**kwargs: Any
) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Entries.
Lookup Dictionary Entries.
@@ -1547,79 +1015,8 @@ async def lookup_dictionary_entries(
:return: list of DictionaryLookupItem
:rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "confidence": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1664,7 +1061,10 @@ async def lookup_dictionary_entries(
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
@@ -1693,7 +1093,6 @@ async def lookup_dictionary_examples(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.DictionaryExampleItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Examples.
Lookup Dictionary Examples.
@@ -1717,56 +1116,6 @@ async def lookup_dictionary_examples(
:return: list of DictionaryExampleItem
:rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str", # Text to translate. Required.
- "translation": "str" # A string specifying the translated text
- previously returned by the Dictionary lookup operation. This should be the
- value from the normalizedTarget field in the translations list of the
- Dictionary lookup response. The service will return examples for the
- specific source-target word-pair. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "examples": [
- {
- "sourcePrefix": "str", # The string to concatenate
- before the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceSuffix": "str", # The string to concatenate
- after the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceTerm": "str", # A string equal to the actual
- term looked up. The string is added with sourcePrefix and
- sourceSuffix to form the complete example. Its value is separated so
- it can be marked in a user interface, e.g., by bolding it. Required.
- "targetPrefix": "str", # A string similar to
- sourcePrefix but for the target. Required.
- "targetSuffix": "str", # A string similar to
- sourceSuffix but for the target. Required.
- "targetTerm": "str" # A string similar to sourceTerm
- but for the target. Required.
- }
- ],
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. Generally, this should be identical to the value of the Text
- field at the matching list index in the body of the request. Required.
- "normalizedTarget": "str" # A string giving the normalized form of
- the target term. Generally, this should be identical to the value of the
- Translation field at the matching list index in the body of the request.
- Required.
- }
- ]
"""
@overload
@@ -1780,7 +1129,6 @@ async def lookup_dictionary_examples(
content_type: str = "application/json",
**kwargs: Any
) -> List[_models.DictionaryExampleItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Examples.
Lookup Dictionary Examples.
@@ -1804,44 +1152,6 @@ async def lookup_dictionary_examples(
:return: list of DictionaryExampleItem
:rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "examples": [
- {
- "sourcePrefix": "str", # The string to concatenate
- before the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceSuffix": "str", # The string to concatenate
- after the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceTerm": "str", # A string equal to the actual
- term looked up. The string is added with sourcePrefix and
- sourceSuffix to form the complete example. Its value is separated so
- it can be marked in a user interface, e.g., by bolding it. Required.
- "targetPrefix": "str", # A string similar to
- sourcePrefix but for the target. Required.
- "targetSuffix": "str", # A string similar to
- sourceSuffix but for the target. Required.
- "targetTerm": "str" # A string similar to sourceTerm
- but for the target. Required.
- }
- ],
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. Generally, this should be identical to the value of the Text
- field at the matching list index in the body of the request. Required.
- "normalizedTarget": "str" # A string giving the normalized form of
- the target term. Generally, this should be identical to the value of the
- Translation field at the matching list index in the body of the request.
- Required.
- }
- ]
"""
@distributed_trace_async
@@ -1854,7 +1164,6 @@ async def lookup_dictionary_examples(
client_trace_id: Optional[str] = None,
**kwargs: Any
) -> List[_models.DictionaryExampleItem]:
- # pylint: disable=line-too-long
"""Lookup Dictionary Examples.
Lookup Dictionary Examples.
@@ -1876,46 +1185,8 @@ async def lookup_dictionary_examples(
:return: list of DictionaryExampleItem
:rtype: list[~azure.ai.translation.text.models.DictionaryExampleItem]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "examples": [
- {
- "sourcePrefix": "str", # The string to concatenate
- before the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceSuffix": "str", # The string to concatenate
- after the value of sourceTerm to form a complete example. Do not add
- a space character, since it is already there when it should be. This
- value may be an empty string. Required.
- "sourceTerm": "str", # A string equal to the actual
- term looked up. The string is added with sourcePrefix and
- sourceSuffix to form the complete example. Its value is separated so
- it can be marked in a user interface, e.g., by bolding it. Required.
- "targetPrefix": "str", # A string similar to
- sourcePrefix but for the target. Required.
- "targetSuffix": "str", # A string similar to
- sourceSuffix but for the target. Required.
- "targetTerm": "str" # A string similar to sourceTerm
- but for the target. Required.
- }
- ],
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. Generally, this should be identical to the value of the Text
- field at the matching list index in the body of the request. Required.
- "normalizedTarget": "str" # A string giving the normalized form of
- the target term. Generally, this should be identical to the value of the
- Translation field at the matching list index in the body of the request.
- Required.
- }
- ]
"""
- error_map: MutableMapping[int, Type[HttpResponseError]] = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1960,7 +1231,10 @@ async def lookup_dictionary_examples(
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = _deserialize(_models.ErrorResponse, response.json())
raise HttpResponseError(response=response, model=error)
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_patch.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_operations/_patch.py
index 3506e20e8701..f7dd32510333 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,1366 +2,13 @@
# 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
"""
-from typing import Any, cast, IO, List, Optional, overload, Union
-from ... import models as _models
-from ._operations import TextTranslationClientOperationsMixin as TextTranslationClientOperationsMixinGenerated
-
-
-class TextTranslationClientOperationsMixin(TextTranslationClientOperationsMixinGenerated):
- @overload
- async def translate(
- self,
- body: List[str],
- *,
- to_language: List[str],
- client_trace_id: Optional[str] = None,
- from_language: Optional[str] = None,
- text_type: Optional[Union[str, _models.TextType]] = None,
- category: Optional[str] = None,
- profanity_action: Optional[Union[str, _models.ProfanityAction]] = None,
- profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None,
- include_alignment: Optional[bool] = None,
- include_sentence_length: Optional[bool] = None,
- suggested_from: Optional[str] = None,
- from_script: Optional[str] = None,
- to_script: Optional[str] = None,
- allow_fallback: Optional[bool] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
- """Translate Text.
-
- Translate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: list[str]
- :keyword to_language: Specifies the language of the output text. The target language must be one of the
- supported languages included
- in the translation scope. For example, use to_language=de to translate to German.
- It's possible to translate to multiple languages simultaneously by repeating the parameter in
- the query string.
- For example, use to_language=de&to_language=it to translate to German and Italian. Required.
- :paramtype to_language: list[str]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword from_language: Specifies the language of the input text. Find which languages are
- available to translate from by
- looking up supported languages using the translation scope. If the from parameter isn't
- specified,
- automatic language detection is applied to determine the source language.
-
- You must use the from parameter rather than autodetection when using the dynamic dictionary
- feature.
- Note: the dynamic dictionary feature is case-sensitive. Default value is None.
- :paramtype from_language: str
- :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any
- HTML needs to be a well-formed,
- complete element. Possible values are: plain (default) or html. Known values are: "Plain" and
- "Html". Default value is None.
- :paramtype text_type: str or ~azure.ai.translation.text.models.TextType
- :keyword category: A string specifying the category (domain) of the translation. This parameter
- is used to get translations
- from a customized system built with Custom Translator. Add the Category ID from your Custom
- Translator
- project details to this parameter to use your deployed customized system. Default value is:
- general. Default value is None.
- :paramtype category: str
- :keyword profanity_action: Specifies how profanities should be treated in translations.
- Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction",
- "Marked", and "Deleted". Default value is None.
- :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction
- :keyword profanity_marker: Specifies how profanities should be marked in translations.
- Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag".
- Default value is None.
- :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker
- :keyword include_alignment: Specifies whether to include alignment projection from source text
- to translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_alignment: bool
- :keyword include_sentence_length: Specifies whether to include sentence boundaries for the
- input text and the translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_sentence_length: bool
- :keyword suggested_from: Specifies a fallback language if the language of the input text can't
- be identified.
- Language autodetection is applied when the from parameter is omitted. If detection fails,
- the suggestedFrom language will be assumed. Default value is None.
- :paramtype suggested_from: str
- :keyword from_script: Specifies the script of the input text. Default value is None.
- :paramtype from_script: str
- :keyword to_script: Specifies the script of the translated text. Default value is None.
- :paramtype to_script: str
- :keyword allow_fallback: Specifies that the service is allowed to fall back to a general system
- when a custom system doesn't exist.
- Possible values are: true (default) or false.
-
- allowFallback=false specifies that the translation should only use systems trained for the
- category specified
- by the request. If a translation for language X to language Y requires chaining through a
- pivot language E,
- then all the systems in the chain (X → E and E → Y) will need to be custom and have the same
- category.
- If no system is found with the specific category, the request will return a 400 status code.
- allowFallback=true
- specifies that the service is allowed to fall back to a general system when a custom system
- doesn't exist. Default value is None.
- :paramtype allow_fallback: bool
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TranslatedTextItem
- :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- str" # Text to translate. Required.
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
- """
-
- @overload
- async def translate(
- self,
- body: List[_models.InputTextItem],
- *,
- to_language: List[str],
- client_trace_id: Optional[str] = None,
- from_language: Optional[str] = None,
- text_type: Optional[Union[str, _models.TextType]] = None,
- category: Optional[str] = None,
- profanity_action: Optional[Union[str, _models.ProfanityAction]] = None,
- profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None,
- include_alignment: Optional[bool] = None,
- include_sentence_length: Optional[bool] = None,
- suggested_from: Optional[str] = None,
- from_script: Optional[str] = None,
- to_script: Optional[str] = None,
- allow_fallback: Optional[bool] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
- """Translate Text.
-
- Translate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: list[~azure.ai.translation.text.models.InputTextItem]
- :keyword to_language: Specifies the language of the output text. The target language must be one of the
- supported languages included
- in the translation scope. For example, use to_language=de to translate to German.
- It's possible to translate to multiple languages simultaneously by repeating the parameter in
- the query string.
- For example, use to_language=de&to_language=it to translate to German and Italian. Required.
- :paramtype to_language: list[str]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword from_language: Specifies the language of the input text. Find which languages are
- available to translate from by
- looking up supported languages using the translation scope. If the from parameter isn't
- specified,
- automatic language detection is applied to determine the source language.
-
- You must use the from parameter rather than autodetection when using the dynamic dictionary
- feature.
- Note: the dynamic dictionary feature is case-sensitive. Default value is None.
- :paramtype from_language: str
- :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any
- HTML needs to be a well-formed,
- complete element. Possible values are: plain (default) or html. Known values are: "Plain" and
- "Html". Default value is None.
- :paramtype text_type: str or ~azure.ai.translation.text.models.TextType
- :keyword category: A string specifying the category (domain) of the translation. This parameter
- is used to get translations
- from a customized system built with Custom Translator. Add the Category ID from your Custom
- Translator
- project details to this parameter to use your deployed customized system. Default value is:
- general. Default value is None.
- :paramtype category: str
- :keyword profanity_action: Specifies how profanities should be treated in translations.
- Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction",
- "Marked", and "Deleted". Default value is None.
- :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction
- :keyword profanity_marker: Specifies how profanities should be marked in translations.
- Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag".
- Default value is None.
- :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker
- :keyword include_alignment: Specifies whether to include alignment projection from source text
- to translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_alignment: bool
- :keyword include_sentence_length: Specifies whether to include sentence boundaries for the
- input text and the translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_sentence_length: bool
- :keyword suggested_from: Specifies a fallback language if the language of the input text can't
- be identified.
- Language autodetection is applied when the from parameter is omitted. If detection fails,
- the suggestedFrom language will be assumed. Default value is None.
- :paramtype suggested_from: str
- :keyword from_script: Specifies the script of the input text. Default value is None.
- :paramtype from_script: str
- :keyword to_script: Specifies the script of the translated text. Default value is None.
- :paramtype to_script: str
- :keyword allow_fallback: Specifies that the service is allowed to fall back to a general system
- when a custom system doesn't exist.
- Possible values are: true (default) or false.
-
- allowFallback=false specifies that the translation should only use systems trained for the
- category specified
- by the request. If a translation for language X to language Y requires chaining through a
- pivot language E,
- then all the systems in the chain (X → E and E → Y) will need to be custom and have the same
- category.
- If no system is found with the specific category, the request will return a 400 status code.
- allowFallback=true
- specifies that the service is allowed to fall back to a general system when a custom system
- doesn't exist. Default value is None.
- :paramtype allow_fallback: bool
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TranslatedTextItem
- :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
- """
-
- @overload
- async def translate(
- self,
- body: IO[bytes],
- *,
- to_language: List[str],
- client_trace_id: Optional[str] = None,
- from_language: Optional[str] = None,
- text_type: Optional[Union[str, _models.TextType]] = None,
- category: Optional[str] = None,
- profanity_action: Optional[Union[str, _models.ProfanityAction]] = None,
- profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None,
- include_alignment: Optional[bool] = None,
- include_sentence_length: Optional[bool] = None,
- suggested_from: Optional[str] = None,
- from_script: Optional[str] = None,
- to_script: Optional[str] = None,
- allow_fallback: Optional[bool] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TranslatedTextItem]:
- # pylint: disable=line-too-long
- """Translate Text.
-
- Translate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: IO[bytes]
- :keyword to_language: Specifies the language of the output text. The target language must be one of the
- supported languages included
- in the translation scope. For example, use to_language=de to translate to German.
- It's possible to translate to multiple languages simultaneously by repeating the parameter in
- the query string.
- For example, use to_language=de&to_language=it to translate to German and Italian. Required.
- :paramtype to_language: list[str]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword from_language: Specifies the language of the input text. Find which languages are
- available to translate from by
- looking up supported languages using the translation scope. If the from parameter isn't
- specified,
- automatic language detection is applied to determine the source language.
-
- You must use the from parameter rather than autodetection when using the dynamic dictionary
- feature.
- Note: the dynamic dictionary feature is case-sensitive. Default value is None.
- :paramtype from_language: str
- :keyword text_type: Defines whether the text being translated is plain text or HTML text. Any
- HTML needs to be a well-formed,
- complete element. Possible values are: plain (default) or html. Known values are: "Plain" and
- "Html". Default value is None.
- :paramtype text_type: str or ~azure.ai.translation.text.models.TextType
- :keyword category: A string specifying the category (domain) of the translation. This parameter
- is used to get translations
- from a customized system built with Custom Translator. Add the Category ID from your Custom
- Translator
- project details to this parameter to use your deployed customized system. Default value is:
- general. Default value is None.
- :paramtype category: str
- :keyword profanity_action: Specifies how profanities should be treated in translations.
- Possible values are: NoAction (default), Marked or Deleted. Known values are: "NoAction",
- "Marked", and "Deleted". Default value is None.
- :paramtype profanity_action: str or ~azure.ai.translation.text.models.ProfanityAction
- :keyword profanity_marker: Specifies how profanities should be marked in translations.
- Possible values are: Asterisk (default) or Tag. Known values are: "Asterisk" and "Tag".
- Default value is None.
- :paramtype profanity_marker: str or ~azure.ai.translation.text.models.ProfanityMarker
- :keyword include_alignment: Specifies whether to include alignment projection from source text
- to translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_alignment: bool
- :keyword include_sentence_length: Specifies whether to include sentence boundaries for the
- input text and the translated text.
- Possible values are: true or false (default). Default value is None.
- :paramtype include_sentence_length: bool
- :keyword suggested_from: Specifies a fallback language if the language of the input text can't
- be identified.
- Language autodetection is applied when the from parameter is omitted. If detection fails,
- the suggestedFrom language will be assumed. Default value is None.
- :paramtype suggested_from: str
- :keyword from_script: Specifies the script of the input text. Default value is None.
- :paramtype from_script: str
- :keyword to_script: Specifies the script of the translated text. Default value is None.
- :paramtype to_script: str
- :keyword allow_fallback: Specifies that the service is allowed to fall back to a general system
- when a custom system doesn't exist.
- Possible values are: true (default) or false.
-
- allowFallback=false specifies that the translation should only use systems trained for the
- category specified
- by the request. If a translation for language X to language Y requires chaining through a
- pivot language E,
- then all the systems in the chain (X → E and E → Y) will need to be custom and have the same
- category.
- If no system is found with the specific category, the request will return a 400 status code.
- allowFallback=true
- specifies that the service is allowed to fall back to a general system when a custom system
- doesn't exist. Default value is None.
- :paramtype allow_fallback: bool
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TranslatedTextItem
- :rtype: list[~azure.ai.translation.text.models.TranslatedTextItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "translations": [
- {
- "text": "str", # A string giving the translated
- text. Required.
- "to": "str", # A string representing the language
- code of the target language. Required.
- "alignment": {
- "proj": "str" # Maps input text to
- translated text. The alignment information is only provided when
- the request parameter includeAlignment is true. Alignment is
- returned as a string value of the following format:
- [[SourceTextStartIndex]:[SourceTextEndIndex]"u2013[TgtTextStartIndex]:[TgtTextEndIndex]].
- The colon separates start and end index, the dash separates the
- languages, and space separates the words. One word may align
- with zero, one, or multiple words in the other language, and the
- aligned words may be non-contiguous. When no alignment
- information is available, the alignment element will be empty.
- Required.
- },
- "sentLen": {
- "srcSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the input text. The length
- of the array is the number of sentences, and the values are
- the length of each sentence. Required.
- ],
- "transSentLen": [
- 0 # An integer array representing
- the lengths of the sentences in the translated text. The
- length of the array is the number of sentences, and the
- values are the length of each sentence. Required.
- ]
- },
- "transliteration": {
- "script": "str", # A string specifying the
- script used in the output. Required.
- "text": "str" # A string which is the result
- of converting the input string to the output script. Required.
- }
- }
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- },
- "sourceText": {
- "text": "str" # Input text in the default script of the
- source language. Required.
- }
- }
- ]
- """
-
- async def translate( # pyright: ignore[reportIncompatibleMethodOverride]
- self,
- body: Union[List[str], List[_models.InputTextItem], IO[bytes]],
- *,
- to_language: List[str],
- client_trace_id: Optional[str] = None,
- from_language: Optional[str] = None,
- text_type: Optional[Union[str, _models.TextType]] = None,
- category: Optional[str] = None,
- profanity_action: Optional[Union[str, _models.ProfanityAction]] = None,
- profanity_marker: Optional[Union[str, _models.ProfanityMarker]] = None,
- include_alignment: Optional[bool] = None,
- include_sentence_length: Optional[bool] = None,
- suggested_from: Optional[str] = None,
- from_script: Optional[str] = None,
- to_script: Optional[str] = None,
- allow_fallback: Optional[bool] = None,
- **kwargs: Any
- ) -> List[_models.TranslatedTextItem]:
- request_body: Union[List[_models.InputTextItem], IO[bytes]]
- if isinstance(body, list) and all(isinstance(item, str) for item in body):
- input_text_items: List[_models.InputTextItem] = []
- for text in body:
- input_text_items.append(_models.InputTextItem(text=cast(str, text)))
- request_body = input_text_items
- else:
- request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body)
-
- return await super().translate(
- body=request_body,
- to_language=to_language,
- client_trace_id=client_trace_id,
- from_language=from_language,
- text_type=text_type,
- category=category,
- profanity_action=profanity_action,
- profanity_marker=profanity_marker,
- include_alignment=include_alignment,
- include_sentence_length=include_sentence_length,
- suggested_from=suggested_from,
- from_script=from_script,
- to_script=to_script,
- allow_fallback=allow_fallback,
- **kwargs
- )
-
- @overload
- async def transliterate(
- self,
- body: List[str],
- *,
- language: str,
- from_script: str,
- to_script: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TransliteratedText]:
- """Transliterate Text.
-
- Transliterate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: list[str]
- :keyword language: Specifies the language of the text to convert from one script to another.
- Possible languages are listed in the transliteration scope obtained by querying the service
- for its supported languages. Required.
- :paramtype language: str
- :keyword from_script: Specifies the script used by the input text. Look up supported languages
- using the transliteration scope,
- to find input scripts available for the selected language. Required.
- :paramtype from_script: str
- :keyword to_script: Specifies the output script. Look up supported languages using the
- transliteration scope, to find output
- scripts available for the selected combination of input language and input script. Required.
- :paramtype to_script: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TransliteratedText
- :rtype: list[~azure.ai.translation.text.models.TransliteratedText]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
- """
-
- @overload
- async def transliterate(
- self,
- body: List[_models.InputTextItem],
- *,
- language: str,
- from_script: str,
- to_script: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TransliteratedText]:
- """Transliterate Text.
-
- Transliterate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: list[~azure.ai.translation.text.models.InputTextItem]
- :keyword language: Specifies the language of the text to convert from one script to another.
- Possible languages are listed in the transliteration scope obtained by querying the service
- for its supported languages. Required.
- :paramtype language: str
- :keyword from_script: Specifies the script used by the input text. Look up supported languages
- using the transliteration scope,
- to find input scripts available for the selected language. Required.
- :paramtype from_script: str
- :keyword to_script: Specifies the output script. Look up supported languages using the
- transliteration scope, to find output
- scripts available for the selected combination of input language and input script. Required.
- :paramtype to_script: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TransliteratedText
- :rtype: list[~azure.ai.translation.text.models.TransliteratedText]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
- """
-
- @overload
- async def transliterate(
- self,
- body: IO[bytes],
- *,
- language: str,
- from_script: str,
- to_script: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.TransliteratedText]:
- """Transliterate Text.
-
- Transliterate Text.
-
- :param body: Defines the content of the request. Required.
- :type body: IO[bytes]
- :keyword language: Specifies the language of the text to convert from one script to another.
- Possible languages are listed in the transliteration scope obtained by querying the service
- for its supported languages. Required.
- :paramtype language: str
- :keyword from_script: Specifies the script used by the input text. Look up supported languages
- using the transliteration scope,
- to find input scripts available for the selected language. Required.
- :paramtype from_script: str
- :keyword to_script: Specifies the output script. Look up supported languages using the
- transliteration scope, to find output
- scripts available for the selected combination of input language and input script. Required.
- :paramtype to_script: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of TransliteratedText
- :rtype: list[~azure.ai.translation.text.models.TransliteratedText]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "script": "str", # A string specifying the script used in the
- output. Required.
- "text": "str" # A string which is the result of converting the input
- string to the output script. Required.
- }
- ]
- """
-
- async def transliterate( # pyright: ignore[reportIncompatibleMethodOverride]
- self,
- body: Union[List[str], List[_models.InputTextItem], IO[bytes]],
- *,
- language: str,
- from_script: str,
- to_script: str,
- client_trace_id: Optional[str] = None,
- **kwargs: Any
- ) -> List[_models.TransliteratedText]:
- request_body: Union[List[_models.InputTextItem], IO[bytes]]
- if isinstance(body, list) and all(isinstance(item, str) for item in body):
- input_text_items: List[_models.InputTextItem] = []
- for text in body:
- input_text_items.append(_models.InputTextItem(text=cast(str, text)))
- request_body = input_text_items
- else:
- request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body)
-
- return await super().transliterate(
- body=request_body,
- language=language,
- from_script=from_script,
- to_script=to_script,
- client_trace_id=client_trace_id,
- **kwargs
- )
-
- @overload
- async def find_sentence_boundaries(
- self,
- body: List[str],
- *,
- client_trace_id: Optional[str] = None,
- language: Optional[str] = None,
- script: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
- """Find Sentence Boundaries.
-
- Find Sentence Boundaries.
-
- :param body: Defines the content of the request. Required.
- :type body: list[str]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword language: Language tag identifying the language of the input text.
- If a code isn't specified, automatic language detection will be applied. Default value is
- None.
- :paramtype language: str
- :keyword script: Script tag identifying the script used by the input text.
- If a script isn't specified, the default script of the language will be assumed. Default value
- is None.
- :paramtype script: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of BreakSentenceItem
- :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
- """
-
- @overload
- async def find_sentence_boundaries(
- self,
- body: List[_models.InputTextItem],
- *,
- client_trace_id: Optional[str] = None,
- language: Optional[str] = None,
- script: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
- """Find Sentence Boundaries.
-
- Find Sentence Boundaries.
-
- :param body: Defines the content of the request. Required.
- :type body: list[~azure.ai.translation.text.models.InputTextItem]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword language: Language tag identifying the language of the input text.
- If a code isn't specified, automatic language detection will be applied. Default value is
- None.
- :paramtype language: str
- :keyword script: Script tag identifying the script used by the input text.
- If a script isn't specified, the default script of the language will be assumed. Default value
- is None.
- :paramtype script: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of BreakSentenceItem
- :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
- """
-
- @overload
- async def find_sentence_boundaries(
- self,
- body: IO[bytes],
- *,
- client_trace_id: Optional[str] = None,
- language: Optional[str] = None,
- script: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.BreakSentenceItem]:
- # pylint: disable=line-too-long
- """Find Sentence Boundaries.
-
- Find Sentence Boundaries.
-
- :param body: Defines the content of the request. Required.
- :type body: IO[bytes]
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword language: Language tag identifying the language of the input text.
- If a code isn't specified, automatic language detection will be applied. Default value is
- None.
- :paramtype language: str
- :keyword script: Script tag identifying the script used by the input text.
- If a script isn't specified, the default script of the language will be assumed. Default value
- is None.
- :paramtype script: str
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of BreakSentenceItem
- :rtype: list[~azure.ai.translation.text.models.BreakSentenceItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "sentLen": [
- 0 # An integer array representing the lengths of the
- sentences in the input text. The length of the array is the number of
- sentences, and the values are the length of each sentence. Required.
- ],
- "detectedLanguage": {
- "language": "str", # A string representing the code of the
- detected language. Required.
- "score": 0.0 # A float value indicating the confidence in
- the result. The score is between zero and one and a low score indicates a
- low confidence. Required.
- }
- }
- ]
- """
-
- async def find_sentence_boundaries( # pyright: ignore[reportIncompatibleMethodOverride]
- self,
- body: Union[List[str], List[_models.InputTextItem], IO[bytes]],
- *,
- client_trace_id: Optional[str] = None,
- language: Optional[str] = None,
- script: Optional[str] = None,
- **kwargs: Any
- ) -> List[_models.BreakSentenceItem]:
- request_body: Union[List[_models.InputTextItem], IO[bytes]]
- if isinstance(body, list) and all(isinstance(item, str) for item in body):
- input_text_items: List[_models.InputTextItem] = []
- for text in body:
- input_text_items.append(_models.InputTextItem(text=cast(str, text)))
- request_body = input_text_items
-
- else:
- request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body)
-
- return await super().find_sentence_boundaries(
- body=request_body, language=language, script=script, client_trace_id=client_trace_id, **kwargs
- )
-
- @overload
- async def lookup_dictionary_entries(
- self,
- body: List[str],
- *,
- from_language: str,
- to_language: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
- """Lookup Dictionary Entries.
-
- Lookup Dictionary Entries.
-
- :param body: Defines the content of the request. Required.
- :type body: list[str]
- :keyword from_language: Specifies the language of the input text.
- The source language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype from_language: str
- :keyword to_language: Specifies the language of the output text.
- The target language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype to_language: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of DictionaryLookupItem
- :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "score": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
- """
-
- @overload
- async def lookup_dictionary_entries(
- self,
- body: List[_models.InputTextItem],
- *,
- from_language: str,
- to_language: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
- """Lookup Dictionary Entries.
-
- Lookup Dictionary Entries.
-
- :param body: Defines the content of the request. Required.
- :type body: list[~azure.ai.translation.text.models.InputTextItem]
- :keyword from_language: Specifies the language of the input text.
- The source language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype from_language: str
- :keyword to_language: Specifies the language of the output text.
- The target language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype to_language: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of DictionaryLookupItem
- :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- body = [
- {
- "text": "str" # Text to translate. Required.
- }
- ]
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "score": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
- """
-
- @overload
- async def lookup_dictionary_entries(
- self,
- body: IO[bytes],
- *,
- from_language: str,
- to_language: str,
- client_trace_id: Optional[str] = None,
- content_type: str = "application/json",
- **kwargs: Any
- ) -> List[_models.DictionaryLookupItem]:
- # pylint: disable=line-too-long
- """Lookup Dictionary Entries.
-
- Lookup Dictionary Entries.
-
- :param body: Defines the content of the request. Required.
- :type body: IO[bytes]
- :keyword from_language: Specifies the language of the input text.
- The source language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype from_language: str
- :keyword to_language: Specifies the language of the output text.
- The target language must be one of the supported languages included in the dictionary scope.
- Required.
- :paramtype to_language: str
- :keyword client_trace_id: A client-generated GUID to uniquely identify the request. Default
- value is None.
- :paramtype client_trace_id: str
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/json".
- :paramtype content_type: str
- :return: list of DictionaryLookupItem
- :rtype: list[~azure.ai.translation.text.models.DictionaryLookupItem]
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == [
- {
- "displaySource": "str", # A string giving the source term in a form
- best suited for end-user display. For example, if the input is "JOHN", the
- display form will reflect the usual spelling of the name: "John". Required.
- "normalizedSource": "str", # A string giving the normalized form of
- the source term. For example, if the request is "JOHN", the normalized form
- will be "john". The content of this field becomes the input to lookup
- examples. Required.
- "translations": [
- {
- "backTranslations": [
- {
- "displayText": "str", # A string
- giving the source term that is a back-translation of the
- target in a form best suited for end-user display. Required.
- "frequencyCount": 0, # An integer
- representing the frequency of this translation pair in the
- data. The main purpose of this field is to provide a user
- interface with a means to sort back-translations so the most
- frequent terms are first. Required.
- "normalizedText": "str", # A string
- giving the normalized form of the source term that is a
- back-translation of the target. This value should be used as
- input to lookup examples. Required.
- "numExamples": 0 # An integer
- representing the number of examples that are available for
- this translation pair. Actual examples must be retrieved with
- a separate call to lookup examples. The number is mostly
- intended to facilitate display in a UX. For example, a user
- interface may add a hyperlink to the back-translation if the
- number of examples is greater than zero and show the
- back-translation as plain text if there are no examples. Note
- that the actual number of examples returned by a call to
- lookup examples may be less than numExamples, because
- additional filtering may be applied on the fly to remove
- "bad" examples. Required.
- }
- ],
- "score": 0.0, # A value between 0.0 and 1.0
- which represents the "confidence" (or perhaps more accurately,
- "probability in the training data") of that translation pair. The
- sum of confidence scores for one source word may or may not sum to
- 1.0. Required.
- "displayTarget": "str", # A string giving the term
- in the target language and in a form best suited for end-user
- display. Generally, this will only differ from the normalizedTarget
- in terms of capitalization. For example, a proper noun like "Juan"
- will have normalizedTarget = "juan" and displayTarget = "Juan".
- Required.
- "normalizedTarget": "str", # A string giving the
- normalized form of this term in the target language. This value
- should be used as input to lookup examples. Required.
- "posTag": "str", # A string associating this term
- with a part-of-speech tag. Required.
- "prefixWord": "str" # A string giving the word to
- display as a prefix of the translation. Currently, this is the
- gendered determiner of nouns, in languages that have gendered
- determiners. For example, the prefix of the Spanish word "mosca" is
- "la", since "mosca" is a feminine noun in Spanish. This is only
- dependent on the translation, and not on the source. If there is no
- prefix, it will be the empty string. Required.
- }
- ]
- }
- ]
- """
-
- async def lookup_dictionary_entries( # pyright: ignore[reportIncompatibleMethodOverride]
- self,
- body: Union[List[str], List[_models.InputTextItem], IO[bytes]],
- *,
- from_language: str,
- to_language: str,
- client_trace_id: Optional[str] = None,
- **kwargs: Any
- ) -> List[_models.DictionaryLookupItem]:
- request_body: Union[List[_models.InputTextItem], IO[bytes]]
- if isinstance(body, list) and all(isinstance(item, str) for item in body):
- input_text_items: List[_models.InputTextItem] = []
- for text in body:
- input_text_items.append(_models.InputTextItem(text=cast(str, text)))
- request_body = input_text_items
- else:
- request_body = cast(Union[List[_models.InputTextItem], IO[bytes]], body)
-
- return await super().lookup_dictionary_entries(
- body=request_body,
- from_language=from_language,
- to_language=to_language,
- client_trace_id=client_trace_id,
- **kwargs
- )
-
+from typing import List
-__all__: List[str] = [
- "TextTranslationClientOperationsMixin"
-] # Add all objects you want publicly available to users at this package level
+__all__: List[str] = [] # Add all objects you want publicly available to users at this package level
def patch_sdk():
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_patch.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_patch.py
index 235e7539dd94..f7dd32510333 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,26 +2,13 @@
# 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 Optional, Any, overload
-from azure.core.pipeline import PipelineRequest
-from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy, AzureKeyCredentialPolicy
-from azure.core.credentials import AzureKeyCredential
-from azure.core.credentials_async import AsyncTokenCredential
+from typing import List
-from .._patch import (
- DEFAULT_ENTRA_ID_SCOPE,
- DEFAULT_SCOPE,
- get_translation_endpoint,
- TranslatorAuthenticationPolicy,
- is_cognitive_services_scope,
-)
-
-from ._client import TextTranslationClient as ServiceClientGenerated
+__all__: List[str] = [] # Add all objects you want publicly available to users at this package level
def patch_sdk():
@@ -31,146 +18,3 @@ def patch_sdk():
you can't accomplish using the techniques described in
https://aka.ms/azsdk/python/dpcodegen/python/customize
"""
-
-
-class AsyncTranslatorEntraIdAuthenticationPolicy(AsyncBearerTokenCredentialPolicy): # pylint: disable=name-too-long
- """Translator Entra Id Authentication Policy. Adds headers that are required by Translator Service
- when global endpoint is used with Entra Id policy.
- Ocp-Apim-Subscription-Region header contains region of the Translator resource.
- Ocp-Apim-ResourceId header contains Azure resource Id - Translator resource.
-
- :param credential: Translator Entra Id Credentials used to access Translator Resource for global endpoint.
- :type credential: ~azure.core.credentials_async.AsyncTokenCredential
- :keyword str region: Used for National Clouds.
- :keyword str resource_id: Used with both a TokenCredential combined with a region.
- :keyword str audience: Scopes of the credentials.
- """
-
- def __init__(
- self, credential: AsyncTokenCredential, resource_id: str, region: str, audience: str, **kwargs: Any
- ) -> None:
- super(AsyncTranslatorEntraIdAuthenticationPolicy, self).__init__(credential, audience, **kwargs)
- self.resource_id = resource_id
- self.region = region
- self.translator_credential = credential
-
- async def on_request(self, request: PipelineRequest) -> None:
- request.http_request.headers["Ocp-Apim-ResourceId"] = self.resource_id
- request.http_request.headers["Ocp-Apim-Subscription-Region"] = self.region
- await super().on_request(request)
-
-
-def set_authentication_policy(credential, kwargs):
- if isinstance(credential, AzureKeyCredential):
- if not kwargs.get("authentication_policy"):
- if kwargs.get("region"):
- kwargs["authentication_policy"] = TranslatorAuthenticationPolicy(credential, kwargs["region"])
- else:
- kwargs["authentication_policy"] = AzureKeyCredentialPolicy(
- name="Ocp-Apim-Subscription-Key", credential=credential
- )
- elif hasattr(credential, "get_token"):
- if not kwargs.get("authentication_policy"):
- if kwargs.get("region") and kwargs.get("resource_id"):
- scope = kwargs.pop("audience", DEFAULT_ENTRA_ID_SCOPE).rstrip("/").rstrip(DEFAULT_SCOPE) + DEFAULT_SCOPE
- kwargs["authentication_policy"] = AsyncTranslatorEntraIdAuthenticationPolicy(
- credential,
- kwargs["resource_id"],
- kwargs["region"],
- scope,
- )
- else:
- if kwargs.get("resource_id") or kwargs.get("region"):
- raise ValueError(
- """Both 'resource_id' and 'region' must be provided with a TokenCredential
- for regional resource authentication."""
- )
- scope: str = kwargs.pop("audience", DEFAULT_ENTRA_ID_SCOPE)
- if not is_cognitive_services_scope(scope):
- scope = scope.rstrip("/").rstrip(DEFAULT_SCOPE) + DEFAULT_SCOPE
- kwargs["authentication_policy"] = AsyncBearerTokenCredentialPolicy(
- credential, scope
- )
-
-
-class TextTranslationClient(ServiceClientGenerated):
- """Text translation is a cloud-based REST API feature of the Translator service that uses neural
- machine translation technology to enable quick and accurate source-to-target text translation
- in real time across all supported languages.
-
- The following methods are supported by the Text Translation feature:
-
- Languages. Returns a list of languages supported by Translate, Transliterate, and Dictionary
- Lookup operations.
-
- Translate. Renders single source-language text to multiple target-language texts with a single
- request.
-
- Transliterate. Converts characters or letters of a source language to the corresponding
- characters or letters of a target language.
-
- Detect. Returns the source code language code and a boolean variable denoting whether the
- detected language is supported for text translation and transliteration.
-
- Dictionary lookup. Returns equivalent words for the source term in the target language.
-
- Dictionary example Returns grammatical structure and context examples for the source term and
- target term pair.
-
- Combinations of endpoint and credential values:
- str + AzureKeyCredential - used custom domain translator endpoint
- str + AzureKeyCredential + Region - used for global translator endpoint
- str + AsyncTokenCredential - used for regional endpoint with token authentication
- str + None - used with text translation on-prem container
- None + AzureKeyCredential - used for global translator endpoint with global Translator resource
- None + AsyncTokenCredential - general translator endpoint with token authentication
- None + AsyncTokenCredential + Region - general translator endpoint with regional Translator resource
-
- :keyword str endpoint: Supported Text Translation endpoints (protocol and hostname, for example:
- https://api.cognitive.microsofttranslator.com). If not provided, global translator endpoint will be used.
- :keyword credential: Credential used to authenticate with the Translator service
- :paramtype credential: Union[AzureKeyCredential, AsyncTokenCredential]
- :keyword str region: Used for National Clouds.
- :keyword str resource_id: Used with both a TokenCredential combined with a region.
- :keyword str audience: Scopes of the credentials.
- :keyword str api_version: Default value is "3.0". Note that overriding this default value may
- result in unsupported behavior.
- """
-
- @overload
- def __init__(
- self,
- *,
- credential: AsyncTokenCredential,
- region: Optional[str] = None,
- endpoint: Optional[str] = None,
- resource_id: Optional[str] = None,
- audience: Optional[str] = None,
- api_version: str = "3.0",
- **kwargs
- ): ...
-
- @overload
- def __init__(
- self,
- *,
- credential: AzureKeyCredential,
- region: Optional[str] = None,
- endpoint: Optional[str] = None,
- api_version: str = "3.0",
- **kwargs
- ): ...
-
- @overload
- def __init__(self, *, endpoint: str, api_version: str = "3.0", **kwargs): ...
-
- def __init__(self, **kwargs):
- api_version = kwargs.get("api_version", "3.0")
- set_authentication_policy(kwargs.get("credential"), kwargs)
- translation_endpoint = get_translation_endpoint(
- kwargs.pop("endpoint", "https://api.cognitive.microsofttranslator.com"), api_version
- )
- super().__init__(endpoint=translation_endpoint, api_version=api_version, **kwargs)
-
-
-__all__ = ["TextTranslationClient"]
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_vendor.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_vendor.py
index 28781d01428b..465f0d971d88 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_vendor.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/aio/_vendor.py
@@ -13,7 +13,6 @@
from ._configuration import TextTranslationClientConfiguration
if TYPE_CHECKING:
- # pylint: disable=unused-import,ungrouped-imports
from azure.core import AsyncPipelineClient
from .._serialization import Deserializer, Serializer
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/__init__.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/__init__.py
index da99621bc1e2..54f82769c9be 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/__init__.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/__init__.py
@@ -5,38 +5,49 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._models import BackTranslation
-from ._models import BreakSentenceItem
-from ._models import DetectedLanguage
-from ._models import DictionaryExample
-from ._models import DictionaryExampleItem
-from ._models import DictionaryExampleTextItem
-from ._models import DictionaryLookupItem
-from ._models import DictionaryTranslation
-from ._models import ErrorDetails
-from ._models import ErrorResponse
-from ._models import GetSupportedLanguagesResult
-from ._models import InputTextItem
-from ._models import LanguageScript
-from ._models import SentenceBoundaries
-from ._models import SourceDictionaryLanguage
-from ._models import SourceText
-from ._models import TargetDictionaryLanguage
-from ._models import TranslatedTextAlignment
-from ._models import TranslatedTextItem
-from ._models import TranslationLanguage
-from ._models import TranslationText
-from ._models import TransliterableScript
-from ._models import TransliteratedText
-from ._models import TransliterationLanguage
+from typing import TYPE_CHECKING
-from ._enums import LanguageDirectionality
-from ._enums import ProfanityAction
-from ._enums import ProfanityMarker
-from ._enums import TextType
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+
+
+from ._models import ( # type: ignore
+ BackTranslation,
+ BreakSentenceItem,
+ DetectedLanguage,
+ DictionaryExample,
+ DictionaryExampleItem,
+ DictionaryExampleTextItem,
+ DictionaryLookupItem,
+ DictionaryTranslation,
+ ErrorDetails,
+ ErrorResponse,
+ GetSupportedLanguagesResult,
+ InputTextItem,
+ LanguageScript,
+ SentenceBoundaries,
+ SourceDictionaryLanguage,
+ SourceText,
+ TargetDictionaryLanguage,
+ TranslatedTextAlignment,
+ TranslatedTextItem,
+ TranslationLanguage,
+ TranslationText,
+ TransliterableScript,
+ TransliteratedText,
+ TransliterationLanguage,
+)
+
+from ._enums import ( # type: ignore
+ LanguageDirectionality,
+ ProfanityAction,
+ ProfanityMarker,
+ TextType,
+)
from ._patch import __all__ as _patch_all
-from ._patch import * # pylint: disable=unused-wildcard-import
+from ._patch import *
from ._patch import patch_sdk as _patch_sdk
__all__ = [
@@ -69,5 +80,5 @@
"ProfanityMarker",
"TextType",
]
-__all__.extend([p for p in _patch_all if p not in __all__])
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_models.py b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_models.py
index e636f1f0a345..0d377c53c1d5 100644
--- a/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_models.py
+++ b/sdk/translation/azure-ai-translation-text/azure/ai/translation/text/models/_models.py
@@ -1,11 +1,12 @@
-# coding=utf-8
# pylint: disable=too-many-lines
+# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=useless-super-delegation
from typing import Any, Dict, List, Mapping, Optional, TYPE_CHECKING, Union, overload
@@ -13,14 +14,12 @@
from .._model_base import rest_field
if TYPE_CHECKING:
- # pylint: disable=unused-import,ungrouped-imports
from .. import models as _models
class BackTranslation(_model_base.Model):
"""Back Translation.
- All required parameters must be populated in order to send to server.
:ivar normalized_text: A string giving the normalized form of the source term that is a
back-translation of the target.
@@ -78,23 +77,22 @@ def __init__(
display_text: str,
num_examples: int,
frequency_count: int,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class BreakSentenceItem(_model_base.Model):
"""Item containing break sentence result.
- All required parameters must be populated in order to send to server.
:ivar detected_language: The detectedLanguage property is only present in the result object
when language auto-detection is requested.
@@ -119,23 +117,22 @@ def __init__(
*,
sent_len: List[int],
detected_language: Optional["_models.DetectedLanguage"] = None,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class DetectedLanguage(_model_base.Model):
"""An object describing the detected language.
- All required parameters must be populated in order to send to server.
:ivar language: A string representing the code of the detected language. Required.
:vartype language: str
@@ -156,23 +153,22 @@ def __init__(
*,
language: str,
score: float,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class DictionaryExample(_model_base.Model):
"""Dictionary Example.
- All required parameters must be populated in order to send to server.
:ivar source_prefix: The string to concatenate before the value of sourceTerm to form a
complete example.
@@ -226,23 +222,22 @@ def __init__(
target_prefix: str,
target_term: str,
target_suffix: str,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class DictionaryExampleItem(_model_base.Model):
"""Dictionary Example element.
- All required parameters must be populated in order to send to server.
:ivar normalized_source: A string giving the normalized form of the source term. Generally,
this should be identical
@@ -275,16 +270,16 @@ def __init__(
normalized_source: str,
normalized_target: str,
examples: List["_models.DictionaryExample"],
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -305,16 +300,16 @@ def __init__(
self,
*,
text: str,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -347,23 +342,22 @@ def __init__(
*,
text: str,
translation: str,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class DictionaryLookupItem(_model_base.Model):
"""Dictionary Lookup Element.
- All required parameters must be populated in order to send to server.
:ivar normalized_source: A string giving the normalized form of the source term.
For example, if the request is "JOHN", the normalized form will be "john".
@@ -396,23 +390,22 @@ def __init__(
normalized_source: str,
display_source: str,
translations: List["_models.DictionaryTranslation"],
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class DictionaryTranslation(_model_base.Model):
"""Translation source term.
- All required parameters must be populated in order to send to server.
:ivar normalized_target: A string giving the normalized form of this term in the target
language.
@@ -485,23 +478,22 @@ def __init__(
confidence: float,
prefix_word: str,
back_translations: List["_models.BackTranslation"],
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class ErrorDetails(_model_base.Model):
"""Error details as returned by Translator Service.
- All required parameters must be populated in order to send to server.
:ivar code: Number identifier of the error. Required.
:vartype code: int
@@ -520,23 +512,22 @@ def __init__(
*,
code: int,
message: str,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class ErrorResponse(_model_base.Model):
"""Representation of the Error Response from Translator Service.
- All required parameters must be populated in order to send to server.
:ivar error: Error details. Required.
:vartype error: ~azure.ai.translation.text.models.ErrorDetails
@@ -550,16 +541,16 @@ def __init__(
self,
*,
error: "_models.ErrorDetails",
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -588,23 +579,22 @@ def __init__(
translation: Optional[Dict[str, "_models.TranslationLanguage"]] = None,
transliteration: Optional[Dict[str, "_models.TransliterationLanguage"]] = None,
dictionary: Optional[Dict[str, "_models.SourceDictionaryLanguage"]] = None,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class LanguageScript(_model_base.Model):
"""Common properties of language script.
- All required parameters must be populated in order to send to server.
:ivar code: Code identifying the script. Required.
:vartype code: str
@@ -637,23 +627,22 @@ def __init__(
name: str,
native_name: str,
dir: Union[str, "_models.LanguageDirectionality"],
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class 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.
:ivar src_sent_len: An integer array representing the lengths of the sentences in the input
text.
@@ -682,23 +671,22 @@ def __init__(
*,
src_sent_len: List[int],
trans_sent_len: List[int],
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class SourceDictionaryLanguage(_model_base.Model):
"""Properties ot the source dictionary language.
- All required parameters must be populated in order to send to server.
:ivar name: Display name of the language in the locale requested via Accept-Language header.
Required.
@@ -733,23 +721,22 @@ def __init__(
native_name: str,
dir: Union[str, "_models.LanguageDirectionality"],
translations: List["_models.TargetDictionaryLanguage"],
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class SourceText(_model_base.Model):
"""Input text in the default script of the source language.
- All required parameters must be populated in order to send to server.
:ivar text: Input text in the default script of the source language. Required.
:vartype text: str
@@ -763,23 +750,22 @@ def __init__(
self,
*,
text: str,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class TargetDictionaryLanguage(_model_base.Model):
"""Properties of the target dictionary language.
- All required parameters must be populated in order to send to server.
:ivar name: Display name of the language in the locale requested via Accept-Language header.
Required.
@@ -812,23 +798,22 @@ def __init__(
native_name: str,
dir: Union[str, "_models.LanguageDirectionality"],
code: str,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class TranslatedTextAlignment(_model_base.Model):
"""Alignment information object.
- All required parameters must be populated in order to send to server.
:ivar proj: Maps input text to translated text. The alignment information is only provided when
the request
@@ -859,23 +844,22 @@ def __init__(
self,
*,
proj: str,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class TranslatedTextItem(_model_base.Model):
"""Element containing the translated text.
- All required parameters must be populated in order to send to server.
:ivar detected_language: The detectedLanguage property is only present in the result object
when language auto-detection is requested.
@@ -914,16 +898,16 @@ def __init__(
translations: List["_models.TranslationText"],
detected_language: Optional["_models.DetectedLanguage"] = None,
source_text: Optional["_models.SourceText"] = None,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -932,7 +916,6 @@ class TranslationLanguage(_model_base.Model):
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.
@@ -960,23 +943,22 @@ def __init__(
name: str,
native_name: str,
dir: Union[str, "_models.LanguageDirectionality"],
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class TranslationText(_model_base.Model):
"""Translation result.
- All required parameters must be populated in order to send to server.
:ivar to: A string representing the language code of the target language. Required.
:vartype to: str
@@ -1011,23 +993,22 @@ def __init__(
transliteration: Optional["_models.TransliteratedText"] = None,
alignment: Optional["_models.TranslatedTextAlignment"] = None,
sent_len: Optional["_models.SentenceBoundaries"] = None,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class TransliterableScript(LanguageScript):
"""Script definition with list of script into which given script can be translitered.
- All required parameters must be populated in order to send to server.
:ivar code: Code identifying the script. Required.
:vartype code: str
@@ -1056,23 +1037,22 @@ def __init__(
native_name: str,
dir: Union[str, "_models.LanguageDirectionality"],
to_scripts: List["_models.LanguageScript"],
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class TransliteratedText(_model_base.Model):
"""Transliterated text element.
- All required parameters must be populated in order to send to server.
:ivar text: A string which is the result of converting the input string to the output script.
Required.
@@ -1092,16 +1072,16 @@ def __init__(
*,
text: str,
script: str,
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -1111,7 +1091,6 @@ class TransliterationLanguage(_model_base.Model):
from one script
to another script.
- All required parameters must be populated in order to send to server.
:ivar name: Display name of the language in the locale requested via Accept-Language header.
Required.
@@ -1137,14 +1116,14 @@ def __init__(
name: str,
native_name: str,
scripts: List["_models.TransliterableScript"],
- ): ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/find_sentence_boundaries_maximum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/find_sentence_boundaries_maximum_set_gen.py
new file mode 100644
index 000000000000..7d3775211149
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/find_sentence_boundaries_maximum_set_gen.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python find_sentence_boundaries_maximum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.find_sentence_boundaries(
+ body=[{"text": "How are you? I am fine. What did you do today?"}],
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/FindSentenceBoundaries_MaximumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/find_sentence_boundaries_minimum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/find_sentence_boundaries_minimum_set_gen.py
new file mode 100644
index 000000000000..62dbc432bfd0
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/find_sentence_boundaries_minimum_set_gen.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python find_sentence_boundaries_minimum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.find_sentence_boundaries(
+ body=[{"text": "How are you? I am fine. What did you do today?"}],
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/FindSentenceBoundaries_MinimumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_maximum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_maximum_set_gen.py
new file mode 100644
index 000000000000..46eb461d6c30
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_maximum_set_gen.py
@@ -0,0 +1,30 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python get_supported_languages_maximum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.get_supported_languages()
+ print(response)
+
+
+# x-ms-original-file: 3.0/GetSupportedLanguages_MaximumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_minimum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_minimum_set_gen.py
new file mode 100644
index 000000000000..0296addf3ac0
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/get_supported_languages_minimum_set_gen.py
@@ -0,0 +1,30 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python get_supported_languages_minimum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.get_supported_languages()
+ print(response)
+
+
+# x-ms-original-file: 3.0/GetSupportedLanguages_MinimumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_entries_maximum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_entries_maximum_set_gen.py
new file mode 100644
index 000000000000..f6e6f86832d8
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_entries_maximum_set_gen.py
@@ -0,0 +1,34 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python lookup_dictionary_entries_maximum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.lookup_dictionary_entries(
+ body=[{"text": "fly"}],
+ from_language="en",
+ to_language="es",
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/LookupDictionaryEntries_MaximumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_entries_minimum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_entries_minimum_set_gen.py
new file mode 100644
index 000000000000..64209c054997
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_entries_minimum_set_gen.py
@@ -0,0 +1,34 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python lookup_dictionary_entries_minimum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.lookup_dictionary_entries(
+ body=[{"text": "fly"}],
+ from_language="en",
+ to_language="es",
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/LookupDictionaryEntries_MinimumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_examples_maximum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_examples_maximum_set_gen.py
new file mode 100644
index 000000000000..ca317bc537b8
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_examples_maximum_set_gen.py
@@ -0,0 +1,34 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python lookup_dictionary_examples_maximum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.lookup_dictionary_examples(
+ body=[{"text": "fly", "translation": "volar"}],
+ from_language="en",
+ to_language="es",
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/LookupDictionaryExamples_MaximumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_examples_minimum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_examples_minimum_set_gen.py
new file mode 100644
index 000000000000..987877439087
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/lookup_dictionary_examples_minimum_set_gen.py
@@ -0,0 +1,34 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python lookup_dictionary_examples_minimum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.lookup_dictionary_examples(
+ body=[{"text": "fly", "translation": "volar"}],
+ from_language="en",
+ to_language="es",
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/LookupDictionaryExamples_MinimumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/translate_maximum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/translate_maximum_set_gen.py
new file mode 100644
index 000000000000..7f873b7fb671
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/translate_maximum_set_gen.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python translate_maximum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.translate(
+ body=[{"text": "This is a test."}],
+ to_language=["cs"],
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/Translate_MaximumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/translate_minimum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/translate_minimum_set_gen.py
new file mode 100644
index 000000000000..b814131614fe
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/translate_minimum_set_gen.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python translate_minimum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.translate(
+ body=[{"text": "This is a test."}],
+ to_language=["fmlxpuepn"],
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/Translate_MinimumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_maximum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_maximum_set_gen.py
new file mode 100644
index 000000000000..6ea6263d2c06
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_maximum_set_gen.py
@@ -0,0 +1,35 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python transliterate_maximum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.transliterate(
+ body=[{"text": "这是个测试。"}],
+ language="zh-Hans",
+ from_script="Hans",
+ to_script="Latn",
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/Transliterate_MaximumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_minimum_set_gen.py b/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_minimum_set_gen.py
new file mode 100644
index 000000000000..3807b1a35633
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_samples/transliterate_minimum_set_gen.py
@@ -0,0 +1,35 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.ai.translation.text import TextTranslationClient
+
+"""
+# PREREQUISITES
+ pip install azure-ai-translation-text
+# USAGE
+ python transliterate_minimum_set_gen.py
+"""
+
+
+def main():
+ client = TextTranslationClient(
+ endpoint="ENDPOINT",
+ )
+
+ response = client.transliterate(
+ body=[{"text": "这是个测试。"}],
+ language="zh-Hans",
+ from_script="Hans",
+ to_script="Latn",
+ )
+ print(response)
+
+
+# x-ms-original-file: 3.0/Transliterate_MinimumSet_Gen.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/translation/azure-ai-translation-text/generated_tests/conftest.py b/sdk/translation/azure-ai-translation-text/generated_tests/conftest.py
new file mode 100644
index 000000000000..d2b8a8df43e7
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_tests/conftest.py
@@ -0,0 +1,39 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+import os
+import pytest
+from dotenv import load_dotenv
+from devtools_testutils import (
+ test_proxy,
+ add_general_regex_sanitizer,
+ add_body_key_sanitizer,
+ add_header_regex_sanitizer,
+)
+
+load_dotenv()
+
+
+# For security, please avoid record sensitive identity information in recordings
+@pytest.fixture(scope="session", autouse=True)
+def add_sanitizers(test_proxy):
+ texttranslation_subscription_id = os.environ.get(
+ "TEXTTRANSLATION_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000"
+ )
+ texttranslation_tenant_id = os.environ.get("TEXTTRANSLATION_TENANT_ID", "00000000-0000-0000-0000-000000000000")
+ texttranslation_client_id = os.environ.get("TEXTTRANSLATION_CLIENT_ID", "00000000-0000-0000-0000-000000000000")
+ texttranslation_client_secret = os.environ.get(
+ "TEXTTRANSLATION_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000"
+ )
+ add_general_regex_sanitizer(regex=texttranslation_subscription_id, value="00000000-0000-0000-0000-000000000000")
+ add_general_regex_sanitizer(regex=texttranslation_tenant_id, value="00000000-0000-0000-0000-000000000000")
+ add_general_regex_sanitizer(regex=texttranslation_client_id, value="00000000-0000-0000-0000-000000000000")
+ add_general_regex_sanitizer(regex=texttranslation_client_secret, value="00000000-0000-0000-0000-000000000000")
+
+ add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]")
+ add_header_regex_sanitizer(key="Cookie", value="cookie;")
+ add_body_key_sanitizer(json_path="$..access_token", value="access_token")
diff --git a/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation.py b/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation.py
new file mode 100644
index 000000000000..a84626fdca44
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation.py
@@ -0,0 +1,85 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+import pytest
+from devtools_testutils import recorded_by_proxy
+from testpreparer import TextTranslationClientTestBase, TextTranslationPreparer
+
+
+@pytest.mark.skip("you may need to update the auto-generated test case before run it")
+class TestTextTranslation(TextTranslationClientTestBase):
+ @TextTranslationPreparer()
+ @recorded_by_proxy
+ def test_get_supported_languages(self, texttranslation_endpoint):
+ client = self.create_client(endpoint=texttranslation_endpoint)
+ response = client.get_supported_languages()
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy
+ def test_translate(self, texttranslation_endpoint):
+ client = self.create_client(endpoint=texttranslation_endpoint)
+ response = client.translate(
+ body=[{"text": "str"}],
+ to_language=["str"],
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy
+ def test_transliterate(self, texttranslation_endpoint):
+ client = self.create_client(endpoint=texttranslation_endpoint)
+ response = client.transliterate(
+ body=[{"text": "str"}],
+ language="str",
+ from_script="str",
+ to_script="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy
+ def test_find_sentence_boundaries(self, texttranslation_endpoint):
+ client = self.create_client(endpoint=texttranslation_endpoint)
+ response = client.find_sentence_boundaries(
+ body=[{"text": "str"}],
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy
+ def test_lookup_dictionary_entries(self, texttranslation_endpoint):
+ client = self.create_client(endpoint=texttranslation_endpoint)
+ response = client.lookup_dictionary_entries(
+ body=[{"text": "str"}],
+ from_language="str",
+ to_language="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy
+ def test_lookup_dictionary_examples(self, texttranslation_endpoint):
+ client = self.create_client(endpoint=texttranslation_endpoint)
+ response = client.lookup_dictionary_examples(
+ body=[{"text": "str", "translation": "str"}],
+ from_language="str",
+ to_language="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
diff --git a/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation_async.py b/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation_async.py
new file mode 100644
index 000000000000..20e359f90cc7
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_tests/test_text_translation_async.py
@@ -0,0 +1,86 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+import pytest
+from devtools_testutils.aio import recorded_by_proxy_async
+from testpreparer import TextTranslationPreparer
+from testpreparer_async import TextTranslationClientTestBaseAsync
+
+
+@pytest.mark.skip("you may need to update the auto-generated test case before run it")
+class TestTextTranslationAsync(TextTranslationClientTestBaseAsync):
+ @TextTranslationPreparer()
+ @recorded_by_proxy_async
+ async def test_get_supported_languages(self, texttranslation_endpoint):
+ client = self.create_async_client(endpoint=texttranslation_endpoint)
+ response = await client.get_supported_languages()
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy_async
+ async def test_translate(self, texttranslation_endpoint):
+ client = self.create_async_client(endpoint=texttranslation_endpoint)
+ response = await client.translate(
+ body=[{"text": "str"}],
+ to_language=["str"],
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy_async
+ async def test_transliterate(self, texttranslation_endpoint):
+ client = self.create_async_client(endpoint=texttranslation_endpoint)
+ response = await client.transliterate(
+ body=[{"text": "str"}],
+ language="str",
+ from_script="str",
+ to_script="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy_async
+ async def test_find_sentence_boundaries(self, texttranslation_endpoint):
+ client = self.create_async_client(endpoint=texttranslation_endpoint)
+ response = await client.find_sentence_boundaries(
+ body=[{"text": "str"}],
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy_async
+ async def test_lookup_dictionary_entries(self, texttranslation_endpoint):
+ client = self.create_async_client(endpoint=texttranslation_endpoint)
+ response = await client.lookup_dictionary_entries(
+ body=[{"text": "str"}],
+ from_language="str",
+ to_language="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @TextTranslationPreparer()
+ @recorded_by_proxy_async
+ async def test_lookup_dictionary_examples(self, texttranslation_endpoint):
+ client = self.create_async_client(endpoint=texttranslation_endpoint)
+ response = await client.lookup_dictionary_examples(
+ body=[{"text": "str", "translation": "str"}],
+ from_language="str",
+ to_language="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
diff --git a/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer.py b/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer.py
new file mode 100644
index 000000000000..83a74beedfe2
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer.py
@@ -0,0 +1,26 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+from azure.ai.translation.text import TextTranslationClient
+from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer
+import functools
+
+
+class TextTranslationClientTestBase(AzureRecordedTestCase):
+
+ def create_client(self, endpoint):
+ credential = self.get_credential(TextTranslationClient)
+ return self.create_client_from_credential(
+ TextTranslationClient,
+ credential=credential,
+ endpoint=endpoint,
+ )
+
+
+TextTranslationPreparer = functools.partial(
+ PowerShellPreparer, "texttranslation", texttranslation_endpoint="https://fake_texttranslation_endpoint.com"
+)
diff --git a/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer_async.py b/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer_async.py
new file mode 100644
index 000000000000..b8013a976e7c
--- /dev/null
+++ b/sdk/translation/azure-ai-translation-text/generated_tests/testpreparer_async.py
@@ -0,0 +1,20 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+from azure.ai.translation.text.aio import TextTranslationClient
+from devtools_testutils import AzureRecordedTestCase
+
+
+class TextTranslationClientTestBaseAsync(AzureRecordedTestCase):
+
+ def create_async_client(self, endpoint):
+ credential = self.get_credential(TextTranslationClient, is_async=True)
+ return self.create_client_from_credential(
+ TextTranslationClient,
+ credential=credential,
+ endpoint=endpoint,
+ )
diff --git a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_client.py b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_client.py
index 25e7004a4af7..b6e736155ff6 100644
--- a/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_client.py
+++ b/sdk/translation/azure-ai-translation-text/samples/sample_text_translation_client.py
@@ -54,6 +54,7 @@ def create_text_translation_client_with_credential():
# [END create_text_translation_client_with_credential]
return text_translator
+
def create_text_translation_client_custom_with_credential():
from azure.ai.translation.text import TextTranslationClient
from azure.core.credentials import AzureKeyCredential
@@ -66,6 +67,7 @@ def create_text_translation_client_custom_with_credential():
# [END create_text_translation_client_custom_with_credential]
return text_translator
+
def create_text_translation_client_with_cognitive_services_token():
from azure.ai.translation.text import TextTranslationClient
from azure.core.credentials import TokenCredential
@@ -79,6 +81,7 @@ def create_text_translation_client_with_cognitive_services_token():
client = TextTranslationClient(credential=credential, audience="https://api.microsofttranslator.com/")
# [END create_text_translation_client_with_cognitive_services_token]
+
def create_text_translation_client_with_entra_id_token():
from azure.ai.translation.text import TextTranslationClient
from azure.identity import DefaultAzureCredential
@@ -91,6 +94,7 @@ def create_text_translation_client_with_entra_id_token():
client = TextTranslationClient(credential=credential, region=region, resource_id=resource_id)
# [END create_text_translation_client_with_entra_id_token]
+
def create_text_translation_client_custom_with_entra_id_token():
from azure.ai.translation.text import TextTranslationClient
from azure.identity import DefaultAzureCredential
diff --git a/sdk/translation/azure-ai-translation-text/setup.py b/sdk/translation/azure-ai-translation-text/setup.py
index fd168a300310..0188bfb2d400 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 :: 5 - Production/Stable",
+ "Development Status :: 4 - Beta",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3",
diff --git a/sdk/translation/azure-ai-translation-text/tests/test_break_sentence.py b/sdk/translation/azure-ai-translation-text/tests/test_break_sentence.py
index 5ea0659a5f22..83171fe17cd1 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
@@ -21,7 +21,9 @@ def test_autodetect(self, **kwargs):
response = client.find_sentence_boundaries(body=input_text_elements)
assert response is not None
assert response[0].detected_language.language == "en"
- assert response[0].detected_language.score > 0.8 # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493
+ assert (
+ response[0].detected_language.score > 0.8
+ ) # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493
assert response[0].sent_len[0] == 11
@TextTranslationPreparer()
diff --git a/sdk/translation/azure-ai-translation-text/tests/test_break_sentence_async.py b/sdk/translation/azure-ai-translation-text/tests/test_break_sentence_async.py
index cef2c50888d3..e6a082c1ec52 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
@@ -22,7 +22,9 @@ async def test_autodetect(self, **kwargs):
response = await client.find_sentence_boundaries(body=input_text_elements)
assert response is not None
assert response[0].detected_language.language == "en"
- assert response[0].detected_language.score > 0.8 # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493
+ assert (
+ response[0].detected_language.score > 0.8
+ ) # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493
assert response[0].sent_len[0] == 11
@TextTranslationPreparer()
diff --git a/sdk/translation/azure-ai-translation-text/tests/test_translation.py b/sdk/translation/azure-ai-translation-text/tests/test_translation.py
index ba4098075df8..03eb7f6009f8 100644
--- a/sdk/translation/azure-ai-translation-text/tests/test_translation.py
+++ b/sdk/translation/azure-ai-translation-text/tests/test_translation.py
@@ -225,7 +225,7 @@ def test_profanity(self, **kwargs):
assert len(response[0].translations) == 1
assert response[0].detected_language.language == "en"
assert response[0].detected_language.score == 1
- #assert "***" in response[0].translations[0].text # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493
+ # assert "***" in response[0].translations[0].text # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493
@TextTranslationPreparer()
@recorded_by_proxy
diff --git a/sdk/translation/azure-ai-translation-text/tests/test_translation_async.py b/sdk/translation/azure-ai-translation-text/tests/test_translation_async.py
index d2bff209f6d2..97d902efdeb1 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
@@ -242,7 +242,7 @@ async def test_profanity(self, **kwargs):
assert len(response[0].translations) == 1
assert response[0].detected_language.language == "en"
assert response[0].detected_language.score == 1
- #assert "***" in response[0].translations[0].text # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493
+ # assert "***" in response[0].translations[0].text # Created bug: https://machinetranslation.visualstudio.com/MachineTranslation/_workitems/edit/164493
@TextTranslationPreparer()
@recorded_by_proxy_async
diff --git a/sdk/translation/azure-ai-translation-text/tsp-location.yaml b/sdk/translation/azure-ai-translation-text/tsp-location.yaml
index 913c42604909..dca09b3d6e4f 100644
--- a/sdk/translation/azure-ai-translation-text/tsp-location.yaml
+++ b/sdk/translation/azure-ai-translation-text/tsp-location.yaml
@@ -1,3 +1,4 @@
directory: specification/translation/Azure.AI.TextTranslation
-commit: 5656333510e6c6b8c4027c73933349f1f16a0fe6
+commit: 3480bf363db32d50e520b62e201758acf287753c
repo: Azure/azure-rest-api-specs
+additionalDirectories: