Preliminary math and tables support.
[librarian.git] / librarian / functions.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from lxml import etree
7 import re
8
9 from librarian.dcparser import Person
10 from librarian import get_resource
11
12 def _register_function(f):
13     """ Register extension function with lxml """
14     ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
15     ns[f.__name__] = f
16
17
18 def reg_substitute_entities():
19     ENTITY_SUBSTITUTIONS = [
20         (u'---', u'—'),
21         (u'--', u'–'),
22         (u'...', u'…'),
23         (u',,', u'„'),
24         (u'"', u'”'),
25     ]
26
27     def substitute_entities(context, text):
28         """XPath extension function converting all entites in passed text."""
29         if isinstance(text, list):
30             text = ''.join(text)
31         for entity, substitutution in ENTITY_SUBSTITUTIONS:
32             text = text.replace(entity, substitutution)
33         return text
34
35     _register_function(substitute_entities)
36
37
38 def reg_strip():
39     def strip(context, text):
40         """Remove unneeded whitespace from beginning and end"""
41         if isinstance(text, list):
42             text = ''.join(text)
43         return re.sub(r'\s+', ' ', text).strip()
44     _register_function(strip)
45
46
47 def reg_starts_white():
48     def starts_white(context, text):
49         if isinstance(text, list):
50             text = ''.join(text)
51         if not text:
52             return False
53         return text[0].isspace()
54     _register_function(starts_white)
55
56
57 def reg_ends_white():
58     def ends_white(context, text):
59         if isinstance(text, list):
60             text = ''.join(text)
61         if not text:
62             return False
63         return text[-1].isspace()
64     _register_function(ends_white)
65
66
67 def reg_wrap_words():
68     def wrap_words(context, text, wrapping):
69         """XPath extension function automatically wrapping words in passed text"""
70         if isinstance(text, list):
71             text = ''.join(text)
72         if not wrapping:
73             return text
74
75         words = re.split(r'\s', text)
76
77         line_length = 0
78         lines = [[]]
79         for word in words:
80             line_length += len(word) + 1
81             if line_length > wrapping:
82                 # Max line length was exceeded. We create new line
83                 lines.append([])
84                 line_length = len(word)
85             lines[-1].append(word)
86         return '\n'.join(' '.join(line) for line in lines)
87     _register_function(wrap_words)
88
89
90 def reg_person_name():
91     def person_name(context, text):
92         """ Converts "Name, Forename" to "Forename Name" """
93         if isinstance(text, list):
94             text = ''.join(text)
95         return Person.from_text(text).readable()
96     _register_function(person_name)
97
98
99 def reg_texcommand():
100     def texcommand(context, text):
101         """Remove non-letters"""
102         if isinstance(text, list):
103             text = ''.join(text)
104         return re.sub(r'[^a-zA-Z]', '', text).strip()
105     _register_function(texcommand)
106     
107 def reg_lang_code_3to2():
108         def lang_code_3to2(context, text):
109                 """Convert 3-letter language code to 2-letter code"""
110                 result = ''
111                 text = ''.join(text)
112                 with open(get_resource('res/ISO-639-2_8859-1.txt'), 'rb') as f:
113                         for line in f:
114                                 list = line.strip().split('|')
115                                 if list[0] == text:
116                                         result=list[2]
117                 if result == '':
118                         return text
119                 else:
120                         return result
121         _register_function(lang_code_3to2)
122
123
124 def mathml_latex(context, trees):
125     from librarian.embeds.mathml import MathML
126     text = MathML(trees[0]).to_latex().data
127     # Remove invisible multiplications, they produce unwanted spaces.
128     text = text.replace(u'\u2062', '')
129     return text
130
131 def reg_mathml_latex():
132     _register_function(mathml_latex)
133
134 def reg_mathml_epub(zipf):
135     from librarian.embeds.mathml import MathML
136     def mathml(context, trees):
137         data = MathML(trees[0]).to_latex().to_png().data
138         name = "math%d.png" % mathml.count
139         mathml.count += 1
140         zipf.writestr('OPS/' + name, data)
141         return name
142     mathml.count = 0
143     _register_function(mathml)
144