File size: 3,526 Bytes
cf8c8d4 | 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 | """Character error rate (CER) for OCR predictions.
Input: JSONL from common/vlm_infer.py (fields "id", "pred", "gt", optional "source").
Results are grouped by "source" (or by the id prefix before the first "_").
Two CER variants are reported:
strict Markdown symbols and HTML tags removed, Unicode NFKC, all decimal digits mapped to 0-9,
whitespace collapsed. Accents and other combining marks are kept.
folded strict, plus case-folded and all combining marks (Unicode category Mn) removed.
Use it to separate "wrong character" errors from "missing accent / mark" errors.
python -m common.score data/runs/ovisocr3_eval.jsonl
"""
import argparse
import json
import math
import re
import statistics as st
import sys
import unicodedata
from collections import defaultdict
from rapidfuzz.distance import Levenshtein
TAG = re.compile(r"<[^>]+>")
MD = re.compile(r"[*#`>|_\-]+")
def _digit(ch: str) -> str:
d = unicodedata.decimal(ch, None)
return str(d) if d is not None else ch
def norm(s: str, fold: bool = False) -> str:
s = unicodedata.normalize("NFKC", MD.sub(" ", TAG.sub(" ", s)))
s = "".join(_digit(c) for c in s)
if fold:
s = "".join(c for c in unicodedata.normalize("NFD", s) if unicodedata.category(c) != "Mn")
s = unicodedata.normalize("NFC", s).casefold()
return re.sub(r"\s+", " ", s).strip()
def cer(pred: str, gt: str) -> float:
return Levenshtein.distance(pred, gt) / max(1, len(gt))
def has_loop(s: str) -> bool:
"""True if a 30-character chunk repeats 6+ times: the usual sign of a decoding loop."""
for i in range(0, max(1, len(s) - 60), 20):
c = s[i:i + 30]
if len(c.strip()) > 10 and s.count(c) >= 6:
return True
return False
def p90(xs):
xs = sorted(xs)
return xs[min(len(xs) - 1, math.ceil(0.9 * len(xs)) - 1)]
def report(rows, threshold: float = 0.05):
groups = defaultdict(list)
for r in rows:
groups[r.get("source") or r["id"].split("_")[0]].append(r)
for name, rs in sorted(groups.items()):
ok = [r for r in rs if "pred" in r]
if not ok:
print(f"{name}: {len(rs)} rows, all errored")
continue
strict = [cer(norm(r["pred"]), norm(r["gt"])) for r in ok]
folded = [cer(norm(r["pred"], True), norm(r["gt"], True)) for r in ok]
print(f"{name}: n={len(rs)} scored={len(ok)} errors={len(rs) - len(ok)}")
print(f" CER strict mean {st.mean(strict):.3f} median {st.median(strict):.3f} p90 {p90(strict):.3f}")
print(f" CER folded mean {st.mean(folded):.3f} median {st.median(folded):.3f} p90 {p90(folded):.3f}")
print(f" pages with folded CER <= {threshold:.0%}: {sum(x <= threshold for x in folded)}/{len(folded)}"
f" | decoding loops: {sum(has_loop(r['pred']) for r in ok)}"
f" | hit token limit: {sum(r.get('truncated', False) for r in ok)}")
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("predictions", help="JSONL written by common.vlm_infer")
ap.add_argument("--threshold", type=float, default=0.05, help="count pages at or below this folded CER")
a = ap.parse_args(argv)
with open(a.predictions, encoding="utf-8-sig") as fh:
rows = [json.loads(line) for line in fh if line.strip()]
report(rows, a.threshold)
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
main()
|