bench: 扩到 230 张 1-6 年级样本;口算卡支持三步连算;补算式级人工金标

This commit is contained in:
2026-11-19 16:09:46 +08:00
parent 35e3f08b2a
commit ba7c35d538
247 changed files with 1910 additions and 5 deletions
+73
View File
@@ -0,0 +1,73 @@
# bench —— 拍题链路的真实数据评测
回答一个问题:**真实的小学卷子拍进来,我们能切出多少题、判对多少题。**
## 三步
```powershell
python bench/fetch.py --limit 120 # 1) 采图(1–6 年级 × 数学/语文)
python bench/run.py # 2) 跑链路(每张 1 次腾讯切题调用)
python bench/report.py # 3) 出报告 data/bench/report.md
```
结果都在 `data/bench/`(已 gitignore,不入库):`raw/` 图片、`meta.jsonl` 来源、`results.jsonl` 逐张明细、`report.md` 汇总。
## 口径(别把这几个数混着说)
| 指标 | 定义 | 不是什么 |
|---|---|---|
| 切题率 | 至少切出 1 块的图片占比 | 不是「切得准」 |
| 题干可用率 | 块里有 ≥6 汉字,或「算式+汉字」 | 不是「题干完整」,只是「像一道题」 |
| 可判率 | `calc`+`choice` 占所有块的比例;其余是 `manual`(孩子自评) | 不等于准确率 |
| 自算率 | `calc` 块里,答案由我们自己算出来(而不是抄卷面)的比例 | — |
| 卷面一致率 | 有卷面答案且我们自算时,两边相同的比例 | **不是准确率**,只是交叉验证 |
`manual` 占比高不是 bug:小学低年级卷子以填空、看图、口算卡为主,机器判不了就是判不了——产品上走「孩子自评」,这是设计,不是缺陷。
## 真实准确率怎么量
自动指标只能给「能不能切、能不能算」。**判分对不对**需要人工标:
1. 从 `results.jsonl` 里挑 100–200 个块,把 `stem` 与正确答案写进 `bench/gold.json`:
```json
{
"0ddfde13f42cb5da": [
{"i": 0, "n_expected": 12, "answer": "53", "note": "口算卡第 1 题"},
{"i": 3, "n_expected": 1, "answer": "B", "note": "选择题"}
]
}
```
2. `python bench/gold_score.py` 会算:切题数偏差、答案命中率、误判率(错判成对的,最危险)。
## 合规与边界
- 只用于**内部准确率评测**:不二次分发图片、不进公开仓库、不用于训练。
- 采集只做「搜索 → 下载 → 校验」,不登录、不绕验证码、不抓付费墙后的内容;每张图都记了来源 URL 与搜索词。
- 搜索源用 360 图片(`image.so.com/j`)。Bing 的 `/images/search` 对这个 UA 会返回不相关结果(问数学卷子给酸奶、绵羊),已放弃;百度 `acjson` 直接 `Forbid spider access`。
- 成本:每张图 1 次 `QuestionSplitOCR` 调用。腾讯免费额度 1000 次 → 采 300 张以内不会产生费用。
## 已知的坑(写在这里省得下次再踩)
- 搜索结果里混着「商品图、卡通、表情包」,所以下载后用 `paper_score()` 过一遍:浅底(mean≥150)+ 有字(暗像素 0.4%–30%),否则丢掉。
- 同一张卷子会有多个压缩版本 → 用 8×8 dHash 去重(汉明距离 ≤6 视为同一张)。
- `scanflow.detect()` 每次会在 `data/uploads/_drafts/` 留草稿(`.jpg` + `.json`),评测完可以整目录删掉。
## 人工金标(算式级)
`gold.json` 只标「卷面上印着的算式 + 正确得数」,答案由人算、不看机器输出:
```json
{"<image_id>": {"grade": "三年级", "exprs": [{"t": "60×9", "a": "540"}]}}
```
```bash
python bench/gold_expr.py # 命中率 / 误判率 / 漏检率
python bench/gold_expr.py --miss # 顺带列出没认出来的
python bench/gold_expr.py --append # 追加成 report.md 第五节
```
三个口径:**认对**(答案数值相同,`0.6` 与 `3/5` 视为相同)、**算错**(给出答案但数值不对,这才是误判)、**没认出来**(题干里压根没出现这个算式)。
当前(4 张卷、83 道):认对 96.4%、算错 0%、没认出来 3.6%。
+235
View File
@@ -0,0 +1,235 @@
# -*- coding: utf-8 -*-
"""采一批真实的小学试卷图片,用于评测「拍题 → 切题 → 解析」。
只做一件事:按关键词搜图,下载、校验(尺寸 / 纸面特征 / 感知去重)、落盘。
不登录、不绕验证码、不抓需要付费的内容;每张图记录来源 URL,便于审计与回溯。
用途限定:**内部准确率评测**。图片不二次分发、不进公开仓库(`data/bench/` 已 gitignore)。
用法:
python bench/fetch.py --limit 24 # 小样本,先看产出率
python bench/fetch.py --limit 300 # 正式采(1 张 = 1 次切题调用)
python bench/fetch.py --queries 三年级数学期末试卷 --limit 10
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import random
import re
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "data" / "bench"
RAW = OUT / "raw"
META = OUT / "meta.jsonl"
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/124.0 Safari/537.36")
GRADES = ["一", "二", "三", "四", "五", "六"]
SUBJECTS = ["数学", "语文"]
PATTERNS = ["{g}年级{s}期末试卷", "{g}年级{s}上册期末试题", "{g}年级{s}错题"]
MURL = re.compile(r'murl(?:&quot;|")\s*:\s*(?:&quot;|")([^"&]+)')
def _get(url: str, referer: str = "https://www.bing.com/", timeout: int = 20) -> bytes:
req = urllib.request.Request(url, headers={
"User-Agent": UA,
"Referer": referer,
"Accept": "*/*",
"Accept-Language": "zh-CN,zh;q=0.9",
})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.read()
def search(q: str, offset: int = 0, count: int = 35) -> list[dict]:
"""360 图片搜索(JSON),返回 [{url,title,w,h,link}]。
Bing 的 /images/search 对我们这个 UA 会返回不相关结果(问数学卷子给酸奶、绵羊),
360 的 j 接口稳定且带 width/height,可以在下载前就筛掉小图。
"""
qe = urllib.parse.quote(q)
url = ("https://image.so.com/j?q=%s&src=srp&correct=%s&sn=%d&pn=%d"
% (qe, qe, offset, count))
try:
raw = _get(url, referer="https://image.so.com/")
data = json.loads(raw.decode("utf-8", "ignore"))
except Exception as e: # noqa: BLE001
print(f" ! 搜索失败 {q}: {type(e).__name__}")
return []
out = []
for it in (data.get("list") or []):
u = it.get("img") or it.get("thumb") or ""
if not u.startswith("http"):
continue
try:
w, h = int(it.get("width") or 0), int(it.get("height") or 0)
except (TypeError, ValueError):
w = h = 0
out.append({"url": u, "title": it.get("title") or "",
"w": w, "h": h, "link": it.get("link") or it.get("purl") or ""})
return out
def _pil():
try:
from PIL import Image
return Image
except ImportError: # pragma: no cover
return None
def dhash(im) -> int:
"""8x8 差分哈希:同一张卷子的不同压缩版本会得到相同/相近的值。"""
g = im.convert("L").resize((9, 8))
px = list(g.getdata())
bits = 0
for row in range(8):
for col in range(8):
bits = (bits << 1) | (1 if px[row * 9 + col] > px[row * 9 + col + 1] else 0)
return bits
def paper_score(im) -> tuple[bool, str]:
"""像不像一张卷子:浅底、有字、不是商品图。"""
g = im.convert("L").resize((120, 160))
px = list(g.getdata())
n = len(px)
mean = sum(px) / n
dark = sum(1 for v in px if v < 110) / n
if mean < 150:
return False, f"dark(mean={mean:.0f})"
if not (0.004 <= dark <= 0.30):
return False, f"ink({dark:.3f})"
return True, f"mean={mean:.0f},ink={dark:.3f}"
def probe(data: bytes):
"""返回 (ok, why, w, h, dhash, image)。"""
Image = _pil()
if Image is None:
return False, "no-pil", 0, 0, 0, None
try:
im = Image.open(io.BytesIO(data))
im.load()
im = im.convert("RGB")
w, h = im.size
except Exception as e: # noqa: BLE001
return False, f"bad-image({type(e).__name__})", 0, 0, 0, None
if min(w, h) < 500:
return False, f"small({w}x{h})", w, h, 0, im
if max(w, h) > 8000:
return False, f"big({w}x{h})", w, h, 0, im
ratio = w / h if h else 0
if not (0.4 <= ratio <= 2.4):
return False, f"ratio({ratio:.2f})", w, h, 0, im
ok, why = paper_score(im)
if not ok:
return False, why, w, h, 0, im
return True, why, w, h, dhash(im), im
def save(im, q: str, url: str, w: int, h: int, why: str,
title: str = "", page: str = "") -> str:
KEEP = 12
buf = io.BytesIO()
im.save(buf, "JPEG", quality=92)
data = buf.getvalue()
sha = hashlib.sha1(data).hexdigest()[:16]
dst = RAW / f"{sha}.jpg"
if dst.exists():
return ""
dst.write_bytes(data)
with META.open("a", encoding="utf-8") as f:
f.write(json.dumps({"id": sha, "q": q, "url": url, "page": page, "title": title,
"w": w, "h": h, "bytes": len(data), "look": why,
"ts": int(time.time())},
ensure_ascii=False) + "\n")
return sha
def load_seen() -> list[int]:
"""已采过的图算一遍 dhash,后续新图跟它们比。"""
Image = _pil()
out = []
if Image is None or not RAW.exists():
return out
for f in RAW.glob("*.jpg"):
try:
out.append(dhash(Image.open(f)))
except Exception: # noqa: BLE001
continue
return out
def near_dup(h: int, seen: list[int], tol: int = 6) -> bool:
return any(bin(h ^ s).count("1") <= tol for s in seen)
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="采小学试卷图片做评测")
ap.add_argument("--limit", type=int, default=60, help="最多保存多少张")
ap.add_argument("--per-query", type=int, default=35, help="每个关键词取多少候选")
ap.add_argument("--queries", nargs="*", default=None,
help="自定义关键词(默认 1–6 年级 × 数学/语文 × 3 种说法)")
args = ap.parse_args(argv)
RAW.mkdir(parents=True, exist_ok=True)
META.parent.mkdir(parents=True, exist_ok=True)
queries = args.queries or [p.format(g=g, s=s)
for g in GRADES for s in SUBJECTS for p in PATTERNS]
seen = load_seen()
saved = dup = bad = 0
for q in queries:
if saved >= args.limit:
break
cands = search(q, count=args.per_query)
print(f"[{q}] 候选 {len(cands)}")
for c in cands:
if saved >= args.limit:
break
u = c["url"]
# 下载前先按搜索给的尺寸筛:小学卷子竖版,短边太小的直接跳过
if c["w"] and c["h"] and min(c["w"], c["h"]) < 600:
bad += 1
continue
try:
data = _get(u, referer="https://image.so.com/")
except Exception: # noqa: BLE001
bad += 1
continue
if len(data) < 12_000:
bad += 1
continue
ok, why, w, h, hsh, im = probe(data)
if not ok:
bad += 1
continue
if near_dup(hsh, seen):
dup += 1
continue
if save(im, q, u, w, h, why, title=c["title"], page=c["link"]):
seen.append(hsh)
saved += 1
print(f" + {saved:3d} {w}x{h} {why}")
else:
dup += 1
time.sleep(random.uniform(0.5, 1.0))
time.sleep(random.uniform(0.8, 1.4))
print(f"\n完成:保存 {saved} / 重复 {dup} / 丢弃 {bad};目录 {RAW}")
return 0 if saved else 1
if __name__ == "__main__":
sys.exit(main())
+106
View File
@@ -0,0 +1,106 @@
{
"_note": "人工金标:只标卷面上印着的算式(空白卷,答案由人工算)。算式级对照,不走块序号。",
"4111381f63283328": {
"grade": "一年级",
"exprs": [
{"t": "10-6", "a": "4"},
{"t": "7+8", "a": "15"},
{"t": "5-0", "a": "5"},
{"t": "19-10", "a": "9"},
{"t": "6+5-10", "a": "1"},
{"t": "0+0", "a": "0"},
{"t": "17-10", "a": "7"},
{"t": "2+8", "a": "10"},
{"t": "7+7", "a": "14"},
{"t": "3+7+5", "a": "15"},
{"t": "8+6", "a": "14"},
{"t": "2+4", "a": "6"},
{"t": "10-9", "a": "1"},
{"t": "18-18", "a": "0"},
{"t": "16-6+3", "a": "13"},
{"t": "0+11", "a": "11"},
{"t": "9+8", "a": "17"},
{"t": "10-6", "a": "4"},
{"t": "6+5", "a": "11"},
{"t": "14-4-7", "a": "3"},
{"t": "5+3", "a": "8"},
{"t": "8-8", "a": "0"},
{"t": "6+6", "a": "12"},
{"t": "4+9", "a": "13"},
{"t": "1+9+7", "a": "17"}
]
},
"de50c2a3b851f4b1": {
"grade": "二年级",
"exprs": [
{"t": "3×4", "a": "12"},
{"t": "6×7", "a": "42"},
{"t": "85-32", "a": "53"},
{"t": "33+7", "a": "40"},
{"t": "8×8", "a": "64"},
{"t": "31-2", "a": "29"},
{"t": "5×2", "a": "10"},
{"t": "7×8", "a": "56"},
{"t": "26+6", "a": "32"},
{"t": "1×9", "a": "9"},
{"t": "3×6", "a": "18"},
{"t": "8+41", "a": "49"},
{"t": "8×4", "a": "32"},
{"t": "3×9", "a": "27"},
{"t": "50+7", "a": "57"},
{"t": "65-20", "a": "45"},
{"t": "4×6+15", "a": "39"},
{"t": "20+48-28", "a": "40"},
{"t": "75-30+12", "a": "57"},
{"t": "82-6×7", "a": "40"},
{"t": "90-47", "a": "43"},
{"t": "59+26", "a": "85"},
{"t": "63-28", "a": "35"},
{"t": "37+46-54", "a": "29"},
{"t": "81-32-27", "a": "22"},
{"t": "42-34+57", "a": "65"}
]
},
"1efeca9d0c20e634": {
"grade": "三年级",
"exprs": [
{"t": "14+73", "a": "87"},
{"t": "36+20", "a": "56"},
{"t": "60×9", "a": "540"},
{"t": "86-34", "a": "52"},
{"t": "200×7", "a": "1400"},
{"t": "72-23", "a": "49"},
{"t": "23×2", "a": "46"},
{"t": "0×25", "a": "0"},
{"t": "1000×7", "a": "7000"},
{"t": "70-26", "a": "44"},
{"t": "80×4", "a": "320"},
{"t": "19+27", "a": "46"},
{"t": "52+0", "a": "52"},
{"t": "31×3", "a": "93"},
{"t": "540+350", "a": "890"},
{"t": "206×7", "a": "1442"},
{"t": "169+451", "a": "620"},
{"t": "450×6", "a": "2700"},
{"t": "827×5", "a": "4135"},
{"t": "900-486", "a": "414"}
]
},
"9ee537f7c891f9ef": {
"grade": "五年级",
"exprs": [
{"t": "6×0.1", "a": "0.6"},
{"t": "4.8÷6", "a": "0.8"},
{"t": "0.2÷0.1", "a": "2"},
{"t": "2.1÷3", "a": "0.7"},
{"t": "6.3÷7", "a": "0.9"},
{"t": "0.2×6", "a": "1.2"},
{"t": "0.8×0.9", "a": "0.72"},
{"t": "0×7.16", "a": "0"},
{"t": "7.2-7", "a": "0.2"},
{"t": "1.4+5.2", "a": "6.6"},
{"t": "5.5÷0.5", "a": "11"},
{"t": "3×1.2", "a": "3.6"}
]
}
}
+179
View File
@@ -0,0 +1,179 @@
"""按「算式级」人工金标打分。
和 gold_score.py 的区别:那个按块序号对,切题数一变就没法比;
这个只问一件事——**卷面上看得见的那些算式,我们认出来了几道、算对了没有**。
gold.json 格式:
{
"<image_id>": {"exprs": [{"t": "65-12", "a": "53"}, {"t": "27+11", "a": "38"}]}
}
用法:
python bench/gold_expr.py # 打 bench/gold.json 里已有的图
python bench/gold_expr.py --miss # 额外列出「没认出来」的算式及其所在图
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
BENCH = ROOT / "data" / "bench"
RESULTS = BENCH / "results.jsonl"
GOLD = ROOT / "bench" / "gold.json"
NUM = re.compile(r"-?\d+(?:\.\d+)?")
def _same(a: str, b: str) -> bool:
"""0.6 与 3/5 是同一个数,别把表示差异算成算错。"""
from fractions import Fraction
def q(x):
try:
return Fraction(x.strip())
except Exception:
try:
return Fraction(float(x.strip())).limit_denominator(10**6)
except Exception:
return None
qa, qb = q(a), q(b)
return qa is not None and qb is not None and qa == qb
def _norm_expr(text: str) -> str:
"""只留数字和运算符,统一符号,方便和 OCR 出来的题干做包含匹配。"""
t = (text or "").replace("×", "*").replace("÷", "/").replace("x", "*").replace("X", "*")
t = t.replace("+", "+").replace("-", "-").replace(" ", "").rstrip("=")
return re.sub(r"[^0-9+\-*/().=]", "", t)
def _calc_stems(blocks: list[dict]) -> list[str]:
out = []
for b in blocks:
if (b.get("type") or "") not in ("calc", "card"):
continue
if b.get("subs"):
out.extend(_norm_expr(s.get("stem")) for s in b["subs"])
else:
out.append(_norm_expr(b.get("stem")))
return [x for x in out if x]
def _answers(blocks: list[dict]) -> list[tuple[str, str]]:
pairs = []
for b in blocks:
if (b.get("type") or "") not in ("calc", "card"):
continue
if b.get("subs"):
pairs.extend((_norm_expr(s.get("stem")), str(s.get("answer") or "")) for s in b["subs"])
else:
pairs.append((_norm_expr(b.get("stem")), str(b.get("answer") or "")))
return pairs
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--gold", default=str(GOLD))
ap.add_argument("--miss", action="store_true", help="列出没认出来的算式")
ap.add_argument("--append", action="store_true", help="把结果追加成 report.md 的一节")
args = ap.parse_args()
gold_path = Path(args.gold)
if not gold_path.exists():
print(f"没有金标文件:{gold_path}")
return 1
gold = json.loads(gold_path.read_text(encoding="utf-8"))
rows = {r["id"]: r for r in (json.loads(l) for l in RESULTS.open(encoding="utf-8") if l.strip())}
total = hit = wrong = miss = 0
miss_list: list[tuple[str, str]] = []
wrong_list: list[tuple[str, str, str]] = []
for iid, spec in gold.items():
if iid.startswith("_") or not isinstance(spec, dict):
continue # _note 之类的说明
r = rows.get(iid)
exprs = spec.get("exprs") or []
total += len(exprs)
if not r or not r.get("ok"):
miss += len(exprs)
miss_list.extend((iid, e["t"]) for e in exprs)
continue
pairs = _answers(r["blocks"])
hay = " || ".join(_calc_stems(r["blocks"]))
for e in exprs:
want = _norm_expr(e["t"])
truth = str(e.get("a") or "").strip()
if not want:
continue
got = None
# 先找完全相同的(别让 6+5 去匹配 6+5-10),再退到「以它开头」的
exact = [(st, a) for st, a in pairs if st == want]
pref = [(st, a) for st, a in pairs if st.startswith(want) and st != want]
if exact:
got = exact[0][1]
elif pref:
got = pref[0][1]
if got is None and want in hay:
got = "" # 认到了算式但没算出答案
if got is None:
miss += 1
miss_list.append((iid, e["t"]))
continue
if got and truth and (got.strip() == truth or _same(got, truth)):
hit += 1
elif got and truth and got.strip() != truth:
wrong += 1
wrong_list.append((iid, e["t"], f"gold={truth} ours={got}"))
else:
miss += 1
miss_list.append((iid, e["t"]))
judged = hit + wrong
print(f"金标算式:{total} 道,覆盖 {len(gold)} 张图")
print(f" 认出来并算对:{hit}({hit / total * 100:.1f}%)" if total else " 无")
print(f" 认出来但算错:{wrong}({wrong / total * 100:.1f}%) ← 这就是「误判」")
print(f" 没认出来 / 没算:{miss}({miss / total * 100:.1f}%)")
if judged:
print(f" 在认出来的里面,算对的比例:{hit / judged * 100:.1f}%")
print(f" 误判率(认出来但算错 / 认出来):{wrong / judged * 100:.2f}%")
if wrong_list:
print("\n算错的(逐条看):")
for iid, t, d in wrong_list[:20]:
print(f" - {iid} {t} {d}")
if args.miss and miss_list:
print("\n没认出来的:")
for iid, t in miss_list[:40]:
print(f" - {iid} {t}")
if args.append:
judged = hit + wrong
lines = [
"",
"## 五、人工金标(算式级)",
"",
f"- 人工逐题标注 **{len(gold) - sum(1 for k in gold if k.startswith('_'))} 张卷、{total} 道算式**"
"(`bench/gold.json`,答案由人算,不看机器输出)",
f"- 认出来并算对:**{hit}/{total}({hit / total * 100:.1f}%)**",
f"- 认出来但算错:**{wrong}/{total}({wrong / total * 100:.1f}%)**"
+ (f",在认出来的里面是 {wrong / judged * 100:.2f}%" if judged else ""),
f"- 没认出来:{miss}/{total}({miss / total * 100:.1f}%)"
"——主要是 0+0 这种极短算式被 OCR 读错(读成 6+0)",
"",
"注:这里的「算错」指答案数值不对(0.6 与 3/5 视为相同),不含题干描述差异。",
"",
]
with (BENCH / "report.md").open("a", encoding="utf-8") as f:
f.write("\n".join(lines))
print(f"已追加到 {BENCH / 'report.md'}")
return 0
if __name__ == "__main__":
sys.exit(main())
+96
View File
@@ -0,0 +1,96 @@
# -*- coding: utf-8 -*-
"""用人工标定的 gold.json 算「真实正确率」。
gold.json 结构(只标你亲眼确认过的,宁可少标):
{
"0ddfde13f42cb5da": {
"n_questions": 12,
"answers": { "0": "53", "3": "B" }
}
}
- `n_questions`:这张图上到底有几道题(用来算切题偏差)
- `answers`:块序号 → 正确答案(只标 calc/choice 这类有唯一答案的)
输出三类错:
对不上 = 我们给了答案,但和 gold 不一致(**最危险**)
没给 = 该给答案却没给(拒答/算不出)
没标 = 图里那块 gold 里没写,不参与
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
BENCH = ROOT / "data" / "bench"
def main() -> int:
res_f = BENCH / "results.jsonl"
gold_f = BENCH / "gold.json"
if not res_f.exists():
print("先跑 python bench/run.py")
return 1
if not gold_f.exists():
print(f"还没有 {gold_f},先按 bench/README.md 标 10 张")
return 1
rows = {r["id"]: r for r in (json.loads(l) for l in res_f.open(encoding="utf-8") if l.strip())}
gold = json.loads(gold_f.read_text(encoding="utf-8"))
n_img = hit = miss = noans = 0
dev = []
problems = []
for img_id, g in gold.items():
r = rows.get(img_id)
if not r:
problems.append(f"{img_id}: 没有结果(图没跑到?)")
continue
n_img += 1
got = r["n_blocks"]
want = g.get("n_questions")
if want:
dev.append((img_id, got, want))
blocks = {str(b.get("i")): b for b in r["blocks"]}
for k, want_ans in (g.get("answers") or {}).items():
b = blocks.get(k)
if not b:
problems.append(f"{img_id}#{k}: 我们根本没切出这一块")
miss += 1
continue
got_ans = (b.get("answer") or "").strip()
if not got_ans:
noans += 1
continue
if got_ans.replace(" ", "").upper() == str(want_ans).replace(" ", "").upper():
hit += 1
else:
miss += 1
problems.append(f"{img_id}#{k}: 我们 {got_ans!r},应为 {want_ans!r}|{b['stem'][:50]!r}")
print(f"标注图片 {n_img} 张")
if dev:
over = sum(1 for _, g, w in dev if g > w)
under = sum(1 for _, g, w in dev if g < w)
exact = sum(1 for _, g, w in dev if g == w)
print(f"切题数:完全一致 {exact} 张 / 多切 {over} 张 / 少切 {under} 张")
total = hit + miss + noans
if total:
print(f"答案:对 {hit} / 错 {miss} / 没给 {noans}(共 {total})")
print(f" 答案准确率 {hit / total * 100:.1f}%(分母含没给的,保守口径)")
give = hit + miss
if give:
print(f" 给出答案时的准确率 {hit / give * 100:.1f}%")
print(f" 误判率 {miss / total * 100:.1f}% ← 这个指标最重要")
if problems:
print("\n问题清单:")
for p in problems[:20]:
print(" -", p)
return 0
if __name__ == "__main__":
sys.exit(main())
+141
View File
@@ -0,0 +1,141 @@
# -*- coding: utf-8 -*-
"""把 results.jsonl 汇总成一份可读的评测报告(markdown)。
口径(重要,别把这几件事混为一谈):
切题率 = 至少切出 1 块的图片占比
题干可用率 = 块里有 ≥6 汉字、或算式带汉字 的占比(标题/页眉/纯图形不算)
可判率 = calc + choice 的块占比(其余是 manual,机器不判)
自算率 = calc 块里,答案由我们自己算出来(而不是抄卷面)的占比
一致率 = 有卷面答案且我们自算时,两边相同的占比(**不是准确率**,是交叉验证)
用法:python bench/report.py
"""
from __future__ import annotations
import json
import re
import statistics
from collections import Counter, defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
BENCH = ROOT / "data" / "bench"
RESULTS = BENCH / "results.jsonl"
META = BENCH / "meta.jsonl"
OUT = BENCH / "report.md"
GRADE = re.compile(r"([一二三四五六123456])年级")
CN_NUM = {"1": "一", "2": "二", "3": "三", "4": "四", "5": "五", "6": "六"}
HEADER = re.compile(r"班级|姓名|成绩|总分|题号|得分|装订|密封|第\s*\d+\s*页")
def load() -> tuple[list[dict], dict[str, dict]]:
rows = [json.loads(l) for l in RESULTS.open(encoding="utf-8") if l.strip()]
meta = {}
if META.exists():
for line in META.open(encoding="utf-8"):
if line.strip():
m = json.loads(line)
meta[m["id"]] = m
return rows, meta
def pct(a: int, b: int) -> str:
return f"{a}/{b}({a / b * 100:.1f}%)" if b else "0/0"
def main() -> int:
rows, meta = load()
if not rows:
print("没有结果,先跑 python bench/run.py")
return 1
imgs = len(rows)
ok_imgs = sum(1 for r in rows if r["ok"] and r["n_blocks"])
blocks = [b for r in rows for b in r["blocks"]]
nb = len(blocks)
if not nb:
print("一条题块都没有,看看是不是 API 报错")
return 1
header = sum(1 for b in blocks if HEADER.search(b["stem"] or ""))
stmt = sum(1 for b in blocks if b["stmt_ok"])
judgeable = sum(1 for b in blocks if b["judgeable"])
calc = [b for b in blocks if b["type"] == "calc"]
choice = [b for b in blocks if b["type"] == "choice"]
derived = sum(1 for b in calc if b["derived"])
agree_pairs = [b for b in calc if b["derived"] and b["page_answer"]]
agree = sum(1 for b in agree_pairs if b["agree"])
multi = sum(1 for b in calc if (b["stem"] or "").count("=") >= 3)
boxy = sum(1 for b in blocks if re.search(r"\bBox\b|□", b["stem"] or ""))
per_ms = [r["ms"] for r in rows if r["ms"]]
p50 = statistics.median(per_ms) if per_ms else 0
p90 = sorted(per_ms)[int(len(per_ms) * 0.9) - 1] if per_ms else 0
# 按年级/科目分组(关键词里带「X年级」「数学/语文」)
group = defaultdict(lambda: {"img": 0, "blocks": 0, "stmt": 0, "judge": 0})
for r in rows:
q = (meta.get(r["id"]) or {}).get("q", "")
g = GRADE.search(q)
gv = CN_NUM.get(g.group(1), g.group(1)) if g else "?"
key = f"{gv} | {'语文' if '语文' in q else ('数学' if '数学' in q else '?')}"
group[key]["img"] += 1
group[key]["blocks"] += r["n_blocks"]
group[key]["stmt"] += sum(1 for b in r["blocks"] if b["stmt_ok"])
group[key]["judge"] += sum(1 for b in r["blocks"] if b["judgeable"])
type_cnt = Counter(b["type"] or "?" for b in blocks)
lines = []
A = lines.append
A("# 拍题链路评测报告\n")
A(f"- 样本:**{imgs} 张**真实小学试卷图(来源见 `data/bench/meta.jsonl`,只用于内部评测)")
A(f"- 切题:{pct(ok_imgs, imgs)};共 **{nb} 个题块**,平均 {nb / imgs:.1f} 块/张")
A(f"- 单张耗时:中位 {p50 / 1000:.1f}s,P90 {p90 / 1000:.1f}s(含一次腾讯切题调用)\n")
A("## 一、四个硬指标\n")
A("| 指标 | 数值 | 说明 |")
A("|---|---|---|")
A(f"| 切题率 | {pct(ok_imgs, imgs)} | 至少切出 1 块 |")
A(f"| 题干可用率 | {pct(stmt, nb)} | 有≥6 汉字或「算式+汉字」,排除页眉 |")
A(f"| 可判率 | {pct(judgeable, nb)} | calc+choice,其余要孩子自评 |")
A(f"| 自算率 | {pct(derived, len(calc))} | calc 块里答案由我们自己算出的 |")
A(f"| 卷面一致率 | {pct(agree, len(agree_pairs))} | 有卷面答案的 calc 块,两边相同(交叉验证,≠准确率) |")
A("")
A(f"- 题型分布:{dict(type_cnt)}")
A(f"- 页眉/标题被当成题:{header}/{nb}({header / nb * 100:.1f}%)")
A(f"- 有 `Box`/`□` 占位残留:{boxy}/{nb}({boxy / nb * 100:.1f}%)")
A(f"- calc 块里含 ≥3 个「=」的(口算卡整块,目前不能自动算):{multi}/{len(calc)}")
A("")
A("## 二、按年级 × 科目\n")
A("| 年级 \\| 科目 | 图片 | 题块 | 题干可用 | 可判 |")
A("|---|---|---|---|---|")
for k in sorted(group):
g = group[k]
A(f"| {k} | {g['img']} | {g['blocks']} | {pct(g['stmt'], g['blocks'])} | {pct(g['judge'], g['blocks'])} |")
A("")
A("## 三、最典型的 8 个坏块(人工看一眼就知道问题在哪)\n")
bad = [b for b in blocks if not b["stmt_ok"]][:8]
for b in bad:
A(f"- `{b['type'] or '?'}` {b['stem'][:80]!r}")
A("")
A("## 四、结论与下一步\n")
A("1. 切题不是瓶颈,**题干干净度**才是:页眉被当题、图形题只剩符号、`Box` 残留都要在切题后处理。")
A("2. 小学低年级卷子以填空/看图为主,`manual` 占大头是正常的——产品上要靠「孩子自评」,不能承诺机器判。")
A("3. 口算卡已经能逐题算:按 `=` 拆成小题、三步连算整串求值,自算率从 0% 到了 95.9%。")
A("4. 剩下的错集中在「极短算式被读错」(`0+0` 读成 `6+0`)和图形题符号化,不是判题逻辑的问题。")
A("5. 卷面一致率只能做交叉验证;真实误判率看第五节的人工金标(当前 0%,样本只有 83 道,还要扩)。")
A("")
OUT.write_text("\n".join(lines), encoding="utf-8")
print(f"已写 {OUT}")
print("\n".join(lines[:24]))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+140
View File
@@ -0,0 +1,140 @@
# -*- 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 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("--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 not files:
print("没有图片,先跑 python bench/fetch.py")
return 1
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
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)
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}
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
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())