aziz9788's picture
Initial commit
cf8c8d4
Raw History Blame Contribute Delete
17 kB
r"""MDPBench (arXiv 2603.28130): multilingual document parsing, digital and photographed pages,
17 languages, scored with the official code (Yuliang-Liu/MultimodalOCR/MDPBench, pinned).
python -m common.mdpbench setup # official scorer + its own Python 3.10 env (uv)
python -m common.mdpbench subset --name ar_plus --per-lang ar=all,default=10
python -m common.mdpbench run --subset ar_plus --model data/models/OvisOCR3 --tag base \
--prompt-file data/models/OvisOCR3/prompts/document_markdown.txt
python -m common.mdpbench run --subset ar_plus --model data/models/OvisOCR3 --adapter data/runs/x/sft --tag sft
`run` = predict (one Markdown file per image, via common.vlm_infer) + score (official pdf_validation.py and
tools/calculate_scores.py) + collapse checks. Results: <OCR_RUNS_DIR>/mdpbench/<subset>/<tag>/summary.json.
Notes
- Public split only (2,720 pages, 160 per language: 40 digital + 120 photographed). The private split is
scored by the authors on request.
- The scorer needs pinned old packages (numpy<2, pandas 2.0.3); `setup` builds a separate env for it so the
training env is untouched. Set MDPBENCH_PYTHON to use another interpreter.
- Formulas are scored with edit distance only unless the CDM environment is installed (`--cdm`); the
official leaderboard uses CDM, so formula-heavy languages can differ slightly from it. Before/after
comparisons with the same settings are unaffected.
- The model is never told the page's language, as in the official protocol.
"""
import argparse
import json
import os
import random
import re
import shutil
import subprocess
import sys
from collections import Counter, defaultdict
from pathlib import Path
from .paths import RUNS_DIR, WORK_DIR
from .score import has_loop
REPO = "Delores-Lin/MDPBench"
REVISION = "252df132fe1b418dbd5830515ef4b5a06fa7164f" # dataset revision checked on 2026-11-15
BENCH_DIR = Path(os.environ.get("MDPBENCH_DIR", str(WORK_DIR / "benchmarks" / "MDPBench")))
VENV = WORK_DIR / "venvs" / "mdpbench"
EXTRA_PACKAGES = ["beautifulsoup4"] # imported by the scorer but absent from its requirements.txt
LATIN = ["de", "en", "es", "fr", "id", "it", "nl", "pt", "vi"]
NON_LATIN = ["ar", "hi", "jp", "ko", "ru", "th", "zh", "zh-cht"]
ARABIC_LETTER = re.compile(r"[؀-ۿݐ-ݿࢠ-ࣿﭐ-﷿ﹰ-]")
LETTER = re.compile(r"[^\W\d_]")
def lang_of(page_id):
return page_id.split("_", 1)[0].lower()
def scorer_dir():
from .upstream import UPSTREAM_DIR
return UPSTREAM_DIR / "MultimodalOCR" / "MDPBench"
def scorer_python():
if os.environ.get("MDPBENCH_PYTHON"):
return os.environ["MDPBENCH_PYTHON"]
exe = VENV / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
if not exe.exists():
raise SystemExit(f"scorer environment missing: run `python -m common.mdpbench setup` (expected {exe})")
return str(exe)
def cmd_setup(a):
from .upstream import fetch
fetch("MultimodalOCR")
if not shutil.which("uv"):
raise SystemExit("uv is required: https://docs.astral.sh/uv/getting-started/installation/")
req = scorer_dir() / "requirements.txt"
if not (VENV / ("Scripts" if os.name == "nt" else "bin")).exists():
subprocess.run(["uv", "venv", "--python", a.python, str(VENV)], check=True)
py = scorer_python()
pkgs = [l.strip() for l in req.read_text(encoding="utf-8").splitlines() if l.strip() and l.strip() != "notebook"]
pkgs += EXTRA_PACKAGES
subprocess.run(["uv", "pip", "install", "--python", py, *pkgs], check=True)
download_gt()
print(f"scorer ready: {py}")
def download_gt():
from huggingface_hub import hf_hub_download
return Path(hf_hub_download(REPO, "MDPBench_public.json", repo_type="dataset", revision=REVISION,
local_dir=str(BENCH_DIR)))
def parse_per_lang(spec):
"""'ar=all,default=10' -> ({'ar': None}, 10); None means every page of that language."""
per, default = {}, 10
for part in filter(None, (p.strip() for p in spec.split(","))):
k, v = part.split("=")
n = None if v.strip() == "all" else int(v)
if k.strip() == "default":
default = n
else:
per[k.strip().lower()] = n
return per, default
def cmd_subset(a):
gt_path = BENCH_DIR / "MDPBench_public.json"
if not gt_path.exists():
gt_path = download_gt()
pages = json.loads(gt_path.read_text(encoding="utf-8"))
per, default = parse_per_lang(a.per_lang)
# Sampling unit = document. Each MDPBench document appears as 1 digital page + 3 photographs of it, so
# whole documents are drawn: the 1:3 mix is kept exactly and two subsets never share a document.
excluded = set()
for name in getattr(a, "exclude", None) or []:
other = json.loads((BENCH_DIR / "subsets" / name / "gt.json").read_text(encoding="utf-8"))
excluded |= {doc_of(Path(p["page_info"]["image_path"]).stem) for p in other}
by_lang = defaultdict(lambda: defaultdict(list))
for p in pages:
stem = Path(p["page_info"]["image_path"]).stem
if doc_of(stem) not in excluded:
by_lang[lang_of(stem)][doc_of(stem)].append(p)
rng = random.Random(a.seed)
chosen = []
for lang in sorted(by_lang):
docs = sorted(by_lang[lang])
n = per.get(lang, default)
if n is not None:
docs = rng.sample(docs, min(len(docs), -(-n // 4))) # n pages, rounded up to whole documents
for d in sorted(docs):
chosen += sorted(by_lang[lang][d], key=lambda p: p["page_info"]["image_path"])
out = BENCH_DIR / "subsets" / a.name
out.mkdir(parents=True, exist_ok=True)
(out / "gt.json").write_text(json.dumps(chosen, ensure_ascii=False), encoding="utf-8")
names = [p["page_info"]["image_path"] for p in chosen]
img_dir = download_images(names)
with open(out / "items.jsonl", "w", encoding="utf-8") as fh:
for p in chosen:
name = p["page_info"]["image_path"]
fh.write(json.dumps({"id": Path(name).stem, "image": str((img_dir / name).resolve()), "text": "",
"level": "page", "language": lang_of(Path(name).stem)}, ensure_ascii=False) + "\n")
counts = Counter(lang_of(Path(n).stem) for n in names)
print(f"subset {a.name}: {len(chosen)} pages -> {out}\n " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items())))
def doc_of(page_id):
"""'ar_book_9_indoor_light_wrinkle' -> 'ar_book_9': the document a digital page or photograph shows."""
return "_".join([x for x in page_id.split("_") if x][:3]).lower()
def is_digital_id(page_id):
return len([x for x in page_id.split("_") if x]) == 3
def download_images(names):
from huggingface_hub import snapshot_download
snapshot_download(REPO, repo_type="dataset", revision=REVISION, local_dir=str(BENCH_DIR),
allow_patterns=[f"MDPBench_img_public/{n}" for n in names])
return BENCH_DIR / "MDPBench_img_public"
def run_dir(subset, tag):
return RUNS_DIR / "mdpbench" / subset / tag
def cmd_predict(a):
items = BENCH_DIR / "subsets" / a.subset / "items.jsonl"
if not items.exists():
raise SystemExit(f"unknown subset {a.subset}: run `python -m common.mdpbench subset --name {a.subset}` first")
d = run_dir(a.subset, a.tag)
cmd = [sys.executable, "-m", "common.vlm_infer", "--model", a.model, "--input", str(items),
"--out", str(d / "predictions.jsonl"), "--md-dir", str(d / "md"),
"--max-pixels", str(a.max_pixels), "--max-new", str(a.max_new)]
if a.adapter:
cmd += ["--adapter", a.adapter, "--adapter-scale", str(a.adapter_scale)]
if a.prompt_file:
cmd += ["--prompt-file", a.prompt_file]
if getattr(a, "loop_guard", False):
cmd += ["--loop-guard"]
if getattr(a, "retry_temps", ""):
cmd += ["--retry-temps", a.retry_temps]
if getattr(a, "route_script", ""):
cmd += ["--route-script", a.route_script]
if getattr(a, "adapter_fallback", False):
cmd += ["--adapter-fallback"]
if getattr(a, "base_rescue", False):
cmd += ["--base-rescue"]
subprocess.run(cmd, check=True)
def cmd_score(a):
d = run_dir(a.subset, a.tag)
last = {}
for line in open(d / "predictions.jsonl", encoding="utf-8-sig"):
if line.strip():
r = json.loads(line)
last[r["id"]] = r
items = [json.loads(l)["id"] for l in open(BENCH_DIR / "subsets" / a.subset / "items.jsonl", encoding="utf-8")]
missing = [i for i in items if "pred" not in last.get(i, {})]
if missing: # an incomplete run would score unread pages as wrong: refuse instead
raise SystemExit(f"{len(missing)} of {len(items)} pages have no prediction (e.g. {missing[:3]}); "
f"rerun predict (errored pages are retried) before scoring")
trimmed = {}
if getattr(a, "trim_repeats", False): # the authors' repeated-tail clean-up, applied to the scored Markdown only
from .loop_guard import trim_repeated_tail
(d / "md").mkdir(exist_ok=True)
for i in items:
text, cut = trim_repeated_tail(last[i].get("pred") or "")
(d / "md" / f"{i}.md").write_text(text, encoding="utf-8")
if cut:
trimmed[i] = cut
print(f"repeated tails trimmed on {len(trimmed)} pages", flush=True)
gt = (BENCH_DIR / "subsets" / a.subset / "gt.json").resolve()
md = (d / "md").resolve()
work = d / "score"
work.mkdir(parents=True, exist_ok=True)
formula = ["Edit_dist", "CDM"] if a.cdm else ["Edit_dist"]
cfg = {"end2end_eval": {
"metrics": {"text_block": {"metric": ["Edit_dist"]}, "display_formula": {"metric": formula},
"table": {"metric": ["TEDS", "Edit_dist"]}, "reading_order": {"metric": ["Edit_dist"]}},
"dataset": {"dataset_name": "end2end_dataset", "ground_truth": {"data_path": gt.as_posix()},
"prediction": {"data_path": md.as_posix()}, "match_method": "quick_match"}}}
import yaml
(work / "end2end.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")
env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}
py, src = scorer_python(), scorer_dir()
with open(work / "pdf_validation.log", "w", encoding="utf-8") as log:
subprocess.run([py, str(src / "pdf_validation.py"), "--config", str(work / "end2end.yaml")],
cwd=work, env=env, check=True, stdout=log, stderr=subprocess.STDOUT)
result_folder = work / "result" / f"{md.name}_result"
out = subprocess.run([py, str(src / "tools" / "calculate_scores.py"), "--result_folder", str(result_folder)],
cwd=work, env=env, check=True, capture_output=True, text=True, encoding="utf-8")
(work / "calculate_scores.txt").write_text(out.stdout, encoding="utf-8")
scores = parse_scores(out.stdout)
# per-page scores (same aggregation as the official script) for paired significance tests
helper = Path(__file__).with_name("_mdpbench_pages.py")
subprocess.run([py, str(helper), str(src / "tools"), str(result_folder), str(d / "pages.json")],
cwd=work, env=env, check=True)
summary = {"subset": a.subset, "tag": a.tag, "scores": scores, "health": health(d / "predictions.jsonl"),
"trimmed_repeated_tails": trimmed if getattr(a, "trim_repeats", False) else None,
"formula_metric": "CDM" if a.cdm else "edit distance (CDM not installed)"}
(d / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
print(json.dumps(summary, indent=2, ensure_ascii=False))
try: # every evaluation also collects its failures for the next data round (see common/failure_mining.py)
from .failure_mining import mine
mine(a.subset, a.tag, base="base" if a.tag != "base" else None)
except Exception as e: # never let mining break scoring
print(f"failure mining skipped: {e}")
return summary
def parse_scores(text):
"""calculate_scores.py prints sections [Latin], [Non-Latin], [Overall] with 'KEY: value' lines."""
scores, section = {}, ""
for line in text.splitlines():
m = re.match(r"\s*\[(.+)\]\s*$", line)
if m:
section = m.group(1)
continue
m = re.match(r"\s+([A-Za-z.\-]+)\s*:\s*([\d.]+|N/A|nan)", line)
if not m:
continue
key, val = m.group(1).rstrip("."), m.group(2)
val = None if val in ("N/A", "nan") else float(val)
if key == "Avg":
key = f"{section}_Avg"
elif section == "Overall":
key = f"Overall_{key}"
scores[key] = val
return scores
def health(pred_path):
"""Collapse signals per language: decoding loops, hit token limit, empty output, and script drift
(share of Arabic letters on non-Arabic pages, a sign the model started writing Arabic everywhere)."""
rows = list({r["id"]: r for r in (json.loads(l) for l in open(pred_path, encoding="utf-8-sig") if l.strip())}.values())
out = defaultdict(lambda: {"pages": 0, "loops": 0, "truncated": 0, "empty": 0, "errors": 0, "arabic_share": []})
for r in rows:
h = out[lang_of(r["id"])]
h["pages"] += 1
pred = r.get("pred")
if pred is None:
h["errors"] += 1
continue
h["loops"] += has_loop(pred)
h["truncated"] += bool(r.get("truncated"))
h["empty"] += not pred.strip()
letters = LETTER.findall(pred)
h["arabic_share"].append(len(ARABIC_LETTER.findall(pred)) / max(1, len(letters)))
res = {}
for lang, h in sorted(out.items()):
sh = h.pop("arabic_share")
res[lang] = {**h, "arabic_share": round(sum(sh) / max(1, len(sh)), 3)}
return res
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("setup", help="fetch the official scorer and build its environment")
s.add_argument("--python", default="3.10", help="Python version for the scorer env (uv downloads it if missing)")
s = sub.add_parser("subset", help="choose pages per language and download only their images")
s.add_argument("--name", required=True)
s.add_argument("--per-lang", default="ar=all,default=10",
help="pages per language, e.g. ar=all,en=40,default=10 ('all' = 160); rounded up to whole "
"documents (1 digital page + 3 photographs each)")
s.add_argument("--exclude", nargs="*", help="subsets whose documents must not be drawn (disjoint dev / test)")
s.add_argument("--seed", type=int, default=0)
for name in ("predict", "score", "run"):
s = sub.add_parser(name)
s.add_argument("--subset", required=True)
s.add_argument("--tag", required=True, help="name of this model / checkpoint in the results")
if name != "score":
s.add_argument("--model", required=True)
s.add_argument("--adapter")
s.add_argument("--adapter-scale", type=float, default=1.0)
s.add_argument("--prompt-file")
s.add_argument("--max-pixels", type=int, default=2880 * 2880, help="native resolution up to the OvisOCR limit")
s.add_argument("--max-new", type=int, default=8192)
s.add_argument("--loop-guard", action="store_true", help="decode with common/loop_guard.py")
s.add_argument("--retry-temps", default="", help="re-read looping pages at these temperatures, e.g. 0.1,0.3,0.5,0.8")
s.add_argument("--route-script", default="",
help="use the adapter only on pages written in this script (see common/vlm_infer.py)")
s.add_argument("--adapter-fallback", action="store_true",
help="base model first; the adapter re-reads only failed pages in the routed script")
s.add_argument("--base-rescue", action="store_true",
help="adapter first on routed pages; the base model re-reads pages whose adapter reading failed")
if name != "predict":
s.add_argument("--cdm", action="store_true", help="also score formulas with CDM (needs its environment)")
s.add_argument("--trim-repeats", action="store_true",
help="cut repeated tails from long outputs before scoring (the OvisOCR3 authors' post-processing)")
a = ap.parse_args(argv)
if a.cmd == "setup":
cmd_setup(a)
elif a.cmd == "subset":
cmd_subset(a)
elif a.cmd == "predict":
cmd_predict(a)
elif a.cmd == "score":
cmd_score(a)
else:
cmd_predict(a)
cmd_score(a)
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
main()