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