1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
9 from librarian.dcparser import Person
10 from librarian import get_resource
12 def _register_function(f):
13 """ Register extension function with lxml """
14 ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
18 def reg_substitute_entities():
19 ENTITY_SUBSTITUTIONS = [
27 def substitute_entities(context, text):
28 """XPath extension function converting all entites in passed text."""
29 if isinstance(text, list):
31 for entity, substitutution in ENTITY_SUBSTITUTIONS:
32 text = text.replace(entity, substitutution)
35 _register_function(substitute_entities)
39 def strip(context, text):
40 """Remove unneeded whitespace from beginning and end"""
41 if isinstance(text, list):
43 return re.sub(r'\s+', ' ', text).strip()
44 _register_function(strip)
47 def reg_starts_white():
48 def starts_white(context, text):
49 if isinstance(text, list):
53 return text[0].isspace()
54 _register_function(starts_white)
58 def ends_white(context, text):
59 if isinstance(text, list):
63 return text[-1].isspace()
64 _register_function(ends_white)
68 def wrap_words(context, text, wrapping):
69 """XPath extension function automatically wrapping words in passed text"""
70 if isinstance(text, list):
75 words = re.split(r'\s', text)
80 line_length += len(word) + 1
81 if line_length > wrapping:
82 # Max line length was exceeded. We create new line
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)
90 def reg_person_name():
91 def person_name(context, text):
92 """ Converts "Name, Forename" to "Forename Name" """
93 if isinstance(text, list):
95 return Person.from_text(text).readable()
96 _register_function(person_name)
100 def texcommand(context, text):
101 """Remove non-letters"""
102 if isinstance(text, list):
104 return re.sub(r'[^a-zA-Z]', '', text).strip()
105 _register_function(texcommand)
107 def reg_lang_code_3to2():
108 def lang_code_3to2(context, text):
109 """Convert 3-letter language code to 2-letter code"""
112 with open(get_resource('res/ISO-639-2_8859-1.txt'), 'rb') as f:
114 list = line.strip().split('|')
121 _register_function(lang_code_3to2)
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', '')
131 def reg_mathml_latex():
132 _register_function(mathml_latex)
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
140 zipf.writestr('OPS/' + name, data)
143 _register_function(mathml)