Jul
30
2009

Getting Groovy with Google Language Translation APIs

One of the most requested features for groovyblogs is the ability to filter posts by language. Well I’ve been working hard to get this implemented. I wrote ages ago how the first version used the Textcat classification library to do some of the heavy lifting, which worked fine, but only had a small set of languages.

I was mentioning this to my buddy Sven and he suggested I checkout the Google translation AJAX APIs that are now available – and even sent me a code snippet to get me going.

Turns out that accessing these services from Grails is a total snack. Here’s a complete worked example of how you can integrate both language detection and translation in a tiny amount of Groovy code (feel free to cut and paste into your local groovyConsole and take for a spin):


def text =  'das ist ein test'.encodeAsURL()

def detect = 'http://www.google.com/uds/GlangDetect?v=1.0&q=' + text
def response = grails.converters.JSON.parse(detect.toURL().text)

println "Lang is: ${response.responseData.language}"

def targetLang = "en"
def translate = "http://www.google.com/uds/Gtranslate?v=1.0&q=" + text +
    "&langpair=${response.responseData.language}%7C${targetLang}"
def response2 = grails.converters.JSON.parse(translate.toURL().text)

println "Translation is: ${response2.responseData.translatedText}"

Which gives you the expected output of:

Lang is: de
Translation is: This is a test

Cute stuff! Language detection and translation in just a few lines! Coming soon to a groovyblogs near you…

About the Author: Glen Smith

7 Comments + Add Comment

  • That is easy and powerful.

  • Inspired by this nice script, I’ve posted a variation on the Groovy web console.

    It’s using URLEncoder and a nice trick for parsing JSON as Groovy maps ;-)

  • Dude that is so cool! Love the Groovy web console!

  • Hrm…a Grails plugin that would do this (and cache the results) as a fall-back for i18n would be pretty cool. It’d take the place of the fall-back “default” messaging.

  • Yeah comon Glen where is the Grails plugin? ;-)

  • Hey Glen. Have just been looking at the Lispparser
    http://groovyconsole.appspot.com/view.groovy?id=22
    Went out and tracked down his (uehaj’s) blog & Twitter id:
    http://d.hatena.ne.jp/uehaj/
    http://twitter.com/uehaj
    Needed to translate it.
    So I used the Babelfish Firefox plugin
    Seems to call into Google translation API’s too.
    Seems like Yahoo has some sort of translation service too that Babelfish can call
    He also posted on Slideshare BTW:
    http://www.slideshare.net/uehaj

  • Now if only Babelfish could translate Flash ! Slideshare translation doesn’t work

Leave a comment

Glen Smith

About Glen

Co-author Grails in Action