/// <summary> /// Translates a single message from a source language to a target language. /// </summary> /// <param name="textToTranslate">The text to translate.</param> /// <param name="from">The language code of the translation text. For example, "en" for English.</param> /// <param name="to">The language code to translate the text into.</param> /// <returns>The translated document.</returns> public async Task <TranslatedDocument> TranslateAsync(string textToTranslate, string from, string to) { var currentTranslatedDocument = new TranslatedDocument(textToTranslate); PreprocessMessage(currentTranslatedDocument.SourceMessage, out var processedText, out var literanlNoTranslateList); currentTranslatedDocument.SourceMessage = processedText; currentTranslatedDocument.LiteranlNoTranslatePhrases = literanlNoTranslateList; var url = "http://api.microsofttranslator.com/v2/Http.svc/Translate"; var query = $"?text={System.Net.WebUtility.UrlEncode(textToTranslate)}" + $"&from={from}" + $"&to={to}"; using (var request = new HttpRequestMessage()) { var accessToken = await _authToken.GetAccessTokenAsync().ConfigureAwait(false); request.Headers.Add("Authorization", accessToken); request.RequestUri = new Uri(url + query); using (var response = await _httpClient.SendAsync(request)) { var result = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new ArgumentException(result); } var translatedText = XElement.Parse(result).Value.Trim(); currentTranslatedDocument.TargetMessage = translatedText; return(currentTranslatedDocument); } } }
/// <summary> /// Translates an array of strings from a source language to a target language. /// </summary> /// <param name="translateArraySourceTexts">The strings to translate.</param> /// <param name="from">The language code of the translation text. For example, "en" for English.</param> /// <param name="to">The language code to translate the text into.</param> /// <returns>An array of the translated documents.</returns> public async Task <List <TranslatedDocument> > TranslateArrayAsync(string[] translateArraySourceTexts, string from, string to) { var translatedDocuments = new List <TranslatedDocument>(); var uri = "https://api.microsofttranslator.com/v2/Http.svc/TranslateArray2"; for (var srcTxtIndx = 0; srcTxtIndx < translateArraySourceTexts.Length; srcTxtIndx++) { // Check for literal tag in input user message var currentTranslatedDocument = new TranslatedDocument(translateArraySourceTexts[srcTxtIndx]); translatedDocuments.Add(currentTranslatedDocument); PreprocessMessage(currentTranslatedDocument.SourceMessage, out var processedText, out var literanlNoTranslateList); currentTranslatedDocument.SourceMessage = processedText; translateArraySourceTexts[srcTxtIndx] = processedText; currentTranslatedDocument.LiteranlNoTranslatePhrases = literanlNoTranslateList; } // body of http request var body = $"<TranslateArrayRequest>" + "<AppId />" + $"<From>{from}</From>" + "<Options>" + " <Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" >generalnn</Category>" + "<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">text/plain</ContentType>" + "<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" + "<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" + "<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" + "<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" + "</Options>" + "<Texts>" + string.Join(string.Empty, translateArraySourceTexts.Select(s => $"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{SecurityElement.Escape(s)}</string>\n")) + "</Texts>" + $"<To>{to}</To>" + "</TranslateArrayRequest>"; var accessToken = await _authToken.GetAccessTokenAsync().ConfigureAwait(false); using (var request = new HttpRequestMessage()) { request.Method = HttpMethod.Post; request.RequestUri = new Uri(uri); request.Content = new StringContent(body, Encoding.UTF8, "text/xml"); request.Headers.Add("Authorization", accessToken); using (var response = await _httpClient.SendAsync(request)) { var responseBody = await response.Content.ReadAsStringAsync(); switch (response.StatusCode) { case HttpStatusCode.OK: Console.WriteLine("Request status is OK. Result of translate array method is:"); var doc = XDocument.Parse(responseBody); var ns = XNamespace.Get("http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2"); var results = new List <string>(); var sentIndex = 0; foreach (var xe in doc.Descendants(ns + "TranslateArray2Response")) { var currentTranslatedDocument = translatedDocuments[sentIndex]; currentTranslatedDocument.RawAlignment = xe.Element(ns + "Alignment").Value; if (!string.IsNullOrEmpty(currentTranslatedDocument.RawAlignment)) { var alignments = currentTranslatedDocument.RawAlignment.Trim().Split(' '); currentTranslatedDocument.SourceTokens = PostProcessingUtilities.SplitSentence(currentTranslatedDocument.SourceMessage, alignments); currentTranslatedDocument.TranslatedTokens = PostProcessingUtilities.SplitSentence(xe.Element(ns + "TranslatedText").Value, alignments, false); currentTranslatedDocument.IndexedAlignment = PostProcessingUtilities.WordAlignmentParse(alignments, currentTranslatedDocument.SourceTokens, currentTranslatedDocument.TranslatedTokens); } sentIndex += 1; } return(translatedDocuments); default: throw new Exception(response.ReasonPhrase); } } } }
/// <summary> /// Translates an array of strings from a source language to a target language. /// </summary> /// <param name="translateArraySourceTexts">The strings to translate.</param> /// <param name="from">The language code of the translation text. For example, "en" for English.</param> /// <param name="to">The language code to translate the text into.</param> /// <returns>An array of the translated documents.</returns> public async Task <List <TranslatedDocument> > TranslateArrayAsync(string[] translateArraySourceTexts, string from, string to) { var translatedDocuments = new List <TranslatedDocument>(); for (var srcTxtIndx = 0; srcTxtIndx < translateArraySourceTexts.Length; srcTxtIndx++) { // Check for literal tag in input user message var currentTranslatedDocument = new TranslatedDocument(translateArraySourceTexts[srcTxtIndx]); translatedDocuments.Add(currentTranslatedDocument); PreprocessMessage(currentTranslatedDocument.SourceMessage, out var processedText, out var literanlNoTranslateList); currentTranslatedDocument.SourceMessage = processedText; translateArraySourceTexts[srcTxtIndx] = processedText; currentTranslatedDocument.LiteranlNoTranslatePhrases = literanlNoTranslateList; } // list of translation request for the service var payload = translateArraySourceTexts.Select(s => new TranslatorRequestModel { Text = s }); using (var request = GetTranslateRequestMessage(from, to, payload)) { using (var response = await _httpClient.SendAsync(request).ConfigureAwait(false)) { if (response.IsSuccessStatusCode) { var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var translatedResults = JsonConvert.DeserializeObject <IEnumerable <TranslatedResult> >(responseBody); var sentIndex = 0; foreach (var translatedValue in translatedResults) { var translation = translatedValue.Translations.First(); var currentTranslatedDocument = translatedDocuments[sentIndex]; currentTranslatedDocument.RawAlignment = translation.Alignment?.Projection ?? null; currentTranslatedDocument.TargetMessage = translation.Text; if (!string.IsNullOrEmpty(currentTranslatedDocument.RawAlignment)) { var alignments = currentTranslatedDocument.RawAlignment.Trim().Split(' '); currentTranslatedDocument.SourceTokens = PostProcessingUtilities.SplitSentence(currentTranslatedDocument.SourceMessage, alignments); currentTranslatedDocument.TranslatedTokens = PostProcessingUtilities.SplitSentence(translation.Text, alignments, false); currentTranslatedDocument.IndexedAlignment = PostProcessingUtilities.WordAlignmentParse(alignments, currentTranslatedDocument.SourceTokens, currentTranslatedDocument.TranslatedTokens); currentTranslatedDocument.TargetMessage = PostProcessingUtilities.Join(" ", currentTranslatedDocument.TranslatedTokens); } else { var translatedText = translation.Text; currentTranslatedDocument.TargetMessage = translatedText; currentTranslatedDocument.SourceTokens = new string[] { currentTranslatedDocument.SourceMessage }; currentTranslatedDocument.TranslatedTokens = new string[] { currentTranslatedDocument.TargetMessage }; currentTranslatedDocument.IndexedAlignment = new Dictionary <int, int>(); } sentIndex++; } return(translatedDocuments); } else { var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var errorResult = JsonConvert.DeserializeObject <ErrorModel>(responseBody); throw new ArgumentException(errorResult.Error.Message); } } } }