Files
cuotibiye/backend/kp_graph.py
T

133 lines
4.8 KiB
Python
Raw 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.
# -*- coding: utf-8 -*-
"""迷你先修图:讲不清的时候,往前退一层。
为什么要有它:现在的闭环里,一道题讲不清 → 换个说法再讲 → 还不过 → 7 天后再来。
但如果孩子讲不清的原因是**前置知识缺了**(比如「两位数乘两位数」讲不清,其实是
「表内乘法」不熟),再讲十遍这道题也不会过,闭环就在这儿空转。
这个模块只回答三个问题:
1. 这道题的知识点,前置是什么?(`parents`)
2. 讲不清时该退到哪?(`retreat` → 标 hard 的前置里,年级最高的那个)
3. 为什么是它?(每条边都写了 `reason`,家长点开能看到人话)
数据:`data/kp_graph.json`(小学 1–3 年级数学,id 与工作台 kpt.json 一致)。
只做「退一层」,不做自适应诊断、不做全学段——错了的边只会影响建议,
不影响判分和毕业,所以不需要教师逐条审核就能上线。
"""
from __future__ import annotations
import json
from functools import lru_cache
from pathlib import Path
GRAPH_PATH = Path(__file__).resolve().parent.parent / "data" / "kp_graph.json"
@lru_cache(maxsize=1)
def _load() -> tuple[dict, dict]:
raw = json.loads(GRAPH_PATH.read_text(encoding="utf-8"))
topics = {t["id"]: t for t in raw["topics"]}
parents: dict[str, list[dict]] = {}
for e in raw["edges"]:
parents.setdefault(e["topicId"], []).append({
"id": e["prerequisiteId"],
"strength": e["strength"],
"reason": e["reason"],
})
for lst in parents.values():
lst.sort(key=lambda x: (x["strength"] != "hard", -topics.get(x["id"], {}).get("grade", 0)))
return topics, parents
def topic(kp: str | None) -> dict | None:
"""知识点本身(没有就 None)。"""
if not kp:
return None
t = _load()[0].get(kp)
return dict(t) if t else None
def parents(kp: str, strength: str | None = None) -> list[dict]:
"""直接前置,hard 在前;每条带 name / grade / reason。"""
topics, par = _load()
out = []
for p in par.get(kp or "", []):
if strength and p["strength"] != strength:
continue
t = topics.get(p["id"]) or {}
out.append({"id": p["id"], "name": t.get("name", p["id"]), "grade": t.get("grade"),
"strength": p["strength"], "reason": p["reason"]})
return out
def chain(kp: str, limit: int = 4) -> list[dict]:
"""沿 hard 边一路往前退,返回从根到 kp 的顺序(去掉 kp 自己)。"""
topics, par = _load()
path: list[dict] = []
cur, seen = kp, {kp}
while cur and len(path) < limit:
hard = [p for p in par.get(cur, []) if p["strength"] == "hard"]
if not hard:
break
nxt = hard[0]["id"]
if nxt in seen:
break
seen.add(nxt)
t = topics.get(nxt) or {}
path.append({"id": nxt, "name": t.get("name", nxt), "grade": t.get("grade")})
cur = nxt
return list(reversed(path))
def retreat(kp: str | None) -> dict | None:
"""讲不清时该退到哪。没有知识点、或没有 hard 前置 → None(不给空建议)。"""
t = topic(kp)
if not t:
return None
hard = parents(kp, "hard")
if not hard:
return None
first = hard[0]
return {
"kp": kp,
"name": t["name"],
"step": {"id": first["id"], "name": first["name"], "grade": first["grade"]},
"reason": first["reason"],
"chain": chain(kp),
"tip": f"这道题讲不清,可能不是这道题的问题——先退到「{first['name']}」,"
f"做对两道再回来讲。",
}
def validate() -> list[str]:
"""自检:未知 id、环、前置年级比本节点还高。测试用它,别让图悄悄坏掉。"""
topics, par = _load()
errs: list[str] = []
for tid, lst in par.items():
if tid not in topics:
errs.append(f"边指向了不存在的知识点:{tid}")
for p in lst:
if p["id"] not in topics:
errs.append(f"{tid} 的前置 {p['id']} 不在 topics 里")
elif topics[p["id"]]["grade"] > topics[tid]["grade"]:
errs.append(f"{tid}({topics[tid]['grade']} 年级)的前置 {p['id']}"
f"({topics[p['id']]['grade']} 年级)年级更高")
# 环检测(沿 hard 边)
state: dict[str, int] = {}
def walk(node: str, stack: list[str]) -> None:
if state.get(node) == 1:
errs.append("成环:" + " → ".join(stack + [node]))
return
if state.get(node) == 2:
return
state[node] = 1
for p in par.get(node, []):
if p["strength"] == "hard":
walk(p["id"], stack + [node])
state[node] = 2
for tid in topics:
walk(tid, [])
return errs