error-align 0.1.0b5__cp313-cp313-win32.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 +6 -0
- error_align/_cpp_beam_search.cp313-win32.pyd +0 -0
- error_align/_cpp_edit_distance.cp313-win32.pyd +0 -0
- error_align/backtrace_graph.py +224 -0
- error_align/baselines/__init__.py +10 -0
- error_align/baselines/optimal_word_alignment.py +112 -0
- error_align/baselines/power/cmudict.rep.json +1 -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 +79 -0
- error_align/baselines/rapidfuzz_word_alignment.py +100 -0
- error_align/baselines/utils.py +93 -0
- error_align/beam_search.py +337 -0
- error_align/core.py +26 -0
- error_align/edit_distance.py +144 -0
- error_align/error_align.py +224 -0
- error_align/graph_metadata.py +124 -0
- error_align/path_to_alignment.py +112 -0
- error_align/utils.py +212 -0
- error_align-0.1.0b5.dist-info/METADATA +155 -0
- error_align-0.1.0b5.dist-info/RECORD +32 -0
- error_align-0.1.0b5.dist-info/WHEEL +5 -0
error_align/__init__.py
ADDED
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import random
|
|
2
|
+
from collections import Counter
|
|
3
|
+
|
|
4
|
+
from error_align.utils import END_DELIMITER, OP_TYPE_COMBO_MAP, START_DELIMITER, OpType
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Node:
|
|
8
|
+
"""Node in the backtrace graph corresponding to the index (i, j) in the backtrace matrix."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, hyp_idx, ref_idx) -> None:
|
|
11
|
+
"""Initialize the node at index (i, j)."""
|
|
12
|
+
self.hyp_idx = hyp_idx
|
|
13
|
+
self.ref_idx = ref_idx
|
|
14
|
+
self.children = {}
|
|
15
|
+
self.parents = {}
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def index(self) -> tuple[int, int]:
|
|
19
|
+
return (self.hyp_idx, self.ref_idx)
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def offset_index(self) -> tuple[int, int]:
|
|
23
|
+
"""Get the offset index of the node so indices match the hypothesis and reference strings.
|
|
24
|
+
|
|
25
|
+
Root will be at (-1, -1).
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
tuple[int, int]: The offset index of the node in the backtrace matrix.
|
|
29
|
+
|
|
30
|
+
"""
|
|
31
|
+
return (self.hyp_idx - 1, self.ref_idx - 1)
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def is_terminal(self) -> bool:
|
|
35
|
+
"""Check if the node is a terminal node (i.e., it has no children)."""
|
|
36
|
+
return len(self.children) == 0
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def is_root(self) -> bool:
|
|
40
|
+
"""Check if the node is a root node (i.e., it has no parents)."""
|
|
41
|
+
return len(self.parents) == 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class BacktraceGraph:
|
|
45
|
+
"""Backtrace alignment graph."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, backtrace_matrix: list[list[int]]) -> None:
|
|
48
|
+
"""Create a graph from the backtrace matrix."""
|
|
49
|
+
self.hyp_dim = len(backtrace_matrix)
|
|
50
|
+
self.ref_dim = len(backtrace_matrix[0])
|
|
51
|
+
self.hyp_max_idx = self.hyp_dim - 1
|
|
52
|
+
self.ref_max_idx = self.ref_dim - 1
|
|
53
|
+
self.backtrace_matrix = backtrace_matrix
|
|
54
|
+
|
|
55
|
+
self._nodes = None
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def nodes(self) -> dict[tuple[int, int], Node]:
|
|
59
|
+
"""Get the nodes in the graph.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
dict: A dictionary of nodes indexed by their (hyp_idx, ref_idx).
|
|
63
|
+
|
|
64
|
+
"""
|
|
65
|
+
if self._nodes is None:
|
|
66
|
+
terminal_node = Node(self.hyp_max_idx, self.ref_max_idx)
|
|
67
|
+
self._nodes = {terminal_node.index: terminal_node}
|
|
68
|
+
|
|
69
|
+
# Traverse nodes in reverse topological order to add parents.
|
|
70
|
+
for index in self._iter_topological_order(reverse=True):
|
|
71
|
+
if index in self._nodes and index != (0, 0):
|
|
72
|
+
self._add_parents_from_backtrace(index)
|
|
73
|
+
|
|
74
|
+
# Sort nodes by their indices to ensure topological order.
|
|
75
|
+
self._nodes = dict(sorted(self._nodes.items(), key=lambda item: (item[0][0], item[0][1])))
|
|
76
|
+
|
|
77
|
+
return self._nodes
|
|
78
|
+
|
|
79
|
+
def get_node(self, hyp_idx, ref_idx):
|
|
80
|
+
"""Get the node at the given index.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
hyp_idx (int): Hyp/row index.
|
|
84
|
+
ref_idx (int): Ref/column index.
|
|
85
|
+
|
|
86
|
+
"""
|
|
87
|
+
return self.nodes[(hyp_idx, ref_idx)]
|
|
88
|
+
|
|
89
|
+
def get_node_set(self):
|
|
90
|
+
"""Get the set of all node indices in the graph.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
set: A set of all node indices.
|
|
94
|
+
|
|
95
|
+
"""
|
|
96
|
+
transitions = set()
|
|
97
|
+
for node in self.nodes.values():
|
|
98
|
+
transitions.add(node.offset_index)
|
|
99
|
+
return transitions
|
|
100
|
+
|
|
101
|
+
def get_path(self, sample=False):
|
|
102
|
+
"""Get a path through the graph.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
sample (bool): If True, sample a path randomly based on the transition probabilities. Otherwise, return
|
|
106
|
+
the first path deterministically.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
list[Node]: A list of nodes representing the path.
|
|
110
|
+
|
|
111
|
+
"""
|
|
112
|
+
node = self.get_node(0, 0)
|
|
113
|
+
assert node.is_root, "The node at (-1, -1) was expected to be a root node."
|
|
114
|
+
|
|
115
|
+
path = []
|
|
116
|
+
while not node.is_terminal:
|
|
117
|
+
if sample:
|
|
118
|
+
op_type = random.choice(list(node.children.keys()))
|
|
119
|
+
else:
|
|
120
|
+
op_type = next(iter(node.children.keys()))
|
|
121
|
+
node = node.children[op_type]
|
|
122
|
+
path.append((op_type, node))
|
|
123
|
+
|
|
124
|
+
return path
|
|
125
|
+
|
|
126
|
+
def get_unambiguous_node_matches(self) -> list[tuple[int, int]]:
|
|
127
|
+
"""Get nodes that can only be accounted for by a match.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
list[tuple[int, int]]: A list of index tuples representing the unambiguous node matches.
|
|
131
|
+
|
|
132
|
+
"""
|
|
133
|
+
match_indices = set()
|
|
134
|
+
match_per_token = {
|
|
135
|
+
"ref": Counter(),
|
|
136
|
+
"hyp": Counter(),
|
|
137
|
+
}
|
|
138
|
+
ref_op_types = {OpType.MATCH, OpType.SUBSTITUTE, OpType.DELETE}
|
|
139
|
+
hyp_op_types = {OpType.MATCH, OpType.SUBSTITUTE, OpType.INSERT}
|
|
140
|
+
|
|
141
|
+
for (hyp_idx, ref_idx), node in self.nodes.items():
|
|
142
|
+
# Identify all nodes at which a match occurs.
|
|
143
|
+
if len(node.parents) == 1 and OpType.MATCH in node.parents:
|
|
144
|
+
match_indices.add((hyp_idx, ref_idx))
|
|
145
|
+
|
|
146
|
+
# Count number of paths passing through each token.
|
|
147
|
+
if ref_op_types.intersection(node.parents):
|
|
148
|
+
match_per_token["ref"][ref_idx] += 1
|
|
149
|
+
if hyp_op_types.intersection(node.parents):
|
|
150
|
+
match_per_token["hyp"][hyp_idx] += 1
|
|
151
|
+
|
|
152
|
+
# Collect only those matches that are unambiguous on both sides.
|
|
153
|
+
unambiguous_matches = []
|
|
154
|
+
for hyp_idx, ref_idx in match_indices:
|
|
155
|
+
if match_per_token["ref"][ref_idx] == 1 and match_per_token["hyp"][hyp_idx] == 1:
|
|
156
|
+
unambiguous_matches.append((hyp_idx - 1, ref_idx - 1)) # Offset indices
|
|
157
|
+
|
|
158
|
+
return sorted(unambiguous_matches, key=lambda n: n[1])
|
|
159
|
+
|
|
160
|
+
def get_unambiguous_token_span_matches(self, ref):
|
|
161
|
+
"""Get word spans (i.e., <...>) that are unambiguously matched.
|
|
162
|
+
|
|
163
|
+
That is, there is only one subpath that can account for the span using MATCH operations.
|
|
164
|
+
|
|
165
|
+
Other subpaths that include INSERT, DELETE, SUBSTITUTE operations are not considered.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
list[tuple[int, int]]: A list of index tuples representing the end node of unambiguous span matches.
|
|
169
|
+
|
|
170
|
+
"""
|
|
171
|
+
ref = "_" + ref # NOTE: Implicit index offset for root node.
|
|
172
|
+
mono_match_end_nodes = set()
|
|
173
|
+
ref_idxs = Counter()
|
|
174
|
+
hyp_idxs = Counter()
|
|
175
|
+
for (hyp_idx, ref_idx), node in self.nodes.items():
|
|
176
|
+
if OpType.MATCH in node.parents and ref[ref_idx] == START_DELIMITER:
|
|
177
|
+
_ref_idx, _hyp_idx = ref_idx + 1, hyp_idx + 1
|
|
178
|
+
while True:
|
|
179
|
+
if (_hyp_idx, _ref_idx) not in self.nodes:
|
|
180
|
+
break
|
|
181
|
+
if OpType.MATCH not in self.nodes[(_hyp_idx, _ref_idx)].parents:
|
|
182
|
+
break
|
|
183
|
+
if ref[_ref_idx] == END_DELIMITER:
|
|
184
|
+
end_index = (_hyp_idx, _ref_idx)
|
|
185
|
+
mono_match_end_nodes.add(end_index)
|
|
186
|
+
ref_idxs[_ref_idx] += 1
|
|
187
|
+
hyp_idxs[_hyp_idx] += 1
|
|
188
|
+
break
|
|
189
|
+
_ref_idx, _hyp_idx = _ref_idx + 1, _hyp_idx + 1
|
|
190
|
+
|
|
191
|
+
return {(h - 1, r - 1) for h, r in mono_match_end_nodes if hyp_idxs[h] == 1 and ref_idxs[r] == 1}
|
|
192
|
+
|
|
193
|
+
def _parent_index_from_op_type(self, hyp_idx, ref_idx, op_type):
|
|
194
|
+
"""Create a parent node based on the index of the current node and the operation type."""
|
|
195
|
+
hyp_idx = hyp_idx - 1 if op_type != OpType.DELETE else hyp_idx
|
|
196
|
+
ref_idx = ref_idx - 1 if op_type != OpType.INSERT else ref_idx
|
|
197
|
+
if (hyp_idx, ref_idx) not in self._nodes:
|
|
198
|
+
self._nodes[(hyp_idx, ref_idx)] = Node(hyp_idx, ref_idx)
|
|
199
|
+
return self._nodes[(hyp_idx, ref_idx)]
|
|
200
|
+
|
|
201
|
+
def _iter_topological_order(self, reverse=False):
|
|
202
|
+
"""Iterate through the nodes in topological order."""
|
|
203
|
+
if reverse:
|
|
204
|
+
for i in reversed(range(self.hyp_dim)):
|
|
205
|
+
for j in reversed(range(self.ref_dim)):
|
|
206
|
+
yield (i, j)
|
|
207
|
+
else:
|
|
208
|
+
for i in range(self.hyp_dim):
|
|
209
|
+
for j in range(self.ref_dim):
|
|
210
|
+
yield (i, j)
|
|
211
|
+
|
|
212
|
+
def _add_parents_from_backtrace(self, index):
|
|
213
|
+
"""Add parents to the node at the given index based on the backtrace matrix."""
|
|
214
|
+
node = self._nodes.get(index, None)
|
|
215
|
+
|
|
216
|
+
assert node is not None, f"Node at index {index} does not exist in the graph."
|
|
217
|
+
|
|
218
|
+
op_type_combo_code = self.backtrace_matrix[node.hyp_idx][node.ref_idx]
|
|
219
|
+
op_type_combo = OP_TYPE_COMBO_MAP[op_type_combo_code]
|
|
220
|
+
|
|
221
|
+
for op_type in op_type_combo:
|
|
222
|
+
parent_node = self._parent_index_from_op_type(*node.index, op_type)
|
|
223
|
+
node.parents[op_type] = parent_node
|
|
224
|
+
parent_node.children[op_type] = node
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
|
|
2
|
+
try:
|
|
3
|
+
from error_align.baselines.optimal_word_alignment import OptimalWordAlign as OptimalWordAlign
|
|
4
|
+
from error_align.baselines.power_alignment import PowerAlign as PowerAlign
|
|
5
|
+
from error_align.baselines.rapidfuzz_word_alignment import RapidFuzzWordAlign as RapidFuzzWordAlign
|
|
6
|
+
except ImportError:
|
|
7
|
+
raise ImportError(
|
|
8
|
+
"Baselines module could not be imported. Please ensure all dependencies are installed. "
|
|
9
|
+
"You can install the evaluation dependencies using: pip install error-align[evaluation]"
|
|
10
|
+
)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from rapidfuzz.distance import Levenshtein
|
|
2
|
+
|
|
3
|
+
from error_align.backtrace_graph import BacktraceGraph
|
|
4
|
+
from error_align.edit_distance import compute_distance_matrix
|
|
5
|
+
from error_align.utils import (
|
|
6
|
+
Alignment,
|
|
7
|
+
OpType,
|
|
8
|
+
basic_normalizer,
|
|
9
|
+
basic_tokenizer,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _get_optimal_word_alignment_values(ref_token: str, hyp_token: str):
|
|
14
|
+
"""Compute the optimal word alignment values for deletion, insertion, and diagonal (substitution or match).
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
ref_token (str): The reference token.
|
|
18
|
+
hyp_token (str): The hypothesis token.
|
|
19
|
+
|
|
20
|
+
Returns:
|
|
21
|
+
tuple: A tuple containing the deletion cost, insertion cost, and diagonal cost.
|
|
22
|
+
"""
|
|
23
|
+
if hyp_token == ref_token:
|
|
24
|
+
diag_cost = 0
|
|
25
|
+
else:
|
|
26
|
+
diag_cost = Levenshtein.distance(ref_token, hyp_token, weights=(1, 1, 2))
|
|
27
|
+
diag_cost += abs(len(ref_token) - len(hyp_token))
|
|
28
|
+
|
|
29
|
+
return len(hyp_token), len(ref_token), diag_cost
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class OptimalWordAlign:
|
|
33
|
+
"""Optimal word-level alignment based on global-to-local edits (GLE) metric."""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
ref: str,
|
|
38
|
+
hyp: str,
|
|
39
|
+
tokenizer: callable = basic_tokenizer,
|
|
40
|
+
normalizer: callable = basic_normalizer,
|
|
41
|
+
):
|
|
42
|
+
"""Initialize the optimal word-level alignment with reference and hypothesis texts.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
ref (str): The reference sequence/transcript.
|
|
46
|
+
hyp (str): The hypothesis sequence/transcript.
|
|
47
|
+
tokenizer (callable): A function to tokenize the sequences. Must be regex-based and return Match objects.
|
|
48
|
+
normalizer (callable): A function to normalize the tokens. Defaults to basic_normalizer.
|
|
49
|
+
"""
|
|
50
|
+
if not isinstance(ref, str):
|
|
51
|
+
raise TypeError("Reference sequence must be a string.")
|
|
52
|
+
if not isinstance(hyp, str):
|
|
53
|
+
raise TypeError("Hypothesis sequence must be a string.")
|
|
54
|
+
|
|
55
|
+
self.ref = ref
|
|
56
|
+
self.hyp = hyp
|
|
57
|
+
self._ref_token_matches = tokenizer(ref)
|
|
58
|
+
self._hyp_token_matches = tokenizer(hyp)
|
|
59
|
+
self._ref = [normalizer(r.group()) for r in self._ref_token_matches]
|
|
60
|
+
self._hyp = [normalizer(h.group()) for h in self._hyp_token_matches]
|
|
61
|
+
self._ref_max_idx = len(self._ref) - 1
|
|
62
|
+
self._hyp_max_idx = len(self._hyp) - 1
|
|
63
|
+
self.end_index = (self._hyp_max_idx, self._ref_max_idx)
|
|
64
|
+
|
|
65
|
+
# Extract backtrace graph.
|
|
66
|
+
_, B = compute_distance_matrix(
|
|
67
|
+
self._ref,
|
|
68
|
+
self._hyp,
|
|
69
|
+
_get_optimal_word_alignment_values,
|
|
70
|
+
backtrace=True,
|
|
71
|
+
dtype=float,
|
|
72
|
+
)
|
|
73
|
+
self._backtrace_graph = BacktraceGraph(B)
|
|
74
|
+
|
|
75
|
+
def align(self) -> list[Alignment]:
|
|
76
|
+
"""Extract an arbitrary path from the backtrace graph -- all paths are equal wrt. to the GLE metric.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
list[Alignment]: A list of Alignment objects.
|
|
80
|
+
"""
|
|
81
|
+
path = self._backtrace_graph.get_path()
|
|
82
|
+
alignments = []
|
|
83
|
+
for op_type, node in path:
|
|
84
|
+
if op_type == OpType.MATCH or op_type == OpType.SUBSTITUTE:
|
|
85
|
+
ref_match = self._ref_token_matches[node.ref_idx - 1]
|
|
86
|
+
hyp_match = self._hyp_token_matches[node.hyp_idx - 1]
|
|
87
|
+
alignment = Alignment(
|
|
88
|
+
op_type=op_type,
|
|
89
|
+
ref_slice=slice(*ref_match.span()),
|
|
90
|
+
hyp_slice=slice(*hyp_match.span()),
|
|
91
|
+
ref=ref_match.group(),
|
|
92
|
+
hyp=hyp_match.group(),
|
|
93
|
+
)
|
|
94
|
+
elif op_type == OpType.DELETE:
|
|
95
|
+
ref_match = self._ref_token_matches[node.ref_idx - 1]
|
|
96
|
+
alignment = Alignment(
|
|
97
|
+
op_type=op_type,
|
|
98
|
+
ref_slice=slice(*ref_match.span()),
|
|
99
|
+
ref=ref_match.group(),
|
|
100
|
+
)
|
|
101
|
+
elif op_type == OpType.INSERT:
|
|
102
|
+
hyp_match = self._hyp_token_matches[node.hyp_idx - 1]
|
|
103
|
+
alignment = Alignment(
|
|
104
|
+
op_type=op_type,
|
|
105
|
+
hyp_slice=slice(*hyp_match.span()),
|
|
106
|
+
hyp=hyp_match.group(),
|
|
107
|
+
)
|
|
108
|
+
else:
|
|
109
|
+
raise ValueError(f"Unknown operation type: {op_type}")
|
|
110
|
+
alignments.append(alignment)
|
|
111
|
+
|
|
112
|
+
return alignments
|