"""R5 VLMA: the fixed post-processing script and the scoring definitions for the VLM arms. Written 2026-11-20 ~22:15 UTC, before any fine-tuned model of any arm exists; sha256 and UTC time are recorded in records/R5/VLMA/postproc.sha256 (and DATA/outputs/r5/vlma/postproc.sha256). It is not changed after any result exists. Two figures per validation set (amendment 3.2 C10; decisions use the PLAIN greedy figure, rule 0.3): - PLAIN: reference and output are each normalised by norm(): Unicode NFC, every run of whitespace (newlines included) becomes one space, outer whitespace stripped. Nothing else; case and punctuation kept. - POST-PROCESSED: output = fold(norm(strip_wrappers(raw output))), reference = fold(norm(reference)). strip_wrappers removes, in this order: markdown code-fence lines (```lang), chat special-token leftovers (<|...|>), HTML/XML/DocTags tags with or without attributes (, , , ,
), HTML entities are unescaped (& -> &), markdown heading markers at a line start, a whole-text bold/italic wrapper (**x**, __x__, *x*, _x_), a whole-text LaTeX $\\text{x}$ wrapper, and a leading CJK preamble clause that ends in a colon (seen in zero-shot HunyuanOCR output). These are the J2 rules (CODE/scripts/j2/scorelib.py strip_wrappers) plus the attribute-tag, entity and emphasis cases. fold = apostrophe folding of version 3 section 1 (endpoint N): U+0027, U+2018, U+2019, U+02BC, U+02BB -> U+02BB, in reference and output; no other folding. - CER = sum over items of the character edit distance (Levenshtein, unit costs) / sum of reference characters (pooled). - WER = sum of word edit distances / sum of reference words; words = maximal runs of non-space characters after the normalisation of the figure. - Items with an empty reference (clutter) add their output length to the edit sum and nothing to the reference sum; they are also counted separately (empty_ref_items, empty_ref_nonempty_output). - exact = share of items whose normalised output equals the normalised reference. """ import html import re import unicodedata _WS = re.compile(r"\s+") _FENCE = re.compile(r"^[ \t]*```[A-Za-z0-9_+-]*[ \t]*$", re.M) _SPECIAL = re.compile(r"<\|[^>|]*\|>") _TAG = re.compile(r"]*)?/?>") _HEADING = re.compile(r"^[ \t]*#{1,6}[ \t]+", re.M) _LATEX_TEXT = re.compile(r"^\s*\$\\text\{([^{}]*)\}\$\s*$") _EMPH = re.compile(r"^\s*(\*\*|__|\*|_)(.+?)\1\s*$", re.S) _CJK_PREAMBLE = re.compile(r"^\s*[一-鿿][^\n::]{0,60}[::]") APOS = {"'": "ʻ", "‘": "ʻ", "’": "ʻ", "ʼ": "ʻ", "ʻ": "ʻ"} _APOS_TABLE = str.maketrans(APOS) def norm(text): return _WS.sub(" ", unicodedata.normalize("NFC", text or "")).strip() def fold(text): return text.translate(_APOS_TABLE) def strip_wrappers(text): t = text or "" t = _FENCE.sub("", t) t = _SPECIAL.sub("", t) t = _TAG.sub("", t) t = html.unescape(t) t = _CJK_PREAMBLE.sub("", t) t = _HEADING.sub("", t) t = _LATEX_TEXT.sub(r"\1", t) m = _EMPH.match(t) if m: t = m.group(2) return t def plain_output(raw): return norm(raw) def pp_output(raw): return fold(norm(strip_wrappers(raw))) def plain_ref(ref): return norm(ref) def pp_ref(ref): return fold(norm(ref)) def lev(a, b): """Levenshtein distance between two sequences (strings or lists), unit costs.""" if a == b: return 0 if len(a) < len(b): a, b = b, a if not b: return len(a) prev = list(range(len(b) + 1)) for i, ca in enumerate(a, 1): cur = [i] for j, cb in enumerate(b, 1): cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))) prev = cur return prev[-1] def score(refs, raws): """refs: reference texts; raws: raw decoded model outputs. Returns the plain and post-processed figures.""" out = {"items": len(refs)} for name, fr, fo in (("plain", plain_ref, plain_output), ("pp", pp_ref, pp_output)): ce = cr = we = wr = ex = er = ern = 0 for r0, h0 in zip(refs, raws): r, h = fr(r0), fo(h0) ce += lev(r, h) cr += len(r) rw, hw = r.split(), h.split() we += lev(rw, hw) wr += len(rw) ex += int(r == h) if not r: er += 1 ern += int(bool(h)) out[name] = {"cer": ce / cr if cr else None, "wer": we / wr if wr else None, "char_edits": ce, "ref_chars": cr, "word_edits": we, "ref_words": wr, "exact": ex / len(refs) if refs else None, "empty_ref_items": er, "empty_ref_nonempty_output": ern} return out