4 USAGE: translations-status.py BUILDSCRIPT-DIR LOCALEDIR
6 This script must be run from Documentation/
8 Reads template files translations.template.html.in
9 and for each LANG in LANGUAGES LANG/translations.template.html.in
11 Writes translations.html.in and for each LANG in LANGUAGES
12 translations.LANG.html.in
23 sys.stderr.write (str + '\n')
25 progress ("translations-status.py")
27 buildscript_dir = sys.argv[1]
28 localedir = sys.argv[2]
32 sys.path.append (buildscript_dir)
35 # load gettext messages catalogs
37 for l in langdefs.LANGUAGES:
38 if l.enabled and l.code != 'en':
39 translation[l.code] = gettext.translation('lilypond-doc', localedir, [l.code]).gettext
41 def read_pipe (command):
42 child = subprocess.Popen (command,
43 stdout = subprocess.PIPE,
44 stderr = subprocess.PIPE,
46 (output, error) = child.communicate ()
47 code = str (child.wait ())
48 if not child.stdout or child.stdout.close ():
49 print "pipe failed: %(command)s" % locals ()
51 error = code + ' ' + error
52 return (output, error)
54 comments_re = re.compile (r'^@ignore\n(.|\n)*?\n@end ignore$|@c .*?$', re.M)
55 space_re = re.compile (r'\s+', re.M)
56 lilypond_re = re.compile (r'@lilypond({.*?}|(.|\n)*?\n@end lilypond$)', re.M)
57 node_re = re.compile ('^@node .*?$', re.M)
58 title_re = re.compile ('^@(top|chapter|(?:sub){0,2}section|(?:unnumbered|appendix)(?:(?:sub){0,2}sec)?) (.*?)$', re.M)
59 include_re = re.compile ('^@include (.*?)$', re.M)
61 committish_re = re.compile ('GIT [Cc]ommittish: ([a-f0-9]+)')
62 translators_re = re.compile (r'^@c\s+Translators\s*:\s*(.*?)$', re.M | re.I)
63 checkers_re = re.compile (r'^@c\s+Translation\s*checkers\s*:\s*(.*?)$', re.M | re.I)
64 status_re = re.compile (r'^@c\s+Translation\s*status\s*:\s*(.*?)$', re.M | re.I)
65 post_gdp_re = re.compile ('post.GDP', re.I)
66 untranslated_node_str = 'UNTRANSLATED NODE: IGNORE ME'
67 skeleton_str = '-- SKELETON FILE --'
69 diff_cmd = 'git diff --no-color %(committish)s HEAD -- %(original)s | cat'
72 'not translated': {'color':'d0f0f8', 'short':_doc ('no'), 'long':_doc ('not translated')},
73 'partially translated': {'color':'dfef77', 'short':_doc ('partially (%(p)d %%)'),
74 'long':_doc ('partially translated (%(p)d %%)')},
75 'fully translated': {'color':'1fff1f', 'short':_doc ('yes'), 'long': _doc ('translated')},
76 'up to date': {'short':_doc ('yes'), 'long':_doc ('up to date')},
77 'outdated': {'short':_doc ('partially (%(p)d %%)'), 'long':_doc ('partially up-to-date (%(p)d %%)')},
78 'N/A': {'short':_doc ('N/A'), 'long':'', 'color':'d587ff' },
79 'pre-GDP':_doc ('pre-GDP'),
80 'post-GDP':_doc ('post-GDP')
84 # (Unumbered/Numbered/Lettered, level)
86 'unnumbered': ('u', 1),
87 'unnumberedsec': ('u', 2),
88 'unnumberedsubsec': ('u', 3),
91 'subsection': ('n', 3),
95 appendix_number_trans = string.maketrans ('@ABCDEFGHIJKLMNOPQRSTUVWXY',
96 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
98 class SectionNumber (object):
100 self.__data = [[0,'u']]
102 def __increase_last_index (self):
103 type = self.__data[-1][1]
105 self.__data[-1][0] = self.__data[-1][0].translate (appendix_number_trans)
107 self.__data[-1][0] += 1
110 if self.__data[-1][1] == 'u':
112 return '.'.join ([str (i[0]) for i in self.__data if i[1] != 'u']) + ' '
114 def increase (self, (type, level)):
116 self.__data = [[0,'u']]
117 while level + 1 < len (self.__data):
119 if level + 1 > len (self.__data):
120 self.__data.append ([0, type])
122 self.__data[-1][0] = '@'
123 if type == self.__data[-1][1]:
124 self.__increase_last_index ()
126 self.__data[-1] = ([0, type])
128 self.__data[-1][0] = 'A'
130 self.__data[-1][0] = 1
131 return self.format ()
134 def percentage_color (percent):
137 c = [hex (int (3 * p * b + (1 - 3 * p) * a))[2:] for (a, b) in [(0xff, 0xff), (0x5c, 0xa6), (0x5c, 0x4c)]]
139 c = [hex (int ((3 * p - 1) * b + (2 - 3 * p) * a))[2:] for (a, b) in [(0xff, 0xff), (0xa6, 0xff), (0x4c, 0x3d)]]
141 c = [hex (int ((3 * p - 2) * b + 3 * (1 - p) * a))[2:] for (a, b) in [(0xff, 0x1f), (0xff, 0xff), (0x3d, 0x1f)]]
144 def tely_word_count (tely_doc):
146 Calculate word count of a Texinfo document node by node.
148 Take string tely_doc as an argument.
149 Return a list of integers.
151 Texinfo comments and @lilypond blocks are not included in word counts.
153 tely_doc = comments_re.sub ('', tely_doc)
154 tely_doc = lilypond_re.sub ('', tely_doc)
155 nodes = node_re.split (tely_doc)
156 return [len (space_re.split (n)) for n in nodes]
159 class TelyDocument (object):
160 def __init__ (self, filename):
161 self.filename = filename
162 self.contents = open (filename).read ()
164 ## record title and sectionning level of first Texinfo section
165 m = title_re.search (self.contents)
167 self.title = m.group (2)
168 self.level = texi_level [m.group (1)]
170 self.title = 'Untitled'
171 self.level = ('u', 1)
173 included_files = [os.path.join (os.path.dirname (filename), t) for t in include_re.findall (self.contents)]
174 self.included_files = [p for p in included_files if os.path.exists (p)]
176 def print_title (self, section_number):
177 return section_number.increase (self.level) + self.title
180 class TranslatedTelyDocument (TelyDocument):
181 def __init__ (self, filename, masterdocument, parent_translation=None):
182 TelyDocument.__init__ (self, filename)
184 self.masterdocument = masterdocument
186 ## record authoring information
187 m = translators_re.search (self.contents)
189 self.translators = [n.strip () for n in m.group (1).split (',')]
191 self.translators = parent_translation.translators
192 m = checkers_re.search (self.contents)
194 self.checkers = [n.strip () for n in m.group (1).split (',')]
195 elif isinstance (parent_translation, TranslatedTelyDocument):
196 self.checkers = parent_translation.checkers
200 ## check whether translation is pre- or post-GDP
201 m = status_re.search (self.contents)
203 self.post_gdp = bool (post_gdp_re.search (m.group (1)))
205 self.post_gdp = False
207 ## record which parts (nodes) of the file are actually translated
208 self.partially_translated = not skeleton_str in self.contents
209 nodes = node_re.split (self.contents)
210 self.translated_nodes = [not untranslated_node_str in n for n in nodes]
212 ## calculate translation percentage
213 master_total_word_count = sum (masterdocument.word_count)
214 translation_word_count = sum ([masterdocument.word_count[k] * self.translated_nodes[k]
215 for k in range (min (len (masterdocument.word_count), len (self.translated_nodes)))])
216 self.translation_percentage = 100 * translation_word_count / master_total_word_count
218 ## calculate how much the file is outdated
219 m = committish_re.search (self.contents)
221 sys.stderr.write ('error: ' + filename + \
222 ": no 'GIT committish: <hash>' found.\nPlease check " + \
223 'the whole file against the original in English, then ' + \
224 'fill in HEAD committish in the header.\n')
226 (diff_string, error) = read_pipe (diff_cmd % {'committish':m.group (1), 'original':masterdocument.filename})
228 sys.stderr.write ('warning: %s: %s' % (self.filename, error))
229 self.uptodate_percentage = None
231 diff = diff_string.splitlines ()
232 insertions = sum ([len (l) - 1 for l in diff if l.startswith ('+') and not l.startswith ('+++')])
233 deletions = sum ([len (l) - 1 for l in diff if l.startswith ('-') and not l.startswith ('---')])
234 outdateness_percentage = 50.0 * (deletions + insertions) / (masterdocument.size + 0.5 * (deletions - insertions))
235 self.uptodate_percentage = 100 - int (outdateness_percentage)
236 if self.uptodate_percentage > 100:
238 progress ("%s: strange uptodateness percentage %d %%, setting to %d %%" \
239 % (self.filename, self.uptodate_percentage, alternative))
240 self.uptodate_percentage = alternative
241 elif self.uptodate_percentage < 1:
243 progress ("%s: strange uptodateness percentage %d %%, setting to %d %%" \
244 % (self.filename, self.uptodate_percentage, alternative))
245 self.uptodate_percentage = alternative
247 def completeness (self, formats=['long']):
248 if isinstance (formats, str):
250 p = self.translation_percentage
252 status = 'not translated'
254 status = 'fully translated'
256 status = 'partially translated'
257 return dict ([(f, format_table[status][f] % locals()) for f in formats])
259 def uptodateness (self, formats=['long']):
260 if isinstance (formats, str):
262 p = self.uptodate_percentage
266 status = 'up to date'
271 if f == 'color' and p != None:
272 l['color'] = percentage_color (p)
274 l[f] = format_table[status][f] % locals ()
277 def gdp_status (self, translation=lambda s: s):
279 return translation (format-table['post-GDP'])
281 return translation (format-table['pre-GDP'])
283 def short_html_status (self):
285 if self.partially_translated:
286 s += '<br>\n '.join (self.translators) + '<br>\n'
288 s += ' <small>' + '<br>\n '.join (self.checkers) + '</small><br>\n'
290 c = self.completeness (['long', 'color'])
291 s += ' <span style="background-color: #%(color)s">%(long)s</span><br>\n' % c
293 if self.partially_translated:
294 u = self.uptodateness (['long', 'color'])
295 s += ' <span style="background-color: #%(color)s">%(long)s</span><br>\n' % u
300 def html_status (self):
304 class MasterTelyDocument (TelyDocument):
305 def __init__ (self, filename, parent_translations=dict ([(lang, None) for lang in langdefs.LANGDICT.keys()])):
306 #print "init MasterTelyDocument %s" % filename
307 TelyDocument.__init__ (self, filename)
308 self.size = len (self.contents)
309 self.word_count = tely_word_count (self.contents)
310 translations = dict ([(lang, os.path.join (lang, filename)) for lang in langdefs.LANGDICT.keys()])
312 self.translations = dict ([(lang, TranslatedTelyDocument (translations[lang], self, parent_translations.get (lang)))
313 for lang in langdefs.LANGDICT.keys() if os.path.exists (translations[lang])])
314 if self.translations:
315 self.includes = [MasterTelyDocument (f, self.translations) for f in self.included_files]
320 def print_wc_priority (self):
323 def html_status (self, numbering=SectionNumber ()):
324 if self.title == 'Untitled' or not self.translations:
326 if self.level[1] == 0: # if self is a master document
327 s = '''<table align="center" border="2">
329 <th>%s</th>''' % self.print_title (numbering)
330 s += ''.join ([' <th>%s</th>\n' % l for l in self.translations.keys ()])
332 s += ' <tr align="left">\n <td>Section titles<br>(%d)</td>\n' \
333 % sum (self.word_count)
336 s = ' <tr align="left">\n <td>%s<br>(%d)</td>\n' \
337 % (self.print_title (numbering), sum (self.word_count))
339 s += ''.join ([t.short_html_status () for t in self.translations.values ()])
341 s += ''.join ([i.html_status (numbering) for i in self.includes])
343 if self.level[1] == 0:
344 s += '</table>\n<p></p>\n'
347 progress ("Reading documents...")
349 tely_files = read_pipe ("find -maxdepth 2 -name '*.tely'")[0].splitlines ()
350 master_docs = [MasterTelyDocument (os.path.normpath (filename)) for filename in tely_files]
351 master_docs = [doc for doc in master_docs if doc.translations]
353 main_status_page = open ('translations.template.html.in').read ()
356 #per_lang_status_pages = dict ([(l, open (os.path.join (l, 'translations.template.html')). read ())
357 # for l in langdefs.LANGDICT.keys ()
358 # if langdefs.LANGDICT[l].enabled])
360 progress ("Generating status pages...")
362 main_status_html = ' <p><i>Last updated %s</i></p>\n' % read_pipe ('LANG= date -u')[0]
363 main_status_html += '\n'.join ([doc.html_status () for doc in master_docs])
365 html_re = re.compile ('<html>', re.I)
366 end_body_re = re.compile ('</body>', re.I)
368 main_status_page = html_re.sub ('''<html>
369 <!-- This page is automatically generated by translation-status.py from
370 translations.template.html.in; DO NOT EDIT !-->''', main_status_page)
372 main_status_page = end_body_re.sub (main_status_html + '\n</body>', main_status_page)
374 open ('translations.html.in', 'w').write (main_status_page)