Azure SDK for Java Reference Documentation
Azure Text Translation client library for Java
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.
Use the Text Translation client library for Java 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.
Documentation
Various documentation is available to help you get started
Getting started
Prerequisites
- Java Development Kit (JDK) with version 8 or above
- Azure Subscription
- An existing Translator service or Cognitive Services resource.
Adding the package to your product
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-translation-text</artifactId>
<version>1.0.0-beta.1</version>
</dependency>
Authentication
Interaction with the service using the client library begins with creating an instance of the TextTranslationClient class. You will need an API key or TokenCredential
to instantiate a client object. For more information regarding authenticating with cognitive services, see Authenticate requests to Translator Service.
Get an API key
You can get the endpoint
, API key
and Region
from the Cognitive Services resource or Translator service resource information in the Azure Portal.
Alternatively, use the Azure CLI snippet below to get the API key from the Translator service resource.
az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>
Create a TextTranslationClient
using an API key and Region credential
Once you have the value for the API key and Region, create an AzureKeyCredential
. This will allow you to
update the API key without creating a new client.
With the value of the endpoint, AzureKeyCredential
and a Region
, you can create the TextTranslationClient:
String apiKey = System.getenv("TEXT_TRANSLATOR_API_KEY");
String region = System.getenv("TEXT_TRANSLATOR_API_REGION");
AzureKeyCredential credential = new AzureKeyCredential(apiKey);
TextTranslationClient client = new TextTranslationClientBuilder()
.credential(credential)
.region(region)
.buildClient();
Key concepts
TextTranslationClient
and TextTranslationAsyncClient
A TextTranslationClient
is the primary interface for developers using the Text Translator client library. It provides both synchronous operations to access a specific use of text translator, such as get supported languages detection or text translation.
For asynchronous operations use TextTranslationAsyncClient
.
Input
A text element (InputTextItem
), is a single unit of input to be processed by the translation models in the Translator service. Operations on TextTranslationClient
may take a single text element or a collection of text elements.
For text element length limits, maximum requests size, and supported text encoding see here.
Examples
The following section provides several code snippets using the client
created above, and covers the main features present in this client library. Although most of the snippets below make use of asynchronous service calls, keep in mind that the Azure.AI.Translation.Text
package supports both synchronous and asynchronous APIs.
Get Supported Languages
Gets the set of languages currently supported by other operations of the Translator.
GetLanguagesResult languages = client.getLanguages();
System.out.println("Number of supported languages for translate operation: " + languages.getTranslation().size() + ".");
System.out.println("Number of supported languages for transliterate operation: " + languages.getTransliteration().size() + ".");
System.out.println("Number of supported languages for dictionary operations: " + languages.getDictionary().size() + ".");
System.out.println("Translation Languages:");
for (Map.Entry<String, TranslationLanguage> translationLanguage : languages.getTranslation().entrySet()) {
System.out.println(translationLanguage.getKey() + " -- name: " + translationLanguage.getValue().getName() + " (" + translationLanguage.getValue().getNativeName() + ")");
}
System.out.println("Transliteration Languages:");
for (Map.Entry<String, TransliterationLanguage> transliterationLanguage : languages.getTransliteration().entrySet()) {
System.out.println(transliterationLanguage.getKey() + " -- name: " + transliterationLanguage.getValue().getName() + ", supported script count: " + transliterationLanguage.getValue().getScripts().size());
}
System.out.println("Dictionary Languages:");
for (Map.Entry<String, SourceDictionaryLanguage> dictionaryLanguage : languages.getDictionary().entrySet()) {
System.out.println(dictionaryLanguage.getKey() + " -- name: " + dictionaryLanguage.getValue().getName() + ", supported target languages count: " + dictionaryLanguage.getValue().getTranslations().size());
}
Please refer to the service documentation for a conceptual discussion of languages.
Translate
Renders single source-language text to multiple target-language texts with a single request.
String from = "en";
List<String> targetLanguages = new ArrayList<>();
targetLanguages.add("cs");
List<InputTextItem> content = new ArrayList<>();
content.add(new InputTextItem("This is a test."));
List<TranslatedTextItem> translations = client.translate(targetLanguages, content, null, from, TextType.PLAIN, null, ProfanityAction.NO_ACTION, ProfanityMarker.ASTERISK, false, false, null, null, null, false);
for (TranslatedTextItem translation : translations) {
for (Translation textTranslation : translation.getTranslations()) {
System.out.println("Text was translated to: '" + textTranslation.getTo() + "' and the result is: '" + textTranslation.getText() + "'.");
}
}
Please refer to the service documentation for a conceptual discussion of translate.
Transliterate
Converts characters or letters of a source language to the corresponding characters or letters of a target language.
String language = "zh-Hans";
String fromScript = "Hans";
String toScript = "Latn";
List<InputTextItem> content = new ArrayList<>();
content.add(new InputTextItem("这是个测试。"));
List<TransliteratedText> transliterations = client.transliterate(language, fromScript, toScript, content);
for (TransliteratedText transliteration : transliterations) {
System.out.println("Input text was transliterated to '" + transliteration.getScript() + "' script. Transliterated text: '" + transliteration.getText() + "'.");
}
Please refer to the service documentation for a conceptual discussion of transliterate.
Break Sentence
Identifies the positioning of sentence boundaries in a piece of text.
String sourceLanguage = "zh-Hans";
String sourceScript = "Latn";
List<InputTextItem> content = new ArrayList<>();
content.add(new InputTextItem("zhè shì gè cè shì。"));
List<BreakSentenceItem> breakSentences = client.findSentenceBoundaries(content, null, sourceLanguage, sourceScript);
for (BreakSentenceItem breakSentence : breakSentences) {
System.out.println("The detected sentence boundaries: " + breakSentence.getSentLen());
}
Please refer to the service documentation for a conceptual discussion of break sentence.
Dictionary Lookup
Returns equivalent words for the source term in the target language.
String sourceLanguage = "en";
String targetLanguage = "es";
List<InputTextItem> content = new ArrayList<>();
content.add(new InputTextItem("fly"));
List<DictionaryLookupItem> dictionaryEntries = client.lookupDictionaryEntries(sourceLanguage, targetLanguage, content);
for (DictionaryLookupItem dictionaryEntry : dictionaryEntries) {
System.out.println("For the given input " + dictionaryEntry.getTranslations().size() + " entries were found in the dictionary.");
System.out.println("First entry: '" + dictionaryEntry.getTranslations().get(0).getDisplayTarget() + "', confidence: " + dictionaryEntry.getTranslations().get(0).getConfidence());
}
Please refer to the service documentation for a conceptual discussion of dictionary lookup.
Dictionary Examples
Returns grammatical structure and context examples for the source term and target term pair.
String sourceLanguage = "en";
String targetLanguage = "es";
List<DictionaryExampleTextItem> content = new ArrayList<>();
content.add(new DictionaryExampleTextItem("fly", "volar"));
List<DictionaryExampleItem> dictionaryEntries = client.lookupDictionaryExamples(sourceLanguage, targetLanguage, content);
for (DictionaryExampleItem dictionaryEntry : dictionaryEntries) {
System.out.println("For the given input " + dictionaryEntry.getExamples().size() + " entries were found in the dictionary.");
System.out.println("Example: '" + dictionaryEntry.getExamples().get(0).getTargetPrefix() + dictionaryEntry.getExamples().get(0).getTargetTerm() + dictionaryEntry.getExamples().get(0).getTargetSuffix());
}
Please refer to the service documentation for a conceptual discussion of dictionary examples.
Troubleshooting
When 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, a 400
error is returned, indicating "Bad Request".
Next steps
Samples showing how to use this client library are available in this GitHub repository. Samples are provided for each main functional area, and for each area, samples are provided in both sync and async mode.
- Translation
- Translation with Language Detection
- Handling Profanities in Translation
- Translation to multiple languages
- Translation of multiple sources
- Translation and Transliteration
- Using Custom Translation Model
- Translation with Custom Dictionary
- Translation with NoTranslate tag
- Translation with Alignments
- Translation with Sentence Boundaries
- Handling translation of HTML text
- Transliteration
- Get Languages
- Get Localized Languages
- Get Scoped Languages
- Find Sentence Boundaries
- Lookup Dictionary Examples
- Lookup Dictionary Entries
Contributing
For details on contributing to this repository, see the contributing guide.
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request