Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -633,7 +633,7 @@ def _deserialize(cls, data, exist_discriminators):
discriminator_value = data.find(xml_name).text # pyright: ignore
else:
discriminator_value = data.get(discriminator._rest_name)
mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore
mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member
return mapped_cls._deserialize(data, exist_discriminators)

def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]:
Expand Down
7 changes: 6 additions & 1 deletion sdk/translation/azure-ai-translation-text/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# Release History

## 1.0.2 (Unreleased)
## 2.0.0b1 (Unreleased)

### Features Added

- Added support for the latest Azure AI Translator API, including translations using LLM models, adaptive custom translations, tone variant translations, and gender-specific language translations.

### Breaking Changes

- Dictionary, sentence boundaries and text alignments features have been removed, and relevant models and properties have been removed.
-

### Bugs Fixed

### Other Changes
Expand Down
2 changes: 1 addition & 1 deletion sdk/translation/azure-ai-translation-text/MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ recursive-include tests *.py
recursive-include samples *.py *.md
include azure/__init__.py
include azure/ai/__init__.py
include azure/ai/translation/__init__.py
include azure/ai/translation/__init__.py
124 changes: 5 additions & 119 deletions sdk/translation/azure-ai-translation-text/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ try:
f"Number of supported languages for transliterate operation: {len(response.transliteration) if response.transliteration is not None else 0}"
)
print(
f"Number of supported languages for dictionary operations: {len(response.dictionary) if response.dictionary is not None else 0}"
f"Number of supported models for translation: {len(response.models) if response.models is not None else 0}"
)

if response.translation is not None:
Expand All @@ -114,10 +114,8 @@ try:
for key, value in response.transliteration.items():
print(f"{key} -- name: {value.name}, supported script count: {len(value.scripts)}")

if response.dictionary is not None:
print("Dictionary Languages:")
for key, value in response.dictionary.items():
print(f"{key} -- name: {value.name}, supported target languages count: {len(value.translations)}")
if response.models is not None:
print(f"Models: {', '.join(response.models)}")

except HttpResponseError as exception:
if exception.error is not None:
Expand Down Expand Up @@ -153,7 +151,7 @@ try:
f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
)
for translated_text in translation.translations:
print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")
print(f"Text was translated to: '{translated_text.language}' and the result is: '{translated_text.text}'.")

except HttpResponseError as exception:
if exception.error is not None:
Expand All @@ -163,7 +161,6 @@ except HttpResponseError as exception:

<!-- END SNIPPET -->


For samples on using the `translate` endpoint refer to more samples [here][translate_sample].

Please refer to the service documentation for a conceptual discussion of [translate][translate_doc].
Expand Down Expand Up @@ -202,122 +199,11 @@ except HttpResponseError as exception:
```

<!-- END SNIPPET -->

For samples on using the `transliterate` endpoint refer to more samples [here][transliterate_sample].

Please refer to the service documentation for a conceptual discussion of [transliterate][transliterate_doc].

### Break Sentence

Identifies the positioning of sentence boundaries in a piece of text.

<!-- SNIPPET: sample_text_translation_translate.get_text_translation_sentence_length -->

```python
try:
include_sentence_length = True
to_language = ["cs"]
input_text_elements = ["The answer lies in machine translation. This is a test."]

response = text_translator.translate(
body=input_text_elements, to_language=to_language, include_sentence_length=include_sentence_length
)
translation = response[0] if response else None

if translation:
detected_language = translation.detected_language
if detected_language:
print(
f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
)
for translated_text in translation.translations:
print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")
if translated_text.sent_len:
print(f"Source Sentence length: {translated_text.sent_len.src_sent_len}")
print(f"Translated Sentence length: {translated_text.sent_len.trans_sent_len}")

except HttpResponseError as exception:
if exception.error is not None:
print(f"Error Code: {exception.error.code}")
print(f"Message: {exception.error.message}")
```

<!-- END SNIPPET -->

For samples on using the `break sentence` endpoint refer to more samples [here][breaksentence_sample].

Please refer to the service documentation for a conceptual discussion of [break sentence][breaksentence_doc].

### Dictionary Lookup

Returns equivalent words for the source term in the target language.

<!-- SNIPPET: sample_text_translation_dictionary_lookup.get_text_translation_dictionary_lookup -->

```python
try:
from_language = "en"
to_language = "es"
input_text_elements = ["fly"]

response = text_translator.lookup_dictionary_entries(
body=input_text_elements, from_language=from_language, to_language=to_language
)
dictionary_entry = response[0] if response else None

