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!

3 comments:

  1. 1> the final token to be sent is "Bearer ACTUAL_TOKEN". There is a space there, which you need to uri_escape. You
    2> Yes on the MS website there is big confusion if appId is required or not and the 'Authorization' header is mandatory or not. I tried all combinations, and found only one working, which i've pasted here.
    3> Have you tried printing your token before sending? Since other parameters are also received from first POST query, such as expire time etc.

    Update your code with both the items and test result. The second GET query is pretty straight forward, and yes the header authorization is required. But again the MS translate did not respond 100% successfully each time. For me too, many times it didnt work. I even had to create and register a new AppId on the MS site, to get new values. Try that option too.

    ReplyDelete
  2. hi i am getting this following error.

    Translated text is Can't connect to api.datamarket.azure.com:443

    No connection could be made because the target machine actively refused it. at C
    :/strawberry/perl/vendor/lib/LWP/Protocol/http.pm line 51.

    thanks & regards,

    ReplyDelete
    Replies
    1. Hi Kishore,

      I just re-ran my code from sep-2012, and got the proper response. It seems your code cant connect to the azure site at all.

      Have you verified that these variables in your code are initialized properly?

      # STATIC URL
      $url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";

      # YOUR PERSONAL 'app id', eg: mine is ad_app2
      $client_id = "ad_app2";

      # your app key, alpha-numeric
      $client_secret = "YOUR-KEY";

      # STATIC
      $scope = "http://api.microsofttranslator.com";

      # STATIC
      $grant_type = "client_credentials";

      # Then you need to fire the request
      $response = $browser->post( $url,
      [
      'client_id' => $client_id,
      'client_secret' => $client_secret,
      'scope' => $scope,
      'grant_type' => $grant_type
      ],
      );

      Let me know how it goes, or copy your code portion here. Btw mine is activestate perl (if it makes any difference)

      Regards

      Delete