Thursday, 6 March 2014

Google Translate In Terminal

I am currently trying to learn french, and just to make life a tad easier, i wrote a wrapper for google translate.

Because when do you not have a terminal handy?



(Psst. I have up a more updated version here)
#!/usr/bin/python
import urllib2
import sys
import argparse
import json
DEST_LANG="fr"
SOURCE_LANG="en"
def pull(phrase, source, dest):
phrase = urllib2.quote(phrase)
try:
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
response = opener.open("http://translate.google.co.uk" + "/translate_a/t?client=webapp&sl=" + source + "&tl=" + dest + "&hl=en&sc=1&q=" + phrase)
except urllib2.HTTPError, err:
print "ERROR [" + err + "] Google says no"
sys.exit(-1)
except:
print "ERROR [UNKNOWN] Google really says no"
sys.exit(-2)
return json.loads(response.read())
def parse(reply):
tran = ""
for s in reply['sentences']:
tran+=s['trans']
return tran
def main():
parser = argparse.ArgumentParser(description='A command line wrapper for Google Translate')
parser.add_argument('text', nargs='+', help='Profanities you would like to translate')
parser.add_argument('-s', default=SOURCE_LANG, metavar="source_lang", help="Language you know")
parser.add_argument('-d', default=DEST_LANG, metavar="dest_lang", help="Language you wish you knew")
parser.add_argument('--switch', '-w', action='store_true', help="Switch the default languages")
parser.add_argument('--log', '-l', metavar="log_file", help="Log to [file]")
args = parser.parse_args()
colour="\033[1;91m" # Red
colour_default="\033[0;39m"
original = ' '.join(args.text)
if (args.switch is False):
colour="\033[1;34m" # Blue
args.s, args.d = args.d, args.s
translation = parse(pull(original, args.d, args.s))
if (args.log != None):
try:
fd = open(args.log, 'a')
except:
print "ERROR [FAILED TO OPEN FILE]"
sys.exit(-3);
fd.write(original + " -> " + translation + "\n")
print colour + translation + colour_default
if __name__ == '__main__':
main()

2 comments:

  1. Simple and elegant :)

    ReplyDelete
  2. Interesting! As I am starting to learn italian (from french), this could come handy. May I suggest a few enhancements to your script?

    1- Use a library that does the http for you instead of using a raw socket. There are many reasons, but it my case, I had to since at work I have to go through a proxy. urllib2 handles that.
    2- You receive you reply in json. Better parse json properly to get the translated phrase.
    3- Try not to catch all the exceptions (the except:). When I tried it the first time, it hanged (because of the proxy issue), and when I did ctrl-C, the script just continued with a bad state from that except instead of stopping.

    Link to my modified version: https://gist.github.com/simark/c5f3f0f173fe9cd5f092

    Bonne chance avec le français!

    ReplyDelete