File size: 6,009 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
"""Scoring library for the J2 screen. Frozen before any model output exists (sha256 in scoring.txt).

Own edit-distance code (no package): the design's HR2 needs an alignment with a stated tie-break, which
no package gives. Tested in test_scorelib.py.
Design keys followed: decision_rule_v3.txt rule 0.3 (strip, remove wrappers, NFC, CER definition), section 1
(CER = summed edit distances / summed reference lengths), section 2 (HR1-HR4), j11_v3_design.json
screen.stage_1_zero_shot (Z cut off at 1.0).
"""
import re
import unicodedata

_WS = re.compile(r"\s+")
_TAG = re.compile(r"</?[a-z][a-z0-9_]*>")            # <text>, </text>, <loc_123>, <br>
_SPECIAL = re.compile(r"<\|[^>|]*\|>")                 # <|im_end|> style leftovers
_FENCE = re.compile(r"^```[a-zA-Z0-9_-]*\s*$", re.M)  # markdown code fence lines
_LOOP = re.compile(r"(.{4,}?)\1{2,}", re.S)
_HEADING = re.compile(r"^[ \t]*#{1,6}[ \t]+", re.M)            # markdown heading marker at a line start
_LATEX_TEXT = re.compile(r"\$\\text\{([^{}]*)\}\$")            # $\text{word}$ -> word
_CJK_PREAMBLE = re.compile(r"^\s*[一-鿿][^\n::]{0,60}[::]")  # chat preamble such as "图片中的文本内容是:"


def strip_wrappers(text):
    """The one post-processing step for model output (identical for all models).
    Amendment 2026-11-20 (before the screen, after the 5-crop smoke test): heading markers and a leading CJK
    preamble clause ending in a colon are also removed (seen in the smoke outputs of OvisOCR2 and HunyuanOCR), and a
    whole-text $\\text{...}$ unwrapping (LightOnOCR-3-0.8B smoke output). Only markup without content of its own."""
    t = _FENCE.sub("", text)
    t = _SPECIAL.sub("", t)
    t = _TAG.sub("", t)
    t = _CJK_PREAMBLE.sub("", t)
    t = _HEADING.sub("", t)
    t = _LATEX_TEXT.sub(r"\1", t)
    return t


def norm(text):
    """NFC, whitespace runs (incl. newlines) to one space, strip. Case is kept."""
    return _WS.sub(" ", unicodedata.normalize("NFC", text)).strip()


def prep_output(raw):
    return norm(strip_wrappers(raw))


def prep_ref(label):
    return norm(label)


def align(ref, hyp):
    """Edit distance and operation counts. Backtrace from the end; at a tie the order of preference is
    substitution (or match), then deletion (a reference character missing), then insertion."""
    n, m = len(ref), len(hyp)
    prev = list(range(m + 1))
    rows = [prev]
    for i in range(1, n + 1):
        cur = [i] + [0] * m
        ri = ref[i - 1]
        for j in range(1, m + 1):
            cost = 0 if ri == hyp[j - 1] else 1
            cur[j] = min(prev[j - 1] + cost, prev[j] + 1, cur[j - 1] + 1)
        rows.append(cur)
        prev = cur
    dist = rows[n][m]
    i, j = n, m
    sub = dele = ins = 0
    while i > 0 or j > 0:
        if i > 0 and j > 0 and rows[i][j] == rows[i - 1][j - 1] + (0 if ref[i - 1] == hyp[j - 1] else 1):
            if ref[i - 1] != hyp[j - 1]:
                sub += 1
            i -= 1
            j -= 1
        elif i > 0 and rows[i][j] == rows[i - 1][j] + 1:
            dele += 1
            i -= 1
        else:
            ins += 1
            j -= 1
    assert sub + dele + ins == dist
    return dist, sub, dele, ins


def has_loop(ref, hyp):
    """HR4: a block of 4 or more characters repeated 3 or more times in a row that the reference does not contain.
    Reading: the whole repeated run (block x repeats) must not occur in the reference."""
    for m in _LOOP.finditer(hyp):
        if m.group(0) not in ref:
            return True
    return False


def scripts_of(text):
    out = set()
    for ch in text:
        if unicodedata.category(ch).startswith("L"):
            try:
                out.add(unicodedata.name(ch).split()[0])
            except ValueError:
                out.add("UNKNOWN")
    return out


def other_script(text):
    """Not in the design: output has a letter that is neither Cyrillic nor Latin."""
    return bool(scripts_of(text) - {"CYRILLIC", "LATIN"})


def score_crop(ref_raw, out_raw):
    ref = prep_ref(ref_raw)
    hyp = prep_output(out_raw)
    dist, sub, dele, ins = align(ref, hyp)
    rl = len(ref)
    cer = dist / rl if rl else float(len(hyp) > 0)
    dist_cf, _, _, _ = align(ref.casefold(), hyp.casefold())
    return {
        "ref": ref, "hyp": hyp, "ref_len": rl, "hyp_len": len(hyp), "dist": dist, "sub": sub, "del": dele,
        "ins": ins, "cer": cer, "dist_cf": dist_cf, "exact": hyp == ref, "exact_cf": hyp.casefold() == ref.casefold(),
        "empty": hyp == "", "loop": has_loop(ref, hyp), "other_script": other_script(hyp),
        "ref_other_script": other_script(ref),
        "hr3": (rl >= 5) and ((len(hyp) > rl + max(4, 0.5 * rl)) or cer > 1.0),
        "ref_ge5": rl >= 5,
    }


def aggregate(scored):
    n = len(scored)
    if n == 0:
        return {}
    tot_ref = sum(s["ref_len"] for s in scored)
    pooled = sum(s["dist"] for s in scored) / tot_ref
    ge5 = [s for s in scored if s["ref_ge5"]]
    return {
        "crops": n,
        "cer_mean": sum(s["cer"] for s in scored) / n,
        "cer_mean_cap1": sum(min(s["cer"], 1.0) for s in scored) / n,
        "cer_pooled": pooled,
        "z_term_pooled_cap1": min(pooled, 1.0),
        "cer_pooled_casefold": sum(s["dist_cf"] for s in scored) / tot_ref,
        "exact": sum(s["exact"] for s in scored) / n,
        "exact_casefold": sum(s["exact_cf"] for s in scored) / n,
        "hr2_ins_per_ref_char": sum(s["ins"] for s in scored) / tot_ref,
        "sub_per_ref_char": sum(s["sub"] for s in scored) / tot_ref,
        "del_per_ref_char": sum(s["del"] for s in scored) / tot_ref,
        "hr3_share_refs_ge5": (sum(s["hr3"] for s in ge5) / len(ge5)) if ge5 else float("nan"),
        "refs_ge5": len(ge5),
        "hr4_loop_share": sum(s["loop"] for s in scored) / n,
        "empty_share": sum(s["empty"] for s in scored) / n,
        "other_script_share": sum(s["other_script"] for s in scored) / n,
        "ref_other_script_share": sum(s["ref_other_script"] for s in scored) / n,
    }