180 lines
6.7 KiB
Python
180 lines
6.7 KiB
Python
"""按「算式级」人工金标打分。
|
||
|
||
和 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())
|