From a20329b8265e8c8298073172be8411f87f3b76e1 Mon Sep 17 00:00:00 2001 From: "Matthew Meadows (Rango the Dog)" Date: Thu, 6 Jul 2023 08:53:50 -0700 Subject: [PATCH] [Text Translation] Updates sample code snippets to use code from SampleSnippets.cs. (#37422) * Update Readme.md snippets to be populated by tool, added SampleSnippets.cs file as source. * Fixing missing double quote on region identifier. * Updating sample C# snippets and code (#2) * Updating sample C# snippets and code. * Use explicit type instead of var, remove blank lines from #if * Finished change to use explicit type instead of var --------- Co-authored-by: Rango Meadows --------- Co-authored-by: Rango Meadows Co-authored-by: Michal Materna --- .../Azure.AI.Translation.Text/README.md | 29 +- .../samples/Sample0_CreateClient.md | 26 +- .../samples/Sample1_GetLanguages.md | 6 +- .../samples/Sample2_Translate.md | 30 +- .../samples/Sample4_BreakSentence.md | 7 +- .../samples/Sample5_DictionaryLookup.md | 10 +- .../samples/Sample6_DictionaryExamples.md | 3 +- .../TextTranslationTestEnvironment.cs | 2 +- .../tests/Samples/SampleSnippets.cs | 864 ++++++++++++++++++ 9 files changed, 915 insertions(+), 62 deletions(-) create mode 100644 sdk/translation/Azure.AI.Translation.Text/tests/Samples/SampleSnippets.cs diff --git a/sdk/translation/Azure.AI.Translation.Text/README.md b/sdk/translation/Azure.AI.Translation.Text/README.md index ba1e04fa4464b..bcacc3455d1ca 100644 --- a/sdk/translation/Azure.AI.Translation.Text/README.md +++ b/sdk/translation/Azure.AI.Translation.Text/README.md @@ -58,9 +58,11 @@ update the API key without creating a new client. With the value of the endpoint, `AzureKeyCredential` and a `Region`, you can create the [TextTranslationClient][translator_client_class]: -```C# -AzureKeyCredential credential = new(""); -TextTranslationClient client = new(credential, ""); +```C# Snippet:CreateTextTranslationClient +string endpoint = ""; +string apiKey = ""; +string region = ""; +TextTranslationClient client = new TextTranslationClient(new AzureKeyCredential(apiKey), new Uri(endpoint), region); ``` ## Key concepts @@ -101,7 +103,7 @@ The following section provides several code snippets using the `client` [created Gets the set of languages currently supported by other operations of the Translator. -```C# +```C# Snippet:GetTextTranslationLanguagesAsync try { Response response = await client.GetLanguagesAsync(cancellationToken: CancellationToken.None).ConfigureAwait(false); @@ -124,7 +126,7 @@ Please refer to the service documentation for a conceptual discussion of [langua Renders single source-language text to multiple target-language texts with a single request. -```C# +```C# Snippet:GetTextTranslationAsync try { string targetLanguage = "cs"; @@ -152,7 +154,7 @@ Please refer to the service documentation for a conceptual discussion of [transl Converts characters or letters of a source language to the corresponding characters or letters of a target language. -```C# +```C# Snippet:GetTransliteratedTextAsync try { string language = "zh-Hans"; @@ -182,7 +184,7 @@ Please refer to the service documentation for a conceptual discussion of [transl Identifies the positioning of sentence boundaries in a piece of text. -```C# +```C# Snippet:FindTextSentenceBoundariesAsync try { string inputText = "How are you? I am fine. What did you do today?"; @@ -193,7 +195,6 @@ try 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) { @@ -210,7 +211,7 @@ Please refer to the service documentation for a conceptual discussion of [break Returns equivalent words for the source term in the target language. -```C# +```C# Snippet:LookupDictionaryEntriesAsync try { string sourceLanguage = "en"; @@ -223,7 +224,6 @@ try 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) { @@ -240,7 +240,7 @@ Please refer to the service documentation for a conceptual discussion of [dictio Returns grammatical structure and context examples for the source term and target term pair. -```C# +```C# Snippet:GetGrammaticalStructureAsync try { string sourceLanguage = "en"; @@ -257,7 +257,6 @@ try 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) { @@ -276,10 +275,10 @@ When you interact with the Translator Service using the Text Translation client For example, if you submit a translation request without a target translate language, a `400` error is returned, indicating "Bad Request". -```C# +```C# Snippet:HandleBadRequestAsync try { - var translation = client.TranslateAsync(Array.Empty(), new[] { new InputText { Text = "This is a Test" } }).ConfigureAwait(false); + var translation = await client.TranslateAsync(Array.Empty(), new[] { "This is a Test" }).ConfigureAwait(false); } catch (RequestFailedException e) { @@ -312,7 +311,7 @@ Headers: 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. -```C# +```C# Snippet:CreateLoggingMonitor // Setup a listener to monitor logged events. using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(); ``` diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md index aae2953d696cb..d55c4398f1ca2 100644 --- a/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md @@ -12,9 +12,9 @@ Once you have the value for the API key, create an `AzureKeyCredential`. With the value of the `AzureKeyCredential`, you can create the [TextTranslationClient][translator_client_class]: -```C# -AzureKeyCredential credential = new(""); -TextTranslationClient client = new(credential); +```C# Snippet:CreateTextTranslationClientWithKey +string apiKey = ""; +TextTranslationClient client = new TextTranslationClient(new AzureKeyCredential(apiKey)); ``` > Replace `` with a value created in [Creating Cognitive Services resource](#creating-cognitive-services-resource). @@ -25,9 +25,10 @@ Once you have the value for the API key and Region, create an `AzureKeyCredentia With the value of the `AzureKeyCredential` and a `Region`, you can create the [TextTranslationClient][translator_client_class]: -```C# -AzureKeyCredential credential = new(""); -TextTranslationClient client = new(credential, ""); +```C# Snippet:CreateTextTranslationClientWithRegion +string apiKey = ""; +string region = ""; +TextTranslationClient client = new TextTranslationClient(new AzureKeyCredential(apiKey), region); ``` > Replace `` and `` with a value created in [Creating Cognitive Services resource](#creating-cognitive-services-resource). @@ -38,10 +39,10 @@ When Translator service is configured to use [Virtual Network (VNET)][translator Once you have your resource configured and you have your custom subdomain value and your API key, you can create the [TextTranslationClient][translator_client_class]: -```C# -Uri endpoint = new(""); -AzureKeyCredential credential = new(""); -TextTranslationClient client = new(credential, endpoint); +```C# Snippet:CreateTextTranslationClientWithEndpoint +string endpoint = ""; +string apiKey = ""; +TextTranslationClient client = new TextTranslationClient(new AzureKeyCredential(apiKey), new Uri(endpoint)); ``` > Replace `` with a value created in [Creating Cognitive Services resource](#creating-cognitive-services-resource). @@ -52,8 +53,9 @@ Instead of API key and Region authentication you can use JWT token. For informat Once you have the value for the token, create an class that extends `Azure.Core.TokenCredential`. With the value of the `AzureKeyCredential` and your service returning tokens, you can create the [TextTranslationClient][translator_client_class]: -```C# -TokenCredential credential = new CustomTokenCredential(); +```C# Snippet:CreateTextTranslationClientWithToken +string apiKey = ""; +TokenCredential credential = new CustomTokenCredential(new AzureKeyCredential(apiKey)); TextTranslationClient client = new(credential); ``` diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample1_GetLanguages.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample1_GetLanguages.md index a955d59997d68..6e283b539fcbe 100644 --- a/sdk/translation/Azure.AI.Translation.Text/samples/Sample1_GetLanguages.md +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample1_GetLanguages.md @@ -6,7 +6,7 @@ This sample demonstrates how to get languages that are supported by other operat This will return language metadata from all supported scopes. -```C# +```C# Snippet:GetTextTranslationLanguagesMetadataAsync try { Response response = await client.GetLanguagesAsync().ConfigureAwait(false); @@ -45,7 +45,7 @@ catch (RequestFailedException exception) You can limit the scope of the response of the languages API by providing the optional paramter `scope`. A comma-separated list of names defining the group of languages to return. Allowed group names are: `translation`, `transliteration` and `dictionary`. If no scope is given, then all groups are returned, which is equivalent to passing `translation,transliteration,dictionary`. -```C# +```C# Snippet:GetTextTranslationLanguagesByScopeAsync try { string scope = "translation"; @@ -86,7 +86,7 @@ catch (RequestFailedException exception) You can select the language to use for user interface strings. Some of the fields in the response are names of languages or names of regions. Use this parameter to define the language in which these names are returned. The language is specified by providing a well-formed BCP 47 language tag. For instance, use the value `fr` to request names in French or use the value `zh-Hant` to request names in Chinese Traditional. Names are provided in the English language when a target language is not specified or when localization is not available. -```C# +```C# Snippet:GetTextTranslationLanguagesByCultureAsync try { string acceptLanguage = "es"; diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md index 3a80f1de810ff..cd00506a3d33d 100644 --- a/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md @@ -6,7 +6,7 @@ All samples are using `client` created in [Create a `TextTranslationClient`][cre Translate text from known source language to target language. -```C# +```C# Snippet:GetTextTranslationBySourceAsync try { string from = "en"; @@ -34,7 +34,7 @@ You can ommit source languge of the input text. In this case, API will try to au > Note that you must provide the source language rather than autodetection when using the dynamic dictionary feature. > Note you can use `suggestedFrom` paramter that specifies a fallback language if the language of the input text can't be identified. Language autodetection is applied when the from parameter is omitted. If detection fails, the suggestedFrom language will be assumed. -```C# +```C# Snippet:GetTextTranslationAutoDetectAsync try { string targetLanguage = "cs"; @@ -58,7 +58,7 @@ catch (RequestFailedException exception) You can combine both Translation and Transliteration in one Translate call. Your source Text can be in non-standard Script of a language as well as you can ask for non-standard Script of a target language. -```C# +```C# Snippet:GetTranslationTextTransliteratedAsync try { string fromScript = "Latn"; @@ -77,7 +77,6 @@ try Console.WriteLine($"Source Text: {translation.SourceText.Text}"); Console.WriteLine($"Translation: '{translation?.Translations?.FirstOrDefault()?.Text}'."); Console.WriteLine($"Transliterated text ({translation?.Translations?.FirstOrDefault()?.Transliteration?.Script}): {translation?.Translations?.FirstOrDefault()?.Transliteration?.Text}"); - } catch (RequestFailedException exception) { @@ -90,7 +89,7 @@ catch (RequestFailedException exception) You can translate multiple text elements. Each input element can be in different language (source language parameter needs to be omitted and language auto-detection is used). Refer to [Request limits for Translator](https://learn.microsoft.com/azure/cognitive-services/translator/request-limits) for current limits. -```C# +```C# Snippet:GetMultipleTextTranslationsAsync try { IEnumerable targetLanguages = new[] { "cs" }; @@ -121,7 +120,7 @@ catch (RequestFailedException exception) You can provide multiple target languages which results in each input element being translated to all target languages. -```C# +```C# Snippet:GetTextTranslationMatrixAsync try { IEnumerable targetLanguages = new[] { "cs", "es", "de" }; @@ -151,7 +150,7 @@ catch (RequestFailedException exception) You can select whether the translated text is plain text or HTML text. Any HTML needs to be a well-formed, complete element. Possible values are: plain (default) or html. -```C# +```C# Snippet:GetTextTranslationFormatAsync try { IEnumerable targetLanguages = new[] { "cs" }; @@ -178,7 +177,7 @@ catch (RequestFailedException exception) It's sometimes useful to exclude specific content from translation. You can use the attribute class=notranslate to specify content that should remain in its original language. In the following example, the content inside the first div element won't be translated, while the content in the second div element will be translated. -```C# +```C# Snippet:GetTextTranslationFilterAsync try { string from = "en"; @@ -208,7 +207,7 @@ If you already know the translation you want to apply to a word or a phrase, you > Note You must include the From parameter in your API translation request instead of using the autodetect feature. -```C# +```C# Snippet:GetTextTranslationMarkupAsync try { string from = "en"; @@ -216,7 +215,7 @@ try IEnumerable inputTextElements = new[] { "The word wordomatic is a dictionary entry." - }; +}; Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, sourceLanguage: from).ConfigureAwait(false); IReadOnlyList translations = response.Value; @@ -238,7 +237,7 @@ catch (RequestFailedException exception) If you want to avoid getting profanity in the translation, regardless of the presence of profanity in the source text, you can use the profanity filtering option. The option allows you to choose whether you want to see profanity deleted, whether you want to mark profanities with appropriate tags (giving you the option to add your own post-processing), or you want no action taken. The accepted values of `ProfanityAction` are `Deleted`, `Marked` and `NoAction` (default). -```C# +```C# Snippet:GetTextTranslationProfanityAsync try { ProfanityAction profanityAction = ProfanityAction.Marked; @@ -268,7 +267,7 @@ catch (RequestFailedException exception) You can ask translation service to include alignment projection from source text to translated text. -```C# +```C# Snippet:GetTextTranslationAlignmentAsync try { bool includeAlignment = true; @@ -286,7 +285,6 @@ try 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}'."); Console.WriteLine($"Alignments: {translation?.Translations?.FirstOrDefault()?.Alignment?.Proj}"); - } catch (RequestFailedException exception) { @@ -299,7 +297,7 @@ catch (RequestFailedException exception) You can ask translator service to include sentence boundaries for the input text and the translated text. -```C# +```C# Snippet:GetTextTranslationSentencesAsync try { bool includeSentenceLength = true; @@ -318,8 +316,6 @@ try Console.WriteLine($"Text was translated to: '{translation?.Translations?.FirstOrDefault().To}' and the result is: '{translation?.Translations?.FirstOrDefault()?.Text}'."); Console.WriteLine($"Source Sentece length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.SrcSentLen)}"); Console.WriteLine($"Translated Sentece length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.TransSentLen)}"); - - } catch (RequestFailedException exception) { @@ -336,7 +332,7 @@ It is possible to set `allowFalback` paramter. It specifies that the service is `allowFallback=false` specifies that the translation should only use systems trained for the category specified by the request. If a translation for language X to language Y requires chaining through a pivot language E, then all the systems in the chain (X → E and E → Y) will need to be custom and have the same category. If no system is found with the specific category, the request will return a 400 status code. `allowFallback=true` specifies that the service is allowed to fall back to a general system when a custom system doesn't exist. -```C# +```C# Snippet:GetTextTranslationFallbackAsync try { string category = "<>"; diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample4_BreakSentence.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample4_BreakSentence.md index 697fba5fb3bc8..f502970056daf 100644 --- a/sdk/translation/Azure.AI.Translation.Text/samples/Sample4_BreakSentence.md +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample4_BreakSentence.md @@ -6,7 +6,7 @@ All samples are using `client` created in [Create a `TextTranslationClient`][cre When the input language is known, you can provide those to the service call. -```C# +```C# Snippet:GetTextTranslationSentencesSourceAsync try { string sourceLanguage = "zh-Hans"; @@ -22,8 +22,6 @@ try 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) { @@ -36,7 +34,7 @@ catch (RequestFailedException exception) You can ommit source languge of the input text. In this case, API will try to auto-detect the language. -```C# +```C# Snippet:GetTextTranslationSentencesAutoAsync try { IEnumerable inputTextElements = new[] @@ -50,7 +48,6 @@ try 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) { diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample5_DictionaryLookup.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample5_DictionaryLookup.md index b2bae562d0974..d12c184b5e2f5 100644 --- a/sdk/translation/Azure.AI.Translation.Text/samples/Sample5_DictionaryLookup.md +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample5_DictionaryLookup.md @@ -6,23 +6,19 @@ All samples are using `client` created in [Create a `TextTranslationClient`][cre Returns equivalent words for the source term in the target language. -```C# +```C# Snippet:LookupDictionaryEntriesAsync try { string sourceLanguage = "en"; string targetLanguage = "es"; - IEnumerable inputTextElements = new[] - { - "fly" - }; + string inputText = "fly"; - Response> response = await client.LookupDictionaryEntriesAsync(sourceLanguage, targetLanguage, inputTextElements).ConfigureAwait(false); + Response> response = await client.LookupDictionaryEntriesAsync(sourceLanguage, targetLanguage, inputText).ConfigureAwait(false); IReadOnlyList 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) { diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample6_DictionaryExamples.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample6_DictionaryExamples.md index 41eeca48328e8..ad160928ac9d8 100644 --- a/sdk/translation/Azure.AI.Translation.Text/samples/Sample6_DictionaryExamples.md +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample6_DictionaryExamples.md @@ -6,7 +6,7 @@ All samples are using `client` created in [Create a `TextTranslationClient`][cre Returns grammatical structure and context examples for the source term and target term pair. -```C# +```C# Snippet:GetGrammaticalStructureAsync try { string sourceLanguage = "en"; @@ -23,7 +23,6 @@ try 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) { diff --git a/sdk/translation/Azure.AI.Translation.Text/tests/Infrastructure/TextTranslationTestEnvironment.cs b/sdk/translation/Azure.AI.Translation.Text/tests/Infrastructure/TextTranslationTestEnvironment.cs index 5818e2df5c291..d1f4eef8b811a 100644 --- a/sdk/translation/Azure.AI.Translation.Text/tests/Infrastructure/TextTranslationTestEnvironment.cs +++ b/sdk/translation/Azure.AI.Translation.Text/tests/Infrastructure/TextTranslationTestEnvironment.cs @@ -38,7 +38,7 @@ public TextTranslationTestEnvironment() protected override async ValueTask IsEnvironmentReadyAsync() { string endpoint = GetOptionalVariable(EndpointEnvironmentVariableName); - var client = new TextTranslationClient(Credential, new Uri(endpoint)); + TextTranslationClient client = new TextTranslationClient(Credential, new Uri(endpoint)); try { await client.GetLanguagesAsync(cancellationToken: CancellationToken.None).ConfigureAwait(false); diff --git a/sdk/translation/Azure.AI.Translation.Text/tests/Samples/SampleSnippets.cs b/sdk/translation/Azure.AI.Translation.Text/tests/Samples/SampleSnippets.cs new file mode 100644 index 0000000000000..7ef018e83631b --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/tests/Samples/SampleSnippets.cs @@ -0,0 +1,864 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Azure.AI.Translation.Text.Tests; +using Azure.Core; +using Azure.Core.Diagnostics; +using Azure.Core.TestFramework; +using NUnit.Framework; + +namespace Azure.AI.Translation.Text.Samples +{ + /// + /// Samples that are used in the associated README.md file. + /// + public partial class SampleSnippets : SamplesBase + { + [Test] + public TextTranslationClient CreateTextTranslationClient() + { + #region Snippet:CreateTextTranslationClient + +#if SNIPPET + string endpoint = ""; + string apiKey = ""; + string region = ""; +#else + string endpoint = TestEnvironment.Endpoint; + string apiKey = TestEnvironment.ApiKey; + string region = TestEnvironment.Region; +#endif + TextTranslationClient client = new TextTranslationClient(new AzureKeyCredential(apiKey), new Uri(endpoint), region); + #endregion + + return client; + } + + [Test] + public TextTranslationClient CreateTextTranslationClientWithKey() + { + #region Snippet:CreateTextTranslationClientWithKey + +#if SNIPPET + string apiKey = ""; +#else + string apiKey = TestEnvironment.ApiKey; + +#endif + TextTranslationClient client = new TextTranslationClient(new AzureKeyCredential(apiKey)); + #endregion + + return client; + } + + [Test] + public TextTranslationClient CreateTextTranslationClientWithRegion() + { + #region Snippet:CreateTextTranslationClientWithRegion + +#if SNIPPET + string apiKey = ""; + string region = ""; +#else + string apiKey = TestEnvironment.ApiKey; + string region = TestEnvironment.Region; +#endif + TextTranslationClient client = new TextTranslationClient(new AzureKeyCredential(apiKey), region); + #endregion + + return client; + } + + [Test] + public TextTranslationClient CreateTextTranslationClientWithEndpoint() + { + #region Snippet:CreateTextTranslationClientWithEndpoint + +#if SNIPPET + string endpoint = ""; + string apiKey = ""; +#else + string endpoint = TestEnvironment.Endpoint; + string apiKey = TestEnvironment.ApiKey; +#endif + TextTranslationClient client = new TextTranslationClient(new AzureKeyCredential(apiKey), new Uri(endpoint)); + #endregion + + return client; + } + + public class CustomTokenCredential : TokenCredential + { + public CustomTokenCredential(AzureKeyCredential azureKeyCredential): base() + { + } + + public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } + + public override ValueTask GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) + { + throw new NotImplementedException(); + } + } + + [Test] + public TextTranslationClient CreateTextTranslationClientWithToken() + { + #region Snippet:CreateTextTranslationClientWithToken + +#if SNIPPET + string apiKey = ""; +#else + string apiKey = TestEnvironment.ApiKey; +#endif + TokenCredential credential = new CustomTokenCredential(new AzureKeyCredential(apiKey)); + TextTranslationClient client = new(credential); + + #endregion + + return client; + } + + [Test] + public async void GetTextTranslationLanguagesAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationLanguagesAsync + try + { + Response 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationLanguagesMetadataAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationLanguagesMetadataAsync + try + { + Response response = await client.GetLanguagesAsync().ConfigureAwait(false); + GetLanguagesResult languages = response.Value; + + Console.WriteLine($"Number of supported languages for translate operation: {languages.Translation.Count}."); + Console.WriteLine($"Number of supported languages for transliterate operation: {languages.Transliteration.Count}."); + Console.WriteLine($"Number of supported languages for dictionary operations: {languages.Dictionary.Count}."); + + Console.WriteLine("Translation Languages:"); + foreach (var translationLanguage in languages.Translation) + { + Console.WriteLine($"{translationLanguage.Key} -- name: {translationLanguage.Value.Name} ({translationLanguage.Value.NativeName})"); + } + + Console.WriteLine("Transliteration Languages:"); + foreach (var transliterationLanguage in languages.Transliteration) + { + Console.WriteLine($"{transliterationLanguage.Key} -- name: {transliterationLanguage.Value.Name}, supported script count: {transliterationLanguage.Value.Scripts.Count}"); + } + + Console.WriteLine("Dictionary Languages:"); + foreach (var dictionaryLanguage in languages.Dictionary) + { + Console.WriteLine($"{dictionaryLanguage.Key} -- name: {dictionaryLanguage.Value.Name}, supported target languages count: {dictionaryLanguage.Value.Translations.Count}"); + } + } + catch (RequestFailedException exception) + { + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationLanguagesByScopeAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationLanguagesByScopeAsync + try + { + string scope = "translation"; + Response response = await client.GetLanguagesAsync(scope: scope).ConfigureAwait(false); + GetLanguagesResult languages = response.Value; + + Console.WriteLine($"Number of supported languages for translate operations: {languages.Translation.Count}."); + Console.WriteLine($"Number of supported languages for translate operations: {languages.Transliteration.Count}."); + Console.WriteLine($"Number of supported languages for translate operations: {languages.Dictionary.Count}."); + + Console.WriteLine("Translation Languages:"); + foreach (var translationLanguage in languages.Translation) + { + Console.WriteLine($"{translationLanguage.Key} -- name: {translationLanguage.Value.Name} ({translationLanguage.Value.NativeName})"); + } + + Console.WriteLine("Transliteration Languages:"); + foreach (var transliterationLanguage in languages.Transliteration) + { + Console.WriteLine($"{transliterationLanguage.Key} -- name: {transliterationLanguage.Value.Name}, supported script count: {transliterationLanguage.Value.Scripts.Count}"); + } + + Console.WriteLine("Dictionary Languages:"); + foreach (var dictionaryLanguage in languages.Dictionary) + { + Console.WriteLine($"{dictionaryLanguage.Key} -- name: {dictionaryLanguage.Value.Name}, supported target languages count: {dictionaryLanguage.Value.Translations.Count}"); + } + } + catch (RequestFailedException exception) + { + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationLanguagesByCultureAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationLanguagesByCultureAsync + try + { + string acceptLanguage = "es"; + Response response = await client.GetLanguagesAsync(acceptLanguage: acceptLanguage).ConfigureAwait(false); + GetLanguagesResult languages = response.Value; + + Console.WriteLine($"Number of supported languages for translate operations: {languages.Translation.Count}."); + Console.WriteLine($"Number of supported languages for translate operations: {languages.Transliteration.Count}."); + Console.WriteLine($"Number of supported languages for translate operations: {languages.Dictionary.Count}."); + + Console.WriteLine("Translation Languages:"); + foreach (var translationLanguage in languages.Translation) + { + Console.WriteLine($"{translationLanguage.Key} -- name: {translationLanguage.Value.Name} ({translationLanguage.Value.NativeName})"); + } + + Console.WriteLine("Transliteration Languages:"); + foreach (var transliterationLanguage in languages.Transliteration) + { + Console.WriteLine($"{transliterationLanguage.Key} -- name: {transliterationLanguage.Value.Name}, supported script count: {transliterationLanguage.Value.Scripts.Count}"); + } + + Console.WriteLine("Dictionary Languages:"); + foreach (var dictionaryLanguage in languages.Dictionary) + { + Console.WriteLine($"{dictionaryLanguage.Key} -- name: {dictionaryLanguage.Value.Name}, supported target languages count: {dictionaryLanguage.Value.Translations.Count}"); + } + } + catch (RequestFailedException exception) + { + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationAsync + try + { + string targetLanguage = "cs"; + string inputText = "This is a test."; + + Response> response = await client.TranslateAsync(targetLanguage, inputText).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationBySourceAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationBySourceAsync + try + { + string from = "en"; + string targetLanguage = "cs"; + string inputText = "This is a test."; + + Response> response = await client.TranslateAsync(targetLanguage, inputText, sourceLanguage: from).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationAutoDetectAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationAutoDetectAsync + try + { + string targetLanguage = "cs"; + string inputText = "This is a test."; + + Response> response = await client.TranslateAsync(targetLanguage, inputText).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetMultipleTextTranslationsAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetMultipleTextTranslationsAsync + try + { + IEnumerable targetLanguages = new[] { "cs" }; + IEnumerable inputTextElements = new[] + { + "This is a test.", + "Esto es una prueba.", + "Dies ist ein Test." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationMatrixAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationMatrixAsync + try + { + IEnumerable targetLanguages = new[] { "cs", "es", "de" }; + IEnumerable inputTextElements = new[] + { + "This is a test." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationFormatAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationFormatAsync + try + { + IEnumerable targetLanguages = new[] { "cs" }; + IEnumerable inputTextElements = new[] + { + "This is a test." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, textType: TextType.Html).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationFilterAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationFilterAsync + try + { + string from = "en"; + IEnumerable targetLanguages = new[] { "cs" }; + IEnumerable inputTextElements = new[] + { + "
This will not be translated.
This will be translated.
" + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, textType: TextType.Html, sourceLanguage: from).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationMarkupAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationMarkupAsync + try + { + string from = "en"; + IEnumerable targetLanguages = new[] { "cs" }; + IEnumerable inputTextElements = new[] + { + "The word wordomatic is a dictionary entry." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, sourceLanguage: from).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationProfanityAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationProfanityAsync + try + { + ProfanityAction profanityAction = ProfanityAction.Marked; + ProfanityMarker profanityMarkers = ProfanityMarker.Asterisk; + + IEnumerable targetLanguages = new[] { "cs" }; + IEnumerable inputTextElements = new[] + { + "This is ***." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, profanityAction: profanityAction, profanityMarker: profanityMarkers).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationAlignmentAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationAlignmentAsync + try + { + bool includeAlignment = true; + + IEnumerable targetLanguages = new[] { "cs" }; + IEnumerable inputTextElements = new[] + { + "The answer lies in machine translation." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, includeAlignment: includeAlignment).ConfigureAwait(false); + IReadOnlyList 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}'."); + Console.WriteLine($"Alignments: {translation?.Translations?.FirstOrDefault()?.Alignment?.Proj}"); + } + catch (RequestFailedException exception) + { + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationSentencesAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationSentencesAsync + try + { + bool includeSentenceLength = true; + + IEnumerable targetLanguages = new[] { "cs" }; + IEnumerable inputTextElements = new[] + { + "The answer lies in machine translation. This is a test." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, includeSentenceLength: includeSentenceLength).ConfigureAwait(false); + IReadOnlyList 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}'."); + Console.WriteLine($"Source Sentece length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.SrcSentLen)}"); + Console.WriteLine($"Translated Sentece length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.TransSentLen)}"); + } + catch (RequestFailedException exception) + { + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationFallbackAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationFallbackAsync + try + { + string category = "<>"; + IEnumerable targetLanguages = new[] { "cs" }; + IEnumerable inputTextElements = new[] + { + "This is a test." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, category: category).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTextTranslationSentencesSourceAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationSentencesSourceAsync + try + { + string sourceLanguage = "zh-Hans"; + string sourceScript = "Latn"; + IEnumerable inputTextElements = new[] + { + "zhè shì gè cè shì。" + }; + + Response> response = await client.FindSentenceBoundariesAsync(inputTextElements, language: sourceLanguage, script: sourceScript).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + public async void GetTextTranslationSentencesAutoAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationSentencesAutoAsync + try + { + IEnumerable inputTextElements = new[] + { + "How are you? I am fine. What did you do today?" + }; + + Response> response = await client.FindSentenceBoundariesAsync(inputTextElements).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetTransliteratedTextAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTransliteratedTextAsync + try + { + string language = "zh-Hans"; + string fromScript = "Hans"; + string toScript = "Latn"; + + string inputText = "这是个测试。"; + + Response> response = await client.TransliterateAsync(language, fromScript, toScript, inputText).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + public async void GetTranslationTextTransliteratedAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTranslationTextTransliteratedAsync + try + { + string fromScript = "Latn"; + string fromLanguage = "ar"; + string toScript = "Latn"; + IEnumerable targetLanguages = new[] { "zh-Hans" }; + IEnumerable inputTextElements = new[] + { + "hudha akhtabar." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, sourceLanguage: fromLanguage, fromScript: fromScript, toScript: toScript).ConfigureAwait(false); + IReadOnlyList translations = response.Value; + TranslatedTextItem translation = translations.FirstOrDefault(); + + Console.WriteLine($"Source Text: {translation.SourceText.Text}"); + Console.WriteLine($"Translation: '{translation?.Translations?.FirstOrDefault()?.Text}'."); + Console.WriteLine($"Transliterated text ({translation?.Translations?.FirstOrDefault()?.Transliteration?.Script}): {translation?.Translations?.FirstOrDefault()?.Transliteration?.Text}"); + } + catch (RequestFailedException exception) + { + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); + } + #endregion + } + + [Test] + public async void FindTextSentenceSentenceBoundariesAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:FindTextSentenceBoundariesAsync + try + { + string inputText = "How are you? I am fine. What did you do today?"; + + Response> response = await client.FindSentenceBoundariesAsync(inputText).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void LookupDictionaryEntriesAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:LookupDictionaryEntriesAsync + try + { + string sourceLanguage = "en"; + string targetLanguage = "es"; + string inputText = "fly"; + + Response> response = await client.LookupDictionaryEntriesAsync(sourceLanguage, targetLanguage, inputText).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void GetGrammaticalStructureAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetGrammaticalStructureAsync + try + { + string sourceLanguage = "en"; + string targetLanguage = "es"; + IEnumerable inputTextElements = new[] + { + new InputTextWithTranslation("fly", "volar") + }; + + Response> response = await client.LookupDictionaryExamplesAsync(sourceLanguage, targetLanguage, inputTextElements).ConfigureAwait(false); + IReadOnlyList 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}"); + } + #endregion + } + + [Test] + public async void HandleBadRequestAsync() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:HandleBadRequestAsync + try + { + var translation = await client.TranslateAsync(Array.Empty(), new[] { "This is a Test" }).ConfigureAwait(false); + } + catch (RequestFailedException e) + { + Console.WriteLine(e.ToString()); + } + #endregion + } + + [Test] + public void CreateLoggingMonitor() + { + #region Snippet:CreateLoggingMonitor + + // Setup a listener to monitor logged events. + using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(); + + #endregion + } + } +}