if dictionary_entry:
print(f"For the given input {len(dictionary_entry.translations)} entries were found in the dictionary.")
print(
f"First entry: '{dictionary_entry.translations[0].display_target}', confidence: {dictionary_entry.translations[0].confidence}."
)

except HttpResponseError as exception:
if exception.error is not None:
print(f"Error Code: {exception.error.code}")
print(f"Message: {exception.error.message}")
raise
```

<!-- END SNIPPET -->

For samples on using the `dictionary lookup` endpoint refer to more samples [here][dictionarylookup_sample].

Please refer to the service documentation for a conceptual discussion of [dictionary lookup][dictionarylookup_doc].

### Dictionary Examples

Returns grammatical structure and context examples for the source term and target term pair.

<!-- SNIPPET: sample_text_translation_dictionary_examples.get_text_translation_dictionary_examples -->

```python
try:
from_language = "en"
to_language = "es"
input_text_elements = [DictionaryExampleTextItem(text="fly", translation="volar")]

response = text_translator.lookup_dictionary_examples(
body=input_text_elements, from_language=from_language, to_language=to_language
)
dictionary_entry = response[0] if response else None

if dictionary_entry:
print(f"For the given input {len(dictionary_entry.examples)} entries were found in the dictionary.")
print(
f"First example: '{dictionary_entry.examples[0].target_prefix}{dictionary_entry.examples[0].target_term}{dictionary_entry.examples[0].target_suffix}'."
)

except HttpResponseError as exception:
if exception.error is not None:
print(f"Error Code: {exception.error.code}")
print(f"Message: {exception.error.message}")
raise
```

<!-- END SNIPPET -->

For samples on using the `dictionary examples` endpoint refer to more samples [here][dictionaryexamples_sample].

Please refer to the service documentation for a conceptual discussion of [dictionary examples][dictionaryexamples_doc].

## Troubleshooting

Expand Down
3 changes: 3 additions & 0 deletions sdk/translation/azure-ai-translation-text/_metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"apiVersion": "2025-10-01-preview"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"CrossLanguagePackageId": "TextTranslation",
"CrossLanguageDefinitionId": {
"azure.ai.translation.text.models.DetectedLanguage": "TextTranslation.DetectedLanguage",
"azure.ai.translation.text.models.ErrorDetails": "TextTranslation.ErrorDetails",
"azure.ai.translation.text.models.ErrorResponse": "TextTranslation.ErrorResponse",
"azure.ai.translation.text.models.GetSupportedLanguagesResult": "TextTranslation.GetSupportedLanguagesResult",
"azure.ai.translation.text.models.InputTextItem": "TextTranslation.InputTextItem",
"azure.ai.translation.text.models.LanguageScript": "TextTranslation.LanguageScript",
"azure.ai.translation.text.models.ReferenceTextPair": "TextTranslation.ReferenceTextPair",
"azure.ai.translation.text.models.TranslateBody": "TextTranslation.TranslateBody",
"azure.ai.translation.text.models.TranslatedTextItem": "TextTranslation.TranslatedTextItem",
"azure.ai.translation.text.models.TranslateInputItem": "TextTranslation.TranslateInputItem",
"azure.ai.translation.text.models.TranslationLanguage": "TextTranslation.TranslationLanguage",
"azure.ai.translation.text.models.TranslationResult": "TextTranslation.TranslationResult",
"azure.ai.translation.text.models.TranslationTarget": "TextTranslation.TranslationTarget",
"azure.ai.translation.text.models.TranslationText": "TextTranslation.TranslationText",
"azure.ai.translation.text.models.TransliterableScript": "TextTranslation.TransliterableScript",
"azure.ai.translation.text.models.TransliterateBody": "TextTranslation.TransliterateBody",
"azure.ai.translation.text.models.TransliteratedText": "TextTranslation.TransliteratedText",
"azure.ai.translation.text.models.TransliterateResult": "TextTranslation.TransliterateResult",
"azure.ai.translation.text.models.TransliterationLanguage": "TextTranslation.TransliterationLanguage",
"azure.ai.translation.text.models.LanguageDirectionality": "TextTranslation.LanguageDirectionality",
"azure.ai.translation.text.models.TextType": "TextTranslation.TextType",
"azure.ai.translation.text.models.ProfanityAction": "TextTranslation.ProfanityAction",
"azure.ai.translation.text.models.ProfanityMarker": "TextTranslation.ProfanityMarker",
"azure.ai.translation.text.TextTranslationClient.get_supported_languages": "TextTranslation.getSupportedLanguages",
"azure.ai.translation.text.aio.TextTranslationClient.get_supported_languages": "TextTranslation.getSupportedLanguages",
"azure.ai.translation.text.TextTranslationClient.translate": "TextTranslation.translate",
"azure.ai.translation.text.aio.TextTranslationClient.translate": "TextTranslation.translate",
"azure.ai.translation.text.TextTranslationClient.transliterate": "TextTranslation.transliterate",
"azure.ai.translation.text.aio.TextTranslationClient.transliterate": "TextTranslation.transliterate"
}
}
2 changes: 1 addition & 1 deletion sdk/translation/azure-ai-translation-text/assets.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "python",
"TagPrefix": "python/translation/azure-ai-translation-text",
"Tag": "python/translation/azure-ai-translation-text_35ab9367d7"
"Tag": "python/translation/azure-ai-translation-text_8d7a749482"
}
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,18 @@

from copy import deepcopy
from typing import Any
from typing_extensions import Self

from azure.core import PipelineClient
from azure.core.pipeline import policies
from azure.core.rest import HttpRequest, HttpResponse

from ._configuration import TextTranslationClientConfiguration
from ._operations import TextTranslationClientOperationsMixin
from ._serialization import Deserializer, Serializer
from ._operations import _TextTranslationClientOperationsMixin
from ._utils.serialization import Deserializer, Serializer


class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword
class TextTranslationClient(_TextTranslationClientOperationsMixin):
"""Text translation is a cloud-based REST API feature of the Translator service that uses neural
machine translation technology to enable quick and accurate source-to-target text translation
in real time across all supported languages.
Expand All @@ -37,16 +38,12 @@ class TextTranslationClient(TextTranslationClientOperationsMixin): # pylint: di
Detect. Returns the source code language code and a boolean variable denoting whether the
detected language is supported for text translation and transliteration.

Dictionary lookup. Returns equivalent words for the source term in the target language.

Dictionary example Returns grammatical structure and context examples for the source term and
target term pair.

:param endpoint: Supported Text Translation endpoints (protocol and hostname, for example:
https://api.cognitive.microsofttranslator.com). Required.
`https://api.cognitive.microsofttranslator.com
<https://api.cognitive.microsofttranslator.com>`_). Required.
:type endpoint: str
:keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that
overriding this default value may result in unsupported behavior.
:keyword api_version: Mandatory API version parameter. Default value is "2025-10-01-preview".
Note that overriding this default value may result in unsupported behavior.
:paramtype api_version: str
"""

Expand All @@ -55,6 +52,7 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential
) -> None:
_endpoint = "{Endpoint}"
self._config = TextTranslationClientConfiguration(endpoint=endpoint, **kwargs)

_policies = kwargs.pop("policies", None)
if _policies is None:
_policies = [
Expand Down Expand Up @@ -107,7 +105,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs:
def close(self) -> None:
self._client.close()

def __enter__(self) -> "TextTranslationClient":
def __enter__(self) -> Self:
self._client.__enter__()
return self

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,23 @@
from ._version import VERSION


class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long
class TextTranslationClientConfiguration: # pylint: disable=too-many-instance-attributes
"""Configuration for TextTranslationClient.

