Popular posts

Pages

Thursday, September 27, 2012

Perl program using HTTP Microsoft Translator API

Code


## LWP for bing translator

#use strict;
use LWP::UserAgent;
use URI::Escape;


$browser = LWP::UserAgent->new();

## 1 Prepare for POST query with your application registration details

$url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
$client_id = "YOUR-CLIENT-ID";
$client_secret = "YOUR-KEY";
$scope = "http://api.microsofttranslator.com";       # fixed
$grant_type = "client_credentials";                  # fixed

## POST request for the 'token'
$response = $browser->post( $url,
    [
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'scope' => $scope,
        'grant_type' => $grant_type
    ],
);

## Token received is in JSON format, but I've treated it as a string
## and parsed it using pattern matching.

my $content = $response->content;

@array = split(/,/,$content);
$var = $array[1];
$var =~ /"(.*)":"(.*)"/;
$token = uri_escape("Bearer " . $2);
print "Token is ", $token, "\n\n";

print "Sending text for translation\n";

## Text to be translated.

$text = uri_escape("This is my life.");

## 2 Prepare the URL for the GET request, with 'to' language and other parameters.

$url2 = "http://api.microsofttranslator.com/V2/Http.svc/Translate?text=" .     $text .
        "&to=" . "de" .
        "&appId=" . $token .
        "&contentType=text/plain";

$resp2 = $browser->get ($url2, 'Authorization' => $token);

## Here you get the translated string with some tags, which you can parse as per your wish
$value = $resp2->content;
print "\nTranslated text is ", $value;

Output


Sending text for translation
Translated text is <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Das ist mein Leben.</string>

Explanation

The above Perl code uses the Microsoft Translator API to convert text from one language to other language. Here is the link for the application http://www.bing.com/translator/.
Microsoft has provided couple of ways to use the API. Here, I've used the HTTP API in Perl, because well, that is what I know :p.

So first, you need to register yourself on Windows Azure Marketplace, then register your application (a simple entry) to get your KEY.
How this works is, every time you want to run your program to use the API, you request for a 'token' as a POST HTTP request. This token is valid for 10 minutes. Within this 10 minutes your program can use this token to make any text translation request.
Once you receive the token, make a GET request using this token and the return you get is a translated text.
The reason that I'm writing this, is because the documentation on MS site is not clear at all. I really liked the google implementation, it was straight forward. But then it became paid. I guess all good things come to an end after all.
You can explore more on the MS site http://msdn.microsoft.com/en-us/library/hh454950.aspx. Hope you find this interesting!