40f06cdf03d60329fc4618d25ea2cb089032a94e
[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
11 def _register_function(f):
12     """ Register extension function with lxml """
13     ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
14     ns[f.__name__] = f
15
16
17 ENTITY_SUBSTITUTIONS = [
18         (u'---', u'—'),
19         (u'--', u'–'),
20         (u'...', u'…'),
21         (u',,', u'„'),
22         (u'"', u'”'),
23 ]
24
25 def substitute_entities(context, text):
26     """XPath extension function converting all entites in passed text."""
27     if isinstance(text, list):
28         text = ''.join(text)
29     for entity, substitutution in ENTITY_SUBSTITUTIONS:
30         text = text.replace(entity, substitutution)
31     return text
32
33
34 def reg_substitute_entities():
35     _register_function(substitute_entities)
36
37
38 def strip(context, text):
39     """Remove unneeded whitespace from beginning and end"""
40     if isinstance(text, list):
41         text = ''.join(text)
42     return re.sub(r'\s+', ' ', text).strip()
43
44
45 def reg_strip():
46     _register_function(strip)
47
48
49 def starts_white(context, text):
50     if isinstance(text, list):
51         text = ''.join(text)
52     if not text:
53         return False
54     return text[0].isspace()
55
56
57 def reg_starts_white():
58     _register_function(starts_white)
59
60
61 def reg_ends_white():
62     def ends_white(context, text):
63         if isinstance(text, list):
64             text = ''.join(text)
65         if not text:
66             return False
67         return text[-1].isspace()
68     _register_function(ends_white)
69
70
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
91
92 def reg_wrap_words():
93     _register_function(wrap_words)
94
95
96 def person_name(context, text):
97     """ Converts "Name, Forename" to "Forename Name" """
98     if isinstance(text, list):
99         text = ''.join(text)
100     return Person.from_text(text).readable()
101
102
103 def reg_person_name():
104     _register_function(person_name)
105
106
107 def texcommand(context, text):
108     """Remove non-letters"""
109     if isinstance(text, list):
110         text = ''.join(text)
111     return re.sub(r'[^a-zA-Z]', '', text).strip()
112
113
114 def reg_texcommand():
115     _register_function(texcommand)
116
117
118 def reg_get(format_):
119     def get(context, *args):
120         obj = format_
121         for arg in args:
122             if hasattr(obj, arg):
123                 obj = getattr(obj, arg)
124             else:
125                 try:
126                     obj = obj[arg]
127                 except (TypeError, KeyError), e:
128                     # Just raise proper AttributeError.
129                     getattr(obj, arg)
130         return obj
131     _register_function(get)