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,495 @@
1
+ from collections import defaultdict
2
+ from typing import Union
3
+
4
+ import regex as re
5
+ from tqdm import tqdm
6
+
7
+ from error_align.backtrace_graph import BacktraceGraph
8
+ from error_align.edit_distance import compute_error_align_distance_matrix
9
+ from error_align.utils import (
10
+ END_DELIMITER,
11
+ START_DELIMITER,
12
+ Alignment,
13
+ OpType,
14
+ basic_normalizer,
15
+ basic_tokenizer,
16
+ categorize_char,
17
+ ensure_length_preservation,
18
+ get_manhattan_distance,
19
+ )
20
+
21
+
22
+ class ErrorAlign:
23
+ """Error alignment class that performs a two-pass alignment process."""
24
+
25
+ def __init__(
26
+ self,
27
+ ref: str,
28
+ hyp: str,
29
+ tokenizer: callable = basic_tokenizer,
30
+ normalizer: callable = basic_normalizer,
31
+ ):
32
+ """Initialize the error alignment with reference and hypothesis texts.
33
+
34
+ The first pass (backtrace graph extraction) is performed during initialization.
35
+
36
+ The second pass (beam search) is performed in the `align` method.
37
+
38
+ Args:
39
+ ref (str): The reference sequence/transcript.
40
+ hyp (str): The hypothesis sequence/transcript.
41
+ tokenizer (callable): A function to tokenize the sequences. Must be regex-based and return Match objects.
42
+ normalizer (callable): A function to normalize the tokens. Defaults to basic_normalizer.
43
+
44
+ """
45
+ if not isinstance(ref, str):
46
+ raise TypeError("Reference sequence must be a string.")
47
+ if not isinstance(hyp, str):
48
+ raise TypeError("Hypothesis sequence must be a string.")
49
+
50
+ self.ref = ref
51
+ self.hyp = hyp
52
+
53
+ # Inclusive tokenization: Track the token position in the original text.
54
+ self._ref_token_matches = tokenizer(ref)
55
+ self._hyp_token_matches = tokenizer(hyp)
56
+
57
+ # Length-preserving normalization: Ensure that the normalizer preserves token length.
58
+ normalizer = ensure_length_preservation(normalizer)
59
+ self._ref = "".join([f"<{normalizer(r.group())}>" for r in self._ref_token_matches])
60
+ self._hyp = "".join([f"<{normalizer(h.group())}>" for h in self._hyp_token_matches])
61
+
62
+ # Categorize characters.
63
+ self._ref_char_types = list(map(categorize_char, self._ref))
64
+ self._hyp_char_types = list(map(categorize_char, self._hyp))
65
+
66
+ # Initialize graph attributes.
67
+ self._identical_inputs = self._ref == self._hyp
68
+ self._ref_max_idx = len(self._ref) - 1
69
+ self._hyp_max_idx = len(self._hyp) - 1
70
+ self.end_index = (self._hyp_max_idx, self._ref_max_idx)
71
+
72
+ # Create index maps for reference and hypothesis sequences.
73
+ self._ref_index_map = self._create_index_map(self._ref_token_matches)
74
+ self._hyp_index_map = self._create_index_map(self._hyp_token_matches)
75
+
76
+ # First pass: Extract backtrace graph.
77
+ if not self._identical_inputs:
78
+ _, backtrace_matrix = compute_error_align_distance_matrix(self._ref, self._hyp, backtrace=True)
79
+ self._backtrace_graph = BacktraceGraph(backtrace_matrix)
80
+ self._backtrace_node_set = self._backtrace_graph.get_node_set()
81
+ self._unambiguous_matches = self._backtrace_graph.get_unambiguous_matches(self._ref)
82
+ else:
83
+ self._backtrace_graph = None
84
+ self._backtrace_node_set = None
85
+ self._unambiguous_matches = None
86
+
87
+ def __repr__(self):
88
+ ref_preview = self.ref if len(self.ref) < 20 else self.ref[:17] + "..."
89
+ hyp_preview = self.hyp if len(self.hyp) < 20 else self.hyp[:17] + "..."
90
+ return f'ErrorAlign(ref="{ref_preview}", hyp="{hyp_preview}")'
91
+
92
+ def align(
93
+ self,
94
+ beam_size: int = 100,
95
+ pbar: bool = False,
96
+ return_path: bool = False,
97
+ ) -> Union[list[Alignment], "Path"]:
98
+ """Perform beam search to align reference and hypothesis texts.
99
+
100
+ Args:
101
+ beam_size (int): The size of the beam for beam search. Defaults to 100.
102
+ pbar (bool): Whether to display a progress bar. Defaults to False.
103
+ return_path (bool): Whether to return the path object or just the alignments. Defaults to False.
104
+
105
+ Returns:
106
+ list[Alignment]: A list of Alignment objects.
107
+
108
+ """
109
+ # Skip beam search if inputs are identical.
110
+ if self._identical_inputs:
111
+ return self._identical_input_alignments()
112
+
113
+ # Initialize the beam with a single path starting at the root node.
114
+ start_path = Path(self)
115
+ beam = {start_path.pid: start_path}
116
+ prune_map = defaultdict(lambda: float("inf"))
117
+ ended = []
118
+
119
+ # Setup progress bar, if enabled.
120
+ if pbar:
121
+ total_mdist = self._ref_max_idx + self._hyp_max_idx + 2
122
+ progress_bar = tqdm(total=total_mdist, desc="Aligning transcripts")
123
+
124
+ # Expand candidate paths until all have reached the terminal node.
125
+ while len(beam) > 0:
126
+ new_beam = {}
127
+
128
+ # Expand each path in the current beam.
129
+ for path in beam.values():
130
+ if path.at_end:
131
+ ended.append(path)
132
+ continue
133
+
134
+ # Transition to all child nodes.
135
+ for new_path in path.expand():
136
+ if new_path.pid in prune_map:
137
+ if new_path.cost > prune_map[new_path.pid]:
138
+ continue
139
+ prune_map[new_path.pid] = new_path.cost
140
+
141
+ if new_path.pid not in new_beam or new_path.cost < new_beam[new_path.pid].cost:
142
+ new_beam[new_path.pid] = new_path
143
+
144
+ # Update the beam with the newly expanded paths.
145
+ new_beam = list(new_beam.values())
146
+ new_beam.sort(key=lambda p: p.norm_cost)
147
+ beam = new_beam[:beam_size]
148
+
149
+ # Keep only the best path if, it matches the segment.
150
+ if len(beam) > 0 and beam[0]._at_unambiguous_match_node:
151
+ beam = beam[:1]
152
+ prune_map = defaultdict(lambda: float("inf"))
153
+ beam = {p.pid: p for p in beam} # Convert to dict for diversity check.
154
+
155
+ # Update progress bar, if enabled.
156
+ try:
157
+ worst_path = next(reversed(beam.values()))
158
+ mdist = get_manhattan_distance(worst_path.index, self.end_index)
159
+ if pbar:
160
+ progress_bar.n = total_mdist - mdist
161
+ progress_bar.refresh()
162
+ except StopIteration:
163
+ if pbar:
164
+ progress_bar.n = total_mdist
165
+ progress_bar.refresh()
166
+
167
+ # Return the best path or its alignments.
168
+ ended.sort(key=lambda p: p.cost)
169
+ if return_path:
170
+ return ended[0] if len(ended) > 0 else None
171
+ return ended[0].alignments if len(ended) > 0 else []
172
+
173
+ def _create_index_map(self, text_tokens: list[re.Match]) -> list[int]:
174
+ """Create an index map for the given tokens.
175
+
176
+ The 'index_map' is used to map each aligned character back to its original position in the input text.
177
+
178
+ NOTE: -1 is used for delimiter (<>) and indicates no match in the source sequence.
179
+ """
180
+ index_map = []
181
+ for match in text_tokens:
182
+ index_map.extend([-1]) # Start delimiter
183
+ index_map.extend(list(range(*match.span())))
184
+ index_map.extend([-1]) # End delimiter
185
+ return index_map
186
+
187
+ def _identical_input_alignments(self) -> list[Alignment]:
188
+ """Return alignments for identical reference and hypothesis pairs."""
189
+ assert self._identical_inputs, "Inputs are not identical."
190
+
191
+ alignments = []
192
+ for ref_match, hyp_match in zip(self._ref_token_matches, self._hyp_token_matches, strict=False):
193
+ ref_slice = slice(*ref_match.span())
194
+ hyp_slice = slice(*hyp_match.span())
195
+ ref_token = self.ref[ref_slice]
196
+ hyp_token = self.hyp[hyp_slice]
197
+ alignment = Alignment(
198
+ op_type=OpType.MATCH,
199
+ ref_slice=ref_slice,
200
+ hyp_slice=hyp_slice,
201
+ ref=ref_token,
202
+ hyp=hyp_token,
203
+ )
204
+ alignments.append(alignment)
205
+ return alignments
206
+
207
+
208
+ class Path:
209
+ """Class to represent a graph path."""
210
+
211
+ def __init__(self, src: ErrorAlign):
212
+ """Initialize the Path class with a given path."""
213
+ self.src = src
214
+ self.ref_idx = -1
215
+ self.hyp_idx = -1
216
+ self._closed_cost = 0
217
+ self._open_cost = 0
218
+ self._at_unambiguous_match_node = False
219
+ self._last_end_index = (-1, -1)
220
+ self._end_indices = tuple()
221
+ self._alignments = None
222
+ self._alignments_index = None
223
+
224
+ def __repr__(self):
225
+ return f"Path(({self.ref_idx}, {self.hyp_idx}), score={self.cost})"
226
+
227
+ @property
228
+ def alignments(self) -> list[Alignment]:
229
+ """Get the alignments of the path."""
230
+ # Return cached alignments if available and the path has not changed.
231
+ if self._alignments is not None and self._alignments_index == self.index:
232
+ return self._alignments
233
+
234
+ self._alignments_index = self.index
235
+ alignments = []
236
+ start_hyp, start_ref = (0, 0)
237
+ for (end_hyp, end_ref), score in self._end_indices:
238
+ end_hyp, end_ref = end_hyp + 1, end_ref + 1
239
+
240
+ # Construct DELETE alignment.
241
+ if start_hyp == end_hyp:
242
+ assert start_ref < end_ref
243
+ ref_slice = slice(start_ref, end_ref)
244
+ ref_slice = self._translate_slice(ref_slice, self.src._ref_index_map)
245
+ assert ref_slice is not None
246
+ alignment = Alignment(
247
+ op_type=OpType.DELETE,
248
+ ref_slice=ref_slice,
249
+ ref=self.src.ref[ref_slice],
250
+ )
251
+ alignments.append(alignment)
252
+
253
+ # Construct INSERT alignment.
254
+ elif start_ref == end_ref:
255
+ assert start_hyp < end_hyp
256
+ hyp_slice = slice(start_hyp, end_hyp)
257
+ hyp_slice = self._translate_slice(hyp_slice, self.src._hyp_index_map)
258
+ assert hyp_slice is not None
259
+ alignment = Alignment(
260
+ op_type=OpType.INSERT,
261
+ hyp_slice=hyp_slice,
262
+ hyp=self.src.hyp[hyp_slice],
263
+ left_compound=self.src._hyp_index_map[start_hyp] >= 0,
264
+ right_compound=self.src._hyp_index_map[end_hyp - 1] >= 0,
265
+ )
266
+ alignments.append(alignment)
267
+
268
+ # Construct SUBSTITUTE or MATCH alignment.
269
+ else:
270
+ assert start_hyp < end_hyp and start_ref < end_ref
271
+ hyp_slice = slice(start_hyp, end_hyp)
272
+ ref_slice = slice(start_ref, end_ref)
273
+ hyp_slice = self._translate_slice(hyp_slice, self.src._hyp_index_map)
274
+ ref_slice = self._translate_slice(ref_slice, self.src._ref_index_map)
275
+ assert hyp_slice is not None and ref_slice is not None
276
+ is_match_segment = score == 0
277
+ op_type = OpType.MATCH if is_match_segment else OpType.SUBSTITUTE
278
+ alignment = Alignment(
279
+ op_type=op_type,
280
+ ref_slice=ref_slice,
281
+ hyp_slice=hyp_slice,
282
+ ref=self.src.ref[ref_slice],
283
+ hyp=self.src.hyp[hyp_slice],
284
+ left_compound=self.src._hyp_index_map[start_hyp] >= 0,
285
+ right_compound=self.src._hyp_index_map[end_hyp - 1] >= 0,
286
+ )
287
+ alignments.append(alignment)
288
+
289
+ start_hyp, start_ref = end_hyp, end_ref
290
+
291
+ # Cache the computed alignments.
292
+ self._alignments = alignments
293
+
294
+ return alignments
295
+
296
+ @property
297
+ def pid(self):
298
+ """Get the ID of the path used for pruning."""
299
+ return hash((self.index, self._last_end_index))
300
+
301
+ @property
302
+ def cost(self):
303
+ """Get the cost of the path."""
304
+ return self._closed_cost + self._open_cost + self._substitution_penalty()
305
+
306
+ @property
307
+ def norm_cost(self):
308
+ """Get the normalized cost of the path."""
309
+ if self.cost == 0:
310
+ return 0
311
+ return self.cost / (self.ref_idx + self.hyp_idx + 3) # NOTE: +3 to avoid zero division. Root = (-1,-1).
312
+
313
+ @property
314
+ def index(self):
315
+ """Get the current node index of the path."""
316
+ return (self.hyp_idx, self.ref_idx)
317
+
318
+ @property
319
+ def at_end(self):
320
+ """Check if the path has reached the terminal node."""
321
+ return self.index == self.src.end_index
322
+
323
+ def expand(self):
324
+ """Expand the path by transitioning to child nodes.
325
+
326
+ Yields:
327
+ Path: The expanded child paths.
328
+
329
+ """
330
+ # Add delete operation.
331
+ delete_path = self._add_delete()
332
+ if delete_path is not None:
333
+ yield delete_path
334
+
335
+ # Add insert operation.
336
+ insert_path = self._add_insert()
337
+ if insert_path is not None:
338
+ yield insert_path
339
+
340
+ # Add substitution or match operation.
341
+ sub_or_match_path = self._add_substitution_or_match()
342
+ if sub_or_match_path is not None:
343
+ yield sub_or_match_path
344
+
345
+ def _transition_and_shallow_copy(self, ref_step: int, hyp_step: int):
346
+ """Create a shallow copy of the path."""
347
+ new_path = Path(self.src)
348
+ new_path.ref_idx = self.ref_idx + ref_step
349
+ new_path.hyp_idx = self.hyp_idx + hyp_step
350
+ new_path._closed_cost = self._closed_cost
351
+ new_path._open_cost = self._open_cost
352
+ new_path._at_unambiguous_match_node = False
353
+ new_path._last_end_index = self._last_end_index
354
+ new_path._end_indices = self._end_indices
355
+
356
+ return new_path
357
+
358
+ def _reset_segment_variables(self, index: tuple[int, int]) -> None:
359
+ """Apply updates when segment end is detected."""
360
+ self._closed_cost += self._open_cost
361
+ self._closed_cost += self._substitution_penalty(index)
362
+ self._last_end_index = index
363
+ self._open_cost = 0
364
+
365
+ def _end_insertion_segment(self, index: tuple[int, int]) -> None:
366
+ """End the current segment, if criteria for an insertion are met."""
367
+ hyp_slice = slice(self._last_end_index[0] + 1, index[0] + 1)
368
+ hyp_slice = self._translate_slice(hyp_slice, self.src._hyp_index_map)
369
+ ref_is_empty = index[1] == self._last_end_index[1]
370
+ if hyp_slice is not None and ref_is_empty:
371
+ self._end_indices += ((index, self._open_cost),)
372
+ self._reset_segment_variables(index)
373
+
374
+ def _end_segment(self) -> Union[None, "Path"]:
375
+ """End the current segment, if criteria for an insertion, a substitution, or a match are met."""
376
+ hyp_slice = slice(self._last_end_index[0] + 1, self.index[0] + 1)
377
+ hyp_slice = self._translate_slice(hyp_slice, self.src._hyp_index_map)
378
+ ref_slice = slice(self._last_end_index[1] + 1, self.index[1] + 1)
379
+ ref_slice = self._translate_slice(ref_slice, self.src._ref_index_map)
380
+
381
+ assert ref_slice is not None
382
+
383
+ hyp_is_empty = self.index[0] == self._last_end_index[0]
384
+ if hyp_is_empty:
385
+ self._end_indices += ((self.index, self._open_cost),)
386
+ else:
387
+ # TODO: Handle edge case where hyp has only covered delimiters.
388
+ if hyp_slice is None:
389
+ return None
390
+
391
+ is_match_segment = self._open_cost == 0
392
+ self._at_unambiguous_match_node = is_match_segment and self.index in self.src._unambiguous_matches
393
+ self._end_indices += ((self.index, self._open_cost),)
394
+
395
+ # Update the path score and reset segments attributes.
396
+ self._reset_segment_variables(self.index)
397
+ return self
398
+
399
+ def _in_backtrace_node_set(self, index) -> bool:
400
+ """Check if the given operation is an optimal transition at the current index."""
401
+ return index in self.src._backtrace_node_set
402
+
403
+ def _add_delete(self) -> Union[None, "Path"]:
404
+ """Expand the path by adding a delete operation."""
405
+ # Ensure we are not at the end of the hypothesis sequence.
406
+ if self.hyp_idx >= self.src._hyp_max_idx:
407
+ return None
408
+
409
+ # Transition and update costs.
410
+ new_path = self._transition_and_shallow_copy(ref_step=0, hyp_step=1)
411
+ is_backtrace = self._in_backtrace_node_set(self.index)
412
+ is_delimiter = self.src._hyp_char_types[new_path.hyp_idx] == 0 # NOTE: 0 indicates delimiter.
413
+ new_path._open_cost += 1 if is_delimiter else 2
414
+ new_path._open_cost += 0 if is_backtrace or is_delimiter else 1
415
+
416
+ # Check for end-of-segment criteria.
417
+ if self.src._hyp[new_path.hyp_idx] == END_DELIMITER:
418
+ new_path._end_insertion_segment(new_path.index)
419
+
420
+ return new_path
421
+
422
+ def _add_insert(self) -> Union[None, "Path"]:
423
+ """Expand the path by adding an insert operation."""
424
+ # Ensure we are not at the end of the reference sequence.
425
+ if self.ref_idx >= self.src._ref_max_idx:
426
+ return None
427
+
428
+ # Transition and check for end-of-segment criteria.
429
+ new_path = self._transition_and_shallow_copy(ref_step=1, hyp_step=0)
430
+ if self.src._ref[new_path.ref_idx] == START_DELIMITER:
431
+ new_path._end_insertion_segment(self.index)
432
+
433
+ # Update costs.
434
+ is_backtrace = self._in_backtrace_node_set(self.index)
435
+ is_delimiter = self.src._ref_char_types[new_path.ref_idx] == 0 # NOTE: 0 indicates delimiter.
436
+ new_path._open_cost += 1 if is_delimiter else 2
437
+ new_path._open_cost += 0 if is_backtrace or is_delimiter else 1
438
+
439
+ # Check for end-of-segment criteria.
440
+ if self.src._ref[new_path.ref_idx] == END_DELIMITER:
441
+ new_path = new_path._end_segment()
442
+
443
+ return new_path
444
+
445
+ def _add_substitution_or_match(self) -> Union[None, "Path"]:
446
+ """Expand the given path by adding a substitution or match operation."""
447
+ # Ensure we are not at the end of either sequence.
448
+ if self.ref_idx >= self.src._ref_max_idx or self.hyp_idx >= self.src._hyp_max_idx:
449
+ return None
450
+
451
+ # Transition and ensure that the transition is allowed.
452
+ new_path = self._transition_and_shallow_copy(ref_step=1, hyp_step=1)
453
+ is_match = self.src._ref[new_path.ref_idx] == self.src._hyp[new_path.hyp_idx]
454
+ if not is_match:
455
+ ref_is_delimiter = self.src._ref_char_types[new_path.ref_idx] == 0 # NOTE: 0 indicates delimiter
456
+ hyp_is_delimiter = self.src._hyp_char_types[new_path.hyp_idx] == 0 # NOTE: 0 indicates delimiter
457
+ if ref_is_delimiter or hyp_is_delimiter:
458
+ return None
459
+
460
+ # Check for end-of-segment criteria.
461
+ if self.src._ref[new_path.ref_idx] == START_DELIMITER:
462
+ new_path._end_insertion_segment(self.index)
463
+
464
+ # Update costs, if not a match.
465
+ if not is_match:
466
+ is_backtrace = self._in_backtrace_node_set(self.index)
467
+ is_letter_type_match = (
468
+ self.src._ref_char_types[new_path.ref_idx] == self.src._hyp_char_types[new_path.hyp_idx]
469
+ )
470
+ new_path._open_cost += 2 if is_letter_type_match else 3
471
+ new_path._open_cost += 0 if is_backtrace else 1
472
+
473
+ # Check for end-of-segment criteria.
474
+ if self.src._ref[new_path.ref_idx] == END_DELIMITER:
475
+ new_path = new_path._end_segment()
476
+
477
+ return new_path
478
+
479
+ def _translate_slice(self, segment_slice: slice, index_map: list[int]) -> None | slice:
480
+ """Translate a slice from the alignment sequence back to the original sequence."""
481
+ slice_indices = index_map[segment_slice]
482
+ slice_indices = list(filter(lambda x: x >= 0, slice_indices))
483
+ if len(slice_indices) == 0:
484
+ return None
485
+ start, end = int(slice_indices[0]), int(slice_indices[-1] + 1)
486
+ return slice(start, end)
487
+
488
+ def _substitution_penalty(self, index: tuple[int, int] | None = None) -> int:
489
+ """Get the substitution penalty given an index."""
490
+ index = index or self.index
491
+ ref_is_not_empty = index[1] > self._last_end_index[1]
492
+ hyp_is_not_empty = index[0] > self._last_end_index[0]
493
+ if ref_is_not_empty and hyp_is_not_empty:
494
+ return self._open_cost
495
+ return 0
error_align/func.py ADDED
@@ -0,0 +1,38 @@
1
+ from error_align.error_align import ErrorAlign, Path
2
+ from error_align.utils import Alignment, basic_normalizer, basic_tokenizer
3
+
4
+
5
+ def error_align(
6
+ ref: str,
7
+ hyp: str,
8
+ tokenizer: callable = basic_tokenizer,
9
+ normalizer: callable = basic_normalizer,
10
+ beam_size: int = 100,
11
+ pbar: bool = False,
12
+ return_path: bool = False,
13
+ ) -> list[Alignment] | Path:
14
+ """Perform error alignment between two sequences.
15
+
16
+ Args:
17
+ ref (str): The reference sequence/transcript.
18
+ hyp (str): The hypothesis sequence/transcript.
19
+ tokenizer (callable): A function to tokenize the sequences. Must be regex-based and return Match objects.
20
+ normalizer (callable): A function to normalize the tokens. Defaults to basic_normalizer.
21
+ pbar (bool): Whether to display a progress bar. Defaults to False.
22
+ return_path (bool): Whether to return the path object or just the alignments. Defaults to False.
23
+
24
+ Returns:
25
+ list[tuple[str, str, OpType]]: A list of tuples containing aligned reference token,
26
+ hypothesis token, and the operation type.
27
+
28
+ """
29
+ return ErrorAlign(
30
+ ref,
31
+ hyp,
32
+ tokenizer=tokenizer,
33
+ normalizer=normalizer,
34
+ ).align(
35
+ beam_size=beam_size,
36
+ pbar=pbar,
37
+ return_path=return_path,
38
+ )
error_align/utils.py ADDED
@@ -0,0 +1,166 @@
1
+ from dataclasses import dataclass
2
+ from enum import IntEnum
3
+ from itertools import chain, combinations
4
+
5
+ import regex as re
6
+ from unidecode import unidecode
7
+
8
+
9
+ class OpType(IntEnum):
10
+ MATCH = 0
11
+ INSERT = 1
12
+ DELETE = 2
13
+ SUBSTITUTE = 3
14
+
15
+
16
+ @dataclass
17
+ class Alignment:
18
+ """Class representing an operation with its type and cost."""
19
+
20
+ op_type: OpType
21
+ ref_slice: slice | None = None
22
+ hyp_slice: slice | None = None
23
+ ref: str | None = None
24
+ hyp: str | None = None
25
+ left_compound: bool = False
26
+ right_compound: bool = False
27
+
28
+ @property
29
+ def hyp_with_compound_markers(self) -> str:
30
+ """Return the hypothesis with compound markers if applicable."""
31
+ if self.hyp is None:
32
+ return None
33
+ return f"{'-' if self.left_compound else ''}{self.hyp}{'-' if self.right_compound else ''}"
34
+
35
+ def __repr__(self) -> str:
36
+ lc = "-" if self.left_compound else ""
37
+ rc = "-" if self.right_compound else ""
38
+ if self.op_type == OpType.DELETE:
39
+ return f'Alignment({self.op_type.name}: "{self.ref}")'
40
+ if self.op_type == OpType.INSERT:
41
+ return f'Alignment({self.op_type.name}: "{self.hyp_with_compound_markers}")'
42
+ if self.op_type == OpType.SUBSTITUTE:
43
+ return f'Alignment({self.op_type.name}: "{self.ref}" -> {lc}"{self.hyp}"{rc})'
44
+ return f'Alignment({self.op_type.name}: "{self.ref}" == {lc}"{self.hyp}"{rc})'
45
+
46
+
47
+ def op_type_powerset() -> chain:
48
+ """Generate all possible combinations of operation types, except the empty set.
49
+
50
+ Returns:
51
+ Generator: All possible combinations of operation types.
52
+
53
+ """
54
+ op_types = list(OpType)
55
+ op_combinations = [combinations(op_types, r) for r in range(1, len(op_types) + 1)]
56
+ return chain.from_iterable(op_combinations)
57
+
58
+
59
+ START_DELIMITER = "<"
60
+ END_DELIMITER = ">"
61
+ DELIMITERS = {START_DELIMITER, END_DELIMITER}
62
+
63
+ OP_TYPE_MAP = {op_type.value: op_type for op_type in OpType}
64
+ OP_TYPE_COMBO_MAP = {i: op_types for i, op_types in enumerate(op_type_powerset())}
65
+ OP_TYPE_COMBO_MAP_INV = {v: k for k, v in OP_TYPE_COMBO_MAP.items()}
66
+
67
+ NUMERIC_TOKEN = r"\p{N}+([,.]\p{N}+)*(?=\s|$)"
68
+ STANDARD_TOKEN = r"[\p{L}\p{N}]+(['][\p{L}\p{N}]+)*'?"
69
+
70
+
71
+ def is_vowel(c: str) -> bool:
72
+ """Check if the normalized character is a vowel.
73
+
74
+ Args:
75
+ c (str): The character to check.
76
+
77
+ Returns:
78
+ bool: True if the character is a vowel, False otherwise.
79
+
80
+ """
81
+ assert len(c) == 1, "Input must be a single character."
82
+ return unidecode(c)[0] in "aeiouy"
83
+
84
+
85
+ def is_consonant(c: str) -> bool:
86
+ """Check if the normalized character is a consonant.
87
+
88
+ Args:
89
+ c (str): The character to check.
90
+
91
+ Returns:
92
+ bool: True if the character is a consonant, False otherwise.
93
+
94
+ """
95
+ assert len(c) == 1, "Input must be a single character."
96
+ return unidecode(c)[0] in "bcdfghjklmnpqrstvwxyz"
97
+
98
+
99
+ def categorize_char(c: str) -> int:
100
+ """Categorize a character as 'vowel', 'consonant', or 'unvoiced'.
101
+
102
+ Args:
103
+ c (str): The character to categorize.
104
+
105
+ Returns:
106
+ str: The category of the character.
107
+
108
+ """
109
+ if c in DELIMITERS:
110
+ return 0
111
+ if is_consonant(c):
112
+ return 1
113
+ if is_vowel(c):
114
+ return 2
115
+ return 3 # NOTE: Unvoiced characters (only apostrophes are expected by default).
116
+
117
+
118
+ def get_manhattan_distance(a: tuple[int, int], b: tuple[int, int]) -> int:
119
+ """Calculate the Manhattan distance between two points a and b."""
120
+ return abs(a[0] - b[0]) + abs(a[1] - b[1])
121
+
122
+
123
+ def basic_tokenizer(text: str) -> list:
124
+ """Default tokenizer that splits text into words based on whitespace.
125
+
126
+ Args:
127
+ text (str): The input text to tokenize.
128
+
129
+ Returns:
130
+ list: A list of tokens (words).
131
+
132
+ """
133
+ return list(re.finditer(rf"({NUMERIC_TOKEN})|({STANDARD_TOKEN})", text, re.UNICODE | re.VERBOSE))
134
+
135
+
136
+ def basic_normalizer(text: str) -> str:
137
+ """Default normalizer that only converts text to lowercase.
138
+
139
+ Args:
140
+ text (str): The input text to normalize.
141
+
142
+ Returns:
143
+ str: The normalized text.
144
+
145
+ """
146
+ return text.lower()
147
+
148
+
149
+ def ensure_length_preservation(normalizer: callable) -> callable:
150
+ """Decorator to ensure that the normalizer preserves the length of the input text.
151
+
152
+ Args:
153
+ normalizer (callable): The normalizer function to wrap.
154
+
155
+ Returns:
156
+ callable: The wrapped normalizer function that preserves length.
157
+
158
+ """
159
+
160
+ def wrapper(text: str, *args: list, **kwargs: dict) -> str:
161
+ normalized = normalizer(text, *args, **kwargs)
162
+ if len(normalized) != len(text):
163
+ raise ValueError("Normalizer must preserve length.")
164
+ return normalized
165
+
166
+ return wrapper