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):
183 class HTMLMarkup (TexiMarkup):
186 class TelyDocument (object):
187 def __init__ (self, filename):
188 self.filename = filename
189 self.contents = 'GIT committish: 0'
190 if os.path.exists (filename):
191 self.contents = open (filename).read ()
192 ## record title and sectionning level of first Texinfo section
193 self.sectioning = 'unnumbered'
194 self.title = 'Untitled'
195 m = title_re.search (self.contents)
197 self.sectioning = m.group (1)
198 self.title = m.group (2)
200 if not hasattr (self, 'language'):
202 m = language_re.search (self.contents)
204 self.language = m.group (1)
206 dir = os.path.dirname (filename).split ('/')[0]
211 included_files = [dir + t
212 for t in include_re.findall (self.contents)]
213 self.included_files = [p for p in included_files if os.path.exists (p)]
215 def get_level (self):
216 return texi_level [self.sectioning]
218 def print_title (self, section_number):
219 if not hasattr (self, 'level'):
220 self.level = self.get_level ()
221 return section_number.increase (self.level) + self.title
224 class TranslatedTelyDocument (TelyDocument):
225 def __init__ (self, filename, masterdocument, parent_translation=None):
226 TelyDocument.__init__ (self, filename)
227 self.masterdocument = masterdocument
228 if not hasattr (self, 'language'):
230 if not self.language and parent_translation:
231 self.language = parent_translation.__dict__.get ('language', '')
232 if self.language == 'en':
233 print filename + ': language en specified: set @documentlanguage', self.filename[:2]
235 if not self.language and filename[2] == '/':
236 print filename + ': no language specified: add @documentlanguage', self.filename[:2]
237 self.language = filename[:2]
239 self.translation = translation[self.language]
241 self.translation = lambda x: x
242 self.title = self.translation (self.title)
244 ## record authoring information
245 self.translators = ['']
246 if parent_translation:
247 self.translators = parent_translation.__dict__.get ('translators', [''])
248 m = translators_re.findall (self.contents)
250 self.translators = [n.strip () for n in
251 reduce (operator.add, [n.split (',') for n in m])]
252 if self.language != self.filename[:2]:
253 print 'Barf:', self.filename
255 if (not isinstance (self, UntranslatedTelyDocument)
256 and (not self.translators or not self.translators[0])
257 and not 'macros.itexi' in self.filename):
258 error (self.filename + ''': error: no translator name found
259 please specify one ore more lines in the master file
260 @c Translator: FirstName LastName[, FirstName LastName]..''')
262 m = checkers_re.findall (self.contents)
264 self.checkers = [n.strip () for n in
265 reduce (operator.add, [n.split (',') for n in m])]
266 if not self.checkers and isinstance (parent_translation, TranslatedTelyDocument):
267 self.checkers = parent_translation.checkers
269 ## check whether translation is pre- or post-GDP
270 m = status_re.search (self.contents)
272 self.post_gdp = bool (post_gdp_re.search (m.group (1)))
274 self.post_gdp = False
276 ## record which parts (nodes) of the file are actually translated
277 self.partially_translated = not skeleton_str in self.contents
278 nodes = node_re.split (self.contents)
279 self.translated_nodes = [not untranslated_node_str in n for n in nodes]
281 ## calculate translation percentage
282 master_total_word_count = sum (masterdocument.word_count)
283 translation_word_count = \
284 sum ([masterdocument.word_count[k] * self.translated_nodes[k]
285 for k in range (min (len (masterdocument.word_count),
286 len (self.translated_nodes)))])
287 self.translation_percentage = \
288 100 * translation_word_count / master_total_word_count
290 ## calculate how much the file is outdated
291 (diff_string, git_error) = \
292 buildlib.check_translated_doc (masterdocument.filename, self.filename, self.contents)
294 sys.stderr.write ('warning: %s: %s' % (self.filename, git_error))
295 self.uptodate_percentage = None
297 diff = diff_string.splitlines ()
298 insertions = sum ([len (l) - 1 for l in diff
299 if l.startswith ('+')
300 and not l.startswith ('+++')])
301 deletions = sum ([len (l) - 1 for l in diff
302 if l.startswith ('-')
303 and not l.startswith ('---')])
304 outdateness_percentage = 50.0 * (deletions + insertions) / \
305 (masterdocument.size + 0.5 * (deletions - insertions))
306 self.uptodate_percentage = 100 - int (outdateness_percentage)
307 if self.uptodate_percentage > 100:
309 progress ("%s: strange uptodateness percentage %d %%, \
310 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
311 self.uptodate_percentage = alternative
312 elif self.uptodate_percentage < 1:
314 progress ("%s: strange uptodateness percentage %d %%, \
315 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
316 self.uptodate_percentage = alternative
318 def get_level (self):
319 return texi_level ['top']
321 def completeness (self, formats=['long'], translated=False):
323 translation = self.translation
325 translation = lambda x: x
327 if isinstance (formats, str):
329 p = self.translation_percentage
331 status = 'not translated'
333 status = 'fully translated'
335 status = 'partially translated'
336 return dict ([(f, translation (format_table[status][f]) % locals())
339 def uptodateness (self, formats=['long'], translated=False):
341 translation = self.translation
343 translation = lambda x: x
345 if isinstance (formats, str):
347 p = self.uptodate_percentage
351 status = 'up to date'
356 if f == 'color' and p != None:
357 l['color'] = percentage_color (p)
359 l[f] = translation (format_table[status][f]) % locals ()
362 def gdp_status (self):
364 return self.translation (format_table['post-GDP'])
366 return self.translation (format_table['pre-GDP'])
368 def short_texi_status (self, markup):
369 s = ' <td title="%(filename)s">' % self.__dict__
370 if self.partially_translated:
371 s += '<br>\n '.join (self.translators) + '<br>\n'
374 '<br>\n '.join (self.checkers) + '</small><br>\n'
376 c = self.completeness (['color', 'long'])
377 s += ' <span style="background-color: #%(color)s">\
378 %(long)s</span><br>\n' % c
380 if self.partially_translated:
381 u = self.uptodateness (['vague', 'color'])
382 s += ' <span style="background-color: #%(color)s">\
383 %(vague)s</span><br>\n' % u
388 def text_status (self):
389 s = self.completeness ('abbr')['abbr'] + ' '
391 if self.partially_translated:
392 s += self.uptodateness ('abbr')['abbr'] + ' '
395 def texi_status (self, markup, numbering=SectionNumber ()):
396 s = '''<table align="center" border="2">
398 <th>%s</th>''' % self.print_title (numbering)
399 s += ''.join ([' <th>%s</th>\n' % self.translation (h)
400 for h in detailed_status_heads])
402 s += (' <tr align="left">\n <td title="%%(filename)s">%s<br>(%d)</td>\n'
403 % (self.translation (section_titles_string),
404 sum (self.masterdocument.word_count))) % self.__dict__
405 s += self.texi_body (markup, numbering)
406 s += '</table>\n<p></p>\n'
409 def texi_body (self, markup, numbering):
410 return (self.texi_translators (markup)
411 + self.texi_completeness (markup)
412 + self.texi_uptodateness (markup)
413 + self.texi_gdp (markup)
414 + self.texi_translations (markup, numbering))
416 def texi_translators (self, markup):
417 if self.partially_translated:
418 return (' <td>' + '<br>\n '.join (self.translators) + '</td>\n'
419 + ' <td>' + '<br>\n '.join (self.checkers) + '</td>\n')
420 return ' <td></td>\n' * 2
422 def texi_completeness (self, markup):
423 c = self.completeness (['color', 'short'], translated=True)
424 return ' <td><span style="background-color: #%(color)s">\
425 %(short)s</span></td>\n' % {'color': c['color'],
428 def texi_uptodateness (self, markup):
429 if self.partially_translated:
430 u = self.uptodateness (['short', 'color'], translated=True)
431 return ' <td><span style="background-color: #%(color)s">\
432 %(short)s</span></td>\n' % {'color': u['color'],
434 return ' <td></td>\n'
436 def texi_gdp (self, markup):
437 return ' <td>' + self.gdp_status () + '</td>\n </tr>\n'
439 def texi_translations (self, markup, numbering):
440 return ''.join ([i.translations[self.language].texi_status (markup, numbering)
441 for i in self.masterdocument.includes
442 if self.language in i.translations])
444 class IncludedTranslatedTelyDocument (TranslatedTelyDocument):
445 get_level = TelyDocument.get_level
446 def texi_status (self, markup, numbering=SectionNumber ()):
447 if self.title != 'Untitled':
448 return ((' <tr align="left">\n <td title="%%(filename)s">%s<br>(%d)</td>\n'
449 % (self.print_title (numbering),
450 sum (self.masterdocument.word_count))) % self.__dict__
451 + self.texi_body (markup, numbering))
454 class UntranslatedTelyDocument (TranslatedTelyDocument):
455 def __init__ (self, filename, masterdocument, parent_translation=None):
456 if filename[2] == '/':
457 self.language = filename[:2]
458 TranslatedTelyDocument.__init__ (self, filename, masterdocument, parent_translation)
460 class IncludedUntranslatedTelyDocument (UntranslatedTelyDocument, IncludedTranslatedTelyDocument):
461 get_level = TelyDocument.get_level
463 class MasterTelyDocument (TelyDocument):
466 parent_translations=dict ([(lang, None)
467 for lang in langdefs.LANGDICT])):
468 TelyDocument.__init__ (self, filename)
469 self.size = len (self.contents)
470 self.word_count = tely_word_count (self.contents)
471 self.translations = {}
473 if not self.language or self.language == 'en':
474 languages = [x for x in parent_translations.keys () if x != 'en']
475 self.translations = dict ([x for x in
476 [(lang, self.translated_factory (os.path.join (lang, self.filename),
477 parent_translations.get (lang)))
478 for lang in languages]
480 if self.translations:
481 self.includes = [IncludedMasterTelyDocument (f, self.translations)
482 for f in self.included_files]
484 def get_level (self):
485 return texi_level ['top']
487 def translated_factory (self, filename, parent):
488 if os.path.exists (filename):
489 return TranslatedTelyDocument (filename, self, parent)
492 def update_word_counts (self, s):
493 s = update_word_count (s, self.filename, sum (self.word_count))
494 for i in self.includes:
495 s = i.update_word_counts (s)
498 def texi_status (self, markup, numbering=SectionNumber ()):
499 s = '''<table align="center" border="2">
501 <th>%s</th>''' % self.print_title (numbering)
502 s += ''.join ([' <th>%s</th>\n' % l for l in sorted (self.translations.keys ())])
504 s += (' <tr align="left">\n <td title="%%(filename)s">Section titles<br>(%d)</td>\n'
505 % sum (self.word_count)) % self.__dict__
506 s += self.texi_body (markup, numbering)
507 s += '</table>\n<p></p>\n'
510 def texi_body (self, markup, numbering):
511 return (''.join ([self.translations[k].short_texi_status (markup)
512 for k in sorted (self.translations.keys ())])
514 + ''.join ([i.texi_status (markup, numbering) for i in self.includes]))
516 def text_status (self, markup, numbering=SectionNumber (), colspec=[48,12]):
517 s = (self.print_title (numbering) + ' ').ljust (colspec[0])
518 s += ''.join (['%s'.ljust (colspec[1]) % l
519 for l in sorted (self.translations.keys ())])
521 s += ('Section titles (%d)' % \
522 sum (self.word_count)).ljust (colspec[0])
523 s += self.text_body (markup, numbering, colspec)
527 def text_body (self, markup, numbering, colspec):
528 return (''.join ([self.translations[k].text_status ().ljust(colspec[1])
529 for k in sorted (self.translations.keys ())])
531 + ''.join ([i.text_status (markup, numbering) for i in self.includes]))
533 class IncludedMasterTelyDocument (MasterTelyDocument):
534 get_level = TelyDocument.get_level
536 def translated_factory (self, filename, parent):
537 if os.path.exists (filename):
538 return IncludedTranslatedTelyDocument (filename, self, parent)
539 return IncludedUntranslatedTelyDocument (filename, self, parent)
541 def texi_status (self, markup, numbering=SectionNumber ()):
542 if self.title != 'Untitled':
543 return ((' <tr align="left">\n <td title=%%(filename)s>%s<br>(%d)</td>\n'
544 % (self.print_title (numbering), sum (self.word_count))) % self.__dict__
545 + self.texi_body (markup, numbering))
548 def text_status (self, markup, numbering=SectionNumber (), colspec=[48,12]):
549 if self.title != 'Untitled':
551 % (self.print_title (numbering), sum (self.word_count)))
552 + self.text_body (markup, numbering, colspec)
557 update_category_word_counts_re = re.compile (r'(?ms)^-(\d+)-(.*?\n)\d+ *total')
559 counts_re = re.compile (r'(?m)^(\d+) ')
561 def update_category_word_counts_sub (m):
562 return ('-' + m.group (1) + '-' + m.group (2)
564 for c in counts_re.findall (m.group (2))])).ljust (6)
568 # main () starts here-abouts
570 progress ("Reading documents...")
573 buildlib.read_pipe ("git ls-files | grep -E '[^/]*/?[^/]*[.](tely|texi)$'")[0].splitlines ()
575 master_docs = [MasterTelyDocument (os.path.normpath (filename))
576 for filename in master_files]
577 master_docs = [doc for doc in master_docs if doc.translations]
579 enabled_languages = [l for l in langdefs.LANGDICT
580 if langdefs.LANGDICT[l].enabled
583 progress ("Generating status pages...")
585 date_time = buildlib.read_pipe ('LANG= date -u')[0]
587 markup = HTMLMarkup ()
588 main_status_body = last_updated_string % date_time
589 main_status_body += '\n'.join ([doc.texi_status (markup) for doc in master_docs])
591 texi_header = '''@c -*- coding: utf-8; mode: texinfo; -*-
592 @c This file was generated by translation-status.py -- DO NOT EDIT!
594 Translation of GIT committish: 0
598 Translation status currently only available in HTML.
609 main_status_page = texi_header % locals () + main_status_body + texi_footer
611 open ('translations.itexi', 'w').write (main_status_page)
613 for l in enabled_languages:
614 date_time = buildlib.read_pipe ('LANG=%s date -u' % l)[0]
615 updated = translation[l] (last_updated_string) % date_time
616 texi_status = '\n'.join ([doc.translations[l].texi_status (markup)
617 for doc in master_docs
618 if l in doc.translations])
619 lang_status_page = texi_header + updated + texi_status + texi_footer
620 open (os.path.join (l, 'translations.itexi'), 'w').write (lang_status_page)
622 main_status_txt = '''Documentation translations status
625 FT = fully translated
629 main_status_txt += '\n'.join ([doc.text_status (markup) for doc in master_docs])
631 status_txt_file = 'out/translations-status.txt'
632 progress ("Writing %s..." % status_txt_file)
633 open (status_txt_file, 'w').write (main_status_txt)
635 translation_instructions_file = 'contributor/doc-translation-list.itexi'
636 progress ("Updating %s..." % translation_instructions_file)
637 translation_instructions = open (translation_instructions_file).read ()
639 for doc in master_docs:
640 translation_instructions = doc.update_word_counts (translation_instructions)
642 for html_file in re.findall (r'(?m)^\d+ *(\S+?\.html\S*?)(?: |$)',
643 translation_instructions):
644 word_count = sgml_word_count (open (html_file).read ())
645 translation_instructions = update_word_count (translation_instructions,
649 for po_file in re.findall (r'(?m)^\d+ *(\S+?\.po\S*?)(?: |$)',
650 translation_instructions):
651 word_count = po_word_count (open (po_file).read ())
652 translation_instructions = update_word_count (translation_instructions,
656 translation_instructions = \
657 update_category_word_counts_re.sub (update_category_word_counts_sub,
658 translation_instructions)
660 open (translation_instructions_file, 'w').write (translation_instructions)