Azure Cognitive Services Translator Text API Example

Azure Cognitive Services Translator Text API C# Example

In this Azure tutorial, we will discuss Azure Cognitive Services Translator Text API Example. Along with this, we will also discuss a few other topics as mentioned below

  • What is Azure Cognitive Services Translator Text API?
  • Create a Microsoft Translator Text API in Azure Portal
  • Microsoft Translator API Example.

Azure Cognitive Services Translator Text API Example

Well, in this article We will discuss How to Translate Text Into Multiple Languages Translator Text API With ASP.NET Core And C#. It is going to be an interesting article. As part of this article, we will perform the below steps

  • Create a Translator Text API in Azure Portal.
  • Create ASP.NET Core application using Visual Studio 2019 and use the Translator Text API Key.

Before starting the actual functionality, we need to know What is Azure Cognitive Services Translator Text API? and the Prerequisites needed for the development of this functionality.

What is Azure Cognitive Services Translator Text API?

The Translator Text API is a part of Azure Cognitive Services, an AI service from Microsoft that helps you to translate the text to multiple languages easily. Azure Cognitive Services Translator Text API supports more than 70 languages for the translation.

There are some key benefits of using the Azure Cognitive Services Translator Text API. Those are as below

  • It supports more than 70 languages which is the biggest advantage.
  • You can build custom models for the translation based on your business-specific requirement.
  • As security plays an important role, so it provides Built-in security for your Data. Your Data is safe.

We have a few ideas now on the Microsoft Translator Text API. Now let’s discuss the Prerequisites needed for implementing the functionality here.

Prerequisites

  • You must have a valid Azure Subscription or a valid Azure Account. If you don’t have an Azure Account till now, create an Azure free account now.
  • You need to install the Visual Studio 2019 in your machine. If you haven’t installed the Visual Studio 2019 in your Dev machine till now, Download and install Visual Studio 2019 in your Dev machine now.

Assuming you have all the prerequisites needed here, Let’s start creating the Microsoft Translator Text API in the Azure Portal and discuss an Azure Cognitive Services Translator Text API Example.

Create a Microsoft Translator Text API in Azure Portal

The first step is to Create an Azure Translator Text API in Azure Portal. Follow the below steps to create Azure Cognitive Services Translator Text API.

Login to the Azure Portal (https://portal.azure.com/)

Once you logged in to the Azure Portal, search for the Translator and then click on the search result Translator under the Marketplace as highlighted below.

Create a Microsoft Translator Text API in Azure Portal

Or for the same option, you can click on the + Create a resource from the left navigation on the Home page. On the New window, search for the Translator and then click on the search result Translator.

Create a Translator Text API using Azure Portal

Now the next step is, click on the Create button on the Translator window as shown below.

How to Create a Microsoft Translator Text API in Azure Portal

Now, on the Create Translator window, Provide the below details

  • Subscription: You must Choose a valid subscription that you want to use here.
  • Resource Group: You can choose your existing Resource Group here. If you don’t have an existing Resource Group created till now then create a new Resource Group by clicking on the Create new link.
  • Resource Region: Select a Region for your Azure Resource.
  • Name: You need to provide a unique name for your Azure Cognitive Services Translator Text API.
  • Pricing tier: You can select the Pricing tier based on your business need. You can click on the View full pricing details link to verify the pricing details for your reference. For the Demo purpose, you can choose the Free F0 tier. For this tier, you can get up to 2M number of characters translated per month free of cost.

After providing all the above details, click on the Review + Create button as highlighted below.

Create a Microsoft Translator Text API using Azure Portal

On the next window, it will validate all the information entered by you on the above window, and then it will show you the Validation Passed message. Now, You can able to see the Create button is enabled as shown below. Now you can verify the details entered by you again for a safer side and then click on the Create button to create the Microsoft Translator Text API.

Create Microsoft Translator Text API Azure Portal

Once you will click on the Create button, it will take a few seconds to create all the components and you can able to see below, the deployment is completed successfully without any issue. Click on the Go to resource button to see the Microsoft Translator Text API that you have created just now.

Create Microsoft Translator Text in API Azure Portal

Below is the Microsoft Translator Text API that we have created just now.

Create Microsoft Translator Text API in Azure Portal

So, our Azure Cognitive Services Translator Text API is ready now. The next step is to copy the value of the Key1 of the Azure Cognitive Services Translator Text API. To copy the key1 value, click on the Keys and Endpoint option from the left navigation on the Cognitive Services window. You can click on the Copy button to copy the Key1 or Key2 value as highlighted below. Copy the key value and keep it in a notepad, that we are going to use in the Asp.Net core application code in Visual Studio.

Create Azure Cognitive Services Translator Text API

So, we have created the Azure Cognitive Services Translator Text API in Azure Portal and we have also copied the key value of the Translator Text API which we will use in the next steps.

Now the time to create a Asp.Net core application using Visual Studio 2019.

Open the Visual Studio 2019 and click on the Create a new Project button on the Getting started page

Now on the next window, choose the project template as ASP.Net Core Web Application and then click on the Next button.

Translate Text Into Multiple Languages Using Translator Text API

On the Configure your new project window, Provide the below details

  • Project Name: Provide a unique name for your Project.
  • Location: Choose a location where you want to save your project locally.

Then click on the Create button to navigate to the next window.

Create a Microsoft Translator Text API Azure Portal

On the Create a new ASP.NET Core web application window, select the web Application project template and then click on the Create button to create the project.

Create a Microsoft Translator Text API

Now the Project will get created successfully with out any issue

Now we need to add the code needed for the functionality. You need to do the below changes in the Index.cshtml file.

Azure Cognitive Services Translator Text API example

Now, you need to add the code for the site.js file as the below

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

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

                var url = '/Home/Index';
                var dataToSend = { "LanguageCode": langCode, "Text": eText };
                dataType: "json",
                    $.ajax({
                        url: url,
                        data: dataToSend,
                        type: 'POST',
                        success: function (response) {
                           
                            var result = JSON.parse(response);
                            var tText = result[0].translations[0].text;
                            $('#idtransText').val(tText);
                        }
                    })
            }
            else {
                $('#idText').addClass('redBorder');
                $('#idtransText').val("");
            }
        });
});  

