Wednesday, March 16, 2011

Google Translate

After having some fun building a Factor wrapper for the Google Charts API, I decided to implement the Google Translate API. We will be using version 2, which returns JSON over HTTP.

The Google Translate API requires the use of an API key, which you can get from the Google APIs console.

USING: assocs google http.client io json.reader kernel locals
namespaces sequences urls ;


First, we define a global symbol to store the API key:

SYMBOL: google-api-key

Next, we make a simple word to create translation URLs:

:: translate-url ( text source target -- url )
        google-api-key get-global "key" set-query-param
        source "source" set-query-param
        target "target" set-query-param
        text "q" set-query-param ;

We can translate a string of text from a source language into a target language:

: translate ( text source target -- text' )
    translate-url http-get nip json>
    { "data" "translations" } [ swap at ] each
    first "translatedText" swap at ;

Once you've set your API key, you can try it out:

( scratchpad ) "Hello world!" "en" "es" translate print
¡Hola, mundo!

Google Translate supports many languages, which makes it pretty useful.

Translation Party

If you haven't seen the Translation Party website, you should check it out. Basically, it translates a phrase from English into Japanese and back again until it reaches a stable equilibrium. Some of the results are pretty funny. We are going to build this in Factor, but supporting any source and target language.

:: translation-party ( text source target -- )
    text dup print [
        dup source target translate dup print
        target source translate dup print
        swap dupd = not
    ] loop drop ;

For example, we can translate the phrase "Type anything here and you'll get funny" and you get:

( scratchpad ) "Type anything here and you'll get funny"
               "en" "ja" translation-party
Type anything here and you'll get funny
Here you enter anything gets interesting
Here is something interesting input
Something interesting is entered here
Are entered here is something interesting
Has been entered here is something interesting
What is interesting is entered here
Interestingly, that is entered here
Interestingly, that is entered here

The code for this is on my Github.

No comments: