4 USAGE: cd Documentation && translations-status.py
8 <LANG>/translations.itexi
9 out/translations-status.txt
11 Update word counts in:
12 contributor/doc-translation-list.itexi
25 sys.stderr.write (str + '\n')
29 def error (str, update_status=1):
31 sys.stderr.write ('translations-status.py: %s\n' % str)
32 exit_code = max (exit_code, update_status)
34 progress ("translations-status.py")
38 # load gettext messages catalogs
39 translation = langdefs.translation
42 language_re = re.compile (r'^@documentlanguage (.+)', re.M)
43 comments_re = re.compile (r'^@ignore\n(.|\n)*?\n@end ignore$|@c .*?$', re.M)
44 space_re = re.compile (r'\s+', re.M)
45 lilypond_re = re.compile (r'@lilypond({.*?}|(.|\n)*?\n@end lilypond$)', re.M)
46 node_re = re.compile ('^@node .*?$', re.M)
47 title_re = re.compile ('^@(settitle|chapter|top|(?:sub){0,2}section|'
48 '(?:unnumbered|appendix)(?:(?:sub){0,2}sec)?) (.*?)$', re.M)
49 include_re = re.compile ('^@include (.*?)$', re.M)
51 # allow multiple lines
52 translators_re = re.compile (r'^@c[ ]+[Tt]ranslators?[ ]*:[ ]*(.*?)$', re.M)
53 checkers_re = re.compile (r'^@c[ ]+[Tt]ranslation[ ]*[Cc]heckers?[ ]*:[ ]*(.*?)$', re.M)
54 status_re = re.compile (r'^@c[ ]+[Tt]ranslation[ ]*[Ss]tatus[ ]*:[ ]*(.*?)$', re.M)
55 post_gdp_re = re.compile ('post.GDP', re.I)
56 untranslated_node_str = '@untranslated'
57 skeleton_str = '-- SKELETON FILE --'
59 section_titles_string = _doc ('Section titles')
60 last_updated_string = _doc (' <p><i>Last updated %s</i></p>\n')
61 detailed_status_heads = [_doc ('Translators'), _doc ('Translation checkers'),
62 _doc ('Translated'), _doc ('Up to date'),
65 'not translated': {'color':'d0f0f8', 'short':_doc ('no'), 'abbr':'NT',
66 'long':_doc ('not translated')},
67 'partially translated': {'color':'dfef77',
68 'short':_doc ('partially (%(p)d %%)'),
70 'long':_doc ('partially translated (%(p)d %%)')},
71 'fully translated': {'color':'1fff1f', 'short':_doc ('yes'), 'abbr':'FT',
72 'long': _doc ('translated')},
73 'up to date': {'short':_doc ('yes'), 'long':_doc ('up to date'),
74 'abbr':'100%%', 'vague':_doc ('up to date')},
75 'outdated': {'short':_doc ('partially'), 'abbr':'%(p)d%%',
76 'vague':_doc ('partially up to date')},
77 'N/A': {'short':_doc ('N/A'), 'abbr':'N/A', 'color':'d587ff', 'vague':''},
78 'pre-GDP':_doc ('pre-GDP'),
79 'post-GDP':_doc ('post-GDP')
83 # (Unumbered/Numbered/Lettered, level)
85 'unnumbered': ('u', 1),
86 'unnumberedsec': ('u', 2),
87 'unnumberedsubsec': ('u', 3),
90 'subsection': ('n', 3),
92 'appendixsec': ('l', 2),
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] = \
106 self.__data[-1][0].translate (appendix_number_trans)
108 self.__data[-1][0] += 1
111 if self.__data[-1][1] == 'u':
113 return '.'.join ([str (i[0]) for i in self.__data if i[1] != 'u']) + ' '
115 def increase (self, (type, level)):
117 self.__data = [[0,'u']]
118 while level + 1 < len (self.__data):
120 if level + 1 > len (self.__data):
121 self.__data.append ([0, type])
123 self.__data[-1][0] = '@'
124 if type == self.__data[-1][1]:
125 self.__increase_last_index ()
127 self.__data[-1] = ([0, type])
129 self.__data[-1][0] = 'A'
131 self.__data[-1][0] = 1
132 return self.format ()
135 def percentage_color (percent):
138 c = [hex (int (3 * p * b + (1 - 3 * p) * a))[2:]
139 for (a, b) in [(0xff, 0xff), (0x5c, 0xa6), (0x5c, 0x4c)]]
141 c = [hex (int ((3 * p - 1) * b + (2 - 3 * p) * a))[2:]
142 for (a, b) in [(0xff, 0xff), (0xa6, 0xff), (0x4c, 0x3d)]]
144 c = [hex (int ((3 * p - 2) * b + 3 * (1 - p) * a))[2:]
145 for (a, b) in [(0xff, 0x1f), (0xff, 0xff), (0x3d, 0x1f)]]
149 def update_word_count (text, filename, word_count):
150 return re.sub (r'(?m)^(\d+) *' + filename,
151 str (word_count).ljust (6) + filename,
154 po_msgid_re = re.compile (r'^msgid "(.*?)"(?:\n"(.*?)")*', re.M)
156 def po_word_count (po_content):
157 s = ' '.join ([''.join (t) for t in po_msgid_re.findall (po_content)])
158 return len (space_re.split (s))
160 sgml_tag_re = re.compile (r'<.*?>', re.S)
162 def sgml_word_count (sgml_doc):
163 s = sgml_tag_re.sub ('', sgml_doc)
164 return len (space_re.split (s))
166 def tely_word_count (tely_doc):
168 Calculate word count of a Texinfo document node by node.
170 Take string tely_doc as an argument.
171 Return a list of integers.
173 Texinfo comments and @lilypond blocks are not included in word counts.
175 tely_doc = comments_re.sub ('', tely_doc)
176 tely_doc = lilypond_re.sub ('', tely_doc)
177 nodes = node_re.split (tely_doc)
178 return [len (space_re.split (n)) for n in nodes]
180 class TexiMarkup (object):
181 def entity (self, name, string='', attributes=[]):
187 def paragraph (self, string=''):
189 %(string)s''' % locals ()
190 def table (self, string):
191 return self.entity ('multitable', string)
193 class HTMLMarkup (TexiMarkup):
194 def entity (self, name, string='', attributes=[]):
195 attr_list = ''.join ([' %s="%s"' % x for x in attributes])
196 return '<%(name)s%(attr_list)s>%(string)s</%(name)s>' % locals ()
197 def paragraph (self, string=''):
198 return self.entity ('p')
199 def table (self, string):
200 return self.entity ('table', string, [('align', 'center'), ('border', '2')])
202 class TelyDocument (object):
203 def __init__ (self, filename):
204 self.filename = filename
205 self.contents = 'GIT committish: 0'
206 if os.path.exists (filename):
207 self.contents = open (filename).read ()
208 ## record title and sectionning level of first Texinfo section
209 self.sectioning = 'unnumbered'
210 self.title = 'Untitled'
211 m = title_re.search (self.contents)
213 self.sectioning = m.group (1)
214 self.title = m.group (2)
216 if not hasattr (self, 'language'):
218 m = language_re.search (self.contents)
220 self.language = m.group (1)
222 dir = os.path.dirname (filename).split ('/')[0]
227 included_files = [dir + t
228 for t in include_re.findall (self.contents)]
229 self.included_files = [p for p in included_files if os.path.exists (p)]
231 def get_level (self):
232 return texi_level [self.sectioning]
234 def print_title (self, section_number):
235 if not hasattr (self, 'level'):
236 self.level = self.get_level ()
237 return section_number.increase (self.level) + self.title
240 class TranslatedTelyDocument (TelyDocument):
241 def __init__ (self, filename, masterdocument, parent_translation=None):
242 TelyDocument.__init__ (self, filename)
243 self.masterdocument = masterdocument
244 if not hasattr (self, 'language'):
246 if not self.language and parent_translation:
247 self.language = parent_translation.__dict__.get ('language', '')
248 if self.language == 'en':
249 print filename + ': language en specified: set @documentlanguage', self.filename[:2]
251 if not self.language and filename[2] == '/':
252 print filename + ': no language specified: add @documentlanguage', self.filename[:2]
253 self.language = filename[:2]
255 self.translation = translation[self.language]
257 self.translation = lambda x: x
258 self.title = self.translation (self.title)
260 ## record authoring information
261 self.translators = ['']
262 if parent_translation:
263 self.translators = parent_translation.__dict__.get ('translators', [''])
264 m = translators_re.findall (self.contents)
266 self.translators = [n.strip () for n in
267 reduce (operator.add, [n.split (',') for n in m])]
268 if self.language != self.filename[:2]:
269 print 'Barf:', self.filename
271 if (not isinstance (self, UntranslatedTelyDocument)
272 and (not self.translators or not self.translators[0])
273 and not 'macros.itexi' in self.filename):
274 error (self.filename + ''': error: no translator name found
275 please specify one ore more lines in the master file
276 @c Translator: FirstName LastName[, FirstName LastName]..''')
278 m = checkers_re.findall (self.contents)
280 self.checkers = [n.strip () for n in
281 reduce (operator.add, [n.split (',') for n in m])]
282 if not self.checkers and isinstance (parent_translation, TranslatedTelyDocument):
283 self.checkers = parent_translation.checkers
285 ## check whether translation is pre- or post-GDP
286 m = status_re.search (self.contents)
288 self.post_gdp = bool (post_gdp_re.search (m.group (1)))
290 self.post_gdp = False
292 ## record which parts (nodes) of the file are actually translated
293 self.partially_translated = not skeleton_str in self.contents
294 nodes = node_re.split (self.contents)
295 self.translated_nodes = [not untranslated_node_str in n for n in nodes]
297 ## calculate translation percentage
298 master_total_word_count = sum (masterdocument.word_count)
299 translation_word_count = \
300 sum ([masterdocument.word_count[k] * self.translated_nodes[k]
301 for k in range (min (len (masterdocument.word_count),
302 len (self.translated_nodes)))])
303 self.translation_percentage = \
304 100 * translation_word_count / master_total_word_count
306 ## calculate how much the file is outdated
307 (diff_string, git_error) = \
308 buildlib.check_translated_doc (masterdocument.filename, self.filename, self.contents)
310 sys.stderr.write ('warning: %s: %s' % (self.filename, git_error))
311 self.uptodate_percentage = None
313 diff = diff_string.splitlines ()
314 insertions = sum ([len (l) - 1 for l in diff
315 if l.startswith ('+')
316 and not l.startswith ('+++')])
317 deletions = sum ([len (l) - 1 for l in diff
318 if l.startswith ('-')
319 and not l.startswith ('---')])
320 outdateness_percentage = 50.0 * (deletions + insertions) / \
321 (masterdocument.size + 0.5 * (deletions - insertions))
322 self.uptodate_percentage = 100 - int (outdateness_percentage)
323 if self.uptodate_percentage > 100:
325 progress ("%s: strange uptodateness percentage %d %%, \
326 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
327 self.uptodate_percentage = alternative
328 elif self.uptodate_percentage < 1:
330 progress ("%s: strange uptodateness percentage %d %%, \
331 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
332 self.uptodate_percentage = alternative
334 def get_level (self):
335 return texi_level ['top']
337 def completeness (self, formats=['long'], translated=False):
339 translation = self.translation
341 translation = lambda x: x
343 if isinstance (formats, str):
345 p = self.translation_percentage
347 status = 'not translated'
349 status = 'fully translated'
351 status = 'partially translated'
352 return dict ([(f, translation (format_table[status][f]) % locals())
355 def uptodateness (self, formats=['long'], translated=False):
357 translation = self.translation
359 translation = lambda x: x
361 if isinstance (formats, str):
363 p = self.uptodate_percentage
367 status = 'up to date'
372 if f == 'color' and p != None:
373 l['color'] = percentage_color (p)
375 l[f] = translation (format_table[status][f]) % locals ()
378 def gdp_status (self):
380 return self.translation (format_table['post-GDP'])
382 return self.translation (format_table['pre-GDP'])
384 def short_texi_status (self, markup):
385 s = ' <td title="%(filename)s">' % self.__dict__
386 if self.partially_translated:
387 s += '<br>\n '.join (self.translators) + '<br>\n'
390 '<br>\n '.join (self.checkers) + '</small><br>\n'
392 c = self.completeness (['color', 'long'])
393 s += ' <span style="background-color: #%(color)s">\
394 %(long)s</span><br>\n' % c
396 if self.partially_translated:
397 u = self.uptodateness (['vague', 'color'])
398 s += ' <span style="background-color: #%(color)s">\
399 %(vague)s</span><br>\n' % u
404 def text_status (self):
405 s = self.completeness ('abbr')['abbr'] + ' '
407 if self.partially_translated:
408 s += self.uptodateness ('abbr')['abbr'] + ' '
411 def texi_status (self, markup, numbering=SectionNumber ()):
412 s = '''<tr align="center">
413 <th>%s</th>''' % self.print_title (numbering)
414 s += ''.join ([' <th>%s</th>\n' % self.translation (h)
415 for h in detailed_status_heads])
417 s += (' <tr align="left">\n <td title="%%(filename)s">%s<br>(%d)</td>\n'
418 % (self.translation (section_titles_string),
419 sum (self.masterdocument.word_count))) % self.__dict__
420 s += self.texi_body (markup, numbering)
421 return markup.table (s) + markup.paragraph ()
423 def texi_body (self, markup, numbering):
424 return (self.texi_translators (markup)
425 + self.texi_completeness (markup)
426 + self.texi_uptodateness (markup)
427 + self.texi_gdp (markup)
428 + self.texi_translations (markup, numbering))
430 def texi_translators (self, markup):
431 if self.partially_translated:
432 return (' <td>' + '<br>\n '.join (self.translators) + '</td>\n'
433 + ' <td>' + '<br>\n '.join (self.checkers) + '</td>\n')
434 return ' <td></td>\n' * 2
436 def texi_completeness (self, markup):
437 c = self.completeness (['color', 'short'], translated=True)
438 return ' <td><span style="background-color: #%(color)s">\
439 %(short)s</span></td>\n' % {'color': c['color'],
442 def texi_uptodateness (self, markup):
443 if self.partially_translated:
444 u = self.uptodateness (['short', 'color'], translated=True)
445 return ' <td><span style="background-color: #%(color)s">\
446 %(short)s</span></td>\n' % {'color': u['color'],
448 return ' <td></td>\n'
450 def texi_gdp (self, markup):
451 return ' <td>' + self.gdp_status () + '</td>\n </tr>\n'
453 def texi_translations (self, markup, numbering):
454 return ''.join ([i.translations[self.language].texi_status (markup, numbering)
455 for i in self.masterdocument.includes
456 if self.language in i.translations])
458 class IncludedTranslatedTelyDocument (TranslatedTelyDocument):
459 get_level = TelyDocument.get_level
460 def texi_status (self, markup, numbering=SectionNumber ()):
461 if self.title != 'Untitled':
462 return ((' <tr align="left">\n <td title="%%(filename)s">%s<br>(%d)</td>\n'
463 % (self.print_title (numbering),
464 sum (self.masterdocument.word_count))) % self.__dict__
465 + self.texi_body (markup, numbering))
468 class UntranslatedTelyDocument (TranslatedTelyDocument):
469 def __init__ (self, filename, masterdocument, parent_translation=None):
470 if filename[2] == '/':
471 self.language = filename[:2]
472 TranslatedTelyDocument.__init__ (self, filename, masterdocument, parent_translation)
474 class IncludedUntranslatedTelyDocument (UntranslatedTelyDocument, IncludedTranslatedTelyDocument):
475 get_level = TelyDocument.get_level
477 class MasterTelyDocument (TelyDocument):
480 parent_translations=dict ([(lang, None)
481 for lang in langdefs.LANGDICT])):
482 TelyDocument.__init__ (self, filename)
483 self.size = len (self.contents)
484 self.word_count = tely_word_count (self.contents)
485 self.translations = {}
487 if not self.language or self.language == 'en':
488 languages = [x for x in parent_translations.keys () if x != 'en']
489 self.translations = dict ([x for x in
490 [(lang, self.translated_factory (os.path.join (lang, self.filename),
491 parent_translations.get (lang)))
492 for lang in languages]
494 if self.translations:
495 self.includes = [IncludedMasterTelyDocument (f, self.translations)
496 for f in self.included_files]
498 def get_level (self):
499 return texi_level ['top']
501 def translated_factory (self, filename, parent):
502 if os.path.exists (filename):
503 return TranslatedTelyDocument (filename, self, parent)
506 def update_word_counts (self, s):
507 s = update_word_count (s, self.filename, sum (self.word_count))
508 for i in self.includes:
509 s = i.update_word_counts (s)
512 def texi_status (self, markup, numbering=SectionNumber ()):
515 <th>%s</th>''' % self.print_title (numbering)
516 s += ''.join ([' <th>%s</th>\n' % l for l in sorted (self.translations.keys ())])
518 s += (' <tr align="left">\n <td title="%%(filename)s">Section titles<br>(%d)</td>\n'
519 % sum (self.word_count)) % self.__dict__
520 s += self.texi_body (markup, numbering)
521 return markup.table (s) + markup.paragraph ()
523 def texi_body (self, markup, numbering):
524 return (''.join ([self.translations[k].short_texi_status (markup)
525 for k in sorted (self.translations.keys ())])
527 + ''.join ([i.texi_status (markup, numbering) for i in self.includes]))
529 def text_status (self, markup, numbering=SectionNumber (), colspec=[48,12]):
530 s = (self.print_title (numbering) + ' ').ljust (colspec[0])
531 s += ''.join (['%s'.ljust (colspec[1]) % l
532 for l in sorted (self.translations.keys ())])
534 s += ('Section titles (%d)' % \
535 sum (self.word_count)).ljust (colspec[0])
536 s += self.text_body (markup, numbering, colspec)
540 def text_body (self, markup, numbering, colspec):
541 return (''.join ([self.translations[k].text_status ().ljust(colspec[1])
542 for k in sorted (self.translations.keys ())])
544 + ''.join ([i.text_status (markup, numbering) for i in self.includes]))
546 class IncludedMasterTelyDocument (MasterTelyDocument):
547 get_level = TelyDocument.get_level
549 def translated_factory (self, filename, parent):
550 if os.path.exists (filename):
551 return IncludedTranslatedTelyDocument (filename, self, parent)
552 return IncludedUntranslatedTelyDocument (filename, self, parent)
554 def texi_status (self, markup, numbering=SectionNumber ()):
555 if self.title != 'Untitled':
556 return ((' <tr align="left">\n <td title=%%(filename)s>%s<br>(%d)</td>\n'
557 % (self.print_title (numbering), sum (self.word_count))) % self.__dict__
558 + self.texi_body (markup, numbering))
561 def text_status (self, markup, numbering=SectionNumber (), colspec=[48,12]):
562 if self.title != 'Untitled':
564 % (self.print_title (numbering), sum (self.word_count)))
565 + self.text_body (markup, numbering, colspec)
570 update_category_word_counts_re = re.compile (r'(?ms)^-(\d+)-(.*?\n)\d+ *total')
572 counts_re = re.compile (r'(?m)^(\d+) ')
574 def update_category_word_counts_sub (m):
575 return ('-' + m.group (1) + '-' + m.group (2)
577 for c in counts_re.findall (m.group (2))])).ljust (6)
581 # main () starts here-abouts
583 progress ("Reading documents...")
586 buildlib.read_pipe ("git ls-files | grep -E '[^/]*/?[^/]*[.](tely|texi)$'")[0].splitlines ()
588 master_docs = [MasterTelyDocument (os.path.normpath (filename))
589 for filename in master_files]
590 master_docs = [doc for doc in master_docs if doc.translations]
592 enabled_languages = [l for l in langdefs.LANGDICT
593 if langdefs.LANGDICT[l].enabled
596 progress ("Generating status pages...")
598 date_time = buildlib.read_pipe ('LANG= date -u')[0]
600 markup = HTMLMarkup ()
601 #markup = TexiMarkup ()
602 main_status_body = last_updated_string % date_time
603 main_status_body += '\n'.join ([doc.texi_status (markup) for doc in master_docs])
605 texi_header = '''@c -*- coding: utf-8; mode: texinfo; -*-
606 @c This file was generated by translation-status.py -- DO NOT EDIT!
608 Translation of GIT committish: 0
612 Translation status currently only available in HTML.
623 main_status_page = texi_header % locals () + main_status_body + texi_footer
625 open ('translations.itexi', 'w').write (main_status_page)
627 for l in enabled_languages:
628 date_time = buildlib.read_pipe ('LANG=%s date -u' % l)[0]
629 updated = translation[l] (last_updated_string) % date_time
630 texi_status = '\n'.join ([doc.translations[l].texi_status (markup)
631 for doc in master_docs
632 if l in doc.translations])
633 lang_status_page = texi_header + updated + texi_status + texi_footer
634 open (os.path.join (l, 'translations.itexi'), 'w').write (lang_status_page)
636 main_status_txt = '''Documentation translations status
639 FT = fully translated
643 main_status_txt += '\n'.join ([doc.text_status (markup) for doc in master_docs])
645 status_txt_file = 'out/translations-status.txt'
646 progress ("Writing %s..." % status_txt_file)
647 open (status_txt_file, 'w').write (main_status_txt)
649 translation_instructions_file = 'contributor/doc-translation-list.itexi'
650 progress ("Updating %s..." % translation_instructions_file)
651 translation_instructions = open (translation_instructions_file).read ()
653 for doc in master_docs:
654 translation_instructions = doc.update_word_counts (translation_instructions)
656 for html_file in re.findall (r'(?m)^\d+ *(\S+?\.html\S*?)(?: |$)',
657 translation_instructions):
658 word_count = sgml_word_count (open (html_file).read ())
659 translation_instructions = update_word_count (translation_instructions,
663 for po_file in re.findall (r'(?m)^\d+ *(\S+?\.po\S*?)(?: |$)',
664 translation_instructions):
665 word_count = po_word_count (open (po_file).read ())
666 translation_instructions = update_word_count (translation_instructions,
670 translation_instructions = \
671 update_category_word_counts_re.sub (update_category_word_counts_sub,
672 translation_instructions)
674 open (translation_instructions_file, 'w').write (translation_instructions)