diff --git a/backend/README.md b/backend/README.md index 431e5bd..4cb7307 100644 --- a/backend/README.md +++ b/backend/README.md @@ -648,3 +648,22 @@ python tools/backfill_kp.py --apply # 真写 `checks`(本次勾选,0/1)。 - 没过一样会带 `ask_stuck_at` 与 `retreat`,和打字那条路完全一致。 + +### 四点二十九、变式自校验与严档(`variant_pending`) + +`practice.verify(item) -> (ok, reason)`:变式必须能算、答案和题干一致、选择题答案在选项里, +否则从 `similar()` 的结果里剔掉(宁缺勿错)。 + +严档(`children.strict_variant=1`)下的状态机: + +| 发生什么 | 结果 | +| --- | --- | +| 原题做对 | `variant_pending`,`next_due` 当天,界面提示「换一道」 | +| 变式做对 | `passed_once`,按第 1 档间隔排下一次 | +| 变式做错 | `queued`,间隔归零,`wrong_count+1`,错因 `E2` | + +`attempt(..., is_variant=True)` 只在 `status == "variant_pending"` 时接受, +否则 409 `NOT_VARIANT_PENDING`;反过来 `variant_pending` 下不带 `variant` 会 409 `NEED_VARIANT`。 +`is_due()` 也认 `variant_pending`,所以上次没验完的变式今天还会排回来。 + +接口:`POST /api/children//settings {"strict_variant": 1|0}`。 diff --git a/backend/app.py b/backend/app.py index cbc7ae0..01c5bc9 100644 --- a/backend/app.py +++ b/backend/app.py @@ -382,7 +382,8 @@ def _child_id(ctx: Ctx) -> str: def post_attempt(ctx: Ctx, mid: str, **kw): return svc.attempt(ctx.conn, ctx.gid, _child_id(ctx), mid, str(ctx.body.get("answer") or ""), - ctx.body.get("cost_ms")) + ctx.body.get("cost_ms"), + is_variant=bool(ctx.body.get("variant"))) @route("POST", r"/api/mistakes/(?P[^/]+)/self-judge", auth="child_ok") @@ -415,6 +416,12 @@ def post_explain(ctx: Ctx, mid: str, **kw): audio_ext=ctx.body.get("audio_ext") or None) +@route("POST", r"/api/children/(?P[^/]+)/settings", auth="parent") +def post_settings(ctx: Ctx, cid: str, **kw): + """严档开关:打开后第二次要做对一道没见过的变式。""" + return svc.set_settings(ctx.conn, ctx.gid, cid, ctx.body.get("strict_variant")) + + @route("POST", r"/api/mistakes/(?P[^/]+)/stuck", auth="child_ok") def post_stuck(ctx: Ctx, mid: str, **kw): """讲清失败后记「卡在哪」:read / plan / calc / check。""" diff --git a/backend/db.py b/backend/db.py index 8ba64cb..07dfc58 100644 --- a/backend/db.py +++ b/backend/db.py @@ -282,7 +282,8 @@ def _migrate(conn: sqlite3.Connection) -> None: "guardians": {"phone": "TEXT"}, "papers": {"clean_path": "TEXT", "image_path": "TEXT"}, # 小狮的形态与「今天喂过没有」要跨设备一致,所以落库(原来只在浏览器算出来) - "children": {"pet_stage": "INTEGER NOT NULL DEFAULT 0", "pet_fed_at": "TEXT"}, + "children": {"pet_stage": "INTEGER NOT NULL DEFAULT 0", "pet_fed_at": "TEXT", + "strict_variant": "INTEGER NOT NULL DEFAULT 0"}, } for table, cols in want.items(): ensure_columns(conn, table, cols) diff --git a/backend/practice.py b/backend/practice.py index b491771..490b4a9 100644 --- a/backend/practice.py +++ b/backend/practice.py @@ -88,6 +88,41 @@ def _math_variants(stem: str, n: int) -> list[dict]: return results +def verify(item: dict) -> tuple[bool, str]: + """一道变式能不能给孩子做:能算出唯一答案,且答案就是它自己给的那个。 + + 出错的变式比不做更糟——孩子按对的做反而被判错,一次就毁掉信任。 + """ + stem = str(item.get("stem") or "").strip() + answer = str(item.get("answer") or "").strip() + jt = item.get("judge_type") + if not stem: + return False, "题干是空的" + if not answer: + return False, "没有答案" + if jt == "calc": + # 「36 + 24 =」末尾那个等号要先去掉:safe_eval 会把 = 右边当答案取值 + expr = stem.rstrip("==").strip() + got = judging.safe_eval(expr) + if got is None: + return False, "算不出来" + want = judging.to_qty(answer) + if want is None: + return False, "答案不是数" + if abs(float(got) - float(want)) > 1e-6: + return False, "答案和题干对不上" + return True, "" + if jt == "choice": + opts = item.get("options") or {} + if isinstance(opts, dict) and len(opts) >= 2: + letters = {k.strip().upper() for k in opts} + if answer.strip().upper() not in letters: + return False, "答案不在选项里" + return True, "" + # 填空/问答:答案非空就放;判分靠孩子自评,不假装能验 + return True, "" + + def similar(stem: str, answer: str, judge_type: str, subject: str, grade: int, n: int = 3) -> list[dict]: """返回 n 道同类题;每道都带确定答案。""" items: list[dict] = [] @@ -104,6 +139,8 @@ def similar(stem: str, answer: str, judge_type: str, subject: str, grade: int, n continue items.append({"stem": q["stem"], "answer": q["answer"], "judge_type": q["judge_type"], "options": q.get("options"), "tag": "同知识点变式"}) + # 自校验:算不出答案、答案和题干对不上、选择题选项不干净 —— 一律不给 + items = [it for it in items if verify(it)[0]] for it in items: it.setdefault("subject", subject) it.setdefault("tag", "同类变式") diff --git a/backend/scheduler.py b/backend/scheduler.py index dc98053..2376b10 100644 --- a/backend/scheduler.py +++ b/backend/scheduler.py @@ -27,6 +27,7 @@ STATUS_ZH = { "queued": "待复习", "unstable": "会但不稳", "passed_once": "已对 1 次", + "variant_pending": "换一道", "to_explain": "待讲清", "graduated": "已毕业", "careless": "粗心小记", @@ -48,7 +49,8 @@ def is_due(mistake: dict, on: str | None = None) -> bool: 观察中的题也会在次日回来「复核」一次:做对就是粗心,做错才确认没懂。 不稳的题同样回到队列:今天错、今天对的,明天必须再做对一次才算过。 """ - if mistake.get("status") not in ("observing", "queued", "unstable", "passed_once"): + if mistake.get("status") not in ("observing", "queued", "unstable", "passed_once", + "variant_pending"): return False due = mistake.get("next_due") return bool(due) and due <= (on or today()) @@ -62,12 +64,16 @@ def due_today(mistakes: list[dict], on: str | None = None, cap: int = DAILY_CAP) def on_attempt(mistake: dict, correct: bool, *, created_at: str | None = None, - same_day_wrong: bool = False) -> dict: + same_day_wrong: bool = False, strict: bool = False, + is_variant: bool = False) -> dict: """做了一次(重做/口答)。返回要写回 mistakes 的字段。 :param same_day_wrong: 这道题「今天」已经错过一次。看完解析当场再做对, 只能说明「听完会了」,说明不了「记住了」——所以不推进档位, 只记一道「会但不稳」,明天再从头做对一次才算第一次。 + :param strict: 严档。打开后,第一次做对不算数——先换一道**没见过**的变式 + (`variant_pending`),变式做对才算第一次连对。默认关闭。 + :param is_variant: 这一次做的是变式题(不是原题)。 """ ts = created_at or now() stage = int(mistake.get("stage") or 0) @@ -93,6 +99,23 @@ def on_attempt(mistake: dict, correct: bool, *, created_at: str | None = None, "unstable_count": int(mistake.get("unstable_count") or 0) + 1, "wrong_code": mistake.get("wrong_code") or "E4", } + if strict: + if status == "variant_pending": + # 变式做对了:这才是「换一层皮还会」,算第一次连对 + stage = max(stage, 1) + interval = INTERVALS[min(stage - 1, len(INTERVALS) - 1)] + return {"status": "passed_once", "stage": stage, "interval_days": interval, + "next_due": add_days(interval, base=_date_of(ts)), + "wrong_code": mistake.get("wrong_code") or "E4"} + if is_variant: + # 变式做错了:说明还是没懂,回队列(间隔归零) + return {"status": "queued", "stage": 0, "interval_days": 1, + "next_due": add_days(1, base=_date_of(ts)), + "wrong_count": wrong_count + 1, "wrong_code": "E2"} + # 原题做对但还没验过变式:今天就给一道,别等到明天 + return {"status": "variant_pending", "stage": 0, "interval_days": 0, + "next_due": _date_of(ts), "wrong_code": mistake.get("wrong_code") or "E4"} + stage += 1 interval = INTERVALS[min(stage - 1, len(INTERVALS) - 1)] if stage >= 2: diff --git a/backend/services.py b/backend/services.py index 0ff2610..6a7b515 100644 --- a/backend/services.py +++ b/backend/services.py @@ -950,7 +950,8 @@ def _pet_sync(conn, cid: str) -> dict: "graduated": graduated, "left_today": left} -def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int | None = None) -> dict: +def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int | None = None, + is_variant: bool = False) -> dict: get_child(conn, gid, cid) m = conn.execute("SELECT * FROM mistakes WHERE id=? AND child_id=?", (mid, cid)).fetchone() _need(m, "NO_MISTAKE", "没有这道错题") @@ -965,7 +966,15 @@ def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int | same_day_wrong = conn.execute( "SELECT 1 FROM attempts WHERE mistake_id=? AND is_correct=0" " AND substr(created_at,1,10)=? LIMIT 1", (mid, today())).fetchone() is not None - state = scheduler.on_attempt(mdict, correct, same_day_wrong=same_day_wrong) + # 严档:这道题现在是「等一道变式」,那这次必须做的是变式才算数 + if is_variant and mdict["status"] != "variant_pending": + raise ApiError(409, "NOT_VARIANT_PENDING", "这道题现在不需要做变式") + if mdict["status"] == "variant_pending" and not is_variant: + raise ApiError(409, "NEED_VARIANT", "这道题要先做对一道变式") + child = get_child(conn, gid, cid) + strict = bool((child.get("strict_variant") if isinstance(child, dict) else 0) or 0) + state = scheduler.on_attempt(mdict, correct, same_day_wrong=same_day_wrong, + strict=strict, is_variant=is_variant) with tx(conn): conn.execute("INSERT INTO attempts (id, mistake_id, child_id, answer_text, is_correct, cost_ms, created_at)" " VALUES (?,?,?,?,?,?,?)", @@ -976,6 +985,7 @@ def attempt(conn, gid: str, cid: str, mid: str, answer_text: str, cost_ms: int | return { "mistake_id": mid, "pet": pet, + "need_variant": state["status"] == "variant_pending", "correct": correct, "detail": detail, # 答完才能给答案:讲解要照着它生成步骤,之前不给是为了不让孩子提前看 @@ -1111,6 +1121,16 @@ STUCK_AT = { } +def set_settings(conn, gid: str, cid: str, strict_variant=None) -> dict: + """孩子级设置。目前只有一个:「严档」——第二次要做对一道没见过的变式。""" + get_child(conn, gid, cid) + if strict_variant is not None: + conn.execute("UPDATE children SET strict_variant=? WHERE id=?", + (1 if str(strict_variant) in ("1", "true", "True", "on") else 0, cid)) + row = conn.execute("SELECT strict_variant FROM children WHERE id=?", (cid,)).fetchone() + return {"child_id": cid, "strict_variant": int((row["strict_variant"] if row else 0) or 0)} + + def set_stuck_at(conn, gid: str, cid: str, mid: str, value) -> dict: """记一次卡点。只在讲清失败后问,入库时不问(避免每道题都弹一次)。""" get_child(conn, gid, cid) diff --git a/prototype/workbench/README.md b/prototype/workbench/README.md index 0cf8355..0328f60 100644 --- a/prototype/workbench/README.md +++ b/prototype/workbench/README.md @@ -306,3 +306,16 @@ OCR 缓存,所以预览过一遍之后,正式入库不会再花一次调用 这一版先保证「不打字也能提交」,等语音识别的错字率降下来再收紧成机器判。 - 浏览器不支持 `MediaRecorder` 时按钮会提示,不影响打字那条路。 + +## 十七、严档:第二次换一道 + +默认的毕业标准是「同一道题第二次做对」。严档把它换成「换一道没见过的同类题做对」—— +因为同题第二次常常只是记住了答案。 + +- 开关位置:设置 → 严档(默认关)。打开后写进 `children.strict_variant`。 +- 状态:原题做对 → `variant_pending`(界面显示「换一道」)→ 变式做对才 `passed_once`。 +- 界面:进训练页时如果这道题在 `variant_pending`,只保留下面那道变式的输入框, + 原题题干留着当上下文,不让孩子对着原题再写一遍。 +- 变式从哪来:`practice.similar()`,出题后过一遍 `practice.verify()` + (能算、答案和题干一致、选择题答案在选项里),过不了的**丢弃**——出错的变式比不练更糟。 +- 代价:1–3 年级的变式是换数字(近迁移),4–6 年级还没有换情境的题库,所以目前不分档。 diff --git a/prototype/workbench/index.html b/prototype/workbench/index.html index 4e4e62e..4c7cb7e 100644 --- a/prototype/workbench/index.html +++ b/prototype/workbench/index.html @@ -925,6 +925,8 @@ td .t{font-family:"Consolas",monospace;font-size:13.5px}
语文
听写、看拼音写词、笔顺
+
严档
第二次要做对一道没见过的题(默认关)
+
照片留存
90 天后自动删除
@@ -1284,6 +1286,9 @@ const STATUS_CLS = { graduated: "g", to_explain: "c", unstable: "o", careless: " function renderAll() { setTimeout(() => petRender(), 0); + // 严档开关跟着孩子走(切孩子时要跟着变) + const st = document.getElementById("setStrict"); + if (st) st.classList.toggle("on", !!(S.kid && S.kid.strict_variant)); const k = S.kid || DEMO.child; document.getElementById("kidName").textContent = k.nickname || "皮皮"; document.getElementById("kidGrade").textContent = (GRADE[(k.grade || 2) - 1] || "二") + "年级"; @@ -1364,6 +1369,16 @@ function renderTrain() { document.getElementById("qAnalysis").classList.remove("show"); document.getElementById("qVariant").classList.remove("show"); buildAnalysis(q); + // 上次做对了原题、还没验变式就走了:这次进来就直接验变式 + if (q.status === "variant_pending") { + S.variantStrict = true; + // 只留变式那条输入框,别让孩子对着原题再写一遍 + document.getElementById("qAnswerRow").style.display = "none"; + document.getElementById("btnSubmit").style.display = "none"; + loadVariant(q); + } else { + S.variantStrict = false; + } } /* 选择题:A/B/C/D 四个按钮;非选择题把选项区清空、露出输入框 */ @@ -1903,7 +1918,7 @@ async function submit() { } } else { try { - const r = await api(`/api/mistakes/${q.id}/attempt`, { method: "POST", body: { child_id: S.cid, answer: val } }); + const r = await api(`/api/mistakes/${q.id}/attempt`, { method: "POST", body: { child_id: S.cid, answer: val, variant: !!S.variantStrict } }); correct = r.correct; detail = r.detail || ""; unstableHint = r.unstable_hint || null; nextStatus = r.status || ""; @@ -1931,6 +1946,12 @@ async function submit() { // 当天错了又对:不装作过了,也不打击——说清楚「明天再来一次」 box.className = "result mid"; box.innerHTML = `会了,但还不稳
${esc(unstableHint)}`; + } else if (nextStatus === "variant_pending") { + // 严档:原题做对了不算数,先做对一道没见过的(下面那张变式卡会顶上来) + box.className = "result mid"; + box.innerHTML = `对了,但先别走
换一道同类的,做对才算真的会。 +
`; + S.variantStrict = true; } else if (nextStatus === "to_explain") { // 连对两次,到了「讲一遍」这一步——就地把入口放在结果里,不用回去翻错题本 box.className = "result mid"; @@ -2465,14 +2486,52 @@ document.getElementById("qInput").addEventListener("keydown", e => { if (e.key = document.getElementById("btnNext").addEventListener("click", nextQ); document.getElementById("btnPrev").addEventListener("click", () => { if (S.idx > 0) { S.idx--; renderTrain(); renderSheet(); } }); document.getElementById("btnSkip").addEventListener("click", () => nextQ()); -document.getElementById("btnVCheck").addEventListener("click", () => { +document.getElementById("btnVCheck").addEventListener("click", async () => { const v = S.variant; if (!v) return; - const ok = norm(document.getElementById("vInput").value) === norm(v.answer); - document.getElementById("vResult").innerHTML = ok + const val = document.getElementById("vInput").value; + const out = document.getElementById("vResult"); + // 严档:这一道是用来验「换一层皮还会不会」的,答案要交给后端判、并且记进队列 + if (S.variantStrict) { + const q = curQ(); + if (!q) return; + try { + const r = await api(`/api/mistakes/${q.id}/attempt`, + { method: "POST", body: { child_id: S.cid, answer: val, variant: true } }); + if (r.correct) { + out.innerHTML = `✓ 换一道也做对了——这才是真的会,明天再来一次。`; + S.variantStrict = false; + } else { + out.innerHTML = `✗ ${esc(r.detail || "这道没对")}:明天回来再做一次。`; + S.variantStrict = false; + } + refresh(); + } catch (e) { + out.innerHTML = `没交上:${esc(e.message)}`; + } + return; + } + const ok = norm(val) === norm(v.answer); + out.innerHTML = ok ? `✓ 对了,这类题你会了` : `✗ 再看一眼:答案是 ${esc(v.answer)}`; }); document.getElementById("btnVNext").addEventListener("click", () => { const q = curQ(); if (q) loadVariant(q, true); }); +document.getElementById("btnGoVariant") && document.getElementById("btnGoVariant").addEventListener("click", () => { + const q = curQ(); if (q) loadVariant(q); + document.getElementById("btnGoVariant").disabled = true; +}); +// 设置:严档开关(孩子级,存后端) +document.getElementById("setStrict").addEventListener("click", async () => { + const el = document.getElementById("setStrict"); + const on = !el.classList.contains("on"); + el.classList.toggle("on", on); + if (S.demo) { S.kid = Object.assign(S.kid || {}, { strict_variant: on ? 1 : 0 }); toast(on ? "演示:严档已打开" : "演示:严档已关闭"); return; } + try { + const r = await api(`/api/children/${S.cid}/settings`, { method: "POST", body: { child_id: S.cid, strict_variant: on ? 1 : 0 } }); + S.kid = Object.assign(S.kid || {}, { strict_variant: r.strict_variant }); + toast(r.strict_variant ? "严档已打开:第二次要做对一道没见过的题" : "已改回默认:同题第二次做对即可"); + } catch (e) { el.classList.toggle("on", !on); toast("没改成:" + e.message); } +}); document.getElementById("wrongChips").addEventListener("click", (e) => { const b = e.target.closest("button"); if (!b) return; S.wrongFilter = b.dataset.s; diff --git a/report/预览-严档-换一道.png b/report/预览-严档-换一道.png new file mode 100644 index 0000000..bfd34d7 Binary files /dev/null and b/report/预览-严档-换一道.png differ diff --git a/report/预览-严档-设置.png b/report/预览-严档-设置.png new file mode 100644 index 0000000..17c5db3 Binary files /dev/null and b/report/预览-严档-设置.png differ diff --git a/tests/smoke_login.py b/tests/smoke_login.py index bc731b1..0e38097 100644 --- a/tests/smoke_login.py +++ b/tests/smoke_login.py @@ -64,7 +64,7 @@ try: st, r = call("GET", "/api/health") check("health 200", st == 200, r) - check("routes=61", r["data"]["routes"] == 61, r["data"].get("routes")) + check("routes=62", r["data"]["routes"] == 62, r["data"].get("routes")) st, r = call("POST", "/api/auth/sms-code", {"phone": "13800138000"}) check("发码 200", st == 200 and r["data"]["sent"] is True, r) diff --git a/tests/smoke_manual.py b/tests/smoke_manual.py index 812dae4..9baf468 100644 --- a/tests/smoke_manual.py +++ b/tests/smoke_manual.py @@ -63,7 +63,7 @@ try: st, r = call("GET", "/api/health") check("health 200", st == 200, r) - check("routes=61", r["data"]["routes"] == 61, r["data"].get("routes")) + check("routes=62", r["data"]["routes"] == 62, r["data"].get("routes")) st, r = call("POST", "/api/auth/wx-login", {"code": "demo"}) tok = r["data"]["token"] diff --git a/tests/test_w6.py b/tests/test_w6.py new file mode 100644 index 0000000..4344b7d --- /dev/null +++ b/tests/test_w6.py @@ -0,0 +1,114 @@ +"""W6:变式自校验 + 严档毕业。""" +import unittest + +import backend.db as dbm +import backend.practice as practice +import backend.services as svc +from backend.services import ApiError +from ._tmpdir import workdir + + +class VerifyTest(unittest.TestCase): + def test_good_calc(self): + ok, why = practice.verify({"stem": "36 + 24 =", "answer": "60", "judge_type": "calc"}) + self.assertTrue(ok, why) + + def test_wrong_answer_rejected(self): + ok, why = practice.verify({"stem": "36 + 24 =", "answer": "61", "judge_type": "calc"}) + self.assertFalse(ok) + self.assertIn("对不上", why) + + def test_uncomputable_rejected(self): + ok, _ = practice.verify({"stem": "一个数加 3 等于几?", "answer": "5", "judge_type": "calc"}) + self.assertFalse(ok) + + def test_empty_answer_rejected(self): + ok, why = practice.verify({"stem": "36 + 24 =", "answer": "", "judge_type": "calc"}) + self.assertFalse(ok) + self.assertIn("没有答案", why) + + def test_choice_answer_must_be_in_options(self): + ok, _ = practice.verify({"stem": "哪个对?", "answer": "E", "judge_type": "choice", + "options": {"A": "1", "B": "2"}}) + self.assertFalse(ok) + ok2, _ = practice.verify({"stem": "哪个对?", "answer": "B", "judge_type": "choice", + "options": {"A": "1", "B": "2"}}) + self.assertTrue(ok2) + + def test_similar_only_returns_verified(self): + items = practice.similar("36 + 47 =", "83", "calc", "math", 2, n=3) + for it in items: + self.assertTrue(practice.verify(it)[0], it) + + +class StrictBase(unittest.TestCase): + def setUp(self): + self.conn = dbm.connect(workdir("w6") / (self._testMethodName + ".db")) + dbm.init_db(self.conn) + self.gid = svc.login(self.conn, "demo")["guardian_id"] + svc.give_consent(self.conn, self.gid, "v1") + self.cid = svc.create_child(self.conn, self.gid, "皮皮", 2)["id"] + + def tearDown(self): + self.conn.close() + + def _queued(self, stem="36 + 47 ="): + import backend.judging as judging + ans = judging.fmt_qty(judging.safe_eval(stem.rstrip("== "))) + r = svc.add_manual_mistake(self.conn, self.gid, self.cid, "math", stem, ans) + mid = r["created"][0]["mistake_id"] + for _ in range(3): + self.conn.execute("UPDATE mistakes SET next_due=? WHERE id=?", (svc.today(), mid)) + svc.attempt(self.conn, self.gid, self.cid, mid, "999") + # 隔一天再做对:否则会先命中「当天错了又对 → 会但不稳」,走不到严档分支 + svc.dev_advance(self.conn, 1) + return mid + + def _ans(self, mid): + return self.conn.execute("SELECT answer FROM mistakes WHERE id=?", (mid,)).fetchone()["answer"] + + def _strict(self, on=True): + return svc.set_settings(self.conn, self.gid, self.cid, 1 if on else 0)["strict_variant"] + + +class StrictFlowTest(StrictBase): + def test_strict_requires_variant_before_passed_once(self): + mid = self._queued() + self.assertEqual(self._strict(), 1) + r = svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid)) + self.assertEqual(r["status"], "variant_pending") + self.assertTrue(r["need_variant"]) + # 变式做对 → 才算第一次 + r2 = svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid), is_variant=True) + self.assertEqual(r2["status"], "passed_once") + + def test_variant_wrong_resets(self): + mid = self._queued("52 + 39 =") + self._strict() + svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid)) + r = svc.attempt(self.conn, self.gid, self.cid, mid, "999", is_variant=True) + self.assertEqual(r["status"], "queued") + self.assertFalse(r["correct"]) + + def test_default_off_keeps_old_behaviour(self): + mid = self._queued("18 + 27 =") + r = svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid)) + self.assertEqual(r["status"], "passed_once") + + def test_cannot_fake_variant(self): + mid = self._queued("66 + 18 =") + with self.assertRaises(ApiError) as ctx: + svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid), is_variant=True) + self.assertEqual(ctx.exception.code, "NOT_VARIANT_PENDING") + + def test_pending_requires_variant_flag(self): + mid = self._queued("77 + 16 =") + self._strict() + svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid)) + with self.assertRaises(ApiError) as ctx: + svc.attempt(self.conn, self.gid, self.cid, mid, self._ans(mid)) + self.assertEqual(ctx.exception.code, "NEED_VARIANT") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/check_variants.py b/tools/check_variants.py new file mode 100644 index 0000000..fd4ee5f --- /dev/null +++ b/tools/check_variants.py @@ -0,0 +1,66 @@ +"""变式自校验抽样:跑 100 道题,看 practice.verify 拦下多少、留下来的有没有算错的。 + +独立重算不调用 judging:直接按 "a op b" 用 Fraction 算,和变式自己带的答案比。 +""" +import json +import re +from fractions import Fraction + +import backend.practice as practice + +OP = {"+": 1, "-": -1, "×": 0, "x": 0, "X": 0, "*": 0, "÷": 2, "/": 2} +TERM = re.compile(r"(-?\d+(?:\.\d+)?)\s*([+\-×xX*÷/])\s*(-?\d+(?:\.\d+)?)") + + +def independent(expr): + m = TERM.fullmatch(expr.strip()) + if not m: + return None + a, op, b = Fraction(m.group(1)), m.group(2), Fraction(m.group(3)) + if op == "+": + return a + b + if op == "-": + return a - b + if op in "×xX*": + return a * b + return None if b == 0 else a / b + + +def stems(): + out = [] + p = "data/bench/results.jsonl" + for line in open(p, encoding="utf-8"): + try: + rec = json.loads(line) + except ValueError: + continue + for b in rec.get("blocks") or []: + if b.get("type") == "calc" and b.get("stem") and b.get("derived"): + out.append((b["stem"], b.get("answer") or "")) + return out + + +def main(): + pool = stems()[:100] + kept = rejected = 0 + bad = [] + for stem, ans in pool: + for it in practice.similar(stem, ans, "calc", "math", 2, n=3): + kept += 1 + want = independent(it["stem"]) + if want is None: + continue + if abs(float(want) - float(it["answer"])) > 1e-9: + bad.append((it["stem"], it["answer"], float(want))) + # 反向:被 verify 拦掉的不统计(它们没进来) + # 再跑一遍原始生成(不经 verify),看 verify 总共拦了多少 + raw = 0 + for stem, ans in pool: + raw += len(practice._math_variants(stem, 3)) if "×" in stem or True else 0 + print(f"题样 {len(pool)} 道;生成变式 {raw} 道;通过自校验 {kept} 道;独立重算不符 {len(bad)} 道") + for x in bad[:5]: + print(" 不符:", x) + + +if __name__ == "__main__": + main()