Version 1.3.1dev.
[librarian.git] / scripts / normalize.py
1 #!/usr/bin/env python
2
3 from __future__ import with_statement
4
5 import re
6 import sys
7 import os.path
8
9 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
10
11 from StringIO import StringIO
12 from lxml import etree
13 import librarian
14
15 REPLACEMENTS = (
16     (u'---', u'\u2014'), # mdash
17     (u'--', u'\u2013'),  # ndash
18     (u'...', u'\u2026'), # ldots
19     (u',,', u'\u201E'),  # lower double back-quote
20     (u'"', u'\u201D'),   # upper double quote
21 )
22
23 DIALOG_EXPR = re.compile(r"\s*---\s(.*)")
24
25 def wl_normalize_text(context, text):
26     """XPath extension function converting all entites in passed text."""
27     if isinstance(text, list):
28         text = u''.join(text)
29
30     for code, ucode in REPLACEMENTS:
31         text = text.replace(code, ucode)
32
33     return text
34
35 def wl_fix_dialog(context, data):
36
37     if isinstance(data, list):
38         text = u''.join(data)
39     else:
40         text = data
41
42     m = DIALOG_EXPR.match(text)
43
44     if m is not None:
45         return m.group(1)
46     else:
47         return text   
48     
49
50 def filter_verse_ends(data):
51     return data.replace('/\n', '<br />')
52
53 ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
54 ns['normalize-text'] = wl_normalize_text
55 ns['fix-dialog-line'] = wl_fix_dialog
56
57 def normalize_stylesheet():
58     return etree.XSLT(etree.parse(os.path.join(os.path.dirname(librarian.__file__), 'xslt', 'normalize.xslt')))
59
60 if __name__ == '__main__':    
61     tran = normalize_stylesheet()
62     input = StringIO( f )
63     doc = trans( etree.parse(input) )
64     print etree.tostring(doc, pretty_print=True, encoding=unicode).encode('utf-8')
65
66     for err in trans.error_log:
67         sys.stderr.write( (u"%s\n" % err).encode('utf-8') )
68