Creating A Multi-Language Translator Using Blazor And Azure Cognitive Services

Introduction

 
In this article, we will create a multi-language translator using Blazor and the Translate Text Azure Cognitive Service. This translator will be able to translate between all the languages supported by the Translate Text API. Currently, the Translate Text API supports more than 60 languages for translation. The application will accept the text to translate and the target language as the input and returns the translated text and the detected language for the input text as the output.
 
Take a look at the output shown below.
 
Creating A Multi-Language Translator Using Blazor And Azure Cognitive Services
 
Prerequisites
Source Code
 
You can get the source code from GitHub.
 

Create the Azure Translator Text Cognitive Services Resource

 
Log in to the Azure portal and search for the cognitive services in the search bar and click on the result. Refer to the image shown below.
 
Creating A Multi-Language Translator Using Blazor And Azure Cognitive Services
 
On the next screen, click on the Add button. It will open the cognitive services marketplace page. Search for the "Translator Text" in the search bar and click on the search result. It will open the Translator Text API page. Click on the "Create" button to create a new Translator Text resource. Refer to the image shown below.
 
Creating A Multi-Language Translator Using Blazor And Azure Cognitive Services
 
On the Create page, fill in the details as indicated below, 
  • Name: Give a unique name for your resource.
  • Subscription: Select the subscription type from the dropdown.
  • Pricing tier: Select the pricing tier as per your choice.
  • Resource group: Select an existing resource group or create a new one.
Click on the Create button. Refer to the image shown below.
 
Creating A Multi-Language Translator Using Blazor And Azure Cognitive Services
 
After your resource is successfully deployed, click on the “Go to resource” button. You can see the Key and the endpoint for the newly created Translator Text resource. Refer to the image shown below.
 
Creating A Multi-Language Translator Using Blazor And Azure Cognitive Services
 
Make a note of the key, we will be using this in the latter part of this article to request the translations from the Translator Text API. The values are masked here for privacy.
 

Create a Server-Side Blazor Application

 
Open Visual Studio 2019, click on “Create a new project”. Select “Blazor App” and click on the “Next” button. Refer to the image shown below.
 
Creating A Multi-Language Translator Using Blazor And Azure Cognitive Services
 
On the next window, put the project name as BlazorTranslator and click on the “Create” button. The next window will ask you to select the type of Blazor app. Select Blazor Server App and click on the Create button to create a new server-side Blazor application. Refer to the image shown below.
 
Creating A Multi-Language Translator Using Blazor And Azure Cognitive Services
 

Creating the Models

 
Right-click on BlazorTranslator project and select Add >> New Folder. Name the folder as Models. Again, right-click on the Models folder and select Add >> Class to add a new class file. Put the name of your class as LanguageDetails.cs and click Add.
 
Open LanguageDetails.cs and put the following code inside it.
  1. namespace BlazorTranslator.Models  
  2. {  
  3.     public class LanguageDetails  
  4.     {  
  5.         public string Name { getset; }  
  6.         public string NativeName { getset; }  
  7.         public string Dir { getset; }  
  8.     }  
  9. }  
Similarly, add a new class file TextResult.cs and put the following code inside it.
  1. using System;  
  2.   
  3. namespace BlazorTranslator.Models  
  4. {  
  5.     public class TextResult  
  6.     {  
  7.         public string Text { getset; }  
  8.         public string Script { getset; }  
  9.     }  
  10. }  
Add a new class file Translation.cs and put the following code inside it.
  1. namespace BlazorTranslator.Models  
  2. {  
  3.     public class Translation  
  4.     {  
  5.         public string Text { getset; }  
  6.         public TextResult Transliteration { getset; }  
  7.         public string To { getset; }  
  8.     }  
  9. }  
Create a class file DetectedLanguage.cs and put the following code inside it.
  1. namespace BlazorTranslator.Models  
  2. {  
  3.     public class DetectedLanguage  
  4.     {  
  5.         public string Language { getset; }  
  6.         public float Score { getset; }  
  7.     }  
  8. }  
Create a class file TranslationResult.cs and put the following code inside it.
  1. namespace BlazorTranslator.Models  
  2. {  
  3.     public class TranslationResult  
  4.     {  
  5.         public DetectedLanguage DetectedLanguage { getset; }  
  6.         public TextResult SourceText { getset; }  
  7.         public Translation[] Translations { getset; }  
  8.     }  
  9. }  
Finally, create the class file AvailableLanguage.cs and put the following code inside it.
  1. using System.Collections.Generic;  
  2.   
  3. namespace BlazorTranslator.Models  
  4. {  
  5.     public class AvailableLanguage  
  6.     {  
  7.       public Dictionary<string, LanguageDetails> Translation { getset; }  
  8.     }  
  9. }  