Now the next steps are to create the interface named as ITextTranslation and that should contain the below lines of code

namespace DemoTranslateAPP
{
    interface ITextTranslation
    {
        Task<string> Translation(string uri, string text, string key);
    }
}

Now the next is to create the TextTranslationService and that should contain the below code

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace DemoTranslateAPP
{
    public class TextTranslationService : ITextTranslation
    {
        public async Task<string> Translation(string uri, string text, string key)
        {
            System.Object[] body = new System.Object[] { new { Text = text } };
            var requestBody = JsonConvert.SerializeObject(body);

            using (var cnt = new HttpClient())
            using (var rqst = new HttpRequestMessage())
            {
                rqst.Method = HttpMethod.Post;
                rqst.RequestUri = new Uri(uri);
                rqst.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                rqst.Headers.Add("Ocp-Apim-Subscription-Key", key);

                var rspns = await cnt.SendAsync(rqst);
                var responseBody = await rspns.Content.ReadAsStringAsync();
                dynamic result = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseBody), Formatting.Indented);

                return result;
            }
        }
    }
}

Note: Don’t forget to inject the TextTranslationService and ITextTranslation in the startup.cs class file.

Now we are done with the changes, press F5 to run the project. Now the project should run successfully without any issue.

The JSON response will be something like below

[  
  {  
    "detectedLanguage": {  
      "language": "en",  
      "score": 1.0  
    },  
    "translations": [  
      {  
        "text": "भगवान आपका भला करे",  
        "to": "God is Great"  
      }  
    ]  
  }  
]  

Enter the text and the text will get transferred to the language present in the drop-down list.

This is how you can work with Azure Cognitive Services Translator Text API ASP.NET Core. We have discussed one of the Azure Cognitive Services Translator Text API Example.

Microsoft Translator API Example

Well, here we will discuss another example of the implementation of Azure Cognitive Services Translator Text API. Here in this example, we will perform the below steps

  • We will create an Azure Cognitive Services Translator Text API in the Azure Portal
  • We will create a console application and we will use the Translator Text API there.

How To Create a Microsoft Translator Text API Using Azure Portal

The first step is to create a Microsoft Translator Text API Using Azure Portal. Since we have already created the Microsoft Translator Text API using the Azure Portal above. You can refer to the Create a Microsoft Translator Text API in Azure Portal section of the article to create the Microsoft Translator Text API.

