error-align 0.1.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- error_align/__init__.py +7 -0
- error_align/backtrace_graph.py +258 -0
- error_align/baselines/__init__.py +10 -0
- error_align/baselines/optimal_word_alignment.py +111 -0
- error_align/baselines/power/normalize/__init__.py +3 -0
- error_align/baselines/power/normalize/contractions.py +152 -0
- error_align/baselines/power/normalize/normalize.py +295 -0
- error_align/baselines/power/normalize/numbers.py +289 -0
- error_align/baselines/power/power/__init__.py +3 -0
- error_align/baselines/power/power/aligner.py +467 -0
- error_align/baselines/power/power/levenshtein.py +576 -0
- error_align/baselines/power/power/phonemes.py +16 -0
- error_align/baselines/power/power/pronounce.py +85 -0
- error_align/baselines/power/power/punct.py +166 -0
- error_align/baselines/power/power/readers.py +48 -0
- error_align/baselines/power/power/writers.py +259 -0
- error_align/baselines/power_alignment.py +61 -0
- error_align/baselines/rapidfuzz_word_alignment.py +100 -0
- error_align/baselines/utils.py +93 -0
- error_align/edit_distance.py +144 -0
- error_align/error_align.py +495 -0
- error_align/func.py +38 -0
- error_align/utils.py +166 -0
- error_align-0.1.0b1.dist-info/METADATA +161 -0
- error_align-0.1.0b1.dist-info/RECORD +26 -0
- error_align-0.1.0b1.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,576 @@
|
|
|
1
|
+
from __future__ import division
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
import re
|
|
5
|
+
from collections import Counter, defaultdict, deque
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AlignLabels:
|
|
9
|
+
correct = 'C'
|
|
10
|
+
substitution = 'S'
|
|
11
|
+
insertion = 'I'
|
|
12
|
+
deletion = 'D'
|
|
13
|
+
validOptions = set([correct, substitution, insertion, deletion])
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ExpandedAlignment:
|
|
17
|
+
'''Levenshtein-aligned reference and hypothesis, not just edit distance score.'''
|
|
18
|
+
|
|
19
|
+
def __init__(self, s1, s2, align, s1_map=None, s2_map=None, lowercase=False):
|
|
20
|
+
if not (len(s1) == len(s2) == len(align)):
|
|
21
|
+
raise Exception("Length mismatch: align:{0:d}, s1:{1:d}, s2:{2:d}".format(
|
|
22
|
+
len(align), len(s1), len(s2)))
|
|
23
|
+
if len(align) == 0:
|
|
24
|
+
raise Exception("No alignment: strings are empty")
|
|
25
|
+
|
|
26
|
+
self.s1 = s1
|
|
27
|
+
self.s2 = s2
|
|
28
|
+
self.align = align
|
|
29
|
+
self.s1_map = s1_map
|
|
30
|
+
self.s2_map = s2_map
|
|
31
|
+
self.lowercase = lowercase
|
|
32
|
+
|
|
33
|
+
if not s1_map or s2_map:
|
|
34
|
+
self.recompute_alignment_maps()
|
|
35
|
+
|
|
36
|
+
def __str__(self):
|
|
37
|
+
widths = [max(len(self.s1[i]), len(self.s2[i]))
|
|
38
|
+
for i in range(len(self.s1))]
|
|
39
|
+
s1_args = zip(widths, self.s1)
|
|
40
|
+
s2_args = zip(widths, self.s2)
|
|
41
|
+
align_args = zip(widths, self.align)
|
|
42
|
+
|
|
43
|
+
value = 'REF: %s\n' % ' '.join(['%-*s' % x for x in s1_args])
|
|
44
|
+
value += 'HYP: %s\n' % ' '.join(['%-*s' % x for x in s2_args])
|
|
45
|
+
value += 'Eval: %s' % ' '.join(['%-*s' % x for x in align_args])
|
|
46
|
+
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
def s1_string(self):
|
|
50
|
+
return ' '.join(self.s1_tokens())
|
|
51
|
+
|
|
52
|
+
def s2_string(self):
|
|
53
|
+
return ' '.join(self.s2_tokens())
|
|
54
|
+
|
|
55
|
+
def s1_tokens(self):
|
|
56
|
+
return [x for x in self.s1 if x != '']
|
|
57
|
+
|
|
58
|
+
def s2_tokens(self):
|
|
59
|
+
return [x for x in self.s2 if x != '']
|
|
60
|
+
|
|
61
|
+
def s1_align_tokens(self, i):
|
|
62
|
+
return self.s1[i].split()
|
|
63
|
+
|
|
64
|
+
def s2_align_tokens(self, i):
|
|
65
|
+
return self.s2[i].split()
|
|
66
|
+
|
|
67
|
+
def ref(self):
|
|
68
|
+
return self.s1_tokens()
|
|
69
|
+
|
|
70
|
+
def hyp(self):
|
|
71
|
+
return self.s2_tokens()
|
|
72
|
+
|
|
73
|
+
def length(self):
|
|
74
|
+
return len(self.align)
|
|
75
|
+
|
|
76
|
+
def pos(self, word):
|
|
77
|
+
s1_idx = [i for i in range(len(self.s1)) if self.s1[i] == word]
|
|
78
|
+
s2_idx = [i for i in range(len(self.s2)) if self.s2[i] == word]
|
|
79
|
+
|
|
80
|
+
return s1_idx, s2_idx
|
|
81
|
+
|
|
82
|
+
def subsequence(self, i, j, preserve_index=False):
|
|
83
|
+
# TODO: Right now we're losing any s1_map and s2_map components for compatibility reasons. Refactoring necessary.
|
|
84
|
+
scale = 0 if preserve_index else i
|
|
85
|
+
s1_map = [self.s1_map[k] -
|
|
86
|
+
scale for k in range(len(self.s1_map)) if i <= self.s1_map[k] < j]
|
|
87
|
+
s2_map = [self.s2_map[k] -
|
|
88
|
+
scale for k in range(len(self.s2_map)) if i <= self.s2_map[k] < j]
|
|
89
|
+
return ExpandedAlignment(self.s1[i:j], self.s2[i:j], self.align[i:j], s1_map, s2_map, lowercase=self.lowercase)
|
|
90
|
+
|
|
91
|
+
def split_error_regions(self, error_pattern='[SDI]*S[SDI]+|[SDI]+S[SDI]*'):
|
|
92
|
+
'''
|
|
93
|
+
Splits the object into a list of multiple segments.
|
|
94
|
+
Some segments are defined as error regions, containing at least one substitution error.
|
|
95
|
+
These error regions may candidates for realignment to alignment precision for downstream tasks.
|
|
96
|
+
(i.e. phoneme alignment or character alignment)
|
|
97
|
+
'''
|
|
98
|
+
split_regions = []
|
|
99
|
+
error_indexes = []
|
|
100
|
+
|
|
101
|
+
p = re.compile(error_pattern)
|
|
102
|
+
# Find candidate error regions in the current utterance
|
|
103
|
+
# Matches go from left to right
|
|
104
|
+
prev_index = 0
|
|
105
|
+
|
|
106
|
+
err_str = ''.join(self.align)
|
|
107
|
+
for match in p.finditer(err_str):
|
|
108
|
+
i, j = match.span()
|
|
109
|
+
if prev_index < i:
|
|
110
|
+
# Previous items are rolled up into a 'correct' segment
|
|
111
|
+
split_regions.append(self.subsequence(prev_index, i))
|
|
112
|
+
# Get the error region
|
|
113
|
+
error_indexes.append(len(split_regions))
|
|
114
|
+
split_regions.append(self.subsequence(i, j))
|
|
115
|
+
prev_index = j
|
|
116
|
+
|
|
117
|
+
# Add the trailing segment.
|
|
118
|
+
if prev_index < len(self.align):
|
|
119
|
+
split_regions.append(self.subsequence(prev_index, len(self.align)))
|
|
120
|
+
return split_regions, error_indexes
|
|
121
|
+
|
|
122
|
+
def append_alignment(self, expanded_alignment):
|
|
123
|
+
'''
|
|
124
|
+
Concatenates a string alignment to the current object.
|
|
125
|
+
'''
|
|
126
|
+
map_offset = self.length()
|
|
127
|
+
|
|
128
|
+
self.s1 += expanded_alignment.s1
|
|
129
|
+
self.s2 += expanded_alignment.s2
|
|
130
|
+
self.align += expanded_alignment.align
|
|
131
|
+
if self.s1_map and expanded_alignment.s1_map:
|
|
132
|
+
self.s1_map += [align_pos +
|
|
133
|
+
map_offset for align_pos in expanded_alignment.s1_map]
|
|
134
|
+
if self.s2_map and expanded_alignment.s2_map:
|
|
135
|
+
self.s2_map += [align_pos +
|
|
136
|
+
map_offset for align_pos in expanded_alignment.s2_map]
|
|
137
|
+
|
|
138
|
+
def recompute_alignment_maps(self):
|
|
139
|
+
'''
|
|
140
|
+
Regenerates s1_map and s2_map based on the alignment info.
|
|
141
|
+
'''
|
|
142
|
+
self.s1_map = []
|
|
143
|
+
self.s2_map = []
|
|
144
|
+
|
|
145
|
+
for i in range(self.length()):
|
|
146
|
+
if self.align[i] in (AlignLabels.correct, AlignLabels.substitution, AlignLabels.deletion):
|
|
147
|
+
self.s1_map.extend([i] * len(self.s1[i].split()))
|
|
148
|
+
if self.align[i] in (AlignLabels.correct, AlignLabels.substitution, AlignLabels.insertion):
|
|
149
|
+
self.s2_map.extend([i] * len(self.s2[i].split()))
|
|
150
|
+
|
|
151
|
+
def error_rate(self, cluster_on_ref=False):
|
|
152
|
+
'''
|
|
153
|
+
Computes WER or POWER.
|
|
154
|
+
self.s1 is considered to be the reference and self.s2 is the hypothesis.
|
|
155
|
+
'''
|
|
156
|
+
score_components = {AlignLabels.correct: 0, AlignLabels.substitution: 0,
|
|
157
|
+
AlignLabels.deletion: 0, AlignLabels.insertion: 0, 'L': 0}
|
|
158
|
+
|
|
159
|
+
for i in range(self.length()):
|
|
160
|
+
alignment = self.align[i]
|
|
161
|
+
|
|
162
|
+
magnitude = 1
|
|
163
|
+
if alignment != AlignLabels.insertion:
|
|
164
|
+
ref_seg_length = len(self.s1[i].split())
|
|
165
|
+
hyp_seg_length = len(self.s2[i].split())
|
|
166
|
+
|
|
167
|
+
if cluster_on_ref:
|
|
168
|
+
# NOTE: This relaxes the penalty of errors like
|
|
169
|
+
# anatomy -> "and that to me"
|
|
170
|
+
# And sharply penalizes
|
|
171
|
+
# "and that to me" -> anatomy
|
|
172
|
+
# but it might be in better sync with classic WER.
|
|
173
|
+
magnitude = ref_seg_length
|
|
174
|
+
else:
|
|
175
|
+
# NOTE: This causes a mismatch between reference length and the number of substitutions! Is this a problem?
|
|
176
|
+
magnitude = max(ref_seg_length, hyp_seg_length)
|
|
177
|
+
score_components['L'] += ref_seg_length
|
|
178
|
+
|
|
179
|
+
score_components[alignment] += magnitude
|
|
180
|
+
|
|
181
|
+
if not self.s1:
|
|
182
|
+
# No reference. Error is 100%
|
|
183
|
+
error_rate = 1.0
|
|
184
|
+
else:
|
|
185
|
+
error_rate = (score_components[AlignLabels.substitution] + score_components[AlignLabels.deletion] +
|
|
186
|
+
score_components[AlignLabels.insertion]) / score_components['L']
|
|
187
|
+
return error_rate, score_components
|
|
188
|
+
|
|
189
|
+
def confusion_pairs(self):
|
|
190
|
+
d = defaultdict(Counter)
|
|
191
|
+
for i in range(len(self.align)):
|
|
192
|
+
if self.align[i] == AlignLabels.substitution:
|
|
193
|
+
s1 = self.s1[i]
|
|
194
|
+
s2 = self.s2[i]
|
|
195
|
+
if self.lowercase:
|
|
196
|
+
s1 = s1.lower()
|
|
197
|
+
s2 = s2.lower()
|
|
198
|
+
d[s1] += Counter({s2: 1})
|
|
199
|
+
return d
|
|
200
|
+
|
|
201
|
+
def alignment_capacity(self):
|
|
202
|
+
'''
|
|
203
|
+
Returns the number of word slots occupied by each alignment point.
|
|
204
|
+
'''
|
|
205
|
+
return [(len(self.s1_align_tokens(i)), len(self.s2_align_tokens(i))) for i in range(self.length())]
|
|
206
|
+
|
|
207
|
+
def hyp_oriented_alignment(self, hyp_only=True):
|
|
208
|
+
'''
|
|
209
|
+
Returns all alignment tokens.
|
|
210
|
+
If an S slot is an multiword alignment, duplicates AlignLabels.substitution by the capacity.
|
|
211
|
+
TODO: Move to subclass.
|
|
212
|
+
'''
|
|
213
|
+
alignment = []
|
|
214
|
+
ref_align_len, hyp_align_len = zip(*self.alignment_capacity())
|
|
215
|
+
|
|
216
|
+
for i in range(self.length()):
|
|
217
|
+
if hyp_only:
|
|
218
|
+
# Treat each hyp token as a substitution error
|
|
219
|
+
alignment.extend(self.align[i] * max(1, hyp_align_len[i]))
|
|
220
|
+
else:
|
|
221
|
+
len_diff = ref_align_len[i] - hyp_align_len[i]
|
|
222
|
+
if len_diff == 0:
|
|
223
|
+
alignment.extend(self.align[i] * hyp_align_len[i])
|
|
224
|
+
elif len_diff < 0:
|
|
225
|
+
len_diff = -len_diff
|
|
226
|
+
alignment.extend(self.align[i] * ref_align_len[i])
|
|
227
|
+
alignment.extend([AlignLabels.insertion] * len_diff)
|
|
228
|
+
else:
|
|
229
|
+
alignment.extend(self.align[i] * hyp_align_len[i])
|
|
230
|
+
alignment.extend([AlignLabels.deletion] * len_diff)
|
|
231
|
+
return alignment
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class Levenshtein:
|
|
235
|
+
def __init__(self, lowercase=False, tokenMap=None):
|
|
236
|
+
self.backMatrix = None
|
|
237
|
+
self.distMatrix = None
|
|
238
|
+
self.dist = -1
|
|
239
|
+
self.s1 = None
|
|
240
|
+
self.s2 = None
|
|
241
|
+
self.edits = None
|
|
242
|
+
self.lowercase = lowercase
|
|
243
|
+
|
|
244
|
+
uniformWeights = {AlignLabels.correct: 0, AlignLabels.substitution: 1,
|
|
245
|
+
AlignLabels.deletion: 1, AlignLabels.insertion: 1}
|
|
246
|
+
wordAlignWeights = {AlignLabels.correct: 0, AlignLabels.substitution: 4,
|
|
247
|
+
AlignLabels.deletion: 3, AlignLabels.insertion: 3}
|
|
248
|
+
|
|
249
|
+
@staticmethod
|
|
250
|
+
def align(ref, hyp, reserve_list=None, exclusive_sets=None, lowercase=False, weights=None, dist_penalty=0.5, dist_penalty_set=None):
|
|
251
|
+
'''
|
|
252
|
+
Creates an alignment with hyp x ref matrix.
|
|
253
|
+
reserve_list defines tokens that may never have 'S' alignments.
|
|
254
|
+
exclusive_sets defines families of tokens that can have 'S' alignments. Anything outside of exclusive_sets can be aligned to any other nonmember.
|
|
255
|
+
'''
|
|
256
|
+
if not weights:
|
|
257
|
+
weights = Levenshtein.uniformWeights
|
|
258
|
+
lev = Levenshtein(lowercase=lowercase)
|
|
259
|
+
lev.s1 = ref
|
|
260
|
+
lev.s2 = hyp
|
|
261
|
+
|
|
262
|
+
# If using distance penaties:
|
|
263
|
+
distPenaltyRef = 0
|
|
264
|
+
distPenaltyHyp = 0
|
|
265
|
+
|
|
266
|
+
if lowercase:
|
|
267
|
+
ref = [x.lower() for x in ref]
|
|
268
|
+
hyp = [x.lower() for x in hyp]
|
|
269
|
+
|
|
270
|
+
#pp = pprint.PrettyPrinter(width=300)
|
|
271
|
+
lev.backMatrix = BackTrackMatrix(len(ref), len(hyp), weights)
|
|
272
|
+
|
|
273
|
+
# Starts with 1st word in hyp
|
|
274
|
+
for index2, char2 in enumerate(hyp):
|
|
275
|
+
|
|
276
|
+
if dist_penalty_set and char2 not in dist_penalty_set:
|
|
277
|
+
distPenaltyRef += 1
|
|
278
|
+
else:
|
|
279
|
+
distPenaltyRef = 0
|
|
280
|
+
|
|
281
|
+
# Loop through columns, corresponding to characters in hyp
|
|
282
|
+
for index1, char1 in enumerate(ref):
|
|
283
|
+
if dist_penalty_set and char1 not in dist_penalty_set:
|
|
284
|
+
distPenaltyHyp += 1
|
|
285
|
+
else:
|
|
286
|
+
distPenaltyHyp = 0
|
|
287
|
+
|
|
288
|
+
match_char = AlignLabels.substitution
|
|
289
|
+
# Add insert/delete options
|
|
290
|
+
insPenalty = lev.backMatrix.getWeight(
|
|
291
|
+
index2, index1+1) + weights[AlignLabels.insertion]
|
|
292
|
+
delPenalty = lev.backMatrix.getWeight(
|
|
293
|
+
index2+1, index1) + weights[AlignLabels.deletion]
|
|
294
|
+
|
|
295
|
+
if dist_penalty_set:
|
|
296
|
+
insPenalty += (distPenaltyHyp * dist_penalty) * \
|
|
297
|
+
weights[AlignLabels.insertion]
|
|
298
|
+
delPenalty += (distPenaltyRef * dist_penalty) * \
|
|
299
|
+
weights[AlignLabels.deletion]
|
|
300
|
+
|
|
301
|
+
opts = [insPenalty, # I
|
|
302
|
+
delPenalty, # D
|
|
303
|
+
]
|
|
304
|
+
|
|
305
|
+
if char1 == char2:
|
|
306
|
+
opts.append(lev.backMatrix.getWeight(
|
|
307
|
+
index2, index1) + weights[AlignLabels.correct]) # C
|
|
308
|
+
match_char = AlignLabels.correct
|
|
309
|
+
elif not reserve_list or not (char1 in reserve_list or char2 in reserve_list):
|
|
310
|
+
if exclusive_sets:
|
|
311
|
+
# Check if char1 and char2 belong to the same exclusive set
|
|
312
|
+
no_membership_set = set([-1])
|
|
313
|
+
|
|
314
|
+
# Change this to handle multiple set membership
|
|
315
|
+
char1_sets = set(
|
|
316
|
+
[k for k in range(len(exclusive_sets)) if char1 in exclusive_sets[k]])
|
|
317
|
+
if not char1_sets:
|
|
318
|
+
char1_sets = no_membership_set
|
|
319
|
+
char2_sets = set(
|
|
320
|
+
[k for k in range(len(exclusive_sets)) if char2 in exclusive_sets[k]])
|
|
321
|
+
if not char2_sets:
|
|
322
|
+
char2_sets = no_membership_set
|
|
323
|
+
|
|
324
|
+
if set.intersection(char1_sets, char2_sets):
|
|
325
|
+
opts.append(lev.backMatrix.getWeight(
|
|
326
|
+
index2, index1) + weights[AlignLabels.substitution]) # S
|
|
327
|
+
else:
|
|
328
|
+
opts.append(lev.backMatrix.getWeight(
|
|
329
|
+
index2, index1) + weights[AlignLabels.substitution]) # S
|
|
330
|
+
|
|
331
|
+
# Get the locally minimum score and edit operation
|
|
332
|
+
minDist = min(opts)
|
|
333
|
+
minIndices = [i for i in reversed(
|
|
334
|
+
range(len(opts))) if opts[i] == minDist]
|
|
335
|
+
|
|
336
|
+
# Build the backtrack
|
|
337
|
+
alignLabels = []
|
|
338
|
+
for minIndex in minIndices:
|
|
339
|
+
if minIndex == 2:
|
|
340
|
+
alignLabels.append(match_char)
|
|
341
|
+
elif minIndex == 0:
|
|
342
|
+
alignLabels.append(AlignLabels.insertion)
|
|
343
|
+
elif minIndex == 1:
|
|
344
|
+
alignLabels.append(AlignLabels.deletion)
|
|
345
|
+
|
|
346
|
+
lev.backMatrix.addBackTrack(
|
|
347
|
+
index2+1, index1+1, alignLabels, minDist) # S/C
|
|
348
|
+
pass
|
|
349
|
+
|
|
350
|
+
lev.dist = lev.backMatrix.getWeight(
|
|
351
|
+
lev.backMatrix.hyplen, lev.backMatrix.reflen)
|
|
352
|
+
return lev
|
|
353
|
+
|
|
354
|
+
def matchPositions(self, token, token2=None, min_i=None, min_j=None, max_i=None, max_j=None):
|
|
355
|
+
if not min_i:
|
|
356
|
+
min_i = 0
|
|
357
|
+
if not max_i:
|
|
358
|
+
max_i = len(self.s2)
|
|
359
|
+
|
|
360
|
+
if not min_j:
|
|
361
|
+
min_j = 0
|
|
362
|
+
if not max_j:
|
|
363
|
+
max_j = len(self.s1)
|
|
364
|
+
|
|
365
|
+
if not token2:
|
|
366
|
+
token2 = token
|
|
367
|
+
|
|
368
|
+
# Find match positions of token in hyp
|
|
369
|
+
hypIdx = [i+1 for i in range(min_i, max_i) if self.s2[i] == token]
|
|
370
|
+
refIdx = [j+1 for j in range(min_j, max_j) if self.s1[j] == token]
|
|
371
|
+
|
|
372
|
+
return list(itertools.product(*[hypIdx, refIdx]))
|
|
373
|
+
|
|
374
|
+
def bestPathsGraph(self, minPos=None, maxPos=None):
|
|
375
|
+
"""
|
|
376
|
+
Takes all of the best Levenshtein alignment backtrack paths and puts them in a graph.
|
|
377
|
+
The graph is weighted by the distance between minPos and maxPos for all paths.
|
|
378
|
+
"""
|
|
379
|
+
import networkx as nx
|
|
380
|
+
if not minPos:
|
|
381
|
+
minPos = (0, 0)
|
|
382
|
+
if not maxPos:
|
|
383
|
+
maxPos = (self.backMatrix.hyplen, self.backMatrix.reflen)
|
|
384
|
+
|
|
385
|
+
chart = deque()
|
|
386
|
+
chart.appendleft(maxPos)
|
|
387
|
+
|
|
388
|
+
G = nx.Graph()
|
|
389
|
+
|
|
390
|
+
from time import time
|
|
391
|
+
start = time()
|
|
392
|
+
while chart:
|
|
393
|
+
(i, j) = chart.pop()
|
|
394
|
+
|
|
395
|
+
for alignLabel in self.backMatrix.matrix[i][j].backTrackOptions:
|
|
396
|
+
child = self.backMatrix.matrix[i][j].getBackTrackOffset(
|
|
397
|
+
alignLabel)
|
|
398
|
+
prev_i = i + child[1][0]
|
|
399
|
+
prev_j = j + child[1][1]
|
|
400
|
+
|
|
401
|
+
align = child[0]
|
|
402
|
+
rlabel = self.s1[j-1] if prev_j < j else ''
|
|
403
|
+
hlabel = self.s2[i-1] if prev_i < i else ''
|
|
404
|
+
|
|
405
|
+
# Weight applied based on whether (i & prev_i) or (j & prev_j) are along the hull of minPos or maxPos
|
|
406
|
+
weight = 1
|
|
407
|
+
if (i == prev_i and i in (minPos[0], maxPos[0])) or (j == prev_j and j in (minPos[1], maxPos[1])):
|
|
408
|
+
weight = 0
|
|
409
|
+
|
|
410
|
+
G.add_edge((i, j), (prev_i, prev_j), weight=weight,
|
|
411
|
+
labels=(rlabel, hlabel, align))
|
|
412
|
+
chart.appendleft((prev_i, prev_j))
|
|
413
|
+
|
|
414
|
+
if time() - start > 120:
|
|
415
|
+
print("\nWarning: Long computation time\n")
|
|
416
|
+
raise AssertionError("Computation took too long")
|
|
417
|
+
return G
|
|
418
|
+
|
|
419
|
+
def editops(self):
|
|
420
|
+
'''
|
|
421
|
+
Records edit distance operations in a compact format, changing s1 to s2.
|
|
422
|
+
'''
|
|
423
|
+
i = self.backMatrix.hyplen
|
|
424
|
+
j = self.backMatrix.reflen
|
|
425
|
+
back = []
|
|
426
|
+
|
|
427
|
+
while i > 0 or j > 0:
|
|
428
|
+
op = self.backMatrix.matrix[i][j].getBackTrackOffset()
|
|
429
|
+
off_i, off_j = op[1]
|
|
430
|
+
i += off_i
|
|
431
|
+
j += off_j
|
|
432
|
+
back.append((op[0], (i, j)))
|
|
433
|
+
|
|
434
|
+
back.reverse()
|
|
435
|
+
self.edits = back
|
|
436
|
+
return back
|
|
437
|
+
|
|
438
|
+
def expandAlign(self):
|
|
439
|
+
'''
|
|
440
|
+
Expands the edit operations to actually align the strings.
|
|
441
|
+
Also contains maps to track the positions of each character in the strings
|
|
442
|
+
to its aligned position.
|
|
443
|
+
'''
|
|
444
|
+
if not self.edits:
|
|
445
|
+
return None
|
|
446
|
+
|
|
447
|
+
s1 = []
|
|
448
|
+
s2 = []
|
|
449
|
+
align = []
|
|
450
|
+
s1_map = []
|
|
451
|
+
s2_map = []
|
|
452
|
+
|
|
453
|
+
for op in self.edits:
|
|
454
|
+
a = op[0]
|
|
455
|
+
i, j = op[1]
|
|
456
|
+
|
|
457
|
+
# Bugfix for empty hypotheses or reference (reference shouldn't happen)
|
|
458
|
+
c1 = None
|
|
459
|
+
c2 = None
|
|
460
|
+
if -1 < j < len(self.s1):
|
|
461
|
+
c1 = self.s1[j]
|
|
462
|
+
if -1 < i < len(self.s2):
|
|
463
|
+
c2 = self.s2[i]
|
|
464
|
+
|
|
465
|
+
if a == AlignLabels.deletion:
|
|
466
|
+
s1.append(c1)
|
|
467
|
+
s2.append('')
|
|
468
|
+
s1_map.append(len(align))
|
|
469
|
+
elif a == AlignLabels.insertion:
|
|
470
|
+
s1.append('')
|
|
471
|
+
s2.append(c2)
|
|
472
|
+
s2_map.append(len(align))
|
|
473
|
+
else:
|
|
474
|
+
s1.append(c1)
|
|
475
|
+
s2.append(c2)
|
|
476
|
+
s1_map.append(len(align))
|
|
477
|
+
s2_map.append(len(align))
|
|
478
|
+
|
|
479
|
+
align.append(a)
|
|
480
|
+
|
|
481
|
+
return ExpandedAlignment(s1, s2, align, s1_map, s2_map, lowercase=self.lowercase)
|
|
482
|
+
|
|
483
|
+
def expandAlignCompact(self, minPos=None, maxPos=None):
|
|
484
|
+
"""
|
|
485
|
+
Using the backtracking matrix, finds all of the paths with the minimum Levenshtein distance score and stores them in a graph.
|
|
486
|
+
Then, it returns the expanded alignment of the shortest path in the graph (which still has the same minimum Lev distance score.
|
|
487
|
+
"""
|
|
488
|
+
import networkx as nx
|
|
489
|
+
minPos = (0, 0)
|
|
490
|
+
maxPos = (self.backMatrix.hyplen, self.backMatrix.reflen)
|
|
491
|
+
G = self.bestPathsGraph(minPos, maxPos)
|
|
492
|
+
path = nx.shortest_path(
|
|
493
|
+
G, source=minPos, target=maxPos, weight='weight')
|
|
494
|
+
|
|
495
|
+
# Expand the best path into the Levenshtein alignment.
|
|
496
|
+
s1_align, s2_align, align = [list(a) for a in zip(
|
|
497
|
+
*(G[u][v]['labels'] for (u, v) in zip(path[0:], path[1:])))]
|
|
498
|
+
return ExpandedAlignment(s1_align, s2_align, align, lowercase=self.lowercase)
|
|
499
|
+
|
|
500
|
+
@staticmethod
|
|
501
|
+
def errorRate(s, d, i, reflength):
|
|
502
|
+
return (s + d + i) / reflength
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
class BackTrackMatrix:
|
|
506
|
+
def __init__(self, reflen, hyplen, weights=Levenshtein.uniformWeights):
|
|
507
|
+
self.reflen = reflen
|
|
508
|
+
self.hyplen = hyplen
|
|
509
|
+
self.weights = weights
|
|
510
|
+
|
|
511
|
+
self.matrix = [[None] * (reflen+1) for i in range(hyplen+1)]
|
|
512
|
+
self.row_count = hyplen + 1
|
|
513
|
+
self.col_count = reflen + 1
|
|
514
|
+
|
|
515
|
+
# Initialize the top corner.
|
|
516
|
+
self.matrix[0][0] = BackTrackSlot(0)
|
|
517
|
+
|
|
518
|
+
# Initialize first column.
|
|
519
|
+
for i in range(1, self.row_count):
|
|
520
|
+
self.addBackTrack(i, 0, AlignLabels.insertion,
|
|
521
|
+
i*weights[AlignLabels.insertion])
|
|
522
|
+
|
|
523
|
+
# Initialize columns.
|
|
524
|
+
for j in range(1, self.col_count):
|
|
525
|
+
self.addBackTrack(0, j, AlignLabels.deletion,
|
|
526
|
+
j*weights[AlignLabels.deletion])
|
|
527
|
+
|
|
528
|
+
def addBackTrack(self, i, j, alignLabels, weight=1.0):
|
|
529
|
+
self.matrix[i][j] = BackTrackSlot(weight)
|
|
530
|
+
self.matrix[i][j].addOptions(alignLabels)
|
|
531
|
+
|
|
532
|
+
def backTrackOptions(self, i, j):
|
|
533
|
+
return self.matrix[i][j]
|
|
534
|
+
|
|
535
|
+
def getWeight(self, i, j):
|
|
536
|
+
return self.matrix[i][j].weight
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
class BackTrackSlot:
|
|
540
|
+
def __init__(self, weight):
|
|
541
|
+
self.weight = weight
|
|
542
|
+
self.backTrackOptions = list()
|
|
543
|
+
|
|
544
|
+
def __str__(self):
|
|
545
|
+
return "({0}, {1})".format(self.weight, ','.join(list(self.backTrackOptions)))
|
|
546
|
+
|
|
547
|
+
def iterOptions(self):
|
|
548
|
+
return iter(self.backTrackOptions)
|
|
549
|
+
|
|
550
|
+
def addOption(self, alignLabel):
|
|
551
|
+
if alignLabel not in self.backTrackOptions:
|
|
552
|
+
self.backTrackOptions.append(alignLabel)
|
|
553
|
+
|
|
554
|
+
def addOptions(self, alignLabels):
|
|
555
|
+
self.backTrackOptions.extend(
|
|
556
|
+
[x for x in alignLabels if x not in self.backTrackOptions])
|
|
557
|
+
|
|
558
|
+
def getBackTrackOffset(self, alignLabel=None):
|
|
559
|
+
if alignLabel:
|
|
560
|
+
# Make sure it exists
|
|
561
|
+
if alignLabel not in AlignLabels.validOptions:
|
|
562
|
+
raise Exception("Invalid backtrack option: %s" % alignLabel)
|
|
563
|
+
if alignLabel not in self.backTrackOptions:
|
|
564
|
+
raise Exception("Illegal backtrack option: %s" % alignLabel)
|
|
565
|
+
else:
|
|
566
|
+
# Just arbitrarily grab the first item
|
|
567
|
+
alignLabel = self.backTrackOptions[0]
|
|
568
|
+
|
|
569
|
+
offset = None
|
|
570
|
+
if alignLabel in (AlignLabels.correct, AlignLabels.substitution):
|
|
571
|
+
offset = (-1, -1)
|
|
572
|
+
elif alignLabel == AlignLabels.deletion:
|
|
573
|
+
offset = (0, -1)
|
|
574
|
+
else:
|
|
575
|
+
offset = (-1, 0)
|
|
576
|
+
return (alignLabel, offset)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
class Phonemes(object):
|
|
2
|
+
# Vowels
|
|
3
|
+
monophthongs = set(['ao', 'aa', 'iy', 'uw', 'eh', 'ih', 'uh', 'ah', 'ax', 'ae'])
|
|
4
|
+
diphthongs = set(['ey', 'ay', 'ow', 'aw', 'oy'])
|
|
5
|
+
# Add r-colored monophthongs?
|
|
6
|
+
r_vowels = set(['er', 'axr']) # The remaining are split into two tokens.
|
|
7
|
+
vowels = set.union(monophthongs, diphthongs, r_vowels)
|
|
8
|
+
|
|
9
|
+
# Consonants
|
|
10
|
+
c_stops = set(['p','b','t','d','k','g'])
|
|
11
|
+
c_afficates = set(['ch','jh'])
|
|
12
|
+
c_fricatives = set(['f','v','th','dh','s','z','sh','zh','hh'])
|
|
13
|
+
c_nasals = set(['m','em','n','en','ng','eng'])
|
|
14
|
+
c_liquids = set(['l','el','r','dx','nx'])
|
|
15
|
+
c_semivowels = set(['y','w','q'])
|
|
16
|
+
consonants = set.union(c_stops, c_afficates, c_fricatives, c_nasals, c_liquids, c_semivowels)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
'''
|
|
2
|
+
Created on Mar 30, 2015
|
|
3
|
+
|
|
4
|
+
@author: Nick Ruiz
|
|
5
|
+
Assuming you have a file of word sequences, this processes them through Festival to generate pronunciations.
|
|
6
|
+
|
|
7
|
+
'''
|
|
8
|
+
import json
|
|
9
|
+
from itertools import groupby
|
|
10
|
+
|
|
11
|
+
import pyphen
|
|
12
|
+
|
|
13
|
+
from error_align.baselines.power.normalize import NumToTextEng, splitHyphens
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PronouncerType:
|
|
17
|
+
Base = "base"
|
|
18
|
+
Lexicon = "lexicon"
|
|
19
|
+
|
|
20
|
+
class PronouncerBase(object):
|
|
21
|
+
def __init__(self):
|
|
22
|
+
pass
|
|
23
|
+
def pronounce(self, words):
|
|
24
|
+
'''G2P conversion'''
|
|
25
|
+
raise NotImplementedError
|
|
26
|
+
|
|
27
|
+
class PronouncerLex(PronouncerBase):
|
|
28
|
+
'''Lexicon-based pronunciation generator. Looks up words in the lexicon and if they aren't found, uses a hacky alternative.
|
|
29
|
+
NOTE: English-only
|
|
30
|
+
'''
|
|
31
|
+
def __init__(self, lexicon):
|
|
32
|
+
with open(lexicon, 'r') as f:
|
|
33
|
+
self.lexicon = json.load(f)
|
|
34
|
+
self.fallbackDict = pyphen.Pyphen(lang='en_US')
|
|
35
|
+
|
|
36
|
+
def pronounce(self, words):
|
|
37
|
+
'''G2P using Pyphen + heuristics'''
|
|
38
|
+
wordsLower = (w.lower() for w in words)
|
|
39
|
+
prons = [self.lexicon[w] if w in self.lexicon else self.alt_pronounce(
|
|
40
|
+
w) for w in wordsLower]
|
|
41
|
+
return "| {0} |".format(' | '.join(prons)).split()
|
|
42
|
+
|
|
43
|
+
def alt_pronounce(self, word):
|
|
44
|
+
'''Alternative ways to pronounce the word. Adds simple digit to word conversion'''
|
|
45
|
+
prons = []
|
|
46
|
+
# Split words along hyphens
|
|
47
|
+
wordsSplit = splitHyphens(' '.join(word))
|
|
48
|
+
# Instead of one word, we may have many
|
|
49
|
+
for myword in wordsSplit:
|
|
50
|
+
if myword.isdigit():
|
|
51
|
+
words = NumToTextEng.convert(int(myword)).split()
|
|
52
|
+
pron = ' # '.join((self.pyphen_pronounce(w) for w in words))
|
|
53
|
+
else:
|
|
54
|
+
pron = self.pyphen_pronounce(myword)
|
|
55
|
+
prons.append(pron)
|
|
56
|
+
# Although the hyphenated word is now pronounced as multiple "words",
|
|
57
|
+
# we treat again as a single word with multiple syllables
|
|
58
|
+
return ' # '.join(prons)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def pyphen_pronounce(self, word):
|
|
62
|
+
''' Uses pyphen as a back-off to generate a pseudo-hyphenated-pronounciation for words not in the lexicon. '''
|
|
63
|
+
syllables = self.fallbackDict.inserted(word).split('-')
|
|
64
|
+
pron = []
|
|
65
|
+
for syl in syllables:
|
|
66
|
+
m = 0
|
|
67
|
+
n = len(syl)
|
|
68
|
+
sylpron = []
|
|
69
|
+
while m < n:
|
|
70
|
+
pronidx = [(n-i, self.lexicon[syl[m:n-i]])
|
|
71
|
+
for i in range(n) if syl[m:n-i] in self.lexicon]
|
|
72
|
+
if not pronidx:
|
|
73
|
+
break
|
|
74
|
+
j, p = pronidx[0]
|
|
75
|
+
sylpron.append(p)
|
|
76
|
+
m = j
|
|
77
|
+
if not sylpron:
|
|
78
|
+
# TODO: No dictionary entries found for this word. Error?
|
|
79
|
+
# Break syl into characters
|
|
80
|
+
sylpron = syl
|
|
81
|
+
|
|
82
|
+
# Remove duplicate adjacent phonemes
|
|
83
|
+
sylpron = list(i for i, x in groupby(sylpron))
|
|
84
|
+
pron.append(' '.join(sylpron))
|
|
85
|
+
return ' # '.join(pron)
|