Create the Translation service

 
Right-click on the BlazorTranslator/Data folder and select Add >> Class to add a new class file. Put the name of the file as TranslationService.cs and click on Add. Open TranslationService.cs file and put the following code inside it.
  1. using BlazorTranslator.Models;  
  2. using Newtonsoft.Json;  
  3. using System;  
  4. using System.Net.Http;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace BlazorTranslator.Data  
  9. {  
  10.     public class TranslationService  
  11.     {  
  12.         public async Task<TranslationResult[]> GetTranslatation(string textToTranslate, string targetLanguage)  
  13.         {  
  14.             string subscriptionKey = "af19d996a3cb4a70a808567aad5bc41a";  
  15.             string apiEndpoint = "https://api.cognitive.microsofttranslator.com/";  
  16.             string route = $"/translate?api-version=3.0&to={targetLanguage}";  
  17.             string requestUri = apiEndpoint + route;  
  18.             TranslationResult[] translationResult = await TranslateText(subscriptionKey, requestUri, textToTranslate);  
  19.             return translationResult;  
  20.         }  
  21.   
  22.         async Task<TranslationResult[]> TranslateText(string subscriptionKey, string requestUri, string inputText)  
  23.         {  
  24.             object[] body = new object[] { new { Text = inputText } };  
  25.             var requestBody = JsonConvert.SerializeObject(body);  
  26.   
  27.             using (var client = new HttpClient())  
  28.             using (var request = new HttpRequestMessage())  
  29.             {  
  30.                 request.Method = HttpMethod.Post;  
  31.                 request.RequestUri = new Uri(requestUri);  
  32.                 request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");  
  33.                 request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);  
  34.   
  35.                 HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);  
  36.                 string result = await response.Content.ReadAsStringAsync();  
  37.                 TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);  
  38.   
  39.                 return deserializedOutput;  
  40.             }  
  41.         }  
  42.   
  43.         public async Task<AvailableLanguage> GetAvailableLanguages()  
  44.         {  
  45.             string endpoint = "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation";  
  46.             var client = new HttpClient();  
  47.             using (var request = new HttpRequestMessage())  
  48.             {  
  49.                 request.Method = HttpMethod.Get;  
  50.                 request.RequestUri = new Uri(endpoint);  
  51.                 var response = await client.SendAsync(request).ConfigureAwait(false);  
  52.                 string result = await response.Content.ReadAsStringAsync();  
  53.   
  54.                 AvailableLanguage deserializedOutput = JsonConvert.DeserializeObject<AvailableLanguage>(result);  
  55.   
  56.                 return deserializedOutput;  
  57.             }  
  58.         }  
  59.     }  
  60. }  
We have defined a GetTranslatation method which will accept two parameters – the text to translate and the target language. We will set the subscription key for the Azure Translator Text cognitive service and define a variable for the global endpoint for Translator Text. The request URL contains the API endpoint along with the target language.
Inside the TranslateText method, we will create a new HttpRequestMessage. This HTTP request is a Post request. We will pass the subscription key in the header of the request. The Translator Text API returns a JSON object, which will be deserialized to an array of type TranslationResult. The output contains the translated text as well as the language detected for the input text.
 
The GetAvailableLanguages method will return the list of all the language supported by the Translate Text API. We will set the request URI and create a HttpRequestMessage which will be a Get request. This request URL will return a JSON object which will be deserialized to an object of type AvailableLanguage.
 

Configuring the Service 

 
To make the service available to the components we need to configure it on the server-side app. Open the Startup.cs file. Add the following line inside the ConfigureServices method of Startup class.
  1. services.AddSingleton<TranslationService>();  

Creating the Blazor UI Component

 
We will add the Razor page in BlazorTranslator/Pages folder. By default, we have “Counter” and “Fetch Data” pages provided in our application. These default pages will not affect our application but for the sake of this tutorial, we will delete fetchdata and counter pages from BlazorTranslator/Pages folder.
 
Right-click on BlazorTranslator/Pages folder and then select Add >> New Item. An “Add New Item” dialog box will open, select “Visual C#” from the left panel, then select “Razor Component” from the templates panel, put the name as Translator.razor. Click Add. Refer to the image shown below.
 
Creating A Multi-Language Translator Using Blazor And Azure Cognitive Services
 
Open the Translator.razor file and add the following code at the top.
  1. @page "/translator"  
  2. @using BlazorTranslator.Models  
  3. @using BlazorTranslator.Data  
  4. @inject TranslationService translationService  
We have defined the route for this component. We are also injecting the TranslationService in this component.
 
