-
Notifications
You must be signed in to change notification settings - Fork 387
/
ter.py
600 lines (479 loc) · 22.8 KB
/
ter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# referenced from
# Library Name: torchtext
# Authors: torchtext authors
# Date: 2021-11-30
# Link:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2020 Memsource
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from functools import lru_cache
from typing import Dict, Iterator, List, Optional, Sequence, Tuple, Type, Union
from torch import Tensor, tensor
from torchmetrics.functional.text.helper import (
_flip_trace,
_LevenshteinEditDistance,
_trace_to_alignment,
_validate_inputs,
)
# Tercom-inspired limits
_MAX_SHIFT_SIZE = 10
_MAX_SHIFT_DIST = 50
# Sacrebleu-inspired limits
_MAX_SHIFT_CANDIDATES = 1000
class _TercomTokenizer:
"""Re-implementation of Tercom Tokenizer in Python 3.
See src/ter/core/Normalizer.java in https://github.com/jhclark/tercom Note that Python doesn't support named Unicode
blocks so the mapping for relevant blocks was taken from here: https://unicode-table.com/en/blocks/
This implementation follows the implementation from
https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/tokenizers/tokenizer_ter.py.
"""
_ASIAN_PUNCTUATION = r"([\u3001\u3002\u3008-\u3011\u3014-\u301f\uff61-\uff65\u30fb])"
_FULL_WIDTH_PUNCTUATION = r"([\uff0e\uff0c\uff1f\uff1a\uff1b\uff01\uff02\uff08\uff09])"
def __init__(
self,
normalize: bool = False,
no_punctuation: bool = False,
lowercase: bool = True,
asian_support: bool = False,
) -> None:
"""Initialize the tokenizer.
Args:
normalize: An indication whether a general tokenization to be applied.
no_punctuation: An indication whteher a punctuation to be removed from the sentences.
lowercase: An indication whether to enable case-insensitivity.
asian_support: An indication whether asian characters to be processed.
"""
self.normalize = normalize
self.no_punctuation = no_punctuation
self.lowercase = lowercase
self.asian_support = asian_support
@lru_cache(maxsize=2**16) # noqa: B019
def __call__(self, sentence: str) -> str:
"""Apply a different tokenization techniques according.
Args:
sentence: An input sentence to pre-process and tokenize.
Return:
A tokenized and pre-processed sentence.
"""
if not sentence:
return ""
if self.lowercase:
sentence = sentence.lower()
if self.normalize:
sentence = self._normalize_general_and_western(sentence)
if self.asian_support:
sentence = self._normalize_asian(sentence)
if self.no_punctuation:
sentence = self._remove_punct(sentence)
if self.asian_support:
sentence = self._remove_asian_punct(sentence)
# Strip extra whitespaces
return " ".join(sentence.split())
@staticmethod
def _normalize_general_and_western(sentence: str) -> str:
"""Apply a language-independent (general) tokenization."""
sentence = f" {sentence} "
rules = [
(r"\n-", ""),
# join lines
(r"\n", " "),
# handle XML escaped symbols
(r""", '"'),
(r"&", "&"),
(r"<", "<"),
(r">", ">"),
# tokenize punctuation
(r"([{-~[-` -&(-+:-@/])", r" \1 "),
# handle possessive
(r"'s ", r" 's "),
(r"'s$", r" 's"),
# tokenize period and comma unless preceded by a digit
(r"([^0-9])([\.,])", r"\1 \2 "),
# tokenize period and comma unless followed by a digit
(r"([\.,])([^0-9])", r" \1 \2"),
# tokenize dash when preceded by a digit
(r"([0-9])(-)", r"\1 \2 "),
]
for pattern, replacement in rules:
sentence = re.sub(pattern, replacement, sentence)
return sentence
@classmethod
def _normalize_asian(cls: Type["_TercomTokenizer"], sentence: str) -> str:
"""Split Chinese chars and Japanese kanji down to character level."""
# 4E00—9FFF CJK Unified Ideographs
# 3400—4DBF CJK Unified Ideographs Extension A
sentence = re.sub(r"([\u4e00-\u9fff\u3400-\u4dbf])", r" \1 ", sentence)
# 31C0—31EF CJK Strokes
# 2E80—2EFF CJK Radicals Supplement
sentence = re.sub(r"([\u31c0-\u31ef\u2e80-\u2eff])", r" \1 ", sentence)
# 3300—33FF CJK Compatibility
# F900—FAFF CJK Compatibility Ideographs
# FE30—FE4F CJK Compatibility Forms
sentence = re.sub(r"([\u3300-\u33ff\uf900-\ufaff\ufe30-\ufe4f])", r" \1 ", sentence)
# 3200—32FF Enclosed CJK Letters and Months
sentence = re.sub(r"([\u3200-\u3f22])", r" \1 ", sentence)
# Split Hiragana, Katakana, and KatakanaPhoneticExtensions
# only when adjacent to something else
# 3040—309F Hiragana
# 30A0—30FF Katakana
# 31F0—31FF Katakana Phonetic Extensions
sentence = re.sub(r"(^|^[\u3040-\u309f])([\u3040-\u309f]+)(?=$|^[\u3040-\u309f])", r"\1 \2 ", sentence)
sentence = re.sub(r"(^|^[\u30a0-\u30ff])([\u30a0-\u30ff]+)(?=$|^[\u30a0-\u30ff])", r"\1 \2 ", sentence)
sentence = re.sub(r"(^|^[\u31f0-\u31ff])([\u31f0-\u31ff]+)(?=$|^[\u31f0-\u31ff])", r"\1 \2 ", sentence)
sentence = re.sub(cls._ASIAN_PUNCTUATION, r" \1 ", sentence)
return re.sub(cls._FULL_WIDTH_PUNCTUATION, r" \1 ", sentence)
@staticmethod
def _remove_punct(sentence: str) -> str:
"""Remove punctuation from an input sentence string."""
return re.sub(r"[\.,\?:;!\"\(\)]", "", sentence)
@classmethod
def _remove_asian_punct(cls: Type["_TercomTokenizer"], sentence: str) -> str:
"""Remove asian punctuation from an input sentence string."""
sentence = re.sub(cls._ASIAN_PUNCTUATION, r"", sentence)
return re.sub(cls._FULL_WIDTH_PUNCTUATION, r"", sentence)
def _preprocess_sentence(sentence: str, tokenizer: _TercomTokenizer) -> str:
"""Given a sentence, apply tokenization.
Args:
sentence: The input sentence string.
tokenizer: An instance of ``_TercomTokenizer`` handling a sentence tokenization.
Return:
The pre-processed output sentence string.
"""
return tokenizer(sentence.rstrip())
def _find_shifted_pairs(pred_words: List[str], target_words: List[str]) -> Iterator[Tuple[int, int, int]]:
"""Find matching word sub-sequences in two lists of words. Ignores sub- sequences starting at the same position.
Args:
pred_words: A list of a tokenized hypothesis sentence.
target_words: A list of a tokenized reference sentence.
Return:
Yields tuples of ``target_start, pred_start, length`` such that:
``target_words[target_start : target_start + length] == pred_words[pred_start : pred_start + length]``
pred_start:
A list of hypothesis start indices.
target_start:
A list of reference start indices.
length:
A length of a word span to be considered.
"""
for pred_start in range(len(pred_words)):
for target_start in range(len(target_words)):
# this is slightly different from what tercom does but this should
# really only kick in in degenerate cases
if abs(target_start - pred_start) > _MAX_SHIFT_DIST:
continue
for length in range(1, _MAX_SHIFT_SIZE):
# Check if hypothesis and reference are equal so far
if pred_words[pred_start + length - 1] != target_words[target_start + length - 1]:
break
yield pred_start, target_start, length
# Stop processing once a sequence is consumed.
_hyp = len(pred_words) == pred_start + length
_ref = len(target_words) == target_start + length
if _hyp or _ref:
break
def _handle_corner_cases_during_shifting(
alignments: Dict[int, int],
pred_errors: List[int],
target_errors: List[int],
pred_start: int,
target_start: int,
length: int,
) -> bool:
"""Return ``True`` if any of corner cases has been met. Otherwise, ``False`` is returned.
Args:
alignments: A dictionary mapping aligned positions between a reference and a hypothesis.
pred_errors: A list of error positions in a hypothesis.
target_errors: A list of error positions in a reference.
pred_start: A hypothesis start index.
target_start: A reference start index.
length: A length of a word span to be considered.
Return:
An indication whether any of conrner cases has been met.
"""
# don't do the shift unless both the hypothesis was wrong and the
# reference doesn't match hypothesis at the target position
if sum(pred_errors[pred_start : pred_start + length]) == 0:
return True
if sum(target_errors[target_start : target_start + length]) == 0:
return True
# don't try to shift within the subsequence
if pred_start <= alignments[target_start] < pred_start + length:
return True
return False
def _perform_shift(words: List[str], start: int, length: int, target: int) -> List[str]:
"""Perform a shift in ``words`` from ``start`` to ``target``.
Args:
words: A words to shift.
start: An index where to start shifting from.
length: A number of how many words to be considered.
target: An index where to end shifting.
Return:
A list of shifted words.
"""
def _shift_word_before_previous_position(words: List[str], start: int, target: int, length: int) -> List[str]:
return words[:target] + words[start : start + length] + words[target:start] + words[start + length :]
def _shift_word_after_previous_position(words: List[str], start: int, target: int, length: int) -> List[str]:
return words[:start] + words[start + length : target] + words[start : start + length] + words[target:]
def _shift_word_within_shifted_string(words: List[str], start: int, target: int, length: int) -> List[str]:
shifted_words = words[:start]
shifted_words += words[start + length : length + target]
shifted_words += words[start : start + length]
shifted_words += words[length + target :]
return shifted_words
if target < start:
return _shift_word_before_previous_position(words, start, target, length)
if target > start + length:
return _shift_word_after_previous_position(words, start, target, length)
return _shift_word_within_shifted_string(words, start, target, length)
def _shift_words(
pred_words: List[str],
target_words: List[str],
cached_edit_distance: _LevenshteinEditDistance,
checked_candidates: int,
) -> Tuple[int, List[str], int]:
"""Attempt to shift words to match a hypothesis with a reference.
It returns the lowest number of required edits between a hypothesis and a provided reference, a list of shifted
words and number of checked candidates. Note that the filtering of possible shifts and shift selection are heavily
based on somewhat arbitrary heuristics. The code here follows as closely as possible the logic in Tercom, not
always justifying the particular design choices.
The paragraph copied from https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/lib_ter.py.
Args:
pred_words: A list of tokenized hypothesis sentence.
target_words: A list of lists of tokenized reference sentences.
cached_edit_distance: A pre-computed edit distance between a hypothesis and a reference.
checked_candidates: A number of checked hypothesis candidates to match a provided reference.
Return:
best_score:
The best (lowest) number of required edits to match hypothesis and reference sentences.
shifted_words:
A list of shifted words in hypothesis sentences.
checked_candidates:
A number of checked hypothesis candidates to match a provided reference.
"""
edit_distance, inverted_trace = cached_edit_distance(pred_words)
trace = _flip_trace(inverted_trace)
alignments, target_errors, pred_errors = _trace_to_alignment(trace)
best: Optional[Tuple[int, int, int, int, List[str]]] = None
for pred_start, target_start, length in _find_shifted_pairs(pred_words, target_words):
if _handle_corner_cases_during_shifting(
alignments, pred_errors, target_errors, pred_start, target_start, length
):
continue
prev_idx = -1
for offset in range(-1, length):
if target_start + offset == -1:
idx = 0
elif target_start + offset in alignments:
idx = alignments[target_start + offset] + 1
# offset is out of bounds => aims past reference
else:
break
# Skip idx if already tried
if idx == prev_idx:
continue
prev_idx = idx
shifted_words = _perform_shift(pred_words, pred_start, length, idx)
# Elements of the tuple are designed to replicate Tercom ranking of shifts:
candidate = (
edit_distance - cached_edit_distance(shifted_words)[0], # highest score first
length, # then, longest match first
-pred_start, # then, earliest match first
-idx, # then, earliest target position first
shifted_words,
)
checked_candidates += 1
if not best or candidate > best:
best = candidate
if checked_candidates >= _MAX_SHIFT_CANDIDATES:
break
if not best:
return 0, pred_words, checked_candidates
best_score, _, _, _, shifted_words = best
return best_score, shifted_words, checked_candidates
def _translation_edit_rate(pred_words: List[str], target_words: List[str]) -> Tensor:
"""Compute translation edit rate between hypothesis and reference sentences.
Args:
pred_words: A list of a tokenized hypothesis sentence.
target_words: A list of lists of tokenized reference sentences.
Return:
A number of required edits to match hypothesis and reference sentences.
"""
if len(target_words) == 0:
return tensor(0.0)
cached_edit_distance = _LevenshteinEditDistance(target_words)
num_shifts = 0
checked_candidates = 0
input_words = pred_words
while True:
# do shifts until they stop reducing the edit distance
delta, new_input_words, checked_candidates = _shift_words(
input_words, target_words, cached_edit_distance, checked_candidates
)
if checked_candidates >= _MAX_SHIFT_CANDIDATES or delta <= 0:
break
num_shifts += 1
input_words = new_input_words
edit_distance, _ = cached_edit_distance(input_words)
total_edits = num_shifts + edit_distance
return tensor(total_edits)
def _compute_sentence_statistics(pred_words: List[str], target_words: List[List[str]]) -> Tuple[Tensor, Tensor]:
"""Compute sentence TER statistics between hypothesis and provided references.
Args:
pred_words: A list of tokenized hypothesis sentence.
target_words: A list of lists of tokenized reference sentences.
Return:
best_num_edits:
The best (lowest) number of required edits to match hypothesis and reference sentences.
avg_tgt_len:
Average length of tokenized reference sentences.
"""
tgt_lengths = tensor(0.0)
best_num_edits = tensor(2e16)
for tgt_words in target_words:
num_edits = _translation_edit_rate(tgt_words, pred_words)
tgt_lengths += len(tgt_words)
if num_edits < best_num_edits:
best_num_edits = num_edits
avg_tgt_len = tgt_lengths / len(target_words)
return best_num_edits, avg_tgt_len
def _compute_ter_score_from_statistics(num_edits: Tensor, tgt_length: Tensor) -> Tensor:
"""Compute TER score based on pre-computed a number of edits and an average reference length.
Args:
num_edits: A number of required edits to match hypothesis and reference sentences.
tgt_length: An average length of reference sentences.
Return:
A corpus-level TER score or 1 if reference_length == 0.
"""
if tgt_length > 0 and num_edits > 0:
return num_edits / tgt_length
if tgt_length == 0 and num_edits > 0:
return tensor(1.0)
return tensor(0.0)
def _ter_update(
preds: Union[str, Sequence[str]],
target: Sequence[Union[str, Sequence[str]]],
tokenizer: _TercomTokenizer,
total_num_edits: Tensor,
total_tgt_length: Tensor,
sentence_ter: Optional[List[Tensor]] = None,
) -> Tuple[Tensor, Tensor, Optional[List[Tensor]]]:
"""Update TER statistics.
Args:
preds: An iterable of hypothesis corpus.
target: An iterable of iterables of reference corpus.
tokenizer: An instance of ``_TercomTokenizer`` handling a sentence tokenization.
total_num_edits: A total number of required edits to match hypothesis and reference sentences.
total_tgt_length: A total average length of reference sentences.
sentence_ter: A list of sentence-level TER values
Return:
total_num_edits:
A total number of required edits to match hypothesis and reference sentences.
total_tgt_length:
A total average length of reference sentences.
sentence_ter:
(Optionally) A list of sentence-level TER.
Raises:
ValueError:
If length of ``preds`` and ``target`` differs.
"""
target, preds = _validate_inputs(target, preds)
for pred, tgt in zip(preds, target):
tgt_words_: List[List[str]] = [_preprocess_sentence(_tgt, tokenizer).split() for _tgt in tgt]
pred_words_: List[str] = _preprocess_sentence(pred, tokenizer).split()
num_edits, tgt_length = _compute_sentence_statistics(pred_words_, tgt_words_)
total_num_edits += num_edits
total_tgt_length += tgt_length
if sentence_ter is not None:
sentence_ter.append(_compute_ter_score_from_statistics(num_edits, tgt_length).unsqueeze(0))
return total_num_edits, total_tgt_length, sentence_ter
def _ter_compute(total_num_edits: Tensor, total_tgt_length: Tensor) -> Tensor:
"""Compute TER based on pre-computed a total number of edits and a total average reference length.
Args:
total_num_edits: A total number of required edits to match hypothesis and reference sentences.
total_tgt_length: A total average length of reference sentences.
Return:
A corpus-level TER score.
"""
return _compute_ter_score_from_statistics(total_num_edits, total_tgt_length)
def translation_edit_rate(
preds: Union[str, Sequence[str]],
target: Sequence[Union[str, Sequence[str]]],
normalize: bool = False,
no_punctuation: bool = False,
lowercase: bool = True,
asian_support: bool = False,
return_sentence_level_score: bool = False,
) -> Union[Tensor, Tuple[Tensor, List[Tensor]]]:
"""Calculate Translation edit rate (`TER`_) of machine translated text with one or more references.
This implementation follows the implementations from
https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/ter.py. The `sacrebleu` implementation is a
near-exact reimplementation of the Tercom algorithm, produces identical results on all "sane" outputs.
Args:
preds: An iterable of hypothesis corpus.
target: An iterable of iterables of reference corpus.
normalize: An indication whether a general tokenization to be applied.
no_punctuation: An indication whteher a punctuation to be removed from the sentences.
lowercase: An indication whether to enable case-insensitivity.
asian_support: An indication whether asian characters to be processed.
return_sentence_level_score: An indication whether a sentence-level TER to be returned.
Return:
A corpus-level translation edit rate (TER).
(Optionally) A list of sentence-level translation_edit_rate (TER) if `return_sentence_level_score=True`.
Example:
>>> preds = ['the cat is on the mat']
>>> target = [['there is a cat on the mat', 'a cat is on the mat']]
>>> translation_edit_rate(preds, target)
tensor(0.1538)
References:
[1] A Study of Translation Edit Rate with Targeted Human Annotation
by Mathew Snover, Bonnie Dorr, Richard Schwartz, Linnea Micciulla and John Makhoul `TER`_
"""
if not isinstance(normalize, bool):
raise ValueError(f"Expected argument `normalize` to be of type boolean but got {normalize}.")
if not isinstance(no_punctuation, bool):
raise ValueError(f"Expected argument `no_punctuation` to be of type boolean but got {no_punctuation}.")
if not isinstance(lowercase, bool):
raise ValueError(f"Expected argument `lowercase` to be of type boolean but got {lowercase}.")
if not isinstance(asian_support, bool):
raise ValueError(f"Expected argument `asian_support` to be of type boolean but got {asian_support}.")
tokenizer: _TercomTokenizer = _TercomTokenizer(normalize, no_punctuation, lowercase, asian_support)
total_num_edits = tensor(0.0)
total_tgt_length = tensor(0.0)
sentence_ter: Optional[List[Tensor]] = [] if return_sentence_level_score else None
total_num_edits, total_tgt_length, sentence_ter = _ter_update(
preds,
target,
tokenizer,
total_num_edits,
total_tgt_length,
sentence_ter,
)
ter_score = _ter_compute(total_num_edits, total_tgt_length)
if sentence_ter:
return ter_score, sentence_ter
return ter_score