OCR 省钱三件套:结果缓存、按月预算、跳过无谓裁剪;bench 支持 --skip-done/--no-api
This commit is contained in:
+51
-2
@@ -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]}")
|
||||
|
||||
Reference in New Issue
Block a user