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
10 Writes translations.html.in and for each LANG in LANGUAGES
11 translations.LANG.html.in
12 Writes out/translations-status.txt
13 Updates word counts in TRANSLATION
24 sys.stderr.write (str + '\n')
26 progress ("translations-status.py")
28 buildscript_dir = sys.argv[1]
32 sys.path.append (buildscript_dir)
35 # load gettext messages catalogs
36 translation = langdefs.translation
39 language_re = re.compile (r'^@documentlanguage (.+)', re.M)
40 comments_re = re.compile (r'^@ignore\n(.|\n)*?\n@end ignore$|@c .*?$', re.M)
41 space_re = re.compile (r'\s+', re.M)
42 lilypond_re = re.compile (r'@lilypond({.*?}|(.|\n)*?\n@end lilypond$)', re.M)
43 node_re = re.compile ('^@node .*?$', re.M)
44 title_re = re.compile ('^@(top|chapter|(?:sub){0,2}section|' + \
45 '(?:unnumbered|appendix)(?:(?:sub){0,2}sec)?) (.*?)$', re.M)
46 include_re = re.compile ('^@include (.*?)$', re.M)
48 translators_re = re.compile (r'^@c\s+Translators\s*:\s*(.*?)$', re.M | re.I)
49 checkers_re = re.compile (r'^@c\s+Translation\s*checkers\s*:\s*(.*?)$',
51 status_re = re.compile (r'^@c\s+Translation\s*status\s*:\s*(.*?)$', re.M | re.I)
52 post_gdp_re = re.compile ('post.GDP', re.I)
53 untranslated_node_str = 'UNTRANSLATED NODE: IGNORE ME'
54 skeleton_str = '-- SKELETON FILE --'
56 detailed_status_heads = [_doc ('Translators'), _doc ('Translation checkers'),
57 _doc ('Translated'), _doc ('Up to date'),
60 'not translated': {'color':'d0f0f8', 'short':_doc ('no'), 'abbr':'NT',
61 'long':_doc ('not translated')},
62 'partially translated': {'color':'dfef77',
63 'short':_doc ('partially (%(p)d %%)'),
65 'long':_doc ('partially translated (%(p)d %%)')},
66 'fully translated': {'color':'1fff1f', 'short':_doc ('yes'), 'abbr':'FT',
67 'long': _doc ('translated')},
68 'up to date': {'short':_doc ('yes'), 'long':_doc ('up to date'),
69 'abbr':'100%%', 'vague':_doc ('up to date')},
70 'outdated': {'short':_doc ('partially'), 'abbr':'%(p)d%%',
71 'vague':_doc ('partially up to date')},
72 'N/A': {'short':_doc ('N/A'), 'abbr':'N/A', 'color':'d587ff', 'vague':''},
73 'pre-GDP':_doc ('pre-GDP'),
74 'post-GDP':_doc ('post-GDP')
78 # (Unumbered/Numbered/Lettered, level)
80 'unnumbered': ('u', 1),
81 'unnumberedsec': ('u', 2),
82 'unnumberedsubsec': ('u', 3),
85 'subsection': ('n', 3),
89 appendix_number_trans = string.maketrans ('@ABCDEFGHIJKLMNOPQRSTUVWXY',
90 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
92 class SectionNumber (object):
94 self.__data = [[0,'u']]
96 def __increase_last_index (self):
97 type = self.__data[-1][1]
99 self.__data[-1][0] = \
100 self.__data[-1][0].translate (appendix_number_trans)
102 self.__data[-1][0] += 1
105 if self.__data[-1][1] == 'u':
107 return '.'.join ([str (i[0]) for i in self.__data if i[1] != 'u']) + ' '
109 def increase (self, (type, level)):
111 self.__data = [[0,'u']]
112 while level + 1 < len (self.__data):
114 if level + 1 > len (self.__data):
115 self.__data.append ([0, type])
117 self.__data[-1][0] = '@'
118 if type == self.__data[-1][1]:
119 self.__increase_last_index ()
121 self.__data[-1] = ([0, type])
123 self.__data[-1][0] = 'A'
125 self.__data[-1][0] = 1
126 return self.format ()
129 def percentage_color (percent):
132 c = [hex (int (3 * p * b + (1 - 3 * p) * a))[2:]
133 for (a, b) in [(0xff, 0xff), (0x5c, 0xa6), (0x5c, 0x4c)]]
135 c = [hex (int ((3 * p - 1) * b + (2 - 3 * p) * a))[2:]
136 for (a, b) in [(0xff, 0xff), (0xa6, 0xff), (0x4c, 0x3d)]]
138 c = [hex (int ((3 * p - 2) * b + 3 * (1 - p) * a))[2:]
139 for (a, b) in [(0xff, 0x1f), (0xff, 0xff), (0x3d, 0x1f)]]
143 def update_word_count (text, filename, word_count):
144 return re.sub (r'(?m)^(\d+) *' + filename,
145 str (word_count).ljust (6) + filename,
148 po_msgid_re = re.compile (r'^msgid "(.*?)"(?:\n"(.*?)")*', re.M)
150 def po_word_count (po_content):
151 s = ' '.join ([''.join (t) for t in po_msgid_re.findall (po_content)])
152 return len (space_re.split (s))
154 sgml_tag_re = re.compile (r'<.*?>', re.S)
156 def sgml_word_count (sgml_doc):
157 s = sgml_tag_re.sub ('', sgml_doc)
158 return len (space_re.split (s))
160 def tely_word_count (tely_doc):
162 Calculate word count of a Texinfo document node by node.
164 Take string tely_doc as an argument.
165 Return a list of integers.
167 Texinfo comments and @lilypond blocks are not included in word counts.
169 tely_doc = comments_re.sub ('', tely_doc)
170 tely_doc = lilypond_re.sub ('', tely_doc)
171 nodes = node_re.split (tely_doc)
172 return [len (space_re.split (n)) for n in nodes]
175 class TelyDocument (object):
176 def __init__ (self, filename):
177 self.filename = filename
178 self.contents = open (filename).read ()
180 ## record title and sectionning level of first Texinfo section
181 m = title_re.search (self.contents)
183 self.title = m.group (2)
184 self.level = texi_level [m.group (1)]
186 self.title = 'Untitled'
187 self.level = ('u', 1)
189 m = language_re.search (self.contents)
191 self.language = m.group (1)
193 included_files = [os.path.join (os.path.dirname (filename), t)
194 for t in include_re.findall (self.contents)]
195 self.included_files = [p for p in included_files if os.path.exists (p)]
197 def print_title (self, section_number):
198 return section_number.increase (self.level) + self.title
201 class TranslatedTelyDocument (TelyDocument):
202 def __init__ (self, filename, masterdocument, parent_translation=None):
203 TelyDocument.__init__ (self, filename)
205 self.masterdocument = masterdocument
206 if not hasattr (self, 'language') \
207 and hasattr (parent_translation, 'language'):
208 self.language = parent_translation.language
209 if hasattr (self, 'language'):
210 self.translation = translation[self.language]
212 self.translation = lambda x: x
214 ## record authoring information
215 m = translators_re.search (self.contents)
217 self.translators = [n.strip () for n in m.group (1).split (',')]
219 self.translators = parent_translation.translators
220 m = checkers_re.search (self.contents)
222 self.checkers = [n.strip () for n in m.group (1).split (',')]
223 elif isinstance (parent_translation, TranslatedTelyDocument):
224 self.checkers = parent_translation.checkers
228 ## check whether translation is pre- or post-GDP
229 m = status_re.search (self.contents)
231 self.post_gdp = bool (post_gdp_re.search (m.group (1)))
233 self.post_gdp = False
235 ## record which parts (nodes) of the file are actually translated
236 self.partially_translated = not skeleton_str in self.contents
237 nodes = node_re.split (self.contents)
238 self.translated_nodes = [not untranslated_node_str in n for n in nodes]
240 ## calculate translation percentage
241 master_total_word_count = sum (masterdocument.word_count)
242 translation_word_count = \
243 sum ([masterdocument.word_count[k] * self.translated_nodes[k]
244 for k in range (min (len (masterdocument.word_count),
245 len (self.translated_nodes)))])
246 self.translation_percentage = \
247 100 * translation_word_count / master_total_word_count
249 ## calculate how much the file is outdated
250 (diff_string, error) = \
251 buildlib.check_translated_doc (masterdocument.filename, self.contents)
253 sys.stderr.write ('warning: %s: %s' % (self.filename, error))
254 self.uptodate_percentage = None
256 diff = diff_string.splitlines ()
257 insertions = sum ([len (l) - 1 for l in diff
258 if l.startswith ('+')
259 and not l.startswith ('+++')])
260 deletions = sum ([len (l) - 1 for l in diff
261 if l.startswith ('-')
262 and not l.startswith ('---')])
263 outdateness_percentage = 50.0 * (deletions + insertions) / \
264 (masterdocument.size + 0.5 * (deletions - insertions))
265 self.uptodate_percentage = 100 - int (outdateness_percentage)
266 if self.uptodate_percentage > 100:
268 progress ("%s: strange uptodateness percentage %d %%, \
269 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
270 self.uptodate_percentage = alternative
271 elif self.uptodate_percentage < 1:
273 progress ("%s: strange uptodateness percentage %d %%, \
274 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
275 self.uptodate_percentage = alternative
277 def completeness (self, formats=['long']):
278 if isinstance (formats, str):
280 p = self.translation_percentage
282 status = 'not translated'
284 status = 'fully translated'
286 status = 'partially translated'
287 return dict ([(f, format_table[status][f] % locals()) for f in formats])
289 def uptodateness (self, formats=['long']):
290 if isinstance (formats, str):
292 p = self.uptodate_percentage
296 status = 'up to date'
301 if f == 'color' and p != None:
302 l['color'] = percentage_color (p)
304 l[f] = format_table[status][f] % locals ()
307 def gdp_status (self):
309 return self.translation (format_table['post-GDP'])
311 return self.translation (format_table['pre-GDP'])
313 def short_html_status (self):
315 if self.partially_translated:
316 s += '<br>\n '.join (self.translators) + '<br>\n'
319 '<br>\n '.join (self.checkers) + '</small><br>\n'
321 c = self.completeness (['color', 'long'])
322 s += ' <span style="background-color: #%(color)s">\
323 %(long)s</span><br>\n' % c
325 if self.partially_translated:
326 u = self.uptodateness (['vague', 'color'])
327 s += ' <span style="background-color: #%(color)s">\
328 %(vague)s</span><br>\n' % u
333 def text_status (self):
334 s = self.completeness ('abbr')['abbr'] + ' '
336 if self.partially_translated:
337 s += self.uptodateness ('abbr')['abbr'] + ' '
340 def html_status (self, numbering=SectionNumber ()):
341 if self.level[1] == 0: # if self is a master document
342 s = '''<table align="center" border="2">
344 <th>%s</th>''' % self.print_title (numbering)
345 s += ''.join ([' <th>%s</th>\n' % self.translation (h)
346 for h in detailed_status_heads])
348 s += ' <tr align="left">\n <td>Section titles<br>(%d)</td>\n' \
349 % sum (self.masterdocument.word_count)
352 s = ' <tr align="left">\n <td>%s<br>(%d)</td>\n' \
353 % (self.print_title (numbering),
354 sum (self.masterdocument.word_count))
356 if self.partially_translated:
357 s += ' <td>' + '<br>\n '.join (self.translators) + '</td>\n'
358 s += ' <td>' + '<br>\n '.join (self.checkers) + '</td>\n'
360 s += ' <td></td>\n' * 2
362 c = self.completeness (['color', 'short'])
363 s += ' <td><span style="background-color: #%(color)s">\
364 %(short)s</span></td>\n' % {'color': c['color'],
365 'short': self.translation (c['short'])}
367 if self.partially_translated:
368 u = self.uptodateness (['short', 'color'])
369 s += ' <td><span style="background-color: #%(color)s">\
370 %(short)s</span></td>\n' % {'color': u['color'],
371 'short': self.translation (u['short'])}
375 s += ' <td>' + self.gdp_status () + '</td>\n </tr>\n'
376 s += ''.join ([i.translations[self.language].html_status (numbering)
377 for i in self.masterdocument.includes
378 if self.language in i.translations])
380 if self.level[1] == 0: # if self is a master document
381 s += '</table>\n<p></p>\n'
384 class MasterTelyDocument (TelyDocument):
387 parent_translations=dict ([(lang, None)
388 for lang in langdefs.LANGDICT])):
389 TelyDocument.__init__ (self, filename)
390 self.size = len (self.contents)
391 self.word_count = tely_word_count (self.contents)
392 translations = dict ([(lang, os.path.join (lang, filename))
393 for lang in langdefs.LANGDICT])
394 self.translations = \
396 TranslatedTelyDocument (translations[lang],
397 self, parent_translations.get (lang)))
398 for lang in langdefs.LANGDICT
399 if os.path.exists (translations[lang])])
400 if self.translations:
401 self.includes = [MasterTelyDocument (f, self.translations)
402 for f in self.included_files]
406 def update_word_counts (self, s):
407 s = update_word_count (s, self.filename, sum (self.word_count))
408 for i in self.includes:
409 s = i.update_word_counts (s)
412 def html_status (self, numbering=SectionNumber ()):
413 if self.title == 'Untitled' or not self.translations:
415 if self.level[1] == 0: # if self is a master document
416 s = '''<table align="center" border="2">
418 <th>%s</th>''' % self.print_title (numbering)
419 s += ''.join ([' <th>%s</th>\n' % l for l in self.translations])
421 s += ' <tr align="left">\n <td>Section titles<br>(%d)</td>\n' \
422 % sum (self.word_count)
424 else: # if self is an included file
425 s = ' <tr align="left">\n <td>%s<br>(%d)</td>\n' \
426 % (self.print_title (numbering), sum (self.word_count))
428 s += ''.join ([t.short_html_status ()
429 for t in self.translations.values ()])
431 s += ''.join ([i.html_status (numbering) for i in self.includes])
433 if self.level[1] == 0: # if self is a master document
434 s += '</table>\n<p></p>\n'
437 def text_status (self, numbering=SectionNumber (), colspec=[48,12]):
438 if self.title == 'Untitled' or not self.translations:
442 if self.level[1] == 0: # if self is a master document
443 s += (self.print_title (numbering) + ' ').ljust (colspec[0])
444 s += ''.join (['%s'.ljust (colspec[1]) % l
445 for l in self.translations])
447 s += ('Section titles (%d)' % \
448 sum (self.word_count)).ljust (colspec[0])
452 % (self.print_title (numbering), sum (self.word_count))
453 s = s.ljust (colspec[0])
455 s += ''.join ([t.text_status ().ljust(colspec[1])
456 for t in self.translations.values ()])
458 s += ''.join ([i.text_status (numbering) for i in self.includes])
460 if self.level[1] == 0:
465 update_category_word_counts_re = re.compile (r'(?ms)^-(\d+)-(.*?\n)\d+ *total')
467 counts_re = re.compile (r'(?m)^(\d+) ')
469 def update_category_word_counts_sub (m):
470 return '-' + m.group (1) + '-' + m.group (2) + \
472 for c in counts_re.findall (m.group (2))])).ljust (6) + \
476 progress ("Reading documents...")
479 buildlib.read_pipe ("find -maxdepth 2 -name '*.tely'")[0].splitlines ()
481 master_docs = [MasterTelyDocument (os.path.normpath (filename))
482 for filename in tely_files]
483 master_docs = [doc for doc in master_docs if doc.translations]
485 main_status_page = open ('translations.template.html.in').read ()
487 enabled_languages = [l for l in langdefs.LANGDICT
488 if langdefs.LANGDICT[l].enabled
490 lang_status_pages = \
491 dict ([(l, open (os.path.join (l, 'translations.template.html.in')). read ())
492 for l in enabled_languages])
494 progress ("Generating status pages...")
496 date_time = buildlib.read_pipe ('LANG= date -u')[0]
498 main_status_html = ' <p><i>Last updated %s</i></p>\n' % date_time
499 main_status_html += '\n'.join ([doc.html_status () for doc in master_docs])
501 html_re = re.compile ('<html>', re.I)
502 end_body_re = re.compile ('</body>', re.I)
504 html_header = '''<html>
505 <!-- This page is automatically generated by translation-status.py from
506 translations.template.html.in; DO NOT EDIT !-->'''
508 main_status_page = html_re.sub (html_header, main_status_page)
510 main_status_page = end_body_re.sub (main_status_html + '\n</body>',
513 open ('translations.html.in', 'w').write (main_status_page)
515 for l in enabled_languages:
516 lang_status_page = html_re.sub (html_header, lang_status_pages[l])
517 html_status = '\n'.join ([doc.translations[l].html_status ()
518 for doc in master_docs
519 if l in doc.translations])
520 lang_status_page = end_body_re.sub (html_status + '\n</body>',
522 open (os.path.join (l, 'translations.html.in'), 'w').write (lang_status_page)
524 main_status_txt = '''Documentation translations status
527 FT = fully translated
531 main_status_txt += '\n'.join ([doc.text_status () for doc in master_docs])
533 status_txt_file = 'out/translations-status.txt'
534 progress ("Writing %s..." % status_txt_file)
535 open (status_txt_file, 'w').write (main_status_txt)
537 translation_instructions_file = 'TRANSLATION'
538 progress ("Updating %s..." % translation_instructions_file)
539 translation_instructions = open (translation_instructions_file).read ()
541 for doc in master_docs:
542 translation_instructions = doc.update_word_counts (translation_instructions)
544 for html_file in re.findall (r'(?m)^\d+ *(\S+?\.html\S*?)(?: |$)',
545 translation_instructions):
546 word_count = sgml_word_count (open (html_file).read ())
547 translation_instructions = update_word_count (translation_instructions,
551 for po_file in re.findall (r'(?m)^\d+ *(\S+?\.po\S*?)(?: |$)',
552 translation_instructions):
553 word_count = po_word_count (open (po_file).read ())
554 translation_instructions = update_word_count (translation_instructions,
558 translation_instructions = \
559 update_category_word_counts_re.sub (update_category_word_counts_sub,
560 translation_instructions)
562 open (translation_instructions_file, 'w').write (translation_instructions)