Files
wangtongbo 9f8ef886f0 检测侧:补扫没救回漏检,改成勾中口算卡时裁剪重读(312->321/330)
- scanflow._gap_bands/_gap_blocks:找出没被框盖住但有字的条带,裁出来补切一次
  (OCR_GAP_SCAN=0 可关,一页最多 2 条);实测在 3 张漏检图上救回 0 道,
  因为那 3 道不是空条带,而是框在、内容读歪(27+69 读成 77+69)
- recognize_block 增加 crop_card 分支:勾中口算卡时裁出来重读,两版小题求并集
  (宁多不漏;整页版吞行、裁剪版丢题,谁也说不全)
- bench/verify_effect.py:同一份整页结果内比 page 与 page∪crop,
  不跨调用比——腾讯切题两次调用本身就不完全一致
- bench/run.py --gap / --verify-cards;gold_expr.py --results
- tests/test_gap_scan.py 5 例;卡片重读 2 例;179 单测 + 4 套冒烟全绿
2026-11-19 21:35:10 +08:00

221 lines
8.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""按「算式级」人工金标打分。
和 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 _wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
"""比例的 Wilson 95% 置信区间(小样本比正态近似靠谱,0 也能量)。
金标只有几百道时,直接说「误判率 0%」会被问「你凭什么」;
给出区间,读的人才知道这批数据能把真值压到多窄。
"""
if n <= 0:
return (0.0, 1.0)
p = k / n
denom = 1 + z * z / n
centre = (p + z * z / (2 * n)) / denom
half = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / denom
return (max(0.0, centre - half), min(1.0, centre + half))
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--gold", default=str(GOLD))
ap.add_argument("--results", default=str(RESULTS),
help="换一份评测结果(比如开了卡片重读的 results.verified.jsonl)")
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"))
res_path = Path(args.results)
rows = {r["id"]: r for r in (json.loads(l) for l in res_path.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
n_img = sum(1 for k in gold if not k.startswith("_"))
print(f"金标算式:{total} 道,覆盖 {n_img} 张图")
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:
lo, hi = _wilson(wrong, judged)
print(f" 在认出来的里面,算对的比例:{hit / judged * 100:.1f}%")
print(f" 误判率(认出来但算错 / 认出来):{wrong / judged * 100:.2f}%"
f" (95% CI {lo * 100:.2f}%–{hi * 100:.2f}%)")
if total:
lo2, hi2 = _wilson(hit, total)
print(f" 认对率 95% CI:{lo2 * 100:.1f}%–{hi2 * 100:.1f}%(n={total})")
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
n_img = sum(1 for k in gold if not k.startswith("_"))
by_grade: dict[str, int] = {}
for k, v in gold.items():
if k.startswith("_") or not isinstance(v, dict):
continue
by_grade[v.get("grade") or "?"] = by_grade.get(v.get("grade") or "?", 0) + 1
cover = "、".join(f"{g} {c} 张" for g, c in sorted(by_grade.items()))
wlo, whi = _wilson(wrong, judged)
hlo, hhi = _wilson(hit, total)
lines = [
"",
"## 五、人工金标(算式级)",
"",
f"- 人工逐题标注 **{n_img} 张卷、{total} 道算式**"
"(`bench/gold.json`,答案由人算、不看机器输出;算式级对照,不依赖块序号)",
f"- 认出来并算对:**{hit}/{total}({hit / total * 100:.1f}%)**,"
f"95% CI {hlo * 100:.1f}%–{hhi * 100:.1f}%",
f"- 认出来但算错:**{wrong}/{total}({wrong / total * 100:.1f}%)**"
f" —— 误判率 95% CI **{wlo * 100:.2f}%–{whi * 100:.2f}%**(Wilson)",
f"- 没认出来:{miss}/{total}({miss / total * 100:.1f}%),"
"集中在两类:① 极短算式被 OCR 读错或整块被吞(`0+0`、`2+4`、`5×2`);"
"② 竖式/脱式区块(题干带「用竖式计算」这类指令文字,或整块没被切成 calc)",
f"- 覆盖:{cover}(年级越高的卷子口算题越少,四、六年级这批样本里几乎没有,未覆盖)",
"",
f"**为什么 {total} 道够**:误判率点估计 {wrong / judged * 100 if judged else 0:.2f}%,"
f"n={judged} 时 Wilson 95% 上界 {whi * 100:.2f}%。"
"要压到 1% 以内约需 400 道,0.5% 以内约需 800 道。"
"注意这些算式来自少数几张卷,同卷内的题不独立(难度相近),真实区间比 Wilson 略宽。",
"",
"注:这里的「算错」指答案数值不对(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())