diff --git a/sdk/translation/Azure.AI.Translation.Text/Azure.AI.Translation.Text.sln b/sdk/translation/Azure.AI.Translation.Text/Azure.AI.Translation.Text.sln new file mode 100644 index 0000000000000..03dda3d8f866d --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/Azure.AI.Translation.Text.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33424.131 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.TestFramework", "..\..\core\Azure.Core.TestFramework\src\Azure.Core.TestFramework.csproj", "{ECC730C1-4AEA-420C-916A-66B19B79E4DC}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.AI.Translation.Text", "src\Azure.AI.Translation.Text.csproj", "{1DA1D204-899B-4F27-B49D-D016CEB9EB3D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.AI.Translation.Text.Tests", "tests\Azure.AI.Translation.Text.Tests.csproj", "{D215EFB8-84E4-4C2F-8924-F5980FC89EDB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.Build.0 = Release|Any CPU + {1DA1D204-899B-4F27-B49D-D016CEB9EB3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1DA1D204-899B-4F27-B49D-D016CEB9EB3D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1DA1D204-899B-4F27-B49D-D016CEB9EB3D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1DA1D204-899B-4F27-B49D-D016CEB9EB3D}.Release|Any CPU.Build.0 = Release|Any CPU + {D215EFB8-84E4-4C2F-8924-F5980FC89EDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D215EFB8-84E4-4C2F-8924-F5980FC89EDB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D215EFB8-84E4-4C2F-8924-F5980FC89EDB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D215EFB8-84E4-4C2F-8924-F5980FC89EDB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/translation/Azure.AI.Translation.Text/CHANGELOG.md b/sdk/translation/Azure.AI.Translation.Text/CHANGELOG.md new file mode 100644 index 0000000000000..1d791073556ad --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/CHANGELOG.md @@ -0,0 +1,18 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) +Initial version of Text Translation client library for .NET + +### Features Added +- Added support for Text Translation - [Translate API](https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate) +- Added support for Text Transliteration - [Transliterate API](https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-transliterate) +- Added support for Finding Sentence Boundaries - [FindSentenceBoundaries API](https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-break-sentence) +- Added support for Getting the Supported Languages - [GetLanguages API](https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-languages) +- Added support for Looking up the Dictionary Entries - [LookupDictionaryEntries API](https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-lookup) +- Added support for Looking up the Dictionary Examples - [LookupDictionaryExamples API](https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-examples) + +### Breaking Changes + +### Bugs Fixed + +### Other Changes diff --git a/sdk/translation/Azure.AI.Translation.Text/Directory.Build.props b/sdk/translation/Azure.AI.Translation.Text/Directory.Build.props new file mode 100644 index 0000000000000..1a9611bd49242 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/translation/Azure.AI.Translation.Text/README.md b/sdk/translation/Azure.AI.Translation.Text/README.md new file mode 100644 index 0000000000000..3c7486dfe906f --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/README.md @@ -0,0 +1,379 @@ +# Azure Text Translation client library for .NET + +Text translation is a cloud-based REST API feature of the Translator service that uses neural machine translation technology to enable quick and accurate source-to-target text translation in real time across all supported languages. + +Use the Text Translation client library for .NET to: + +* Return a list of languages supported by Translate, Transliterate, and Dictionary operations. + +* Render single source-language text to multiple target-language texts with a single request. + +* Convert text of a source language in letters of a different script. + +* Return equivalent words for the source term in the target language. + +* Return grammatical structure and context examples for the source term and target term pair. + +[Source code](https://aka.ms/https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/src) | [Package (NuGet)](https://aka.ms/https://www.nuget.org/packages/Azure.AI.Translation.Text) | [API reference documentation](https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-reference) | [Product documentation](https://learn.microsoft.com/azure/cognitive-services/translator/) + +## Getting started + +### Install the package + +Install the Azure Text Translation client library for .NET with [NuGet][nuget]: + +```dotnetcli +dotnet add package Azure.AI.Translation.Text --prerelease +``` + +This table shows the relationship between SDK versions and supported API versions of the service: + +|SDK version |Supported API version of service +|-------------|-----------------------------------------------------| +|1.0.0-beta.1 | 3.0 + +### Prerequisites + +* An [Azure subscription][azure_sub]. +* An existing Translator service or Cognitive Services resource. You can create Translator resource following [Create a Translator resource][translator_resource_create]. + +### Authenticate the client + +Interaction with the service using the client library begins with creating an instance of the [TextTranslationClient][translator_client_class] class. You will need an **API key** or ``TokenCredential`` to instantiate a client object. For more information regarding authenticating with Cognitive Services, see [Authenticate requests to Translator Service][translator_auth]. + +#### Get an API key + +You can get the `endpoint`, `API key` and `Region` from the Cognitive Services resource or Translator service resource information in the [Azure Portal][azure_portal]. + +Alternatively, use the [Azure CLI][azure_cli] snippet below to get the API key from the Translator service resource. + +```PowerShell +az cognitiveservices account keys list --resource-group --name +``` + +#### Create a `TextTranslationClient` using an API key and Region credential + +Once you have the value for the API key and Region, create an `AzureKeyCredential`. This will allow you to +update the API key without creating a new client. + +With the value of the endpoint, `AzureKeyCredential` and a `Region`, you can create the [TextTranslationClient][translator_client_class]: + +```C# +AzureKeyCredential credential = new(""); +TextTranslationClient client = new(credential, ""); +``` + +## Key concepts + +### `TextTranslationClient` + +A `TextTranslationClient` is the primary interface for developers using the Text Translation client library. It provides both synchronous and asynchronous operations to access a specific use of text translator, such as get supported languages detection or text translation. + +### Input + +A **text element** (`string`), is a single unit of input to be processed by the translation models in the Translator service. Operations on `TextTranslationClient` may take a single text element or a collection of text elements. +For text element length limits, maximum requests size, and supported text encoding see [here][translator_limits]. + +### Return value + +Return values, such as `Response>`, is the result of a Text Translation operation, It contains array with one result for each string in the input array. An operation's return value also may optionally include information about the input text element (for example detected language). + +### Thread safety + +We guarantee that all client instance methods are thread-safe and independent of each other ([guideline](https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-service-methods-thread-safety)). This ensures that the recommendation of reusing client instances is always safe, even across threads. + +### Additional concepts + +[Client options](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#configuring-service-clients-using-clientoptions) | +[Accessing the response](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#accessing-http-response-details-using-responset) | +[Long-running operations](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#consuming-long-running-operations-using-operationt) | +[Handling failures](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#reporting-errors-requestfailedexception) | +[Diagnostics](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md) | +[Mocking](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#mocking) | +[Client lifetime](https://devblogs.microsoft.com/azure-sdk/lifetime-management-and-thread-safety-guarantees-of-azure-sdk-net-clients/) + + +## Examples + +The following section provides several code snippets using the `client` [created above](#create-a-texttranslationclient-using-an-api-key-and-region-credential), and covers the main features present in this client library. Although most of the snippets below make use of asynchronous service calls, keep in mind that the `Azure.AI.Translation.Text` package supports both synchronous and asynchronous APIs. + +### Get Supported Languages + +Gets the set of languages currently supported by other operations of the Translator. + +```C# +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}"); +} +``` + +For samples on using the `languages` endpoint refer to more samples [here][languages_sample]. + +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. + +```C# +try +{ + string targetLanguage = "cs"; + string inputText = "This is a test."; + + Response> response = await client.TranslateAsync(targetLanguage, inputText).ConfigureAwait(false); + IReadOnlyList translations = response.Value; + TranslatedTextElement translation = translations.FirstOrDefault(); + + Console.WriteLine($"Detected languages of the input text: {translation?.DetectedLanguage?.Language} with score: {translation?.DetectedLanguage?.Score}."); + Console.WriteLine($"Text was translated to: '{translation?.Translations?.FirstOrDefault().To}' and the result is: '{translation?.Translations?.FirstOrDefault()?.Text}'."); +} +catch (RequestFailedException exception) +{ + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); +} +``` + +For samples on using the `translate` endpoint refer to more samples [here][translate_sample]. + +Please refer to the service documentation for a conceptual discussion of [translate][translate_doc]. + +### Transliterate + +Converts characters or letters of a source language to the corresponding characters or letters of a target language. + +```C# +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}"); +} +``` + +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]. + +### Break Sentence + +Identifies the positioning of sentence boundaries in a piece of text. + +```C# +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; + BreakSentenceElement brokenSentence = brokenSentences.FirstOrDefault(); + + Console.WriteLine($"Detected languages of the input text: {brokenSentence?.DetectedLanguage?.Language} with score: {brokenSentence?.DetectedLanguage?.Score}."); + Console.WriteLine($"The detected sentece boundaries: '{string.Join(",", brokenSentence?.SentLen)}'."); + +} +catch (RequestFailedException exception) +{ + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); +} +``` + +For samples on using the `break sentece` endpoint refer to more samples [here][breaksentence_sample]. + +Please refer to the service documentation for a conceptual discussion of [break sentence][breaksentence_doc]. + +### Dictionary Lookup + +Returns equivalent words for the source term in the target language. + +```C# +try +{ + string sourceLanguage = "en"; + string targetLanguage = "es"; + string inputText = "fly"; + + Response> response = await client.LookupDictionaryEntriesAsync(sourceLanguage, targetLanguage, inputText).ConfigureAwait(false); + IReadOnlyList dictionaryEntries = response.Value; + DictionaryLookupElement dictionaryEntry = dictionaryEntries.FirstOrDefault(); + + Console.WriteLine($"For the given input {dictionaryEntry?.Translations?.Count} entries were found in the dictionary."); + Console.WriteLine($"First entry: '{dictionaryEntry?.Translations?.FirstOrDefault()?.DisplayTarget}', confidence: {dictionaryEntry?.Translations?.FirstOrDefault()?.Confidence}."); + +} +catch (RequestFailedException exception) +{ + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); +} +``` + +For samples on using the `dictionary lookup` endpoint refer to more samples [here][dictionarylookup_sample]. + +Please refer to the service documentation for a conceptual discussion of [dictionary lookup][dictionarylookup_doc]. + +### Dictionary Examples + +Returns grammatical structure and context examples for the source term and target term pair. + +```C# +try +{ + string sourceLanguage = "en"; + string targetLanguage = "es"; + IEnumerable inputTextElements = new[] + { + new InputTextWithTranslation { Text = "fly", Translation = "volar" } + }; + + Response> response = await client.LookupDictionaryExamplesAsync(sourceLanguage, targetLanguage, inputTextElements).ConfigureAwait(false); + IReadOnlyList dictionaryEntries = response.Value; + DictionaryExampleElement dictionaryEntry = dictionaryEntries.FirstOrDefault(); + + Console.WriteLine($"For the given input {dictionaryEntry?.Examples?.Count} examples were found in the dictionary."); + Example firstExample = dictionaryEntry?.Examples?.FirstOrDefault(); + Console.WriteLine($"Example: '{string.Concat(firstExample.TargetPrefix, firstExample.TargetTerm, firstExample.TargetSuffix)}'."); + +} +catch (RequestFailedException exception) +{ + Console.WriteLine($"Error Code: {exception.ErrorCode}"); + Console.WriteLine($"Message: {exception.Message}"); +} +``` + +For samples on using the `dictionary examples` endpoint refer to more samples [here][dictionaryexamples_sample]. + +Please refer to the service documentation for a conceptual discussion of [dictionary examples][dictionaryexamples_doc]. + +## Troubleshooting + +When you interact with the Translator Service using the Text Translation client library, errors returned by the Translator service correspond to the same HTTP status codes returned for REST API requests. + +For example, if you submit a translation request without a target translate language, a `400` error is returned, indicating "Bad Request". + +```C# +try +{ + var translation = client.TranslateAsync(Array.Empty(), new[] { new InputText { Text = "This is a Test" } }).ConfigureAwait(false); +} +catch (RequestFailedException e) +{ + Console.WriteLine(e.ToString()); +} +``` + +You will notice that additional information is logged, like the client request ID of the operation. + +```text +Message: + Azure.RequestFailedException: Service request failed. + Status: 400 (Bad Request) + +Content: + {"error":{"code":400036,"message":"The target language is not valid."}} + +Headers: + X-RequestId: REDACTED + Access-Control-Expose-Headers: REDACTED + X-Content-Type-Options: REDACTED + Strict-Transport-Security: REDACTED + Date: Mon, 27 Feb 2023 23:31:37 GMT + Content-Type: text/plain; charset=utf-8 + Content-Length: 71 +``` + +### Setting up console logging + +The simplest way to see the logs is to enable the console logging. +To create an Azure SDK log listener that outputs messages to console use AzureEventSourceListener.CreateConsoleLogger method. + +```C# +// Setup a listener to monitor logged events. +using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(); +``` + +To learn more about other logging mechanisms see [here][logging]. + +## Next steps + +Samples showing how to use this client library are available in this GitHub repository. +Samples are provided for each main functional area, and for each area, samples are provided in both sync and async mode. + +* [Create TextTranslationClient][client_sample] +* [Languages][languages_sample] +* [Translate][translate_sample] +* [Transliterate][transliterate_sample] +* [Break Sentence][breaksentence_sample] +* [Dictionary Lookup][dictionarylookup_sample] +* [Dictionary Examples][dictionaryexamples_sample] + +## Contributing + +See the [CONTRIBUTING.md][contributing] for details on building, testing, and contributing to this library. + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla]. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments. + + +[contributing]: https://github.com/Azure/azure-sdk-for-net/blob/main/CONTRIBUTING.md +[cla]: https://cla.microsoft.com +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ +[coc_contact]: mailto:opencode@microsoft.com + +[translator_client_class]: https://aka.ms/https://github.com/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/src/TextTranslationClient.cs + +[translator_auth]: https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-reference#authentication +[translator_limits]: https://learn.microsoft.com/azure/cognitive-services/translator/request-limits + +[languages_doc]: https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-languages +[translate_doc]: https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate +[transliterate_doc]: https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-transliterate +[breaksentence_doc]: https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-break-sentence +[dictionarylookup_doc]: https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-lookup +[dictionaryexamples_doc]: https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-examples + +[client_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md +[languages_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample1_GetLanguages.md +[translate_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md +[transliterate_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample3_Transliterate.md +[breaksentence_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample4_BreakSentence.md +[dictionarylookup_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample5_DictionaryLookup.md +[dictionaryexamples_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample6_DictionaryExamples.md + +[translator_resource_create]: https://learn.microsoft.com/azure/cognitive-services/Translator/create-translator-resource + +[logging]: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md + +[azure_cli]: https://docs.microsoft.com/cli/azure +[azure_sub]: https://azure.microsoft.com/free/dotnet/ +[nuget]: https://www.nuget.org/ +[azure_portal]: https://portal.azure.com 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 new file mode 100644 index 0000000000000..337fdd4154a65 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.netstandard2.0.cs @@ -0,0 +1,262 @@ +namespace Azure.AI.Translation.Text +{ + public partial class BackTranslation + { + internal BackTranslation() { } + public string DisplayText { get { throw null; } } + public int FrequencyCount { get { throw null; } } + public string NormalizedText { get { throw null; } } + public int NumExamples { get { throw null; } } + } + public partial class BreakSentenceItem + { + internal BreakSentenceItem() { } + public Azure.AI.Translation.Text.DetectedLanguage DetectedLanguage { get { throw null; } } + public System.Collections.Generic.IReadOnlyList SentLen { get { throw null; } } + } + public partial class CommonScriptModel + { + internal CommonScriptModel() { } + public string Code { get { throw null; } } + public string Dir { get { throw null; } } + public string Name { get { throw null; } } + public string NativeName { get { throw null; } } + } + public partial class DetectedLanguage + { + internal DetectedLanguage() { } + public string Language { get { throw null; } } + public float Score { get { throw null; } } + } + public partial class DictionaryExample + { + internal DictionaryExample() { } + public string SourcePrefix { get { throw null; } } + public string SourceSuffix { get { throw null; } } + public string SourceTerm { get { throw null; } } + public string TargetPrefix { get { throw null; } } + public string TargetSuffix { get { throw null; } } + public string TargetTerm { get { throw null; } } + } + public partial class DictionaryExampleItem + { + internal DictionaryExampleItem() { } + public System.Collections.Generic.IReadOnlyList Examples { get { throw null; } } + public string NormalizedSource { get { throw null; } } + public string NormalizedTarget { get { throw null; } } + } + public partial class DictionaryLookupItem + { + internal DictionaryLookupItem() { } + public string DisplaySource { get { throw null; } } + public string NormalizedSource { get { throw null; } } + public System.Collections.Generic.IReadOnlyList Translations { get { throw null; } } + } + public partial class DictionaryTranslation + { + internal DictionaryTranslation() { } + public System.Collections.Generic.IReadOnlyList BackTranslations { get { throw null; } } + public float Confidence { get { throw null; } } + public string DisplayTarget { get { throw null; } } + public string NormalizedTarget { get { throw null; } } + public string PosTag { get { throw null; } } + public string PrefixWord { get { throw null; } } + } + public partial class GetLanguagesResult + { + internal GetLanguagesResult() { } + public System.Collections.Generic.IReadOnlyDictionary Dictionary { get { throw null; } } + public System.Collections.Generic.IReadOnlyDictionary Translation { get { throw null; } } + public System.Collections.Generic.IReadOnlyDictionary Transliteration { get { throw null; } } + } + public partial class InputTextWithTranslation + { + public InputTextWithTranslation(string word, string translation) { } + public string Text { get { throw null; } } + public string Translation { get { throw null; } } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct ProfanityAction : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public ProfanityAction(string value) { throw null; } + public static Azure.AI.Translation.Text.ProfanityAction Deleted { get { throw null; } } + public static Azure.AI.Translation.Text.ProfanityAction Marked { get { throw null; } } + public static Azure.AI.Translation.Text.ProfanityAction NoAction { get { throw null; } } + public bool Equals(Azure.AI.Translation.Text.ProfanityAction other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.AI.Translation.Text.ProfanityAction left, Azure.AI.Translation.Text.ProfanityAction right) { throw null; } + public static implicit operator Azure.AI.Translation.Text.ProfanityAction (string value) { throw null; } + public static bool operator !=(Azure.AI.Translation.Text.ProfanityAction left, Azure.AI.Translation.Text.ProfanityAction right) { throw null; } + public override string ToString() { throw null; } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct ProfanityMarker : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public ProfanityMarker(string value) { throw null; } + public static Azure.AI.Translation.Text.ProfanityMarker Asterisk { get { throw null; } } + public static Azure.AI.Translation.Text.ProfanityMarker Tag { get { throw null; } } + public bool Equals(Azure.AI.Translation.Text.ProfanityMarker other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.AI.Translation.Text.ProfanityMarker left, Azure.AI.Translation.Text.ProfanityMarker right) { throw null; } + public static implicit operator Azure.AI.Translation.Text.ProfanityMarker (string value) { throw null; } + public static bool operator !=(Azure.AI.Translation.Text.ProfanityMarker left, Azure.AI.Translation.Text.ProfanityMarker right) { throw null; } + public override string ToString() { throw null; } + } + public partial class SentenceLength + { + internal SentenceLength() { } + public System.Collections.Generic.IReadOnlyList SrcSentLen { get { throw null; } } + public System.Collections.Generic.IReadOnlyList TransSentLen { get { throw null; } } + } + public partial class SourceDictionaryLanguage + { + internal SourceDictionaryLanguage() { } + public string Dir { get { throw null; } } + public string Name { get { throw null; } } + public string NativeName { get { throw null; } } + public System.Collections.Generic.IReadOnlyList Translations { get { throw null; } } + } + public partial class SourceText + { + internal SourceText() { } + public string Text { get { throw null; } } + } + public partial class TargetDictionaryLanguage + { + internal TargetDictionaryLanguage() { } + public string Code { get { throw null; } } + public string Dir { get { throw null; } } + public string Name { get { throw null; } } + public string NativeName { get { throw null; } } + } + public partial class TextTranslationClient + { + protected TextTranslationClient() { } + public TextTranslationClient(Azure.AzureKeyCredential credential, string region = "global", Azure.AI.Translation.Text.TextTranslationClientOptions options = null) { } + public TextTranslationClient(Azure.AzureKeyCredential credential, System.Uri endpoint, string region = "global", Azure.AI.Translation.Text.TextTranslationClientOptions options = null) { } + public TextTranslationClient(Azure.Core.TokenCredential credential, Azure.AI.Translation.Text.TextTranslationClientOptions options = null) { } + public TextTranslationClient(Azure.Core.TokenCredential credential, System.Uri endpoint, Azure.AI.Translation.Text.TextTranslationClientOptions options = null) { } + protected TextTranslationClient(System.Uri endpoint) { } + protected TextTranslationClient(System.Uri endpoint, Azure.AI.Translation.Text.TextTranslationClientOptions options) { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response> FindSentenceBoundaries(System.Collections.Generic.IEnumerable content, string clientTraceId = null, string language = null, string script = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response> FindSentenceBoundaries(string text, string clientTraceId = null, string language = null, string script = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task>> FindSentenceBoundariesAsync(System.Collections.Generic.IEnumerable content, string clientTraceId = null, string language = null, string script = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task>> FindSentenceBoundariesAsync(string text, string clientTraceId = null, string language = null, string script = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response GetLanguages(string clientTraceId = null, string scope = null, string acceptLanguage = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task> GetLanguagesAsync(string clientTraceId = null, string scope = null, string acceptLanguage = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response> LookupDictionaryEntries(string from, string to, System.Collections.Generic.IEnumerable words, string clientTraceId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response> LookupDictionaryEntries(string from, string to, string word, string clientTraceId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task>> LookupDictionaryEntriesAsync(string from, string to, System.Collections.Generic.IEnumerable words, string clientTraceId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task>> LookupDictionaryEntriesAsync(string from, string to, string word, string clientTraceId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response> LookupDictionaryExamples(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 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(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(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(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(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; } + } + public partial class TextTranslationClientOptions : Azure.Core.ClientOptions + { + public TextTranslationClientOptions(Azure.AI.Translation.Text.TextTranslationClientOptions.ServiceVersion version = Azure.AI.Translation.Text.TextTranslationClientOptions.ServiceVersion.V3_0) { } + public enum ServiceVersion + { + V3_0 = 1, + } + } + [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] + public readonly partial struct TextType : System.IEquatable + { + private readonly object _dummy; + private readonly int _dummyPrimitive; + public TextType(string value) { throw null; } + public static Azure.AI.Translation.Text.TextType Html { get { throw null; } } + public static Azure.AI.Translation.Text.TextType Plain { get { throw null; } } + public bool Equals(Azure.AI.Translation.Text.TextType other) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override bool Equals(object obj) { throw null; } + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + public override int GetHashCode() { throw null; } + public static bool operator ==(Azure.AI.Translation.Text.TextType left, Azure.AI.Translation.Text.TextType right) { throw null; } + public static implicit operator Azure.AI.Translation.Text.TextType (string value) { throw null; } + public static bool operator !=(Azure.AI.Translation.Text.TextType left, Azure.AI.Translation.Text.TextType right) { throw null; } + public override string ToString() { throw null; } + } + public partial class TranslatedTextAlignment + { + internal TranslatedTextAlignment() { } + public string Proj { get { throw null; } } + } + public partial class TranslatedTextItem + { + internal TranslatedTextItem() { } + public Azure.AI.Translation.Text.DetectedLanguage DetectedLanguage { get { throw null; } } + public Azure.AI.Translation.Text.SourceText SourceText { get { throw null; } } + public System.Collections.Generic.IReadOnlyList Translations { get { throw null; } } + } + public partial class Translation + { + internal Translation() { } + public Azure.AI.Translation.Text.TranslatedTextAlignment Alignment { get { throw null; } } + public Azure.AI.Translation.Text.SentenceLength SentLen { get { throw null; } } + public string Text { get { throw null; } } + public string To { get { throw null; } } + public Azure.AI.Translation.Text.TransliteratedText Transliteration { get { throw null; } } + } + public partial class TranslationLanguage + { + internal TranslationLanguage() { } + public string Dir { get { throw null; } } + public string Name { get { throw null; } } + public string NativeName { get { throw null; } } + } + public partial class TransliterableScript : Azure.AI.Translation.Text.CommonScriptModel + { + internal TransliterableScript() { } + public System.Collections.Generic.IReadOnlyList ToScripts { get { throw null; } } + } + public partial class TransliteratedText + { + internal TransliteratedText() { } + public string Script { get { throw null; } } + public string Text { get { throw null; } } + } + public partial class TransliterationLanguage + { + internal TransliterationLanguage() { } + public string Name { get { throw null; } } + public string NativeName { get { throw null; } } + public System.Collections.Generic.IReadOnlyList Scripts { get { throw null; } } + } +} +namespace Azure.AI.Translation.Text.Custom +{ + public static partial class TextTranslationClientBuilderExtensions + { + public static Azure.Core.Extensions.IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, Azure.AzureKeyCredential credential) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, Azure.AzureKeyCredential credential, string region) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, Azure.AzureKeyCredential credential, System.Uri endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, Azure.AzureKeyCredential credential, System.Uri endpoint, string region) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, Azure.Core.TokenCredential credential) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, Azure.Core.TokenCredential credential, System.Uri endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/README.md b/sdk/translation/Azure.AI.Translation.Text/samples/README.md new file mode 100644 index 0000000000000..0b50dd90db970 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/samples/README.md @@ -0,0 +1,45 @@ +--- +page_type: sample +languages: +- csharp +products: +- azure +- azure-cognitive-services +- azure-translator +name: Azure.AI.Translation.Text samples for .NET +description: Samples for the Azure.AI.Translation.Text client library. +--- + +# Azure Text Translation client library for .NET + +Translator Service is a cloud-based neural machine translation service that is part of the Azure Cognitive Services family of REST APIs and can be used with any operating system. This client library offers the following features: + +* Get Supported Languages +* Translate +* Transliterate +* Break Sentence +* Dictionary Lookup +* Dictionary Examples + +See the [README][README] of the Text Analytics client library for more information, including useful links and instructions. + +## Common scenarios samples + +* [Create a `TextTranslationClient`][create_client_sample] +* [Get Languages][languages_sample] +* [Translate][translate_sample] +* [Transliterate][transliterate_sample] +* [Break Sentence][breaksentence_sample] +* [Dictionary Lookup][dictionarylookup_sample] +* [Dictionary Examples][dictionaryexamples_sample] + + +[README]: https://aka.ms/https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/README.md + +[create_client_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md +[languages_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample1_GetLanguages.md +[translate_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md +[transliterate_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample3_Transliterate.md +[breaksentence_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample4_BreakSentence.md +[dictionarylookup_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample5_DictionaryLookup.md +[dictionaryexamples_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample6_DictionaryExamples.md diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md new file mode 100644 index 0000000000000..414d15d5dffbc --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md @@ -0,0 +1,67 @@ +# Create Text Translation Client + +## Creating Cognitive Services resource + +Text translation supports both [multi-service and single-service access][service_access]. Create a Cognitive Services resource if you plan to access multiple Cognitive Services under a single endpoint and API key. To access the features of the Text translation service only, create a Text translation service resource instead. + +You can create Cognitive Services resource via the [Azure portal][cognitive_resource_azure_portal] or, alternatively, you can follow the steps in [this document][cognitive_resource_azure_cli] to create it using the [Azure CLI][azure_cli]. + +## Create a `TextTranslationClient` using an API key from Global Text Translator resource + +Once you have the value for the API key, create an `AzureKeyCredential`. + +With the value of the `AzureKeyCredential`, you can create the [TextTranslationClient][translator_client_class]: + +```C# +AzureKeyCredential credential = new(""); +TextTranslationClient client = new(credential); +``` + +> Replace `` with a value created in [Creating Cognitive Services resource](#creating-cognitive-services-resource). + +## Create a `TextTranslationClient` using an API key and Region credential + +Once you have the value for the API key and Region, create an `AzureKeyCredential`. This will allow you to update the API key without creating a new client. + +With the value of the `AzureKeyCredential` and a `Region`, you can create the [TextTranslationClient][translator_client_class]: + +```C# +AzureKeyCredential credential = new(""); +TextTranslationClient client = new(credential, ""); +``` + +> Replace `` and `` with a value created in [Creating Cognitive Services resource](#creating-cognitive-services-resource). + +## Create a `TextTranslationClient` using a Custom Subdomain and Api Key + +When Translator service is configured to use [Virtual Network (VNET)][translator_vnet] capability you need to use [custom subdomain][custom_subdomain]. + +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); +``` + +> Replace `` with a value created in [Creating Cognitive Services resource](#creating-cognitive-services-resource). + +## Create a `TextTranslationClient` using a Token Authentication + +Instead of API key and Region authentication you can use JWT token. For information on how to create token refer to [Authenticating with an access token][translator_token]. + +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(); +TextTranslationClient client = new(credential); +``` + +[translator_client_class]: https://aka.ms/https://github.com/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/src/TextTranslationClient.cs +[translator_vnet]: https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-reference#virtual-network-support +[custom_subdomain]: https://docs.microsoft.com/azure/cognitive-services/authentication#create-a-resource-with-a-custom-subdomain +[translator_token]: https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-reference#authenticating-with-an-access-token +[cognitive_resource_azure_portal]: https://learn.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account +[cognitive_resource_azure_cli]: https://learn.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account-cli +[azure_cli]: https://docs.microsoft.com/cli/azure +[service_access]: https://learn.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample1_GetLanguages.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample1_GetLanguages.md new file mode 100644 index 0000000000000..5462d8d47508e --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample1_GetLanguages.md @@ -0,0 +1,128 @@ +# Get Languages + +This sample demonstrates how to get languages that are supported by other operations. All samples are using `client` created in [Create a `TextTranslationClient`][create_client_sample] samples. + +## Get Supported Languages for ALL other operations + +This will return language metadata from all supported scopes. + +```C# +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}"); +} +``` + +### Get Supported Languages for a given scope + +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# +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}"); +} +``` + +### Get Languages in a given culture + +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# +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}"); +} +``` + +See the [README] of the Text Translation client library for more information, including useful links and instructions. + +[README]: https://aka.ms/https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/README.md +[create_client_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md new file mode 100644 index 0000000000000..66fbb3963cf02 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample2_Translate.md @@ -0,0 +1,366 @@ +# Translate + +All samples are using `client` created in [Create a `TextTranslationClient`][create_client_sample] samples. + +## Translate text + +Translate text from known source language to target language. + +```C# +try +{ + string from = "en"; + string targetLanguage = "cs"; + string inputText = "This is a test."; + + Response> response = await client.TranslateAsync(targetLanguage, inputText, from: from).ConfigureAwait(false); + IReadOnlyList translations = response.Value; + TranslatedTextElement 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}"); +} +``` + +## Translate with auto-detection + +You can ommit source languge of the input text. In this case, API will try to auto-detect the language. + +> 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# +try +{ + string targetLanguage = "cs"; + string inputText = "This is a test."; + + Response> response = await client.TranslateAsync(targetLanguage, inputText).ConfigureAwait(false); + IReadOnlyList translations = response.Value; + TranslatedTextElement 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}"); +} +``` + +## Translate with Transliteration + +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# +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, from: fromLanguage, fromScript: fromScript, toScript: toScript).ConfigureAwait(false); + IReadOnlyList translations = response.Value; + TranslatedTextElement 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# +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 (TranslatedTextElement 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}"); +} +``` + +## Translate multiple target languages + +You can provide multiple target languages which results in each input element being translated to all target languages. + +```C# +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 (TranslatedTextElement 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}"); +} +``` + +## Translate different text types + +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# +try +{ + IEnumerable targetLanguages = new[] { "cs" }; + IEnumerable inputTextElements = new[] + { + "This is a test." + }; + + Response> response = await client.TranslateAsync(targetLanguages, inputTextElements, textType: TextTypes.Html).ConfigureAwait(false); + IReadOnlyList translations = response.Value; + TranslatedTextElement 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}"); +} +``` + +## Don’t translate specific entity name in a text + +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# +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: TextTypes.Html, from: from).ConfigureAwait(false); + IReadOnlyList translations = response.Value; + TranslatedTextElement 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}"); +} +``` + +## Translate specific entity name in a text applying a dictionary + +If you already know the translation you want to apply to a word or a phrase, you can supply it as markup within the request. The dynamic dictionary is safe only for compound nouns like proper names and product names. + +> Note You must include the From parameter in your API translation request instead of using the autodetect feature. + +```C# +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, from: from).ConfigureAwait(false); + IReadOnlyList translations = response.Value; + TranslatedTextElement 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}"); +} +``` + +## Profanity handling + +[Profanity handling](https://learn.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate#handle-profanity). Normally the Translator service will retain profanity that is present in the source in the translation. The degree of profanity and the context that makes words profane differ between cultures, and as a result the degree of profanity in the target language may be amplified or reduced. + +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# +try +{ + ProfanityActions profanityAction = ProfanityActions.Marked; + ProfanityMarkers profanityMarkers = ProfanityMarkers.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; + TranslatedTextElement 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}"); +} +``` + +## Include alignments into translations + +You can ask translation service to include alignment projection from source text to translated text. + +```C# +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; + TranslatedTextElement 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}"); +} +``` + +## Include sentence lenght + +You can ask translator service to include sentence boundaries for the input text and the translated text. + +```C# +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; + TranslatedTextElement 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}"); +} +``` + +## Custom Translator + +You can get translations from a customized system built with [Custom Translator](https://learn.microsoft.com/azure/cognitive-services/translator/customization). Add the Category ID from your Custom Translator [project details](https://learn.microsoft.com/azure/cognitive-services/translator/custom-translator/how-to-create-project#view-project-details) to this parameter to use your deployed customized system. + +It is possible to set `allowFalback` paramter. It 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. + +```C# +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; + TranslatedTextElement 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}"); +} +``` + +See the [README] of the Text Translation client library for more information, including useful links and instructions. + +[README]: https://aka.ms/https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/README.md +[create_client_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample3_Transliterate.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample3_Transliterate.md new file mode 100644 index 0000000000000..90ddda42a501d --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample3_Transliterate.md @@ -0,0 +1,37 @@ +# Transliterate + +All samples are using `client` created in [Create a `TextTranslationClient`][create_client_sample] samples. + +## Transliterate Text + +Converts characters or letters of a source language to the corresponding characters or letters of a target language. + +```C# +try +{ + string language = "zh-Hans"; + string fromScript = "Hans"; + string toScript = "Latn"; + + IEnumerable inputTextElements = new[] + { + "这是个测试。" + }; + + Response> response = await client.TransliterateAsync(language, fromScript, toScript, inputTextElements).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}"); +} +``` + +See the [README] of the Text Translation client library for more information, including useful links and instructions. + +[README]: https://aka.ms/https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/README.md +[create_client_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.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 new file mode 100644 index 0000000000000..d3e7db836c6db --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample4_BreakSentence.md @@ -0,0 +1,65 @@ +# Break Sentence + +All samples are using `client` created in [Create a `TextTranslationClient`][create_client_sample] samples. + +## Break Sentence with language and script parameters + +When the input language is known, you can provide those to the service call. + +```C# +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; + BreakSentenceElement 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}"); +} +``` + +## Break Sentence with auto-detection + +You can ommit source languge of the input text. In this case, API will try to auto-detect the language. + +```C# +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; + BreakSentenceElement 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}"); +} +``` + +See the [README] of the Text Translation client library for more information, including useful links and instructions. + +[README]: https://aka.ms/https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/README.md +[create_client_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample5_DictionaryLookup.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample5_DictionaryLookup.md new file mode 100644 index 0000000000000..e932e27043a06 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample5_DictionaryLookup.md @@ -0,0 +1,37 @@ +# Dictionary Lookup + +All samples are using `client` created in [Create a `TextTranslationClient`][create_client_sample] samples. + +## Lookup Dictionary Entries + +Returns equivalent words for the source term in the target language. + +```C# +try +{ + string sourceLanguage = "en"; + string targetLanguage = "es"; + IEnumerable inputTextElements = new[] + { + "fly" + }; + + Response> response = await client.LookupDictionaryEntriesAsync(sourceLanguage, targetLanguage, inputTextElements).ConfigureAwait(false); + IReadOnlyList dictionaryEntries = response.Value; + DictionaryLookupElement 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}"); +} +``` + +See the [README] of the Text Translation client library for more information, including useful links and instructions. + +[README]: https://aka.ms/https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/README.md +[create_client_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md diff --git a/sdk/translation/Azure.AI.Translation.Text/samples/Sample6_DictionaryExamples.md b/sdk/translation/Azure.AI.Translation.Text/samples/Sample6_DictionaryExamples.md new file mode 100644 index 0000000000000..dd31e94dfcd87 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/samples/Sample6_DictionaryExamples.md @@ -0,0 +1,38 @@ +# Dictionary Examples + +All samples are using `client` created in [Create a `TextTranslationClient`][create_client_sample] samples. + +## Lookup Dictionary Examples + +Returns grammatical structure and context examples for the source term and target term pair. + +```C# +try +{ + string sourceLanguage = "en"; + string targetLanguage = "es"; + IEnumerable inputTextElements = new[] + { + new InputTextWithTranslation { Text = "fly", Translation = "volar" } + }; + + Response> response = await client.LookupDictionaryExamplesAsync(sourceLanguage, targetLanguage, inputTextElements).ConfigureAwait(false); + IReadOnlyList dictionaryEntries = response.Value; + DictionaryExampleElement dictionaryEntry = dictionaryEntries.FirstOrDefault(); + + Console.WriteLine($"For the given input {dictionaryEntry?.Examples?.Count} examples were found in the dictionary."); + Example 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}"); +} +``` + +See the [README] of the Text Translation client library for more information, including useful links and instructions. + +[README]: https://aka.ms/https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/translation/Azure.AI.Translation.Text/README.md +[create_client_sample]: https://aka.ms/https://github.com/azure-sdk-for-net/tree/main/sdk/translation/Azure.AI.Translation.Text/samples/Sample0_CreateClient.md diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Azure.AI.Translation.Text.csproj b/sdk/translation/Azure.AI.Translation.Text/src/Azure.AI.Translation.Text.csproj new file mode 100644 index 0000000000000..c92bced69ec3f --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Azure.AI.Translation.Text.csproj @@ -0,0 +1,22 @@ + + + This is the Text Translation client library for developing .NET applications with rich experience. + Azure SDK Code Generation Text Translation for Azure Data Plane + 1.0.0-beta.1 + Azure Text Translation;$(PackageCommonTags) + $(RequiredTargetFrameworks) + true + + + + + + + + + + + + + + diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClient.cs b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClient.cs new file mode 100644 index 0000000000000..c3f7a274e9343 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClient.cs @@ -0,0 +1,1751 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core.Pipeline; +using Azure.Core; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Threading; +using System.Linq; +using Azure.AI.Translation.Text.Models; +using System.Text.Json; + +namespace Azure.AI.Translation.Text +{ + /// The Translator service client. + public partial class TextTranslationClient + { + private const string KEY_HEADER_NAME = "Ocp-Apim-Subscription-Key"; + private const string TOKEN_SCOPE = "https://cognitiveservices.azure.com/.default"; + private const string PLATFORM_PATH = "/translator/text/v3.0"; + private const string DEFAULT_REGION = "global"; + + private static readonly Uri DEFAULT_ENDPOINT = new Uri("https://api.cognitive.microsofttranslator.com"); + + /// Initializes a new instance of TextTranslationClient. + /// + /// Supported Text Translation endpoints (protocol and hostname, for example: + /// https://api.cognitive.microsofttranslator.com). + /// + /// is null. + protected TextTranslationClient(Uri endpoint) : this(endpoint, new TextTranslationClientOptions()) + { + } + + /// Initializes a new instance of TextTranslationClient. + /// + /// Supported Text Translation endpoints (protocol and hostname, for example: + /// https://api.cognitive.microsofttranslator.com). + /// + /// The options for configuring the client. + /// is null. + protected TextTranslationClient(Uri endpoint, TextTranslationClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + options ??= new TextTranslationClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), Array.Empty(), new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// + /// Initializes a new instance of the class. + /// + /// Azure Key Credential + /// Azure Resource Region + /// Translate Client Options + public TextTranslationClient(AzureKeyCredential credential, string region = DEFAULT_REGION, TextTranslationClientOptions options = default) : this(credential, DEFAULT_ENDPOINT, region, options) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Azure Key Credential + /// Service Endpoint + /// Azure Resource Region + /// Translate Client Options + public TextTranslationClient(AzureKeyCredential credential, Uri endpoint, string region = DEFAULT_REGION, TextTranslationClientOptions options = default) : this(endpoint, options) + { + options = options ?? new TextTranslationClientOptions(); + + List authenticationPolicies = new List() + { + new AzureKeyCredentialPolicy(credential, KEY_HEADER_NAME) + }; + + if (!string.IsNullOrWhiteSpace(region) && !string.Equals(DEFAULT_REGION, region, StringComparison.InvariantCultureIgnoreCase)) + { + authenticationPolicies.Add(new TranslatorRegionalEndpointAuthenticationPolicy(region)); + } + + this._pipeline = HttpPipelineBuilder.Build(options, authenticationPolicies.ToArray(), Array.Empty(), new ResponseClassifier()); + + if (endpoint.IsPlatformHost()) + { + this._endpoint = new Uri(endpoint, PLATFORM_PATH); + } + } + + /// + /// Initializes a new instance of the class. + /// + /// Cognitive Services Token + /// Translate Client Options + public TextTranslationClient(TokenCredential credential, TextTranslationClientOptions options = default) : this(credential, DEFAULT_ENDPOINT, options) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Cognitive Services Token + /// Service Endpoint + /// Translate Client Options + public TextTranslationClient(TokenCredential credential, Uri endpoint, TextTranslationClientOptions options = default) : this(endpoint, options) + { + var policy = new BearerTokenAuthenticationPolicy(credential, TOKEN_SCOPE); + options = options ?? new TextTranslationClientOptions(); + + this._pipeline = HttpPipelineBuilder.Build(options, new[] { policy }, Array.Empty(), new ResponseClassifier()); + + if (endpoint.IsPlatformHost()) + { + this._endpoint = new Uri(endpoint, PLATFORM_PATH); + } + } + + /// Translate Text. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + public virtual Task>> TranslateAsync(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, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(targetLanguages, nameof(targetLanguages)); + Argument.AssertNotNull(content, nameof(content)); + + return this.TranslateAsync(targetLanguages, content.Select(input => new InputText(input)) as object, clientTraceId, sourceLanguage, textType?.ToString(), category, profanityAction?.ToString(), profanityMarker?.ToString(), includeAlignment, includeSentenceLength, suggestedFrom, fromScript, toScript, allowFallback, cancellationToken); + } + + /// Translate Text. + /// + /// 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. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + public virtual Task>> TranslateAsync(string targetLanguage, IEnumerable content, string sourceLanguage = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(targetLanguage, nameof(targetLanguage)); + Argument.AssertNotNull(content, nameof(content)); + + return this.TranslateAsync(new[] { targetLanguage }, content.Select(input => new InputText(input)) as object, from: sourceLanguage, cancellationToken: cancellationToken); + } + + /// Translate Text. + /// + /// 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. + /// + /// Text to be translated. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + public virtual Task>> TranslateAsync(string targetLanguage, string text, string sourceLanguage = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(targetLanguage, nameof(targetLanguage)); + Argument.AssertNotNull(text, nameof(text)); + + return this.TranslateAsync(new[] { targetLanguage }, new[] { new InputText(text) } as object, from: sourceLanguage, cancellationToken: cancellationToken); + } + + /// Translate Text. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + public virtual Response> Translate(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, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(targetLanguages, nameof(targetLanguages)); + Argument.AssertNotNull(content, nameof(content)); + + return this.Translate(targetLanguages, content.Select(input => new InputText(input)) as object, clientTraceId, sourceLanguage, textType?.ToString(), category, profanityAction?.ToString(), profanityMarker?.ToString(), includeAlignment, includeSentenceLength, suggestedFrom, fromScript, toScript, allowFallback, cancellationToken); + } + + /// Translate Text. + /// + /// 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. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + public virtual Response> Translate(string targetLanguage, IEnumerable content, string sourceLanguage = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(targetLanguage, nameof(targetLanguage)); + Argument.AssertNotNull(content, nameof(content)); + + return this.Translate(new[] { targetLanguage }, content.Select(input => new InputText(input)) as object, from: sourceLanguage, cancellationToken: cancellationToken); + } + + /// Translate Text. + /// + /// 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. + /// + /// Text to be translated. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + public virtual Response> Translate(string targetLanguage, string text, string sourceLanguage = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(targetLanguage, nameof(targetLanguage)); + Argument.AssertNotNull(text, nameof(text)); + + return this.Translate(new[] { targetLanguage }, new[] { new InputText(text) } as object, from: sourceLanguage, cancellationToken: cancellationToken); + } + + /// Transliterate Text. + /// + /// 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. + /// The cancellation token to use. + /// , , or is null. + public virtual Task>> TransliterateAsync(string language, string fromScript, string toScript, IEnumerable content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(language, nameof(language)); + Argument.AssertNotNull(fromScript, nameof(fromScript)); + Argument.AssertNotNull(toScript, nameof(toScript)); + Argument.AssertNotNull(content, nameof(content)); + + return this.TransliterateAsync(language, fromScript, toScript, content.Select(input => new InputText(input)) as object, clientTraceId, cancellationToken); + } + + /// Transliterate Text. + /// + /// 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. + /// + /// Text to be transliterated. + /// The cancellation token to use. + /// , , or is null. + public virtual Task>> TransliterateAsync(string language, string fromScript, string toScript, string text, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(language, nameof(language)); + Argument.AssertNotNull(fromScript, nameof(fromScript)); + Argument.AssertNotNull(toScript, nameof(toScript)); + Argument.AssertNotNull(text, nameof(text)); + + return this.TransliterateAsync(language, fromScript, toScript, new[] { new InputText(text) } as object, cancellationToken: cancellationToken); + } + + /// Transliterate Text. + /// + /// 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. + /// The cancellation token to use. + /// , , or is null. + public virtual Response> Transliterate(string language, string fromScript, string toScript, IEnumerable content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(language, nameof(language)); + Argument.AssertNotNull(fromScript, nameof(fromScript)); + Argument.AssertNotNull(toScript, nameof(toScript)); + Argument.AssertNotNull(content, nameof(content)); + + return this.Transliterate(language, fromScript, toScript, content.Select(input => new InputText(input)) as object, clientTraceId, cancellationToken); + } + + /// Transliterate Text. + /// + /// 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. + /// + /// Text to be transliterated. + /// The cancellation token to use. + /// , , or is null. + public virtual Response> Transliterate(string language, string fromScript, string toScript, string text, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(language, nameof(language)); + Argument.AssertNotNull(fromScript, nameof(fromScript)); + Argument.AssertNotNull(toScript, nameof(toScript)); + Argument.AssertNotNull(text, nameof(text)); + + return this.Transliterate(language, fromScript, toScript, new[] { new InputText(text) } as object, cancellationToken: cancellationToken); + } + + /// Break Sentence. + /// Array of the text for which values the sentence boundaries will be calculated. + /// A client-generated GUID to uniquely identify the request. + /// + /// Language tag identifying the language of the input text. + /// If a code isn't specified, automatic language detection will be applied. + /// + /// + /// Script tag identifying the script used by the input text. + /// If a script isn't specified, the default script of the language will be assumed. + /// + /// The cancellation token to use. + /// is null. + public virtual Task>> FindSentenceBoundariesAsync(IEnumerable content, string clientTraceId = null, string language = null, string script = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(content, nameof(content)); + + return this.FindSentenceBoundariesAsync(content.Select(input => new InputText(input)) as object, clientTraceId, language, script, cancellationToken); + } + + /// Break Sentence. + /// Array of the text for which values the sentence boundaries will be calculated. + /// A client-generated GUID to uniquely identify the request. + /// + /// Language tag identifying the language of the input text. + /// If a code isn't specified, automatic language detection will be applied. + /// + /// + /// Script tag identifying the script used by the input text. + /// If a script isn't specified, the default script of the language will be assumed. + /// + /// The cancellation token to use. + /// is null. + public virtual Task>> FindSentenceBoundariesAsync(string text, string clientTraceId = null, string language = null, string script = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(text, nameof(text)); + + return this.FindSentenceBoundariesAsync(new[] { new InputText(text) } as object, clientTraceId, language, script, cancellationToken); + } + + /// Break Sentence. + /// Array of the text for which values the sentence boundaries will be calculated. + /// A client-generated GUID to uniquely identify the request. + /// + /// Language tag identifying the language of the input text. + /// If a code isn't specified, automatic language detection will be applied. + /// + /// + /// Script tag identifying the script used by the input text. + /// If a script isn't specified, the default script of the language will be assumed. + /// + /// The cancellation token to use. + /// is null. + public virtual Response> FindSentenceBoundaries(IEnumerable content, string clientTraceId = null, string language = null, string script = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(content, nameof(content)); + + return this.FindSentenceBoundaries(content.Select(input => new InputText(input)) as object, clientTraceId, language, script, cancellationToken); + } + + /// Break Sentence. + /// Array of the text for which values the sentence boundaries will be calculated. + /// A client-generated GUID to uniquely identify the request. + /// + /// Language tag identifying the language of the input text. + /// If a code isn't specified, automatic language detection will be applied. + /// + /// + /// Script tag identifying the script used by the input text. + /// If a script isn't specified, the default script of the language will be assumed. + /// + /// The cancellation token to use. + /// is null. + public virtual Response> FindSentenceBoundaries(string text, string clientTraceId = null, string language = null, string script = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(text, nameof(text)); + + return this.FindSentenceBoundaries(new[] { new InputText(text) } as object, clientTraceId, language, script, cancellationToken); + } + + /// Dictionary Lookup. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the words to lookup in the dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + public virtual Task>> LookupDictionaryEntriesAsync(string @from, string to, IEnumerable words, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(words, nameof(words)); + + return this.LookupDictionaryEntriesAsync(from, to, words.Select(input => new InputText(input)) as object, clientTraceId, cancellationToken); + } + + /// Dictionary Lookup. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// A word to lookup in the dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + public virtual Task>> LookupDictionaryEntriesAsync(string @from, string to, string word, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(word, nameof(word)); + + return this.LookupDictionaryEntriesAsync(from, to, new[] { new InputText(word) } as object, clientTraceId, cancellationToken); + } + + /// Dictionary Lookup. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the words to lookup in the dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + public virtual Response> LookupDictionaryEntries(string @from, string to, IEnumerable words, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(words, nameof(words)); + + return this.LookupDictionaryEntries(from, to, words.Select(input => new InputText(input)) as object, clientTraceId, cancellationToken); + } + + /// Dictionary Lookup. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// A word to lookup in the dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + public virtual Response> LookupDictionaryEntries(string @from, string to, string word, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(word, nameof(word)); + + return this.LookupDictionaryEntries(from, to, new[] { new InputText(word) } as object, clientTraceId, cancellationToken); + } + + /// Dictionary Examples. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the text to be sent to dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + public virtual Task>> LookupDictionaryExamplesAsync(string @from, string to, IEnumerable content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + return this.LookupDictionaryExamplesAsync(from, to, content as object, clientTraceId, cancellationToken); + } + + /// Dictionary Examples. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the text to be sent to dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + public virtual Task>> LookupDictionaryExamplesAsync(string @from, string to, InputTextWithTranslation content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + return this.LookupDictionaryExamplesAsync(from, to, new[] { content } as object, clientTraceId, cancellationToken); + } + + /// Dictionary Examples. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the text to be sent to dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + public virtual Response> LookupDictionaryExamples(string @from, string to, IEnumerable content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + return this.LookupDictionaryExamples(from, to, content as object, clientTraceId, cancellationToken); + } + + /// Dictionary Examples. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the text to be sent to dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + public virtual Response> LookupDictionaryExamples(string @from, string to, InputTextWithTranslation content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + return this.LookupDictionaryExamples(from, to, new[] { content } as object, clientTraceId, cancellationToken); + } + + /// Gets the set of languages currently supported by other operations of the Translator. + /// A client-generated GUID to uniquely identify the request. + /// + /// 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 + /// `scope=translation,transliteration,dictionary`. To decide which set of supported languages + /// is appropriate for your scenario, see the description of the [response object](#response-body). + /// + /// + /// 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. + /// + /// + /// Passing the value of the ETag response header in an If-None-Match field will allow the service to optimize the response. + /// If the resource has not been modified, the service will return status code 304 and an empty response body. + /// + /// Request context. + internal virtual async Task GetLanguagesAsync(string clientTraceId = null, string scope = null, string acceptLanguage = null, string ifNoneMatch = null, RequestContext context = default) + { + ETag? eTag = null; + if (ifNoneMatch != null) + { + eTag = new ETag(ifNoneMatch); + } + + return await this.GetLanguagesAsync(clientTraceId, scope, acceptLanguage, eTag, context).ConfigureAwait(false); + } + + /// Gets the set of languages currently supported by other operations of the Translator. + /// A client-generated GUID to uniquely identify the request. + /// + /// 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 + /// `scope=translation,transliteration,dictionary`. To decide which set of supported languages + /// is appropriate for your scenario, see the description of the [response object](#response-body). + /// + /// + /// 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. + /// + /// + /// Passing the value of the ETag response header in an If-None-Match field will allow the service to optimize the response. + /// If the resource has not been modified, the service will return status code 304 and an empty response body. + /// + /// Request context. + internal virtual Response GetLanguages(string clientTraceId = null, string scope = null, string acceptLanguage = null, string ifNoneMatch = null, RequestContext context = default) + { + ETag? eTag = null; + if (ifNoneMatch != null) + { + eTag = new ETag(ifNoneMatch); + } + + return this.GetLanguages(clientTraceId, scope, acceptLanguage, eTag, context); + } + + // Overrides for generated class + + /// Gets the set of languages currently supported by other operations of the Translator. + /// A client-generated GUID to uniquely identify the request. + /// + /// 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 + /// `scope=translation,transliteration,dictionary`. To decide which set of supported languages + /// is appropriate for your scenario, see the description of the [response object](#response-body). + /// + /// + /// 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. + /// + /// + /// Passing the value of the ETag response header in an If-None-Match field will allow the service to optimize the response. + /// If the resource has not been modified, the service will return status code 304 and an empty response body. + /// + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual async Task GetLanguagesAsync(string clientTraceId = null, string scope = null, string acceptLanguage = null, ETag? ifNoneMatch = null, RequestContext context = null) + { + using var scope0 = ClientDiagnostics.CreateScope("TextTranslationClient.GetLanguages"); + scope0.Start(); + try + { + using HttpMessage message = CreateGetLanguagesRequest(clientTraceId, scope, acceptLanguage, ifNoneMatch, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Gets the set of languages currently supported by other operations of the Translator. + /// A client-generated GUID to uniquely identify the request. + /// + /// 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 + /// `scope=translation,transliteration,dictionary`. To decide which set of supported languages + /// is appropriate for your scenario, see the description of the [response object](#response-body). + /// + /// + /// 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. + /// + /// + /// Passing the value of the ETag response header in an If-None-Match field will allow the service to optimize the response. + /// If the resource has not been modified, the service will return status code 304 and an empty response body. + /// + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual Response GetLanguages(string clientTraceId = null, string scope = null, string acceptLanguage = null, ETag? ifNoneMatch = null, RequestContext context = null) + { + using var scope0 = ClientDiagnostics.CreateScope("TextTranslationClient.GetLanguages"); + scope0.Start(); + try + { + using HttpMessage message = CreateGetLanguagesRequest(clientTraceId, scope, acceptLanguage, ifNoneMatch, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope0.Failed(e); + throw; + } + } + + /// Translate Text. + /// + /// 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. Allowed values: "plain" | "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. Allowed values: "NoAction" | "Marked" | "Deleted" + /// + /// + /// Specifies how profanities should be marked in translations. + /// Possible values are: Asterisk (default) or Tag. . Allowed values: "Asterisk" | "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. + /// + /// The cancellation token to use. + /// or is null. + internal virtual async Task>> TranslateAsync(IEnumerable to, object content, string clientTraceId = null, string @from = null, string textType = null, string category = null, string profanityAction = null, string profanityMarker = null, bool? includeAlignment = null, bool? includeSentenceLength = null, string suggestedFrom = null, string fromScript = null, string toScript = null, bool? allowFallback = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await TranslateAsync(to, RequestContent.Create(content), clientTraceId, @from, textType, category, profanityAction, profanityMarker, includeAlignment, includeSentenceLength, suggestedFrom, fromScript, toScript, allowFallback, context).ConfigureAwait(false); + IReadOnlyList value = default; + using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(TranslatedTextItem.DeserializeTranslatedTextItem(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Translate Text. + /// + /// 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. Allowed values: "plain" | "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. Allowed values: "NoAction" | "Marked" | "Deleted" + /// + /// + /// Specifies how profanities should be marked in translations. + /// Possible values are: Asterisk (default) or Tag. . Allowed values: "Asterisk" | "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. + /// + /// The cancellation token to use. + /// or is null. + internal virtual Response> Translate(IEnumerable to, object content, string clientTraceId = null, string @from = null, string textType = null, string category = null, string profanityAction = null, string profanityMarker = null, bool? includeAlignment = null, bool? includeSentenceLength = null, string suggestedFrom = null, string fromScript = null, string toScript = null, bool? allowFallback = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Translate(to, RequestContent.Create(content), clientTraceId, @from, textType, category, profanityAction, profanityMarker, includeAlignment, includeSentenceLength, suggestedFrom, fromScript, toScript, allowFallback, context); + IReadOnlyList value = default; + using var document = JsonDocument.Parse(response.ContentStream); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(TranslatedTextItem.DeserializeTranslatedTextItem(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Translate Text. + /// + /// 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. + /// + /// The content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// 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. Allowed values: "plain" | "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. Allowed values: "NoAction" | "Marked" | "Deleted" + /// + /// + /// Specifies how profanities should be marked in translations. + /// Possible values are: Asterisk (default) or Tag. . Allowed values: "Asterisk" | "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. + /// + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual async Task TranslateAsync(IEnumerable to, RequestContent content, string clientTraceId = null, string @from = null, string textType = null, string category = null, string profanityAction = null, string profanityMarker = null, bool? includeAlignment = null, bool? includeSentenceLength = null, string suggestedFrom = null, string fromScript = null, string toScript = null, bool? allowFallback = null, RequestContext context = null) + { + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.Translate"); + scope.Start(); + try + { + using HttpMessage message = CreateTranslateRequest(to, content, clientTraceId, @from, textType, category, profanityAction, profanityMarker, includeAlignment, includeSentenceLength, suggestedFrom, fromScript, toScript, allowFallback, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Translate Text. + /// + /// 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. + /// + /// The content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// 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. Allowed values: "plain" | "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. Allowed values: "NoAction" | "Marked" | "Deleted" + /// + /// + /// Specifies how profanities should be marked in translations. + /// Possible values are: Asterisk (default) or Tag. . Allowed values: "Asterisk" | "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. + /// + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual Response Translate(IEnumerable to, RequestContent content, string clientTraceId = null, string @from = null, string textType = null, string category = null, string profanityAction = null, string profanityMarker = null, bool? includeAlignment = null, bool? includeSentenceLength = null, string suggestedFrom = null, string fromScript = null, string toScript = null, bool? allowFallback = null, RequestContext context = null) + { + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.Translate"); + scope.Start(); + try + { + using HttpMessage message = CreateTranslateRequest(to, content, clientTraceId, @from, textType, category, profanityAction, profanityMarker, includeAlignment, includeSentenceLength, suggestedFrom, fromScript, toScript, allowFallback, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Transliterate Text. + /// + /// 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. + /// The cancellation token to use. + /// , , or is null. + internal virtual async Task>> TransliterateAsync(string language, string fromScript, string toScript, object content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(language, nameof(language)); + Argument.AssertNotNull(fromScript, nameof(fromScript)); + Argument.AssertNotNull(toScript, nameof(toScript)); + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await TransliterateAsync(language, fromScript, toScript, RequestContent.Create(content), clientTraceId, context).ConfigureAwait(false); + IReadOnlyList value = default; + using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(TransliteratedText.DeserializeTransliteratedText(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Transliterate Text. + /// + /// 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. + /// The cancellation token to use. + /// , , or is null. + internal virtual Response> Transliterate(string language, string fromScript, string toScript, object content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(language, nameof(language)); + Argument.AssertNotNull(fromScript, nameof(fromScript)); + Argument.AssertNotNull(toScript, nameof(toScript)); + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Transliterate(language, fromScript, toScript, RequestContent.Create(content), clientTraceId, context); + IReadOnlyList value = default; + using var document = JsonDocument.Parse(response.ContentStream); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(TransliteratedText.DeserializeTransliteratedText(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Transliterate Text. + /// + /// 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 content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// A client-generated GUID to uniquely identify the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , , or is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual async Task TransliterateAsync(string language, string fromScript, string toScript, RequestContent content, string clientTraceId = null, RequestContext context = null) + { + Argument.AssertNotNull(language, nameof(language)); + Argument.AssertNotNull(fromScript, nameof(fromScript)); + Argument.AssertNotNull(toScript, nameof(toScript)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.Transliterate"); + scope.Start(); + try + { + using HttpMessage message = CreateTransliterateRequest(language, fromScript, toScript, content, clientTraceId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Transliterate Text. + /// + /// 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 content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// A client-generated GUID to uniquely identify the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , , or is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual Response Transliterate(string language, string fromScript, string toScript, RequestContent content, string clientTraceId = null, RequestContext context = null) + { + Argument.AssertNotNull(language, nameof(language)); + Argument.AssertNotNull(fromScript, nameof(fromScript)); + Argument.AssertNotNull(toScript, nameof(toScript)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.Transliterate"); + scope.Start(); + try + { + using HttpMessage message = CreateTransliterateRequest(language, fromScript, toScript, content, clientTraceId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Find Sentence Boundaries. + /// Array of the text for which values the sentence boundaries will be calculated. + /// A client-generated GUID to uniquely identify the request. + /// + /// Language tag identifying the language of the input text. + /// If a code isn't specified, automatic language detection will be applied. + /// + /// + /// Script tag identifying the script used by the input text. + /// If a script isn't specified, the default script of the language will be assumed. + /// + /// The cancellation token to use. + /// is null. + internal virtual async Task>> FindSentenceBoundariesAsync(object content, string clientTraceId = null, string language = null, string script = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await FindSentenceBoundariesAsync(RequestContent.Create(content), clientTraceId, language, script, context).ConfigureAwait(false); + IReadOnlyList value = default; + using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(BreakSentenceItem.DeserializeBreakSentenceItem(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Find Sentence Boundaries. + /// Array of the text for which values the sentence boundaries will be calculated. + /// A client-generated GUID to uniquely identify the request. + /// + /// Language tag identifying the language of the input text. + /// If a code isn't specified, automatic language detection will be applied. + /// + /// + /// Script tag identifying the script used by the input text. + /// If a script isn't specified, the default script of the language will be assumed. + /// + /// The cancellation token to use. + /// is null. + internal virtual Response> FindSentenceBoundaries(object content, string clientTraceId = null, string language = null, string script = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = FindSentenceBoundaries(RequestContent.Create(content), clientTraceId, language, script, context); + IReadOnlyList value = default; + using var document = JsonDocument.Parse(response.ContentStream); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(BreakSentenceItem.DeserializeBreakSentenceItem(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Find Sentence Boundaries. + /// The content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// A client-generated GUID to uniquely identify the request. + /// + /// Language tag identifying the language of the input text. + /// If a code isn't specified, automatic language detection will be applied. + /// + /// + /// Script tag identifying the script used by the input text. + /// If a script isn't specified, the default script of the language will be assumed. + /// + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual async Task FindSentenceBoundariesAsync(RequestContent content, string clientTraceId = null, string language = null, string script = null, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.FindSentenceBoundaries"); + scope.Start(); + try + { + using HttpMessage message = CreateFindSentenceBoundariesRequest(content, clientTraceId, language, script, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Find Sentence Boundaries. + /// The content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// A client-generated GUID to uniquely identify the request. + /// + /// Language tag identifying the language of the input text. + /// If a code isn't specified, automatic language detection will be applied. + /// + /// + /// Script tag identifying the script used by the input text. + /// If a script isn't specified, the default script of the language will be assumed. + /// + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual Response FindSentenceBoundaries(RequestContent content, string clientTraceId = null, string language = null, string script = null, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.FindSentenceBoundaries"); + scope.Start(); + try + { + using HttpMessage message = CreateFindSentenceBoundariesRequest(content, clientTraceId, language, script, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Lookup Dictionary Entries. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the text to be sent to dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + internal virtual async Task>> LookupDictionaryEntriesAsync(string @from, string to, object content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await LookupDictionaryEntriesAsync(@from, to, RequestContent.Create(content), clientTraceId, context).ConfigureAwait(false); + IReadOnlyList value = default; + using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(DictionaryLookupItem.DeserializeDictionaryLookupItem(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Lookup Dictionary Entries. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the text to be sent to dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + internal virtual Response> LookupDictionaryEntries(string @from, string to, object content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = LookupDictionaryEntries(@from, to, RequestContent.Create(content), clientTraceId, context); + IReadOnlyList value = default; + using var document = JsonDocument.Parse(response.ContentStream); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(DictionaryLookupItem.DeserializeDictionaryLookupItem(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Lookup Dictionary Entries. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// The content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// A client-generated GUID to uniquely identify the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual async Task LookupDictionaryEntriesAsync(string @from, string to, RequestContent content, string clientTraceId = null, RequestContext context = null) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.LookupDictionaryEntries"); + scope.Start(); + try + { + using HttpMessage message = CreateLookupDictionaryEntriesRequest(@from, to, content, clientTraceId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Lookup Dictionary Entries. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// The content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// A client-generated GUID to uniquely identify the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual Response LookupDictionaryEntries(string @from, string to, RequestContent content, string clientTraceId = null, RequestContext context = null) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.LookupDictionaryEntries"); + scope.Start(); + try + { + using HttpMessage message = CreateLookupDictionaryEntriesRequest(@from, to, content, clientTraceId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Lookup Dictionary Examples. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the text to be sent to dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + internal virtual async Task>> LookupDictionaryExamplesAsync(string @from, string to, object content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await LookupDictionaryExamplesAsync(@from, to, RequestContent.Create(content), clientTraceId, context).ConfigureAwait(false); + IReadOnlyList value = default; + using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(DictionaryExampleItem.DeserializeDictionaryExampleItem(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Lookup Dictionary Examples. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// Array of the text to be sent to dictionary. + /// A client-generated GUID to uniquely identify the request. + /// The cancellation token to use. + /// , or is null. + internal virtual Response> LookupDictionaryExamples(string @from, string to, object content, string clientTraceId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = LookupDictionaryExamples(@from, to, RequestContent.Create(content), clientTraceId, context); + IReadOnlyList value = default; + using var document = JsonDocument.Parse(response.ContentStream); + List array = new List(); + foreach (var item in document.RootElement.EnumerateArray()) + { + array.Add(DictionaryExampleItem.DeserializeDictionaryExampleItem(item)); + } + value = array; + return Response.FromValue(value, response); + } + + /// Lookup Dictionary Examples. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// The content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// A client-generated GUID to uniquely identify the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual async Task LookupDictionaryExamplesAsync(string @from, string to, RequestContent content, string clientTraceId = null, RequestContext context = null) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.LookupDictionaryExamples"); + scope.Start(); + try + { + using HttpMessage message = CreateLookupDictionaryExamplesRequest(@from, to, content, clientTraceId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Lookup Dictionary Examples. + /// + /// Specifies the language of the input text. + /// The source language must be one of the supported languages included in the dictionary scope. + /// + /// + /// Specifies the language of the output text. + /// The target language must be one of the supported languages included in the dictionary scope. + /// + /// The content to send as the body of the request. Details of the request body schema are in the Remarks section below. + /// A client-generated GUID to uniquely identify the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// Service returned a non-success status code. + /// The response returned from the service. Details of the response body schema are in the Remarks section below. + internal virtual Response LookupDictionaryExamples(string @from, string to, RequestContent content, string clientTraceId = null, RequestContext context = null) + { + Argument.AssertNotNull(@from, nameof(@from)); + Argument.AssertNotNull(to, nameof(to)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TextTranslationClient.LookupDictionaryExamples"); + scope.Start(); + try + { + using HttpMessage message = CreateLookupDictionaryExamplesRequest(@from, to, content, clientTraceId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClientBuilderExtensions.cs b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClientBuilderExtensions.cs new file mode 100644 index 0000000000000..dd3cb0d90b2b0 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Custom/TextTranslationClientBuilderExtensions.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Net; +using System.Text; +using Azure; +using Azure.AI.Translation.Text; +using Azure.Core; +using Azure.Core.Extensions; + +//TODO: there is no way to only suppress a single memmber of a static class so we need to have everything custom here. +[assembly: CodeGenSuppressType("TextTranslationClientBuilderExtensions")] + +namespace Azure.AI.Translation.Text.Custom +{ + /// Extension methods to add to client builder. + public static partial class TextTranslationClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// Azure Credentials + public static IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, AzureKeyCredential credential) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new TextTranslationClient(credential, options: options)); + } + + /// Registers a instance. + /// The builder to register with. + /// Azure Credentials + /// Region of Azure Resource + public static IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, AzureKeyCredential credential, string region) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new TextTranslationClient(credential, region, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// Azure Credentials + /// Endpoint of the translation service + public static IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, AzureKeyCredential credential, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new TextTranslationClient(credential, endpoint, options: options)); + } + + /// Registers a instance. + /// The builder to register with. + /// Azure Credentials + /// Endpoint of the translation service + /// Region of Azure Resource + public static IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, AzureKeyCredential credential, Uri endpoint, string region) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new TextTranslationClient(credential, endpoint, region, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// Cognitive Services Token + public static IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, TokenCredential credential) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new TextTranslationClient(credential, options: options)); + } + + /// Registers a instance. + /// The builder to register with. + /// Cognitive Services Token + /// Endpoint of the translation service + public static IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, TokenCredential credential, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new TextTranslationClient(credential, endpoint, options: options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddTextTranslationClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.Serialization.cs new file mode 100644 index 0000000000000..7e35b176e3429 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.Serialization.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + public partial class BackTranslation + { + internal static BackTranslation DeserializeBackTranslation(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string normalizedText = default; + string displayText = default; + int numExamples = default; + int frequencyCount = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("normalizedText"u8)) + { + normalizedText = property.Value.GetString(); + continue; + } + if (property.NameEquals("displayText"u8)) + { + displayText = property.Value.GetString(); + continue; + } + if (property.NameEquals("numExamples"u8)) + { + numExamples = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("frequencyCount"u8)) + { + frequencyCount = property.Value.GetInt32(); + continue; + } + } + return new BackTranslation(normalizedText, displayText, numExamples, frequencyCount); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BackTranslation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeBackTranslation(document.RootElement); + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.cs new file mode 100644 index 0000000000000..511094f256d99 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + /// Back Translation. + public partial class BackTranslation + { + /// Initializes a new instance of BackTranslation. + /// + /// A string giving the normalized form of the source term that is a back-translation of the target. + /// This value should be used as input to lookup examples. + /// + /// + /// A string giving the source term that is a back-translation of the target in a form best + /// suited for end-user display. + /// + /// + /// An integer representing the number of examples that are available for this translation pair. + /// Actual examples must be retrieved with a separate call to lookup examples. The number is mostly + /// intended to facilitate display in a UX. For example, a user interface may add a hyperlink + /// to the back-translation if the number of examples is greater than zero and show the back-translation + /// as plain text if there are no examples. Note that the actual number of examples returned + /// by a call to lookup examples may be less than numExamples, because additional filtering may be + /// applied on the fly to remove "bad" examples. + /// + /// + /// An integer representing the frequency of this translation pair in the data. The main purpose of this + /// field is to provide a user interface with a means to sort back-translations so the most frequent terms are first. + /// + /// or is null. + internal BackTranslation(string normalizedText, string displayText, int numExamples, int frequencyCount) + { + Argument.AssertNotNull(normalizedText, nameof(normalizedText)); + Argument.AssertNotNull(displayText, nameof(displayText)); + + NormalizedText = normalizedText; + DisplayText = displayText; + NumExamples = numExamples; + FrequencyCount = frequencyCount; + } + + /// + /// A string giving the normalized form of the source term that is a back-translation of the target. + /// This value should be used as input to lookup examples. + /// + public string NormalizedText { get; } + /// + /// A string giving the source term that is a back-translation of the target in a form best + /// suited for end-user display. + /// + public string DisplayText { get; } + /// + /// An integer representing the number of examples that are available for this translation pair. + /// Actual examples must be retrieved with a separate call to lookup examples. The number is mostly + /// intended to facilitate display in a UX. For example, a user interface may add a hyperlink + /// to the back-translation if the number of examples is greater than zero and show the back-translation + /// as plain text if there are no examples. Note that the actual number of examples returned + /// by a call to lookup examples may be less than numExamples, because additional filtering may be + /// applied on the fly to remove "bad" examples. + /// + public int NumExamples { get; } + /// + /// An integer representing the frequency of this translation pair in the data. The main purpose of this + /// field is to provide a user interface with a means to sort back-translations so the most frequent terms are first. + /// + public int FrequencyCount { get; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.Serialization.cs new file mode 100644 index 0000000000000..752a9f1daed1a --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.Serialization.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + public partial class BreakSentenceItem + { + internal static BreakSentenceItem DeserializeBreakSentenceItem(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Optional detectedLanguage = default; + IReadOnlyList sentLen = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("detectedLanguage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + property.ThrowNonNullablePropertyIsNull(); + continue; + } + detectedLanguage = DetectedLanguage.DeserializeDetectedLanguage(property.Value); + continue; + } + if (property.NameEquals("sentLen"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + sentLen = array; + continue; + } + } + return new BreakSentenceItem(detectedLanguage, sentLen); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BreakSentenceItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeBreakSentenceItem(document.RootElement); + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.cs new file mode 100644 index 0000000000000..3311c36f2f318 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + /// Item containing break sentence result. + public partial class BreakSentenceItem + { + /// Initializes a new instance of BreakSentenceItem. + /// + /// An integer array representing the lengths of the sentences in the input text. + /// The length of the array is the number of sentences, and the values are the length of each sentence. + /// + /// is null. + internal BreakSentenceItem(IEnumerable sentLen) + { + Argument.AssertNotNull(sentLen, nameof(sentLen)); + + SentLen = sentLen.ToList(); + } + + /// Initializes a new instance of BreakSentenceItem. + /// The detectedLanguage property is only present in the result object when language auto-detection is requested. + /// + /// An integer array representing the lengths of the sentences in the input text. + /// The length of the array is the number of sentences, and the values are the length of each sentence. + /// + internal BreakSentenceItem(DetectedLanguage detectedLanguage, IReadOnlyList sentLen) + { + DetectedLanguage = detectedLanguage; + SentLen = sentLen.ToList(); + } + + /// The detectedLanguage property is only present in the result object when language auto-detection is requested. + public DetectedLanguage DetectedLanguage { get; } + /// + /// An integer array representing the lengths of the sentences in the input text. + /// The length of the array is the number of sentences, and the values are the length of each sentence. + /// + public IReadOnlyList SentLen { get; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/CommonScriptModel.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/CommonScriptModel.Serialization.cs new file mode 100644 index 0000000000000..d746c420e51cf --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/CommonScriptModel.Serialization.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + public partial class CommonScriptModel + { + internal static CommonScriptModel DeserializeCommonScriptModel(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string code = default; + string name = default; + string nativeName = default; + string dir = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code"u8)) + { + code = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("nativeName"u8)) + { + nativeName = property.Value.GetString(); + continue; + } + if (property.NameEquals("dir"u8)) + { + dir = property.Value.GetString(); + continue; + } + } + return new CommonScriptModel(code, name, nativeName, dir); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CommonScriptModel FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCommonScriptModel(document.RootElement); + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/CommonScriptModel.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/CommonScriptModel.cs new file mode 100644 index 0000000000000..049c115d9d678 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/CommonScriptModel.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + /// Common properties of language script. + public partial class CommonScriptModel + { + /// Initializes a new instance of CommonScriptModel. + /// Code identifying the script. + /// Display name of the script in the locale requested via Accept-Language header. + /// Display name of the language in the locale native for the language. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// , , or is null. + internal CommonScriptModel(string code, string name, string nativeName, string dir) + { + Argument.AssertNotNull(code, nameof(code)); + Argument.AssertNotNull(name, nameof(name)); + Argument.AssertNotNull(nativeName, nameof(nativeName)); + Argument.AssertNotNull(dir, nameof(dir)); + + Code = code; + Name = name; + NativeName = nativeName; + Dir = dir; + } + + /// Code identifying the script. + public string Code { get; } + /// Display name of the script in the locale requested via Accept-Language header. + public string Name { get; } + /// Display name of the language in the locale native for the language. + public string NativeName { get; } + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + public string Dir { get; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.Serialization.cs new file mode 100644 index 0000000000000..4fd256ce97291 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.Serialization.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + public partial class DetectedLanguage + { + internal static DetectedLanguage DeserializeDetectedLanguage(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string language = default; + float score = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("language"u8)) + { + language = property.Value.GetString(); + continue; + } + if (property.NameEquals("score"u8)) + { + score = property.Value.GetSingle(); + continue; + } + } + return new DetectedLanguage(language, score); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DetectedLanguage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeDetectedLanguage(document.RootElement); + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.cs new file mode 100644 index 0000000000000..64725994eb5e0 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.cs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + /// An object describing the detected language. + public partial class DetectedLanguage + { + /// Initializes a new instance of DetectedLanguage. + /// A string representing the code of the detected language. + /// + /// A float value indicating the confidence in the result. + /// The score is between zero and one and a low score indicates a low confidence. + /// + /// is null. + internal DetectedLanguage(string language, float score) + { + Argument.AssertNotNull(language, nameof(language)); + + Language = language; + Score = score; + } + + /// A string representing the code of the detected language. + public string Language { get; } + /// + /// A float value indicating the confidence in the result. + /// The score is between zero and one and a low score indicates a low confidence. + /// + public float Score { get; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExample.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExample.Serialization.cs new file mode 100644 index 0000000000000..441a717bd8ab8 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExample.Serialization.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + public partial class DictionaryExample + { + internal static DictionaryExample DeserializeDictionaryExample(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string sourcePrefix = default; + string sourceTerm = default; + string sourceSuffix = default; + string targetPrefix = default; + string targetTerm = default; + string targetSuffix = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sourcePrefix"u8)) + { + sourcePrefix = property.Value.GetString(); + continue; + } + if (property.NameEquals("sourceTerm"u8)) + { + sourceTerm = property.Value.GetString(); + continue; + } + if (property.NameEquals("sourceSuffix"u8)) + { + sourceSuffix = property.Value.GetString(); + continue; + } + if (property.NameEquals("targetPrefix"u8)) + { + targetPrefix = property.Value.GetString(); + continue; + } + if (property.NameEquals("targetTerm"u8)) + { + targetTerm = property.Value.GetString(); + continue; + } + if (property.NameEquals("targetSuffix"u8)) + { + targetSuffix = property.Value.GetString(); + continue; + } + } + return new DictionaryExample(sourcePrefix, sourceTerm, sourceSuffix, targetPrefix, targetTerm, targetSuffix); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DictionaryExample FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeDictionaryExample(document.RootElement); + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExample.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExample.cs new file mode 100644 index 0000000000000..0ece5675cae3d --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExample.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + /// Dictionary Example. + public partial class DictionaryExample + { + /// Initializes a new instance of DictionaryExample. + /// + /// The string to concatenate before the value of sourceTerm to form a complete example. + /// Do not add a space character, since it is already there when it should be. + /// This value may be an empty string. + /// + /// + /// A string equal to the actual term looked up. The string is added with sourcePrefix + /// and sourceSuffix to form the complete example. Its value is separated so it can be + /// marked in a user interface, e.g., by bolding it. + /// + /// + /// The string to concatenate after the value of sourceTerm to form a complete example. + /// Do not add a space character, since it is already there when it should be. + /// This value may be an empty string. + /// + /// A string similar to sourcePrefix but for the target. + /// A string similar to sourceTerm but for the target. + /// A string similar to sourceSuffix but for the target. + /// , , , , or is null. + internal DictionaryExample(string sourcePrefix, string sourceTerm, string sourceSuffix, string targetPrefix, string targetTerm, string targetSuffix) + { + Argument.AssertNotNull(sourcePrefix, nameof(sourcePrefix)); + Argument.AssertNotNull(sourceTerm, nameof(sourceTerm)); + Argument.AssertNotNull(sourceSuffix, nameof(sourceSuffix)); + Argument.AssertNotNull(targetPrefix, nameof(targetPrefix)); + Argument.AssertNotNull(targetTerm, nameof(targetTerm)); + Argument.AssertNotNull(targetSuffix, nameof(targetSuffix)); + + SourcePrefix = sourcePrefix; + SourceTerm = sourceTerm; + SourceSuffix = sourceSuffix; + TargetPrefix = targetPrefix; + TargetTerm = targetTerm; + TargetSuffix = targetSuffix; + } + + /// + /// The string to concatenate before the value of sourceTerm to form a complete example. + /// Do not add a space character, since it is already there when it should be. + /// This value may be an empty string. + /// + public string SourcePrefix { get; } + /// + /// A string equal to the actual term looked up. The string is added with sourcePrefix + /// and sourceSuffix to form the complete example. Its value is separated so it can be + /// marked in a user interface, e.g., by bolding it. + /// + public string SourceTerm { get; } + /// + /// The string to concatenate after the value of sourceTerm to form a complete example. + /// Do not add a space character, since it is already there when it should be. + /// This value may be an empty string. + /// + public string SourceSuffix { get; } + /// A string similar to sourcePrefix but for the target. + public string TargetPrefix { get; } + /// A string similar to sourceTerm but for the target. + public string TargetTerm { get; } + /// A string similar to sourceSuffix but for the target. + public string TargetSuffix { get; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExampleItem.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExampleItem.Serialization.cs new file mode 100644 index 0000000000000..884aaa970e8e9 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExampleItem.Serialization.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + public partial class DictionaryExampleItem + { + internal static DictionaryExampleItem DeserializeDictionaryExampleItem(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string normalizedSource = default; + string normalizedTarget = default; + IReadOnlyList examples = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("normalizedSource"u8)) + { + normalizedSource = property.Value.GetString(); + continue; + } + if (property.NameEquals("normalizedTarget"u8)) + { + normalizedTarget = property.Value.GetString(); + continue; + } + if (property.NameEquals("examples"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DictionaryExample.DeserializeDictionaryExample(item)); + } + examples = array; + continue; + } + } + return new DictionaryExampleItem(normalizedSource, normalizedTarget, examples); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DictionaryExampleItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeDictionaryExampleItem(document.RootElement); + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExampleItem.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExampleItem.cs new file mode 100644 index 0000000000000..6037f81d7700b --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryExampleItem.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + /// Dictionary Example element. + public partial class DictionaryExampleItem + { + /// Initializes a new instance of DictionaryExampleItem. + /// + /// A string giving the normalized form of the source term. Generally, this should be identical + /// to the value of the Text field at the matching list index in the body of the request. + /// + /// + /// A string giving the normalized form of the target term. Generally, this should be identical + /// to the value of the Translation field at the matching list index in the body of the request. + /// + /// A list of examples for the (source term, target term) pair. + /// , or is null. + internal DictionaryExampleItem(string normalizedSource, string normalizedTarget, IEnumerable examples) + { + Argument.AssertNotNull(normalizedSource, nameof(normalizedSource)); + Argument.AssertNotNull(normalizedTarget, nameof(normalizedTarget)); + Argument.AssertNotNull(examples, nameof(examples)); + + NormalizedSource = normalizedSource; + NormalizedTarget = normalizedTarget; + Examples = examples.ToList(); + } + + /// Initializes a new instance of DictionaryExampleItem. + /// + /// A string giving the normalized form of the source term. Generally, this should be identical + /// to the value of the Text field at the matching list index in the body of the request. + /// + /// + /// A string giving the normalized form of the target term. Generally, this should be identical + /// to the value of the Translation field at the matching list index in the body of the request. + /// + /// A list of examples for the (source term, target term) pair. + internal DictionaryExampleItem(string normalizedSource, string normalizedTarget, IReadOnlyList examples) + { + NormalizedSource = normalizedSource; + NormalizedTarget = normalizedTarget; + Examples = examples.ToList(); + } + + /// + /// A string giving the normalized form of the source term. Generally, this should be identical + /// to the value of the Text field at the matching list index in the body of the request. + /// + public string NormalizedSource { get; } + /// + /// A string giving the normalized form of the target term. Generally, this should be identical + /// to the value of the Translation field at the matching list index in the body of the request. + /// + public string NormalizedTarget { get; } + /// A list of examples for the (source term, target term) pair. + public IReadOnlyList Examples { get; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryLookupItem.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryLookupItem.Serialization.cs new file mode 100644 index 0000000000000..f1a7374802b41 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryLookupItem.Serialization.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + public partial class DictionaryLookupItem + { + internal static DictionaryLookupItem DeserializeDictionaryLookupItem(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string normalizedSource = default; + string displaySource = default; + IReadOnlyList translations = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("normalizedSource"u8)) + { + normalizedSource = property.Value.GetString(); + continue; + } + if (property.NameEquals("displaySource"u8)) + { + displaySource = property.Value.GetString(); + continue; + } + if (property.NameEquals("translations"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DictionaryTranslation.DeserializeDictionaryTranslation(item)); + } + translations = array; + continue; + } + } + return new DictionaryLookupItem(normalizedSource, displaySource, translations); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DictionaryLookupItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeDictionaryLookupItem(document.RootElement); + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryLookupItem.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryLookupItem.cs new file mode 100644 index 0000000000000..bf6e709db979e --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryLookupItem.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + /// Dictionary Lookup Element. + public partial class DictionaryLookupItem + { + /// Initializes a new instance of DictionaryLookupItem. + /// + /// A string giving the normalized form of the source term. + /// For example, if the request is "JOHN", the normalized form will be "john". + /// The content of this field becomes the input to lookup examples. + /// + /// + /// A string giving the source term in a form best suited for end-user display. + /// For example, if the input is "JOHN", the display form will reflect the usual + /// spelling of the name: "John". + /// + /// A list of translations for the source term. + /// , or is null. + internal DictionaryLookupItem(string normalizedSource, string displaySource, IEnumerable translations) + { + Argument.AssertNotNull(normalizedSource, nameof(normalizedSource)); + Argument.AssertNotNull(displaySource, nameof(displaySource)); + Argument.AssertNotNull(translations, nameof(translations)); + + NormalizedSource = normalizedSource; + DisplaySource = displaySource; + Translations = translations.ToList(); + } + + /// Initializes a new instance of DictionaryLookupItem. + /// + /// A string giving the normalized form of the source term. + /// For example, if the request is "JOHN", the normalized form will be "john". + /// The content of this field becomes the input to lookup examples. + /// + /// + /// A string giving the source term in a form best suited for end-user display. + /// For example, if the input is "JOHN", the display form will reflect the usual + /// spelling of the name: "John". + /// + /// A list of translations for the source term. + internal DictionaryLookupItem(string normalizedSource, string displaySource, IReadOnlyList translations) + { + NormalizedSource = normalizedSource; + DisplaySource = displaySource; + Translations = translations.ToList(); + } + + /// + /// A string giving the normalized form of the source term. + /// For example, if the request is "JOHN", the normalized form will be "john". + /// The content of this field becomes the input to lookup examples. + /// + public string NormalizedSource { get; } + /// + /// A string giving the source term in a form best suited for end-user display. + /// For example, if the input is "JOHN", the display form will reflect the usual + /// spelling of the name: "John". + /// + public string DisplaySource { get; } + /// A list of translations for the source term. + public IReadOnlyList Translations { get; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryTranslation.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryTranslation.Serialization.cs new file mode 100644 index 0000000000000..31641a8d0649e --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryTranslation.Serialization.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + public partial class DictionaryTranslation + { + internal static DictionaryTranslation DeserializeDictionaryTranslation(JsonElement element) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string normalizedTarget = default; + string displayTarget = default; + string posTag = default; + float confidence = default; + string prefixWord = default; + IReadOnlyList backTranslations = default; + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("normalizedTarget"u8)) + { + normalizedTarget = property.Value.GetString(); + continue; + } + if (property.NameEquals("displayTarget"u8)) + { + displayTarget = property.Value.GetString(); + continue; + } + if (property.NameEquals("posTag"u8)) + { + posTag = property.Value.GetString(); + continue; + } + if (property.NameEquals("confidence"u8)) + { + confidence = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("prefixWord"u8)) + { + prefixWord = property.Value.GetString(); + continue; + } + if (property.NameEquals("backTranslations"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(BackTranslation.DeserializeBackTranslation(item)); + } + backTranslations = array; + continue; + } + } + return new DictionaryTranslation(normalizedTarget, displayTarget, posTag, confidence, prefixWord, backTranslations); + } + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DictionaryTranslation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeDictionaryTranslation(document.RootElement); + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryTranslation.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryTranslation.cs new file mode 100644 index 0000000000000..19031f3187a3f --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DictionaryTranslation.cs @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure.Core; + +namespace Azure.AI.Translation.Text +{ + /// Translation source term. + public partial class DictionaryTranslation + { + /// Initializes a new instance of DictionaryTranslation. + /// + /// A string giving the normalized form of this term in the target language. + /// This value should be used as input to lookup examples. + /// + /// + /// A string giving the term in the target language and in a form best suited + /// for end-user display. Generally, this will only differ from the normalizedTarget + /// in terms of capitalization. For example, a proper noun like "Juan" will have + /// normalizedTarget = "juan" and displayTarget = "Juan". + /// + /// A string associating this term with a part-of-speech tag. + /// + /// A value between 0.0 and 1.0 which represents the "confidence" + /// (or perhaps more accurately, "probability in the training data") of that translation pair. + /// The sum of confidence scores for one source word may or may not sum to 1.0. + /// + /// + /// A string giving the word to display as a prefix of the translation. Currently, + /// this is the gendered determiner of nouns, in languages that have gendered determiners. + /// For example, the prefix of the Spanish word "mosca" is "la", since "mosca" is a feminine noun in Spanish. + /// This is only dependent on the translation, and not on the source. + /// If there is no prefix, it will be the empty string. + /// + /// + /// A list of "back translations" of the target. For example, source words that the target can translate to. + /// The list is guaranteed to contain the source word that was requested (e.g., if the source word being + /// looked up is "fly", then it is guaranteed that "fly" will be in the backTranslations list). + /// However, it is not guaranteed to be in the first position, and often will not be. + /// + /// , , , or is null. + internal DictionaryTranslation(string normalizedTarget, string displayTarget, string posTag, float confidence, string prefixWord, IEnumerable backTranslations) + { + Argument.AssertNotNull(normalizedTarget, nameof(normalizedTarget)); + Argument.AssertNotNull(displayTarget, nameof(displayTarget)); + Argument.AssertNotNull(posTag, nameof(posTag)); + Argument.AssertNotNull(prefixWord, nameof(prefixWord)); + Argument.AssertNotNull(backTranslations, nameof(backTranslations)); + + NormalizedTarget = normalizedTarget; + DisplayTarget = displayTarget; + PosTag = posTag; + Confidence = confidence; + PrefixWord = prefixWord; + BackTranslations = backTranslations.ToList(); + } + + /// Initializes a new instance of DictionaryTranslation. + /// + /// A string giving the normalized form of this term in the target language. + /// This value should be used as input to lookup examples. + /// + /// + /// A string giving the term in the target language and in a form best suited + /// for end-user display. Generally, this will only differ from the normalizedTarget + /// in terms of capitalization. For example, a proper noun like "Juan" will have + /// normalizedTarget = "juan" and displayTarget = "Juan". + /// + /// A string associating this term with a part-of-speech tag. + /// + /// A value between 0.0 and 1.0 which represents the "confidence" + /// (or perhaps more accurately, "probability in the training data") of that translation pair. + /// The sum of confidence scores for one source word may or may not sum to 1.0. + /// + /// + /// A string giving the word to display as a prefix of the translation. Currently, + /// this is the gendered determiner of nouns, in languages that have gendered determiners. + /// For example, the prefix of the Spanish word "mosca" is "la", since "mosca" is a feminine noun in Spanish. + /// This is only dependent on the translation, and not on the source. + /// If there is no prefix, it will be the empty string. + /// + /// + /// A list of "back translations" of the target. For example, source words that the target can translate to. + /// The list is guaranteed to contain the source word that was requested (e.g., if the source word being + /// looked up is "fly", then it is guaranteed that "fly" will be in the backTranslations list). + /// However, it is not guaranteed to be in the first position, and often will not be. + /// + internal DictionaryTranslation(string normalizedTarget, string displayTarget, string posTag, float confidence, string prefixWord, IReadOnlyList backTranslations) + { + NormalizedTarget = normalizedTarget; + DisplayTarget = displayTarget; + PosTag = posTag; + Confidence = confidence; + PrefixWord = prefixWord; + BackTranslations = backTranslations.ToList(); + } + + /// + /// A string giving the normalized form of this term in the target language. + /// This value should be used as input to lookup examples. + /// + public string NormalizedTarget { get; } + /// + /// A string giving the term in the target language and in a form best suited + /// for end-user display. Generally, this will only differ from the normalizedTarget + /// in terms of capitalization. For example, a proper noun like "Juan" will have + /// normalizedTarget = "juan" and displayTarget = "Juan". + /// + public string DisplayTarget { get; } + /// A string associating this term with a part-of-speech tag. + public string PosTag { get; } + /// + /// A value between 0.0 and 1.0 which represents the "confidence" + /// (or perhaps more accurately, "probability in the training data") of that translation pair. + /// The sum of confidence scores for one source word may or may not sum to 1.0. + /// + public float Confidence { get; } + /// + /// A string giving the word to display as a prefix of the translation. Currently, + /// this is the gendered determiner of nouns, in languages that have gendered determiners. + /// For example, the prefix of the Spanish word "mosca" is "la", since "mosca" is a feminine noun in Spanish. + /// This is only dependent on the translation, and not on the source. + /// If there is no prefix, it will be the empty string. + /// + public string PrefixWord { get; } + /// + /// A list of "back translations" of the target. For example, source words that the target can translate to. + /// The list is guaranteed to contain the source word that was requested (e.g., if the source word being + /// looked up is "fly", then it is guaranteed that "fly" will be in the backTranslations list). + /// However, it is not guaranteed to be in the first position, and often will not be. + /// + public IReadOnlyList BackTranslations { get; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/Docs/TextTranslationClient.xml b/sdk/translation/Azure.AI.Translation.Text/src/Generated/Docs/TextTranslationClient.xml new file mode 100644 index 0000000000000..f34e51d1f2e51 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/Docs/TextTranslationClient.xml @@ -0,0 +1,963 @@ + + + + + +This sample shows how to call GetLanguagesAsync and parse the result. +"); +var client = new TextTranslationClient(endpoint); + +Response response = await client.GetLanguagesAsync(); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call GetLanguagesAsync with all parameters, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +Response response = await client.GetLanguagesAsync("", "", "", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("translation").GetProperty("").GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("translation").GetProperty("").GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("translation").GetProperty("").GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("toScripts")[0].GetProperty("code").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("toScripts")[0].GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("toScripts")[0].GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("toScripts")[0].GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("code").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("translations")[0].GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("translations")[0].GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("translations")[0].GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("translations")[0].GetProperty("code").ToString()); +]]> + + +Below is the JSON schema for the response payload. + +Response Body: + +Schema for GetLanguagesResult: +{ + translation: Dictionary<string, TranslationLanguage>, # Optional. Languages that support translate API. + transliteration: Dictionary<string, TransliterationLanguage>, # Optional. Languages that support transliteration API. + dictionary: Dictionary<string, SourceDictionaryLanguage>, # Optional. Languages that support dictionary API. +} + + + + + + +This sample shows how to call GetLanguages and parse the result. +"); +var client = new TextTranslationClient(endpoint); + +Response response = client.GetLanguages(); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call GetLanguages with all parameters, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +Response response = client.GetLanguages("", "", "", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("translation").GetProperty("").GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("translation").GetProperty("").GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("translation").GetProperty("").GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("toScripts")[0].GetProperty("code").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("toScripts")[0].GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("toScripts")[0].GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("toScripts")[0].GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("code").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("transliteration").GetProperty("").GetProperty("scripts")[0].GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("translations")[0].GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("translations")[0].GetProperty("nativeName").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("translations")[0].GetProperty("dir").ToString()); +Console.WriteLine(result.GetProperty("dictionary").GetProperty("").GetProperty("translations")[0].GetProperty("code").ToString()); +]]> + + +Below is the JSON schema for the response payload. + +Response Body: + +Schema for GetLanguagesResult: +{ + translation: Dictionary<string, TranslationLanguage>, # Optional. Languages that support translate API. + transliteration: Dictionary<string, TransliterationLanguage>, # Optional. Languages that support transliteration API. + dictionary: Dictionary<string, SourceDictionaryLanguage>, # Optional. Languages that support dictionary API. +} + + + + + + +This sample shows how to call TranslateAsync with required parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = await client.TranslateAsync(new String[]{""}, RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("to").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("text").ToString()); +]]> +This sample shows how to call TranslateAsync with all parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = await client.TranslateAsync(new String[]{""}, RequestContent.Create(data), "", "", "", "", "", "", true, true, "", "", "", true); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result[0].GetProperty("detectedLanguage").GetProperty("language").ToString()); +Console.WriteLine(result[0].GetProperty("detectedLanguage").GetProperty("score").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("to").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("text").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("transliteration").GetProperty("text").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("transliteration").GetProperty("script").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("alignment").GetProperty("proj").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("sentLen").GetProperty("srcSentLen")[0].ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("sentLen").GetProperty("transSentLen")[0].ToString()); +Console.WriteLine(result[0].GetProperty("sourceText").GetProperty("text").ToString()); +]]> + + +Below is the JSON schema for the request and response payloads. + +Request Body: + +Schema for InputTextItem: +{ + text: string, # Required. Text to translate. +} + + +Response Body: + +Schema for TranslatedTextItem: +{ + detectedLanguage: { + language: string, # Required. A string representing the code of the detected language. + score: number, # Required. A float value indicating the confidence in the result. +The score is between zero and one and a low score indicates a low confidence. + }, # Optional. The detectedLanguage property is only present in the result object when language auto-detection is requested. + translations: [ + { + to: string, # Required. A string representing the language code of the target language. + text: string, # Required. A string giving the translated text. + transliteration: { + text: string, # Required. A string which is the result of converting the input string to the output script. + script: string, # Required. A string specifying the script used in the output. + }, # Optional. An object giving the translated text in the script specified by the toScript parameter. + alignment: { + proj: string, # Required. Maps input text to translated text. The alignment information is only provided when the request +parameter includeAlignment is true. Alignment is returned as a string value of the following +format: [[SourceTextStartIndex]:[SourceTextEndIndex]–[TgtTextStartIndex]:[TgtTextEndIndex]]. +The colon separates start and end index, the dash separates the languages, and space separates the words. +One word may align with zero, one, or multiple words in the other language, and the aligned words may +be non-contiguous. When no alignment information is available, the alignment element will be empty. + }, # Optional. Alignment information. + sentLen: { + srcSentLen: [number], # Required. An integer array representing the lengths of the sentences in the input text. +The length of the array is the number of sentences, and the values are the length of each sentence. + transSentLen: [number], # Required. An integer array representing the lengths of the sentences in the translated text. +The length of the array is the number of sentences, and the values are the length of each sentence. + }, # Optional. Sentence boundaries in the input and output texts. + } + ], # Required. An array of translation results. The size of the array matches the number of target +languages specified through the to query parameter. + sourceText: { + text: string, # Required. Input text in the default script of the source language. + }, # Optional. Input text in the default script of the source language. sourceText property is present only when +the input is expressed in a script that's not the usual script for the language. For example, +if the input were Arabic written in Latin script, then sourceText.text would be the same Arabic text +converted into Arab script. +} + + + + + + +This sample shows how to call Translate with required parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = client.Translate(new String[]{""}, RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("to").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("text").ToString()); +]]> +This sample shows how to call Translate with all parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = client.Translate(new String[]{""}, RequestContent.Create(data), "", "", "", "", "", "", true, true, "", "", "", true); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result[0].GetProperty("detectedLanguage").GetProperty("language").ToString()); +Console.WriteLine(result[0].GetProperty("detectedLanguage").GetProperty("score").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("to").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("text").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("transliteration").GetProperty("text").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("transliteration").GetProperty("script").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("alignment").GetProperty("proj").ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("sentLen").GetProperty("srcSentLen")[0].ToString()); +Console.WriteLine(result[0].GetProperty("translations")[0].GetProperty("sentLen").GetProperty("transSentLen")[0].ToString()); +Console.WriteLine(result[0].GetProperty("sourceText").GetProperty("text").ToString()); +]]> + + +Below is the JSON schema for the request and response payloads. + +Request Body: + +Schema for InputTextItem: +{ + text: string, # Required. Text to translate. +} + + +Response Body: + +Schema for TranslatedTextItem: +{ + detectedLanguage: { + language: string, # Required. A string representing the code of the detected language. + score: number, # Required. A float value indicating the confidence in the result. +The score is between zero and one and a low score indicates a low confidence. + }, # Optional. The detectedLanguage property is only present in the result object when language auto-detection is requested. + translations: [ + { + to: string, # Required. A string representing the language code of the target language. + text: string, # Required. A string giving the translated text. + transliteration: { + text: string, # Required. A string which is the result of converting the input string to the output script. + script: string, # Required. A string specifying the script used in the output. + }, # Optional. An object giving the translated text in the script specified by the toScript parameter. + alignment: { + proj: string, # Required. Maps input text to translated text. The alignment information is only provided when the request +parameter includeAlignment is true. Alignment is returned as a string value of the following +format: [[SourceTextStartIndex]:[SourceTextEndIndex]–[TgtTextStartIndex]:[TgtTextEndIndex]]. +The colon separates start and end index, the dash separates the languages, and space separates the words. +One word may align with zero, one, or multiple words in the other language, and the aligned words may +be non-contiguous. When no alignment information is available, the alignment element will be empty. + }, # Optional. Alignment information. + sentLen: { + srcSentLen: [number], # Required. An integer array representing the lengths of the sentences in the input text. +The length of the array is the number of sentences, and the values are the length of each sentence. + transSentLen: [number], # Required. An integer array representing the lengths of the sentences in the translated text. +The length of the array is the number of sentences, and the values are the length of each sentence. + }, # Optional. Sentence boundaries in the input and output texts. + } + ], # Required. An array of translation results. The size of the array matches the number of target +languages specified through the to query parameter. + sourceText: { + text: string, # Required. Input text in the default script of the source language. + }, # Optional. Input text in the default script of the source language. sourceText property is present only when +the input is expressed in a script that's not the usual script for the language. For example, +if the input were Arabic written in Latin script, then sourceText.text would be the same Arabic text +converted into Arab script. +} + + + + + + +This sample shows how to call TransliterateAsync with required parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = await client.TransliterateAsync("", "", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result[0].GetProperty("text").ToString()); +Console.WriteLine(result[0].GetProperty("script").ToString()); +]]> +This sample shows how to call TransliterateAsync with all parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = await client.TransliterateAsync("", "", "", RequestContent.Create(data), ""); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result[0].GetProperty("text").ToString()); +Console.WriteLine(result[0].GetProperty("script").ToString()); +]]> + + +Below is the JSON schema for the request and response payloads. + +Request Body: + +Schema for InputTextItem: +{ + text: string, # Required. Text to translate. +} + + +Response Body: + +Schema for TransliteratedText: +{ + text: string, # Required. A string which is the result of converting the input string to the output script. + script: string, # Required. A string specifying the script used in the output. +} + + + + + + +This sample shows how to call Transliterate with required parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = client.Transliterate("", "", "", RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result[0].GetProperty("text").ToString()); +Console.WriteLine(result[0].GetProperty("script").ToString()); +]]> +This sample shows how to call Transliterate with all parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = client.Transliterate("", "", "", RequestContent.Create(data), ""); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result[0].GetProperty("text").ToString()); +Console.WriteLine(result[0].GetProperty("script").ToString()); +]]> + + +Below is the JSON schema for the request and response payloads. + +Request Body: + +Schema for InputTextItem: +{ + text: string, # Required. Text to translate. +} + + +Response Body: + +Schema for TransliteratedText: +{ + text: string, # Required. A string which is the result of converting the input string to the output script. + script: string, # Required. A string specifying the script used in the output. +} + + + + + + +This sample shows how to call FindSentenceBoundariesAsync with required parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = await client.FindSentenceBoundariesAsync(RequestContent.Create(data)); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result[0].GetProperty("sentLen")[0].ToString()); +]]> +This sample shows how to call FindSentenceBoundariesAsync with all parameters and request content, and how to parse the result. +"); +var client = new TextTranslationClient(endpoint); + +var data = new[] { + new { + text = "", + } +}; + +Response response = await client.FindSentenceBoundariesAsync(RequestContent.Create(data), "", "", "