Text Translation with Azure Translation Services

In the last post, we built an OCR to get text from images. In this post we will translate text from any language to Hindi.
First, create an instance of Text Translator service in your resource group. We used “Translator” Resource Group for this experiment.
Grab the Service key to be used in our application.
In the app

BingTranslator.TranslateTextAsync(text, LanguageCodes.Hindi);

Pass the text and language code to Bing Translation API and you should get your translated text back.

internal static class BingTranslator
        static readonly string uri = "";
        public static async Task<string> TranslateTextAsync(string text, string lang)
            System.Object[] body = new System.Object[] { new { Text = text } };
            var requestBody = JsonConvert.SerializeObject(body);
            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
                request.Method = HttpMethod.Post;
                request.RequestUri = new Uri(uri + lang);
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                request.Headers.Add("Ocp-Apim-Subscription-Key", (string)Application.Current.Resources["BingTranslationKey"]);
                var response = await client.SendAsync(request);
                var responseBody = await response.Content.ReadAsStringAsync();
                TranslatedText[] translatedText = TranslatedText.FromJson(responseBody);
                StringBuilder sb = new StringBuilder();
                foreach (TranslatedText textBlock in translatedText)
                    foreach (Translation translation in textBlock.Translations)
                return sb.ToString();

Here’s Json response expected from the API

    public partial class TranslatedText
        public DetectedLanguage DetectedLanguage { get; set; }
        public Translation[] Translations { get; set; }
    public partial class DetectedLanguage
        public string Language { get; set; }
        public long Score { get; set; }
    public partial class Translation
        public string Text { get; set; }
        public string To { get; set; }

Easy and straight forward, right?

I am a curious mind, always building and experimenting, trying things to decode their inner design. Kind of a small scale inventor ;-) I like to help people realise their passion.

One Comment

Leave a Reply

Your email address will not be published.