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,166 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
from error_align.baselines.power.power.aligner import CharToWordAligner
|
|
5
|
+
from error_align.baselines.power.power.levenshtein import AlignLabels
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PunctInsertOracle(object):
|
|
9
|
+
'''
|
|
10
|
+
Insert punctuation on hypothesis based on alignment with reference
|
|
11
|
+
'''
|
|
12
|
+
|
|
13
|
+
def __init__(self, params):
|
|
14
|
+
'''
|
|
15
|
+
Constructor
|
|
16
|
+
'''
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
@staticmethod
|
|
20
|
+
def insertPunct(error_alignment, ref_punct):
|
|
21
|
+
if not (error_alignment.s1_map and error_alignment.s2_map):
|
|
22
|
+
# Don't try to add punct if either the hyp or ref are empty.
|
|
23
|
+
return error_alignment
|
|
24
|
+
|
|
25
|
+
# Align reference with punct against reference without punct
|
|
26
|
+
# Is this needed? Yes, in case there's punctuation that makes an extra token
|
|
27
|
+
ref_punct_tokens = ref_punct.split()
|
|
28
|
+
ref_nopunct_tokens = error_alignment.s1_string().split() # [x for x in error_alignment.s1 if x]
|
|
29
|
+
hyp_nopunct_tokens = error_alignment.s2_string().split() # [x for x in error_alignment.s2 if x]
|
|
30
|
+
|
|
31
|
+
ref_punct_string = ' '.join(ref_punct_tokens)
|
|
32
|
+
ref_nopunct_string = ' '.join(ref_nopunct_tokens)
|
|
33
|
+
c2w_aligner = CharToWordAligner(ref_punct_string, ref_nopunct_string, lowercase=True)
|
|
34
|
+
c2w_aligner.charAlign()
|
|
35
|
+
ref_punct_align = c2w_aligner.charAlignToWordAlign()
|
|
36
|
+
|
|
37
|
+
# lev = Levenshtein.align(ref_punct_tokens, ref_nopunct_tokens, lowercase=True)
|
|
38
|
+
# lev.editops()
|
|
39
|
+
# ref_punct_align = lev.expandAlign()
|
|
40
|
+
|
|
41
|
+
error_alignment_punct = copy.deepcopy(error_alignment)
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
err_align_index = None
|
|
45
|
+
err_align_label = None
|
|
46
|
+
ref_punct_index = -1
|
|
47
|
+
ref_nopunct_index = -1
|
|
48
|
+
for ref_align_index in range(len(ref_punct_align.align)):
|
|
49
|
+
# Check the error type.
|
|
50
|
+
ref_align_error_type = ref_punct_align.align[ref_align_index]
|
|
51
|
+
ref_word_punct = ref_punct_align.s1[ref_align_index]
|
|
52
|
+
ref_word_nopunct = ref_punct_align.s2[ref_align_index]
|
|
53
|
+
|
|
54
|
+
punct_lhs = ""
|
|
55
|
+
punct_rhs = ""
|
|
56
|
+
|
|
57
|
+
if ref_align_error_type in (AlignLabels.correct, AlignLabels.substitution):
|
|
58
|
+
# There's some punct attached to the word. Split it off!
|
|
59
|
+
# Idea #1, Use regex to find punct around a word sequence. However, this will fail if there's punctuation in between words
|
|
60
|
+
pattern = '^(.*?){0}(.*?)$'.format(ref_word_nopunct)
|
|
61
|
+
match = re.search(pattern, ref_word_punct)
|
|
62
|
+
|
|
63
|
+
if not match:
|
|
64
|
+
# Whoops! something went wrong
|
|
65
|
+
raise Exception("Regex match not found\nPattern: {0}\nPunct: {1}\nNo Punct: {2}"
|
|
66
|
+
.format(pattern, ref_word_nopunct, ref_word_nopunct))
|
|
67
|
+
punct_lhs = match.group(1)
|
|
68
|
+
punct_rhs = match.group(2)
|
|
69
|
+
|
|
70
|
+
if punct_lhs:
|
|
71
|
+
# Apply to front of hyp
|
|
72
|
+
punct_lhs = punct_lhs.strip()
|
|
73
|
+
else:
|
|
74
|
+
punct_lhs = ""
|
|
75
|
+
if punct_rhs:
|
|
76
|
+
# Apply to back of hyp
|
|
77
|
+
punct_rhs = punct_rhs.strip()
|
|
78
|
+
else:
|
|
79
|
+
punct_rhs = ""
|
|
80
|
+
|
|
81
|
+
ref_punct_index += 1
|
|
82
|
+
ref_nopunct_index += 1
|
|
83
|
+
|
|
84
|
+
elif ref_align_error_type == AlignLabels.deletion:
|
|
85
|
+
# TODO: The extra token on the reference side is probably punct. Check if token is punct
|
|
86
|
+
# Determine if punct should attach as punct_lhs or punct_rhs. We'll make that decision later.
|
|
87
|
+
punct_lhs = '{0} '.format(ref_word_punct)
|
|
88
|
+
punct_rhs = ' {0}'.format(ref_word_punct)
|
|
89
|
+
|
|
90
|
+
ref_punct_index += 1
|
|
91
|
+
elif ref_align_error_type == 'I':
|
|
92
|
+
# TODO: uh-oh. This shouldn't happen!
|
|
93
|
+
ref_nopunct_index += 1
|
|
94
|
+
raise TypeError("Insertion errors shouldn't happen between punct and nopunct")
|
|
95
|
+
else:
|
|
96
|
+
# Now this is impossible!
|
|
97
|
+
raise TypeError("Invalid error type: {0}".format(ref_align_error_type))
|
|
98
|
+
|
|
99
|
+
# Advance error_alignment to the word alignment position containing the nopunct reference word
|
|
100
|
+
if ref_nopunct_index >= 0: # TODO: Check if the words have changed.
|
|
101
|
+
try:
|
|
102
|
+
err_align_index = error_alignment.s1_map[ref_nopunct_index]
|
|
103
|
+
err_align_label = error_alignment_punct.align[err_align_index]
|
|
104
|
+
except Exception:
|
|
105
|
+
print(error_alignment)
|
|
106
|
+
print("ref_nopunct_index:", ref_nopunct_index)
|
|
107
|
+
print("ref_align_index: ", ref_align_index)
|
|
108
|
+
raise
|
|
109
|
+
|
|
110
|
+
if punct_lhs or punct_rhs:
|
|
111
|
+
# print "Punct: |_{0}_| |_{1}_|".format(punct_lhs, punct_rhs)
|
|
112
|
+
if err_align_label == AlignLabels.deletion:
|
|
113
|
+
# If there's no token here, apply punct to previous or next
|
|
114
|
+
# TODO: This won't work for long strings of D's. You'll need to find the next closest one.
|
|
115
|
+
|
|
116
|
+
# Scan backward for the previous non-empty hyp word. Try to apply the punct there.
|
|
117
|
+
err_align_index_shift = err_align_index - 1
|
|
118
|
+
|
|
119
|
+
# ... except if the punct was at the end of the last ref word
|
|
120
|
+
if ref_nopunct_index == len(ref_nopunct_tokens) - 1:
|
|
121
|
+
err_align_index_shift = error_alignment.s2_map[len(hyp_nopunct_tokens) - 1]
|
|
122
|
+
|
|
123
|
+
while err_align_index_shift > 0 and not error_alignment.s2[err_align_index_shift]:
|
|
124
|
+
err_align_index_shift -= 1
|
|
125
|
+
if err_align_index_shift >= 0:
|
|
126
|
+
|
|
127
|
+
# Apply punct to previous position
|
|
128
|
+
if ref_align_error_type == AlignLabels.deletion:
|
|
129
|
+
punct_lhs = ""
|
|
130
|
+
|
|
131
|
+
error_alignment_punct.s2[err_align_index_shift] = "{1}{0}{2}".format(error_alignment_punct.s2[err_align_index_shift], punct_lhs, punct_rhs)
|
|
132
|
+
else:
|
|
133
|
+
# Scan forward for the next non-empty hyp word. Try to apply the punct there.
|
|
134
|
+
err_align_index_shift = err_align_index + 1
|
|
135
|
+
while err_align_index_shift < len(hyp_nopunct_tokens) and not error_alignment_punct.s2[err_align_index_shift]:
|
|
136
|
+
err_align_index_shift += 1
|
|
137
|
+
if err_align_index_shift < len(hyp_nopunct_tokens):
|
|
138
|
+
|
|
139
|
+
# Apply punct to next position
|
|
140
|
+
if ref_align_error_type == "D":
|
|
141
|
+
punct_rhs = ""
|
|
142
|
+
|
|
143
|
+
error_alignment_punct.s2[err_align_index_shift] = "{1}{0}{2}".format(error_alignment_punct.s2[err_align_index_shift], punct_lhs, punct_rhs)
|
|
144
|
+
else:
|
|
145
|
+
# Otherwise ignore punct altogether
|
|
146
|
+
print("Discarding punct")
|
|
147
|
+
else:
|
|
148
|
+
# Apply punct on the end of the current word.
|
|
149
|
+
if ref_align_error_type == "D":
|
|
150
|
+
punct_lhs = "" # TODO: Is this assumption correct? Apply punct to rhs?
|
|
151
|
+
|
|
152
|
+
# Force punct at the end of the last reference word to appear at the end of the hyp word
|
|
153
|
+
if ref_nopunct_index == len(ref_nopunct_tokens) - 1:
|
|
154
|
+
err_align_index_shift = error_alignment.s2_map[len(hyp_nopunct_tokens) - 1]
|
|
155
|
+
error_alignment_punct.s2[err_align_index_shift] = "{0}{1}".format(error_alignment_punct.s2[err_align_index_shift], punct_rhs)
|
|
156
|
+
punct_rhs = ""
|
|
157
|
+
|
|
158
|
+
error_alignment_punct.s2[err_align_index] = "{1}{0}{2}".format(error_alignment_punct.s2[err_align_index], punct_lhs, punct_rhs)
|
|
159
|
+
|
|
160
|
+
except Exception:
|
|
161
|
+
# TODO: Add exception handling to output the sentences as well as the offending segment.
|
|
162
|
+
raise
|
|
163
|
+
|
|
164
|
+
return error_alignment_punct
|
|
165
|
+
|
|
166
|
+
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
from error_align.baselines.power.power.levenshtein import ExpandedAlignment
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AlignmentReaderJson(object):
|
|
8
|
+
def __init__(self, filepath):
|
|
9
|
+
self.filepath = filepath
|
|
10
|
+
|
|
11
|
+
def read_alignments(self):
|
|
12
|
+
with open(self.filepath, 'r') as f:
|
|
13
|
+
for line in f:
|
|
14
|
+
yield AlignmentReaderJson.read_json(line)
|
|
15
|
+
|
|
16
|
+
@staticmethod
|
|
17
|
+
def read_json(jstr):
|
|
18
|
+
in_dict = json.loads(jstr)
|
|
19
|
+
if not in_dict:
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
ref = []
|
|
23
|
+
hyp = []
|
|
24
|
+
align = []
|
|
25
|
+
ref_map = []
|
|
26
|
+
hyp_map = []
|
|
27
|
+
|
|
28
|
+
for i in range(len(in_dict['alignments'])):
|
|
29
|
+
alignment = in_dict['alignments'][i]
|
|
30
|
+
ref.append(alignment['ref'])
|
|
31
|
+
hyp.append(alignment['hyp'])
|
|
32
|
+
align.append(alignment['align'])
|
|
33
|
+
if ref[-1]:
|
|
34
|
+
ref_map.extend([i for r in ref[-1].split()])
|
|
35
|
+
if hyp[-1]:
|
|
36
|
+
hyp_map.extend([i for h in hyp[-1].split()])
|
|
37
|
+
return ExpandedAlignment(ref, hyp, align, ref_map, hyp_map)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main(args):
|
|
41
|
+
filename = args[0]
|
|
42
|
+
reader = AlignmentReaderJson(filename)
|
|
43
|
+
for alignment in reader.read_alignments():
|
|
44
|
+
print(alignment)
|
|
45
|
+
print('---')
|
|
46
|
+
|
|
47
|
+
if __name__ == '__main__':
|
|
48
|
+
main(sys.argv[1:])
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
from __future__ import division
|
|
2
|
+
|
|
3
|
+
import abc
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from error_align.baselines.power.power.levenshtein import Levenshtein
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def CreateWriter(output_type, filepath, hypfile, reffile):
|
|
10
|
+
writer = None
|
|
11
|
+
if output_type == "sgml":
|
|
12
|
+
writer = SgmlWriter(filepath, hypfile, reffile)
|
|
13
|
+
elif output_type == "snt":
|
|
14
|
+
writer = SntWriter(filepath, hypfile, reffile)
|
|
15
|
+
elif output_type == "json":
|
|
16
|
+
writer = JsonWriter(filepath, hypfile, reffile)
|
|
17
|
+
elif output_type == "align":
|
|
18
|
+
writer = AlignWriter(filepath, hypfile, reffile)
|
|
19
|
+
else:
|
|
20
|
+
raise NotImplementedError("Writer not implemented for %s" % format)
|
|
21
|
+
return writer
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class WerWriter(object):
|
|
25
|
+
__metaclass__ = abc.ABCMeta
|
|
26
|
+
|
|
27
|
+
def __init__(self, filepath, hypfile, reffile):
|
|
28
|
+
self.out_file = open(filepath, "w")
|
|
29
|
+
self.filepath = filepath
|
|
30
|
+
|
|
31
|
+
@abc.abstractmethod
|
|
32
|
+
def write(self, segid, score_components, expanded_alignment, phonetic_alignments=None):
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
def write_blank(self):
|
|
36
|
+
return
|
|
37
|
+
|
|
38
|
+
def finalize(self):
|
|
39
|
+
if self.out_file:
|
|
40
|
+
self.out_file.close()
|
|
41
|
+
print("File written to {}".format(self.filepath))
|
|
42
|
+
self.out_file = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class AlignWriter(WerWriter):
|
|
46
|
+
def __init__(self, filepath, hypfile, reffile):
|
|
47
|
+
WerWriter.__init__(self, filepath, hypfile, reffile)
|
|
48
|
+
|
|
49
|
+
def write(self, segid, score_components, expanded_alignment, phonetic_alignments=None):
|
|
50
|
+
self.out_file.write("{0}\n".format(" ".join(expanded_alignment.alignment_expanded())))
|
|
51
|
+
|
|
52
|
+
def finalize(self):
|
|
53
|
+
WerWriter.finalize(self)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class SgmlWriter(WerWriter):
|
|
57
|
+
def __init__(self, filepath, hypfile, reffile):
|
|
58
|
+
WerWriter.__init__(self, filepath, hypfile, reffile)
|
|
59
|
+
self.out_file.write(
|
|
60
|
+
'<SYSTEM title="%s" ref_fname="%s" hyp_fname="%s" format="2.0">\n' % (hypfile, reffile, hypfile)
|
|
61
|
+
)
|
|
62
|
+
self.out_file.write('<SPEAKER id="spk1">\n')
|
|
63
|
+
|
|
64
|
+
def write(self, segid, score_components, expanded_alignment, phonetic_alignments=None):
|
|
65
|
+
self.out_file.write('<PATH id="(%d)" word_cnt="%d">\n' % (segid, len(expanded_alignment.align)))
|
|
66
|
+
self.out_file.write(
|
|
67
|
+
"%s\n"
|
|
68
|
+
% ":".join(
|
|
69
|
+
[
|
|
70
|
+
'%s,"%s","%s"' % (expanded_alignment.align[i], expanded_alignment.s1[i], expanded_alignment.s2[i])
|
|
71
|
+
for i in range(len(expanded_alignment.align))
|
|
72
|
+
]
|
|
73
|
+
)
|
|
74
|
+
)
|
|
75
|
+
self.out_file.write("</PATH>\n")
|
|
76
|
+
|
|
77
|
+
def finalize(self):
|
|
78
|
+
self.out_file.write("</SPEAKER>\n")
|
|
79
|
+
self.out_file.write("</SYSTEM>\n")
|
|
80
|
+
WerWriter.finalize(self)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class JsonWriter(WerWriter):
|
|
84
|
+
def __init__(self, filepath, hypfile, reffile):
|
|
85
|
+
WerWriter.__init__(self, filepath, hypfile, reffile)
|
|
86
|
+
|
|
87
|
+
def write(self, segid, score_components, expanded_alignment, phonetic_alignments=None):
|
|
88
|
+
out_dict = dict()
|
|
89
|
+
out_dict["id"] = segid
|
|
90
|
+
out_dict["errorTypes"] = score_components.copy()
|
|
91
|
+
out_dict["errorTypes"]["refLength"] = out_dict["errorTypes"].pop("L")
|
|
92
|
+
out_dict["errRate"] = Levenshtein.errorRate(
|
|
93
|
+
score_components["S"], score_components["D"], score_components["I"], score_components["L"]
|
|
94
|
+
)
|
|
95
|
+
out_dict["alignments"] = []
|
|
96
|
+
for i in range(len(expanded_alignment.align)):
|
|
97
|
+
out_dict["alignments"].append(
|
|
98
|
+
{"align": expanded_alignment.align[i], "ref": expanded_alignment.s1[i], "hyp": expanded_alignment.s2[i]}
|
|
99
|
+
)
|
|
100
|
+
self.out_file.write("%s\n" % json.dumps(out_dict))
|
|
101
|
+
|
|
102
|
+
def write_blank(self):
|
|
103
|
+
self.out_file.write("%s\n" % json.dumps({}))
|
|
104
|
+
|
|
105
|
+
def finalize(self):
|
|
106
|
+
WerWriter.finalize(self)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class SntWriter(WerWriter):
|
|
110
|
+
def __init__(self, filepath, hypfile, reffile):
|
|
111
|
+
WerWriter.__init__(self, filepath, hypfile, reffile)
|
|
112
|
+
self.out_file.write("===============================================================================\n")
|
|
113
|
+
self.out_file.write(" SENTENCE LEVEL REPORT FOR THE SYSTEM:\n")
|
|
114
|
+
self.out_file.write("\tName: %s\n" % hypfile)
|
|
115
|
+
self.out_file.write("===============================================================================\n")
|
|
116
|
+
self.out_file.write("\n\n")
|
|
117
|
+
|
|
118
|
+
def write(self, segid, score_components, expanded_alignment, phonetic_alignments=None):
|
|
119
|
+
self.out_file.write("id: (%d)\n" % segid)
|
|
120
|
+
labels = ["C", "S", "D", "I"]
|
|
121
|
+
counts = [score_components[label] for label in labels]
|
|
122
|
+
|
|
123
|
+
# Print score components
|
|
124
|
+
self.out_file.write(
|
|
125
|
+
"Scores (%s) %s\n" % (" ".join(["#%s" % label for label in labels]), " ".join([str(x) for x in counts]))
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
# Print word alignment
|
|
129
|
+
self.out_file.write("%s\n" % expanded_alignment)
|
|
130
|
+
self.out_file.write("\n")
|
|
131
|
+
|
|
132
|
+
# Print phonetic alignments
|
|
133
|
+
if phonetic_alignments:
|
|
134
|
+
for palign in [p for p in phonetic_alignments if p]:
|
|
135
|
+
self.out_file.write("%s\n" % palign)
|
|
136
|
+
self.out_file.write("\n")
|
|
137
|
+
|
|
138
|
+
# Print statistics
|
|
139
|
+
self.out_file.write(
|
|
140
|
+
"Correct = {0:4.1%} {1} ({2})\n".format(
|
|
141
|
+
score_components["C"] / score_components["L"], score_components["C"], score_components["L"]
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
self.out_file.write(
|
|
145
|
+
"Substitutions = {0:4.1%} {1} ({2})\n".format(
|
|
146
|
+
score_components["S"] / score_components["L"], score_components["S"], score_components["L"]
|
|
147
|
+
)
|
|
148
|
+
)
|
|
149
|
+
self.out_file.write(
|
|
150
|
+
"Deletions = {0:4.1%} {1} ({2})\n".format(
|
|
151
|
+
score_components["D"] / score_components["L"], score_components["D"], score_components["L"]
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
self.out_file.write(
|
|
155
|
+
"Insertions = {0:4.1%} {1} ({2})\n".format(
|
|
156
|
+
score_components["I"] / score_components["L"], score_components["I"], score_components["L"]
|
|
157
|
+
)
|
|
158
|
+
)
|
|
159
|
+
self.out_file.write("\n")
|
|
160
|
+
self.out_file.write(
|
|
161
|
+
"Errors = {0:4.1%} {1} ({2})\n".format(
|
|
162
|
+
Levenshtein.errorRate(
|
|
163
|
+
score_components["S"], score_components["D"], score_components["I"], score_components["L"]
|
|
164
|
+
),
|
|
165
|
+
score_components["S"] + score_components["D"] + score_components["I"],
|
|
166
|
+
score_components["L"],
|
|
167
|
+
)
|
|
168
|
+
)
|
|
169
|
+
self.out_file.write("\n")
|
|
170
|
+
self.out_file.write(
|
|
171
|
+
"Ref. words = {0} ({1})\n".format(score_components["L"], score_components["L"])
|
|
172
|
+
)
|
|
173
|
+
self.out_file.write(
|
|
174
|
+
"Hyp. words = {0} ({1})\n".format(
|
|
175
|
+
len(expanded_alignment.s2_string().split()), score_components["L"]
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
self.out_file.write(
|
|
179
|
+
"Aligned words = {0} ({1})\n".format(
|
|
180
|
+
score_components["C"] + score_components["S"], score_components["L"]
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
self.out_file.write("\n")
|
|
184
|
+
self.out_file.write("-------------------------------------------------------------------------------\n")
|
|
185
|
+
self.out_file.write("\n")
|
|
186
|
+
|
|
187
|
+
def finalize(self):
|
|
188
|
+
WerWriter.finalize(self)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class ConfusionPairWriter(WerWriter):
|
|
192
|
+
@staticmethod
|
|
193
|
+
def write(filepath, hypfile, reffile, conf_dict):
|
|
194
|
+
with open(filepath, "w") as out_file:
|
|
195
|
+
out_file.write("System name: %s\n" % hypfile)
|
|
196
|
+
out_file.write("Ref file : %s\n" % reffile)
|
|
197
|
+
|
|
198
|
+
for key in sorted(conf_dict.keys()):
|
|
199
|
+
for item in sorted(conf_dict[key].keys()):
|
|
200
|
+
out_file.write("%s\t==>\t%s\t%d\n" % (key, item, conf_dict[key][item]))
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def write_json(filepath, hypfile, reffile, conf_dict):
|
|
204
|
+
with open(filepath, "w") as out_file:
|
|
205
|
+
out_file.write("%s\n" % json.dumps(conf_dict))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class CompareWriter:
|
|
209
|
+
@staticmethod
|
|
210
|
+
def write_comparison(
|
|
211
|
+
filepath,
|
|
212
|
+
hypfile,
|
|
213
|
+
reffile,
|
|
214
|
+
linecount,
|
|
215
|
+
final_power,
|
|
216
|
+
final_wer,
|
|
217
|
+
power_score_components,
|
|
218
|
+
wer_score_components,
|
|
219
|
+
diff_score,
|
|
220
|
+
diff_components,
|
|
221
|
+
):
|
|
222
|
+
with open(filepath, "w") as out_file:
|
|
223
|
+
out_file.write("System name: %s\n" % hypfile)
|
|
224
|
+
out_file.write("Ref file : %s\n" % reffile)
|
|
225
|
+
out_file.write("Hyp file : %s\n" % hypfile)
|
|
226
|
+
out_file.write(
|
|
227
|
+
"""
|
|
228
|
+
,---------------------------------------------------------.
|
|
229
|
+
|{0:^57}|
|
|
230
|
+
|---------------------------------------------------------|
|
|
231
|
+
| Metric | # Snt # Wrd | Corr Sub Del Ins Err |
|
|
232
|
+
|--------+-------------+----------------------------------|
|
|
233
|
+
| POWER | {1:5d} {8:5d} | {9:5d} {10:5d} {11:5d} {12:5d} {13:3.1%} |
|
|
234
|
+
| WER | {1:5d} {2:5d} | {3:5d} {4:5d} {5:5d} {6:5d} {7:3.1%} |
|
|
235
|
+
|=========================================================|
|
|
236
|
+
| Diff | {1:5d} {2:5d} | {14:-5d} {15:-5d} {16:-5d} {17:-5d} {18:-3.1%} |
|
|
237
|
+
`---------------------------------------------------------'
|
|
238
|
+
""".format(
|
|
239
|
+
hypfile,
|
|
240
|
+
linecount,
|
|
241
|
+
wer_score_components["L"],
|
|
242
|
+
wer_score_components["C"],
|
|
243
|
+
wer_score_components["S"],
|
|
244
|
+
wer_score_components["D"],
|
|
245
|
+
wer_score_components["I"],
|
|
246
|
+
final_wer,
|
|
247
|
+
power_score_components["L"],
|
|
248
|
+
power_score_components["C"],
|
|
249
|
+
power_score_components["S"],
|
|
250
|
+
power_score_components["D"],
|
|
251
|
+
power_score_components["I"],
|
|
252
|
+
final_power,
|
|
253
|
+
diff_components["C"],
|
|
254
|
+
diff_components["S"],
|
|
255
|
+
diff_components["D"],
|
|
256
|
+
diff_components["I"],
|
|
257
|
+
diff_score,
|
|
258
|
+
)
|
|
259
|
+
)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from error_align.baselines.power.power.aligner import PowerAligner as _PowerAligner
|
|
2
|
+
from error_align.utils import Alignment, OpType
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class PowerAlign:
|
|
6
|
+
"""Phonetically-oriented word error alignment."""
|
|
7
|
+
|
|
8
|
+
def __init__(
|
|
9
|
+
self,
|
|
10
|
+
ref: str,
|
|
11
|
+
hyp: str,
|
|
12
|
+
):
|
|
13
|
+
"""Initialize the phonetically-oriented word error alignment with reference and hypothesis texts.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
ref (str): The reference sequence/transcript.
|
|
17
|
+
hyp (str): The hypothesis sequence/transcript.
|
|
18
|
+
"""
|
|
19
|
+
self.aligner = _PowerAligner(
|
|
20
|
+
ref=ref,
|
|
21
|
+
hyp=hyp,
|
|
22
|
+
lowercase=True,
|
|
23
|
+
verbose=True,
|
|
24
|
+
lexicon="/home/lb/repos/power-asr/lex/cmudict.rep.json",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
def align(self):
|
|
28
|
+
"""Run the two-pass Power alignment algorithm.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
list[Alignment]: A list of Alignment objects.
|
|
32
|
+
"""
|
|
33
|
+
self.aligner.align()
|
|
34
|
+
widths = [
|
|
35
|
+
max(len(self.aligner.power_alignment.s1[i]), len(self.aligner.power_alignment.s2[i]))
|
|
36
|
+
for i in range(len(self.aligner.power_alignment.s1))
|
|
37
|
+
]
|
|
38
|
+
s1_args = list(zip(widths, self.aligner.power_alignment.s1))
|
|
39
|
+
s2_args = list(zip(widths, self.aligner.power_alignment.s2))
|
|
40
|
+
align_args = list(zip(widths, self.aligner.power_alignment.align))
|
|
41
|
+
|
|
42
|
+
alignments = []
|
|
43
|
+
for (_, ref_token), (_, hyp_token), (_, align_token) in zip(s1_args, s2_args, align_args):
|
|
44
|
+
|
|
45
|
+
if align_token == "C":
|
|
46
|
+
op_type = OpType.MATCH
|
|
47
|
+
if align_token == "S":
|
|
48
|
+
op_type = OpType.SUBSTITUTE
|
|
49
|
+
if align_token == "I":
|
|
50
|
+
op_type = OpType.INSERT
|
|
51
|
+
if align_token == "D":
|
|
52
|
+
op_type = OpType.DELETE
|
|
53
|
+
|
|
54
|
+
alignment = Alignment(
|
|
55
|
+
op_type=op_type,
|
|
56
|
+
ref=ref_token,
|
|
57
|
+
hyp=hyp_token,
|
|
58
|
+
)
|
|
59
|
+
alignments.append(alignment)
|
|
60
|
+
|
|
61
|
+
return alignments
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
from rapidfuzz.distance import Levenshtein
|
|
2
|
+
|
|
3
|
+
from error_align.utils import (
|
|
4
|
+
Alignment,
|
|
5
|
+
OpType,
|
|
6
|
+
basic_normalizer,
|
|
7
|
+
basic_tokenizer,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
OPS_MAP = {
|
|
11
|
+
"match": OpType.MATCH,
|
|
12
|
+
"replace": OpType.SUBSTITUTE,
|
|
13
|
+
"insert": OpType.INSERT,
|
|
14
|
+
"delete": OpType.DELETE,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RapidFuzzWordAlign:
|
|
19
|
+
"""Levenshtein-based word-level alignment."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
ref: str,
|
|
24
|
+
hyp: str,
|
|
25
|
+
tokenizer: callable = basic_tokenizer,
|
|
26
|
+
normalizer: callable = basic_normalizer,
|
|
27
|
+
):
|
|
28
|
+
"""Initialize the Levenshtein-based word-level alignment with reference and hypothesis texts.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
ref (str): The reference sequence/transcript.
|
|
32
|
+
hyp (str): The hypothesis sequence/transcript.
|
|
33
|
+
tokenizer (callable): A function to tokenize the sequences. Must be regex-based and return Match objects.
|
|
34
|
+
normalizer (callable): A function to normalize the tokens. Defaults to basic_normalizer.
|
|
35
|
+
"""
|
|
36
|
+
if not isinstance(ref, str):
|
|
37
|
+
raise TypeError("Reference sequence must be a string.")
|
|
38
|
+
if not isinstance(hyp, str):
|
|
39
|
+
raise TypeError("Hypothesis sequence must be a string.")
|
|
40
|
+
|
|
41
|
+
self.ref = ref
|
|
42
|
+
self.hyp = hyp
|
|
43
|
+
self._ref_token_matches = tokenizer(ref)
|
|
44
|
+
self._hyp_token_matches = tokenizer(hyp)
|
|
45
|
+
self._ref = [normalizer(r.group()) for r in self._ref_token_matches]
|
|
46
|
+
self._hyp = [normalizer(h.group()) for h in self._hyp_token_matches]
|
|
47
|
+
self._ref_max_idx = len(self._ref) - 1
|
|
48
|
+
self._hyp_max_idx = len(self._hyp) - 1
|
|
49
|
+
self.end_index = (self._hyp_max_idx, self._ref_max_idx)
|
|
50
|
+
|
|
51
|
+
def align(self) -> list[Alignment]:
|
|
52
|
+
"""Extract an arbitrary path from the backtrace graph.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
list[Alignment]: A list of Alignment objects.
|
|
56
|
+
"""
|
|
57
|
+
edit_ops = Levenshtein.editops(self._ref, self._hyp).as_list()
|
|
58
|
+
|
|
59
|
+
# Add match segments to editops
|
|
60
|
+
ref_edit_idxs = set([op[1] for op in edit_ops if op[0] != "insert"])
|
|
61
|
+
hyp_edit_idxs = set([op[2] for op in edit_ops if op[0] != "delete"])
|
|
62
|
+
ref_match_idxs = [i for i in range(len(self._ref)) if i not in ref_edit_idxs]
|
|
63
|
+
hyp_match_idxs = [i for i in range(len(self._hyp)) if i not in hyp_edit_idxs]
|
|
64
|
+
assert len(ref_match_idxs) == len(hyp_match_idxs)
|
|
65
|
+
for ref_idx, hyp_idx in zip(ref_match_idxs, hyp_match_idxs):
|
|
66
|
+
edit_ops.append(("match", ref_idx, hyp_idx))
|
|
67
|
+
edit_ops = sorted(edit_ops, key=lambda x: (x[1], x[2]))
|
|
68
|
+
|
|
69
|
+
# Convert to Alignment objects
|
|
70
|
+
alignments = []
|
|
71
|
+
for op_type, ref_idx, hyp_idx in edit_ops:
|
|
72
|
+
if op_type == "match" or op_type == "replace":
|
|
73
|
+
ref_match = self._ref_token_matches[ref_idx]
|
|
74
|
+
hyp_match = self._hyp_token_matches[hyp_idx]
|
|
75
|
+
alignment = Alignment(
|
|
76
|
+
op_type=OPS_MAP[op_type],
|
|
77
|
+
ref_slice=slice(*ref_match.span()),
|
|
78
|
+
hyp_slice=slice(*hyp_match.span()),
|
|
79
|
+
ref=ref_match.group(),
|
|
80
|
+
hyp=hyp_match.group(),
|
|
81
|
+
)
|
|
82
|
+
elif op_type == "delete":
|
|
83
|
+
ref_match = self._ref_token_matches[ref_idx]
|
|
84
|
+
alignment = Alignment(
|
|
85
|
+
op_type=OPS_MAP[op_type],
|
|
86
|
+
ref_slice=slice(*ref_match.span()),
|
|
87
|
+
ref=ref_match.group(),
|
|
88
|
+
)
|
|
89
|
+
elif op_type == "insert":
|
|
90
|
+
hyp_match = self._hyp_token_matches[hyp_idx]
|
|
91
|
+
alignment = Alignment(
|
|
92
|
+
op_type=OPS_MAP[op_type],
|
|
93
|
+
hyp_slice=slice(*hyp_match.span()),
|
|
94
|
+
hyp=hyp_match.group(),
|
|
95
|
+
)
|
|
96
|
+
else:
|
|
97
|
+
raise ValueError(f"Unknown operation type: {op_type}")
|
|
98
|
+
alignments.append(alignment)
|
|
99
|
+
|
|
100
|
+
return alignments
|