Now we will add the following HTML code in this file.
  1. <h3>Multilanguage translator using Microsoft Translator API Cognitive Service</h3>  
  2. <hr />  
  3.   
  4. <div class="container">  
  5.     <div class="row">  
  6.         <div class="col-md-6">  
  7.             <select class="form-control" @bind="inputLanguage">  
  8.                 <option value="">-- Select input language --</option>  
  9.                 @foreach (KeyValuePair<string, LanguageDetails> lang in LanguageList)  
  10.                 {  
  11.                     <option value="@lang.Key">@lang.Value.Name</option>  
  12.                 }  
  13.             </select>  
  14.             <textarea placeholder="Enter text to translate" class="form-control translation-box" rows="5" @bind="@inputText"></textarea>  
  15.         </div>  
  16.         <div class="col-md-6">  
  17.             <select class="form-control" @onchange="SelectLanguage">  
  18.                 <option value="">-- Select target language --</option>  
  19.                 @foreach (KeyValuePair<string, LanguageDetails> lang in LanguageList)  
  20.                 {  
  21.                     <option value="@lang.Key">@lang.Value.Name</option>  
  22.                 }  
  23.             </select>  
  24.             <textarea disabled class="form-control translation-box" rows="5">@outputText</textarea>  
  25.         </div>  
  26.     </div>  
  27.     <div class="text-center">  
  28.         <button class="btn btn-primary btn-lg" @onclick="Translate">Translate</button>  
  29.     </div>  
  30. </div>  
We have defined two dropdown lists, one each for input language and one for the target language. The Azure Translate Text API will detect the input language and we will use that value to populate the dropdown for input language. We have also defined two text areas for the input and the translated text.
 
Finally, add the following code in the @code section of the page.
  1. @code {  
  2.     private TranslationResult[] translations;  
  3.     private AvailableLanguage availableLanguages;  
  4.   
  5.     private string outputLanguage { getset; }  
  6.     private string inputLanguage { getset; }  
  7.   
  8.     string inputText { getset; }  
  9.     string outputText { getset; }  
  10.   
  11.     private Dictionary<string, LanguageDetails> LanguageList = new Dictionary<string, LanguageDetails>();  
  12.   
  13.     protected override async Task OnInitializedAsync()  
  14.     {  
  15.         availableLanguages = await translationService.GetAvailableLanguages();  
  16.         LanguageList = availableLanguages.Translation;  
  17.     }  
  18.   
  19.     private void SelectLanguage(ChangeEventArgs langEvent)  
  20.     {  
  21.         this.outputLanguage = langEvent.Value.ToString();  
  22.     }  
  23.   
  24.     private async Task Translate()  
  25.     {  
  26.         if (!string.IsNullOrEmpty(outputLanguage))  
  27.         {  
  28.             translations = await translationService.GetTranslatation(this.inputText, this.outputLanguage);  
  29.             outputText = translations[0].Translations[0].Text;  
  30.             inputLanguage = translations[0].DetectedLanguage.Language;  
  31.         }  
  32.     }  
  33. }  
We are invoking the GetAvailableLanguages method from our service inside the OnInitializedAsync. This OnInitializedAsync is a lifecycle method that will be invoked upon component initialization. This will make sure that the language dropdown will be populated as the page loads.
 
The SelectLanguage method will be set the outputLanguage for the translation. The Translate method will invoke the GetTranslatation method from the service. We will set the outputText and the language detected for the inputLanguage as returned from the service.
 

Add styling for the Translator component

 
Navigate to BlazorTranslator\wwwroot\css\site.css file and put the following style definition inside it.
  1. .translation-box {  
  2.     margin15px 0px;  
  3. }  

Adding Link to Navigation menu

 
The last step is to add the link of our Translator component in the navigation menu. Open BlazorTranslator/Shared/NavMenu.razor file and add the following code into it.
  1. <li class="nav-item px-3">  
  2.     <NavLink class="nav-link" href="translator">  
  3.         <span class="oi oi-list-rich" aria-hidden="true"></span> Translator  
  4.     </NavLink>  
  5. </li>  
Remove the navigation links for Counter and Fetch-data components as they are not required for this application.
 

Execution Demo

 
Press F5 to launch the application. Click on the Translator button on the nav menu in the left. You can perform the multilanguage translation as shown in the image below.
 
 

Summary

 
We have created a Translator Text Cognitive Services resource on Azure. We have used the Translator Text API to create a multilanguage translator using Blazor. This translator supports more than 60 languages for translation. We fetched the list of supported languages for translation from the global API endpoint for Translator Text.
Get the Source code from GitHub and play around to get a better understanding.
 
See Also,


Similar Articles