Files
cuotibiye/bench/run.py
T

190 lines
7.1 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 _detect_from_cache_only(data: bytes, name: str) -> dict:
"""不联网:只有缓存命中才算数,否则抛 NO_CACHE。"""
from backend import ocr_cache, tencent_ocr
hit = ocr_cache.get(data)
if not hit:
raise RuntimeError("NO_CACHE")
res = tencent_ocr.split_questions(data, use_cache=True)
if not res.get("ok"):
raise RuntimeError(res.get("code") or "NO_CACHE")
return {"blocks": [_to_block(i, q) for i, q in enumerate(res["questions"])]}
def _to_block(i: int, q: dict) -> dict:
return {"i": i, "box": q.get("box"), "stem": q["stem"],
"judge_type": q.get("detected_as") or q.get("judge_type"),
"options": q.get("options"), "page_answer": q.get("page_answer"),
"subs": q.get("subs") or []}
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("--no-api", action="store_true",
help="只用 OCR 缓存,缺的不发请求(额度用完后重算指标用)")
ap.add_argument("--skip-done", action="store_true",
help="跳过 results.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 args.skip_done and RESULTS.exists():
done_ids = {json.loads(l)["id"] for l in RESULTS.open(encoding="utf-8") if l.strip()}
files = [f for f in files if f.stem not in done_ids]
if not files:
print("没有图片,先跑 python bench/fetch.py")
return 1
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
# 先读旧的,最后整体回写:中途 --ids / --limit 只跑几张时,别把之前的结果冲掉
merged: dict[str, dict] = {}
if out.exists():
for line in out.open(encoding="utf-8"):
if line.strip():
row = json.loads(line)
merged[row["id"]] = row
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:
if args.no_api:
res = _detect_from_cache_only(data, fp.name)
else:
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}
# 这次失败(比如缓存没有)不要把之前跑成功的结果冲掉
prev = merged.get(fp.stem)
if not ok and prev and prev.get("ok"):
print(f" {n:3d}/{len(files)} 跳过(保留上次成功的记录){fp.stem[:12]}")
done += 1
continue
merged[fp.stem] = rec
f.seek(0)
f.truncate()
for row in merged.values():
f.write(json.dumps(row, ensure_ascii=False) + "\n")
f.flush()
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())