So I am going to use the same Azure Cognitive Services Translator Text API that I have created above. Below is the Translator Text API that I have already created above.

So copy the Key1 value to a notepad that we are going to use in the console application which we are going to create in the next step. Click on the Copy button next to the Key1 value as highlighted below. You can also click on the Regenerate key1 or Regenerate key2 and copy the new key-value if you want to use the new key value.

How To Create a Microsoft Translator Text API Using Azure Portal

Now We have copied the Key value of our Azure Translator Text API and the Region for our Azure Translator Text API is eastus. Now let’s move to the next step where we are going to create a console application using Visual Studio 2019.

Create a console application using Visual Studio 2019

Follow the below steps to Create a console application using Visual Studio 2019.

Open the Visual Studio 2019 in your dev machine and click on the Create a new project button on the Getting Started window.

Now choose the Project template as Console App (.NET Frame work) and click on the Next Button. You can also select the Core Console App.

Create a Azure Translator Text API Azure Portal

Now on the Configure your new project window, Provide the Project name, Choose a location for your Console application project and then choose the Framework as the latest version of the .NET Framework. Now, Finally, click on the Create button to create the Console application.

How To Create a Microsoft Translator Text API

Now the Project will create successfully with out any issue.

Now the next step is to add the NuGet Package i.e Newtonsoft.Json to the project. To add the NuGet package, Right-click on the Project and then choose Manage NuGet Packages.

Now From the below window select the Browse tab and search for the Network.json and select the NuGet package and click on the Install button to install the NuGet package as highlighted below.

Microsoft Translator Text API Example

Now on the Program.cs file add the below using statement

using Newtonsoft.Json;

Now on the same Program.cs file, Add the rest of the code as below. Below is the complete code for the Program.cs file.

Note: Make sure to change the value for the Key-Value(Put the key value of your Azure Translator Text API that you have copied in the above step ) and then also change the value for the Ocp-Apim-Subscription-Region value (This should be the Region for your Azure Translator Text API. For me, it is eastus).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Newtonsoft.Json;



namespace DemoTranslatorAPI
{
    
   public class Program
    {
        private const string key = "db0746e18e27457fbe3ed52ba6188753";

        public static async Task Main()

        {
            while (true)
            {
                var text = Console.ReadLine();

                var lang = Console.ReadLine();
                Translate(text, lang);
            }
        }
        public static async void Translate(string text, string language)
        {
            var encodtxt = WebUtility.UrlEncode(text);
            string texttotranslate = text;

            string uri = $"https://api.cognitive.microsofttranslator.com//translate?api-version=3.0&from=en&to={language}";

            System.Object[] body = new System.Object[] { new { Text = texttotranslate } };
            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);
                request.Headers.Add("Ocp-Apim-Subscription-Region", "eastus");
                var response = await client.SendAsync(request);
                var responseBody = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject<List<Dictionary<string, List<Dictionary<string, string>>>>>(responseBody);
                var translation = result[0]["translations"][0]["text"];

                Console.WriteLine(translation);

            }
        }
    }
}

Now we are done with the code changes, Press F5 to run the Application, You can able to see the Console window Type a word or sentence in the English language and choose the language code to which you want to translate the text, and then press Enter from your Key Board.

For example, I have entered the word “love” and then I have chosen “it”(Italian) and then pressed Enter and also I have entered a statement in English “God bless you” and then entered “it”(Italian), then pressed Enter from the Keyboard. Then I have entered “God bless you” and then entered “es” and then I have entered “love” and then “es” You can able to see I got the OutPut as below.

love
it
Amore
God Bless you
it
Dio ti benedica
God Bless you
es
Que dios te bendiga
love
es
Amor

You can see the Output as below

How To Create a Microsoft Translator Text API Using Azure Portal

So, We have discussed here two Azure Cognitive Services Translator Text API Examples. One is with the ASP.Net core and one with the Console application. We discussed here, How to Translate Text Into Multiple Languages Using Translator Text API.

You may also like following the below Articles

Wrapping Up

Well, in this article, we have discussed Azure Cognitive Services Translator Text API ASP.NET Core Example, What is Azure Cognitive Services Translator Text API? and we also discussed Create a Microsoft Translator Text API in Azure Portal, Microsoft Translator Text API Example. Hope you have enjoyed this article !!!

Leave a Comment