File size: 4,270 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
"""Compare two scored benchmark runs (from common.mdpbench) page by page: what changed and where.

    python -m common.eval_compare --subset g_dev_ar --base base --new F1_focus

Prints: score per language (base -> new, change), mean edit distance per part (text blocks, tables, reading
order, formulas; lower is better) per language, loop / token-limit counts, and the pages that improved and
regressed most with their per-part edits, so a change in the headline number can be traced to its cause.
Writes the same as JSON to <new run>/compare_<base>.json.
"""
import argparse
import json
import statistics as st
from pathlib import Path

from .mdpbench import lang_of, run_dir

PARTS = ["text_block", "table", "reading_order", "display_formula"]


def load(subset, tag):
    d = run_dir(subset, tag)
    pages = json.loads((d / "pages.json").read_text(encoding="utf-8"))
    res = d / "score" / "result" / "md_result"
    parts = {}
    for p in PARTS:
        f = res / f"md_result_{p}_All_per_page_edit.json"
        parts[p] = json.loads(f.read_text()) if f.exists() else {}
    preds = {}
    pf = d / "predictions.jsonl"
    if pf.exists():
        for line in open(pf, encoding="utf-8"):
            r = json.loads(line)
            preds[r["id"]] = r
    summary = json.loads((d / "summary.json").read_text(encoding="utf-8"))
    return pages, parts, preds, summary


def num(x):
    return x if isinstance(x, (int, float)) else None


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--subset", required=True)
    ap.add_argument("--base", required=True)
    ap.add_argument("--new", required=True)
    ap.add_argument("--top", type=int, default=8)
    a = ap.parse_args(argv)
    bp, bparts, bpred, bs = load(a.subset, a.base)
    np_, nparts, npred, ns = load(a.subset, a.new)
    common = sorted(set(bp) & set(np_))
    langs = sorted({lang_of(k) for k in common})
    out = {"subset": a.subset, "base": a.base, "new": a.new, "languages": {}, "pages": {}}
    print(f"== {a.subset}: {a.base} -> {a.new} on {len(common)} pages")
    print(f"{'lang':6s}{'pages':>6s}{'score':>16s}{'change':>8s}   mean edit per part (base -> new)       loops/limit")
    for lg in langs:
        ks = [k for k in common if lang_of(k) == lg]
        b, n = 100 * st.mean(bp[k] for k in ks), 100 * st.mean(np_[k] for k in ks)
        parts = {}
        for p in PARTS:
            bv = [num(bparts[p].get(k)) for k in ks]
            nv = [num(nparts[p].get(k)) for k in ks]
            pair = [(x, y) for x, y in zip(bv, nv) if x is not None and y is not None]
            if pair:
                parts[p] = (round(st.mean(x for x, _ in pair), 3), round(st.mean(y for _, y in pair), 3))
        lb = sum(bool(bpred.get(k, {}).get("truncated")) for k in ks)
        ln = sum(bool(npred.get(k, {}).get("truncated")) for k in ks)
        out["languages"][lg] = {"pages": len(ks), "base": round(b, 1), "new": round(n, 1), "parts": parts,
                                "limit_hits": [lb, ln]}
        ptxt = " ".join(f"{p.split('_')[0]} {x}->{y}" for p, (x, y) in parts.items())
        print(f"{lg:6s}{len(ks):>6d}{b:>8.1f} ->{n:>6.1f}{n - b:>+8.1f}   {ptxt:40s} {lb}->{ln}")
    delta = sorted(((np_[k] - bp[k], k) for k in common))
    for title, sel in [("regressed most", delta[:a.top]), ("improved most", delta[::-1][:a.top])]:
        print(f"\n== {title}")
        for d, k in sel:
            if (title.startswith("reg") and d >= 0) or (title.startswith("imp") and d <= 0):
                continue
            pp = " ".join(f"{p.split('_')[0]} {num(bparts[p].get(k))}->{num(nparts[p].get(k))}"
                          for p in PARTS if num(bparts[p].get(k)) is not None or num(nparts[p].get(k)) is not None)
            tok = f"tokens {bpred.get(k, {}).get('out_tokens')}->{npred.get(k, {}).get('out_tokens')}"
            print(f"  {100 * d:+6.1f}  {k[:58]:58s} {100 * bp[k]:5.1f}->{100 * np_[k]:5.1f}  {pp}  {tok}")
            out["pages"][k] = {"base": bp[k], "new": np_[k]}
    path = run_dir(a.subset, a.new) / f"compare_{a.base}.json"
    path.write_text(json.dumps(out, indent=2, ensure_ascii=False), encoding="utf-8")


if __name__ == "__main__":
    main()