"""拿一堆图片快速试切题:每张跑一次切题,打印切出几道、几道能机器判、读出来是什么。 用法: python bench/try_images.py data/inbox python bench/try_images.py data/inbox --no-api # 只认缓存,不发请求 每张图 1 次调用(命中缓存则 0 次)。结果同时写 data/bench/try.md。 """ from __future__ import annotations import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) from backend import tencent_ocr # noqa: E402 EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"} OUT_MD = ROOT / "data" / "bench" / "try.md" def summarize(path: Path, use_api: bool) -> dict: data = path.read_bytes() row = {"file": path.name, "ok": False, "ms": 0, "blocks": [], "code": "", "cached": False} t0 = time.time() try: res = tencent_ocr.split_questions(data, use_cache=use_api) except Exception as e: # noqa: BLE001 - 一张图失败不该中断整批 row["code"] = type(e).__name__ row["msg"] = str(e)[:120] return row row["ms"] = int((time.time() - t0) * 1000) if not res.get("ok"): row["code"] = res.get("code") or "FAILED" row["msg"] = (res.get("message") or "")[:120] return row row["ok"] = True row["cached"] = bool(res.get("cached")) for i, q in enumerate(res.get("questions") or []): subs = q.get("subs") or [] row["blocks"].append( { "i": i, "type": q.get("detected_as") or q.get("judge_type"), "stem": (q.get("stem") or "").replace("\n", " / ")[:90], "subs": len(subs), "first_sub": (subs[0].get("stem") if subs else "") or "", "answer": q.get("answer") or "", } ) return row def _kind(b: dict) -> str: if b["subs"]: return "卡片" return {"choice": "选择", "calc": "可算"}.get(b["type"], "自评") def render(rows: list[dict]) -> str: lines = ["# 切题试跑", ""] total = ok = calc = choice = manual = subs_total = 0 for r in rows: total += 1 if not r["ok"]: lines.append(f"- **{r['file']}** 失败:`{r['code']}` {r.get('msg', '')}") continue ok += 1 blocks = r["blocks"] n_calc = sum(1 for b in blocks if b["subs"] or b["type"] == "calc") n_choice = sum(1 for b in blocks if not b["subs"] and b["type"] == "choice") n_manual = len(blocks) - n_calc - n_choice n_subs = sum(b["subs"] for b in blocks) calc += n_calc choice += n_choice manual += n_manual subs_total += n_subs note = "缓存" if r["cached"] else f"{r['ms']}ms" lines.append( f"- **{r['file']}** {note}:{len(blocks)} 块,可算 {n_calc}、选择 {n_choice}、需自评 {n_manual}" + (f",卡片内 {n_subs} 道小题" if n_subs else "") ) for b in blocks: extra = f" → {b['subs']} 道,首条 `{b['first_sub']}`" if b["subs"] else "" ans = f" = {b['answer']}" if b["answer"] and not b["subs"] else "" lines.append(f" - [{_kind(b)}] `{b['stem']}`{ans}{extra}") lines += [ "", f"合计 {total} 张,成功 {ok} 张;可算 {calc}、选择 {choice}、需自评 {manual}," f"卡片内小题 {subs_total} 道。", "", ] return "\n".join(lines) def main(argv: list[str]) -> int: args = [a for a in argv if not a.startswith("-")] use_api = "--no-api" not in argv folder = Path(args[0]) if args else ROOT / "data" / "inbox" if not folder.exists(): print(f"目录不存在:{folder}") return 2 files = sorted(p for p in folder.iterdir() if p.suffix.lower() in EXTS) if not files: print(f"{folder} 里没有图片(支持 {' '.join(sorted(EXTS))})") return 2 rows = [] for p in files: print(f"… {p.name}", flush=True) rows.append(summarize(p, use_api)) md = render(rows) OUT_MD.parent.mkdir(parents=True, exist_ok=True) OUT_MD.write_text(md, encoding="utf-8") print(md) print(f"已写入 {OUT_MD}") return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))