-
Notifications
You must be signed in to change notification settings - Fork 0
/
transducer.py
344 lines (296 loc) · 11.9 KB
/
transducer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"""
This package several defines `Transducer` classes. The instances of `Transducer` can be used to transduce a HTML file
using the method `process_file`.
"""
import gettext
import heapq
import itertools
import re
import sys
from abc import abstractmethod, ABCMeta
from argparse import ArgumentParser
from collections import OrderedDict
from enum import Enum
from itertools import chain
from queue import PriorityQueue
from ordered_set import OrderedSet
from overrides import overrides
import config
_ = gettext.translation(config.domain, localedir=config.localedir, fallback=True).gettext
class Transducer(metaclass=ABCMeta):
"""
The abstract base class for transducers
"""
def __init__(self, name=None, description=None, examples=None):
self.name = name
self.description = description
self.examples = examples
def __str__(self):
return self.name
def print_help(self, file=sys.stdout):
"""
Print a help string for this transducer into a file.
:param file: the file to write the help string to
"""
file.write(_('Transducer "{0}":\n').format(self.name))
if self.description:
file.write(_(' Description: {0}\n').format(self.description))
if self.examples:
file.write(_(' Examples:\n'))
for before in self.examples:
# Before:
file.write(' -{0}\n'.format(before))
# After:
file.write(' +{0}\n'.format(self.transduce_html(before)))
@abstractmethod
def substitute(self, string, indices):
"""
Translates a string.
:param string: the string to be translated
:param indices: the indices of characters of the string
:return: a pair of string and indices
"""
raise NotImplementedError() # pragma: no cover
def transduce_html(self, html):
"""
Transduces a HTML formatted string.
:param html: a HTML formatted string
:return: the HTML string with the content transduced by this transducer
"""
# Load html
inside_tag = False
content_list = []
tags = OrderedDict()
i = 0
tag = []
for c in html:
assert isinstance(c, str)
assert len(c) == 1
if c == r'<':
inside_tag = True
tag.append(c)
continue
if c == r'>':
inside_tag = False
tag.append(c)
continue
if inside_tag:
tag.append(c)
continue
if tag:
tags[i] = ''.join(tag)
tag = []
content_list.append(c)
i += 1
if tag:
tags[i] = ''.join(tag)
content = ''.join(content_list)
# Transduce
content_transduced, indices = self.substitute(content, range(len(content)))
transduced = zip(indices, content_transduced)
# Insert tags
# The `key` argument requires Python 3.5
merged = heapq.merge(tags.items(), transduced, key=lambda x: x[0])
return ''.join((string for i, string in merged))
def process_file(self, infile, outfile):
"""
Transduces an input HTML file, writing to an output file.
:param infile: input HTML file
:param outfile: output HTML file
"""
outfile.write(self.transduce_html(infile.read()))
class ReTransducer(Transducer):
"""
Regular expression `Transducer`
"""
class Align(Enum):
left = 'left'
right = 'right'
def __init__(self, pattern, replacement, align=Align.left, fixpoint=True, name=None, description=None,
examples=None):
super().__init__(name=name, description=description, examples=examples)
self.pattern = pattern
assert isinstance(replacement, dict)
self.replacement = replacement
self.align = align
self.fixpoint = fixpoint
@overrides
def print_help(self, file=sys.stdout):
super().print_help(file)
file.write(_(' Pattern: {0}\n').format(self.pattern))
file.write(_(' Replacement: {0}\n').format(self.replacement))
file.write(_(' Align: {0}\n').format(self.align))
file.write(_(' Fixpoint: {0}\n').format(self.fixpoint))
@overrides
def substitute(self, string, indices):
result_string, indices = self.substitute_once(string, indices)
if self.fixpoint:
while result_string != string:
string = result_string
result_string, indices = self.substitute_once(string, indices)
return result_string, indices
def substitute_once(self, string, indices):
assert isinstance(string, str)
indices = list(indices)
assert len(string) == len(indices)
n = len(string)
i = 0
result_string = []
result_indices = []
match = re.search(self.pattern, string)
if match:
q = PriorityQueue()
for key, value in self.replacement.items():
span = match.span(key)
assert span
q.put((span, value))
while not q.empty():
(start, end), value = q.get()
assert start >= i
assert start < len(string)
# TODO: Allow align to be set in value
align = self.align
result_string.append(string[i:start])
result_indices.append(indices[i:start])
i = start
if align == self.Align.left:
pretend = indices[start]
else:
pretend = indices[end - 1]
result_string.append(value)
result_indices.append([pretend] * len(value))
i = end
result_string.append(string[i:n])
result_indices.append(indices[i:n])
return ''.join(result_string), itertools.chain.from_iterable(result_indices)
class WordsNbspSubstituter(ReTransducer):
"""
Replaces spaces that separate a given sequence of words.
"""
def __init__(self, words, name=None, description=None, examples=None):
words = list(words)
pattern = '( )'.join(words)
replacement = {i: r' ' for i in range(1, len(words))}
super().__init__(pattern, replacement, name=name, description=description, examples=examples)
class DottedNbspSubstituter(WordsNbspSubstituter):
"""
Replaces spaces that separate a given sequence of abbreviations. Automatically terminates the abbreviations (words)
with periods.
"""
@overrides
def __init__(self, words, name=None, description=None, examples=None):
words_iter = iter(words)
head_word_dotted = r'\b{0}\.'.format(next(words_iter))
tail_words_dotted = (r'{0}\.'.format(word) for word in words_iter)
words_dotted = chain([head_word_dotted], tail_words_dotted)
super().__init__(words_dotted, name=name, description=description, examples=examples)
class TransducerGroup(Transducer):
"""
A sequence of transducers
"""
def __init__(self, name, description=None):
super().__init__(name=name, description=description)
self.transducers = []
def add(self, transducer):
self.transducers.append(transducer)
@overrides
def print_help(self, file=sys.stdout):
file.write(_('Transducer group "{0}":\n').format(self.name))
if self.description:
file.write(_(' Description: {0}\n').format(self.description))
file.write(_(' Transducers:\n {0}').format('\n '.join(map(str, self.transducers))))
file.write('\n')
@overrides
def substitute(self, string, indices):
for transducer in self.transducers:
string, indices = transducer.substitute(string, indices)
return string, indices
class MasterTransducer(Transducer):
"""
A collection of transducers. This class is intended to be used as a singleton.
"""
def __init__(self):
super().__init__([])
self.transducers = OrderedDict()
self.groups = OrderedDict()
self.selected = OrderedSet()
self.parser = None
def add(self, transducer, groups=None):
"""
Registers a `Transducer`.
The transducers are guaranteed to execute in the order in which they are added.
"""
assert isinstance(transducer, Transducer)
name = transducer.name
assert name is not None
assert name not in self.transducers.keys(), 'Duplicit transducer "{0}"'.format(name)
self.transducers[name] = transducer
for group in groups:
assert group in self.groups.values()
group.add(transducer)
def add_group(self, name, description=None):
"""
Creates and registers a transducer group.
:param name: the name of the group
:param description: the description of the group
:return: the constructed group instance
"""
assert name not in self.groups.keys(), 'Duplicit group "{0}"'.format(name)
group = TransducerGroup(name, description)
self.groups[name] = group
return group
def add_arguments(self, parser):
"""
Registers command line arguments that control this `MasterTransducer` in an :py:mod:`ArgumentParser`.
:param parser: an :py:mod:`ArgumentParser`
"""
assert isinstance(parser, ArgumentParser)
self.parser = parser
group_names = list(self.groups.keys())
parser.add_argument('--group', '-g', nargs='+', action='append', choices=group_names, metavar='G',
help=_(
'Enables the transducer group G. Combine with --help to show detailed information. Available groups: {0}').format(
', '.join(group_names)))
transducer_names = list(self.transducers.keys())
parser.add_argument('--transducer', '-t', nargs='+', action='append', choices=transducer_names, metavar='T',
help=_(
'Enables the transducer T. Combine with --help to show detailed information. Available transducers: {0}').format(
', '.join(transducer_names)))
def configure(self, args, file=sys.stdout):
"""
Configures this `MasterTransducer` using the arguments parsed by an :py:mod:`ArgumentParser`.
:param args: command line arguments parsed by an :py:mod:`ArgumentParser`
:param file: the file to print help string to
"""
self.selected = OrderedSet()
if args.group:
for group_name in chain.from_iterable(args.group):
group = self.groups[group_name]
if args.help:
self.parser.print_help(file)
file.write('\n')
group.print_help(file)
self.parser.exit()
for transducer in group.transducers:
self.selected.add(transducer)
if args.transducer:
for transducer_name in chain.from_iterable(args.transducer):
transducer = self.transducers[transducer_name]
if args.help:
self.parser.print_help(file)
file.write('\n')
transducer.print_help(file)
self.parser.exit()
self.selected.add(transducer)
if len(self.selected) == 0:
# If no transducer is selected explicitly, all transducers are used.
self.selected = self.transducers.values()
@overrides
def substitute(self, string, indices):
"""
Translates a string using the selected transducers.
"""
for transducer in self.selected:
string, indices = transducer.substitute(string, indices)
return string, indices
master = MasterTransducer()