File size: 18,043 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Unit tests of r5eval core (hand-made cases with known answers). usage: python -I test_core.py
Exit code 0 only if every test passes; each test prints PASS or FAIL."""
import hashlib
import os
import random
import sys
import traceback

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "src"))
import numpy as np  # noqa: E402

from r5eval import analyse, frozen, lookalike, stats, textnorm  # noqa: E402
from r5eval.align import align_ops, lev_fast, min_cost_line_assignment, op_counts  # noqa: E402

RESULTS = []


def test(fn):
    try:
        fn()
        RESULTS.append((fn.__name__, True, ""))
        print("PASS", fn.__name__)
    except Exception:  # noqa: BLE001
        RESULTS.append((fn.__name__, False, traceback.format_exc()))
        print("FAIL", fn.__name__)
        print(traceback.format_exc())
    return fn


def close(a, b, tol=1e-9):
    return abs(a - b) <= tol


@test
def t_frozen_files_hash_checked():
    assert frozen.j2.norm("  a \n b ") == "a b"
    assert frozen.vlma_pp.fold("a'b") == "aʻb"
    p = os.path.join(HERE, "..", "src", "r5eval", "frozen", "scorelib_j2.py")
    assert hashlib.sha256(open(p, "rb").read()).hexdigest() == frozen.FROZEN_SHA256["scorelib_j2.py"]


@test
def t_align_tie_break_cases():
    assert align_ops("ab", "ba")[0] == 2 and op_counts(align_ops("ab", "ba")[1]) == (2, 0, 0)
    assert op_counts(align_ops("abc", "bcd")[1]) == (0, 1, 1)
    assert op_counts(align_ops("", "xy")[1]) == (0, 0, 2)
    assert op_counts(align_ops("ab", "b")[1]) == (0, 1, 0)       # deletion
    assert op_counts(align_ops("b", "ab")[1]) == (0, 0, 1)       # insertion
    d, ops = align_ops("қазақ", "казак")
    assert d == 2 and op_counts(ops) == (2, 0, 0)
    d, ops = align_ops("kitten", "sitting")
    assert d == 3 and op_counts(ops) == (2, 0, 1)


@test
def t_align_matches_j2_counts_on_random_pairs():
    random.seed(7)
    alphabet = "аәбвгғдеёжзийкқлмнңоөпрстуұүфхһцчшщъыіьэюяabc 1,."
    for _ in range(4000):
        a = "".join(random.choice(alphabet) for _ in range(random.randint(0, 14)))
        b = "".join(random.choice(alphabet) for _ in range(random.randint(0, 18)))
        d, ops = align_ops(a, b)
        dj, sj, dlj, ij = frozen.j2.align(a, b)
        assert d == dj and op_counts(ops) == (sj, dlj, ij), (a, b)
        # the operation list reproduces both strings
        ra = "".join(a[i] for o, i, j in ops if o in "MSD")
        rb = "".join(b[j] for o, i, j in ops if o in "MSI")
        assert ra == a and rb == b
        assert lev_fast(a, b) == d


@test
def t_lev_fast_long_strings_and_token_lists():
    random.seed(3)
    for _ in range(60):
        a = "".join(random.choice("abcdefg ") for _ in range(random.randint(100, 400)))
        b = "".join(random.choice("abcdefg ") for _ in range(random.randint(100, 400)))
        assert lev_fast(a, b) == align_ops(a, b)[0]
    assert lev_fast(["a", "b", "c"], ["a", "c"]) == 1
    assert lev_fast("", "") == 0 and lev_fast("abc", "") == 3 and lev_fast("", "abc") == 3


@test
def t_n0_n1_n2_n3():
    assert textnorm.norm(" й\n  и ") == "й и"
    assert textnorm.n1_key("Қазақ-123!", "kk") == "қазақ123"
    assert textnorm.n1_key("İSTANBUL", "tr") == "istanbul"
    assert textnorm.n1_key("ILIK", "tr") == "ılık"          # Turkic fold: I -> dotless i
    assert textnorm.n1_key("ILIK", "kk") == "ilik"
    assert textnorm.n1_key("Oʻzbek", "uz_latn") == "oʻzbek"   # U+02BB is a letter (Lm), kept
    assert textnorm.fold_lower("İSTANBUL ILIK", "tr") == "istanbul ılık"
    assert textnorm.fold_lower("İ", "kk") != "i"           # default Python lower(): two code points
    for ch in ["'", "‘", "’", "ʼ", "ʻ"]:
        assert textnorm.fold_apostrophes("o" + ch + "g") == "oʻg"
    assert textnorm.fold_apostrophes("abc") == "abc"


@test
def t_scripts():
    assert textnorm.other_script("oʻzbek") is False         # J2 other_script() flags this one (RESEVAL finding)
    assert textnorm.other_script("слово") is False and textnorm.other_script("word1") is False
    assert textnorm.other_script("слово字") is True and textnorm.other_script("كلمة") is True
    assert textnorm.is_mixed_script("кaзак") is True        # Latin a inside a Cyrillic word
    assert textnorm.is_mixed_script("казак") is False and textnorm.is_mixed_script("kazak") is False
    assert textnorm.is_mixed_script("123") is False and textnorm.is_mixed_script("а-б.") is False
    assert textnorm.is_mixed_script("Қазақстан") is False
    assert textnorm.latin_cyrillic_counts("кaзак") == (1, 4)


@test
def t_lookalike_table_and_repair():
    p = lookalike.table_path()
    assert open(p, encoding="utf-8").read() == lookalike.table_tsv()
    sha_line = open(p.replace(".tsv", ".sha256")).read().split()[0]
    assert hashlib.sha256(lookalike.table_tsv().encode("utf-8")).hexdigest() == sha_line
    assert lookalike.PARTNER["a"] == "а" and lookalike.PARTNER["а"] == "a"
    new, ch = lookalike.repair_label("кiтап", "Cyrl")        # Latin i inside a Cyrillic word
    assert new == "кітап" and ch == [("кiтап", "кітап")]
    new, ch = lookalike.repair_label("ISBN 5 кiтап", "Cyrl")   # Latin-only token untouched
    assert new == "ISBN 5 кітап"
    new, ch = lookalike.repair_label("мəтін", "Cyrl")          # Latin schwa inside a Cyrillic word
    assert new == "мәтін"
    new, ch = lookalike.repair_label("kaзak", "Latn")          # Cyrillic з in a Latin word (z is not a table pair): untouched
    assert new == "kaзak" and ch == []
    new, ch = lookalike.repair_label("kаzak", "Latn")          # Cyrillic а in a Latin word: repaired to Latin a
    assert new == "kazak"
    assert lookalike.repair_label("слово  слово", "Cyrl")[0] == "слово  слово"


def feats(ref, hyp, lang="kk", full=True):
    b, L, extra = analyse.crop_features(ref, hyp, lang, full=full)
    return b, L, extra


@test
def t_crop_features_basic_counts_and_hr():
    b, L, e = feats("слово", "слово слово слово слово слово")
    assert b["hr3_den"] == 1 and b["hr3_num"] == 1 and b["loop"] == 1 and b["n_ref"] == 1
    b, L, e = feats("1", "11")
    assert b.get("hr3_den", 0) == 0 and b["cer_sum"] == 1.0 and b["ins"] == 1
    b, L, e = feats("слово", "")
    assert b["empty_out"] == 1 and b["dist"] == 5 and b["del"] == 5 and b["cer_sum"] == 1.0
    b, L, e = feats("", "abc")                     # clutter crop: HR1 only
    assert b["hr1_den"] == 1 and b["hr1_num"] == 1 and "dist" not in b and "n_ref" not in b
    b, L, e = feats("", "")
    assert b["hr1_den"] == 1 and "hr1_num" not in b
    assert e is None


@test
def t_special_letters_and_collapse():
    b, L, e = feats("қазақ", "казак")
    assert L["sl|kk|қ|ref"] == 2 and L["sl|kk|қ|miss"] == 2 and L["sl|kk|қ|collapse"] == 2
    assert "sl|kk|қ|tp" not in L
    b, L, e = feats("қазақ", "қазақ")
    assert L["sl|kk|қ|tp"] == 2 and "sl|kk|қ|miss" not in L
    b, L, e = feats("кітап", "китап")                   # і -> и
    assert L["sl|kk|і|collapse"] == 1
    b, L, e = feats("жаз", "жаз", "kk")
    assert not L
    b, L, e = feats("мектеп", "мектеп", "kk")
    assert not any(k.endswith("|ref") for k in L)
    # false alarm: output writes a special letter where the reference has none
    b, L, e = feats("кат", "қат")
    assert L["sl|kk|қ|fp"] == 1


@test
def t_uzbek_latin_units_and_other_script():
    b, L, e = feats("oʻzbek", "ozbek", "uz_latn")
    assert L["sl|uz_latn|oʻ|ref"] == 1 and L["sl|uz_latn|oʻ|miss"] == 1 and L["sl|uz_latn|oʻ|collapse"] == 1
    assert "other_script_out" not in b
    b, L, e = feats("oʻzbek", "oʻzbek", "uz_latn")
    assert L["sl|uz_latn|oʻ|tp"] == 1
    b, L, e = feats("gʻoya", "goʻya", "uz_latn")      # oʻ written where the reference has o, gʻ lost
    assert L["sl|uz_latn|gʻ|miss"] == 1


@test
def t_case_diacritic_ifamily_turkish():
    b, L, e = feats("Işık", "ışık", "tr")             # I -> dotless i is a case error, not an i-family error
    assert b["case_err"] == 1 and b.get("ifam_sub", 0) == 0 and b["dist"] == 1
    b, L, e = feats("Işık", "işık", "tr")             # I -> i: i-family error, not case
    assert b.get("case_err", 0) == 0 and b["ifam_sub"] == 1
    b, L, e = feats("İstanbul", "Istanbul", "tr")      # dot lost: diacritic error (missing) and i-family error
    assert b["der_num"] == 1 and b["der_missing"] == 1 and b["ifam_sub"] == 1
    b, L, e = feats("çay", "cay", "tr")                # cedilla lost
    assert b["der_num"] == 1 and b["der_missing"] == 1 and L["sl|tr|ç|collapse"] == 1
    b, L, e = feats("cay", "çay", "tr")                # extra cedilla
    assert b["der_num"] == 1 and b["der_extra"] == 1 and b.get("der_missing", 0) == 0
    b, L, e = feats("Қазақ", "қазақ", "kk")           # case error on a special letter
    assert b["case_err"] == 1 and b["dist"] == 1
    # case-insensitive companions use the Turkic fold
    b, L, e = feats("IŞIK", "ışık", "tr")
    assert b["exact_cf"] == 1 and b["dist_cf"] == 0
    b, L, e = feats("IŞIK", "işik", "tr")
    assert b.get("exact_cf", 0) == 0


@test
def t_digits_punct_apostrophe_homoglyph():
    b, L, e = feats("4,5", "4.5")
    assert b["dig_ref"] == 2 and b.get("dig_miss", 0) == 0 and b["punct_ref"] == 1 and b["punct_miss"] == 1
    assert b["digrun_n"] == 1 and b.get("digrun_ok", 0) == 0
    b, L, e = feats("45", "45")
    assert b["digrun_n"] == 1 and b["digrun_ok"] == 1
    b, L, e = feats("12", "132")
    assert b["dig_ins"] == 1 and b["dig_ref"] == 2
    b, L, e = feats("дата 5", "дата")
    assert b["dig_miss"] == 1
    b, L, e = feats("o'g'li", "oʻgʻli", "uz_latn")
    assert b["apos_ref"] == 2 and b["apos_miss"] == 2
    b, L, e = feats("кітап", "кiтап")                  # Cyrillic і written as Latin i: homoglyph substitution and mixed token
    assert b["homoglyph_sub"] == 1 and b["mixed_hyp_tokens"] == 1 and b["hyp_tokens"] == 1
    b, L, e = feats("слово", "字词слово")
    assert b["other_script_out"] == 1


@test
def t_word_level_and_fabricated():
    b, L, e = feats("мен үйге бардым", "мен үйге бардым")
    assert b["wdist"] == 0 and b["ref_words"] == 3
    b, L, e = feats("мен үйге бардым", "мен бардым")
    assert b["wdist"] == 1 and b["wdel"] == 1
    b, L, e = feats("мен үйге бардым", "мен үйге бардым қаламсапқа")   # invented long word
    assert b["fab_words"] == 1 and b["wdist"] == 1
    b, L, e = feats("мен үйге бардым", "мен үйгэ бардым")             # near-miss word is not fabricated
    assert b.get("fab_words", 0) == 0 and b["wdist"] == 1


@test
def t_group_metrics_and_bootstrap_point_values():
    K = 3
    acc = analyse.Acc(K)
    rows = [("а", "а", 0), ("бв", "бг", 1), ("где", "гд", 1), ("жзик", "жзик", 2)]
    for rep in range(10):                        # 40 crops, so that no denominator is below the rare-event limit of 30
        for ref, hyp, k in rows:
            b, L, e = feats(ref, hyp)
            acc.add(["all"], k, b, L)
    idx, f = acc.dense("all")
    m = analyse.group_metrics(idx, f, K, B=500, compact=False)
    assert close(m["cer"]["value"], 2 / 10)          # distance 0+1+1+0 over reference length 1+2+3+4 (x10 each)
    assert close(m["exact_match"]["value"], 0.5)
    assert m["cer"]["lo"] is not None and m["cer"]["lo"] <= m["cer"]["value"] + 1e-12 <= m["cer"]["hi"] + 2e-12
    assert close(m["sub_rate"]["value"], 1 / 10) and close(m["del_rate"]["value"], 1 / 10)
    assert m["cer"]["num"] == 20 and m["cer"]["den"] == 100


@test
def t_bootstrap_is_deterministic_and_paired_arms_share_resamples():
    a = stats.boot_matmul(np.arange(5), np.arange(10, dtype=float).reshape(5, 2), 5, B=200)
    b = stats.boot_matmul(np.arange(5), np.arange(10, dtype=float).reshape(5, 2), 5, B=200)
    assert np.array_equal(a, b)
    # identical arms: the paired difference is exactly zero everywhere
    num = np.array([3.0, 5.0, 2.0, 8.0])
    den = np.array([40.0, 50.0, 30.0, 60.0])
    r = stats.paired_ratio_difference(num, den, num, den, B=500)
    assert r["d_rel"] == 0.0 and r["d_rel_ci95"] == [0.0, 0.0] and r["prob_improvement"] == 0.0
    # a clearly better system
    r = stats.paired_ratio_difference(num * 0.5, den, num, den, B=2000)
    assert close(r["d_rel"], -0.5) and r["d_rel_ci95"][1] < 0 and r["p_better"] < 0.01 and r["prob_improvement"] == 1.0


@test
def t_holm_known_example():
    h = stats.holm_adjust({"a": 0.01, "b": 0.04, "c": 0.03, "d": 0.02}, 0.05)
    assert h["a"]["reject"] is True and h["a"]["threshold"] == 0.05 / 4
    assert h["d"]["reject"] is False        # 0.02 > 0.05/3: Holm stops here
    assert h["c"]["reject"] is False and h["b"]["reject"] is False
    h = stats.holm_adjust({"a": 0.001, "b": 0.012, "c": 0.02}, 0.05)
    assert all(h[k]["reject"] for k in "abc")         # 0.001<=.05/3, 0.012<=.05/2, 0.02<=.05/1
    assert stats.holm_adjust({"a": 0.2}, 0.05)["a"]["reject"] is False


@test
def t_ece_and_risk_coverage():
    conf = [0.9] * 1500
    correct = [1, 0] * 750             # every one of the 15 equal-mass bins holds an alternating run: accuracy 0.5, confidence 0.9
    assert close(stats.ece_equal_mass(conf, correct), 0.4)
    assert close(stats.ece_equal_width(conf, correct), 0.4)
    assert close(stats.ece_equal_mass([1.0] * 4, [1, 1, 1, 1]), 0.0)
    # perfectly ordered confidence: risk rises with coverage
    conf = np.linspace(0.99, 0.01, 100)
    dist = np.zeros(100)
    dist[80:] = 3.0
    reflen = np.full(100, 5.0)
    risk, aurc = stats.risk_coverage(conf, dist, reflen)
    assert risk[0] == 0.0 and risk[15] == 0.0 and risk[-1] > risk[15] and close(risk[-1], dist.sum() / reflen.sum())
    assert np.all(np.diff(risk) >= -1e-12)
    # an uninformative ordering gives a flat curve at the overall CER
    rng = np.random.default_rng(1)
    conf = rng.random(2000)
    dist = rng.integers(0, 2, 2000).astype(float)
    risk, aurc = stats.risk_coverage(conf, dist, np.ones(2000))
    assert abs(risk[-1] - dist.mean()) < 1e-9 and abs(risk[5] - dist.mean()) < 0.06


@test
def t_quantile_ci_and_rare_event_rule():
    v = np.arange(100, dtype=float) / 100.0
    cl = np.arange(100) % 10
    q = stats.quantiles_ci(v, cl, 10, qs=(0.5, 0.9), B=300, chunk=100)
    assert close(q["q0.5"]["value"], np.quantile(v, 0.5)) and q["q0.5"]["lo"] <= q["q0.5"]["hi"]
    assert stats.rare_event(3, 29) is True and stats.rare_event(3, 30) is False
    K = 2
    acc = analyse.Acc(K)
    for k in (0, 1):
        b, L, e = feats("a", "b")
        acc.add(["all"], k, b, L)
    idx, f = acc.dense("all")
    m = analyse.group_metrics(idx, f, K, B=100)
    assert m["cer"]["rare"] is True and m["cer"]["value"] is None and m["cer"]["num"] == 2.0 and m["cer"]["den"] == 2.0


@test
def t_paper_metrics_n4_and_n5_match_the_reference_checks():
    # RESEVAL work/eval_reference_checks_out.txt: on these four pairs the HTR-Flor style CER is 0.2394 and the HKR 'CER Lev' 24.75 percent
    toy = [("Қазақ", "қазак"), ("ab", "abcdef"), ("тіл", "тіл"), ("Шёл человек", "Шел человек")]
    n4 = n5 = ser = 0.0
    for r, h in toy:
        b, L, e = feats(r, h)
        n4 += b.get("n4_cer_sum", 0.0)
        n5 += b.get("n5_cerlev_sum", 0.0)
        ser += b.get("n4_ser", 0)
    assert abs(n4 / 4 - 0.2394) < 5e-5, n4 / 4
    assert abs(n5 / 4 - 24.75) < 1e-9, n5 / 4
    assert ser == 3           # three of the four pairs still differ after lower-casing (қ/к, ab/abcdef, ё/е)


@test
def t_scoring_hash_ignores_reporting_modules():
    """A change of the report cards, the verdict, the selection or the summary must not force a re-score; a change of a scoring module must."""
    import importlib
    import shutil
    import tempfile
    d = tempfile.mkdtemp(prefix="r5eval_hash_")
    shutil.copytree(os.path.join(HERE, "..", "src", "r5eval"), os.path.join(d, "r5eval"), ignore=shutil.ignore_patterns("__pycache__"))
    sys.path.insert(0, d)
    saved = {k: v for k, v in sys.modules.items() if k == "r5eval" or k.startswith("r5eval.")}
    for k in saved:
        del sys.modules[k]
    try:
        pkg = importlib.import_module("r5eval")
        a, b = pkg.code_sha256(), pkg.report_code_sha256()
        with open(os.path.join(d, "r5eval", "cards.py"), "a") as f:
            f.write("\n# a change in a reporting module\n")
        with open(os.path.join(d, "r5eval", "verdictlib.py"), "a") as f:
            f.write("\n# another one\n")
        assert pkg.code_sha256() == a and pkg.report_code_sha256() != b
        with open(os.path.join(d, "r5eval", "align.py"), "a") as f:
            f.write("\n# a change in a scoring module\n")
        assert pkg.code_sha256() != a
    finally:
        sys.path.remove(d)
        for k in [k for k in sys.modules if k == "r5eval" or k.startswith("r5eval.")]:
            del sys.modules[k]
        sys.modules.update(saved)
        shutil.rmtree(d, ignore_errors=True)


@test
def t_min_cost_line_assignment_m29():
    cost, pairs = min_cost_line_assignment(["аб", "вг"], ["вг", "аб"])
    assert cost == 0 and sorted(pairs) == [(0, 1), (1, 0)]
    cost, pairs = min_cost_line_assignment(["аб", "вг"], ["вг", "аб", "xyz"])      # an invented line is charged in full
    assert cost == 3
    cost, pairs = min_cost_line_assignment(["аб", "вг"], ["абвг"])                  # merged lines are charged
    assert cost == 4
    cost, pairs = min_cost_line_assignment(["аб", "вг"], [])
    assert cost == 4
    cost, pairs = min_cost_line_assignment([], ["abc"])
    assert cost == 3


if __name__ == "__main__":
    bad = [r for r in RESULTS if not r[1]]
    print("tests: %d passed, %d failed" % (len(RESULTS) - len(bad), len(bad)))
    sys.exit(1 if bad else 0)