6 from locale import getpreferredencoding
7 from urllib.request import urlopen, Request
8 from urllib.parse import urlencode
9 from argparse import ArgumentParser
13 sys.stderr.write((msg % args) + '\n')
17 def translate(text, dst_lang, src_lang='auto'):
31 url = 'http://translate.google.com/translate_a/t'
32 data = ('client=t&' + urlencode(dict(text=text)) + '&hl=en&' +
33 urlencode(dict(sl=src_lang)) + '&' +
34 urlencode(dict(tl=dst_lang)) +
35 '&multires=1&otf=2&pc=1&ssel=0&tsel=0&sc=1')
36 headers = { 'User-agent': 'Mozilla/5.0' }
38 req = Request(url=url, data=data.encode('utf-8'),
40 page = urlopen(req).read().decode('utf-8')
41 # attempt to fix invalid json (will break translated text that had ,,+)
42 page = re.sub(',,+', ',', page)
45 result = json.loads(page)
46 except Exception as e:
47 die("Error parsing results: %s", e)
49 return ''.join((c[0] for c in result[0]))
53 parser = ArgumentParser(description='Translate text using '
55 parser.add_argument('--from','-f', dest='from_', metavar='LANG',
57 help='Translate from LANG language '
58 '(e.g. en, de, es, default: auto)')
59 parser.add_argument('--to', '-t', metavar='LANG', default='en',
60 help='Translate to LANG language '
61 '(e.g. en, de, es, default: en)')
62 parser.add_argument('--input-file', '-i', metavar='FILE',
63 help='Get text to translate from FILE instead of stdin')
64 parser.add_argument('--output-file', '-o', metavar='FILE',
65 help='Output translated text to FILE instead of stdout')
66 parser.add_argument('--input-encoding', '-I', metavar='ENC',
67 default='LOCALE,utf-8,iso-8859-15',
68 help='Use ENC caracter encoding to read the input, '
69 'can be a comma separated list of encodings to '
70 'try, LOCALE being a special value for the '
71 'user\'s locale-specified preferred encoding '
72 '(default: LOCALE,utf-8,iso-8859-15)')
73 parser.add_argument('--output-encoding', '-O', metavar='ENC',
75 help='Use ENC caracter encoding to write the output '
78 args = parser.parse_args()
80 args.input = sys.stdin
83 args.input = open(args.input_file)
84 except Exception as e:
85 die("Can't open file %s for reading: %s",
88 args.output = sys.stdout
91 args.output = open(args.output_file, 'w')
92 except Exception as e:
93 die("Can't open file %s for writing: %s",
96 args.input_encoding = args.input_encoding.split(',')
97 if not args.input_encoding:
98 args.input_encoding = ['LOCALE']
99 args.input_encoding = [getpreferredencoding() if e == 'LOCALE' else e
100 for e in args.input_encoding]
102 if args.output_encoding == 'LOCALE':
103 args.output_encoding = getpreferredencoding()
110 text = args.input.buffer.read()
112 for enc in args.input_encoding:
114 text = text.decode(enc)
116 except UnicodeError as e:
119 die("Can't decode input (tried these encodings: %s). Last error: %s",
120 args.input_encoding, err)
122 trans_text = translate(text, args.to, args.from_) + '\n'
124 args.output.buffer.write(trans_text.encode(args.output_encoding))