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]
181 class TelyDocument (object):
182 def __init__ (self, filename):
183 self.filename = filename
184 self.contents = 'GIT committish: 0'
185 if os.path.exists (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 self.title = m.group (2)
195 # This is all quite ugly and hairy. The original code worked
196 # with @top node detection and each manual had its own @top
197 # node. Not any more. Declaring .tely / .texi files to be
198 # @top sort of works...
200 self.sectioning = 'top'
201 self.level = texi_level [self.sectioning]
203 if not hasattr (self, 'language'):
205 m = language_re.search (self.contents)
207 self.language = m.group (1)
209 dir = os.path.dirname (filename).split ('/')[0]
214 included_files = [dir + t
215 for t in include_re.findall (self.contents)]
216 self.included_files = [p for p in included_files if os.path.exists (p)]
218 def print_title (self, section_number):
219 return section_number.increase (self.level) + self.title
222 class TranslatedTelyDocument (TelyDocument):
223 def __init__ (self, filename, masterdocument, parent_translation=None):
224 TelyDocument.__init__ (self, filename)
225 self.masterdocument = masterdocument
226 if not hasattr (self, 'language'):
228 if not self.language and parent_translation:
229 self.language = parent_translation.__dict__.get ('language', '')
230 if self.language == 'en':
231 print filename + ': language en specified: set @documentlanguage', self.filename[:2]
233 if not self.language and filename[2] == '/':
234 print filename + ': no language specified: add @documentlanguage', self.filename[:2]
235 self.language = filename[:2]
237 self.translation = translation[self.language]
239 self.translation = lambda x: x
240 self.title = self.translation (self.title)
242 ## record authoring information
243 self.translators = ['']
244 if parent_translation:
245 self.translators = parent_translation.__dict__.get ('translators', [''])
246 m = translators_re.findall (self.contents)
248 self.translators = [n.strip () for n in
249 reduce (operator.add, [n.split (',') for n in m])]
250 if self.language != self.filename[:2]:
251 print 'Barf:', self.filename
253 if (not isinstance (self, UntranslatedTelyDocument)
254 and (not self.translators or not self.translators[0])
255 and not 'macros.itexi' in self.filename):
256 error (self.filename + ''': error: no translator name found
257 please specify one ore more lines in the master file
258 @c Translator: FirstName LastName[, FirstName LastName]..''')
260 m = checkers_re.findall (self.contents)
262 self.checkers = [n.strip () for n in
263 reduce (operator.add, [n.split (',') for n in m])]
264 if not self.checkers and isinstance (parent_translation, TranslatedTelyDocument):
265 self.checkers = parent_translation.checkers
267 ## check whether translation is pre- or post-GDP
268 m = status_re.search (self.contents)
270 self.post_gdp = bool (post_gdp_re.search (m.group (1)))
272 self.post_gdp = False
274 ## record which parts (nodes) of the file are actually translated
275 self.partially_translated = not skeleton_str in self.contents
276 nodes = node_re.split (self.contents)
277 self.translated_nodes = [not untranslated_node_str in n for n in nodes]
279 ## calculate translation percentage
280 master_total_word_count = sum (masterdocument.word_count)
281 translation_word_count = \
282 sum ([masterdocument.word_count[k] * self.translated_nodes[k]
283 for k in range (min (len (masterdocument.word_count),
284 len (self.translated_nodes)))])
285 self.translation_percentage = \
286 100 * translation_word_count / master_total_word_count
288 ## calculate how much the file is outdated
289 (diff_string, git_error) = \
290 buildlib.check_translated_doc (masterdocument.filename, self.filename, self.contents)
292 sys.stderr.write ('warning: %s: %s' % (self.filename, git_error))
293 self.uptodate_percentage = None
295 diff = diff_string.splitlines ()
296 insertions = sum ([len (l) - 1 for l in diff
297 if l.startswith ('+')
298 and not l.startswith ('+++')])
299 deletions = sum ([len (l) - 1 for l in diff
300 if l.startswith ('-')
301 and not l.startswith ('---')])
302 outdateness_percentage = 50.0 * (deletions + insertions) / \
303 (masterdocument.size + 0.5 * (deletions - insertions))
304 self.uptodate_percentage = 100 - int (outdateness_percentage)
305 if self.uptodate_percentage > 100:
307 progress ("%s: strange uptodateness percentage %d %%, \
308 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
309 self.uptodate_percentage = alternative
310 elif self.uptodate_percentage < 1:
312 progress ("%s: strange uptodateness percentage %d %%, \
313 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
314 self.uptodate_percentage = alternative
316 def completeness (self, formats=['long'], translated=False):
318 translation = self.translation
320 translation = lambda x: x
322 if isinstance (formats, str):
324 p = self.translation_percentage
326 status = 'not translated'
328 status = 'fully translated'
330 status = 'partially translated'
331 return dict ([(f, translation (format_table[status][f]) % locals())
334 def uptodateness (self, formats=['long'], translated=False):
336 translation = self.translation
338 translation = lambda x: x
340 if isinstance (formats, str):
342 p = self.uptodate_percentage
346 status = 'up to date'
351 if f == 'color' and p != None:
352 l['color'] = percentage_color (p)
354 l[f] = translation (format_table[status][f]) % locals ()
357 def gdp_status (self):
359 return self.translation (format_table['post-GDP'])
361 return self.translation (format_table['pre-GDP'])
363 def short_texi_status (self):
364 s = ' <td title="%(filename)s">' % self.__dict__
365 if self.partially_translated:
366 s += '<br>\n '.join (self.translators) + '<br>\n'
369 '<br>\n '.join (self.checkers) + '</small><br>\n'
371 c = self.completeness (['color', 'long'])
372 s += ' <span style="background-color: #%(color)s">\
373 %(long)s</span><br>\n' % c
375 if self.partially_translated:
376 u = self.uptodateness (['vague', 'color'])
377 s += ' <span style="background-color: #%(color)s">\
378 %(vague)s</span><br>\n' % u
383 def text_status (self):
384 s = self.completeness ('abbr')['abbr'] + ' '
386 if self.partially_translated:
387 s += self.uptodateness ('abbr')['abbr'] + ' '
390 def texi_status (self, numbering=SectionNumber ()):
391 if self.title == 'Untitled':
395 s = '''<table align="center" border="2">
397 <th>%s</th>''' % self.print_title (numbering)
398 s += ''.join ([' <th>%s</th>\n' % self.translation (h)
399 for h in detailed_status_heads])
401 s += (' <tr align="left">\n <td title="%%(filename)s">%s<br>(%d)</td>\n'
402 % (self.translation (section_titles_string),
403 sum (self.masterdocument.word_count))) % self.__dict__
406 s = (' <tr align="left">\n <td title="%%(filename)s">%s<br>(%d)</td>\n'
407 % (self.print_title (numbering),
408 sum (self.masterdocument.word_count))) % self.__dict__
410 if self.partially_translated:
411 s += ' <td>' + '<br>\n '.join (self.translators) + '</td>\n'
412 s += ' <td>' + '<br>\n '.join (self.checkers) + '</td>\n'
414 s += ' <td></td>\n' * 2
416 c = self.completeness (['color', 'short'], translated=True)
417 s += ' <td><span style="background-color: #%(color)s">\
418 %(short)s</span></td>\n' % {'color': c['color'],
421 if self.partially_translated:
422 u = self.uptodateness (['short', 'color'], translated=True)
423 s += ' <td><span style="background-color: #%(color)s">\
424 %(short)s</span></td>\n' % {'color': u['color'],
429 s += ' <td>' + self.gdp_status () + '</td>\n </tr>\n'
430 s += ''.join ([i.translations[self.language].texi_status (numbering)
431 for i in self.masterdocument.includes
432 if self.language in i.translations])
435 s += '</table>\n<p></p>\n'
438 class UntranslatedTelyDocument (TranslatedTelyDocument):
439 def __init__ (self, filename, masterdocument, parent_translation=None):
440 if filename[2] == '/':
441 self.language = filename[:2]
442 TranslatedTelyDocument.__init__ (self, filename, masterdocument, parent_translation)
444 class MasterTelyDocument (TelyDocument):
447 parent_translations=dict ([(lang, None)
448 for lang in langdefs.LANGDICT])):
449 TelyDocument.__init__ (self, filename)
450 self.size = len (self.contents)
451 self.word_count = tely_word_count (self.contents)
452 self.translations = {}
454 translations = dict ([(lang, os.path.join (lang, filename))
455 for lang in langdefs.LANGDICT])
456 if not self.language or self.language == 'en':
457 languages = [x for x in parent_translations.keys () if x != 'en']
458 for lang in languages:
459 self.translations[lang] = self.translated_factory (translations[lang],
460 parent_translations.get (lang))
461 found[lang] = not isinstance (self.translations[lang], UntranslatedTelyDocument)
463 for lang in [x for x in langdefs.LANGDICT if x and x != 'en']:
464 if not found.get (lang, False):
465 del self.translations[lang]
467 if self.translations:
468 self.includes = [MasterTelyDocument (f, self.translations)
469 for f in self.included_files]
473 def translated_factory (self, filename, parent):
474 if os.path.exists (filename):
475 return TranslatedTelyDocument (filename, self, parent)
477 return UntranslatedTelyDocument (filename, self, parent)
479 def update_word_counts (self, s):
480 s = update_word_count (s, self.filename, sum (self.word_count))
481 for i in self.includes:
482 s = i.update_word_counts (s)
485 def texi_status (self, numbering=SectionNumber ()):
486 if self.title == 'Untitled' or not self.translations:
489 s = '''<table align="center" border="2">
491 <th>%s</th>''' % self.print_title (numbering)
492 s += ''.join ([' <th>%s</th>\n' % l for l in sorted (self.translations.keys ())])
494 s += (' <tr align="left">\n <td title="%%(filename)s">Section titles<br>(%d)</td>\n'
495 % sum (self.word_count)) % self.__dict__
497 else: # if self is an included file
498 s = (' <tr align="left">\n <td title=%%(filename)s>%s<br>(%d)</td>\n'
499 % (self.print_title (numbering), sum (self.word_count))) % self.__dict__
501 s += ''.join ([self.translations[k].short_texi_status ()
502 for k in sorted (self.translations.keys ())])
504 s += ''.join ([i.texi_status (numbering) for i in self.includes])
507 s += '</table>\n<p></p>\n'
510 def text_status (self, numbering=SectionNumber (), colspec=[48,12]):
511 if self.title == 'Untitled' or not self.translations:
516 s += (self.print_title (numbering) + ' ').ljust (colspec[0])
517 s += ''.join (['%s'.ljust (colspec[1]) % l
518 for l in sorted (self.translations.keys ())])
520 s += ('Section titles (%d)' % \
521 sum (self.word_count)).ljust (colspec[0])
525 % (self.print_title (numbering), sum (self.word_count))
526 s = s.ljust (colspec[0])
528 s += ''.join ([self.translations[k].text_status ().ljust(colspec[1])
529 for k in sorted (self.translations.keys ())])
531 s += ''.join ([i.text_status (numbering) for i in self.includes])
538 update_category_word_counts_re = re.compile (r'(?ms)^-(\d+)-(.*?\n)\d+ *total')
540 counts_re = re.compile (r'(?m)^(\d+) ')
542 def update_category_word_counts_sub (m):
543 return ('-' + m.group (1) + '-' + m.group (2)
545 for c in counts_re.findall (m.group (2))])).ljust (6)
549 # main () starts here-abouts
551 progress ("Reading documents...")
554 buildlib.read_pipe ("git ls-files | grep -E '[^/]*/?[^/]*[.](tely|texi)$'")[0].splitlines ()
556 master_docs = [MasterTelyDocument (os.path.normpath (filename))
557 for filename in master_files]
558 master_docs = [doc for doc in master_docs if doc.translations]
560 enabled_languages = [l for l in langdefs.LANGDICT
561 if langdefs.LANGDICT[l].enabled
564 progress ("Generating status pages...")
566 date_time = buildlib.read_pipe ('LANG= date -u')[0]
568 main_status_body = last_updated_string % date_time
569 main_status_body += '\n'.join ([doc.texi_status () for doc in master_docs])
571 texi_header = '''@c -*- coding: utf-8; mode: texinfo; -*-
572 @c This file was generated by translation-status.py -- DO NOT EDIT!
574 Translation of GIT committish: 0
578 Translation status currently only available in HTML.
589 main_status_page = texi_header % locals () + main_status_body + texi_footer
591 open ('translations.itexi', 'w').write (main_status_page)
593 for l in enabled_languages:
594 date_time = buildlib.read_pipe ('LANG=%s date -u' % l)[0]
595 updated = translation[l] (last_updated_string) % date_time
596 texi_status = '\n'.join ([doc.translations[l].texi_status ()
597 for doc in master_docs
598 if l in doc.translations])
599 lang_status_page = texi_header + updated + texi_status + texi_footer
600 open (os.path.join (l, 'translations.itexi'), 'w').write (lang_status_page)
602 main_status_txt = '''Documentation translations status
605 FT = fully translated
609 main_status_txt += '\n'.join ([doc.text_status () for doc in master_docs])
611 status_txt_file = 'out/translations-status.txt'
612 progress ("Writing %s..." % status_txt_file)
613 open (status_txt_file, 'w').write (main_status_txt)
615 translation_instructions_file = 'contributor/doc-translation-list.itexi'
616 progress ("Updating %s..." % translation_instructions_file)
617 translation_instructions = open (translation_instructions_file).read ()
619 for doc in master_docs:
620 translation_instructions = doc.update_word_counts (translation_instructions)
622 for html_file in re.findall (r'(?m)^\d+ *(\S+?\.html\S*?)(?: |$)',
623 translation_instructions):
624 word_count = sgml_word_count (open (html_file).read ())
625 translation_instructions = update_word_count (translation_instructions,
629 for po_file in re.findall (r'(?m)^\d+ *(\S+?\.po\S*?)(?: |$)',
630 translation_instructions):
631 word_count = po_word_count (open (po_file).read ())
632 translation_instructions = update_word_count (translation_instructions,
636 translation_instructions = \
637 update_category_word_counts_re.sub (update_category_word_counts_sub,
638 translation_instructions)
640 open (translation_instructions_file, 'w').write (translation_instructions)