diff --git a/sdk/translation/Azure.AI.Translation.Text/CHANGELOG.md b/sdk/translation/Azure.AI.Translation.Text/CHANGELOG.md index 3f012045f49d5..1eb8c6ed6629f 100644 --- a/sdk/translation/Azure.AI.Translation.Text/CHANGELOG.md +++ b/sdk/translation/Azure.AI.Translation.Text/CHANGELOG.md @@ -5,6 +5,7 @@ ### Features Added - Introduced model factory `Azure.AI.Translation.Text.TextTranslationModelFactory` for mocking. +- Added options overloads to Translate and Transliterate. TextTranslationTranslateOptions and TextTranslationTransliterateOptions roll up method parameters into a single object. ### Breaking Changes diff --git a/sdk/translation/Azure.AI.Translation.Text/README.md b/sdk/translation/Azure.AI.Translation.Text/README.md index d0a4bb6e7ff9c..ce5452788ee54 100644 --- a/sdk/translation/Azure.AI.Translation.Text/README.md +++ b/sdk/translation/Azure.AI.Translation.Text/README.md @@ -123,8 +123,7 @@ For samples on using the `languages` endpoint refer to more samples [here][langu Please refer to the service documentation for a conceptual discussion of [languages][languages_doc]. ### Translate - -Renders single source-language text to multiple target-language texts with a single request. +The simplest use of the Translate method is to invoke it with a single target language and one input string. ```C# Snippet:GetTextTranslation try @@ -146,6 +145,62 @@ catch (RequestFailedException exception) } ``` +A convenience overload of Translate is provided using a TextTranslationTranslateOptions parameter. This sample demonstrates rendering a single source-language to multiple target languages with a single request using the options overload. + +```C# Snippet:GetTextTranslationMatrixOptions +try +{ + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguages: new[] { "cs", "es", "de" }, + content: new[] { "This is a test." } + ); + + Response> response = client.Translate(options); + 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}"); +} +``` + +This sample demonstrates Translation and Transliteration in a single call using the TextTranslationTranslateOptions parameter. Required parameters are passed to the constructor, optional parameters are set using an object initializer. + +```C# Snippet:GetTranslationTextTransliteratedOptions +try +{ + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "zh-Hans", + content: "hudha akhtabar.") + { + FromScript = "Latn", + SourceLanguage = "ar", + ToScript = "Latn" + }; + + Response> response = client.Translate(options); + 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}"); +} +``` + For samples on using the `translate` endpoint refer to more samples [here][translate_sample]. Please refer to the service documentation for a conceptual discussion of [translate][translate_doc]. @@ -176,6 +231,31 @@ catch (RequestFailedException exception) } ``` +A convenience overload of Transliterate is provided using a single TextTranslationTransliterateOptions parameter. A modified version of the preceding sample is provided here demonstrating its use. + +```C# Snippet:GetTransliteratedTextOptions +try +{ + TextTranslationTransliterateOptions options = new TextTranslationTransliterateOptions( + language: "zh-Hans", + fromScript: "Hans", + toScript: "Latn", + content: "这是个测试。" + ); + + Response> response = client.Transliterate(options); + 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}"); +} +``` + For samples on using the `transliterate` endpoint refer to more samples [here][transliterate_sample]. Please refer to the service documentation for a conceptual discussion of [transliterate][transliterate_doc]. @@ -194,7 +274,7 @@ try 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)}'."); + Console.WriteLine($"The detected sentence boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); } catch (RequestFailedException exception) { diff --git a/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.netstandard2.0.cs b/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.netstandard2.0.cs index 67bc13edc30a4..907eb99bd20c5 100644 --- a/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.netstandard2.0.cs +++ b/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.netstandard2.0.cs @@ -196,14 +196,18 @@ protected TextTranslationClient(System.Uri endpoint, Azure.AI.Translation.Text.T public virtual Azure.Response> LookupDictionaryExamples(string from, string to, System.Collections.Generic.IEnumerable content, string clientTraceId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task>> LookupDictionaryExamplesAsync(string from, string to, Azure.AI.Translation.Text.InputTextWithTranslation content, string clientTraceId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task>> LookupDictionaryExamplesAsync(string from, string to, System.Collections.Generic.IEnumerable content, string clientTraceId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response> Translate(Azure.AI.Translation.Text.TextTranslationTranslateOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response> Translate(System.Collections.Generic.IEnumerable targetLanguages, System.Collections.Generic.IEnumerable content, string clientTraceId = null, string sourceLanguage = null, Azure.AI.Translation.Text.TextType? textType = default(Azure.AI.Translation.Text.TextType?), string category = null, Azure.AI.Translation.Text.ProfanityAction? profanityAction = default(Azure.AI.Translation.Text.ProfanityAction?), Azure.AI.Translation.Text.ProfanityMarker? profanityMarker = default(Azure.AI.Translation.Text.ProfanityMarker?), bool? includeAlignment = default(bool?), bool? includeSentenceLength = default(bool?), string suggestedFrom = null, string fromScript = null, string toScript = null, bool? allowFallback = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response> Translate(string targetLanguage, System.Collections.Generic.IEnumerable content, string sourceLanguage = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response> Translate(string targetLanguage, string text, string sourceLanguage = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task>> TranslateAsync(Azure.AI.Translation.Text.TextTranslationTranslateOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task>> TranslateAsync(System.Collections.Generic.IEnumerable targetLanguages, System.Collections.Generic.IEnumerable content, string clientTraceId = null, string sourceLanguage = null, Azure.AI.Translation.Text.TextType? textType = default(Azure.AI.Translation.Text.TextType?), string category = null, Azure.AI.Translation.Text.ProfanityAction? profanityAction = default(Azure.AI.Translation.Text.ProfanityAction?), Azure.AI.Translation.Text.ProfanityMarker? profanityMarker = default(Azure.AI.Translation.Text.ProfanityMarker?), bool? includeAlignment = default(bool?), bool? includeSentenceLength = default(bool?), string suggestedFrom = null, string fromScript = null, string toScript = null, bool? allowFallback = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task>> TranslateAsync(string targetLanguage, System.Collections.Generic.IEnumerable content, string sourceLanguage = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task>> TranslateAsync(string targetLanguage, string text, string sourceLanguage = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response> Transliterate(Azure.AI.Translation.Text.TextTranslationTransliterateOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response> Transliterate(string language, string fromScript, string toScript, System.Collections.Generic.IEnumerable content, string clientTraceId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response> Transliterate(string language, string fromScript, string toScript, string text, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task>> TransliterateAsync(Azure.AI.Translation.Text.TextTranslationTransliterateOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task>> TransliterateAsync(string language, string fromScript, string toScript, System.Collections.Generic.IEnumerable content, string clientTraceId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task>> TransliterateAsync(string language, string fromScript, string toScript, string text, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } @@ -215,6 +219,36 @@ public enum ServiceVersion V3_0 = 1, } } + public partial class TextTranslationTranslateOptions + { + public TextTranslationTranslateOptions(System.Collections.Generic.IEnumerable targetLanguages, System.Collections.Generic.IEnumerable content) { } + public TextTranslationTranslateOptions(System.Collections.Generic.IEnumerable targetLanguages, System.Collections.Generic.IEnumerable content, string clientTraceId = null, string sourceLanguage = null, Azure.AI.Translation.Text.TextType? textType = default(Azure.AI.Translation.Text.TextType?), string category = null, Azure.AI.Translation.Text.ProfanityAction? profanityAction = default(Azure.AI.Translation.Text.ProfanityAction?), Azure.AI.Translation.Text.ProfanityMarker? profanityMarker = default(Azure.AI.Translation.Text.ProfanityMarker?), bool? includeAlignment = default(bool?), bool? includeSentenceLength = default(bool?), string suggestedFrom = null, string fromScript = null, string toScript = null, bool? allowFallback = default(bool?)) { } + public TextTranslationTranslateOptions(string targetLanguage, string content) { } + public bool? AllowFallback { get { throw null; } set { } } + public string Category { get { throw null; } set { } } + public string ClientTraceId { get { throw null; } set { } } + public System.Collections.Generic.IEnumerable Content { get { throw null; } } + public string FromScript { get { throw null; } set { } } + public bool? IncludeAlignment { get { throw null; } set { } } + public bool? IncludeSentenceLength { get { throw null; } set { } } + public Azure.AI.Translation.Text.ProfanityAction? ProfanityAction { get { throw null; } set { } } + public Azure.AI.Translation.Text.ProfanityMarker? ProfanityMarker { get { throw null; } set { } } + public string SourceLanguage { get { throw null; } set { } } + public string SuggestedFrom { get { throw null; } set { } } + public System.Collections.Generic.IEnumerable TargetLanguages { get { throw null; } } + public Azure.AI.Translation.Text.TextType? TextType { get { throw null; } set { } } + public string ToScript { get { throw null; } set { } } + } + public partial class TextTranslationTransliterateOptions + { + public TextTranslationTransliterateOptions(string language, string fromScript, string toScript, System.Collections.Generic.IEnumerable content, string clientTraceId = null) { } + public TextTranslationTransliterateOptions(string language, string fromScript, string toScript, string content, string clientTraceId = null) { } + public string ClientTraceId { get { throw null; } set { } } + public System.Collections.Generic.IEnumerable Content { get { throw null; } } + public string FromScript { get { throw null; } } + public string Language { get { throw null; } } + public string ToScript { get { throw null; } } + } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct TextType : System.IEquatable { diff --git a/sdk/translation/Azure.AI.Translation.Text/assets.json b/sdk/translation/Azure.AI.Translation.Text/assets.json index 17c231b90195d..0db91e5c1edd0 100644 --- a/sdk/translation/Azure.AI.Translation.Text/assets.json +++ b/sdk/translation/Azure.AI.Translation.Text/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "net", "TagPrefix": "net/translation/Azure.AI.Translation.Text", - "Tag": "net/translation/Azure.AI.Translation.Text_311c195b9c" + "Tag": "net/translation/Azure.AI.Translation.Text_9702e6ff9b" } 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 8824c5cc72dc6..5578798ef6dd8 100644 --- a/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md @@ -85,22 +85,53 @@ catch (RequestFailedException exception) } ``` -## Translate multiple input texts - -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. +A convenience overload of Translate is provided using a single TextTranslationTranslateOptions parameter. This sample demonstrates Translation and Transliteration in a single call using the options parameter. -```C# Snippet:GetMultipleTextTranslations +```C# Snippet:GetTranslationTextTransliteratedOptions try { - IEnumerable targetLanguages = new[] { "cs" }; - IEnumerable inputTextElements = new[] + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "zh-Hans", + content: "hudha akhtabar.") { - "This is a test.", - "Esto es una prueba.", - "Dies ist ein Test." + FromScript = "Latn", + SourceLanguage = "ar", + ToScript = "Latn" }; - Response> response = client.Translate(targetLanguages, inputTextElements); + Response> response = client.Translate(options); + 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}"); +} +``` + +## Translate multiple input texts + +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# Snippet:GetMultipleTextTranslationsOptions +try +{ + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguages: new[] { "cs" }, + content: new[] + { + "This is a test.", + "Esto es una prueba.", + "Dies ist ein Test." + } + ); + + Response> response = client.Translate(options); IReadOnlyList translations = response.Value; foreach (TranslatedTextItem translation in translations) @@ -314,8 +345,8 @@ 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($"Source Sentece length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.SrcSentLen)}"); - Console.WriteLine($"Translated Sentece length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.TransSentLen)}"); + Console.WriteLine($"Source Sentence length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.SrcSentLen)}"); + Console.WriteLine($"Translated Sentence length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.TransSentLen)}"); } catch (RequestFailedException exception) { diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample3_Transliterate.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample3_Transliterate.md index d5927f7180263..caddf546918ac 100644 --- a/sdk/translation/Azure.AI.Translation.Text/samples/Sample3_Transliterate.md +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample3_Transliterate.md @@ -28,6 +28,31 @@ catch (RequestFailedException exception) } ``` +A convenience overload of Transliterate is provided using a single TextTranslationTransliterateOptions parameter. A modified version of the preceding sample is provided here demonstrating its use. + +```C# Snippet:GetTransliteratedTextOptions +try +{ + TextTranslationTransliterateOptions options = new TextTranslationTransliterateOptions( + language: "zh-Hans", + fromScript: "Hans", + toScript: "Latn", + content: "这是个测试。" + ); + + Response> response = client.Transliterate(options); + 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}"); +} +``` + See the [README] of the Text Translation client library for more information, including useful links and instructions. [README]: https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/README.md 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 46533ad1c4d48..d0f65ca85d0cd 100644 --- a/sdk/translation/Azure.AI.Translation.Text/samples/Sample4_BreakSentence.md +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample4_BreakSentence.md @@ -21,7 +21,7 @@ try 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)}'."); + Console.WriteLine($"The detected sentence boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); } catch (RequestFailedException exception) { @@ -47,7 +47,7 @@ try 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)}'."); + Console.WriteLine($"The detected sentence boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); } catch (RequestFailedException exception) { diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClient.cs b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClient.cs index 022ce5466e358..ac02f2592ce37 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClient.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClient.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Linq; using System.Text.Json; +using System.Security.Principal; namespace Azure.AI.Translation.Text { @@ -186,6 +187,17 @@ public virtual Task>> TranslateAsync( return this.TranslateAsync(targetLanguages, content.Select(input => new InputTextItem(input)), clientTraceId, sourceLanguage, textType?.ToString(), category, profanityAction?.ToString(), profanityMarker?.ToString(), includeAlignment, includeSentenceLength, suggestedFrom, fromScript, toScript, allowFallback, cancellationToken); } + /// Translate Text. + /// The client translation options. + /// The cancellation token to use. + /// is null. + public virtual Task>> TranslateAsync(TextTranslationTranslateOptions options, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(options, nameof(options)); + + return this.TranslateAsync(options.TargetLanguages, options.Content.Select(input => new InputTextItem(input)), options.ClientTraceId, options.SourceLanguage, options.TextType?.ToString(), options.Category, options.ProfanityAction?.ToString(), options.ProfanityMarker?.ToString(), options.IncludeAlignment, options.IncludeSentenceLength, options.SuggestedFrom, options.FromScript, options.ToScript, options.AllowFallback, cancellationToken); + } + /// Translate Text. /// /// Specifies the language of the output text. The target language must be one of the supported languages included @@ -307,6 +319,17 @@ public virtual Response> Translate(IEnumerable return this.Translate(targetLanguages, content.Select(input => new InputTextItem(input)), clientTraceId, sourceLanguage, textType?.ToString(), category, profanityAction?.ToString(), profanityMarker?.ToString(), includeAlignment, includeSentenceLength, suggestedFrom, fromScript, toScript, allowFallback, cancellationToken); } + /// Translate Text. + /// The client translation options. + /// The cancellation token to use. + /// is null. + public virtual Response> Translate(TextTranslationTranslateOptions options, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(options, nameof(options)); + + return this.Translate(options.TargetLanguages, options.Content.Select(input => new InputTextItem(input)), options.ClientTraceId, options.SourceLanguage, options.TextType?.ToString(), options.Category, options.ProfanityAction?.ToString(), options.ProfanityMarker?.ToString(), options.IncludeAlignment, options.IncludeSentenceLength, options.SuggestedFrom, options.FromScript, options.ToScript, options.AllowFallback, cancellationToken); + } + /// Translate Text. /// /// Specifies the language of the output text. The target language must be one of the supported languages included @@ -387,6 +410,17 @@ public virtual Task>> TransliterateAs return this.TransliterateAsync(language, fromScript, toScript, content.Select(input => new InputTextItem(input)), clientTraceId, cancellationToken); } + /// Transliterate Text. + /// + /// + /// A representing the result of the asynchronous operation. + public virtual Task>> TransliterateAsync(TextTranslationTransliterateOptions options, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(options, nameof(options)); + + return this.TransliterateAsync(options.Language, options.FromScript, options.ToScript, options.Content.Select(input => new InputTextItem(input)), options.ClientTraceId, cancellationToken); + } + /// Transliterate Text. /// /// Specifies the language of the text to convert from one script to another. @@ -442,6 +476,17 @@ public virtual Response> Transliterate(string return this.Transliterate(language, fromScript, toScript, content.Select(input => new InputTextItem(input)), clientTraceId, cancellationToken); } + /// Transliterate Text. + /// The configuration options for the transliterate call. + /// The cancellation token to use. + /// is null. + public virtual Response> Transliterate(TextTranslationTransliterateOptions options, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(options, nameof(options)); + + return this.Transliterate(options.Language, options.FromScript, options.ToScript, options.Content.Select(input => new InputTextItem(input)), options.ClientTraceId, cancellationToken); + } + /// Transliterate Text. /// /// Specifies the language of the text to convert from one script to another. diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationTranslateOptions.cs b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationTranslateOptions.cs new file mode 100644 index 0000000000000..2e59728665b20 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationTranslateOptions.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core; +using System.Collections.Generic; + +namespace Azure.AI.Translation.Text +{ + /// Client options for TextTranslationClient.Translate + public partial class TextTranslationTranslateOptions + { + /// + /// Specifies the language of the output text. The target language must be one of the supported languages included + /// in the translation scope. For example, use to=de to translate to German. + /// It's possible to translate to multiple languages simultaneously by repeating the parameter in the query string. + /// For example, use to=de and to=it to translate to German and Italian. + /// + public IEnumerable TargetLanguages { get; } + /// + /// Array of the text to be translated. + /// + public IEnumerable Content { get; } + /// + /// A client-generated GUID to uniquely identify the request. + /// + public string ClientTraceId { get; set; } + /// + /// Specifies the language of the input text. Find which languages are available to translate from by + /// looking up supported languages using the translation scope. If the from parameter isn't specified, + /// automatic language detection is applied to determine the source language. + /// + /// You must use the from parameter rather than autodetection when using the dynamic dictionary feature. + /// Note: the dynamic dictionary feature is case-sensitive. + /// + public string SourceLanguage { get; set; } + /// + /// Defines whether the text being translated is plain text or HTML text. Any HTML needs to be a well-formed, + /// complete element. Possible values are: plain (default) or html. + /// + public TextType? TextType { get; set; } + /// + /// A string specifying the category (domain) of the translation. This parameter is used to get translations + /// from a customized system built with Custom Translator. Add the Category ID from your Custom Translator + /// project details to this parameter to use your deployed customized system. Default value is: general. + /// + public string Category { get; set; } + /// + /// Specifies how profanities should be treated in translations. + /// Possible values are: NoAction (default), Marked or Deleted. + /// + public ProfanityAction? ProfanityAction { get; set; } + /// + /// Specifies how profanities should be marked in translations. + /// Possible values are: Asterisk (default) or Tag. + /// + public ProfanityMarker? ProfanityMarker { get; set; } + /// + /// Specifies whether to include alignment projection from source text to translated text. + /// Possible values are: true or false (default). + /// + public bool? IncludeAlignment { get; set; } + /// + /// Specifies whether to include sentence boundaries for the input text and the translated text. + /// Possible values are: true or false (default). + /// + public bool? IncludeSentenceLength { get; set; } + /// + /// 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. + /// + public string SuggestedFrom { get; set; } + /// + /// Specifies the script of the input text. + /// + public string FromScript { get; set; } + /// + /// Specifies the script of the translated text. + /// + public string ToScript { get; set; } + /// + /// Specifies that the service is allowed to fall back to a general system when a custom system doesn't exist. + /// Possible values are: true (default) or false. + /// + /// 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. + /// + public bool? AllowFallback { get; set; } + + /// Initializes new instance of TextTranslationTranslateOptions. + /// + /// Specifies the language of the output text. The target language must be one of the supported languages included + /// in the translation scope. For example, use to=de to translate to German. + /// It's possible to translate to multiple languages simultaneously by repeating the parameter in the query string. + /// For example, use to=de&to=it to translate to German and Italian. + /// + /// Array of the text to be translated. + public TextTranslationTranslateOptions(IEnumerable targetLanguages, IEnumerable content) + { + Argument.AssertNotNull(targetLanguages, nameof(targetLanguages)); + Argument.AssertNotNull(content, nameof(content)); + TargetLanguages = targetLanguages; + Content = content; + } + + /// Initializes new instance of TextTranslationTranslateOptions. + /// + /// Specifies the language of the output text. The target language must be one of the supported languages included + /// in the translation scope. For example, use to=de to translate to German. + /// + /// Text to be translated. + public TextTranslationTranslateOptions(string targetLanguage, string content) + { + Argument.AssertNotNullOrWhiteSpace(targetLanguage, nameof(targetLanguage)); + Argument.AssertNotNullOrWhiteSpace(content, nameof(content)); + TargetLanguages = new[] { targetLanguage }; + Content = new[] { content }; + } + + /// Initializes new instance of TextTranslationTranslateOptions. + /// + /// Specifies the language of the output text. The target language must be one of the supported languages included + /// in the translation scope. For example, use to=de to translate to German. + /// It's possible to translate to multiple languages simultaneously by repeating the parameter in the query string. + /// For example, use to=de&to=it to translate to German and Italian. + /// + /// Array of the text to be translated. + /// A client-generated GUID to uniquely identify the request. + /// + /// Specifies the language of the input text. Find which languages are available to translate from by + /// looking up supported languages using the translation scope. If the from parameter isn't specified, + /// automatic language detection is applied to determine the source language. + /// + /// You must use the from parameter rather than autodetection when using the dynamic dictionary feature. + /// Note: the dynamic dictionary feature is case-sensitive. + /// + /// + /// Defines whether the text being translated is plain text or HTML text. Any HTML needs to be a well-formed, + /// complete element. Possible values are: plain (default) or html. + /// + /// + /// A string specifying the category (domain) of the translation. This parameter is used to get translations + /// from a customized system built with Custom Translator. Add the Category ID from your Custom Translator + /// project details to this parameter to use your deployed customized system. Default value is: general. + /// + /// + /// Specifies how profanities should be treated in translations. + /// Possible values are: NoAction (default), Marked or Deleted. + /// + /// + /// Specifies how profanities should be marked in translations. + /// Possible values are: Asterisk (default) or Tag. + /// + /// + /// Specifies whether to include alignment projection from source text to translated text. + /// Possible values are: true or false (default). + /// + /// + /// Specifies whether to include sentence boundaries for the input text and the translated text. + /// Possible values are: true or false (default). + /// + /// + /// 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. + /// + /// Specifies the script of the input text. + /// Specifies the script of the translated text. + /// + /// Specifies that the service is allowed to fall back to a general system when a custom system doesn't exist. + /// Possible values are: true (default) or false. + /// + /// 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. + /// + public TextTranslationTranslateOptions(IEnumerable targetLanguages, IEnumerable content, string clientTraceId = null, string sourceLanguage = null, TextType? textType = null, string category = null, ProfanityAction? profanityAction = null, ProfanityMarker? profanityMarker = null, bool? includeAlignment = null, bool? includeSentenceLength = null, string suggestedFrom = null, string fromScript = null, string toScript = null, bool? allowFallback = null): base() + { + TargetLanguages = targetLanguages; + Content = content; + ClientTraceId = clientTraceId; + SourceLanguage = sourceLanguage; + TextType = textType; + Category = category; + ProfanityAction = profanityAction; + ProfanityMarker = profanityMarker; + IncludeAlignment = includeAlignment; + IncludeSentenceLength = includeSentenceLength; + SuggestedFrom = suggestedFrom; + FromScript = fromScript; + ToScript = toScript; + AllowFallback = allowFallback; + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationTransliterateOptions.cs b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationTransliterateOptions.cs new file mode 100644 index 0000000000000..a1e7b57853bb2 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationTransliterateOptions.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core; +using System.Collections.Generic; + +namespace Azure.AI.Translation.Text +{ + /// Client options for TextTranslationClient.Transliterate + public partial class TextTranslationTransliterateOptions + { + /// + /// Specifies the language of the text to convert from one script to another. + /// Possible languages are listed in the transliteration scope obtained by querying the service + /// for its supported languages. + /// + public string Language { get; } + /// + /// Specifies the script used by the input text. Look up supported languages using the transliteration scope, + /// to find input scripts available for the selected language. + /// + public string FromScript { get; } + /// + /// Specifies the output script. Look up supported languages using the transliteration scope, to find output + /// scripts available for the selected combination of input language and input script. + /// + public string ToScript { get; } + /// + /// Array of the text to be transliterated. + /// + public IEnumerable Content { get; } + /// + /// A client-generated GUID to uniquely identify the request. + /// + public string ClientTraceId { get; set; } + + /// Initializes new instance of TextTranslationTransliterateOptions. + /// + /// Specifies the language of the text to convert from one script to another. + /// Possible languages are listed in the transliteration scope obtained by querying the service + /// for its supported languages. + /// + /// + /// Specifies the script used by the input text. Look up supported languages using the transliteration scope, + /// to find input scripts available for the selected language. + /// + /// + /// Specifies the output script. Look up supported languages using the transliteration scope, to find output + /// scripts available for the selected combination of input language and input script. + /// + /// Array of the text to be transliterated. + /// A client-generated GUID to uniquely identify the request. + public TextTranslationTransliterateOptions(string language, string fromScript, string toScript, IEnumerable content, string clientTraceId = null): base() + { + Language = language; + FromScript = fromScript; + ToScript = toScript; + Content = content; + ClientTraceId = clientTraceId; + } + + /// Initializes new instance of TextTranslationTransliterateOptions. + /// + /// Specifies the language of the text to convert from one script to another. + /// Possible languages are listed in the transliteration scope obtained by querying the service + /// for its supported languages. + /// + /// + /// Specifies the script used by the input text. Look up supported languages using the transliteration scope, + /// to find input scripts available for the selected language. + /// + /// + /// Specifies the output script. Look up supported languages using the transliteration scope, to find output + /// scripts available for the selected combination of input language and input script. + /// + /// The text to be transliterated. + /// A client-generated GUID to uniquely identify the request. + public TextTranslationTransliterateOptions(string language, string fromScript, string toScript, string content, string clientTraceId = null) + { + Language = language; + FromScript = fromScript; + ToScript = toScript; + Content = new[] { content }; + ClientTraceId = clientTraceId; + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/tests/Samples/SampleSnippets.cs b/sdk/translation/Azure.AI.Translation.Text/tests/Samples/SampleSnippets.cs index d9affd436b1f0..3f05e87edf15b 100644 --- a/sdk/translation/Azure.AI.Translation.Text/tests/Samples/SampleSnippets.cs +++ b/sdk/translation/Azure.AI.Translation.Text/tests/Samples/SampleSnippets.cs @@ -437,6 +437,32 @@ public void GetTextTranslation() #endregion } + [Test] + public void GetTextTranslationOptions() + { + TextTranslationClient client = CreateTextTranslationClient(); + + try + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "cs", + content: "This is a test." + ); + + Response> response = client.Translate(options); + 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}"); + } + } + [Test] public async void GetTextTranslationAsync() { @@ -568,7 +594,6 @@ public void GetMultipleTextTranslations() { TextTranslationClient client = CreateTextTranslationClient(); - #region Snippet:GetMultipleTextTranslations try { IEnumerable targetLanguages = new[] { "cs" }; @@ -593,6 +618,40 @@ public void GetMultipleTextTranslations() Console.WriteLine($"Error Code: {exception.ErrorCode}"); Console.WriteLine($"Message: {exception.Message}"); } + } + + [Test] + public void GetMultipleTextTranslationsOptions() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetMultipleTextTranslationsOptions + try + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguages: new[] { "cs" }, + content: new[] + { + "This is a test.", + "Esto es una prueba.", + "Dies ist ein Test." + } + ); + + Response> response = client.Translate(options); + 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 } @@ -659,6 +718,37 @@ public void GetTextTranslationMatrix() #endregion } + [Test] + public void GetTextTranslationMatrixOptions() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTextTranslationMatrixOptions + try + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguages: new[] { "cs", "es", "de" }, + content: new[] { "This is a test." } + ); + + Response> response = client.Translate(options); + 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() { @@ -1007,8 +1097,8 @@ public void GetTextTranslationSentences() 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)}"); + Console.WriteLine($"Source Sentence length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.SrcSentLen)}"); + Console.WriteLine($"Translated Sentence length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.TransSentLen)}"); } catch (RequestFailedException exception) { @@ -1039,8 +1129,8 @@ public async void GetTextTranslationSentencesAsync() 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)}"); + Console.WriteLine($"Source Sentence length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.SrcSentLen)}"); + Console.WriteLine($"Translated Sentence length: {string.Join(",", translation?.Translations?.FirstOrDefault()?.SentLen?.TransSentLen)}"); } catch (RequestFailedException exception) { @@ -1127,7 +1217,7 @@ public void GetTextTranslationSentencesSource() 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)}'."); + Console.WriteLine($"The detected sentence boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); } catch (RequestFailedException exception) { @@ -1156,7 +1246,7 @@ public async void GetTextTranslationSentencesSourceAsync() 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)}'."); + Console.WriteLine($"The detected sentence boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); } catch (RequestFailedException exception) { @@ -1182,7 +1272,7 @@ public void GetTextTranslationSentencesAuto() 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)}'."); + Console.WriteLine($"The detected sentence boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); } catch (RequestFailedException exception) { @@ -1208,7 +1298,7 @@ public async void GetTextTranslationSentencesAutoAsync() 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)}'."); + Console.WriteLine($"The detected sentence boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); } catch (RequestFailedException exception) { @@ -1245,6 +1335,35 @@ public void GetTransliteratedText() #endregion } + [Test] + public void GetTransliteratedTextOptions() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTransliteratedTextOptions + try + { + TextTranslationTransliterateOptions options = new TextTranslationTransliterateOptions( + language: "zh-Hans", + fromScript: "Hans", + toScript: "Latn", + content: "这是个测试。" + ); + + Response> response = client.Transliterate(options); + 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 + } + [Test] public async void GetTransliteratedTextAsync() { @@ -1304,6 +1423,39 @@ public void GetTranslationTextTransliterated() #endregion } + [Test] + public void GetTranslationTextTransliteratedOptions() + { + TextTranslationClient client = CreateTextTranslationClient(); + + #region Snippet:GetTranslationTextTransliteratedOptions + try + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "zh-Hans", + content: "hudha akhtabar.") + { + FromScript = "Latn", + SourceLanguage = "ar", + ToScript = "Latn" + }; + + Response> response = client.Translate(options); + 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 GetTranslationTextTransliteratedAsync() { @@ -1350,7 +1502,7 @@ public void FindTextSentenceSentenceBoundaries() 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)}'."); + Console.WriteLine($"The detected sentence boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); } catch (RequestFailedException exception) { @@ -1374,7 +1526,7 @@ public async void FindTextSentenceSentenceBoundariesAsync() 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)}'."); + Console.WriteLine($"The detected sentence boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); } catch (RequestFailedException exception) { diff --git a/sdk/translation/Azure.AI.Translation.Text/tests/TranslationLiveTests.cs b/sdk/translation/Azure.AI.Translation.Text/tests/TranslationLiveTests.cs index b1bb30aa76f91..a07086322de5b 100644 --- a/sdk/translation/Azure.AI.Translation.Text/tests/TranslationLiveTests.cs +++ b/sdk/translation/Azure.AI.Translation.Text/tests/TranslationLiveTests.cs @@ -39,6 +39,24 @@ public async Task TranslateBasic() Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); } + [RecordedTest] + public async Task TranslateBasicOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions(targetLanguage: "cs", content: "Hola mundo") + { + SourceLanguage = "es", + }; + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync( + options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual(1, response.Value.FirstOrDefault().Translations.Count); + Assert.AreEqual("cs", response.Value.FirstOrDefault().Translations.FirstOrDefault().To); + Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); + } + [RecordedTest] public async Task TranslateWithAutoDetect() { @@ -55,6 +73,21 @@ public async Task TranslateWithAutoDetect() Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); } + [RecordedTest] + public async Task TranslateWithAutoDetectOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions(targetLanguage: "cs", content: "This is a test."); + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual("en", response.Value.FirstOrDefault().DetectedLanguage.Language); + Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); + Assert.AreEqual("cs", response.Value.FirstOrDefault().Translations.FirstOrDefault().To); + Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); + } + [RecordedTest] public async Task TranslateWithNoTranslateTag() { @@ -70,6 +103,23 @@ public async Task TranslateWithNoTranslateTag() Assert.IsTrue(response.Value.FirstOrDefault().Translations.First().Text.Contains("今天是怎么回事是")); } + [RecordedTest] + public async Task TranslateWithNoTranslateTagOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions(targetLanguage: "en", content: "今天是怎么回事是非常可怕的") + { + SourceLanguage = "zh-chs", + TextType = TextType.Html + }; + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual(1, response.Value.FirstOrDefault().Translations.Count); + Assert.IsTrue(response.Value.FirstOrDefault().Translations.First().Text.Contains("今天是怎么回事是")); + } + [RecordedTest] public async Task TranslateWithDictionaryTag() { @@ -86,6 +136,23 @@ public async Task TranslateWithDictionaryTag() Assert.IsTrue(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text.Contains("wordomatic")); } + [RecordedTest] + public async Task TranslateWithDictionaryTagOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions(targetLanguage: "es", content: "The word < mstrans:dictionary translation =\"wordomatic\">wordomatic is a dictionary entry.") + { + SourceLanguage = "en" + }; + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual(1, response.Value.FirstOrDefault().Translations.Count); + Assert.AreEqual("es", response.Value.FirstOrDefault().Translations.FirstOrDefault().To); + Assert.IsTrue(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text.Contains("wordomatic")); + } + [RecordedTest] public async Task TranslateWithTransliteration() { @@ -102,6 +169,26 @@ public async Task TranslateWithTransliteration() Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); } + [RecordedTest] + public async Task TranslateWithTransliterationOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions(targetLanguage: "zh-Hans", content: "hudha akhtabar.") + { + SourceLanguage = "ar", + FromScript = "Latn", + ToScript = "Latn" + }; + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + + Assert.NotNull(response.Value.FirstOrDefault().SourceText.Text); + Assert.AreEqual("zh-Hans", response.Value.FirstOrDefault().Translations.FirstOrDefault().To); + Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); + } + [RecordedTest] public async Task TranslateFromLatinToLatinScript() { @@ -115,6 +202,25 @@ public async Task TranslateFromLatinToLatinScript() Assert.AreEqual("eppadi irukkiraai?", response.Value.FirstOrDefault().Translations.FirstOrDefault().Transliteration.Text); } + [RecordedTest] + public async Task TranslateFromLatinToLatinScriptOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "ta", + content: "ap kaise ho") + { + SourceLanguage = "hi", + FromScript = "Latn", + ToScript = "Latn", + }; + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Transliteration); + Assert.AreEqual("eppadi irukkiraai?", response.Value.FirstOrDefault().Translations.FirstOrDefault().Transliteration.Text); + } + [RecordedTest] public async Task TranslateWithMultipleInputTexts() { @@ -144,6 +250,37 @@ public async Task TranslateWithMultipleInputTexts() Assert.NotNull(response.Value[2].Translations.FirstOrDefault().Text); } + [RecordedTest] + public async Task TranslateWithMultipleInputTextsOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguages: new[] { "cs" }, + content: new[] + { + "This is a test.", + "Esto es una prueba.", + "Dies ist ein Test." + } + ); + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(3, response.Value.Count); + + Assert.AreEqual("en", response.Value.FirstOrDefault().DetectedLanguage.Language); + Assert.AreEqual("es", response.Value[1].DetectedLanguage.Language); + Assert.AreEqual("de", response.Value[2].DetectedLanguage.Language); + + Assert.AreEqual(1, response.Value.FirstOrDefault().DetectedLanguage.Score); + Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); + Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); + + Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); + Assert.NotNull(response.Value[1].Translations.FirstOrDefault().Text); + Assert.NotNull(response.Value[2].Translations.FirstOrDefault().Text); + } + [RecordedTest] public async Task TranslateMultipleTargetLanguages() { @@ -164,6 +301,28 @@ public async Task TranslateMultipleTargetLanguages() Assert.NotNull(response.Value.FirstOrDefault().Translations[2].Text); } + [RecordedTest] + public async Task TranslateMultipleTargetLanguagesOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguages: new[] { "cs", "es", "de" }, + content: new[] { "This is a test." } + ); + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual(3, response.Value.FirstOrDefault().Translations.Count); + + Assert.AreEqual("en", response.Value.FirstOrDefault().DetectedLanguage.Language); + Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); + + Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); + Assert.NotNull(response.Value.FirstOrDefault().Translations[1].Text); + Assert.NotNull(response.Value.FirstOrDefault().Translations[2].Text); + } + [RecordedTest] public async Task TranslateDifferentTextTypes() { @@ -180,6 +339,26 @@ public async Task TranslateDifferentTextTypes() Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); } + [RecordedTest] + public async Task TranslateDifferentTextTypesOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguages: new[] { "cs" }, + content: new[] { "This is a test." }) + { + TextType = TextType.Html + }; + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual(1, response.Value.FirstOrDefault().Translations.Count); + + Assert.AreEqual("en", response.Value.FirstOrDefault().DetectedLanguage.Language); + Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); + } + [RecordedTest] public async Task TranslateWithProfanity() { @@ -197,6 +376,28 @@ public async Task TranslateWithProfanity() Assert.AreEqual(1, response.Value.FirstOrDefault().Translations.Count); Assert.IsTrue(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text.Contains("***")); } + + [RecordedTest] + public async Task TranslateWithProfanityOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "zh-cn", + content: "shit this is fucking crazy") + { + ProfanityAction = ProfanityAction.Marked, + ProfanityMarker = ProfanityMarker.Asterisk, + }; + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual("en", response.Value.FirstOrDefault().DetectedLanguage.Language); + Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); + Assert.AreEqual(1, response.Value.FirstOrDefault().Translations.Count); + Assert.IsTrue(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text.Contains("***")); + } + [RecordedTest] public async Task TranslateWithAlignment() { @@ -214,6 +415,25 @@ public async Task TranslateWithAlignment() Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Alignment.Proj); } + public async Task TranslateWithAlignmentOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "cs", + content: "It is a beautiful morning") + { + IncludeAlignment = true, + }; + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual("en", response.Value.FirstOrDefault().DetectedLanguage.Language); + Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); + Assert.AreEqual(1, response.Value.FirstOrDefault().Translations.Count); + Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Alignment.Proj); + } + [RecordedTest] public async Task TranslateWithIncludeSentenceLength() { @@ -232,6 +452,27 @@ public async Task TranslateWithIncludeSentenceLength() Assert.AreEqual(3, response.Value.FirstOrDefault().Translations.FirstOrDefault().SentLen.TransSentLen.Count); } + [RecordedTest] + public async Task TranslateWithIncludeSentenceLengthOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "fr", + content: "La réponse se trouve dans la traduction automatique. La meilleure technologie de traduction automatique ne peut pas toujours fournir des traductions adaptées à un site ou des utilisateurs comme un être humain. Il suffit de copier et coller un extrait de code n'importe où.") + { + IncludeSentenceLength = true + }; + TextTranslationClient client = GetClient(); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual("fr", response.Value.FirstOrDefault().DetectedLanguage.Language); + Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); + Assert.AreEqual(1, response.Value.FirstOrDefault().Translations.Count); + Assert.AreEqual(3, response.Value.FirstOrDefault().Translations.FirstOrDefault().SentLen.SrcSentLen.Count); + Assert.AreEqual(3, response.Value.FirstOrDefault().Translations.FirstOrDefault().SentLen.TransSentLen.Count); + } + [RecordedTest] public async Task TranslateWithCustomEndpoint() { @@ -248,6 +489,24 @@ public async Task TranslateWithCustomEndpoint() Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); } + [RecordedTest] + public async Task TranslateWithCustomEndpointOptions() + { + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "cs", + content: "It is a beautiful morning" + ); + TextTranslationClient client = GetClient(endpoint: new Uri(TestEnvironment.CustomEndpoint)); + var response = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.AreEqual(1, response.Value.Count); + Assert.AreEqual("en", response.Value.FirstOrDefault().DetectedLanguage.Language); + Assert.LessOrEqual(0.5, response.Value.FirstOrDefault().DetectedLanguage.Score); + Assert.AreEqual(1, response.Value.FirstOrDefault().Translations.Count); + Assert.NotNull(response.Value.FirstOrDefault().Translations.FirstOrDefault().Text); + } + [RecordedTest] public async Task TranslateWithToken() { @@ -270,5 +529,31 @@ public async Task TranslateWithToken() Assert.AreEqual(200, translate.GetRawResponse().Status); Assert.AreEqual(1, translate.Value.Count); } + + [RecordedTest] + public async Task TranslateWithTokenOptions() + { + string accessToken; + if (Mode == RecordedTestMode.Playback) + { + accessToken = string.Empty; + } + else + { + accessToken = await GetAzureAuthorizationTokenAsync(); + } + + TokenCredential token = new StaticAccessTokenCredential(new AccessToken(accessToken, DateTimeOffset.Now.AddDays(1))); + + TextTranslationClient client = GetClient(token: token); + TextTranslationTranslateOptions options = new TextTranslationTranslateOptions( + targetLanguage: "cs", + content: "This is a test." + ); + var translate = await client.TranslateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, translate.GetRawResponse().Status); + Assert.AreEqual(1, translate.Value.Count); + } } } diff --git a/sdk/translation/Azure.AI.Translation.Text/tests/TransliterationLiveTests.cs b/sdk/translation/Azure.AI.Translation.Text/tests/TransliterationLiveTests.cs index bf513695fc0ca..5ebfe98132278 100644 --- a/sdk/translation/Azure.AI.Translation.Text/tests/TransliterationLiveTests.cs +++ b/sdk/translation/Azure.AI.Translation.Text/tests/TransliterationLiveTests.cs @@ -32,6 +32,21 @@ public async Task VerifyTransliterationTest() Assert.AreEqual(200, response.GetRawResponse().Status); } + [RecordedTest] + public async Task VerifyTransliterationTestOptions() + { + TextTranslationClient client = GetClient(); + TextTranslationTransliterateOptions options = new TextTranslationTransliterateOptions( + language: "zh-Hans", + fromScript: "Hans", + toScript: "Latn", + content: new[] { "这里怎么一回事?" } + ); + Response> response = + await client.TransliterateAsync(options).ConfigureAwait(false); + Assert.AreEqual(200, response.GetRawResponse().Status); + } + [RecordedTest] public async Task VerifyTransliterationWithMultipleTextArray() { @@ -48,6 +63,27 @@ public async Task VerifyTransliterationWithMultipleTextArray() Assert.IsFalse(string.IsNullOrEmpty(response.Value[1].Text)); } + [RecordedTest] + public async Task VerifyTransliterationWithMultipleTextArrayOptions() + { + TextTranslationClient client = GetClient(); + TextTranslationTransliterateOptions options = new TextTranslationTransliterateOptions( + language: "hi", + fromScript: "Deva", + toScript: "Latn", + content: new[] + { + "यहएककसौटीहैयहएककसौटीहै", + "यहएककसौटीहै" + } + ); + Response> response = await client.TransliterateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.IsFalse(string.IsNullOrEmpty(response.Value[0].Text)); + Assert.IsFalse(string.IsNullOrEmpty(response.Value[1].Text)); + } + [RecordedTest] public async Task VerifyTransliterationWithEditDistance() { @@ -75,5 +111,39 @@ public async Task VerifyTransliterationWithEditDistance() } Assert.IsTrue(editDistance < 6, $"Total string distance: {editDistance}"); } + + [RecordedTest] + public async Task VerifyTransliterationWithEditDistanceOptions() + { + TextTranslationClient client = GetClient(); + + TextTranslationTransliterateOptions options = new TextTranslationTransliterateOptions( + language: "gu", + fromScript: "latn", + toScript: "gujr", + content: new[] + { + "gujarat", + "hadman", + "hukkabar" + } + ); + Response> response = await client.TransliterateAsync(options).ConfigureAwait(false); + + Assert.AreEqual(200, response.GetRawResponse().Status); + Assert.IsFalse(string.IsNullOrEmpty(response.Value[0].Text)); + Assert.IsFalse(string.IsNullOrEmpty(response.Value[1].Text)); + Assert.IsFalse(string.IsNullOrEmpty(response.Value[2].Text)); + + List expectedText = new() + { "ગુજરાત", "હદમાં", "હુક્કાબાર" }; + + int editDistance = 0; + for (int i = 0; i < expectedText.Count; i++) + { + editDistance = editDistance + TestHelper.EditDistance(expectedText[i], response.Value[i].Text); + } + Assert.IsTrue(editDistance < 6, $"Total string distance: {editDistance}"); + } } }