Package: azure-ai-translation-text
Azure Text Translation client library for PythonText 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.Use the Text Translation client library for Python to:Return a list of languages supported by Translate, Transliterate, and Dictionary operations.Render single source-language text to multiple target-language texts with a single request.Convert text of a source language in letters of a different script.Return equivalent words for the source term in the target language.Return grammatical structure and context examples for the source term and target term pair.Source code|Package (PyPI)|API reference documentation|Product documentation|SamplesGetting startedPrerequisitesPython 3.7 or later is required to use this package.An existing Translator service or Cognitive Services resource.Install the packageInstall the Azure Text Translation client library for Python withpip:pipinstallazure-ai-translation-textCreate a Translator service resourceYou can create Translator resource followingCreate a Translator resource.Authenticate the clientInteraction with the service using the client library begins with creating an instance of theTextTranslationClientclass. You will need anAPI keyorTokenCredentialto instantiate a client object. For more information regarding authenticating with cognitive services, seeAuthenticate requests to Translator Service.Get an API keyYou can get theendpoint,API keyandRegionfrom the Cognitive Services resource or Translator service resource information in theAzure Portal.Alternatively, use theAzure CLIsnippet below to get the API key from the Translator service resource.azcognitiveservicesaccountkeyslist--resource-group<your-resource-group-name>--name<your-resource-name>Create aTextTranslationClientusing an API key and Region credentialOnce you have the value for the API key and Region, create anTranslatorCredential. This will allow you to
update the API key without creating a new client.With the value of the endpoint,TranslatorCredentialand aRegion, you can create theTextTranslationClient:text_translator=TextTranslationClient(credential=TranslatorCredential("<apiKey>","<apiRegion>"));Key conceptsTextTranslationClientATextTranslationClientis the primary interface for developers using the Text Translation client library.  It provides both synchronous and asynchronous operations to access a specific use of text translator, such as get supported languages detection or text translation.InputAtext element(string), is a single unit of input to be processed by the translation models in the Translator service. Operations onTextTranslationClientmay take a single text element or a collection of text elements.
For text element length limits, maximum requests size, and supported text encoding seehere.ExamplesThe following section provides several code snippets using theclientcreated above, and covers the main features present in this client library. Although most of the snippets below make use of synchronous service calls, keep in mind that the Text Translation for Python library package supports both synchronous and asynchronous APIs.Get Supported LanguagesGets the set of languages currently supported by other operations of the Translator.try:response=text_translator.get_languages()print(f"Number of supported languages for translate operation:{len(response.translation)ifresponse.translationisnotNoneelse0}")print(f"Number of supported languages for transliterate operation:{len(response.transliteration)ifresponse.transliterationisnotNoneelse0}")print(f"Number of supported languages for dictionary operations:{len(response.dictionary)ifresponse.dictionaryisnotNoneelse0}")ifresponse.translationisnotNone:print("Translation Languages:")forkey,valueinresponse.translation.items():print(f"{key}-- name:{value.name}({value.native_name})")ifresponse.transliterationisnotNone:print("Transliteration Languages:")forkey,valueinresponse.transliteration.items():print(f"{key}-- name:{value.name}, supported script count:{len(value.scripts)}")ifresponse.dictionaryisnotNone:print("Dictionary Languages:")forkey,valueinresponse.dictionary.items():print(f"{key}-- name:{value.name}, supported target languages count:{len(value.translations)}")exceptHttpResponseErrorasexception:print(f"Error Code:{exception.error.code}")print(f"Message:{exception.error.message}")For samples on using thelanguagesendpoint refer to more sampleshere.Please refer to the service documentation for a conceptual discussion oflanguages.TranslateRenders single source-language text to multiple target-language texts with a single request.try:source_language="en"target_languages=["cs"]input_text_elements=[InputTextItem(text="This is a test")]response=text_translator.translate(content=input_text_elements,to=target_languages,from_parameter=source_language)translation=response[0]ifresponseelseNoneiftranslation:fortranslated_textintranslation.translations:print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")exceptHttpResponseErrorasexception:print(f"Error Code:{exception.error.code}")print(f"Message:{exception.error.message}")For samples on using thetranslateendpoint refer to more sampleshere.Please refer to the service documentation for a conceptual discussion oftranslate.TransliterateConverts characters or letters of a source language to the corresponding characters or letters of a target language.try:language="zh-Hans"from_script="Hans"to_script="Latn"input_text_elements=[InputTextItem(text="这是个测试。")]response=text_translator.transliterate(content=input_text_elements,language=language,from_script=from_script,to_script=to_script)transliteration=response[0]ifresponseelseNoneiftransliteration:print(f"Input text was transliterated to '{transliteration.script}' script. Transliterated text: '{transliteration.text}'.")exceptHttpResponseErrorasexception:print(f"Error Code:{exception.error.code}")print(f"Message:{exception.error.message}")For samples on using thetransliterateendpoint refer to more sampleshere.Please refer to the service documentation for a conceptual discussion oftransliterate.Break SentenceIdentifies the positioning of sentence boundaries in a piece of text.try:source_language="zh-Hans"source_script="Latn"input_text_elements=[InputTextItem(text="zhè shì gè cè shì。")]response=text_translator.find_sentence_boundaries(content=input_text_elements,language=source_language,script=source_script)sentence_boundaries=response[0]ifresponseelseNoneifsentence_boundaries:detected_language=sentence_boundaries.detected_languageifdetected_language:print(f"Detected languages of the input text:{detected_language.language}with score:{detected_language.score}.")print(f"The detected sentence boundaries:")forboundaryinsentence_boundaries.sent_len:print(boundary)exceptHttpResponseErrorasexception:print(f"Error Code:{exception.error.code}")print(f"Message:{exception.error.message}")For samples on using thebreak sentenceendpoint refer to more sampleshere.Please refer to the service documentation for a conceptual discussion ofbreak sentence.Dictionary LookupReturns equivalent words for the source term in the target language.try:source_language="en"target_language="es"input_text_elements=[InputTextItem(text="fly")]response=text_translator.lookup_dictionary_entries(content=input_text_elements,from_parameter=source_language,to=target_language)dictionary_entry=response[0]ifresponseelseNoneifdictionary_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}.")exceptHttpResponseErrorasexception:print(f"Error Code:{exception.error.code}")print(f"Message:{exception.error.message}")For samples on using thedictionary lookupendpoint refer to more sampleshere.Please refer to the service documentation for a conceptual discussion ofdictionary lookup.Dictionary ExamplesReturns grammatical structure and context examples for the source term and target term pair.fromazure.ai.translation.text.modelsimportDictionaryExampleTextItemtry:source_language="en"target_language="es"input_text_elements=[DictionaryExampleTextItem(text="fly",translation="volar")]response=text_translator.lookup_dictionary_examples(content=input_text_elements,from_parameter=source_language,to=target_language)dictionary_entry=response[0]ifresponseelseNoneifdictionary_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}'.")exceptHttpResponseErrorasexception:print(f"Error Code:{exception.error.code}")print(f"Message:{exception.error.message}")For samples on using thedictionary examplesendpoint refer to more sampleshere.Please refer to the service documentation for a conceptual discussion ofdictionary examples.TroubleshootingWhen you interact with the Translator Service using the TextTranslator client library, errors returned by the Translator service correspond to the same HTTP status codes returned for REST API requests.For example, if you submit a translation request without a target translate language, a400error is returned, indicating "Bad Request".You can find the different error codes returned by the service in theService Documentation.Provide FeedbackIf you encounter any bugs or have suggestions, please file an issue in theIssuessection of the project.Next stepsMore samples can be found under thesamplesdirectory.ContributingThis project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visitcla.microsoft.com.When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.This project has adopted theMicrosoft Open Source Code of Conduct. For more information see theCode of Conduct FAQor contactopencode@microsoft.comwith any additional questions or comments.Release History1.0.0b1 (2023-04-19)Initial Release