]> git.donarmstrong.com Git - lilypond.git/blob - scripts/auxiliar/translations-status.py
Resurrect translation-status.py. Fixes producing of translation status.
[lilypond.git] / scripts / auxiliar / translations-status.py
1 #!/usr/bin/env python
2
3 '''
4 USAGE: cd Documentation && translations-status.py
5
6   Write:
7     translations.itexi
8     <LANG>/translations.itexi
9     out/translations-status.txt
10
11   Update word counts in:
12     contributor/doc-translation-list.itexi
13 '''
14
15 import sys
16 import re
17 import string
18 import operator
19 import os
20 #
21 import langdefs
22 import buildlib
23
24 def progress (str):
25     sys.stderr.write (str + '\n')
26
27 exit_code = 0
28
29 def error (str, update_status=1):
30     global exit_code
31     sys.stderr.write ('translations-status.py: %s\n' % str)
32     exit_code = max (exit_code, update_status)
33
34 progress ("translations-status.py")
35
36 _doc = lambda s: s
37
38 # load gettext messages catalogs
39 translation = langdefs.translation
40
41
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)
50
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*(.*?)$',
55                           re.M | re.I)
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 --'
60
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'),
65                          _doc ('Other info')]
66 format_table = {
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 %%)'),
71                              'abbr':'%(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')
82 }
83
84 texi_level = {
85 # (Unumbered/Numbered/Lettered, level)
86     'top': ('u', 0),
87     'unnumbered': ('u', 1),
88     'unnumberedsec': ('u', 2),
89     'unnumberedsubsec': ('u', 3),
90     'chapter': ('n', 1),
91     'section': ('n', 2),
92     'subsection': ('n', 3),
93     'appendix': ('l', 1),
94     'appendixsec': ('l', 2),
95 }
96
97 appendix_number_trans = string.maketrans ('@ABCDEFGHIJKLMNOPQRSTUVWXY',
98                                           'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
99
100 class SectionNumber (object):
101     def __init__ (self):
102         self.__data = [[0,'u']]
103
104     def __increase_last_index (self):
105         type = self.__data[-1][1]
106         if type == 'l':
107             self.__data[-1][0] = \
108                 self.__data[-1][0].translate (appendix_number_trans)
109         elif type == 'n':
110             self.__data[-1][0] += 1
111
112     def format (self):
113         if self.__data[-1][1] == 'u':
114             return ''
115         return '.'.join ([str (i[0]) for i in self.__data if i[1] != 'u']) + ' '
116
117     def increase (self, (type, level)):
118         if level == 0:
119             self.__data = [[0,'u']]
120         while level + 1 < len (self.__data):
121             del self.__data[-1]
122         if level + 1 > len (self.__data):
123             self.__data.append ([0, type])
124             if type == 'l':
125                 self.__data[-1][0] = '@'
126         if type == self.__data[-1][1]:
127             self.__increase_last_index ()
128         else:
129             self.__data[-1] = ([0, type])
130             if type == 'l':
131                 self.__data[-1][0] = 'A'
132             elif type == 'n':
133                 self.__data[-1][0] = 1
134         return self.format ()
135
136
137 def percentage_color (percent):
138     p = percent / 100.0
139     if p < 0.33:
140         c = [hex (int (3 * p * b + (1 - 3 * p) * a))[2:]
141              for (a, b) in [(0xff, 0xff), (0x5c, 0xa6), (0x5c, 0x4c)]]
142     elif p < 0.67:
143         c = [hex (int ((3 * p - 1) * b + (2 - 3 * p) * a))[2:]
144              for (a, b) in [(0xff, 0xff), (0xa6, 0xff), (0x4c, 0x3d)]]
145     else:
146         c = [hex (int ((3 * p - 2) * b + 3 * (1 - p) * a))[2:]
147              for (a, b) in [(0xff, 0x1f), (0xff, 0xff), (0x3d, 0x1f)]]
148     return ''.join (c)
149
150
151 def update_word_count (text, filename, word_count):
152     return re.sub (r'(?m)^(\d+) *' + filename,
153                    str (word_count).ljust (6) + filename,
154                    text)
155
156 po_msgid_re = re.compile (r'^msgid "(.*?)"(?:\n"(.*?)")*', re.M)
157
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))
161
162 sgml_tag_re = re.compile (r'<.*?>', re.S)
163
164 def sgml_word_count (sgml_doc):
165     s = sgml_tag_re.sub ('', sgml_doc)
166     return len (space_re.split (s))
167
168 def tely_word_count (tely_doc):
169     '''
170     Calculate word count of a Texinfo document node by node.
171
172     Take string tely_doc as an argument.
173     Return a list of integers.
174
175     Texinfo comments and @lilypond blocks are not included in word counts.
176     '''
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]
181
182
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)
192         if m:
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]
198
199         m = language_re.search (self.contents)
200         if m:
201             self.language = m.group (1)
202
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)]
206
207     def print_title (self, section_number):
208         return section_number.increase (self.level) + self.title
209
210
211 class TranslatedTelyDocument (TelyDocument):
212     def __init__ (self, filename, masterdocument, parent_translation=None):
213         TelyDocument.__init__ (self, filename)
214
215         self.masterdocument = masterdocument
216         if not hasattr (self, 'language'):
217             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]
222             self.language = ''
223         if not self.language and filename[2] == '/':
224             print filename + ': no language specified: add @documentlanguage', self.filename[:2]
225             self.language = filename[:2]
226         if self.language:
227             self.translation = translation[self.language]
228         else:
229             self.translation = lambda x: x
230         self.title = self.translation (self.title)
231
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)
237         if m:
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)
245         self.checkers = []
246         m = checkers_re.findall (self.contents)
247         if m:
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
252
253         ## check whether translation is pre- or post-GDP
254         m = status_re.search (self.contents)
255         if m:
256             self.post_gdp = bool (post_gdp_re.search (m.group (1)))
257         else:
258             self.post_gdp = False
259
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]
264
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
273
274         ## calculate how much the file is outdated
275         (diff_string, git_error) = \
276             buildlib.check_translated_doc (masterdocument.filename, self.filename, self.contents)
277         if git_error:
278             sys.stderr.write ('warning: %s: %s' % (self.filename, git_error))
279             self.uptodate_percentage = None
280         else:
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:
292                 alternative = 50
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:
297                 alternative = 1
298                 progress ("%s: strange uptodateness percentage %d %%, \
299 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
300                 self.uptodate_percentage = alternative
301
302     def completeness (self, formats=['long'], translated=False):
303         if translated:
304             translation = self.translation
305         else:
306             translation = lambda x: x
307
308         if isinstance (formats, str):
309             formats = [formats]
310         p = self.translation_percentage
311         if p == 0:
312             status = 'not translated'
313         elif p == 100:
314             status = 'fully translated'
315         else:
316             status = 'partially translated'
317         return dict ([(f, translation (format_table[status][f]) % locals())
318                       for f in formats])
319
320     def uptodateness (self, formats=['long'], translated=False):
321         if translated:
322             translation = self.translation
323         else:
324             translation = lambda x: x
325
326         if isinstance (formats, str):
327             formats = [formats]
328         p = self.uptodate_percentage
329         if p == None:
330             status = 'N/A'
331         elif p == 100:
332             status = 'up to date'
333         else:
334             status = 'outdated'
335         l = {}
336         for f in formats:
337             if f == 'color' and p != None:
338                 l['color'] = percentage_color (p)
339             else:
340                 l[f] = translation (format_table[status][f]) % locals ()
341         return l
342
343     def gdp_status (self):
344         if self.post_gdp:
345             return self.translation (format_table['post-GDP'])
346         else:
347             return self.translation (format_table['pre-GDP'])
348
349     def short_texi_status (self):
350         s = '  <td>'
351         if self.partially_translated:
352             s += '<br>\n   '.join (self.translators) + '<br>\n'
353             if self.checkers:
354                 s += '   <small>' + \
355                     '<br>\n   '.join (self.checkers) + '</small><br>\n'
356
357         c = self.completeness (['color', 'long'])
358         s += '   <span style="background-color: #%(color)s">\
359 %(long)s</span><br>\n' % c
360
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
365
366         s += '  </td>\n'
367         return s
368
369     def text_status (self):
370         s = self.completeness ('abbr')['abbr'] + ' '
371
372         if self.partially_translated:
373             s += self.uptodateness ('abbr')['abbr'] + ' '
374         return s
375
376     def texi_status (self, numbering=SectionNumber ()):
377         if self.title == 'Untitled':
378             return ''
379
380         if self.top:
381             s = '''<table align="center" border="2">
382  <tr align="center">
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])
386             s += ' </tr>\n'
387             s += ' <tr align="left">\n  <td>%s<br>(%d)</td>\n' \
388                 % (self.translation (section_titles_string),
389                    sum (self.masterdocument.word_count))
390
391         else:
392             s =  ''' <!-- no table 388
393 filename: %(filename)s
394 sectioning: %(sectioning)s
395 title: %(title)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))
400
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'
404         else:
405             s += '  <td></td>\n' * 2
406
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'],
410                            'short': c['short']}
411
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'],
416                            'short': u['short']}
417         else:
418             s += '  <td></td>\n'
419
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])
424
425         if self.top:
426             s += '</table>\n<p></p>\n'
427         return s
428
429 class MasterTelyDocument (TelyDocument):
430     def __init__ (self,
431                   filename,
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)
438         if m:
439             self.title = m.group (2)
440         self.level = texi_level [self.sectioning]
441
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 = \
447             dict ([(lang,
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]
455         else:
456             self.includes = []
457
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)
462         return s
463
464     def texi_status (self, numbering=SectionNumber ()):
465         if self.title == 'Untitled' or not self.translations:
466             return ''
467         if self.top:
468             s = '''<table align="center" border="2">
469  <tr align="center">
470   <th>%s</th>''' % self.print_title (numbering)
471             s += ''.join (['  <th>%s</th>\n' % l for l in self.translations])
472             s += ' </tr>\n'
473             s += ' <tr align="left">\n  <td>Section titles<br>(%d)</td>\n' \
474                 % sum (self.word_count)
475
476         else:  # if self is an included file
477            s =  ''' <!-- no table 462
478 filename: %(filename)s
479 sectioning: %(sectioning)s
480 title: %(title)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))
484
485         s += ''.join ([t.short_texi_status ()
486                        for t in self.translations.values ()])
487         s += ' </tr>\n'
488         s += ''.join ([i.texi_status (numbering) for i in self.includes])
489
490         if self.top:
491             s += '</table>\n<p></p>\n'
492         return s
493
494     def text_status (self, numbering=SectionNumber (), colspec=[48,12]):
495         if self.title == 'Untitled' or not self.translations:
496             return ''
497
498         s = ''
499         if self.top:
500             s += (self.print_title (numbering) + ' ').ljust (colspec[0])
501             s += ''.join (['%s'.ljust (colspec[1]) % l
502                            for l in self.translations])
503             s += '\n'
504             s += ('Section titles (%d)' % \
505                       sum (self.word_count)).ljust (colspec[0])
506
507         else:
508             s = '%s (%d) ' \
509                 % (self.print_title (numbering), sum (self.word_count))
510             s = s.ljust (colspec[0])
511
512         s += ''.join ([t.text_status ().ljust(colspec[1])
513                        for t in self.translations.values ()])
514         s += '\n\n'
515         s += ''.join ([i.text_status (numbering) for i in self.includes])
516
517         if self.top:
518             s += '\n'
519         return s
520
521
522 update_category_word_counts_re = re.compile (r'(?ms)^-(\d+)-(.*?\n)\d+ *total')
523
524 counts_re = re.compile (r'(?m)^(\d+) ')
525
526 def update_category_word_counts_sub (m):
527     return ('-' + m.group (1) + '-' + m.group (2)
528             + str (sum ([int (c)
529                          for c in counts_re.findall (m.group (2))])).ljust (6)
530             + 'total')
531
532 # urg 
533 # main () starts here-abouts
534
535 progress ("Reading documents...")
536
537 master_files = \
538     buildlib.read_pipe ("git ls-files | grep -E '[^/]*/?[^/]*[.](tely|texi)$'")[0].splitlines ()
539 master_files.sort ()
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]
543
544 enabled_languages = [l for l in langdefs.LANGDICT
545                      if langdefs.LANGDICT[l].enabled
546                      and l != 'en']
547
548 progress ("Generating status pages...")
549
550 date_time = buildlib.read_pipe ('LANG= date -u')[0]
551
552 main_status_body = last_updated_string % date_time
553 main_status_body += '\n'.join ([doc.texi_status () for doc in master_docs])
554
555 ats = 'Actual translation status'
556 node = '''
557 @node %(ats)s
558 @unnumberedsubsubsec %(ats)s
559 ''' % locals ()
560
561 texi_header = '''@c -*- coding: utf-8; mode: texinfo; -*-
562 @c This file was generated by translation-status.py -- DO NOT EDIT!
563
564 %(node)s
565
566 @ifnothtml
567 Translation status currently only available in HTML.
568 @end ifnothtml
569 @ifhtml
570 @html
571 '''
572
573 texi_footer = '''
574 @end html
575 @end ifhtml
576 '''
577
578 main_status_page = texi_header % locals () + main_status_body + texi_footer
579
580 open ('translations.itexi', 'w').write (main_status_page)
581
582 for l in enabled_languages:
583     lats = translation[l] (ats)
584     node = '''
585 @node %(lats)s
586 @subheading %(lats)s
587 ''' % locals ()
588     date_time = buildlib.read_pipe ('LANG=%s date -u' % l)[0]
589     updated = translation[l] (last_updated_string) % date_time
590     if l and l != 'en':
591         node += '''@translationof %(ats)s
592 ''' % locals ()
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)
598
599 main_status_txt = '''Documentation translations status
600 Generated %s
601 NT = not translated
602 FT = fully translated
603
604 ''' % date_time
605
606 main_status_txt += '\n'.join ([doc.text_status () for doc in master_docs])
607
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)
611
612 translation_instructions_file = 'contributor/doc-translation-list.itexi'
613 progress ("Updating %s..." % translation_instructions_file)
614 translation_instructions = open (translation_instructions_file).read ()
615
616 for doc in master_docs:
617     translation_instructions = doc.update_word_counts (translation_instructions)
618
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,
623                                                   html_file,
624                                                   word_count)
625
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,
630                                                   po_file,
631                                                   word_count)
632
633 translation_instructions = \
634     update_category_word_counts_re.sub (update_category_word_counts_sub,
635                                         translation_instructions)
636
637 open (translation_instructions_file, 'w').write (translation_instructions)
638 sys.exit (exit_code)