Popular posts

Pages

Showing posts with label lwp. Show all posts
Showing posts with label lwp. Show all posts

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!

Saturday, April 9, 2011

perl script to use google language translate API

I created this script which translated text from one language to another using yahoo's http://babelfish.yahoo.com/ services. But its not the one which i'm going to talk about. That is because in the yahoo version i used perl's LWP module to do a post query on the yahoo server and get back the http response, much like what we see on a browser, and got the translated text using pattern matching operations. That is one crude way of getting things done, but it works!

Now this does the same job but using google services (translate.google.com) and the respective APIs. Its a more sophisticated and efficient way of achieve the same result. Google has exposed the API and the methods for doing this job. You can call them from applications such as - your software, your mobile app, your website or a small script (like tihs one), etc. Mind you, it is illegal to use it for commercial purposes.

For this translate API, you've to generate an activation key (tied to your google account). 
First section is the creation of a LWP::UserAgent object. Then for sanity, convert the text to webformat. Then I've created the url with editable parameters as variables. The text to be converted is $str and needs to be given as command line argument. I like German so its my language of choice for converted text. The response object is created by the get function on UA object. The 'content' method is used on response object for the output, whereas the error state and message are captured in 'is_success' and 'status_line' methods of the response obj. Again, for the desired line in the http response content we need to use pattern matching as shown.

The idea is, how the google (or any) api can be leveraged with perl's lwp module to do some fun programming or something more useful which can solve real problems at your work/school/college. If you've something to share, do comment.
Here's the code:

## google translate API

# https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&q=hello%20world&source=en&target=de

use Strict;
use LWP::UserAgent;
use URI::Escape;

if ($ARGV[0] eq "") {
print "Usage: perl lwp12 \"text to be converted\""; die; }
$ua = LWP::UserAgent->new();

$str = uri_escape ($ARGV[0]);
$tolang = "de";

$url = "https://www.googleapis.com/language/translat/v2?key=<yourPersonalKeyHere>&q=" 
. $str 
. "&source=en&target="
. $tolang;

$resp = $ua->get ($url);

if ($resp->is_success) {
$newstr = $resp->content;
$newstr =~ /Text":\s"(.*)"\n/;
print "Text in $tolang:\n$1\n"; }

else { print "Program failed with message: ", $resp->status_line;}
# END


Here is how it runs:

>perl lwp12googletranslate.pl "My first program."
Text in de:
Mein erstes Programm.


Output while error handling:

>perl lwp12googletranslate.pl "my first wife"
Program failed with message: 404 Not Found