Login

autotranslate po files using microsoft translator

Author:
prabhat246
Posted:
February 8, 2012
Language:
Python
Version:
1.3
Score:
1 (after 1 ratings)

This snippet is inspired by dnordberg 's translation script which used google's translation script. But after google translation is no more free. I put together it to use microsoft translator's python wrapper by openlab

usage

  1. get a bing appID from here and replace it on the top of script

  2. sudo apt-get install translate-toolkit

  3. sudo pip install microsofttranslator

  4. sudo autotranslate.py [pofile] [sourcelangcode] [targetlangcode]

Enjoy!!!

Prabhat Kumar Gupta Python/Django Dev http://www.prabhatgupta.com

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/python
from translate.storage import po
from django.utils import simplejson
import sys, os, re, urllib
from htmlentitydefs import name2codepoint
BINGAPPID='YOURAPPID'
from microsofttranslator import Translator

def ms_get_translation(sl,tl,x):
    translator = Translator(BINGAPPID)
    return translator.translate(x, tl, sl)

def translate_po(file, sl, tl):
    openfile = po.pofile(open(file))
    nb_elem = len(openfile.units)
    moves = 1
    cur_elem = 0
    for unit in  openfile.units:
        # report progress
        cur_elem += 1
        s = "\r%f %% - (%d msg processed out of %d) " \
            % (100 * float(cur_elem) / float(nb_elem), cur_elem, nb_elem)
        sys.stderr.write(s)
        if not unit.isheader():
            if len(unit.msgid):
                if unit.msgstr==[u'""']:
                    moves += 1
                    unit.msgstr = ['"%s"' % ms_get_translation(sl, tl, x) for x in unit.msgid ]
        if not bool(moves % 50):
            print "Saving file..."
            openfile.save()
    openfile.save()

if __name__ == "__main__":

    if len(sys.argv) < 4 or \
       not os.path.exists(sys.argv[1]):
        sys.stderr.write("""
usage example: python autotranslate.py <lang.po> en fr
""")
        sys.exit(1)
    else:
        in_pofile = os.path.abspath(sys.argv[1])
        from_lang = sys.argv[2]
        to_lang = sys.argv[3]
        print('Translating %s to %s' %(from_lang,  to_lang))
        translate_po(in_pofile, from_lang, to_lang)
        print('Translation done')

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.