Python 3.4-3.7 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 __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         """XPath extension function automatically wrapping words in passed text"""
73         if isinstance(text, list):
74             text = ''.join(text)
75         if not wrapping:
76             return text
77
78         words = re.split(r'\s', text)
79
80         line_length = 0
81         lines = [[]]
82         for word in words:
83             line_length += len(word) + 1
84             if line_length > wrapping:
85                 # Max line length was exceeded. We create new line
86                 lines.append([])
87                 line_length = len(word)
88             lines[-1].append(word)
89         return '\n'.join(' '.join(line) for line in lines)
90     _register_function(wrap_words)
91
92
93 def reg_person_name():
94     def person_name(context, text):
95         """ Converts "Name, Forename" to "Forename Name" """
96         if isinstance(text, list):
97             text = ''.join(text)
98         return Person.from_text(text).readable()
99     _register_function(person_name)
100
101
102 def reg_texcommand():
103     def texcommand(context, text):
104         """Remove non-letters"""
105         if isinstance(text, list):
106             text = ''.join(text)
107         return re.sub(r'[^a-zA-Z]', '', text).strip()
108     _register_function(texcommand)
109
110
111 def reg_lang_code_3to2():
112     def lang_code_3to2(context, text):
113         """Convert 3-letter language code to 2-letter code"""
114         result = ''
115         text = ''.join(text)
116         with open(get_resource('res/ISO-639-2_8859-1.txt'), 'rb') as f:
117             for line in f.read().decode('latin1').split('\n'):
118                 list = line.strip().split('|')
119                 if list[0] == text:
120                     result = list[2]
121         if result == '':
122             return text
123         else:
124             return result
125     _register_function(lang_code_3to2)
126
127
128 def mathml_latex(context, trees):
129     from librarian.embeds.mathml import MathML
130     text = MathML(trees[0]).to_latex().data
131     # Remove invisible multiplications, they produce unwanted spaces.
132     text = text.replace(u'\u2062', '')
133     return text
134
135
136 def reg_mathml_latex():
137     _register_function(mathml_latex)
138
139
140 def reg_mathml_epub(zipf):
141     from librarian.embeds.mathml import MathML
142
143     def mathml(context, trees):
144         data = MathML(trees[0]).to_latex().to_png().data
145         name = "math%d.png" % mathml.count
146         mathml.count += 1
147         zipf.writestr('OPS/' + name, data)
148         return name
149     mathml.count = 0
150     _register_function(mathml)