Style changes.
[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 reg_lang_code_3to2():
115     def lang_code_3to2(context, text):
116         """Convert 3-letter language code to 2-letter code"""
117         result = ''
118         text = ''.join(text)
119         with open(get_resource('res/ISO-639-2_8859-1.txt'), 'rb') as f:
120             for line in f.read().decode('latin1').split('\n'):
121                 list = line.strip().split('|')
122                 if list[0] == text:
123                     result = list[2]
124         if result == '':
125             return text
126         else:
127             return result
128     _register_function(lang_code_3to2)
129
130
131 def mathml_latex(context, trees):
132     from librarian.embeds.mathml import MathML
133     text = MathML(trees[0]).to_latex().data
134     # Remove invisible multiplications, they produce unwanted spaces.
135     text = text.replace(u'\u2062', '')
136     return text
137
138
139 def reg_mathml_latex():
140     _register_function(mathml_latex)
141
142
143 def reg_mathml_epub(zipf):
144     from librarian.embeds.mathml import MathML
145
146     def mathml(context, trees):
147         data = MathML(trees[0]).to_latex().to_png().data
148         name = "math%d.png" % mathml.count
149         mathml.count += 1
150         zipf.writestr('OPS/' + name, data)
151         return name
152     mathml.count = 0
153     _register_function(mathml)