bench: 加 try_images.py,把一堆图丢进 data/inbox 就能试切题

This commit is contained in:
2026-11-20 15:50:05 +08:00
parent 9f8ef886f0
commit e32598553c
2 changed files with 138 additions and 0 deletions
+122
View File
@@ -0,0 +1,122 @@
"""拿一堆图片快速试切题:每张跑一次切题,打印切出几道、几道能机器判、读出来是什么。
用法:
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:]))
+16
View File
@@ -0,0 +1,16 @@
# 切题试跑
- **2b28ad468e54b88f.jpg** 缓存:11 块,可算 3、选择 0、需自评 8,卡片内 20 道小题
- [卡片] `500×4= / 37×10= / 70×80= / 75×75= / 18×5= / 240÷6= / 65×11= / 8×7+6= / 72÷3= / 3×29= / 4/7` → 11 道,首条 `500×4 =`
- [卡片] `1.8+0.6 / 6.5-2.9 / 40×65 / 53×50 / 12×94 / *49×59` → 6 道,首条 `1.8+0.6 =`
- [卡片] `50×63+52 / 575-355÷5 / 34×(90-46)` → 3 道,首条 `50*63+52 =`
- [自评] `1.2×23得46个一,20×23得46个(); / 40×5得20个(),40×50得20个( )。`
- [自评] `2.李叔叔骑自行车上班,每分钟行驶250米。照这样,他4分钟一共行驶()千米。`
- [自评] `3.在()里填合适的单位。`
- [自评] `(1)一只奶牛重500(),4只这样的奶牛重2()。`
- [自评] `(2)南京到上海的铁路大约长300()。在铁路上行驶的一列火车大约长300()。`
- [自评] `(3)一块正方形手帕的面积大约是400(),校园里一条长方形走道的占地面积大约是250()。`
- [自评] `4.填写出今年每个季度的天数。`
- [自评] `5.5吨=()千克 / )平方分米` = -1-
合计 1 张,成功 1 张;可算 3、选择 0、需自评 8,卡片内小题 20 道。