OCR 省钱三件套:结果缓存、按月预算、跳过无谓裁剪;bench 支持 --skip-done/--no-api

This commit is contained in:
2026-11-19 16:33:15 +08:00
parent ba7c35d538
commit df196fd8d9
15 changed files with 685 additions and 237 deletions
+18
View File
@@ -71,3 +71,21 @@ python bench/gold_expr.py --append # 追加成 report.md 第五节
三个口径:**认对**(答案数值相同,`0.6` 与 `3/5` 视为相同)、**算错**(给出答案但数值不对,这才是误判)、**没认出来**(题干里压根没出现这个算式)。
当前(4 张卷、83 道):认对 96.4%、算错 0%、没认出来 3.6%。
## 额度纪律(重要)
评测的每一次 `run.py` 都是一次真实计费调用。**不要反复全量重跑**:
```bash
python bench/run.py --skip-done # 只跑还没成功过的图(日常用这个)
python bench/run.py --ids a1b2,c3d4 # 只重跑个别图
python bench/run.py --no-api # 只用缓存重算指标,不发请求
python -m backend.ocr_budget # 本月还剩多少次
python -m backend.ocr_cache # 缓存里有多少张
```
`results.jsonl` 是合并写的:中途只跑几张不会冲掉之前的结果,也不会用一次失败覆盖上次的成功记录。
已知状态:`data/bench/results.jsonl` 是**加链式求值之前**的 230 张结果;
`report.md`(和 `report/错题毕业-拍题评测-230张.md`)里的数字是加链式求值**之后**的口径。
要复现后者需要重跑那 230 张(有缓存的话不会重复计费)。
+51 -2
View File
@@ -58,10 +58,34 @@ def norm_ans(x: str) -> str:
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)
@@ -71,19 +95,33 @@ def main(argv=None) -> int:
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:
res = scanflow.detect(data, fp.name)
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__), []
@@ -127,7 +165,18 @@ def main(argv=None) -> int:
})
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")
# 这次失败(比如缓存没有)不要把之前跑成功的结果冲掉
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]}")