Delen via


Azure Text Translation client library for .NET - version 1.0.0-beta.1

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 .NET 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 | API reference documentation | Product documentation

Getting started

Install the package

Install the Azure Text Translation client library for .NET with NuGet:

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

This table shows the relationship between SDK versions and supported API versions of the service:

SDK version Supported API version of service
1.0.0-beta.1 3.0

Prerequisites

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 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:

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

Key concepts

TextTranslationClient

A TextTranslationClient is 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.

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 see here.

Return value

Return values, such as Response<IReadOnlyList<TranslatedTextItem>>, is the result of a Text Translation operation, It contains array with one result for each string in the input array. An operation's return value also may optionally include information about the input text element (for example detected language).

Thread safety

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

Additional concepts

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

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.

try
{
    Response<GetLanguagesResult> response = await client.GetLanguagesAsync(cancellationToken: CancellationToken.None).ConfigureAwait(false);
    GetLanguagesResult languages = response.Value;

    Console.WriteLine($"Number of supported languages for translate operations: {languages.Translation.Count}.");
}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

For samples on using the languages endpoint refer to more samples here.

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.

try
{
    string targetLanguage = "cs";
    string inputText = "This is a test.";

    Response<IReadOnlyList<TranslatedTextItem>> response = await client.TranslateAsync(targetLanguage, inputText).ConfigureAwait(false);
    IReadOnlyList<TranslatedTextItem> translations = response.Value;
    TranslatedTextItem translation = translations.FirstOrDefault();

    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}");
}

For samples on using the translate endpoint refer to more samples here.

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.

try
{
    string language = "zh-Hans";
    string fromScript = "Hans";
    string toScript = "Latn";

    string inputText = "这是个测试。";

    Response<IReadOnlyList<TransliteratedText>> response = await client.TransliterateAsync(language, fromScript, toScript, inputText).ConfigureAwait(false);
    IReadOnlyList<TransliteratedText> transliterations = response.Value;
    TransliteratedText transliteration = transliterations.FirstOrDefault();

    Console.WriteLine($"Input text was transliterated to '{transliteration?.Script}' script. Transliterated text: '{transliteration?.Text}'.");
}
catch (RequestFailedException exception)
{
    Console.WriteLine($"Error Code: {exception.ErrorCode}");
    Console.WriteLine($"Message: {exception.Message}");
}

For samples on using the transliterate endpoint refer to more samples here.

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.

try
{
    string inputText = "How are you? I am fine. What did you do today?";

    Response<IReadOnlyList<BreakSentenceItem>> response = await client.FindSentenceBoundariesAsync(inputText).ConfigureAwait(false);
    IReadOnlyList<BreakSentenceItem> brokenSentences = response.Value;
    BreakSentenceItem brokenSentence = brokenSentences.FirstOrDefault();

    Console.WriteLine($"Detected languages of the input text: {brokenSentence?.DetectedLanguage?.Language} with score: {brokenSentence?.DetectedLanguage?.Score}.");
    Console.WriteLine($"The detected sentece boundaries: '{string.Join(",", brokenSentence?.SentLen)}'.");

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

For samples on using the break sentece endpoint refer to more samples here.

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.

try
{
    string sourceLanguage = "en";
    string targetLanguage = "es";
    string inputText = "fly";

    Response<IReadOnlyList<DictionaryLookupItem>> response = await client.LookupDictionaryEntriesAsync(sourceLanguage, targetLanguage, inputText).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}");
}

For samples on using the dictionary lookup endpoint refer to more samples here.

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.

try
{
    string sourceLanguage = "en";
    string targetLanguage = "es";
    IEnumerable<InputTextWithTranslation> inputTextElements = new[]
    {
        new InputTextWithTranslation("fly", "volar")
    };

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

    Console.WriteLine($"For the given input {dictionaryEntry?.Examples?.Count} examples were found in the dictionary.");
    DictionaryExample firstExample = dictionaryEntry?.Examples?.FirstOrDefault();
    Console.WriteLine($"Example: '{string.Concat(firstExample.TargetPrefix, firstExample.TargetTerm, firstExample.TargetSuffix)}'.");

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

For samples on using the dictionary examples endpoint refer to more samples here.

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

Troubleshooting

When you interact with the Translator Service using the Text Translation 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".

try
{
    var translation = client.TranslateAsync(Array.Empty<string>(), new[] { new InputText { Text = "This is a Test" } }).ConfigureAwait(false);
}
catch (RequestFailedException e)
{
    Console.WriteLine(e.ToString());
}

You will notice that additional information is logged, like the client request ID of the operation.

Message:
    Azure.RequestFailedException: Service request failed.
    Status: 400 (Bad Request)

Content:
    {"error":{"code":400036,"message":"The target language is not valid."}}

Headers:
    X-RequestId: REDACTED
    Access-Control-Expose-Headers: REDACTED
    X-Content-Type-Options: REDACTED
    Strict-Transport-Security: REDACTED
    Date: Mon, 27 Feb 2023 23:31:37 GMT
    Content-Type: text/plain; charset=utf-8
    Content-Length: 71

Setting up console logging

The simplest way to see the logs is to enable the console logging. To create an Azure SDK log listener that outputs messages to console use AzureEventSourceListener.CreateConsoleLogger method.

// Setup a listener to monitor logged events.
using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();

To learn more about other logging mechanisms see here.

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.

Contributing

See the CONTRIBUTING.md for details on building, testing, and contributing to this library.

This 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, visit cla.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 the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.