Microsoft Azure Text Translation SDK now in Public Preview
Published May 23 2023 09:00 AM 3,009 Views
Microsoft

The Azure Text Translation SDK is a cloud-based REST API feature of the Translator service that uses neural machine translation. It enables quick and accurate source-to-target text translation across all supported languages in real-time. The SDK simplifies the developer experience and reduces the need to assimilate API definitions.

 

The Azure Text Translation SDK offers several key benefits for developers, including-

- Quick and accurate translations in real-time across all supported languages.

- Easy to integrate with your application or workflow.

- Customization options for your specific needs.

- Scalable in handling a large volume of text for translation.

 

The client libraries provided in the section below enable developers to

  • Return a list of languages supported by Translate, Transliterate, and Dictionary operations.
  • Render a single source-language text to multiple target languages in a single request.
  • Convert text of a source language to different scripts.
  • Return equivalent words for the source term in the target language.

Client Libraries and details

We are now announcing the public previews for client libraries across .NET, Java, JavaScript, and Python. But before we dive in let's take a quick look at some of the key concepts.

 

Key concepts

 

TextTranslationClient

A TextTranslationClient is a primary interface for developers using the Text Translation client library. It provides both synchronous and asynchronous operations to make calls, such as getting supported languages and translating text.

 

Input

A text element (string) 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 refer to https://learn.microsoft.com/azure/cognitive-services/translator/request-limits 

 

Return value

Return values, such as Response<IReadOnlyList<TranslatedTextItem>>, result from a Text Translation operation. It contains an array with one result for each string in the input array. A request return value also may include additional information about the input text element (for example source language when auto-detect is used).

 

Thread safety

 

Typically, all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is safe, even across threads.

 

Additional concepts

Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime

 

Getting started with .NET

The following section provides several code snippets for a specific user scenario 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 Azure. AI.Translation.Text package supports both synchronous and asynchronous APIs.

 

Scenario

As a developer for a retail company, say your goal is to localize content in a product catalog. In this case, the company wants to expand its global reach and therefore sell products in multiple markets. As a developer solving this business case, you will need to ensure that the product descriptions and other content are translated accurately and appropriately for each language the market supports. Moreover, there could be a requirement for some product names in the catalog to remain as-is or be presented differently in the target language.  Text translation SDK provides the capability to enable this business scenario. Follow the steps below to develop your solution.

 

Prerequisites Completion

You need an active Azure subscription and an existing or new Translator service / Cognitive service resource to request translations from our general domain. You can follow the instructions in our online documentation to successfully create an Azure translator resource. You can also use create a Cognitive Services resource using the Azure CLI to create the cognitive resources using the Azure CLI.

 

Note - Text translation supports resource creation for multi-service and single-service access. Create a Cognitive Services resource if you plan to access multiple Cognitive Services under a single endpoint and API key. To access the features of the Text translation service only, create a Text translation service resource.

 

Authenticate the client

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 authentication options 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.

Create a Text Translation Client

Firstly, install the package the Azure Text Translation client library for .NET with NuGet

 

 

 

dotnet add package Azure.AI.Translation.Text –prerelease

 

 

Create a TextTranslationClient using an API key from the Global Text Translator resource.

Once you have the value for the API key, create an AzureKeyCredential. With the value of the AzureKeyCredential, you can create the TextTranslationClient

 

 

 

 

AzureKeyCredential credential = new("<apiKey>");
TextTranslationClient client = new(credential);

 

 

 

Replace <apiKey> with a value created in Creating Cognitive Services resource.

 

There are also other ways to create a text translation client such as using -  

  • API key and Region credential
  • Custom Subdomain and API Key
  • Token Authentication

For How-to, refer to creating a Text Translation client.

 

Translate

Once you have set up the Text translation client, we can now complete the localization use case by translating the input product catalog text into various languages. For this use case, let’s look at an example code on how to translate text into multiple target languages. You can provide multiple target languages which results in the input element being translated to all those target languages. You can specify the input text language or let the service auto-detect it. 

 

 

