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):
184 def entity (self, name, string='', attributes=[]):
185 attr_list = ''.join ([' %s="%s"' % x for x in attributes])
186 return '<%(name)s%(attr_list)s>%(string)s</%(name)s>' % locals ()
187 def paragraph (self, string=''):
188 return self.entity ('p')
189 def table (self, string):
190 return self.entity ('table', string, [('align', 'center'), ('border', '2')])
192 class TelyDocument (object):
193 def __init__ (self, filename):
194 self.filename = filename
195 self.contents = 'GIT committish: 0'
196 if os.path.exists (filename):
197 self.contents = open (filename).read ()
198 ## record title and sectionning level of first Texinfo section
199 self.sectioning = 'unnumbered'
200 self.title = 'Untitled'
201 m = title_re.search (self.contents)
203 self.sectioning = m.group (1)
204 self.title = m.group (2)
206 if not hasattr (self, 'language'):
208 m = language_re.search (self.contents)
210 self.language = m.group (1)
212 dir = os.path.dirname (filename).split ('/')[0]
217 included_files = [dir + t
218 for t in include_re.findall (self.contents)]
219 self.included_files = [p for p in included_files if os.path.exists (p)]
221 def get_level (self):
222 return texi_level [self.sectioning]
224 def print_title (self, section_number):
225 if not hasattr (self, 'level'):
226 self.level = self.get_level ()
227 return section_number.increase (self.level) + self.title
230 class TranslatedTelyDocument (TelyDocument):
231 def __init__ (self, filename, masterdocument, parent_translation=None):
232 TelyDocument.__init__ (self, filename)
233 self.masterdocument = masterdocument
234 if not hasattr (self, 'language'):
236 if not self.language and parent_translation:
237 self.language = parent_translation.__dict__.get ('language', '')
238 if self.language == 'en':
239 print filename + ': language en specified: set @documentlanguage', self.filename[:2]
241 if not self.language and filename[2] == '/':
242 print filename + ': no language specified: add @documentlanguage', self.filename[:2]
243 self.language = filename[:2]
245 self.translation = translation[self.language]
247 self.translation = lambda x: x
248 self.title = self.translation (self.title)
250 ## record authoring information
251 self.translators = ['']
252 if parent_translation:
253 self.translators = parent_translation.__dict__.get ('translators', [''])
254 m = translators_re.findall (self.contents)
256 self.translators = [n.strip () for n in
257 reduce (operator.add, [n.split (',') for n in m])]
258 if self.language != self.filename[:2]:
259 print 'Barf:', self.filename
261 if (not isinstance (self, UntranslatedTelyDocument)
262 and (not self.translators or not self.translators[0])
263 and not 'macros.itexi' in self.filename):
264 error (self.filename + ''': error: no translator name found
265 please specify one ore more lines in the master file
266 @c Translator: FirstName LastName[, FirstName LastName]..''')
268 m = checkers_re.findall (self.contents)
270 self.checkers = [n.strip () for n in
271 reduce (operator.add, [n.split (',') for n in m])]
272 if not self.checkers and isinstance (parent_translation, TranslatedTelyDocument):
273 self.checkers = parent_translation.checkers
275 ## check whether translation is pre- or post-GDP
276 m = status_re.search (self.contents)
278 self.post_gdp = bool (post_gdp_re.search (m.group (1)))
280 self.post_gdp = False
282 ## record which parts (nodes) of the file are actually translated
283 self.partially_translated = not skeleton_str in self.contents
284 nodes = node_re.split (self.contents)
285 self.translated_nodes = [not untranslated_node_str in n for n in nodes]
287 ## calculate translation percentage
288 master_total_word_count = sum (masterdocument.word_count)
289 translation_word_count = \
290 sum ([masterdocument.word_count[k] * self.translated_nodes[k]
291 for k in range (min (len (masterdocument.word_count),
292 len (self.translated_nodes)))])
293 self.translation_percentage = \
294 100 * translation_word_count / master_total_word_count
296 ## calculate how much the file is outdated
297 (diff_string, git_error) = \
298 buildlib.check_translated_doc (masterdocument.filename, self.filename, self.contents)
300 sys.stderr.write ('warning: %s: %s' % (self.filename, git_error))
301 self.uptodate_percentage = None
303 diff = diff_string.splitlines ()
304 insertions = sum ([len (l) - 1 for l in diff
305 if l.startswith ('+')
306 and not l.startswith ('+++')])
307 deletions = sum ([len (l) - 1 for l in diff
308 if l.startswith ('-')
309 and not l.startswith ('---')])
310 outdateness_percentage = 50.0 * (deletions + insertions) / \
311 (masterdocument.size + 0.5 * (deletions - insertions))
312 self.uptodate_percentage = 100 - int (outdateness_percentage)
313 if self.uptodate_percentage > 100:
315 progress ("%s: strange uptodateness percentage %d %%, \
316 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
317 self.uptodate_percentage = alternative
318 elif self.uptodate_percentage < 1:
320 progress ("%s: strange uptodateness percentage %d %%, \
321 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
322 self.uptodate_percentage = alternative
324 def get_level (self):
325 return texi_level ['top']
327 def completeness (self, formats=['long'], translated=False):
329 translation = self.translation
331 translation = lambda x: x
333 if isinstance (formats, str):
335 p = self.translation_percentage
337 status = 'not translated'
339 status = 'fully translated'
341 status = 'partially translated'
342 return dict ([(f, translation (format_table[status][f]) % locals())
345 def uptodateness (self, formats=['long'], translated=False):
347 translation = self.translation
349 translation = lambda x: x
351 if isinstance (formats, str):
353 p = self.uptodate_percentage
357 status = 'up to date'
362 if f == 'color' and p != None:
363 l['color'] = percentage_color (p)
365 l[f] = translation (format_table[status][f]) % locals ()
368 def gdp_status (self):
370 return self.translation (format_table['post-GDP'])
372 return self.translation (format_table['pre-GDP'])
374 def short_texi_status (self, markup):
375 s = ' <td title="%(filename)s">' % self.__dict__
376 if self.partially_translated:
377 s += '<br>\n '.join (self.translators) + '<br>\n'
380 '<br>\n '.join (self.checkers) + '</small><br>\n'
382 c = self.completeness (['color', 'long'])
383 s += ' <span style="background-color: #%(color)s">\
384 %(long)s</span><br>\n' % c
386 if self.partially_translated:
387 u = self.uptodateness (['vague', 'color'])
388 s += ' <span style="background-color: #%(color)s">\
389 %(vague)s</span><br>\n' % u
394 def text_status (self):
395 s = self.completeness ('abbr')['abbr'] + ' '
397 if self.partially_translated:
398 s += self.uptodateness ('abbr')['abbr'] + ' '
401 def texi_status (self, markup, numbering=SectionNumber ()):
402 s = '''<tr align="center">
403 <th>%s</th>''' % self.print_title (numbering)
404 s += ''.join ([' <th>%s</th>\n' % self.translation (h)
405 for h in detailed_status_heads])
407 s += (' <tr align="left">\n <td title="%%(filename)s">%s<br>(%d)</td>\n'
408 % (self.translation (section_titles_string),
409 sum (self.masterdocument.word_count))) % self.__dict__
410 s += self.texi_body (markup, numbering)
411 return markup.table (s) + markup.paragraph ()
413 def texi_body (self, markup, numbering):
414 return (self.texi_translators (markup)
415 + self.texi_completeness (markup)
416 + self.texi_uptodateness (markup)
417 + self.texi_gdp (markup)
418 + self.texi_translations (markup, numbering))
420 def texi_translators (self, markup):
421 if self.partially_translated:
422 return (' <td>' + '<br>\n '.join (self.translators) + '</td>\n'
423 + ' <td>' + '<br>\n '.join (self.checkers) + '</td>\n')
424 return ' <td></td>\n' * 2
426 def texi_completeness (self, markup):
427 c = self.completeness (['color', 'short'], translated=True)
428 return ' <td><span style="background-color: #%(color)s">\
429 %(short)s</span></td>\n' % {'color': c['color'],
432 def texi_uptodateness (self, markup):
433 if self.partially_translated:
434 u = self.uptodateness (['short', 'color'], translated=True)
435 return ' <td><span style="background-color: #%(color)s">\
436 %(short)s</span></td>\n' % {'color': u['color'],
438 return ' <td></td>\n'
440 def texi_gdp (self, markup):
441 return ' <td>' + self.gdp_status () + '</td>\n </tr>\n'
443 def texi_translations (self, markup, numbering):
444 return ''.join ([i.translations[self.language].texi_status (markup, numbering)
445 for i in self.masterdocument.includes
446 if self.language in i.translations])
448 class IncludedTranslatedTelyDocument (TranslatedTelyDocument):
449 get_level = TelyDocument.get_level
450 def texi_status (self, markup, numbering=SectionNumber ()):
451 if self.title != 'Untitled':
452 return ((' <tr align="left">\n <td title="%%(filename)s">%s<br>(%d)</td>\n'
453 % (self.print_title (numbering),
454 sum (self.masterdocument.word_count))) % self.__dict__
455 + self.texi_body (markup, numbering))
458 class UntranslatedTelyDocument (TranslatedTelyDocument):
459 def __init__ (self, filename, masterdocument, parent_translation=None):
460 if filename[2] == '/':
461 self.language = filename[:2]
462 TranslatedTelyDocument.__init__ (self, filename, masterdocument, parent_translation)
464 class IncludedUntranslatedTelyDocument (UntranslatedTelyDocument, IncludedTranslatedTelyDocument):
465 get_level = TelyDocument.get_level
467 class MasterTelyDocument (TelyDocument):
470 parent_translations=dict ([(lang, None)
471 for lang in langdefs.LANGDICT])):
472 TelyDocument.__init__ (self, filename)
473 self.size = len (self.contents)
474 self.word_count = tely_word_count (self.contents)
475 self.translations = {}
477 if not self.language or self.language == 'en':
478 languages = [x for x in parent_translations.keys () if x != 'en']
479 self.translations = dict ([x for x in
480 [(lang, self.translated_factory (os.path.join (lang, self.filename),
481 parent_translations.get (lang)))
482 for lang in languages]
484 if self.translations:
485 self.includes = [IncludedMasterTelyDocument (f, self.translations)
486 for f in self.included_files]
488 def get_level (self):
489 return texi_level ['top']
491 def translated_factory (self, filename, parent):
492 if os.path.exists (filename):
493 return TranslatedTelyDocument (filename, self, parent)
496 def update_word_counts (self, s):
497 s = update_word_count (s, self.filename, sum (self.word_count))
498 for i in self.includes:
499 s = i.update_word_counts (s)
502 def texi_status (self, markup, numbering=SectionNumber ()):
505 <th>%s</th>''' % self.print_title (numbering)
506 s += ''.join ([' <th>%s</th>\n' % l for l in sorted (self.translations.keys ())])
508 s += (' <tr align="left">\n <td title="%%(filename)s">Section titles<br>(%d)</td>\n'
509 % sum (self.word_count)) % self.__dict__
510 s += self.texi_body (markup, numbering)
511 return markup.table (s) + markup.paragraph ()
513 def texi_body (self, markup, numbering):
514 return (''.join ([self.translations[k].short_texi_status (markup)
515 for k in sorted (self.translations.keys ())])
517 + ''.join ([i.texi_status (markup, numbering) for i in self.includes]))
519 def text_status (self, markup, numbering=SectionNumber (), colspec=[48,12]):
520 s = (self.print_title (numbering) + ' ').ljust (colspec[0])
521 s += ''.join (['%s'.ljust (colspec[1]) % l
522 for l in sorted (self.translations.keys ())])
524 s += ('Section titles (%d)' % \
525 sum (self.word_count)).ljust (colspec[0])
526 s += self.text_body (markup, numbering, colspec)
530 def text_body (self, markup, numbering, colspec):
531 return (''.join ([self.translations[k].text_status ().ljust(colspec[1])
532 for k in sorted (self.translations.keys ())])
534 + ''.join ([i.text_status (markup, numbering) for i in self.includes]))
536 class IncludedMasterTelyDocument (MasterTelyDocument):
537 get_level = TelyDocument.get_level
539 def translated_factory (self, filename, parent):
540 if os.path.exists (filename):
541 return IncludedTranslatedTelyDocument (filename, self, parent)
542 return IncludedUntranslatedTelyDocument (filename, self, parent)
544 def texi_status (self, markup, numbering=SectionNumber ()):
545 if self.title != 'Untitled':
546 return ((' <tr align="left">\n <td title=%%(filename)s>%s<br>(%d)</td>\n'
547 % (self.print_title (numbering), sum (self.word_count))) % self.__dict__
548 + self.texi_body (markup, numbering))
551 def text_status (self, markup, numbering=SectionNumber (), colspec=[48,12]):
552 if self.title != 'Untitled':
554 % (self.print_title (numbering), sum (self.word_count)))
555 + self.text_body (markup, numbering, colspec)
560 update_category_word_counts_re = re.compile (r'(?ms)^-(\d+)-(.*?\n)\d+ *total')
562 counts_re = re.compile (r'(?m)^(\d+) ')
564 def update_category_word_counts_sub (m):
565 return ('-' + m.group (1) + '-' + m.group (2)
567 for c in counts_re.findall (m.group (2))])).ljust (6)
571 # main () starts here-abouts
573 progress ("Reading documents...")
576 buildlib.read_pipe ("git ls-files | grep -E '[^/]*/?[^/]*[.](tely|texi)$'")[0].splitlines ()
578 master_docs = [MasterTelyDocument (os.path.normpath (filename))
579 for filename in master_files]
580 master_docs = [doc for doc in master_docs if doc.translations]
582 enabled_languages = [l for l in langdefs.LANGDICT
583 if langdefs.LANGDICT[l].enabled
586 progress ("Generating status pages...")
588 date_time = buildlib.read_pipe ('LANG= date -u')[0]
590 markup = HTMLMarkup ()
591 main_status_body = last_updated_string % date_time
592 main_status_body += '\n'.join ([doc.texi_status (markup) for doc in master_docs])
594 texi_header = '''@c -*- coding: utf-8; mode: texinfo; -*-
595 @c This file was generated by translation-status.py -- DO NOT EDIT!
597 Translation of GIT committish: 0
601 Translation status currently only available in HTML.
612 main_status_page = texi_header % locals () + main_status_body + texi_footer
614 open ('translations.itexi', 'w').write (main_status_page)
616 for l in enabled_languages:
617 date_time = buildlib.read_pipe ('LANG=%s date -u' % l)[0]
618 updated = translation[l] (last_updated_string) % date_time
619 texi_status = '\n'.join ([doc.translations[l].texi_status (markup)
620 for doc in master_docs
621 if l in doc.translations])
622 lang_status_page = texi_header + updated + texi_status + texi_footer
623 open (os.path.join (l, 'translations.itexi'), 'w').write (lang_status_page)
625 main_status_txt = '''Documentation translations status
628 FT = fully translated
632 main_status_txt += '\n'.join ([doc.text_status (markup) for doc in master_docs])
634 status_txt_file = 'out/translations-status.txt'
635 progress ("Writing %s..." % status_txt_file)
636 open (status_txt_file, 'w').write (main_status_txt)
638 translation_instructions_file = 'contributor/doc-translation-list.itexi'
639 progress ("Updating %s..." % translation_instructions_file)
640 translation_instructions = open (translation_instructions_file).read ()
642 for doc in master_docs:
643 translation_instructions = doc.update_word_counts (translation_instructions)
645 for html_file in re.findall (r'(?m)^\d+ *(\S+?\.html\S*?)(?: |$)',
646 translation_instructions):
647 word_count = sgml_word_count (open (html_file).read ())
648 translation_instructions = update_word_count (translation_instructions,
652 for po_file in re.findall (r'(?m)^\d+ *(\S+?\.po\S*?)(?: |$)',
653 translation_instructions):
654 word_count = po_word_count (open (po_file).read ())
655 translation_instructions = update_word_count (translation_instructions,
659 translation_instructions = \
660 update_category_word_counts_re.sub (update_category_word_counts_sub,
661 translation_instructions)
663 open (translation_instructions_file, 'w').write (translation_instructions)