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