Spaces:
Sleeping
Sleeping
Precalculus Studio: placement, worked examples, retrieval quizzes, peer instruction (part 5)
1289247 verified Download src/edtech_core/learner_model.py from BenjaminKaindu0506/ed-tech-studio: direct link, hf CLI and curl.
- Browser
- Download file 7.25 kB
-
https://huggingface.co/spaces/BenjaminKaindu0506/ed-tech-studio/resolve/main/src/edtech_core/learner_model.py
- Command line
-
hf download hf://spaces/BenjaminKaindu0506/ed-tech-studio/src/edtech_core/learner_model.py
-
curl -L -o learner_model.py https://huggingface.co/spaces/BenjaminKaindu0506/ed-tech-studio/resolve/main/src/edtech_core/learner_model.py
7.25 kB
| """Per-learner state for retrieval practice: what's been covered, and a successive- | |
| relearning schedule per topic. Deterministic, JSON on disk, no LLM in the loop. | |
| Scheduling model (see ARCHITECTURE.md §Learning science): | |
| - Successive relearning (Rawson & Dunlosky 2011, 2018): a topic counts as successfully | |
| relearned in a quiz session when every item on it is answered correctly (criterion = | |
| one correct recall per session). Each success moves it one step up an expanding | |
| interval ladder (1, 3, 7, 21, 60 days); a miss drops it back to a 1-day interval. | |
| - After RELEARNING_SESSIONS_FOR_DURABLE spaced successes the topic is "durable" and is | |
| only revisited on its long interval (maintenance), mirroring the ~3-session finding. | |
| - Expanding gaps follow Cepeda et al. (2008): the optimal gap grows with the retention | |
| interval you care about. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import re | |
| from dataclasses import asdict, dataclass, field | |
| from datetime import datetime, timedelta, timezone | |
| from src.config import LEARNERS_DIR, RELEARNING_INTERVALS_DAYS, RELEARNING_SESSIONS_FOR_DURABLE | |
| from src.edtech_core.curriculum import TOPIC_BY_ID | |
| def _now() -> datetime: | |
| return datetime.now(timezone.utc) | |
| def _iso(dt: datetime) -> str: | |
| return dt.isoformat(timespec="seconds") | |
| class TopicMemory: | |
| attempts: int = 0 | |
| correct: int = 0 | |
| stage: int = 0 # consecutive spaced successes on the interval ladder | |
| spaced_successes: int = 0 | |
| last_reviewed: str | None = None | |
| due: str | None = None | |
| def current_interval_days(self) -> int: | |
| """Gap to the next review: 1 day after a miss/first success, then up the ladder.""" | |
| return RELEARNING_INTERVALS_DAYS[min(max(self.stage - 1, 0), len(RELEARNING_INTERVALS_DAYS) - 1)] | |
| def error_rate(self) -> float: | |
| return 1 - self.correct / self.attempts if self.attempts else 0.5 # unseen = uncertain | |
| def durable(self) -> bool: | |
| return self.spaced_successes >= RELEARNING_SESSIONS_FOR_DURABLE | |
| def overdue_ratio(self, now: datetime) -> float: | |
| """>0 means due/overdue, scaled by the current interval (1.0 = one interval late).""" | |
| if not self.due: | |
| return 1.0 # covered but never quizzed → due now | |
| late_days = (now - datetime.fromisoformat(self.due)).total_seconds() / 86400 | |
| return late_days / self.current_interval_days | |
| class LearnerState: | |
| learner_id: str | |
| covered: list[str] = field(default_factory=list) # topic ids, in order covered | |
| topics: dict[str, TopicMemory] = field(default_factory=dict) | |
| seen_problems: dict[str, str] = field(default_factory=dict) # problem_id -> iso time | |
| quiz_ids: list[str] = field(default_factory=list) | |
| # Placement assessment result: {assessment_id, completed_at, levels{topic: gap|partial|solid}, placement} | |
| assessment: dict | None = None | |
| # Research Agent's plan built from the assessment: {created, steps:[{topic, start_stage, reason}]} | |
| learning_plan: dict | None = None | |
| # Worked-example / transfer progress per topic: {topic: {status, stage, transfer_passed, updated}} | |
| concept_progress: dict = field(default_factory=dict) | |
| # Peer-instruction log (calibration: confidence vs. correctness) | |
| peer_log: list = field(default_factory=list) | |
| def assessed(self) -> bool: | |
| return bool(self.assessment and self.assessment.get("completed_at")) | |
| # ------------------------------------------------------------------ persistence | |
| def _dir(learner_id: str): | |
| if not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", learner_id): | |
| raise ValueError("learner_id must be 1-64 chars of letters, digits, _ . -") | |
| return LEARNERS_DIR / learner_id | |
| def load(cls, learner_id: str) -> "LearnerState": | |
| path = cls._dir(learner_id) / "state.json" | |
| if not path.exists(): | |
| return cls(learner_id=learner_id) | |
| raw = json.loads(path.read_text()) | |
| raw["topics"] = {k: TopicMemory(**v) for k, v in raw.get("topics", {}).items()} | |
| return cls(**raw) | |
| def save(self) -> None: | |
| d = self._dir(self.learner_id) | |
| d.mkdir(parents=True, exist_ok=True) | |
| (d / "state.json").write_text(json.dumps(asdict(self), indent=2)) | |
| def quiz_dir(self): | |
| return self._dir(self.learner_id) / "quizzes" | |
| # ------------------------------------------------------------------ coverage | |
| def cover(self, topic_id: str) -> None: | |
| if topic_id not in TOPIC_BY_ID: | |
| raise ValueError(f"unknown topic {topic_id!r}") | |
| if topic_id not in self.covered: | |
| self.covered.append(topic_id) | |
| self.topics.setdefault(topic_id, TopicMemory()) | |
| def current_topic(self) -> str | None: | |
| return self.covered[-1] if self.covered else None | |
| # ------------------------------------------------------------------ results | |
| def apply_quiz_results(self, results: list[dict], when: datetime | None = None) -> dict[str, bool]: | |
| """results: [{problem_id, topic, correct: bool}] for one quiz session. | |
| Returns {topic: session_success} after updating the relearning schedule.""" | |
| now = when or _now() | |
| by_topic: dict[str, list[bool]] = {} | |
| for r in results: | |
| by_topic.setdefault(r["topic"], []).append(bool(r["correct"])) | |
| if r.get("problem_id"): | |
| self.seen_problems[r["problem_id"]] = _iso(now) | |
| outcome = {} | |
| for topic, marks in by_topic.items(): | |
| mem = self.topics.setdefault(topic, TopicMemory()) | |
| mem.attempts += len(marks) | |
| mem.correct += sum(marks) | |
| success = all(marks) | |
| # Only a success at (or near) the due date counts as a *spaced* relearning | |
| # session; re-quizzing the same day must not fast-track a topic to "durable". | |
| spaced = mem.due is None or now >= datetime.fromisoformat(mem.due) - timedelta( | |
| days=0.25 * mem.current_interval_days) | |
| if success and spaced: | |
| mem.spaced_successes += 1 | |
| mem.stage += 1 | |
| mem.due = _iso(now + timedelta(days=mem.current_interval_days)) | |
| elif not success: | |
| mem.stage = 0 | |
| mem.due = _iso(now + timedelta(days=1)) | |
| # success but early: schedule unchanged (still counts toward accuracy) | |
| mem.last_reviewed = _iso(now) | |
| outcome[topic] = success | |
| return outcome | |
| def summary(self) -> list[dict]: | |
| now = _now() | |
| rows = [] | |
| for tid in self.covered: | |
| m = self.topics.get(tid, TopicMemory()) | |
| rows.append({ | |
| "topic": tid, | |
| "title": TOPIC_BY_ID[tid].title, | |
| "attempts": m.attempts, | |
| "accuracy": f"{m.correct / m.attempts:.0%}" if m.attempts else "—", | |
| "spaced_successes": m.spaced_successes, | |
| "status": "durable" if m.durable else ("due" if m.overdue_ratio(now) >= 0 else "scheduled"), | |
| "due": m.due or "now", | |
| }) | |
| return rows | |