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.
@@ -0,0 +1,295 @@
1
+ import itertools
2
+ import re
3
+ import string
4
+ from collections import defaultdict
5
+
6
+ from error_align.baselines.power.normalize import ContractionsEng, NumToTextEng, TextToNumEng
7
+
8
+
9
+ def splitHyphens(text):
10
+ return [x for x in re.split('[ -]', text) if x]
11
+
12
+ class HypothesisNormalizer(object):
13
+ '''
14
+ Normalizes a hypothesis towards a reference.
15
+ Currently numbers, hyphens, and contractions are implemented (reduce and expand).
16
+ '''
17
+
18
+ @staticmethod
19
+ def normalizeAligned(expand_align, fix_casing=False):
20
+ # Given a Levenshtein-aligned utterance pair, normalize the aligned hypothesis to look like the reference.
21
+
22
+ # Pass #1, only fix substitution errors
23
+ for i in range(expand_align.length()):
24
+ if expand_align.align[i] == 'S':
25
+ expand_align.s2[i] = HypothesisNormalizer.normalize(expand_align.s2[i], expand_align.s1[i])
26
+
27
+ if ' '.join(expand_align.s2[i]).lower() == ' '.join(expand_align.s1[i]).lower():
28
+ expand_align.align[i] = 'C'
29
+
30
+ if expand_align.align[i] == 'C' and fix_casing:
31
+ expand_align.s2[i] = expand_align.s1[i]
32
+ normed_components = expand_align.s2
33
+
34
+ # Pass #2, find error regions and correct them.
35
+ split_regions, error_indexes = expand_align.split_error_regions()
36
+ if len(error_indexes) > 0:
37
+ normed_components = []
38
+ for i in range(len(split_regions)):
39
+ if i not in error_indexes:
40
+ normed_components.append(split_regions[i].s2_string())
41
+ else:
42
+ seg = split_regions[i]
43
+ normed = HypothesisNormalizer.normalize(seg.s2_string(), seg.s1_string())
44
+ normed_components.append(normed)
45
+
46
+ return ' '.join(normed_components)
47
+
48
+ @staticmethod
49
+ def normalize(hyp, ref):
50
+ # Normalizes the hypothesis toward the reference (no alignment required).
51
+ hyp_fixed = ' '.join(HypothesisNormalizer.normalizeHyphenated(hyp, ref, removeHyphens=True))
52
+ if hyp_fixed != ref:
53
+ hyp_fixed = ' '.join(HypothesisNormalizer.normalizeHyphenated(hyp_fixed, ref, removeHyphens=False))
54
+ return hyp_fixed
55
+
56
+ @staticmethod
57
+ def normalizeHyphenated(hyp, ref, removeHyphens=False):
58
+ if removeHyphens:
59
+ refwords = splitHyphens(ref)
60
+ hypwords = splitHyphens(hyp)
61
+ else:
62
+ refwords = ref.split()
63
+ hypwords = hyp.split()
64
+
65
+ hyp_start = 0
66
+ ref_start = 0
67
+
68
+ hyp_normalized = list()
69
+
70
+ while (hyp_start < len(hypwords)):
71
+ # Find the first hyp word that may need correcting.
72
+ while (hyp_start < len(hypwords) and
73
+ ref_start < len(refwords) and
74
+ (hypwords[hyp_start].lower() == refwords[ref_start].lower())):
75
+ hyp_normalized.append(hypwords[hyp_start])
76
+ hyp_start += 1
77
+ ref_start += 1
78
+ if hyp_start < len(hypwords):
79
+ if ref_start >= len(refwords):
80
+ hyp_normalized.append(hypwords[hyp_start])
81
+ hyp_start += 1
82
+ continue
83
+
84
+ # There's a hyp word that doesn't match the ref word. Try to fix it.
85
+ ref_span_str = ' '.join(refwords[ref_start:])
86
+
87
+ hyp_match_string = None
88
+ best_ref_index_end = None
89
+ hyp_stop_index = -1
90
+ rollback_dist = 0
91
+
92
+ for hyp_span, hyp_stop_index in HypothesisNormalizer.wordSpans(hypwords, hyp_start, len(hypwords)):
93
+ # Convert the word span into a string
94
+ hyp_span_str = ' '.join(hyp_span)
95
+ # Find the normalization options for the current span
96
+ # TODO: no 'th' suffixes right now
97
+ norm_options = HypothesisNormalizer.getNormOptions(hyp_span_str)
98
+ norm_options['text'].add(hyp_span_str)
99
+ # norm_options = defaultdict(set)
100
+ # norm_options.keys() = ['text', 'num', 'textnum', 'textyear']
101
+
102
+ # Collapse the options
103
+ # sort by number of words (descending)
104
+ norm_options_collapsed = [re.escape(x) for x in
105
+ sorted(
106
+ sorted(set(itertools.chain(*norm_options.values())),
107
+ key=lambda x: -len(x)),
108
+ key=lambda x: -len(x.split()))]
109
+
110
+ # Look for matches (or near matches)
111
+ match = re.search("(^| )({0})".format("|".join(norm_options_collapsed)), ref_span_str, re.IGNORECASE)
112
+ rollback_dist += 1
113
+
114
+ # The first match should be the best match.
115
+ if not match:
116
+ # If there's a number option, try continuing to see if it can be resolved.
117
+ # TODO: This could lead to some problems.
118
+ if 'num' in norm_options:
119
+ # Check if the numbers have zeroes at the end.
120
+ zero_term_nums = [re.escape(x.rstrip('0')) for x in norm_options['num'] if len(x) > 1 and x[-1] == '0']
121
+ # Check for a partial match
122
+ if zero_term_nums and re.search("(^| )({0})".format("|".join(zero_term_nums)), ref_span_str, re.IGNORECASE):
123
+ continue
124
+ # Abandon the current hyp and move on
125
+ break
126
+
127
+ # Check if the word was completed.
128
+ best_ref_index_end = match.regs[2][1]
129
+ match_string = match.group(2)
130
+
131
+ if len(ref_span_str) == best_ref_index_end or ref_span_str[best_ref_index_end] == ' 'in set([' ', '-']):
132
+ # Full match. Store this intermediate string as a possible normalization match
133
+ hyp_match_string = match_string
134
+ rollback_dist = 0
135
+
136
+ # Check if a match was found.
137
+ if hyp_match_string:
138
+ hyp_normalized.append(hyp_match_string)
139
+ hyp_start = hyp_stop_index - rollback_dist
140
+ ref_start = len(ref_span_str[:best_ref_index_end].split(" "))
141
+ else:
142
+ hyp_normalized.append(hypwords[hyp_start])
143
+ hyp_start += 1
144
+
145
+ return hyp_normalized
146
+
147
+ @staticmethod
148
+ def wordSpans(hyp_words, start_index, end_index = -1):
149
+ '''
150
+ Generates all subsequences of words always starting at start_index.
151
+ '''
152
+ if end_index < 0:
153
+ end_index = len(hyp_words)
154
+ for stop_index in range(start_index, end_index):
155
+ yield hyp_words[start_index:stop_index+1], stop_index
156
+
157
+ @staticmethod
158
+ def normalizeHyphens(hyp, ref):
159
+ '''
160
+ Greedy algorithm. Potentially suboptimal.
161
+ '''
162
+ if not hyp:
163
+ return ""
164
+ if not ref:
165
+ return hyp
166
+
167
+ hyp_words = hyp.replace('-', ' ').split()
168
+ if hyp[0] == '-':
169
+ hyp_words[0] = '-{0}'.format(hyp_words[0])
170
+ if hyp[-1] == '-':
171
+ hyp_words[-1] = '{0}-'.format(hyp_words[-1])
172
+
173
+ hyp_word_start = 0
174
+ hyp_word_end = 0
175
+ ref_index = 0
176
+ best_ref_index = 0
177
+
178
+ hyp_fixed = []
179
+ hyp_match_string = None
180
+
181
+ end_compare = False
182
+ while hyp_word_start < len(hyp_words):
183
+ if hyp_word_end == len(hyp_words) - 1:
184
+ end_compare = True
185
+
186
+ if hyp_word_start < len(hyp_words) - 1:
187
+ # Span from hyp_word_start to hyp_word_end
188
+ hyp_span = hyp_words[hyp_word_start:hyp_word_end+1]
189
+ hyp_options = r'[ \-]'.join(hyp_span)
190
+
191
+ #print "Pattern:", hyp_options
192
+
193
+ match = re.search("({0})".format(hyp_options), ref[ref_index:], re.IGNORECASE)
194
+ if match:
195
+ best_ref_index = match.regs[1][1]
196
+ hyp_match_string = match.group(1)
197
+ hyp_word_end += 1
198
+ else:
199
+ end_compare = True
200
+ else:
201
+ end_compare = True
202
+
203
+ if end_compare:
204
+ # Roll back to previous best
205
+ if hyp_match_string:
206
+ # Add it to the output
207
+ hyp_fixed.append(hyp_match_string)
208
+ ref_index = best_ref_index
209
+ else:
210
+ # Add whatever junk was at hyp_word_start
211
+ hyp_word_end = hyp_word_start + 1
212
+ hyp_fixed.append(hyp_words[hyp_word_start])
213
+
214
+ #print hyp_word_end, "Current:", hyp_fixed
215
+ hyp_word_start = hyp_word_end
216
+ hyp_match_string = None
217
+ end_compare = False
218
+
219
+ return ' '.join(hyp_fixed)
220
+
221
+ @staticmethod
222
+ def isDashEquivalent(hyp, ref):
223
+ # Dashes must be between words
224
+ if '-' in (hyp[0], hyp[-1], ref[0], ref[-1]):
225
+ return False
226
+
227
+ # Strip the dashes, then compare tokens
228
+ hyp_words = hyp.replace('-', ' ').split()
229
+ ref_words = ref.replace('-', ' ').split()
230
+ return (hyp_words == ref_words)
231
+
232
+ @staticmethod
233
+ def getNormOptions(word_string, extended=True):
234
+ # Returns possible ways to normalize the string
235
+ options_dict = defaultdict(set)
236
+
237
+ # Number conversion
238
+ if word_string.isdigit():
239
+ word_number = int(word_string)
240
+ # Convert digits to words
241
+ try:
242
+ num_text = NumToTextEng.convert(word_number)
243
+ options_dict['textnum'].add(num_text)
244
+ except:
245
+ pass
246
+
247
+ # Convert digits to year
248
+ try:
249
+ num_text = NumToTextEng.convertTryYear(word_number)
250
+ options_dict['textyear'].add(num_text)
251
+ except:
252
+ pass
253
+ else:
254
+ if extended and len(word_string.split()) > 1:
255
+ ext = set()
256
+
257
+ # Hyphenation
258
+ ext.add('-'.join(word_string.split()))
259
+
260
+ # All one single word
261
+ ext.add(''.join(word_string.split()))
262
+
263
+ # Strip punctuation (both sides)
264
+ ext.add(word_string.strip(string.punctuation))
265
+ # Strip left punct only
266
+ ext.add(word_string.lstrip(string.punctuation))
267
+ # Strip right punct only
268
+ ext.add(word_string.rstrip(string.punctuation))
269
+ options_dict['extended'].update(ext)
270
+
271
+
272
+ wstr = word_string
273
+ # Deyphenation
274
+ if '-' in word_string:
275
+ wstr = word_string.replace('-', ' ')
276
+ options_dict['text'].add(wstr)
277
+
278
+ # Convert words to digits
279
+ try:
280
+ num = TextToNumEng.convertTryYear(wstr)
281
+ options_dict['num'].add(str(num))
282
+ except:
283
+ pass
284
+
285
+ # Contractions
286
+ if "'" in word_string:
287
+ # Expand contractions
288
+ cont_options = ContractionsEng.expandOptions(word_string)
289
+ else:
290
+ # Apply contractions
291
+ cont_options = ContractionsEng.contractOptions(word_string)
292
+ if cont_options:
293
+ options_dict['text'].update(cont_options)
294
+
295
+ return options_dict
@@ -0,0 +1,289 @@
1
+ # Parts of code are adapted from
2
+ # https://www.daniweb.com/software-development/python/code/216839/number-to-word-converter-python
3
+
4
+
5
+ class NumbersEnum(object):
6
+ unit = 1
7
+ teens = 2
8
+ tens = 3
9
+ scale = 4
10
+ none = 0
11
+
12
+ # TODO: Merge these two classes into one.
13
+ class TextToNumEng(object):
14
+ '''
15
+ Currently only works with positive numbers and dates
16
+ Does not work with "twenty one hundred" ==> 2100
17
+ Also doesn't work with month/day combos like "nine eleven" !==> "9/11"
18
+ '''
19
+ # TODO: Don't hardcode everything.
20
+ units = [
21
+ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
22
+ "nine",
23
+ ]
24
+ teens = [
25
+ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
26
+ "sixteen", "seventeen", "eighteen", "nineteen",
27
+ ]
28
+ tens = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
29
+ scales = ["hundred", "thousand", "million", "billion", "trillion",
30
+ "quadrillion", "quintillion", "sextillion", "septillion", "octillion",
31
+ "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion",
32
+ "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion",
33
+ "novemdecillion", "vigintillion"]
34
+
35
+ numericWords = set(units + teens + tens + scales)
36
+
37
+ # Number to word map for calculating numbers
38
+ num2txt_map = dict()
39
+ num2txt_map["and"] = (NumbersEnum.none, 1, 0)
40
+ for idx, word in enumerate(units): num2txt_map[word] = (NumbersEnum.unit, 1, idx)
41
+ for idx, word in enumerate(teens): num2txt_map[word] = (NumbersEnum.teens, 1, idx + 10)
42
+ for idx, word in enumerate(tens): num2txt_map[word] = (NumbersEnum.tens, 1, (idx+2) * 10)
43
+ for idx, word in enumerate(scales): num2txt_map[word] = (NumbersEnum.scale, 10 ** (idx * 3 or 2), 0)
44
+
45
+ invalidTransitions = set([
46
+ (NumbersEnum.unit, NumbersEnum.unit),
47
+ (NumbersEnum.unit, NumbersEnum.teens),
48
+ (NumbersEnum.teens, NumbersEnum.unit),
49
+ (NumbersEnum.teens, NumbersEnum.tens),
50
+ (NumbersEnum.tens, NumbersEnum.teens)
51
+ ])
52
+
53
+ @staticmethod
54
+ def convertTryYear(textnum):
55
+ '''
56
+ Tries to handle dates if they appear.
57
+ Currently only works with ones, teens, and twenty
58
+ e.g.
59
+ nineteen ninety four
60
+ twelve eleven
61
+ twenty fifteen
62
+ '''
63
+ if not textnum:
64
+ raise TypeError
65
+
66
+ words = []
67
+ if isinstance(textnum, int) or isinstance(textnum, float):
68
+ return textnum
69
+ elif isinstance(textnum, list):
70
+ words = textnum
71
+ elif isinstance(textnum, str) or isinstance(textnum, unicode):
72
+ words = textnum.split()
73
+ else:
74
+ raise TypeError
75
+
76
+ first_candidates = set(TextToNumEng.units + TextToNumEng.teens + ['twenty'])
77
+ first_candidates.remove('zero')
78
+
79
+ if len(words) > 1 and words[0] in first_candidates and words[1] != 'hundred' and (words[1] in TextToNumEng.numericWords or words[1].isdigit()):
80
+ # Split into two parses
81
+ first = words[0]
82
+ # Added special "oh" => 0 case. Like "twelve oh one" => 1201
83
+ second = ' '.join([w for w in words[1:len(words)] if w != "oh"])
84
+
85
+ combinedNumberStr = ""
86
+
87
+ try:
88
+ secondNumber = -1
89
+ firstNumber = -1
90
+ if second.isdigit():
91
+ secondNumber = int(second)
92
+ else:
93
+ secondNumber = TextToNumEng.convert(second)
94
+ if first.isdigit():
95
+ firstNumber = int(first)
96
+ else:
97
+ firstNumber = TextToNumEng.convert(first)
98
+
99
+ # secondNumber = TextToNumEng.convert(second)
100
+ # firstNumber = TextToNumEng.convert(first)
101
+
102
+ # Concatenate the result
103
+ combinedNumberStr = "{0:d}{1:02d}".format(firstNumber, secondNumber)
104
+
105
+ if not (3 <= len(combinedNumberStr) <= 4):
106
+ raise Exception("Invalid year: {0}".format(combinedNumberStr))
107
+ else:
108
+ return int(combinedNumberStr)
109
+ except:
110
+ printtraceback.format_exc()
111
+
112
+ # Either skipped year or year parsing failed.
113
+ return TextToNumEng.convert(words)
114
+
115
+
116
+ @staticmethod
117
+ def convert(textnum):
118
+ '''
119
+ Assumes that the number is in a string or list(str). Splits the string into word tokens and tries to convert it to a number
120
+ '''
121
+ if not textnum:
122
+ raise TypeError
123
+
124
+ words = []
125
+ if isinstance(textnum, int) or isinstance(textnum, float):
126
+ return textnum
127
+ elif isinstance(textnum, list):
128
+ words = textnum
129
+ elif isinstance(textnum, str) or isinstance(textnum, unicode):
130
+ words = textnum.replace('-', ' ').split()
131
+ else:
132
+ raise TypeError
133
+
134
+ if words[0] in TextToNumEng.scales:
135
+ raise Exception("Illegal number start: %s" % words[0])
136
+
137
+ current = result = 0
138
+ prevNumType = NumbersEnum.none
139
+ prevScale = 0
140
+ prevWord = ""
141
+ for word in words:
142
+ if word not in TextToNumEng.num2txt_map:
143
+ raise Exception("Illegal word: " + word)
144
+
145
+ numtype, scale, increment = TextToNumEng.num2txt_map[word]
146
+ # print numtype, prevNumType
147
+ if prevScale == scale and (numtype == prevNumType or (prevNumType,numtype) in TextToNumEng.invalidTransitions):
148
+ raise Exception("Illegal number transition: {0} => {1}".format(prevWord, word))
149
+ current = current * scale + increment
150
+ if scale > 100:
151
+ result += current
152
+ current = 0
153
+ prevNumType = numtype
154
+ prevScale = scale
155
+ prevWord = word
156
+ return result + current
157
+
158
+ # integer number to english word conversion
159
+ # can be used for numbers as large as 999 vigintillion
160
+ # (vigintillion --> 10 to the power 60)
161
+ # tested with Python24 vegaseat 07dec2006
162
+ @staticmethod
163
+ def int2word(n):
164
+ """
165
+ convert an integer number n into a string of english words
166
+ """
167
+ # break the number into groups of 3 digits using slicing
168
+ # each group representing hundred, thousand, million, billion, ...
169
+ n3 = []
170
+
171
+ # create numeric string
172
+ ns = str(n)
173
+ for k in range(3, 33, 3):
174
+ r = ns[-k:]
175
+ q = len(ns) - k
176
+ # break if end of ns has been reached
177
+ if q < -2:
178
+ break
179
+ else:
180
+ if q >= 0:
181
+ n3.append(int(r[:3]))
182
+ elif q >= -1:
183
+ n3.append(int(r[:2]))
184
+ elif q >= -2:
185
+ n3.append(int(r[:1]))
186
+
187
+
188
+ #print n3 # test
189
+
190
+ # break each group of 3 digits into
191
+ # ones, tens/twenties, hundreds
192
+ # and form a string
193
+ nw = ""
194
+ for i, x in enumerate(n3):
195
+ b1 = x % 10
196
+ b2 = (x % 100)//10
197
+ b3 = (x % 1000)//100
198
+ #print b1, b2, b3 # test
199
+ if x == 0:
200
+ continue # skip
201
+ else:
202
+ t = TextToNumEng.thousands[i]
203
+ if b2 == 0:
204
+ nw = TextToNumEng.ones[b1] + t + nw
205
+ elif b2 == 1:
206
+ nw = TextToNumEng.tens[b1] + t + nw
207
+ elif b2 > 1:
208
+ nw = TextToNumEng.twenties[b2] + TextToNumEng.ones[b1] + t + nw
209
+ if b3 > 0:
210
+ nw = TextToNumEng.ones[b3] + "hundred " + nw
211
+ return nw
212
+
213
+ class NumToTextEng(object):
214
+ units = ["", "one", "two", "three", "four", "five",
215
+ "six", "seven", "eight", "nine"]
216
+ teens = ["", "eleven", "twelve", "thirteen", "fourteen",
217
+ "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
218
+ tens = ["", "ten", "twenty", "thirty", "forty",
219
+ "fifty", "sixty", "seventy", "eighty", "ninety"]
220
+ thousands = ["","thousand", "million", "billion", "trillion",
221
+ "quadrillion", "quintillion", "sextillion", "septillion", "octillion",
222
+ "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion",
223
+ "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion",
224
+ "novemdecillion", "vigintillion"]
225
+
226
+ @staticmethod
227
+ def convertTryYear(num):
228
+ first = None
229
+ second = None
230
+
231
+ num_str = str(num)
232
+ if len(num_str) > 4 or len(num_str) == 0:
233
+ raise ValueError("Invalid date: {0}", num)
234
+ elif len(num_str) >= 3:
235
+ # Check if it could be a year
236
+ if len(num_str) == 3:
237
+ first = int(num_str[0])
238
+ second = int(num_str[1:len(num_str)])
239
+ elif len(num_str) == 4:
240
+ first = int(num_str[0:2])
241
+ second = int(num_str[1:len(num_str)])
242
+
243
+ if not (first and second):
244
+ raise ValueError("Invalid date: {0:d}", num)
245
+
246
+ return "{0} {1}".format(NumToTextEng.convert(first), NumToTextEng.convert(second))
247
+ else:
248
+ return NumToTextEng.convert(num)
249
+
250
+
251
+ @staticmethod
252
+ def convert(num):
253
+ if not isinstance(num, int):
254
+ raise TypeError
255
+
256
+ words = []
257
+ if num == 0:
258
+ words.append("zero")
259
+ else:
260
+ numStr = "%d" % num
261
+ numStrLen = len(numStr)
262
+ groups = (numStrLen + 2) // 3
263
+ numStr = numStr.zfill((groups) * 3)
264
+ for i in range(0, groups*3, 3):
265
+ h = int(numStr[i])
266
+ t = int(numStr[i+1])
267
+ u = int(numStr[i+2])
268
+ g = groups - (i // 3 + 1)
269
+
270
+ if h >= 1:
271
+ words.append(NumToTextEng.units[h])
272
+ words.append("hundred")
273
+
274
+ if t > 1:
275
+ words.append(NumToTextEng.tens[t])
276
+ if u >= 1:
277
+ words.append(NumToTextEng.units[u])
278
+ elif t == 1:
279
+ if u >= 1:
280
+ words.append(NumToTextEng.teens[u])
281
+ else:
282
+ words.append(NumToTextEng.tens[t])
283
+ else:
284
+ if u >= 1:
285
+ words.append(NumToTextEng.units[u])
286
+
287
+ if g >= 1 and (h + t + u) > 0:
288
+ words.append(NumToTextEng.thousands[g])
289
+ return ' '.join(words)
@@ -0,0 +1,3 @@
1
+ # from align_labeler import AlignLabeler
2
+ from error_align.baselines.power.power.levenshtein import ExpandedAlignment, Levenshtein
3
+ from error_align.baselines.power.power.phonemes import Phonemes