Files
cuotibiye/bench/run.py
T

141 lines
4.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""把采到的试卷图片跑一遍「拍题」链路,逐张记录结果。
链路 = `backend.scanflow.detect()`:腾讯云 QuestionSplitOCR 切题 → 清洗 → 判题型 →
(算式题)自算答案。**每张图 1 次 API 调用**,不逐块裁剪,避免把额度烧在评测上。
输出 data/bench/results.jsonl,一行一张图:
{id, ok, code, ms, n_blocks, blocks:[{i, type, stem, answer, page_answer,
stmt_ok, judgeable, derived, agree}]}
用法:
python bench/run.py --limit 30
python bench/run.py --from-results # 只重算指标,不重新调 API
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from backend import scanflow # noqa: E402
BENCH = ROOT / "data" / "bench"
RAW = BENCH / "raw"
RESULTS = BENCH / "results.jsonl"
CALC = r"[0-90-9]"
def has_calc(s: str) -> bool:
import re
return bool(re.search(r"\d\s*[+\-×÷*/]\s*\d", s or ""))
def stmt_ok(stem: str) -> bool:
"""题干是不是一句可读的题:够长、有汉字或算式、不是纯符号碎片。"""
s = (stem or "").strip()
if len(s) < 4:
return False
han = sum(1 for ch in s if "\u4e00" <= ch <= "\u9fff")
if han >= 6:
return True
if has_calc(s) and han >= 1:
return True
return False
def norm_ans(x: str) -> str:
import re
s = (x or "").strip()
s = re.sub(r"^(答|答案)[::]?", "", s)
s = s.replace("。", "").replace(" ", "").replace("(", "(").replace(")", ")")
return s.strip()
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="跑评测链路")
ap.add_argument("--limit", type=int, default=0, help="最多跑多少张(0=全部)")
ap.add_argument("--ids", default="", help="只跑这些图 id(逗号分隔),结果合并进原 jsonl")
ap.add_argument("--out", default=str(RESULTS))
args = ap.parse_args(argv)
files = sorted(RAW.glob("*.jpg"))
only = [x.strip() for x in args.ids.split(",") if x.strip()]
if only:
files = [f for f in files if f.stem in only]
if args.limit:
files = files[: args.limit]
if not files:
print("没有图片,先跑 python bench/fetch.py")
return 1
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
done = 0
with out.open("w", encoding="utf-8") as f:
for n, fp in enumerate(files, 1):
data = fp.read_bytes()
t0 = time.time()
try:
res = scanflow.detect(data, fp.name)
ok, code, blocks = True, "", res.get("blocks") or []
except Exception as e: # noqa: BLE001
ok, code, blocks = False, getattr(e, "code", type(e).__name__), []
ms = int((time.time() - t0) * 1000)
rows = []
for b in blocks:
# 口算卡:一块里十几道,评测按「小题」计
subs = b.get("subs") or []
if subs:
for k, sub in enumerate(subs):
rows.append({
"i": f"{b.get('i')}.{k}",
"box": b.get("box"),
"type": "calc",
"stem": (sub.get("stem") or "")[:160],
"answer": norm_ans(sub.get("answer") or ""),
"page_answer": "",
"stmt_ok": True,
"judgeable": True,
"derived": True,
"agree": None,
})
continue
stem = b.get("stem") or ""
jt = b.get("judge_type") or ""
ans = norm_ans(b.get("answer") or "")
page = norm_ans(b.get("page_answer") or "")
derived = bool(ans) and jt == "calc"
rows.append({
"i": b.get("i"),
"box": b.get("box"),
"type": jt,
"stem": stem[:160],
"answer": ans,
"page_answer": page,
"stmt_ok": stmt_ok(stem),
"judgeable": jt in ("calc", "choice"),
"derived": derived,
"agree": (derived and page and ans == page) or None,
})
rec = {"id": fp.stem, "ok": ok, "code": code, "ms": ms,
"n_blocks": len(rows), "blocks": rows}
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
done += 1
flag = "OK " if ok and rows else "空 "
print(f" {n:3d}/{len(files)} {flag}{len(rows):2d} 题 {ms:5d}ms {fp.stem[:12]}")
print(f"\n完成 {done} 张 → {out}")
return 0
if __name__ == "__main__":
sys.exit(main())