Debian Codegraph @

util/sync_translations.py

raw
1 #!/usr/bin/env python3
2 from io import BytesIO
3 import os
4 import re
5 import sys
6
7 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
8 sys.path.insert(0, root)
9
10 from DisplayCAL import lazydict
11 from DisplayCAL.util_list import natsort
12 from DisplayCAL.util_os import listdir_re
13
14
15 USE_INLINE = False
16
17
18 def quote(obj):
19 if isinstance(obj, str):
20 return '"%s"' % obj.replace("\\", "\\\\").replace('"', '\\"').replace(
21 "\n", "\\n"
22 ).replace("\t", "\\t")
23 else:
24 return repr(obj)
25
26
27 def langmerge(infilename1, infilename2, outfilename):
28 print("Syncing", infilename1, "to", infilename2)
29 dictin1 = lazydict.LazyDictYAMLUltraLite(infilename1)
30 dictin1.load()
31 dictin2 = lazydict.LazyDictYAMLUltraLite(infilename2)
32 dictin2.load()
33
34 added = []
35 same = []
36 for key in dictin2:
37 value = dictin2[key]
38 if key not in dictin1:
39 dictin1[key] = value
40 added.append(key.encode("UTF-8"))
41 if "*" + key not in dictin1:
42 print("Added: '%s' '%s'" % (key, value))
43 # elif dictin1[key] == value and not key.startswith("*") and not key.startswith("!") and value.strip():
44 # same.append(key.encode("UTF-8"))
45 # print("Same: '%s' '%s'" % (key, value))
46 elif key != "*":
47 # Check format chars
48 format_chars = "dixXfFeEgGcs%"
49 profile_name_placeholder_chars = "aAbBHIjmMpSUwWyY"
50 for c in format_chars + profile_name_placeholder_chars:
51 a = dictin1[key].count("%" + c)
52 b = value.count("%" + c)
53 if a != b:
54 print(
55 key,
56 "ERROR: Format character count for %%%s is wrong:" % c,
57 a,
58 "(expected %i)" % b,
59 )
60 if key.startswith("info."):
61 # Check tag formatting and correct Google translator messing
62 # with tags
63 original = dictin1[key]
64 # Clean up whitespace
65 # E.g. ' <font> ' -> ' <font>'
66 wscleaned = re.sub(r"(^|\s+)(<[^/> ]+[^>]*>)\s+", r"\1\2", original)
67 # E.g. 'x<font> ' -> 'x <font>'
68 wscleaned = re.sub(r"([^>])(<[^/> ]+[^>]*>)(\s+)", r"\1\3\2", wscleaned)
69 # E.g. ': </font>' -> ':</font> '
70 wscleaned = re.sub(r"([:\-])(\s+)(</[^>]*>)\s*", r"\1\3\2", wscleaned)
71 # E.g. ', </font>' -> '</font>, '
72 wscleaned = re.sub(r"([,;.])(\s+)(</[^>]*>)\s*", r"\3\1\2", wscleaned)
73 # E.g. ' </font> ' -> '</font> '
74 wscleaned = re.sub(r"\s+(</[^>]*>\s+)", r"\1", wscleaned)
75 # E.g. ' </font>x' -> '</font> x'
76 wscleaned = re.sub(
77 r"(\s+)(</[^>]*>)([^<,;.:\- \n])", r"\2\1\3", wscleaned
78 )
79 if original != wscleaned:
80 print(key, "INFO: Corrected whitespace.")
81 # Find all tags
82 tags = re.findall(
83 r"<(\s*[^/> ]+)([^>]*)>([^<]*)(<\s*/\s*\1>)", wscleaned
84 )
85 replaced = wscleaned
86 cleaned = wscleaned
87 tagcleaned = wscleaned
88 for tagname, attrs, contents, end in tags:
89 tag = "<%s%s>%s%s" % (tagname, attrs, contents, end)
90 replaced = replaced.replace(tag, contents)
91 # <font weight='bold'></font> is the only supported tag
92 cleaned = cleaned.replace(
93 tag, "<font weight='bold'>%s</font>" % contents.strip()
94 )
95 if contents != contents.strip():
96 print(
97 key,
98 "INFO: Removed surrounding whitespace from tag contents %s"
99 % tag,
100 )
101 tagcleaned = cleaned.replace(
102 tag, "<font weight='bold'>%s</font>" % contents
103 )
104 stripped = re.sub(r"<[^>]*>", "", replaced)
105 stripped = stripped.replace("<", "").replace(">", "")
106 if replaced != stripped:
107 print(key, "ERROR: Invalid markup")
108 if wscleaned != tagcleaned:
109 print(key, "INFO: Corrected tag formatting.")
110 if original != cleaned:
111 dictin1[key] = cleaned
112
113 merged = dict()
114 merged["*"] = dictin1["*"] = dictin2["*"]
115
116 for key in natsort(dictin2.keys(), False):
117 merged[key] = dictin1[key]
118
119 for key in natsort(dictin1.keys(), False):
120 if key not in dictin2 and not key.startswith("*") and dictin1[key]:
121 if "ORPHANED KEY-VALUE PAIRS" not in merged:
122 merged[
123 "ORPHANED KEY-VALUE PAIRS"
124 ] = "Note to translators: Key-value pairs below this point are no longer used. You may consider removing them."
125 merged[key] = dictin1[key]
126 print("Orphan: '%s' '%s'" % (key, dictin1[key]))
127
128 outstream = BytesIO()
129 for key in merged:
130 value = merged[key]
131 if not USE_INLINE or b"\n" in value:
132 outstream.write(b'"%s": |-\n' % key.encode("UTF-8"))
133 for line in value.split("\n"):
134 # Do not use splitlines, returns empty list for empty string
135 outstream.write(b" %s\n" % line.encode("UTF-8"))
136 else:
137 # Inline
138 outstream.write(
139 b'"%s": "%s"\n'
140 % (key.encode("UTF-8"), lazydict.escape(value).encode("UTF-8"))
141 )
142 outstream.seek(0)
143 formatted = outstream.read()
144 for key in added:
145 formatted = formatted.replace(b'"%s":' % key, b'"*%s":' % key)
146 for key in same:
147 formatted = formatted.replace(b'"%s":' % key, b'"*%s":' % key)
148 with open(dictin1.path, "rb") as infile:
149 if infile.read() == formatted:
150 print("no change")
151 return
152 print("writing", outfilename)
153 with open(outfilename, "wb") as outfile:
154 outfile.write(formatted)
155
156
157 if __name__ == "__main__":
158 if "-h" in sys.argv[1:] or "--help" in sys.argv[1:]:
159 print("Usage: %s" % os.path.basename(sys.argv[0]))
160 print("Synchronizes translations to en.yaml")
161 else:
162 for langfile in listdir_re(
163 os.path.join(root, "DisplayCAL", "lang"), r"^\w+\.yaml$"
164 ):
165 if langfile != "template.yaml":
166 langmerge(
167 os.path.join("lang", langfile),
168 os.path.join("lang", "en.yaml"),
169 os.path.join(root, "DisplayCAL", "lang", langfile),
170 )
171 print("")