# -------------------------------------------#
# Google translate interface                 #
# -------------------------------------------#
# Written up by Alexander Miles              #
# Available at http://www.alexander-miles.com#
# Last updated: November 30th, 2009          #
# -------------------------------------------#
# Usage: Import this script as a module,     #
# e.g. "from translate import *" and pass    #
# the translate function a string, a from    #
# language and a to language.                #
# -------------------------------------------#

import urllib, urllib2, re

langCode={ "arabic":"ar", "bulgarian":"bg", "chinese":"zh-CN", "croatian":"hr", 
           "czech":"cs", "danish":"da", "dutch":"nl", "english":"en", "finnish":"fi", 
           "french":"fr", "german":"de", "greek":"el", "hindi":"hi", "italian":"it", 
           "japanese":"ja", "korean":"ko", "norwegian":"no", "polish":"pl", 
           "portugese":"pt", "romanian":"ro", "russian":"ru", "spanish":"es", 
           "swedish":"sv" }

class MyOpener(urllib.FancyURLopener):
    version = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.5) Gecko/20091109 Ubuntu/9.10 (karmic) Firefox/3.5.5'

def setUserAgent(userAgent):
    '''
    Takes a user-agent string and sets that as the effective agent string.

    This function changes the user agent utilized by the translate function.
    Google translate rejects requests from clients with blank user agent strings.
    ''' 
    urllib.FancyURLopener.version = userAgent
    pass

def translate(text_in, fromLang="German", toLang="English"):
    '''
    Takes a string, a first language, and a second language, and returns 
    the string translated from the first language into the second language.
    This is done by utilizing Google's translation service. 

    Ex:
    translate('wie gehts?', 'German', 'English') -> 'how are you?' 

    Valid languages at present are (case insensitive):
    arabic, bulgarian, chinese, croatian, czech, danish, dutch, english, 
    finnish, french, german, greek, hindi, italian, japanese, korean, 
    norwegian, polish, portugese, romanian, russian, spanish, swedish

    These can be modified by altering the content of the langCode variable.
    '''
    try:
        params = urllib.urlencode(dict(text=text_in, sl=langCode[fromLang.lower()], tl=langCode[toLang.lower()]))
    except KeyError, error:
        print "Google Traslation API does not support %s" %(error.args[0])
        return
    urlopen = MyOpener().open
    page = urlopen("http://translate.google.com/", params)
    content = page.read()
    page.close()
    try:
        return re.findall('name=gtrans value="(.+?)">', content)[0]
    except IndexError:
        print "Google translate appears to have changed again."
