File: blend-doc-translate

package info (click to toggle)
blends 0.7.11
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,260 kB
  • sloc: xml: 4,904; python: 1,226; sh: 705; makefile: 290
file content (96 lines) | stat: -rwxr-xr-x 3,225 bytes parent folder | download | duplicates (2)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#! /usr/bin/python3

"""
This script translates the documentation.
<remark> elements are stripped off when translating.

sys.argv[1] must be a supported (non EN) language, which entails using
doc/{sys.argv[1]}.po and the subdirectory {sys.argv[1]}/
"""

import gettext
_ = gettext.gettext

import sys, os, re
sys.path.append(os.path.dirname(__file__))

from utils import normalizedText

import xml.etree.ElementTree as ET
from subprocess import call

def usage():
    print(f"Usage: {sys.argv[0]} <language-code>")
    sys.exit(1)
    return # never reached

def translate(source, target = "/tmp/example.xml", docdir = "doc", lang = "fr"):
    """
    Translates an XMLDOC file.
    <remark> elements are stripped off

    Parameters:
    -----------

    - source (str) the source XML file
    - target (str) the file to create
    - docdir (str) the directory which contains MO files and translated subdirs
    - lang (str) the language code
    """
    tree = ET.parse(source)
    root = tree.getroot()
    accessors = []
    with open(os.path.join(docdir, lang + ".po")) as pofile:
        pattern = re.compile("^#\\. en/" + source.split("/")[-1] + " : (.*)")
        for l in pofile.readlines():
            m = pattern.match(l.strip())
            if m:
                et = eval('.'.join(m.group(1).split('.')[:-1]))
                text_tail = m.group(1).split('.')[-1]# either '.text' or '.tail'
                t = "".join(normalizedText(eval(m.group(1)), escape = False))
                t = t.replace('\\"', '"')
                setattr(et, text_tail, _(t))
    for parent_of_remark in root.findall(".//remark/.."):
        for remark in parent_of_remark.findall("./remark"):
            parent_of_remark.remove(remark)
            print("+----------- Removing a remark: ---------------")
            for l in remark.text.split("\n"):
                print("|", l)
            print("+----------------------------------------------")
    with open(target, "w") as outfile:
        tree.write(outfile, encoding='unicode')
    call(['/usr/bin/xmllint', '--format', target,
          "--output", target + ".tmp",
          "--encode", "UTF-8"])
    call(['mv', target + ".tmp", target])
    return
    
if __name__ == "__main__":
    if len(sys.argv) < 2:
        usage()
    l = sys.argv[1].lower()
    print(f"translating --> {l}")
    docdir = None
    pofile = None
    for root, dirs, files in os.walk("."):
        if f"{l}.po" in files:
            pofile = os.path.join(root, f"{l}.po")
            docdir = root
    if not pofile:
        raise Exception(f"ERROR: The path to {l}.po was not found.")
    # l, docdir and pofile are defined
    os.environ['LANG'] = l
    gettext.bindtextdomain("blends", localedir=docdir)
    gettext.textdomain('blends')
    
    for root, dirs, files in os.walk(os.path.join(docdir, "en")):
        for f in files:
            if f.endswith(".xml"):
                filename = os.path.join(root, f)
                target = os.path.join(docdir, l, f)
                print(f"Translating: {filename} --> {target}")
                translate(
                    filename,
                    target = target,
                    docdir = docdir, lang = l,
                )