forked from SETI/rms-webtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslator.py
executable file
·613 lines (441 loc) · 19.8 KB
/
translator.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
################################################################################
# translator.py
#
# An abstract class and subclasses for mapping strings such as file paths to
# other information. It is implemented in several ways including Python
# dictionaries and regular expression/substitution pairs.
################################################################################
import os
import re
class Translator(object):
"""Abstract class to define translators from a set of strings (such as file
paths) to associated information.
All subclasses implement the following methods:
Translator.all(strings, strings_first=False)
Translator.first(strings, strings_first=False)
Input is a list of strings. The Translator object tests each string and
determines if it passes a test. If it does pass the test, then one or more
"translated" strings are returned.
Translator.all() returns every translated string. Translator.first() returns
the first translated string.
If input argument strings_first is True, then every test is applied to the
first string, after which every test is applied to the second string, etc.
If strings_first is False, then the first test is applied to every string,
after which the second test is applied to every string, etc. This can affect
the order of the translated strings returned by all(), or the single
translated string that is returned by first().
"""
def __add__(self, other):
return self.append(other)
def __iadd__(self, other):
return self.append(other)
################################################################################
################################################################################
class TranslatorBySequence(Translator):
"""Translator defined by a sequence of other translators."""
TAG = 'SEQUENCE'
def __init__(self, args):
for arg in args:
assert isinstance(arg, Translator)
self.sequence = args
def all(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning every unique
result in priority order."""
# Convert an individual string to a list
if isinstance(strings, str):
strings = [strings]
# Initialize the set of results
results = []
# Two options for priority...
if strings_first: # Try each string in order
for string in strings:
for translator in self.sequence:
partial_results = translator.all(string)
if partial_results:
for item in partial_results:
if item not in results:
results.append(item)
else: # Try each translator in order
for translator in self.sequence:
partial_results = translator.all(strings)
if partial_results:
for item in partial_results:
if item not in results:
results.append(item)
return results
def first(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning the first
result. Return None if no translation is found."""
# Convert an individual string to a list
if isinstance(strings, str):
strings = [strings]
# Two options for priority...
if strings_first: # Try each string in order
for string in strings:
for translator in self.sequence:
result = translator.first(string)
if result is not None: return result
else: # Try each string in order
for translator in self.sequence:
result = translator.first(strings)
if result is not None: return result
return None
def keys(self):
"""Return all of the keys."""
key_list = []
for translator in self.sequence:
key_list.append(translator.keys())
return key_list
def values(self):
"""Return all of the values in the same order as keys()."""
value_list = []
for translator in self.sequence:
value_list.append(translator.values())
return value_list
def prepend(self, translator):
"""Return a new translator with the given translator in front of this
one."""
if translator.TAG == 'NULL': return translator
# If arg is also a sequence, merge
if translator.TAG == self.TAG:
return TranslatorBySequence(translator.sequence + self.sequence)
# If arg matches class of first in sequence, merge
if translator.TAG == self.sequence[0].TAG:
new_translator = self.sequence[0].prepend(translator)
if new_translator.TAG == translator.TAG:
return TranslatorBySequence([new_translator] +
self.sequence[1:])
return TranslatorBySequence([translator, self])
def append(self, translator):
"""Return a new translator with the given translator after this one.
"""
if translator.TAG == 'NULL': return translator
# If arg is also a sequence, merge
if translator.TAG == 'SEQUENCE':
return TranslatorBySequence(self.sequence + translator.sequence,
self.key_priority)
# If arg matches class of last in sequence, merge
if translator.TAG == self.sequence[-1].TAG:
new_translator = self.sequence[-1].append(translator)
if new_translator.TAG == translator.TAG:
return TranslatorBySequence(self.sequence[:-1] +
[new_translator])
return TranslatorBySequence([self, translator])
################################################################################
################################################################################
class TranslatorByDict(Translator):
"""Translator defined by a standard dictionary. Fast but inflexible.
If the value is string containing "\1", that substring is replaced by the
key.
A second translator, if provided, translates strings into the keys used in
the dictionary.
"""
TAG = 'DICT'
def __init__(self, arg, path_translator=None):
assert isinstance(arg, dict)
self.dict = arg
self.path_translator = path_translator
def all(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning every unique
result in priority order.
For this subclass, strings_first is ignored."""
# Convert an individual string to a list
if isinstance(strings, str):
strings = [strings]
# Convert the strings to dictionary keys
if self.path_translator is None:
keys = strings
else:
keys = self.path_translator.all(strings)
# Initialize the set of results
results = []
# Test keys in order
for key in keys:
if key in self.dict:
result = self.dict[key]
expanded = TranslatorByDict.expand(result, key)
for result in expanded:
if result not in results:
results.append(result)
return results
def first(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning the first
result. Return None if no translation is found."""
# Convert an individual string to a list
if isinstance(strings, str):
strings = [strings]
# Convert the strings to dictionary keys, preserving order
if self.path_translator is None:
keys = strings
else:
keys = self.path_translator.all(strings)
# Test keys in order
for key in keys:
if key in self.dict:
result = self.dict[key]
expanded = TranslatorByDict.expand(result, key)
return expanded[0]
return None
@staticmethod
def expand(results, key):
if type(results) != list:
results = [results]
expanded = []
for result in results:
if isinstance(result, str):
result = result.replace(r'\1', key)
elif type(result) == tuple:
items = []
for item in result:
if isinstance(item, str):
item = item.replace(r'\1', key)
items.append(item)
result = tuple(items)
expanded.append(result)
return expanded
def keys(self):
"""Return all of the keys (in a vaguely sensible order)."""
keylist = self.dict.keys()
keylist.sort()
return keylist
def values(self):
"""Return all of the values in the same order as keys()."""
keylist = self.keys()
return [self.dict[k] for k in keylist]
def prepend(self, translator):
"""Return a new translator with the given translator in front of this
one."""
if translator.TAG == 'NULL': return translator
if translator.TAG == 'SEQUENCE':
return translator.append(self)
return TranslatorBySequence([translator, self])
def append(self, translator):
"""Add a new translator after this one."""
if translator.TAG == 'NULL': return translator
if translator.TAG == 'SEQUENCE':
return translator.prepend(self)
return TranslatorBySequence([self, translator])
################################################################################
################################################################################
class TranslatorByRegex(Translator):
"""Translator defined by a list of tuples defining regular expressions.
Each element in the list must be a tuple:
(regular expression string, flags, value)
Upon evaluation, if the regular expression matches a given string, using the
given set of regular expression flags, then the replacement patterns are
applied to a value and the modified value is returned.
The value can be a string, a list of strings, or a tuple of strings.
"""
TAG = 'REGEX'
def __init__(self, tuples):
# Compile regular expressions (if not already compiled)
compiled_tuples = []
for items in tuples:
if len(items) == 2:
if isinstance(items[0], str):
items = (re.compile('^' + items[0] + '$'), items[1])
compiled_tuples.append(items)
else:
regex = re.compile('^' + items[0] + '$', flags=items[1])
compiled_tuples.append((regex, items[2]))
self.tuples = compiled_tuples
def all(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning every unique
value in priority order."""
# Convert an individual string to a list
if isinstance(strings, str):
strings = [strings]
# Initialize the list of results
results = []
# Two options for priority...
if strings_first: # Try each string in order
for string in strings:
for (regex, replacement) in self.tuples:
expanded = TranslatorByRegex.expand(regex, string,
replacement)
for item in expanded:
if item not in results:
results.append(item)
else: # Try each regex in order
for (regex, replacement) in self.tuples:
for string in strings:
expanded = TranslatorByRegex.expand(regex, string,
replacement)
for item in expanded:
if item not in results:
results.append(item)
return results
def first(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning the first
result. Return None if no translation is found."""
# Convert an individual string to a list
if isinstance(strings, str):
strings = [strings]
# Two options for priority...
if strings_first: # Try each string in order
for string in strings:
for (regex, replacement) in self.tuples:
expanded = TranslatorByRegex.expand(regex, string,
replacement)
if expanded:
return expanded[0]
else: # Try each regex in order
for (regex, replacement) in self.tuples:
for string in strings:
expanded = TranslatorByRegex.expand(regex, string,
replacement)
if expanded:
return expanded[0]
return None
@staticmethod
def expand(regex, string, replacements):
"""Handle substitutions in the cases where the replacement is a list, a
string, or a tuple containing strings."""
def _fix_case(string):
# Change text following "#UPPER#" to upper case
# Change text following "#LOWER#" to lower case
# Stop changing case of text following "#MIXED#"
parts = string.split('#')
newparts = []
change = 'MIXED'
literal_hash = False
for part in parts:
if part in ('LOWER', 'UPPER', 'MIXED'):
change = part
literal_hash = False
else:
if change == 'UPPER':
part = part.upper()
elif change == 'LOWER':
part = part.lower()
if literal_hash:
newparts.append('#')
newparts.append(part)
literal_hash = True
return ''.join(newparts)
def _evaluate_dict(string):
# Evaluate an in-line dictionary expression
dicts = re.findall(r'{.*?}\[.*?\]', string)
for d in dicts:
value = eval(d)
string = string.replace(d, value)
return string
matchobj = regex.match(string)
if matchobj is None: return []
if not isinstance(replacements, list):
replacements = [replacements]
results = []
for replacement in replacements:
# If replacement is a string, apply substitution
if isinstance(replacement, str):
result = matchobj.expand(replacement)
result = _fix_case(result)
result = _evaluate_dict(result)
results.append(result)
# Deal with a tuple
elif isinstance(replacement, tuple):
items = []
for item in replacement:
if isinstance(item, str):
result = matchobj.expand(item)
result = _fix_case(result)
result = _evaluate_dict(result)
items.append(matchobj.expand(result))
else:
items.append(item)
results.append(tuple(items))
# Anything else is unchanged
else:
results.append(replacement)
return results
def keys(self):
"""Return all of the keys."""
return [t[0] for t in self.tuples]
def values(self):
"""Return all of the values in the same order as keys()."""
return [t[1] for t in self.tuples]
def prepend(self, translator):
"""Return a new translator with the given translator in front of this
one."""
if translator.TAG == 'NULL': return translator
if translator.TAG == self.TAG:
return TranslatorByRegex(translator.tuples + self.tuples)
if translator.TAG == 'SEQUENCE':
return translator.append(self)
return TranslatorBySequence([translator, self])
def append(self, translator):
"""Add a new translator after this one."""
if translator.TAG == 'NULL': return translator
if translator.TAG == self.TAG:
return TranslatorByRegex(self.tuples + translator.tuples)
if translator.TAG == 'SEQUENCE':
return translator.prepend(self)
return TranslatorBySequence([self, translator])
################################################################################
################################################################################
class NullTranslator(Translator):
"""Translator that returns nothing."""
TAG = 'NULL'
def __init__(self):
pass
def all(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning every unique
result."""
return []
def first(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning the first
result. Return None if no translation is found."""
return None
def keys(self):
"""Return all of the keys."""
return []
def values(self):
"""Return all of the values in the same order as keys()."""
return []
def prepend(self, translator):
"""Return a new translator with the given translator in front of this
one."""
return translator
def append(self, translator):
"""Return a new translator with the given translator after this one.
"""
return translator
################################################################################
################################################################################
class SelfTranslator(Translator):
"""Translator that returns itself."""
TAG = 'SELF'
def __init__(self):
pass
def all(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning every unique
result."""
return strings
def first(self, strings, strings_first=False):
"""Apply a translator to one or more strings, returning the first
result. Return None if no translation is found."""
return strings[0]
def keys(self):
"""Return all of the keys."""
return []
def values(self):
"""Return all of the values in the same order as keys()."""
return []
def prepend(self, translator):
"""Return a new translator with the given translator in front of this
one."""
if translator.TAG == self.TAG: return self
if translator.TAG == 'NULL': return self
if translator.TAG == 'SEQUENCE':
return translator.append(self)
return TranslatorBySequence([translator, self])
def append(self, translator):
"""Return a new translator with the given translator after this one.
"""
if translator.TAG == self.TAG: return self
if translator.TAG == 'NULL': return self
if translator.TAG == 'SEQUENCE':
return translator.prepend(self)
return TranslatorBySequence([self, translator])
################################################################################
################################################################################