Note that all parameters used to create this instance are saved as instance
attributes.

:param endpoint: Supported Text Translation endpoints (protocol and hostname, for example:
https://api.cognitive.microsofttranslator.com). Required.
`https://api.cognitive.microsofttranslator.com
<https://api.cognitive.microsofttranslator.com>`_). Required.
:type endpoint: str
:keyword api_version: Mandatory API version parameter. Default value is "3.0". Note that
overriding this default value may result in unsupported behavior.
:keyword api_version: Mandatory API version parameter. Default value is "2025-10-01-preview".
Note that overriding this default value may result in unsupported behavior.
:paramtype api_version: str
"""

def __init__(self, endpoint: str, **kwargs: Any) -> None:
api_version: str = kwargs.pop("api_version", "3.0")
api_version: str = kwargs.pop("api_version", "2025-10-01-preview")

if endpoint is None:
raise ValueError("Parameter 'endpoint' must not be None.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -667,7 +667,7 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915,
except AttributeError:
model_name = annotation
if module is not None:
annotation = _get_model(module, model_name)
annotation = _get_model(module, model_name) # type: ignore

try:
if module and _is_model(annotation):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,19 @@
# 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 ._patch import patch_sdk as _patch_sdk
from ._operations import _TextTranslationClientOperationsMixin # type: ignore # pylint: disable=unused-import

__all__ = [
"TextTranslationClientOperationsMixin",
]
from ._patch import __all__ as _patch_all
from ._patch import *
from ._patch import patch_sdk as _patch_sdk

__all__ = []
__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
Loading
Loading