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 ('^@(top|chapter|(?: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\s+[tT]ranslators?\s*:\s*(.*?)$', re.M | re.I)
53 # FIXME: use revision: (or proofreading:?)
54 checkers_re = re.compile (r'^@c\s+Translation\s*checkers\s*:\s*(.*?)$',
56 status_re = re.compile (r'^@c\s+Translation\s*status\s*:\s*(.*?)$', re.M | re.I)
57 post_gdp_re = re.compile ('post.GDP', re.I)
58 untranslated_node_str = '@untranslated'
59 skeleton_str = '-- SKELETON FILE --'
61 section_titles_string = _doc ('Section titles')
62 last_updated_string = _doc (' <p><i>Last updated %s</i></p>\n')
63 detailed_status_heads = [_doc ('Translators'), _doc ('Translation checkers'),
64 _doc ('Translated'), _doc ('Up to date'),
67 'not translated': {'color':'d0f0f8', 'short':_doc ('no'), 'abbr':'NT',
68 'long':_doc ('not translated')},
69 'partially translated': {'color':'dfef77',
70 'short':_doc ('partially (%(p)d %%)'),
72 'long':_doc ('partially translated (%(p)d %%)')},
73 'fully translated': {'color':'1fff1f', 'short':_doc ('yes'), 'abbr':'FT',
74 'long': _doc ('translated')},
75 'up to date': {'short':_doc ('yes'), 'long':_doc ('up to date'),
76 'abbr':'100%%', 'vague':_doc ('up to date')},
77 'outdated': {'short':_doc ('partially'), 'abbr':'%(p)d%%',
78 'vague':_doc ('partially up to date')},
79 'N/A': {'short':_doc ('N/A'), 'abbr':'N/A', 'color':'d587ff', 'vague':''},
80 'pre-GDP':_doc ('pre-GDP'),
81 'post-GDP':_doc ('post-GDP')
85 # (Unumbered/Numbered/Lettered, level)
87 'unnumbered': ('u', 1),
88 'unnumberedsec': ('u', 2),
89 'unnumberedsubsec': ('u', 3),
92 'subsection': ('n', 3),
94 'appendixsec': ('l', 2),
97 appendix_number_trans = string.maketrans ('@ABCDEFGHIJKLMNOPQRSTUVWXY',
98 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
100 class SectionNumber (object):
102 self.__data = [[0,'u']]
104 def __increase_last_index (self):
105 type = self.__data[-1][1]
107 self.__data[-1][0] = \
108 self.__data[-1][0].translate (appendix_number_trans)
110 self.__data[-1][0] += 1
113 if self.__data[-1][1] == 'u':
115 return '.'.join ([str (i[0]) for i in self.__data if i[1] != 'u']) + ' '
117 def increase (self, (type, level)):
119 self.__data = [[0,'u']]
120 while level + 1 < len (self.__data):
122 if level + 1 > len (self.__data):
123 self.__data.append ([0, type])
125 self.__data[-1][0] = '@'
126 if type == self.__data[-1][1]:
127 self.__increase_last_index ()
129 self.__data[-1] = ([0, type])
131 self.__data[-1][0] = 'A'
133 self.__data[-1][0] = 1
134 return self.format ()
137 def percentage_color (percent):
140 c = [hex (int (3 * p * b + (1 - 3 * p) * a))[2:]
141 for (a, b) in [(0xff, 0xff), (0x5c, 0xa6), (0x5c, 0x4c)]]
143 c = [hex (int ((3 * p - 1) * b + (2 - 3 * p) * a))[2:]
144 for (a, b) in [(0xff, 0xff), (0xa6, 0xff), (0x4c, 0x3d)]]
146 c = [hex (int ((3 * p - 2) * b + 3 * (1 - p) * a))[2:]
147 for (a, b) in [(0xff, 0x1f), (0xff, 0xff), (0x3d, 0x1f)]]
151 def update_word_count (text, filename, word_count):
152 return re.sub (r'(?m)^(\d+) *' + filename,
153 str (word_count).ljust (6) + filename,
156 po_msgid_re = re.compile (r'^msgid "(.*?)"(?:\n"(.*?)")*', re.M)
158 def po_word_count (po_content):
159 s = ' '.join ([''.join (t) for t in po_msgid_re.findall (po_content)])
160 return len (space_re.split (s))
162 sgml_tag_re = re.compile (r'<.*?>', re.S)
164 def sgml_word_count (sgml_doc):
165 s = sgml_tag_re.sub ('', sgml_doc)
166 return len (space_re.split (s))
168 def tely_word_count (tely_doc):
170 Calculate word count of a Texinfo document node by node.
172 Take string tely_doc as an argument.
173 Return a list of integers.
175 Texinfo comments and @lilypond blocks are not included in word counts.
177 tely_doc = comments_re.sub ('', tely_doc)
178 tely_doc = lilypond_re.sub ('', tely_doc)
179 nodes = node_re.split (tely_doc)
180 return [len (space_re.split (n)) for n in nodes]
183 class TelyDocument (object):
184 def __init__ (self, filename):
185 self.filename = filename
186 self.contents = open (filename).read ()
187 self.top = os.path.splitext (filename)[1] in ['.tely', '.texi']
188 ## record title and sectionning level of first Texinfo section
189 self.sectioning = 'unnumbered'
190 self.title = 'Untitled'
191 m = title_re.search (self.contents)
193 self.sectioning = m.group (1)
194 if self.sectioning == 'top':
195 self.sectioning = 'unnumbered'
196 self.title = m.group (2)
197 self.level = texi_level [self.sectioning]
199 m = language_re.search (self.contents)
201 self.language = m.group (1)
203 included_files = [os.path.join (os.path.dirname (filename), t)
204 for t in include_re.findall (self.contents)]
205 self.included_files = [p for p in included_files if os.path.exists (p)]
207 def print_title (self, section_number):
208 return section_number.increase (self.level) + self.title
211 class TranslatedTelyDocument (TelyDocument):
212 def __init__ (self, filename, masterdocument, parent_translation=None):
213 TelyDocument.__init__ (self, filename)
215 self.masterdocument = masterdocument
216 if not hasattr (self, 'language'):
218 if not self.language and parent_translation:
219 self.language = parent_translation.__dict__.get ('language', '')
220 if self.language == 'en':
221 print filename + ': language en specified: set @documentlanguage', self.filename[:2]
223 if not self.language and filename[2] == '/':
224 print filename + ': no language specified: add @documentlanguage', self.filename[:2]
225 self.language = filename[:2]
227 self.translation = translation[self.language]
229 self.translation = lambda x: x
230 self.title = self.translation (self.title)
232 ## record authoring information
233 self.translators = []
234 if parent_translation:
235 self.translators = parent_translation.__dict__.get ('translators', [])
236 m = translators_re.findall (self.contents)
238 self.translators = [n.strip () for n in
239 reduce (operator.add, [n.split (',') for n in m])]
240 if (not self.translators
241 and not 'macros.itexi' in self.filename):
242 error ('%s: no translator name found, \nplease \
243 specify at least one in the master file as a line containing\n\
244 @c Translators: FirstName1 LastName1, FirstName2 LastName2' % self.filename)
246 m = checkers_re.findall (self.contents)
248 self.checkers = [n.strip () for n in
249 reduce (operator.add, [n.split (',') for n in m])]
250 if not self.checkers and isinstance (parent_translation, TranslatedTelyDocument):
251 self.checkers = parent_translation.checkers
253 ## check whether translation is pre- or post-GDP
254 m = status_re.search (self.contents)
256 self.post_gdp = bool (post_gdp_re.search (m.group (1)))
258 self.post_gdp = False
260 ## record which parts (nodes) of the file are actually translated
261 self.partially_translated = not skeleton_str in self.contents
262 nodes = node_re.split (self.contents)
263 self.translated_nodes = [not untranslated_node_str in n for n in nodes]
265 ## calculate translation percentage
266 master_total_word_count = sum (masterdocument.word_count)
267 translation_word_count = \
268 sum ([masterdocument.word_count[k] * self.translated_nodes[k]
269 for k in range (min (len (masterdocument.word_count),
270 len (self.translated_nodes)))])
271 self.translation_percentage = \
272 100 * translation_word_count / master_total_word_count
274 ## calculate how much the file is outdated
275 (diff_string, git_error) = \
276 buildlib.check_translated_doc (masterdocument.filename, self.filename, self.contents)
278 sys.stderr.write ('warning: %s: %s' % (self.filename, git_error))
279 self.uptodate_percentage = None
281 diff = diff_string.splitlines ()
282 insertions = sum ([len (l) - 1 for l in diff
283 if l.startswith ('+')
284 and not l.startswith ('+++')])
285 deletions = sum ([len (l) - 1 for l in diff
286 if l.startswith ('-')
287 and not l.startswith ('---')])
288 outdateness_percentage = 50.0 * (deletions + insertions) / \
289 (masterdocument.size + 0.5 * (deletions - insertions))
290 self.uptodate_percentage = 100 - int (outdateness_percentage)
291 if self.uptodate_percentage > 100:
293 progress ("%s: strange uptodateness percentage %d %%, \
294 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
295 self.uptodate_percentage = alternative
296 elif self.uptodate_percentage < 1:
298 progress ("%s: strange uptodateness percentage %d %%, \
299 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
300 self.uptodate_percentage = alternative
302 def completeness (self, formats=['long'], translated=False):
304 translation = self.translation
306 translation = lambda x: x
308 if isinstance (formats, str):
310 p = self.translation_percentage
312 status = 'not translated'
314 status = 'fully translated'
316 status = 'partially translated'
317 return dict ([(f, translation (format_table[status][f]) % locals())
320 def uptodateness (self, formats=['long'], translated=False):
322 translation = self.translation
324 translation = lambda x: x
326 if isinstance (formats, str):
328 p = self.uptodate_percentage
332 status = 'up to date'
337 if f == 'color' and p != None:
338 l['color'] = percentage_color (p)
340 l[f] = translation (format_table[status][f]) % locals ()
343 def gdp_status (self):
345 return self.translation (format_table['post-GDP'])
347 return self.translation (format_table['pre-GDP'])
349 def short_texi_status (self):
351 if self.partially_translated:
352 s += '<br>\n '.join (self.translators) + '<br>\n'
355 '<br>\n '.join (self.checkers) + '</small><br>\n'
357 c = self.completeness (['color', 'long'])
358 s += ' <span style="background-color: #%(color)s">\
359 %(long)s</span><br>\n' % c
361 if self.partially_translated:
362 u = self.uptodateness (['vague', 'color'])
363 s += ' <span style="background-color: #%(color)s">\
364 %(vague)s</span><br>\n' % u
369 def text_status (self):
370 s = self.completeness ('abbr')['abbr'] + ' '
372 if self.partially_translated:
373 s += self.uptodateness ('abbr')['abbr'] + ' '
376 def texi_status (self, numbering=SectionNumber ()):
377 if self.title == 'Untitled':
381 s = '''<table align="center" border="2">
383 <th>%s</th>''' % self.print_title (numbering)
384 s += ''.join ([' <th>%s</th>\n' % self.translation (h)
385 for h in detailed_status_heads])
387 s += ' <tr align="left">\n <td>%s<br>(%d)</td>\n' \
388 % (self.translation (section_titles_string),
389 sum (self.masterdocument.word_count))
392 s = ''' <!-- no table 388
393 filename: %(filename)s
394 sectioning: %(sectioning)s
396 !-->''' % self.__dict__
397 s += ' <tr align="left">\n <td>%s<br>(%d)</td>\n' \
398 % (self.print_title (numbering),
399 sum (self.masterdocument.word_count))
401 if self.partially_translated:
402 s += ' <td>' + '<br>\n '.join (self.translators) + '</td>\n'
403 s += ' <td>' + '<br>\n '.join (self.checkers) + '</td>\n'
405 s += ' <td></td>\n' * 2
407 c = self.completeness (['color', 'short'], translated=True)
408 s += ' <td><span style="background-color: #%(color)s">\
409 %(short)s</span></td>\n' % {'color': c['color'],
412 if self.partially_translated:
413 u = self.uptodateness (['short', 'color'], translated=True)
414 s += ' <td><span style="background-color: #%(color)s">\
415 %(short)s</span></td>\n' % {'color': u['color'],
420 s += ' <td>' + self.gdp_status () + '</td>\n </tr>\n'
421 s += ''.join ([i.translations[self.language].texi_status (numbering)
422 for i in self.masterdocument.includes
423 if self.language in i.translations])
426 s += '</table>\n<p></p>\n'
429 class MasterTelyDocument (TelyDocument):
432 parent_translations=dict ([(lang, None)
433 for lang in langdefs.LANGDICT])):
434 TelyDocument.__init__ (self, filename)
435 self.sectioning = 'top'
436 self.title = 'Untitled'
437 m = title_re.search (self.contents)
439 self.title = m.group (2)
440 self.level = texi_level [self.sectioning]
442 self.size = len (self.contents)
443 self.word_count = tely_word_count (self.contents)
444 translations = dict ([(lang, os.path.join (lang, filename))
445 for lang in langdefs.LANGDICT])
446 self.translations = \
448 TranslatedTelyDocument (translations[lang],
449 self, parent_translations.get (lang)))
450 for lang in langdefs.LANGDICT
451 if os.path.exists (translations[lang])])
452 if self.translations:
453 self.includes = [MasterTelyDocument (f, self.translations)
454 for f in self.included_files]
458 def update_word_counts (self, s):
459 s = update_word_count (s, self.filename, sum (self.word_count))
460 for i in self.includes:
461 s = i.update_word_counts (s)
464 def texi_status (self, numbering=SectionNumber ()):
465 if self.title == 'Untitled' or not self.translations:
468 s = '''<table align="center" border="2">
470 <th>%s</th>''' % self.print_title (numbering)
471 s += ''.join ([' <th>%s</th>\n' % l for l in self.translations])
473 s += ' <tr align="left">\n <td>Section titles<br>(%d)</td>\n' \
474 % sum (self.word_count)
476 else: # if self is an included file
477 s = ''' <!-- no table 462
478 filename: %(filename)s
479 sectioning: %(sectioning)s
481 !-->''' % self.__dict__
482 s += ' <tr align="left">\n <td>%s<br>(%d)</td>\n' \
483 % (self.print_title (numbering), sum (self.word_count))
485 s += ''.join ([t.short_texi_status ()
486 for t in self.translations.values ()])
488 s += ''.join ([i.texi_status (numbering) for i in self.includes])
491 s += '</table>\n<p></p>\n'
494 def text_status (self, numbering=SectionNumber (), colspec=[48,12]):
495 if self.title == 'Untitled' or not self.translations:
500 s += (self.print_title (numbering) + ' ').ljust (colspec[0])
501 s += ''.join (['%s'.ljust (colspec[1]) % l
502 for l in self.translations])
504 s += ('Section titles (%d)' % \
505 sum (self.word_count)).ljust (colspec[0])
509 % (self.print_title (numbering), sum (self.word_count))
510 s = s.ljust (colspec[0])
512 s += ''.join ([t.text_status ().ljust(colspec[1])
513 for t in self.translations.values ()])
515 s += ''.join ([i.text_status (numbering) for i in self.includes])
522 update_category_word_counts_re = re.compile (r'(?ms)^-(\d+)-(.*?\n)\d+ *total')
524 counts_re = re.compile (r'(?m)^(\d+) ')
526 def update_category_word_counts_sub (m):
527 return ('-' + m.group (1) + '-' + m.group (2)
529 for c in counts_re.findall (m.group (2))])).ljust (6)
533 # main () starts here-abouts
535 progress ("Reading documents...")
538 buildlib.read_pipe ("git ls-files | grep -E '[^/]*/?[^/]*[.](tely|texi)$'")[0].splitlines ()
540 master_docs = [MasterTelyDocument (os.path.normpath (filename))
541 for filename in master_files]
542 master_docs = [doc for doc in master_docs if doc.translations]
544 enabled_languages = [l for l in langdefs.LANGDICT
545 if langdefs.LANGDICT[l].enabled
548 progress ("Generating status pages...")
550 date_time = buildlib.read_pipe ('LANG= date -u')[0]
552 main_status_body = last_updated_string % date_time
553 main_status_body += '\n'.join ([doc.texi_status () for doc in master_docs])
555 ats = 'Actual translation status'
558 @unnumberedsubsubsec %(ats)s
561 texi_header = '''@c -*- coding: utf-8; mode: texinfo; -*-
562 @c This file was generated by translation-status.py -- DO NOT EDIT!
567 Translation status currently only available in HTML.
578 main_status_page = texi_header % locals () + main_status_body + texi_footer
580 open ('translations.itexi', 'w').write (main_status_page)
582 for l in enabled_languages:
583 lats = translation[l] (ats)
588 date_time = buildlib.read_pipe ('LANG=%s date -u' % l)[0]
589 updated = translation[l] (last_updated_string) % date_time
591 node += '''@translationof %(ats)s
593 texi_status = '\n'.join ([doc.translations[l].texi_status ()
594 for doc in master_docs
595 if l in doc.translations])
596 lang_status_page = texi_header % locals () + updated + texi_status + texi_footer
597 open (os.path.join (l, 'translations.itexi'), 'w').write (lang_status_page)
599 main_status_txt = '''Documentation translations status
602 FT = fully translated
606 main_status_txt += '\n'.join ([doc.text_status () for doc in master_docs])
608 status_txt_file = 'out/translations-status.txt'
609 progress ("Writing %s..." % status_txt_file)
610 open (status_txt_file, 'w').write (main_status_txt)
612 translation_instructions_file = 'contributor/doc-translation-list.itexi'
613 progress ("Updating %s..." % translation_instructions_file)
614 translation_instructions = open (translation_instructions_file).read ()
616 for doc in master_docs:
617 translation_instructions = doc.update_word_counts (translation_instructions)
619 for html_file in re.findall (r'(?m)^\d+ *(\S+?\.html\S*?)(?: |$)',
620 translation_instructions):
621 word_count = sgml_word_count (open (html_file).read ())
622 translation_instructions = update_word_count (translation_instructions,
626 for po_file in re.findall (r'(?m)^\d+ *(\S+?\.po\S*?)(?: |$)',
627 translation_instructions):
628 word_count = po_word_count (open (po_file).read ())
629 translation_instructions = update_word_count (translation_instructions,
633 translation_instructions = \
634 update_category_word_counts_re.sub (update_category_word_counts_sub,
635 translation_instructions)
637 open (translation_instructions_file, 'w').write (translation_instructions)