1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 """reads a set of .po or .pot files to produce a pootle-terminology.pot
21
22 See: http://translate.sourceforge.net/wiki/toolkit/poterminology for examples and
23 usage instructions
24 """
25
26 from translate.lang import factory as lang_factory
27 from translate.misc import optrecurse
28 from translate.storage import po
29 from translate.storage import factory
30 from translate.misc import file_discovery
31 import os
32 import re
33 import sys
34
36 """a specialized Option Parser for the terminology tool..."""
37
38
39 formatpat = re.compile(r"%(?:\([^)]+\)|[0-9]+\$)?[-+#0]*[0-9.*]*(?:[hlLzjt][hl])?[EFGXc-ginoprsux]")
40
41 xmlelpat = re.compile(r"<(?:![[-]|[/?]?[A-Za-z_:])[^>]*>")
42
43 xmlentpat = re.compile(r"&(?:#(?:[0-9]+|x[0-9a-f]+)|[a-z_:][\w.-:]*);",
44 flags=re.UNICODE|re.IGNORECASE)
45
46 sortorders = [ "frequency", "dictionary", "length" ]
47
48 files = 0
49 units = 0
50
52 """parses the command line options, handling implicit input/output args"""
53 (options, args) = optrecurse.optparse.OptionParser.parse_args(self, args, values)
54
55 if args and not options.input:
56 if not options.output and not options.update and len(args) > 1:
57 options.input = args[:-1]
58 args = args[-1:]
59 else:
60 options.input = args
61 args = []
62
63
64 if args and not options.output and not options.update:
65 if os.path.lexists(args[-1]) and not os.path.isdir(args[-1]):
66 self.error("To overwrite %s, specify it with -o/--output or -u/--update" % (args[-1]))
67 options.output = args[-1]
68 args = args[:-1]
69 if options.output and options.update:
70 self.error("You cannot use both -u/--update and -o/--output")
71 if args:
72 self.error("You have used an invalid combination of -i/--input, -o/--output, -u/--update and freestanding args")
73 if isinstance(options.input, list) and len(options.input) == 1:
74 options.input = options.input[0]
75 if options.inputmin == None:
76 options.inputmin = 1
77 elif not isinstance(options.input, list) and not os.path.isdir(options.input):
78 if options.inputmin == None:
79 options.inputmin = 1
80 elif options.inputmin == None:
81 options.inputmin = 2
82 if options.update:
83 options.output = options.update
84 if isinstance(options.input, list):
85 options.input.append(options.update)
86 elif options.input:
87 options.input = [options.input, options.update]
88 else:
89 options.input = options.update
90 if not options.output:
91 options.output = "pootle-terminology.pot"
92 return (options, args)
93
95 """sets the usage string - if usage not given, uses getusagestring for each option"""
96 if usage is None:
97 self.usage = "%prog " + " ".join([self.getusagestring(option) for option in self.option_list]) + \
98 "\n input directory is searched for PO files, terminology PO file is output file"
99 else:
100 super(TerminologyOptionParser, self).set_usage(usage)
101
109
111 """recurse through directories and process files"""
112 if self.isrecursive(options.input, 'input') and getattr(options, "allowrecursiveinput", True):
113 if isinstance(options.input, list):
114 inputfiles = self.recurseinputfilelist(options)
115 else:
116 inputfiles = self.recurseinputfiles(options)
117 else:
118 if options.input:
119 inputfiles = [os.path.basename(options.input)]
120 options.input = os.path.dirname(options.input)
121 else:
122 inputfiles = [options.input]
123 if os.path.isdir(options.output):
124 options.output = os.path.join(options.output,"pootle-terminology.pot")
125
126 if self.defaultstopfile:
127 parse_stopword_file(None, "-S", self.defaultstopfile, self)
128 self.glossary = {}
129 self.initprogressbar(inputfiles, options)
130 for inputpath in inputfiles:
131 self.files += 1
132 fullinputpath = self.getfullinputpath(options, inputpath)
133 success = True
134 try:
135 self.processfile(None, options, fullinputpath)
136 except Exception, error:
137 if isinstance(error, KeyboardInterrupt):
138 raise
139 self.warning("Error processing: input %s" % (fullinputpath), options, sys.exc_info())
140 success = False
141 self.reportprogress(inputpath, success)
142 del self.progressbar
143 self.outputterminology(options)
144
145 - def clean(self, string, options):
146 """returns the cleaned string that contains the text to be matched"""
147 for accelerator in options.accelchars:
148 string = string.replace(accelerator, "")
149 string = self.formatpat.sub(" ", string)
150 string = self.xmlelpat.sub(" ", string)
151 string = self.xmlentpat.sub(" ", string)
152 string = string.strip()
153 return string
154
156 """return case-mapped stopword for input word"""
157 if self.stopignorecase or (self.stopfoldtitle and word.istitle()):
158 word = word.lower()
159 return word
160
161 - def stopword(self, word, defaultset=frozenset()):
162 """return stoplist frozenset for input word"""
163 return self.stopwords.get(self.stopmap(word),defaultset)
164
165 - def addphrases(self, words, skips, translation, partials=True):
166 """adds (sub)phrases with non-skipwords and more than one word"""
167 if (len(words) > skips + 1 and
168 'skip' not in self.stopword(words[0]) and
169 'skip' not in self.stopword(words[-1])):
170 self.glossary.setdefault(' '.join(words), []).append(translation)
171 if partials:
172 part = list(words)
173 while len(part) > 2:
174 if 'skip' in self.stopword(part.pop()):
175 skips -= 1
176 if (len(part) > skips + 1 and
177 'skip' not in self.stopword(part[0]) and
178 'skip' not in self.stopword(part[-1])):
179 self.glossary.setdefault(' '.join(part), []).append(translation)
180
181 - def processfile(self, fileprocessor, options, fullinputpath):
182 """process an individual file"""
183 inputfile = self.openinputfile(options, fullinputpath)
184 inputfile = factory.getobject(inputfile)
185 sourcelang = lang_factory.getlanguage(options.sourcelanguage)
186 rematchignore = frozenset(('word','phrase'))
187 defaultignore = frozenset()
188 for unit in inputfile.units:
189 self.units += 1
190 if unit.isheader():
191 continue
192 if unit.hasplural():
193 continue
194 if not options.invert:
195 source = self.clean(unit.source, options)
196 target = self.clean(unit.target, options)
197 else:
198 target = self.clean(unit.source, options)
199 source = self.clean(unit.target, options)
200 if len(source) <= 1:
201 continue
202 for sentence in sourcelang.sentences(source):
203 words = []
204 skips = 0
205 for word in sourcelang.words(sentence):
206 stword = self.stopmap(word)
207 if options.ignorecase or (options.foldtitle and word.istitle()):
208 word = word.lower()
209 ignore = defaultignore
210 if stword in self.stopwords:
211 ignore = self.stopwords[stword]
212 else:
213 for stopre in self.stoprelist:
214 if stopre.match(stword) != None:
215 ignore = rematchignore
216 break
217 translation = (source, target, unit, fullinputpath)
218 if 'word' not in ignore:
219
220 root = word
221 if len(word) > 3 and word[-1] == 's' and word[0:-1] in self.glossary:
222 root = word[0:-1]
223 elif len(root) > 2 and root + 's' in self.glossary:
224 self.glossary[root] = self.glossary.pop(root + 's')
225 self.glossary.setdefault(root, []).append(translation)
226 if options.termlength > 1:
227 if 'phrase' in ignore:
228
229 while len(words) > 2:
230 if 'skip' in self.stopword(words.pop(0)):
231 skips -= 1
232 self.addphrases(words, skips, translation)
233 words = []
234 skips = 0
235 else:
236 words.append(word)
237 if 'skip' in ignore:
238 skips += 1
239 if len(words) > options.termlength + skips:
240 while len(words) > options.termlength + skips:
241 if 'skip' in self.stopword(words.pop(0)):
242 skips -= 1
243 self.addphrases(words, skips, translation)
244 else:
245 self.addphrases(words, skips, translation, partials=False)
246 if options.termlength > 1:
247
248 while options.termlength > 1 and len(words) > 2:
249
250 if 'skip' in self.stopword(words.pop(0)):
251 skips -= 1
252 self.addphrases(words, skips, translation)
253
255 """saves the generated terminology glossary"""
256 termfile = po.pofile()
257 terms = {}
258 locre = re.compile(r":[0-9]+$")
259 print >> sys.stderr, ("%d terms from %d units in %d files" %
260 (len(self.glossary), self.units, self.files))
261 for term, translations in self.glossary.iteritems():
262 if len(translations) <= 1:
263 continue
264 filecounts = {}
265 sources = {}
266 termunit = po.pounit(term)
267 locations = {}
268 sourcenotes = {}
269 transnotes = {}
270 targets = {}
271 fullmsg = False
272 for source, target, unit, filename in translations:
273 sources[source] = 1
274 filecounts[filename] = filecounts.setdefault(filename, 0) + 1
275 if term.lower() == self.clean(unit.source, options).lower():
276 fullmsg = True
277 target = self.clean(unit.target, options)
278 if options.ignorecase or (options.foldtitle and target.istitle()):
279 target = target.lower()
280 unit.settarget(target)
281 if target != "":
282 targets.setdefault(target, []).append(filename)
283 if term.lower() == unit.source.strip().lower():
284 sourcenotes[unit.getnotes("source code")] = None
285 transnotes[unit.getnotes("translator")] = None
286 else:
287 unit.settarget("")
288 unit.setsource(term)
289 termunit.merge(unit, overwrite=False, comments=False)
290 for loc in unit.getlocations():
291 locations.setdefault(locre.sub("", loc))
292 numsources = len(sources)
293 numfiles = len(filecounts)
294 numlocs = len(locations)
295 if numfiles < options.inputmin or numlocs < options.locmin:
296 continue
297 if fullmsg:
298 if numsources < options.fullmsgmin:
299 continue
300 elif numsources < options.substrmin:
301 continue
302 if len(targets.keys()) > 1:
303 txt = '; '.join(["%s {%s}" % (target, ', '.join(files))
304 for target, files in targets.iteritems()])
305 if termunit.gettarget().find('};') < 0:
306 termunit.settarget(txt)
307 termunit.markfuzzy()
308 else:
309
310 termunit.addnote(txt, "translator")
311 locmax = 2 * options.locmin
312 if numlocs > locmax:
313 for location in locations.keys()[0:locmax]:
314 termunit.addlocation(location)
315 termunit.addlocation("(poterminology) %d more locations"
316 % (numlocs - locmax))
317 else:
318 for location in locations.keys():
319 termunit.addlocation(location)
320 for sourcenote in sourcenotes.keys():
321 termunit.addnote(sourcenote, "source code")
322 for transnote in transnotes.keys():
323 termunit.addnote(transnote, "translator")
324 for filename, count in filecounts.iteritems():
325 termunit.othercomments.append("# (poterminology) %s (%d)\n" % (filename, count))
326 terms[term] = (((10 * numfiles) + numsources, termunit))
327
328 termlist = terms.keys()
329 print >> sys.stderr, "%d terms after thresholding" % len(termlist)
330 termlist.sort(lambda x, y: cmp(len(x), len(y)))
331 for term in termlist:
332 words = term.split()
333 if len(words) <= 2:
334 continue
335 while len(words) > 2:
336 words.pop()
337 if terms[term][0] == terms.get(' '.join(words), [0])[0]:
338 del terms[' '.join(words)]
339 words = term.split()
340 while len(words) > 2:
341 words.pop(0)
342 if terms[term][0] == terms.get(' '.join(words), [0])[0]:
343 del terms[' '.join(words)]
344 print >> sys.stderr, "%d terms after subphrase reduction" % len(terms.keys())
345 termitems = terms.values()
346 if options.sortorders == None:
347 options.sortorders = self.sortorders
348 while len(options.sortorders) > 0:
349 order = options.sortorders.pop()
350 if order == "frequency":
351 termitems.sort(lambda x, y: cmp(y[0], x[0]))
352 elif order == "dictionary":
353 termitems.sort(lambda x, y: cmp(x[1].source.lower(), y[1].source.lower()))
354 elif order == "length":
355 termitems.sort(lambda x, y: cmp(len(x[1].source), len(y[1].source)))
356 else:
357 self.warning("unknown sort order %s" % order, options)
358 for count, unit in termitems:
359 termfile.units.append(unit)
360 open(options.output, "w").write(str(termfile))
361
363 parser.values.ignorecase = False
364 parser.values.foldtitle = True
365
367 parser.values.ignorecase = parser.values.foldtitle = False
368
370
371 actions = { '+': frozenset(), ':': frozenset(['skip']),
372 '<': frozenset(['phrase']), '=': frozenset(['word']),
373 '>': frozenset(['word','skip']),
374 '@': frozenset(['word','phrase']) }
375
376 stopfile = open(value, "r")
377 line = 0
378 try:
379 for stopline in stopfile:
380 line += 1
381 stoptype = stopline[0]
382 if stoptype == '#' or stoptype == "\n":
383 continue
384 elif stoptype == '!':
385 if stopline[1] == 'C':
386 parser.stopfoldtitle = False
387 parser.stopignorecase = False
388 elif stopline[1] == 'F':
389 parser.stopfoldtitle = True
390 parser.stopignorecase = False
391 elif stopline[1] == 'I':
392 parser.stopignorecase = True
393 else:
394 parser.warning("%s line %d - bad case mapping directive" % (value, line), parser.values, ("", stopline[:2]))
395 elif stoptype == '/':
396 parser.stoprelist.append(re.compile(stopline[1:-1]+'$'))
397 else:
398 parser.stopwords[stopline[1:-1]] = actions[stoptype]
399 except KeyError, character:
400 parser.warning("%s line %d - bad stopword entry starts with" % (value, line), parser.values, sys.exc_info())
401 parser.warning("%s line %d" % (value, line + 1), parser.values, ("", "all lines after error ignored" ))
402 stopfile.close()
403 parser.defaultstopfile = None
404
406 formats = {"po":("po", None), "pot": ("pot", None), None:("po", None)}
407 parser = TerminologyOptionParser(formats)
408
409 parser.add_option("-u", "--update", type="string", dest="update",
410 metavar="UPDATEFILE", help="update terminology in UPDATEFILE")
411
412 parser.stopwords = {}
413 parser.stoprelist = []
414 parser.stopfoldtitle = True
415 parser.stopignorecase = False
416 parser.defaultstopfile = file_discovery.get_abs_data_filename('stoplist-en')
417 parser.add_option("-S", "--stopword-list", type="string", metavar="STOPFILE",
418 action="callback", callback=parse_stopword_file,
419 help="read stopword (term exclusion) list from STOPFILE (default %s)" % parser.defaultstopfile,
420 default=parser.defaultstopfile)
421
422 parser.set_defaults(foldtitle = True, ignorecase = False)
423 parser.add_option("-F", "--fold-titlecase", callback=fold_case_option,
424 action="callback", help="fold \"Title Case\" to lowercase (default)")
425 parser.add_option("-C", "--preserve-case", callback=preserve_case_option,
426 action="callback", help="preserve all uppercase/lowercase")
427 parser.add_option("-I", "--ignore-case", dest="ignorecase",
428 action="store_true", help="make all terms lowercase")
429
430 parser.add_option("", "--accelerator", dest="accelchars", default="",
431 metavar="ACCELERATORS", help="ignores the given accelerator characters when matching")
432
433 parser.add_option("-t", "--term-words", type="int", dest="termlength", default="3",
434 help="generate terms of up to LENGTH words (default 3)", metavar="LENGTH")
435 parser.add_option("", "--inputs-needed", type="int", dest="inputmin",
436 help="omit terms appearing in less than MIN input files (default 2, or 1 if only one input file)", metavar="MIN")
437 parser.add_option("", "--fullmsg-needed", type="int", dest="fullmsgmin", default="1",
438 help="omit full message terms appearing in less than MIN different messages (default 1)", metavar="MIN")
439 parser.add_option("", "--substr-needed", type="int", dest="substrmin", default="2",
440 help="omit substring-only terms appearing in less than MIN different messages (default 2)", metavar="MIN")
441 parser.add_option("", "--locs-needed", type="int", dest="locmin", default="2",
442 help="omit terms appearing in less than MIN different original source files (default 2)", metavar="MIN")
443
444 parser.add_option("", "--sort", dest="sortorders", action="append",
445 type="choice", choices=parser.sortorders, metavar="ORDER",
446 help="output sort order(s): %s (default is all orders in the above priority)" % ', '.join(parser.sortorders))
447
448 parser.add_option("", "--source-language", dest="sourcelanguage", default="en",
449 help="the source language code (default 'en')", metavar="LANG")
450 parser.add_option("-v", "--invert", dest="invert",
451 action="store_true", default=False, help="invert the source and target languages for terminology")
452 parser.set_usage()
453 parser.description = __doc__
454 parser.run()
455
456
457 if __name__ == '__main__':
458 main()
459