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 | re.I)
53 checkers_re = re.compile (r'^@c[ ]+Translation[ ]*checkers?[ ]*:[ ]*(.*?)$',
55 status_re = re.compile (r'^@c[ ]+Translation[ ]*status[ ]*:[ ]*(.*?)$', re.M | re.I)
56 post_gdp_re = re.compile ('post.GDP', re.I)
57 untranslated_node_str = '@untranslated'
58 skeleton_str = '-- SKELETON FILE --'
60 section_titles_string = _doc ('Section titles')
61 last_updated_string = _doc (' <p><i>Last updated %s</i></p>\n')
62 detailed_status_heads = [_doc ('Translators'), _doc ('Translation checkers'),
63 _doc ('Translated'), _doc ('Up to date'),
66 'not translated': {'color':'d0f0f8', 'short':_doc ('no'), 'abbr':'NT',
67 'long':_doc ('not translated')},
68 'partially translated': {'color':'dfef77',
69 'short':_doc ('partially (%(p)d %%)'),
71 'long':_doc ('partially translated (%(p)d %%)')},
72 'fully translated': {'color':'1fff1f', 'short':_doc ('yes'), 'abbr':'FT',
73 'long': _doc ('translated')},
74 'up to date': {'short':_doc ('yes'), 'long':_doc ('up to date'),
75 'abbr':'100%%', 'vague':_doc ('up to date')},
76 'outdated': {'short':_doc ('partially'), 'abbr':'%(p)d%%',
77 'vague':_doc ('partially up to date')},
78 'N/A': {'short':_doc ('N/A'), 'abbr':'N/A', 'color':'d587ff', 'vague':''},
79 'pre-GDP':_doc ('pre-GDP'),
80 'post-GDP':_doc ('post-GDP')
84 # (Unumbered/Numbered/Lettered, level)
86 'unnumbered': ('u', 1),
87 'unnumberedsec': ('u', 2),
88 'unnumberedsubsec': ('u', 3),
91 'subsection': ('n', 3),
93 'appendixsec': ('l', 2),
96 appendix_number_trans = string.maketrans ('@ABCDEFGHIJKLMNOPQRSTUVWXY',
97 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
99 class SectionNumber (object):
101 self.__data = [[0,'u']]
103 def __increase_last_index (self):
104 type = self.__data[-1][1]
106 self.__data[-1][0] = \
107 self.__data[-1][0].translate (appendix_number_trans)
109 self.__data[-1][0] += 1
112 if self.__data[-1][1] == 'u':
114 return '.'.join ([str (i[0]) for i in self.__data if i[1] != 'u']) + ' '
116 def increase (self, (type, level)):
118 self.__data = [[0,'u']]
119 while level + 1 < len (self.__data):
121 if level + 1 > len (self.__data):
122 self.__data.append ([0, type])
124 self.__data[-1][0] = '@'
125 if type == self.__data[-1][1]:
126 self.__increase_last_index ()
128 self.__data[-1] = ([0, type])
130 self.__data[-1][0] = 'A'
132 self.__data[-1][0] = 1
133 return self.format ()
136 def percentage_color (percent):
139 c = [hex (int (3 * p * b + (1 - 3 * p) * a))[2:]
140 for (a, b) in [(0xff, 0xff), (0x5c, 0xa6), (0x5c, 0x4c)]]
142 c = [hex (int ((3 * p - 1) * b + (2 - 3 * p) * a))[2:]
143 for (a, b) in [(0xff, 0xff), (0xa6, 0xff), (0x4c, 0x3d)]]
145 c = [hex (int ((3 * p - 2) * b + 3 * (1 - p) * a))[2:]
146 for (a, b) in [(0xff, 0x1f), (0xff, 0xff), (0x3d, 0x1f)]]
150 def update_word_count (text, filename, word_count):
151 return re.sub (r'(?m)^(\d+) *' + filename,
152 str (word_count).ljust (6) + filename,
155 po_msgid_re = re.compile (r'^msgid "(.*?)"(?:\n"(.*?)")*', re.M)
157 def po_word_count (po_content):
158 s = ' '.join ([''.join (t) for t in po_msgid_re.findall (po_content)])
159 return len (space_re.split (s))
161 sgml_tag_re = re.compile (r'<.*?>', re.S)
163 def sgml_word_count (sgml_doc):
164 s = sgml_tag_re.sub ('', sgml_doc)
165 return len (space_re.split (s))
167 def tely_word_count (tely_doc):
169 Calculate word count of a Texinfo document node by node.
171 Take string tely_doc as an argument.
172 Return a list of integers.
174 Texinfo comments and @lilypond blocks are not included in word counts.
176 tely_doc = comments_re.sub ('', tely_doc)
177 tely_doc = lilypond_re.sub ('', tely_doc)
178 nodes = node_re.split (tely_doc)
179 return [len (space_re.split (n)) for n in nodes]
182 class TelyDocument (object):
183 def __init__ (self, filename):
184 self.filename = filename
185 self.contents = 'GIT committish: 0'
186 if os.path.exists (filename):
187 self.contents = open (filename).read ()
188 self.top = os.path.splitext (filename)[1] in ['.tely', '.texi']
189 ## record title and sectionning level of first Texinfo section
190 self.sectioning = 'unnumbered'
191 self.title = 'Untitled'
192 m = title_re.search (self.contents)
194 self.sectioning = m.group (1)
195 self.title = m.group (2)
196 # This is all quite ugly and hairy. The original code worked
197 # with @top node detection and each manual had its own @top
198 # node. Not any more. Declaring .tely / .texi files to be
199 # @top sort of works...
201 self.sectioning = 'top'
202 self.level = texi_level [self.sectioning]
204 if not hasattr (self, 'language'):
206 m = language_re.search (self.contents)
208 self.language = m.group (1)
210 dir = os.path.dirname (filename).split ('/')[0]
215 included_files = [dir + t
216 for t in include_re.findall (self.contents)]
217 self.included_files = [p for p in included_files if os.path.exists (p)]
219 def print_title (self, section_number):
220 return section_number.increase (self.level) + self.title
223 class TranslatedTelyDocument (TelyDocument):
224 def __init__ (self, filename, masterdocument, parent_translation=None):
225 TelyDocument.__init__ (self, filename)
226 self.masterdocument = masterdocument
227 if not hasattr (self, 'language'):
229 if not self.language and parent_translation:
230 self.language = parent_translation.__dict__.get ('language', '')
231 if self.language == 'en':
232 print filename + ': language en specified: set @documentlanguage', self.filename[:2]
234 if not self.language and filename[2] == '/':
235 print filename + ': no language specified: add @documentlanguage', self.filename[:2]
236 self.language = filename[:2]
238 self.translation = translation[self.language]
240 self.translation = lambda x: x
241 self.title = self.translation (self.title)
243 ## record authoring information
244 self.translators = ['']
245 if parent_translation:
246 self.translators = parent_translation.__dict__.get ('translators', [''])
247 m = translators_re.findall (self.contents)
249 self.translators = [n.strip () for n in
250 reduce (operator.add, [n.split (',') for n in m])]
251 if self.language != self.filename[:2]:
252 print 'Barf:', self.filename
254 if (not isinstance (self, UntranslatedTelyDocument)
255 and (not self.translators or not self.translators[0])
256 and not 'macros.itexi' in self.filename):
257 error ('%s: error: no translator name found, \nplease \
258 specify at least one in the master file as a line containing\n\
259 @c Translators: FirstName1 LastName1, FirstName2 LastName2' % self.filename)
261 m = checkers_re.findall (self.contents)
263 self.checkers = [n.strip () for n in
264 reduce (operator.add, [n.split (',') for n in m])]
265 if not self.checkers and isinstance (parent_translation, TranslatedTelyDocument):
266 self.checkers = parent_translation.checkers
268 ## check whether translation is pre- or post-GDP
269 m = status_re.search (self.contents)
271 self.post_gdp = bool (post_gdp_re.search (m.group (1)))
273 self.post_gdp = False
275 ## record which parts (nodes) of the file are actually translated
276 self.partially_translated = not skeleton_str in self.contents
277 nodes = node_re.split (self.contents)
278 self.translated_nodes = [not untranslated_node_str in n for n in nodes]
280 ## calculate translation percentage
281 master_total_word_count = sum (masterdocument.word_count)
282 translation_word_count = \
283 sum ([masterdocument.word_count[k] * self.translated_nodes[k]
284 for k in range (min (len (masterdocument.word_count),
285 len (self.translated_nodes)))])
286 self.translation_percentage = \
287 100 * translation_word_count / master_total_word_count
289 ## calculate how much the file is outdated
290 (diff_string, git_error) = \
291 buildlib.check_translated_doc (masterdocument.filename, self.filename, self.contents)
293 sys.stderr.write ('warning: %s: %s' % (self.filename, git_error))
294 self.uptodate_percentage = None
296 diff = diff_string.splitlines ()
297 insertions = sum ([len (l) - 1 for l in diff
298 if l.startswith ('+')
299 and not l.startswith ('+++')])
300 deletions = sum ([len (l) - 1 for l in diff
301 if l.startswith ('-')
302 and not l.startswith ('---')])
303 outdateness_percentage = 50.0 * (deletions + insertions) / \
304 (masterdocument.size + 0.5 * (deletions - insertions))
305 self.uptodate_percentage = 100 - int (outdateness_percentage)
306 if self.uptodate_percentage > 100:
308 progress ("%s: strange uptodateness percentage %d %%, \
309 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
310 self.uptodate_percentage = alternative
311 elif self.uptodate_percentage < 1:
313 progress ("%s: strange uptodateness percentage %d %%, \
314 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
315 self.uptodate_percentage = alternative
317 def completeness (self, formats=['long'], translated=False):
319 translation = self.translation
321 translation = lambda x: x
323 if isinstance (formats, str):
325 p = self.translation_percentage
327 status = 'not translated'
329 status = 'fully translated'
331 status = 'partially translated'
332 return dict ([(f, translation (format_table[status][f]) % locals())
335 def uptodateness (self, formats=['long'], translated=False):
337 translation = self.translation
339 translation = lambda x: x
341 if isinstance (formats, str):
343 p = self.uptodate_percentage
347 status = 'up to date'
352 if f == 'color' and p != None:
353 l['color'] = percentage_color (p)
355 l[f] = translation (format_table[status][f]) % locals ()
358 def gdp_status (self):
360 return self.translation (format_table['post-GDP'])
362 return self.translation (format_table['pre-GDP'])
364 def short_texi_status (self):
365 s = ' <td title="%(filename)s">' % self.__dict__
366 if self.partially_translated:
367 s += '<br>\n '.join (self.translators) + '<br>\n'
370 '<br>\n '.join (self.checkers) + '</small><br>\n'
372 c = self.completeness (['color', 'long'])
373 s += ' <span style="background-color: #%(color)s">\
374 %(long)s</span><br>\n' % c
376 if self.partially_translated:
377 u = self.uptodateness (['vague', 'color'])
378 s += ' <span style="background-color: #%(color)s">\
379 %(vague)s</span><br>\n' % u
384 def text_status (self):
385 s = self.completeness ('abbr')['abbr'] + ' '
387 if self.partially_translated:
388 s += self.uptodateness ('abbr')['abbr'] + ' '
391 def texi_status (self, numbering=SectionNumber ()):
392 if self.title == 'Untitled':
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__
407 s = (' <tr align="left">\n <td title="%%(filename)s">%s<br>(%d)</td>\n'
408 % (self.print_title (numbering),
409 sum (self.masterdocument.word_count))) % self.__dict__
411 if self.partially_translated:
412 s += ' <td>' + '<br>\n '.join (self.translators) + '</td>\n'
413 s += ' <td>' + '<br>\n '.join (self.checkers) + '</td>\n'
415 s += ' <td></td>\n' * 2
417 c = self.completeness (['color', 'short'], translated=True)
418 s += ' <td><span style="background-color: #%(color)s">\
419 %(short)s</span></td>\n' % {'color': c['color'],
422 if self.partially_translated:
423 u = self.uptodateness (['short', 'color'], translated=True)
424 s += ' <td><span style="background-color: #%(color)s">\
425 %(short)s</span></td>\n' % {'color': u['color'],
430 s += ' <td>' + self.gdp_status () + '</td>\n </tr>\n'
431 s += ''.join ([i.translations[self.language].texi_status (numbering)
432 for i in self.masterdocument.includes
433 if self.language in i.translations])
436 s += '</table>\n<p></p>\n'
439 class UntranslatedTelyDocument (TranslatedTelyDocument):
440 def __init__ (self, filename, masterdocument, parent_translation=None):
441 if filename[2] == '/':
442 self.language = filename[:2]
443 TranslatedTelyDocument.__init__ (self, filename, masterdocument, parent_translation)
445 class MasterTelyDocument (TelyDocument):
448 parent_translations=dict ([(lang, None)
449 for lang in langdefs.LANGDICT])):
450 TelyDocument.__init__ (self, filename)
451 self.size = len (self.contents)
452 self.word_count = tely_word_count (self.contents)
453 self.translations = {}
455 translations = dict ([(lang, os.path.join (lang, filename))
456 for lang in langdefs.LANGDICT])
457 if not self.language or self.language == 'en':
458 languages = [x for x in parent_translations.keys () if x != 'en']
459 for lang in languages:
460 if os.path.exists (translations[lang]):
462 self.translations[lang] = TranslatedTelyDocument (translations[lang],
464 parent_translations.get (lang))
466 self.translations[lang] = UntranslatedTelyDocument (translations[lang],
468 parent_translations.get (lang))
470 for lang in [x for x in langdefs.LANGDICT if x and x != 'en']:
471 if not found.has_key (lang):
472 del self.translations[lang]
474 if self.translations:
475 self.includes = [MasterTelyDocument (f, self.translations)
476 for f in self.included_files]
480 def update_word_counts (self, s):
481 s = update_word_count (s, self.filename, sum (self.word_count))
482 for i in self.includes:
483 s = i.update_word_counts (s)
486 def texi_status (self, numbering=SectionNumber ()):
487 if self.title == 'Untitled' or not self.translations:
490 s = '''<table align="center" border="2">
492 <th>%s</th>''' % self.print_title (numbering)
493 s += ''.join ([' <th>%s</th>\n' % l for l in sorted (self.translations.keys ())])
495 s += (' <tr align="left">\n <td title="%%(filename)s">Section titles<br>(%d)</td>\n'
496 % sum (self.word_count)) % self.__dict__
498 else: # if self is an included file
499 s = (' <tr align="left">\n <td title=%%(filename)s>%s<br>(%d)</td>\n'
500 % (self.print_title (numbering), sum (self.word_count))) % self.__dict__
502 s += ''.join ([self.translations[k].short_texi_status ()
503 for k in sorted (self.translations.keys ())])
505 s += ''.join ([i.texi_status (numbering) for i in self.includes])
508 s += '</table>\n<p></p>\n'
511 def text_status (self, numbering=SectionNumber (), colspec=[48,12]):
512 if self.title == 'Untitled' or not self.translations:
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])
526 % (self.print_title (numbering), sum (self.word_count))
527 s = s.ljust (colspec[0])
529 s += ''.join ([self.translations[k].text_status ().ljust(colspec[1])
530 for k in sorted (self.translations.keys ())])
532 s += ''.join ([i.text_status (numbering) for i in self.includes])
539 update_category_word_counts_re = re.compile (r'(?ms)^-(\d+)-(.*?\n)\d+ *total')
541 counts_re = re.compile (r'(?m)^(\d+) ')
543 def update_category_word_counts_sub (m):
544 return ('-' + m.group (1) + '-' + m.group (2)
546 for c in counts_re.findall (m.group (2))])).ljust (6)
550 # main () starts here-abouts
552 progress ("Reading documents...")
555 buildlib.read_pipe ("git ls-files | grep -E '[^/]*/?[^/]*[.](tely|texi)$'")[0].splitlines ()
557 master_docs = [MasterTelyDocument (os.path.normpath (filename))
558 for filename in master_files]
559 master_docs = [doc for doc in master_docs if doc.translations]
561 enabled_languages = [l for l in langdefs.LANGDICT
562 if langdefs.LANGDICT[l].enabled
565 progress ("Generating status pages...")
567 date_time = buildlib.read_pipe ('LANG= date -u')[0]
569 main_status_body = last_updated_string % date_time
570 main_status_body += '\n'.join ([doc.texi_status () for doc in master_docs])
572 texi_header = '''@c -*- coding: utf-8; mode: texinfo; -*-
573 @c This file was generated by translation-status.py -- DO NOT EDIT!
575 Translation of GIT committish: 0
579 Translation status currently only available in HTML.
590 main_status_page = texi_header % locals () + main_status_body + texi_footer
592 open ('translations.itexi', 'w').write (main_status_page)
594 for l in enabled_languages:
595 date_time = buildlib.read_pipe ('LANG=%s date -u' % l)[0]
596 updated = translation[l] (last_updated_string) % date_time
597 texi_status = '\n'.join ([doc.translations[l].texi_status ()
598 for doc in master_docs
599 if l in doc.translations])
600 lang_status_page = texi_header + updated + texi_status + texi_footer
601 open (os.path.join (l, 'translations.itexi'), 'w').write (lang_status_page)
603 main_status_txt = '''Documentation translations status
606 FT = fully translated
610 main_status_txt += '\n'.join ([doc.text_status () for doc in master_docs])
612 status_txt_file = 'out/translations-status.txt'
613 progress ("Writing %s..." % status_txt_file)
614 open (status_txt_file, 'w').write (main_status_txt)
616 translation_instructions_file = 'contributor/doc-translation-list.itexi'
617 progress ("Updating %s..." % translation_instructions_file)
618 translation_instructions = open (translation_instructions_file).read ()
620 for doc in master_docs:
621 translation_instructions = doc.update_word_counts (translation_instructions)
623 for html_file in re.findall (r'(?m)^\d+ *(\S+?\.html\S*?)(?: |$)',
624 translation_instructions):
625 word_count = sgml_word_count (open (html_file).read ())
626 translation_instructions = update_word_count (translation_instructions,
630 for po_file in re.findall (r'(?m)^\d+ *(\S+?\.po\S*?)(?: |$)',
631 translation_instructions):
632 word_count = po_word_count (open (po_file).read ())
633 translation_instructions = update_word_count (translation_instructions,
637 translation_instructions = \
638 update_category_word_counts_re.sub (update_category_word_counts_sub,
639 translation_instructions)
641 open (translation_instructions_file, 'w').write (translation_instructions)