]> git.donarmstrong.com Git - lilypond.git/blob - scripts/auxiliar/translations-status.py
4cf7d9ddbd582b0cc231153a87852fc4dc800443
[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 ('^@(settitle|chapter|top|(?: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[ ]+[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 --'
58
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'),
63                          _doc ('Other info')]
64 format_table = {
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 %%)'),
69                              'abbr':'%(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')
80 }
81
82 texi_level = {
83 # (Unumbered/Numbered/Lettered, level)
84     'top': ('u', 0),
85     'unnumbered': ('u', 1),
86     'unnumberedsec': ('u', 2),
87     'unnumberedsubsec': ('u', 3),
88     'chapter': ('n', 1),
89     'section': ('n', 2),
90     'subsection': ('n', 3),
91     'appendix': ('l', 1),
92     'appendixsec': ('l', 2),
93 }
94
95 appendix_number_trans = string.maketrans ('@ABCDEFGHIJKLMNOPQRSTUVWXY',
96                                           'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
97
98 class SectionNumber (object):
99     def __init__ (self):
100         self.__data = [[0,'u']]
101
102     def __increase_last_index (self):
103         type = self.__data[-1][1]
104         if type == 'l':
105             self.__data[-1][0] = \
106                 self.__data[-1][0].translate (appendix_number_trans)
107         elif type == 'n':
108             self.__data[-1][0] += 1
109
110     def format (self):
111         if self.__data[-1][1] == 'u':
112             return ''
113         return '.'.join ([str (i[0]) for i in self.__data if i[1] != 'u']) + ' '
114
115     def increase (self, (type, level)):
116         if level == 0:
117             self.__data = [[0,'u']]
118         while level + 1 < len (self.__data):
119             del self.__data[-1]
120         if level + 1 > len (self.__data):
121             self.__data.append ([0, type])
122             if type == 'l':
123                 self.__data[-1][0] = '@'
124         if type == self.__data[-1][1]:
125             self.__increase_last_index ()
126         else:
127             self.__data[-1] = ([0, type])
128             if type == 'l':
129                 self.__data[-1][0] = 'A'
130             elif type == 'n':
131                 self.__data[-1][0] = 1
132         return self.format ()
133
134
135 def percentage_color (percent):
136     p = percent / 100.0
137     if p < 0.33:
138         c = [hex (int (3 * p * b + (1 - 3 * p) * a))[2:]
139              for (a, b) in [(0xff, 0xff), (0x5c, 0xa6), (0x5c, 0x4c)]]
140     elif p < 0.67:
141         c = [hex (int ((3 * p - 1) * b + (2 - 3 * p) * a))[2:]
142              for (a, b) in [(0xff, 0xff), (0xa6, 0xff), (0x4c, 0x3d)]]
143     else:
144         c = [hex (int ((3 * p - 2) * b + 3 * (1 - p) * a))[2:]
145              for (a, b) in [(0xff, 0x1f), (0xff, 0xff), (0x3d, 0x1f)]]
146     return ''.join (c)
147
148
149 def update_word_count (text, filename, word_count):
150     return re.sub (r'(?m)^(\d+) *' + filename,
151                    str (word_count).ljust (6) + filename,
152                    text)
153
154 po_msgid_re = re.compile (r'^msgid "(.*?)"(?:\n"(.*?)")*', re.M)
155
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))
159
160 sgml_tag_re = re.compile (r'<.*?>', re.S)
161
162 def sgml_word_count (sgml_doc):
163     s = sgml_tag_re.sub ('', sgml_doc)
164     return len (space_re.split (s))
165
166 def tely_word_count (tely_doc):
167     '''
168     Calculate word count of a Texinfo document node by node.
169
170     Take string tely_doc as an argument.
171     Return a list of integers.
172
173     Texinfo comments and @lilypond blocks are not included in word counts.
174     '''
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]
179
180
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)
192         if m:
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...
199         if self.top:
200             self.sectioning = 'top'
201         self.level = texi_level [self.sectioning]
202
203         if not hasattr (self, 'language'):
204             self.language = ''
205         m = language_re.search (self.contents)
206         if m:
207             self.language = m.group (1)
208
209         dir = os.path.dirname (filename).split ('/')[0]
210         if len (dir) == 2:
211             dir += '/'
212         else:
213             dir = ''
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)]
217
218     def print_title (self, section_number):
219         return section_number.increase (self.level) + self.title
220
221
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'):
227             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]
232             self.language = ''
233         if not self.language and filename[2] == '/':
234             print filename + ': no language specified: add @documentlanguage', self.filename[:2]
235             self.language = filename[:2]
236         if self.language:
237             self.translation = translation[self.language]
238         else:
239             self.translation = lambda x: x
240         self.title = self.translation (self.title)
241
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)
247         if m:
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
252             barf
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]..''')
259         self.checkers = []
260         m = checkers_re.findall (self.contents)
261         if m:
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
266
267         ## check whether translation is pre- or post-GDP
268         m = status_re.search (self.contents)
269         if m:
270             self.post_gdp = bool (post_gdp_re.search (m.group (1)))
271         else:
272             self.post_gdp = False
273
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]
278
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
287
288         ## calculate how much the file is outdated
289         (diff_string, git_error) = \
290             buildlib.check_translated_doc (masterdocument.filename, self.filename, self.contents)
291         if git_error:
292             sys.stderr.write ('warning: %s: %s' % (self.filename, git_error))
293             self.uptodate_percentage = None
294         else:
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:
306                 alternative = 50
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:
311                 alternative = 1
312                 progress ("%s: strange uptodateness percentage %d %%, \
313 setting to %d %%" % (self.filename, self.uptodate_percentage, alternative))
314                 self.uptodate_percentage = alternative
315
316     def completeness (self, formats=['long'], translated=False):
317         if translated:
318             translation = self.translation
319         else:
320             translation = lambda x: x
321
322         if isinstance (formats, str):
323             formats = [formats]
324         p = self.translation_percentage
325         if p == 0:
326             status = 'not translated'
327         elif p == 100:
328             status = 'fully translated'
329         else:
330             status = 'partially translated'
331         return dict ([(f, translation (format_table[status][f]) % locals())
332                       for f in formats])
333
334     def uptodateness (self, formats=['long'], translated=False):
335         if translated:
336             translation = self.translation
337         else:
338             translation = lambda x: x
339
340         if isinstance (formats, str):
341             formats = [formats]
342         p = self.uptodate_percentage
343         if p == None:
344             status = 'N/A'
345         elif p == 100:
346             status = 'up to date'
347         else:
348             status = 'outdated'
349         l = {}
350         for f in formats:
351             if f == 'color' and p != None:
352                 l['color'] = percentage_color (p)
353             else:
354                 l[f] = translation (format_table[status][f]) % locals ()
355         return l
356
357     def gdp_status (self):
358         if self.post_gdp:
359             return self.translation (format_table['post-GDP'])
360         else:
361             return self.translation (format_table['pre-GDP'])
362
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'
367             if self.checkers:
368                 s += '   <small>' + \
369                     '<br>\n   '.join (self.checkers) + '</small><br>\n'
370
371         c = self.completeness (['color', 'long'])
372         s += '   <span style="background-color: #%(color)s">\
373 %(long)s</span><br>\n' % c
374
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
379
380         s += '  </td>\n'
381         return s
382
383     def text_status (self):
384         s = self.completeness ('abbr')['abbr'] + ' '
385
386         if self.partially_translated:
387             s += self.uptodateness ('abbr')['abbr'] + ' '
388         return s
389
390     def texi_status (self, numbering=SectionNumber ()):
391         if self.title == 'Untitled':
392             return ''
393
394         if self.top:
395             s = '''<table align="center" border="2">
396  <tr align="center">
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])
400             s += ' </tr>\n'
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__
404
405         else:
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__
409
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'
413         else:
414             s += '  <td></td>\n' * 2
415
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'],
419                            'short': c['short']}
420
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'],
425                            'short': u['short']}
426         else:
427             s += '  <td></td>\n'
428
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])
433
434         if self.top:
435             s += '</table>\n<p></p>\n'
436         return s
437
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)
443
444 class MasterTelyDocument (TelyDocument):
445     def __init__ (self,
446                   filename,
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 = {}
453         found = {}
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                 if os.path.exists (translations[lang]):
460                     found[lang] = True
461                     self.translations[lang] = TranslatedTelyDocument (translations[lang],
462                                                                       self,
463                                                                       parent_translations.get (lang))
464                 else:
465                     self.translations[lang] = UntranslatedTelyDocument (translations[lang],
466                                                                         self,
467                                                                         parent_translations.get (lang))
468             if self.top:
469                 for lang in [x for x in langdefs.LANGDICT if x and x != 'en']:
470                     if not found.has_key (lang):
471                         del self.translations[lang]
472
473         if self.translations:
474             self.includes = [MasterTelyDocument (f, self.translations)
475                              for f in self.included_files]
476         else:
477             self.includes = []
478
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)
483         return s
484
485     def texi_status (self, numbering=SectionNumber ()):
486         if self.title == 'Untitled' or not self.translations:
487             return ''
488         if self.top:
489             s = '''<table align="center" border="2">
490  <tr align="center">
491   <th>%s</th>''' % self.print_title (numbering)
492             s += ''.join (['  <th>%s</th>\n' % l for l in sorted (self.translations.keys ())])
493             s += ' </tr>\n'
494             s += (' <tr align="left">\n  <td title="%%(filename)s">Section titles<br>(%d)</td>\n'
495                       % sum (self.word_count)) % self.__dict__
496
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__
500
501         s += ''.join ([self.translations[k].short_texi_status ()
502                        for k in sorted (self.translations.keys ())])
503         s += ' </tr>\n'
504         s += ''.join ([i.texi_status (numbering) for i in self.includes])
505
506         if self.top:
507             s += '</table>\n<p></p>\n'
508         return s
509
510     def text_status (self, numbering=SectionNumber (), colspec=[48,12]):
511         if self.title == 'Untitled' or not self.translations:
512             return ''
513
514         s = ''
515         if self.top:
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 ())])
519             s += '\n'
520             s += ('Section titles (%d)' % \
521                       sum (self.word_count)).ljust (colspec[0])
522
523         else:
524             s = '%s (%d) ' \
525                 % (self.print_title (numbering), sum (self.word_count))
526             s = s.ljust (colspec[0])
527
528         s += ''.join ([self.translations[k].text_status ().ljust(colspec[1])
529                        for k in sorted (self.translations.keys ())])
530         s += '\n\n'
531         s += ''.join ([i.text_status (numbering) for i in self.includes])
532
533         if self.top:
534             s += '\n'
535         return s
536
537
538 update_category_word_counts_re = re.compile (r'(?ms)^-(\d+)-(.*?\n)\d+ *total')
539
540 counts_re = re.compile (r'(?m)^(\d+) ')
541
542 def update_category_word_counts_sub (m):
543     return ('-' + m.group (1) + '-' + m.group (2)
544             + str (sum ([int (c)
545                          for c in counts_re.findall (m.group (2))])).ljust (6)
546             + 'total')
547
548 # urg 
549 # main () starts here-abouts
550
551 progress ("Reading documents...")
552
553 master_files = \
554     buildlib.read_pipe ("git ls-files | grep -E '[^/]*/?[^/]*[.](tely|texi)$'")[0].splitlines ()
555 master_files.sort ()
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]
559
560 enabled_languages = [l for l in langdefs.LANGDICT
561                      if langdefs.LANGDICT[l].enabled
562                      and l != 'en']
563
564 progress ("Generating status pages...")
565
566 date_time = buildlib.read_pipe ('LANG= date -u')[0]
567
568 main_status_body = last_updated_string % date_time
569 main_status_body += '\n'.join ([doc.texi_status () for doc in master_docs])
570
571 texi_header = '''@c -*- coding: utf-8; mode: texinfo; -*-
572 @c This file was generated by translation-status.py -- DO NOT EDIT!
573 @ignore
574     Translation of GIT committish: 0
575 @end ignore
576
577 @ifnothtml
578 Translation status currently only available in HTML.
579 @end ifnothtml
580 @ifhtml
581 @html
582 '''
583
584 texi_footer = '''
585 @end html
586 @end ifhtml
587 '''
588
589 main_status_page = texi_header % locals () + main_status_body + texi_footer
590
591 open ('translations.itexi', 'w').write (main_status_page)
592
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)
601
602 main_status_txt = '''Documentation translations status
603 Generated %s
604 NT = not translated
605 FT = fully translated
606
607 ''' % date_time
608
609 main_status_txt += '\n'.join ([doc.text_status () for doc in master_docs])
610
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)
614
615 translation_instructions_file = 'contributor/doc-translation-list.itexi'
616 progress ("Updating %s..." % translation_instructions_file)
617 translation_instructions = open (translation_instructions_file).read ()
618
619 for doc in master_docs:
620     translation_instructions = doc.update_word_counts (translation_instructions)
621
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,
626                                                   html_file,
627                                                   word_count)
628
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,
633                                                   po_file,
634                                                   word_count)
635
636 translation_instructions = \
637     update_category_word_counts_re.sub (update_category_word_counts_sub,
638                                         translation_instructions)
639
640 open (translation_instructions_file, 'w').write (translation_instructions)
641 sys.exit (exit_code)