Translate Text Into Multiple Languages Using Translator Text API With ASP.NET Core And C#

Introduction

In this article, we are going to learn how to translate text into multiple languages using an important Cognitive Services API called Microsoft Translate Text API (one of the Language APIs). It’s a simple cloud-based machine translation service and obviously, we can test it through simple Rest API call. Microsoft is using a new standard for high-quality AI-powered machine translations known as Neural Machine Translation (NMT).

Neural Machine

Pic source: https://www.microsoft.com/en-us/translator/business/machine-translation/#whatmachine

You can also refer to the following articles on Cognitive Services.

Prerequisites

  1. Subscription key (Azure Portal)
  2. Visual Studio 2015 or 2017

Translator Text API

First, we need to log into the Azure Portal with our Azure credentials. Then, we need to create an Azure Translator Text API in the Azure portal. So please click on the "Create a resource" on the left top menu and search "Translator Text" in the search bar on the right side window or on the top of Azure Marketplace.

Azure Marketplace

Click on the “Create” button to create Translator Text API.

Create

Provision a translator text subscription key

After clicking "Create", it will open another window. There, we need to provide the basic information about Translator Text API.

Window

  • Name: Name of the Translator Text API ( Eg. TranslatorTextApp ).
  • Subscription: We can select our Azure subscription for Translator Text API creation.
  • Location: We can select the location of a resource group. The best thing is we can choose a location closest to our customers.
  • Pricing tier: Select an appropriate pricing tier for our requirement.
  • Resource group: We can create a new resource group or choose from an existing one.

Now click on the "TranslatorTextApp" in the dashboard page and it will redirect to the detailed page of TranslatorTextApp ( "Overview" ). Here, we can see the "Keys" ( Subscription key details ) menu on the left side panel. Then click on the "Keys" menu and it will open the Subscription Keys details. We can use any of the subscription keys or regenerate the given key for text translation using Microsoft Translator Text API.

Text API

Language request URL

The following request URL gets the set of languages currently supported by other operations of the Microsoft Translator Text API.

"https://api.cognitive.microsofttranslator.com/languages?api-version=3.0"

Endpoint

The version of the API requested by the client and the Value must be 3.0 and also we can include query parameters and request headers in the following endPoint used in our application.

"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0"

Mandatorily required parameters in the query string are "API-version" and "to". The "API-version" value must be "3.0" as per the current documentation. "to" is the language code parameter used for translating the entered text into the desired language.

The mandatory request headers are "authorization header" and "Content-Type". We can pass our subscription key into the "authorization header" and the simplest way is to pass our Azure secret key to the Translator service using the request header "Ocp-Apim-Subscription-Key".

Index.html

The following HTML contains the binding methodology that we have used in our application by using the latest Tag helpers of ASP.Net Core.

ASP.Net Core

site.js

The following Ajax call will trigger for each drop-down index change in the language selection using the drop-down list.

$(function () {
    $(document)
        .on('change', '#ddlLangCode', function () {
            var languageCode = $(this).val();
            var enterText = $("#enterText").val();
            if (1 <= $("#enterText").val().trim().length && languageCode != "NA") {

                $('#enterText').removeClass('redBorder');

                var url = '/Home/Index';
                var dataToSend = { "LanguageCode": languageCode, "Text": enterText };
                dataType: "json",
                $.ajax({
                    url: url,
                    data: dataToSend,
                    type: 'POST',
                    success: function (response) {
                        //update control on View
                        var result = JSON.parse(response);
                        var translatedText = result[0].translations[0].text;
                        $('#translatedText').val(translatedText);
                    }
                })
            } else {
                $('#enterText').addClass('redBorder');
                $('#translatedText').val("");
            }
        });
});

Interface

The "ITranslateText" contains one signature for translating text content based on the given input. So we have injected this interface in the ASP.NET Core "Startup. cs" class as an "AddTransient".

using System.Threading.Tasks;
namespace TranslateTextApp.Business_Layer.Interface
{
    interface ITranslateText
    {
        Task<string> Translate(string uri, string text, string key);
    }
}

Translator text API service

We can add the valid Translator Text API Subscription Key to the following code.

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using TranslateTextApp.Business_Layer.Interface;
namespace TranslateTextApp.Business_Layer
{
    public class TranslateTextService : ITranslateText
    {
        /// <summary>
        /// Translate the given text into the selected language.
        /// </summary>
        /// <param name="uri">Request URI</param>
        /// <param name="text">The text to be translated</param>
        /// <param name="key">Subscription key</param>
        /// <returns></returns>
        public async Task<string> Translate(string uri, string text, string key)
        {
            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);
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                request.Headers.Add("Ocp-Apim-Subscription-Key", key);

                var response = await client.SendAsync(request);
                var responseBody = await response.Content.ReadAsStringAsync();
                dynamic result = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseBody), Formatting.Indented);

                return result;
            }
        }
    }
}

API response Based on the given text

The successful JSON response.

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "सफलता का कोई शार्टकट नहीं होता",
        "to": "hi"
      }
    ]
  }
]

Download: Source Code

Output

The given text is translated into the desired language listed in the drop-down list using Microsoft Translator API.

 Translator API

Reference

Summary

From this article, we have learned to translate a text (typed in English) into different languages as per the API documentation using one of the important Cognitive Services API ( Translator Text API is a part of Language API ). I hope this article is useful for all Azure Cognitive Services API beginners.

See Also

You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.


Similar Articles