Spaces:
Running
Running
Download app/session.py from lukehola/opa-traint: direct link, hf CLI and curl.
- Browser
- Download file 16.6 kB
-
https://huggingface.co/spaces/lukehola/opa-traint/resolve/main/app/session.py
- Command line
-
hf download hf://spaces/lukehola/opa-traint/app/session.py
-
curl -L -o session.py https://huggingface.co/spaces/lukehola/opa-traint/resolve/main/app/session.py
16.6 kB
| """Daily plan builder and adaptive-difficulty logic. | |
| Everything here is deterministic per day where possible (seeded by the date) so a | |
| reload during the same day yields the same plan, while still rotating content | |
| across days without repetition until a pool is exhausted. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import random | |
| import unicodedata | |
| from datetime import date, datetime, timedelta | |
| from functools import lru_cache | |
| from pathlib import Path | |
| from typing import Any | |
| from . import data_store as ds | |
| ROOT = Path(__file__).resolve().parent.parent | |
| CONTENT_DIR = ROOT / "content" | |
| # --------------------------------------------------------------------------- | |
| # Config + content loading (public, non-personal) | |
| # --------------------------------------------------------------------------- | |
| def load_config() -> dict: | |
| return json.loads((ROOT / "config.json").read_text(encoding="utf-8")) | |
| def load_content(name: str) -> Any: | |
| p = CONTENT_DIR / f"{name}.json" | |
| if not p.exists(): | |
| return None | |
| return json.loads(p.read_text(encoding="utf-8")) | |
| # --------------------------------------------------------------------------- | |
| # Text helpers | |
| # --------------------------------------------------------------------------- | |
| def normalize(text: str) -> str: | |
| """Case-insensitive, diacritic-insensitive comparison key.""" | |
| text = unicodedata.normalize("NFKD", text or "") | |
| text = "".join(c for c in text if not unicodedata.combining(c)) | |
| return text.strip().lower() | |
| WEEKDAYS_NL = [ | |
| "maandag", "dinsdag", "woensdag", "donderdag", | |
| "vrijdag", "zaterdag", "zondag", | |
| ] | |
| MONTHS_NL = [ | |
| "", "januari", "februari", "maart", "april", "mei", "juni", | |
| "juli", "augustus", "september", "oktober", "november", "december", | |
| ] | |
| def season_for(d: date) -> str: | |
| m = d.month | |
| if m in (12, 1, 2): | |
| return "winter" | |
| if m in (3, 4, 5): | |
| return "lente" | |
| if m in (6, 7, 8): | |
| return "zomer" | |
| return "herfst" | |
| def date_greeting(d: date | None = None) -> dict: | |
| d = d or date.today() | |
| return { | |
| "weekday": WEEKDAYS_NL[d.weekday()], | |
| "day": d.day, | |
| "month": MONTHS_NL[d.month], | |
| "year": d.year, | |
| "season": season_for(d), | |
| "iso": d.isoformat(), | |
| "text": f"{WEEKDAYS_NL[d.weekday()]} {d.day} {MONTHS_NL[d.month]} {d.year}", | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Weighted, non-repeating daily selection | |
| # --------------------------------------------------------------------------- | |
| def _rng(seed_extra: str = "") -> random.Random: | |
| return random.Random(f"{ds.today_str()}::{seed_extra}") | |
| def pick_without_repeat(items: list, used_ids: list, key="id", n: int = 1, seed_extra=""): | |
| """Pick ``n`` items avoiding those in ``used_ids`` until the pool is exhausted, | |
| then reset. Returns (picked_items, updated_used_ids).""" | |
| if not items: | |
| return [], used_ids | |
| avail = [it for it in items if it.get(key) not in used_ids] | |
| if len(avail) < n: | |
| # Pool exhausted — reset, but avoid immediately repeating the very last ones. | |
| used_ids = [] | |
| avail = list(items) | |
| rng = _rng(seed_extra) | |
| rng.shuffle(avail) | |
| picked = avail[:n] | |
| used_ids = used_ids + [p.get(key) for p in picked] | |
| return picked, used_ids | |
| def weighted_tier_pick(challenges: list, used_ids: list, tier_weights: dict, seed_extra=""): | |
| if not challenges: | |
| return None, used_ids | |
| avail = [c for c in challenges if c.get("id") not in used_ids] | |
| if not avail: | |
| used_ids = [] | |
| avail = list(challenges) | |
| rng = _rng(seed_extra) | |
| tiers = {} | |
| for c in avail: | |
| tiers.setdefault(c.get("tier", "seated"), []).append(c) | |
| present = list(tiers.keys()) | |
| weights = [max(tier_weights.get(t, 0.01), 0.001) for t in present] | |
| tier = rng.choices(present, weights=weights, k=1)[0] | |
| choice = rng.choice(tiers[tier]) | |
| used_ids = used_ids + [choice.get("id")] | |
| return choice, used_ids | |
| # --------------------------------------------------------------------------- | |
| # Family data (from private dataset) | |
| # --------------------------------------------------------------------------- | |
| def load_all_people() -> list[dict]: | |
| data = ds.read_json("people.json", {"people": []}) or {"people": []} | |
| return data.get("people", []) | |
| def load_all_events() -> list[dict]: | |
| data = ds.read_json("events.json", {"events": []}) or {"events": []} | |
| return data.get("events", []) | |
| def load_people() -> list[dict]: | |
| return [p for p in load_all_people() if p.get("active", True)] | |
| def load_events() -> list[dict]: | |
| return [e for e in load_all_events() if e.get("active", True)] | |
| # --------------------------------------------------------------------------- | |
| # Daily plan | |
| # --------------------------------------------------------------------------- | |
| def build_plan(state: dict) -> dict: | |
| """Assemble everything the frontend needs for one day. | |
| Content is chosen here; the frontend just renders. Picks are recorded back | |
| into ``state['used']`` and saved by the caller (progress router). | |
| """ | |
| cfg = load_config() | |
| adaptive = state["adaptive"] | |
| used = state.setdefault("used", {}) | |
| plan: dict[str, Any] = { | |
| "config": { | |
| "sound_on": cfg.get("sound_on", True), | |
| "tts": cfg.get("tts", "auto"), | |
| "music_on": cfg.get("music_on", False), | |
| "music_volume": cfg.get("music_volume", 0.35), | |
| "words_per_day": cfg.get("words_per_day", 3), | |
| "fluency_seconds": cfg.get("fluency_seconds", 60), | |
| "snelkijker_trials": cfg.get("snelkijker_trials", 6), | |
| "recording_max_seconds": cfg.get("recording_max_seconds", 180), | |
| }, | |
| "user_name": cfg.get("user_name", "Opa"), | |
| "module_order": cfg.get("module_order", []), | |
| "date": date_greeting(), | |
| "streak": state.get("streak", 0), | |
| "total_stars": state.get("total_stars", 0), | |
| # One session per day: after completion the frontend shows a friendly | |
| # "already done" screen instead of the Start button. Only enforced in | |
| # deployment mode — during the testing phase (deployment_mode false) | |
| # the session can be replayed any number of times per day. | |
| "done_today": (bool(cfg.get("deployment_mode")) | |
| and state.get("last_completed_date") == ds.today_str()), | |
| "adaptive": { | |
| "people_mode": adaptive.get("people_mode", "type"), | |
| "speed_ms": adaptive.get("speed_ms", 900), | |
| # Fixed tunable, not adaptive: read from config so a stale copy in | |
| # progress state can never pin an old pace. | |
| "reveal_interval_ms": cfg.get("defaults", {}).get("reveal_interval_ms", 4000), | |
| "chess_enabled": adaptive.get("chess_enabled", True), | |
| }, | |
| "modules": {}, | |
| } | |
| # --- Oriëntatie --- | |
| plan["modules"]["orientatie"] = { | |
| "upcoming_birthdays": upcoming_birthdays(), | |
| } | |
| # --- Wie is dit? --- | |
| people = load_people() | |
| plan["modules"]["wie_is_dit"] = build_people_module(people, state, cfg) | |
| # --- Vertel eens --- | |
| events = load_events() | |
| ev_pick, used["events"] = pick_without_repeat( | |
| events, used.get("events", []), n=1, seed_extra="event" | |
| ) | |
| plan["modules"]["vertel_eens"] = { | |
| "event": public_event(ev_pick[0]) if ev_pick else None, | |
| } | |
| # --- Woorden --- | |
| plan["modules"]["woorden"] = build_words_module(cfg, adaptive, used) | |
| # --- Snelkijker --- | |
| plan["modules"]["snelkijker"] = { | |
| "speed_ms": adaptive.get("speed_ms", 900), | |
| "trials": cfg.get("snelkijker_trials", 6), | |
| "icons": ["huis", "boom", "auto", "vis"], | |
| } | |
| # --- Categorie --- | |
| cats = load_content("fluency_categories") or {"categories": []} | |
| cat_list = cats.get("categories", []) | |
| rng = _rng("category") | |
| cat = rng.choice(cat_list) if cat_list else None | |
| plan["modules"]["categorie"] = { | |
| "category": cat, | |
| "seconds": cfg.get("fluency_seconds", 60), | |
| } | |
| # --- Stappenplan --- | |
| seqs = (load_content("sequences") or {"sequences": []}).get("sequences", []) | |
| seq_pick, used["sequences"] = pick_without_repeat( | |
| seqs, used.get("sequences", []), key="title", n=1, seed_extra="seq" | |
| ) | |
| plan["modules"]["stappenplan"] = {"sequence": seq_pick[0] if seq_pick else None} | |
| # --- Beweegmoment --- | |
| challenges = (load_content("challenges") or {"challenges": []}).get("challenges", []) | |
| chal, used["challenges"] = weighted_tier_pick( | |
| challenges, used.get("challenges", []), | |
| adaptive.get("tier_weights") or cfg.get("tier_weights", {}), | |
| seed_extra="challenge", | |
| ) | |
| plan["modules"]["beweegmoment"] = {"challenge": chal} | |
| # --- Schaak --- | |
| plan["modules"]["schaak"] = build_chess_module(adaptive) | |
| # --- Go --- | |
| # The daily goproblems.com puzzle is fetched lazily via /api/go_daily so a | |
| # slow or offline upstream can never delay the plan. | |
| plan["modules"]["go"] = {"enabled": True} | |
| # --- Weetje --- | |
| facts = (load_content("facts") or {"facts": []}).get("facts", []) | |
| fact_pick, used["facts"] = pick_without_repeat( | |
| facts, used.get("facts", []), n=1, seed_extra="fact" | |
| ) | |
| plan["modules"]["weetje"] = {"fact": fact_pick[0] if fact_pick else None} | |
| # --- Video van de dag --- | |
| videos = (load_content("videos") or {"videos": []}).get("videos", []) | |
| vid_pick, used["videos"] = pick_without_repeat( | |
| videos, used.get("videos", []), n=1, seed_extra="video" | |
| ) | |
| plan["modules"]["video"] = {"video": vid_pick[0] if vid_pick else None} | |
| return plan | |
| def build_people_module(people: list, state: dict, cfg: dict) -> dict: | |
| mode = state["adaptive"].get("people_mode", "type") | |
| rng = _rng("people") | |
| # One full round over every face, freshly shuffled each session. | |
| picked = people[:] | |
| rng.shuffle(picked) | |
| all_names = [p["name"] for p in people] | |
| items = [] | |
| for p in picked: | |
| photos = p.get("photos", []) | |
| photo = rng.choice(photos) if photos else None | |
| distractors = [n for n in all_names if n != p["name"]] | |
| rng.shuffle(distractors) | |
| items.append({ | |
| "id": p["id"], | |
| "name": p["name"], | |
| "aliases": p.get("aliases", []), | |
| "relation": p.get("relation", ""), | |
| "photo": photo, | |
| "choices": ([p["name"]] + distractors[:2]) if mode == "choose3" else None, | |
| }) | |
| return {"mode": mode, "people": items} | |
| def build_words_module(cfg: dict, adaptive: dict, used: dict) -> dict: | |
| words = (load_content("words") or {"words": []}).get("words", []) | |
| level = adaptive.get("words_level", cfg.get("words_start_level", 1)) | |
| pool = [w for w in words if w.get("level", 1) <= level] or words | |
| # Rotate without repeats until the pool is exhausted (like facts/events), | |
| # so consecutive sessions always bring fresh words. | |
| chosen, used["words"] = pick_without_repeat( | |
| pool, used.get("words", []), key="nl", | |
| n=cfg.get("words_per_day", 3), seed_extra="words", | |
| ) | |
| rng = _rng("words") | |
| out = [] | |
| for w in chosen: | |
| # Build choose-3 distractors per language from the wider pool. | |
| fr_pool = [x["fr"] for x in words if x.get("fr") and x["fr"] != w.get("fr")] | |
| en_pool = [x["en"] for x in words if x.get("en") and x["en"] != w.get("en")] | |
| rng.shuffle(fr_pool) | |
| rng.shuffle(en_pool) | |
| out.append({ | |
| "nl": w["nl"], | |
| "fr": w["fr"], | |
| "en": w["en"], | |
| "icon": w.get("icon", ""), | |
| "fr_choices": _shuffled([w["fr"]] + fr_pool[:2], rng), | |
| "en_choices": _shuffled([w["en"]] + en_pool[:2], rng), | |
| }) | |
| return {"words": out} | |
| def build_chess_module(adaptive: dict) -> dict: | |
| """Pick today's puzzles from the bundled Lichess set (played on our own | |
| in-app board — no external site). Deterministic per day.""" | |
| if not adaptive.get("chess_enabled", True): | |
| return {"enabled": False, "puzzles": []} | |
| puzzles = (load_content("puzzles") or {"puzzles": []}).get("puzzles", []) | |
| band = adaptive.get("puzzle_rating_band", [1400, 1800]) | |
| lo, hi = band[0], band[1] | |
| pool = [p for p in puzzles if lo <= p.get("rating", 1500) <= hi] or puzzles | |
| rng = _rng("chess") | |
| rng.shuffle(pool) | |
| chosen = pool[:3] # one main + up to 2 extra ("Nog eentje?") | |
| # Strip rating before sending to the frontend — never displayed. | |
| safe = [{"fen": p["fen"], "moves": p["moves"]} for p in chosen] | |
| return {"enabled": True, "puzzles": safe} | |
| def _shuffled(lst, rng): | |
| lst = list(lst) | |
| rng.shuffle(lst) | |
| return lst | |
| # --------------------------------------------------------------------------- | |
| # Public (non-personal) projections | |
| # --------------------------------------------------------------------------- | |
| def public_event(ev: dict) -> dict: | |
| return { | |
| "id": ev["id"], | |
| "photo": ev.get("photo"), | |
| "title": ev.get("title", ""), | |
| "description": ev.get("description", ""), | |
| "prompts": ev.get("prompts", []), | |
| } | |
| def upcoming_birthdays(days: int = 7) -> list[dict]: | |
| out = [] | |
| today = date.today() | |
| for p in load_people(): | |
| bd = p.get("birthday") | |
| if not bd: | |
| continue | |
| try: | |
| m, d = int(bd.split("-")[-2]), int(bd.split("-")[-1]) | |
| except (ValueError, IndexError): | |
| continue | |
| this_year = date(today.year, m, d) | |
| target = this_year if this_year >= today else date(today.year + 1, m, d) | |
| delta = (target - today).days | |
| if 0 <= delta <= days: | |
| out.append({ | |
| "name": p["name"], | |
| "days": delta, | |
| "weekday": WEEKDAYS_NL[target.weekday()], | |
| }) | |
| return out | |
| # --------------------------------------------------------------------------- | |
| # Adaptive difficulty updates (applied when module results arrive) | |
| # --------------------------------------------------------------------------- | |
| def apply_snelkijker_result(state: dict, correct: bool) -> None: | |
| cfg = load_config()["adaptation"] | |
| a = state["adaptive"] | |
| if correct: | |
| a["speed_correct_streak"] = a.get("speed_correct_streak", 0) + 1 | |
| if a["speed_correct_streak"] >= cfg["speed_correct_streak_to_decrease"]: | |
| a["speed_ms"] = max(cfg["speed_floor_ms"], a["speed_ms"] - cfg["speed_decrease_ms"]) | |
| a["speed_correct_streak"] = 0 | |
| else: | |
| a["speed_correct_streak"] = 0 | |
| a["speed_ms"] = min(cfg["speed_ceiling_ms"], a["speed_ms"] + cfg["speed_increase_ms"]) | |
| def apply_people_session(state: dict, fullreveal_rate: float) -> None: | |
| """Track name-fully-revealed rate; switch type->choose3 after threshold streak.""" | |
| cfg = load_config()["adaptation"] | |
| a = state["adaptive"] | |
| hist = a.setdefault("people_fullreveal_history", []) | |
| hist.append(round(fullreveal_rate, 3)) | |
| a["people_fullreveal_history"] = hist[-10:] | |
| if a.get("people_mode") == "type": | |
| recent = a["people_fullreveal_history"][-cfg["people_sessions_to_switch"]:] | |
| if (len(recent) >= cfg["people_sessions_to_switch"] | |
| and all(r >= cfg["people_fullreveal_threshold"] for r in recent)): | |
| a["people_mode"] = "choose3" | |
| def register_completion(state: dict, stars: int, module_results: dict) -> dict: | |
| """Update streak, stars, history when a session finishes.""" | |
| today = date.today() | |
| last = state.get("last_completed_date") | |
| if last == today.isoformat(): | |
| pass # already counted today | |
| else: | |
| if last: | |
| last_d = datetime.fromisoformat(last).date() | |
| if (today - last_d).days == 1: | |
| state["streak"] = state.get("streak", 0) + 1 | |
| elif (today - last_d).days > 1: | |
| state["streak"] = 1 | |
| else: | |
| state["streak"] = max(1, state.get("streak", 0)) | |
| else: | |
| state["streak"] = 1 | |
| state["last_completed_date"] = today.isoformat() | |
| state["total_stars"] = state.get("total_stars", 0) + max(0, int(stars)) | |
| state.setdefault("history", []).append({ | |
| "date": today.isoformat(), | |
| "module_results": module_results or {}, | |
| }) | |
| state["history"] = state["history"][-400:] | |
| # Apply adaptation from aggregated results. | |
| if "people_fullreveal_rate" in (module_results or {}): | |
| apply_people_session(state, module_results["people_fullreveal_rate"]) | |
| return state | |