Command-line language translation

Here is a simple utility created using Python for translating text from various languages into English. It uses the Google AJAX API to do this.

Usage

prashanth@prashanth-desktop:~$ translate bonjour
hello
prashanth@prashanth-desktop:~$ translate guten morgen
Good morning




Code

#!/usr/bin/env python
'''
Translates text into english using Google Translate.
Usage: python translate.py 
        (or)
       echo  | python translate.py

For convenience, make a symlink to this file from /usr/bin/translate.
'''
# derived from : http://code.google.com/p/py-gtranslate/source/browse/trunk/gtrans.py

import sys
import urllib2
import urllib
import simplejson as json

FROM_LANGUAGE = ''
TO_LANGUAGE = 'en'
BASE_URL = 'http://ajax.googleapis.com/ajax/services/language/translate'

def translate(from_language, to_language, text):
    langpair = '%s|%s' % (from_language, to_language)
    params = {'v': '1.0', 'langpair': langpair, 'q': urllib.quote_plus(text)}
    
    params = '%s' % ('&'.join(['%s=%s' % (k,v) for (k,v) in params.items()]))
    
    url = '%s?%s' % (BASE_URL, params)
    resp = json.load(urllib2.urlopen(url))
    try:
        return resp['responseData']['translatedText']
    except:
        return text

def main(text):
    if text:
        print translate(FROM_LANGUAGE, TO_LANGUAGE, text)

    else:
        lines = [l.strip() for l in sys.stdin.readlines()]
        for line in lines:
            if line:
                text = translate(FROM_LANGUAGE, TO_LANGUAGE, line)
                print '[%s]' % line
                print text
            else:
                print

if __name__ == '__main__':
    args = sys.argv[1:]
    text = ' '.join(sys.argv[1:])
    main(text)


No Trackbacks

4 Comments

  1. I tried it using python verion 2.5.2 (ubuntu), but I got an error:

    Traceback (most recent call last):
    File “translate”, line 6, in
    import simplejson as json
    ImportError: No module named simplejson

    I will install the required module.
    Thanks for the script.

    Posted August 20, 2009 at 8:22 am | Permalink
  2. Aaah… Thanks for the info Shantanu :)

    Posted August 20, 2009 at 8:43 am | Permalink
  3. monu

    Nice util Prashanth.
    I think there’s a small typo, you return phrase when excepttion though there’s no phrase vriable.

    Posted August 25, 2009 at 2:11 pm | Permalink
  4. Thanks monu. I fixed it now.

    Posted August 25, 2009 at 2:27 pm | Permalink