解析自校验:425 道真题逐句重算,修掉三类算错(395 全对/0 错/30 退回通用)

This commit is contained in:
2026-11-21 21:07:54 +08:00
parent 82cc3adbcd
commit 924b4bee43
6 changed files with 2964 additions and 3 deletions
+65
View File
@@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
"""把评测语料里能算的题抽出来,喂给前端解析生成器做自校验。
输出 data/bench/plan_input.json:[{"stem": "...", "answer": "...", "src": "bench|db"}]
"""
import json
import sqlite3
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
BENCH = ROOT / "data" / "bench" / "results.jsonl"
DB = ROOT / "data" / "app.db"
OUT = ROOT / "data" / "bench" / "plan_input.json"
def from_bench():
out = []
if not BENCH.exists():
return out
for line in BENCH.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line:
continue
rec = json.loads(line)
if not rec.get("ok"):
continue
for b in rec.get("blocks") or []:
if b.get("type") in ("calc", "card") and b.get("answer") and b.get("stem"):
out.append({"stem": b["stem"], "answer": str(b["answer"]), "src": "bench",
"judge_type": b.get("type")})
return out
def from_db():
out = []
if not DB.exists():
return out
conn = sqlite3.connect(str(DB))
try:
rows = conn.execute("SELECT stem, answer, judge_type FROM questions").fetchall()
finally:
conn.close()
for stem, answer, jt in rows:
if answer and stem:
out.append({"stem": stem, "answer": str(answer), "src": "db", "judge_type": jt})
return out
def main():
items = from_bench() + from_db()
seen, uniq = set(), []
for it in items:
k = (it["stem"], it["answer"])
if k in seen:
continue
seen.add(k)
uniq.append(it)
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(uniq, ensure_ascii=False, indent=1), encoding="utf-8")
print(f"抽取 {len(uniq)} 道(bench {sum(1 for x in uniq if x['src'] == 'bench')},"
f"db {sum(1 for x in uniq if x['src'] == 'db')})→ {OUT}")
if __name__ == "__main__":
main()
+131
View File
@@ -0,0 +1,131 @@
// 解析自校验:把 425 道真实题喂给工作台的 calcPlan/fracPlan,逐句重算它说的话。
//
// 为什么要这样验:147 条模板是「文字」,题里的数字是前端按算式临时生成的。
// 模板写得对不对,看不出错;生成的那句话里数字算错,才是真错。
// 这个脚本只做一件事:解析里出现的每一个「a ○ b = c」都重算一遍,对不上就报。
//
// 用法:node tools/verify_plan.mjs
// 输出:data/plan_verify.md(明细)+ 控制台摘要
import { ensureBrowser, attach, navigate, evaluate } from "../collector/cdp.mjs";
import fs from "node:fs";
const ROOT = "D:/gitee/errortopic";
const OUT = `${ROOT}/data/plan_verify.md`;
const PORT = 9307;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const items = JSON.parse(fs.readFileSync(`${ROOT}/data/bench/plan_input.json`, "utf8"));
/* ---- 只认数字、运算符、括号的求值(不接受变量和函数) ---- */
function calc(expr) {
const s = String(expr).replace(/[×xX]/g, "*").replace(/÷/g, "/").replace(/−/g, "-");
if (!/^[\d+\-*/().\s]+$/.test(s)) return NaN;
try {
const v = Function(`"use strict";return (${s});`)();
return typeof v === "number" && isFinite(v) ? v : NaN;
} catch {
return NaN;
}
}
const near = (a, b) => Math.abs(a - b) < 1e-6 * Math.max(1, Math.abs(a), Math.abs(b));
/* ---- 分数与小数都按数值比 ---- */
function toNum(v) {
const s = String(v).trim();
const fr = s.match(/^(-?\d+)\s*\/\s*(\d+)$/);
if (fr) return Number(fr[1]) / Number(fr[2]);
const mix = s.match(/^(-?\d+)又(\d+)\/(\d+)$/);
if (mix) {
const sign = Number(mix[1]) < 0 ? -1 : 1;
return sign * (Math.abs(Number(mix[1])) + Number(mix[2]) / Number(mix[3]));
}
return Number(s.replace(/[^\d.\-]/g, ""));
}
const CLAIM = /(-?\d+(?:\.\d+)?)\s*([+\-−×÷*xX/])\s*(\d+(?:\.\d+)?)\s*=\s*(-?\d+(?:\.\d+)?)/g;
function badClaims(text, limit = 3) {
const out = [];
for (const m of String(text).matchAll(CLAIM)) {
const [, a, op, b, c] = m;
const want = calc(`${a}${op === "−" ? "-" : op}${b}`);
if (isNaN(want)) continue;
if (!near(want, toNum(c))) out.push({ claim: `${a}${op}${b}=${c}`, want });
if (out.length >= limit) break;
}
return out;
}
await ensureBrowser({ port: PORT, headless: true, width: 1200, height: 900 });
const { cdp } = await attach(PORT);
await navigate(cdp, `file:///${ROOT}/prototype/workbench/index.html`);
await sleep(800);
// 一次性把 425 道算完(在页面里跑,省得来回传)
const plans = JSON.parse(await evaluate(cdp, `
JSON.stringify(${JSON.stringify(items)}.map(it => {
let p = null;
try { p = calcPlan({ stem: it.stem, answer: it.answer }); } catch (e) { p = { error: String(e) }; }
return p ? { stem: it.stem, answer: it.answer, src: it.src,
know: p.know, idea: p.idea, steps: p.steps, traps: p.traps,
error: p.error || null } : null;
}))
`, { awaitPromise: true }));
const rows = [];
const stats = { total: items.length, noPlan: 0, claimBad: 0, answerBad: 0, errored: 0, skippedChoice: 0 };
plans.forEach((p, idx) => {
const it = items[idx] || {};
if (!p) { stats.noPlan++; rows.push({ stem: it.stem, answer: it.answer, kind: "无解析" }); return; }
if (p.error) { stats.errored++; rows.push({ stem: p.stem, kind: "抛错", note: p.error }); return; }
const text = [p.idea, ...(p.steps || []), p.traps].join("\n");
const bad = badClaims(text);
const body = String(p.stem).split("=")[0];
// 注意:先把 × ÷ 归一成 * /,再删掉其他字符——反过来做会把 × 一起删掉(60×9 变成 609)
const clean = body.replace(/[((]\s*[))]/g, "")
.replace(/[×xX]/g, "*").replace(/÷/g, "/")
.replace(/[^\d+\-*/().\s]/g, "");
const want = calc(clean);
const got = toNum(p.answer);
// 选择题(答案 A/B/C)、涂卡、多行糊在一起的块不算——那些不是这道脚本要管的事
const skip = isNaN(got) || /(\s*)/.test(p.stem) || /\n/.test(String(p.stem));
const answerBad = !skip && !isNaN(want) && !near(want, got);
if (answerBad) stats.skippedChoice += 0;
if (bad.length) {
stats.claimBad++;
rows.push({ stem: p.stem, answer: p.answer, kind: "算错", note: bad.map(b => `${b.claim}(应 ${b.want})`).join(";"), steps: p.steps });
} else if (answerBad) {
stats.answerBad++;
rows.push({ stem: p.stem, answer: p.answer, kind: "答案不符", note: `题干算出来是 ${want}` });
}
});
const okN = stats.total - stats.noPlan - stats.claimBad - stats.answerBad - stats.errored;
const lines = [];
lines.push("# 解析自校验");
lines.push("");
lines.push(`语料:${stats.total} 道(评测 ${items.filter(i => i.src === "bench").length} + 题库 ${items.filter(i => i.src === "db").length}),全部是机器能算出答案的题。`);
lines.push("");
lines.push("| 结果 | 道数 |");
lines.push("| --- | --- |");
lines.push(`| 三步全对(每个「a ○ b = c」都重算通过) | ${okN} |`);
lines.push(`| 句子里的算式算错 | ${stats.claimBad} |`);
lines.push(`| 题干与答案对不上 | ${stats.answerBad} |`);
lines.push(`| 生成器抛错 | ${stats.errored} |`);
lines.push(`| 根本没有解析(calcPlan 返回 null) | ${stats.noPlan} |`);
lines.push("");
if (rows.length) {
lines.push("## 明细(最多 40 条)");
lines.push("");
for (const r of rows.slice(0, 40)) {
lines.push(`- **${r.kind}** \`${r.stem}\` 答案 ${r.answer ?? "—"}`);
if (r.note) lines.push(` - ${r.note}`);
if (r.steps) r.steps.forEach((s, i) => lines.push(` ${i + 1}. ${s}`));
}
}
fs.writeFileSync(OUT, lines.join("\n"), "utf8");
console.log(JSON.stringify(stats, null, 0));
console.log("报告 →", OUT);
await cdp.send("Browser.close").catch(() => {});