Home » Microsoft Cognitive Services – Translation API

Microsoft Cognitive Services – Translation API

If you want to programmatically translate text from one language to another, then the Translation service (translation api) is the right one for you. The Microsoft Translation Service just requires an authentication and then you can easily translate text from one language to another. It sounds simple…and it is simple! In this blog post, I’ll quickly describe how to create the translation service and how to use it with C#, Powershell and Node.js.

Create the translation service in Azure

The translation service is part of the cognitive services and can therefore be found as cognitive service in the Azure portal:

The creation of the service just takes a few seconds. After the creation, we can check the service and see, that it is globally deployed and it also shows us the endpoint url. The keys can be accessed via the keys link in menu. Navigate to it and copy one of the keys that are shown there. Now we are ready to implement a simple C# application, that reads text from the console and translates it to another language.

Translate text using C#, dotnet core and Translation API

This time, I’ll build the application using dotnet core and the command line tools. So no Visual Studio 2017, just Visual Studio code and the command line (but the code would by sure also work in a .net 4.x Console Application in VS2017):

mkdir TranslationApp # create a directory for the solution
cd TranslationApp
dotnet new console   # create a new dotnet core console application
dotnet restore       # restore dotnet dependencies and tools
dotnet build         # build the application
code Program.cs      # edit the file in Visual Studio Code

Copy and paste the following C# console sample to the Program.cs and replace the APIKEY with the one that you got from the Azure portal:

Program.cs

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace TranslationService
{
    class Program
    {
        static readonly string APIKEY = "APIKEY";
        static readonly string TRANSLATETO = "de";
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a text to translate:");
            var input = Console.ReadLine();
            
            Task.Run(async () =>
            {
                var accessToken = await GetAuthenticationToken(APIKEY);
                var output = await Translate(input, TRANSLATETO, accessToken);
                Console.WriteLine(output);
            }).Wait();

            
            Console.WriteLine("Press key to exit!");
            Console.ReadKey();
        }

        static async Task<string> Translate(string textToTranslate, string language, string accessToken)
        {
            string url = "http://api.microsofttranslator.com/v2/Http.svc/Translate";
            string query = $"?text={System.Net.WebUtility.UrlEncode(textToTranslate)}&to={language}&contentType=text/plain";
            
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                var response = await client.GetAsync(url + query);
                var result = await response.Content.ReadAsStringAsync();
                
                if (!response.IsSuccessStatusCode)
                    return "ERROR: " + result;
                
                var translatedText = XElement.Parse(result).Value;
                return translatedText;
            }
        }

        static async Task<string> GetAuthenticationToken(string key)
        {
            string endpoint = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
                var response = await client.PostAsync(endpoint, null);
                var token = await response.Content.ReadAsStringAsync();
                return token;
            }
        }
    }
}

Save it and then we can run the application via:

dotnet run

Translate text via Powershell

If we want to use the translation API in the Powershell, then it’s as easy as building the C# application. The Powershell code for calling the translation service is a bit different, but not much:

function GetAuthenticationHeader([string] $authKey) {
    $endpoint = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key=$authKey"
    $token = Invoke-RestMethod -Uri $url -Method Post 
    $auth = "Bearer " + $token
    $header = @{ Authorization = $auth }
    return $header
}

function Translate([string] $textToTranslate, [string] $translateToLanguage, $authHeader) {
    $translationUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate"
    $query = "?text=" + [System.Web.HttpUtility]::UrlEncode($textToTranslate)
    $query = $query + "&to=$translateToLanguage&contentType=text/plain"
    $uri = $translationUrl + $query

    $ret = Invoke-RestMethod -Uri $uri -Method Get -Headers $authHeader 
    return $ret.string.'#text'
}


$key = "APIKEY"      # the subscription key

Write-Host "Please enter a text that should be translated:"
$input = Read-Host

$authHeader = GetAuthenticationHeader $key     # authenticate
$output = Translate $input "de" $authHeader    # translate the text

Write-Host $output

Translate text via JavaScript and Node.js

Using the translation service with JavaScript and Node.js is the easiest one, because there is a package available that can be used for the translation. The usage of the package is described at npm (https://www.npmjs.com/package/mstranslator) and also at GitHub (https://github.com/nanek/mstranslator). I just took the code from the sample and tried it on my own. My code looks as follows:

npm install mstranslator
node

and the javascript:

var MsTranslator = require('mstranslator');
var client = new MsTranslator({ api_key: "APIKEY" }, true);
 
var params = {
  text: 'This is just a test! CodeHollow rocks"'
  , to: 'de'
};
 
client.translate(params, function(err, data) {
  console.log(data);
});

Additional information

Microsoft Translator API overview: https://www.microsoft.com/cognitive-services/en-us/translator-api
Microsoft Translator: https://msdn.microsoft.com/en-us/library/dd576287.aspx
Microsoft Translator – Translate REST API: https://msdn.microsoft.com/en-us/library/ff512421.aspx
Visual Studio Code – command line options: https://code.visualstudio.com/docs/editor/command-line

Leave a Reply

Your email address will not be published. Required fields are marked *