try
{
    IEnumerable<string> targetLanguages = new[] { "cs", "es", "de"};
    IEnumerable<string> inputTextElements = new[]
    {
        "This is a test."
    };

    Response<IReadOnlyList<TranslatedTextItem>> response = await client.TranslateAsync(targetLanguages, inputTextElements).ConfigureAwait(false);
    IReadOnlyList<TranslatedTextItem> translations = response.Value;

    foreach (TranslatedTextItem translation in translations)
    {
        Console.WriteLine($"Detected languages of the input text: {translation?.DetectedLanguage?.Language} with score: {translation?.DetectedLanguage?.Score}.");

        Console.WriteLine($"Text was translated to: '{translation?.Translations?.FirstOrDefault().To}' and the result is: '{translation?.Translations?.FirstOrDefault()?.Text}'.");
    }
}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

 

 

 

You now have a working Text translation client!

 

Note - For the above product catalog localization use-case, the translation workflow can also include Transliterating certain product names or validating if the target language is supported (supported languages). More capabilities can be leveraged depending on the intended translation scenarios. 

 

Other capabilities are listed below for your reference:

  • Translate Text
  • Translate with Auto detection of input text language.
  • Translate with transliteration.
  • Translate multiple text inputs
  • Translate multiple target languages
  • Translate different text types.
  • Non-Translation of Entities names in a text
  • Apply dictionary for a specific entity name in a text
  • Profanity handling
  • Include alignment in translation (some languages supported for research)
  • Translate using sentence length
  • Translate with your custom models. 

You can learn more about them in Translate text samples.

 

Dictionary Lookup

Once you have a working text translation client that can detect the language of the input text and translate it across multiple languages, you might need to ensure that certain product names in the catalog are accurately returned for the target language. To achieve this, we can leverage the dictionary lookup.

 

 

 

 

try
{
    string sourceLanguage = "en";
    string targetLanguage = "es";
    IEnumerable<string> inputTextElements = new[]
    {
        "fly"
    };

    Response<IReadOnlyList<DictionaryLookupItem>> response = await client.LookupDictionaryEntriesAsync(sourceLanguage, targetLanguage, inputTextElements).ConfigureAwait(false);
    IReadOnlyList<DictionaryLookupItem> dictionaryEntries = response.Value;
    DictionaryLookupItem dictionaryEntry = dictionaryEntries.FirstOrDefault();

    Console.WriteLine($"For the given input {dictionaryEntry?.Translations?.Count} entries were found in the dictionary.");
    Console.WriteLine($"First entry: '{dictionaryEntry?.Translations?.FirstOrDefault()?.DisplayTarget}', confidence: {dictionaryEntry?.Translations?.FirstOrDefault()?.Confidence}.");

}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

 

 

 

 

You have now completed the localization use case for a retail client involving the translation of product catalog entities to multiple Target languages. However, while doing so you also ensured that for certain specific product names, you adhered to the business pre-determined translation via Dictionary lookup.

 

Other Client Libraries

The same use case above can be implemented in Python, JavaScript, and Java apart from .Net.  You can use the respective SDKs to bootstrap your development.

 

In summary, the Microsoft Azure Text Translation SDK is a powerful tool that allows developers to easily add text translation capabilities to their applications. With support for multiple languages to meet your market need, an easy-to-use API, and scalable cloud infrastructure, the SDK offers a range of benefits for developers looking to integrate text translation capabilities into their business solutions.

Following the steps outlined in this post, developers can quickly get started with the Azure Text Translation SDK to build translation solutions that reflect their business, industry, and domain-specific terminology and style. These solutions seamlessly integrate into your existing applications, workflows, and websites.

 

 

 

Version history
Last update:
‎May 22 2023 10:35 PM
Updated by: