| @@ -1,23 +1,65 @@ |
| 1 | 1 | """Wiederholung nach Fehlern – Lernkarten wie bei Anki, eine Karte pro Kurslinie. |
| 2 | 2 | |
| 3 | | -Eine Linie ist ein Weg durch den Kurs vom Start bis zum Ende einer Variante. |
| 4 | | -Fehlerfrei und ohne Hinweis gespielt, wächst der Abstand bis zur nächsten |
| 5 | | -Wiederholung (1, 3, 7, 14 … Tage). Mit Fehler oder Hinweis ist sie sofort wieder |
| 6 | | -fällig (ein Hinweis, der nur die Figur zeigt, zählt halb) – kommt aber erst nach den anderen fälligen Linien dran. |
| 3 | +Eine Linie ist ein Weg durch den Kurs vom Start bis zum Ende einer Variante. Geplant wird |
| 4 | +mit FSRS (``py-fsrs``, wie Anki seit 23.10): Gut, Schwer und Nochmal verändern Stabilität |
| 5 | +und Schwierigkeit der Karte, daraus folgt der nächste Termin. Nach „Nochmal“ ist die Linie |
| 6 | +zusätzlich heute noch einmal fällig – nach den anderen fälligen – und beginnt kurz vor |
| 7 | +dem ersten Ausrutscher (``retry_from``). |
| 7 | 8 | |
| 8 | | -Reine Logik ohne GTK. Gespeichert wird als JSON, pro Kurs (Titel) und Linie |
| 9 | | -(UCI-Züge, mit Leerzeichen getrennt). |
| 9 | +Reine Logik ohne GTK. Gespeichert in SQLite (Tabellen ``cards`` und ``reviews``, siehe |
| 10 | +``roadmap/training.md``), eine Datei pro Benutzer. Der alte Stand aus ``training.json`` |
| 11 | +wird einmal übernommen. |
| 10 | 12 | """ |
| 11 | 13 | |
| 12 | 14 | import datetime |
| 13 | 15 | import json |
| 14 | 16 | import os |
| 17 | +import sqlite3 |
| 15 | 18 | |
| 16 | 19 | from . import opening |
| 17 | 20 | |
| 18 | | -LADDER = [1, 3, 7, 14, 30, 60, 120] # Tage bis zur nächsten Wiederholung, Stufe für Stufe |
| 21 | +try: |
| 22 | + import fsrs |
| 23 | +except ImportError: # schach.sh holt es per uv, siehe requirements.txt |
| 24 | + fsrs = None |
| 25 | + |
| 19 | 26 | GOOD, HARD, AGAIN = "good", "hard", "again" |
| 20 | 27 | NEW_PER_DAY = 3 # neue Linien pro Kurs und Tag – Wiederholungen kommen immer dran |
| 28 | +KIND_LINE = "course_line" |
| 29 | +MAX_DAYS = 60 # länger nicht: sonst merkt man sich eher die Stellung als das Muster |
| 30 | +RETENTION = {"relaxed": 0.80, "balanced": 0.85, "thorough": 0.92} # Einstellung „Wiederholen“ |
| 31 | +DEFAULT_RETENTION = "balanced" |
| 32 | +LEGACY_LADDER = [1, 3, 7, 14, 30, 60, 120] # Tage je Stufe in training.json (vor FSRS) |
| 33 | + |
| 34 | +SCHEMA = """ |
| 35 | +CREATE TABLE IF NOT EXISTS cards ( |
| 36 | + id INTEGER PRIMARY KEY, |
| 37 | + kind TEXT NOT NULL, -- course_line; später auch Rätsel, Patzer, Lichess-Rätsel |
| 38 | + source TEXT NOT NULL, -- Kurstitel |
| 39 | + key TEXT NOT NULL, -- Linie: UCI-Züge, mit Leerzeichen getrennt |
| 40 | + created TEXT NOT NULL, -- Ortsdatum des ersten Versuchs (Tageslimit für Neues) |
| 41 | + state INTEGER NOT NULL, -- fsrs.State |
| 42 | + step INTEGER, |
| 43 | + stability REAL, |
| 44 | + difficulty REAL, |
| 45 | + due TEXT NOT NULL, -- UTC, ISO 8601 |
| 46 | + last_review TEXT, -- UTC, ISO 8601 |
| 47 | + again_day TEXT, -- Ortsdatum eines „Nochmal“: heute noch einmal fällig |
| 48 | + slip INTEGER, -- Halbzug des ersten Ausrutschers dabei |
| 49 | + UNIQUE (kind, source, key) |
| 50 | +); |
| 51 | +CREATE TABLE IF NOT EXISTS reviews ( |
| 52 | + id INTEGER PRIMARY KEY, |
| 53 | + card_id INTEGER NOT NULL REFERENCES cards (id), |
| 54 | + at TEXT NOT NULL, -- UTC, ISO 8601 |
| 55 | + rating INTEGER NOT NULL, -- fsrs.Rating: 1 Nochmal, 2 Schwer, 3 Gut, 4 Leicht |
| 56 | + errors INTEGER, |
| 57 | + hints REAL, -- halbe Hinweise zählen halb |
| 58 | + blunders INTEGER, |
| 59 | + duration_ms INTEGER |
| 60 | +); |
| 61 | +CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT); |
| 62 | +""" |
| 21 | 63 | |
| 22 | 64 | |
| 23 | 65 | def lines(course): |
| @@ -52,32 +94,129 @@ def _date(text): |
| 52 | 94 | return None |
| 53 | 95 | |
| 54 | 96 | |
| 97 | +def _utc(moment): |
| 98 | + """Ortszeit (ohne Zeitzone) oder beliebige Zeitzone → UTC, wie py-fsrs es verlangt.""" |
| 99 | + return moment.astimezone(datetime.timezone.utc) |
| 100 | + |
| 101 | + |
| 102 | +def _instant(text): |
| 103 | + return datetime.datetime.fromisoformat(text) if text else None |
| 104 | + |
| 105 | + |
| 106 | +def _local_day(text): |
| 107 | + """Ortsdatum eines gespeicherten UTC-Zeitpunkts.""" |
| 108 | + return _instant(text).astimezone().date() |
| 109 | + |
| 110 | + |
| 111 | +def _midnight(day): |
| 112 | + """Beginn eines Ortsdatums als UTC-Zeitpunkt.""" |
| 113 | + return _utc(datetime.datetime.combine(day, datetime.time())) |
| 114 | + |
| 115 | + |
| 116 | +RATINGS = {} # GOOD/HARD/AGAIN → fsrs.Rating, gefüllt, sobald fsrs da ist |
| 117 | +if fsrs is not None: |
| 118 | + RATINGS = {GOOD: fsrs.Rating.Good, HARD: fsrs.Rating.Hard, AGAIN: fsrs.Rating.Again} |
| 119 | + |
| 120 | + |
| 55 | 121 | class Progress: |
| 56 | | - """Lernstand aller Kurse; ``path`` None = nur im Speicher (Tests).""" |
| 122 | + """Lernstand aller Kurse; ``path`` None = nur im Speicher (Tests). |
| 57 | 123 | |
| 58 | | - def __init__(self, path=None): |
| 124 | + ``legacy_path``: altes ``training.json``, wird beim ersten Öffnen einmal übernommen. |
| 125 | + ``retention``: Stufe aus ``RETENTION`` (oder ein Wert zwischen 0 und 1). |
| 126 | + ``fuzz``: Termine leicht streuen, damit sich Wiederholungen nicht auf einen Tag ballen. |
| 127 | + """ |
| 128 | + |
| 129 | + def __init__(self, path=None, legacy_path=None, retention=DEFAULT_RETENTION, fuzz=True): |
| 130 | + if fsrs is None: |
| 131 | + raise RuntimeError("Für die Wiederholung fehlt das Paket „fsrs“. Am einfachsten über " |
| 132 | + "schach.sh starten, das holt es per uv (siehe requirements.txt).") |
| 59 | 133 | self.path = path |
| 60 | | - self.data = {} |
| 61 | | - if path and os.path.exists(path): |
| 62 | | - try: |
| 63 | | - with open(path) as fh: |
| 64 | | - loaded = json.load(fh) |
| 65 | | - if isinstance(loaded, dict): |
| 66 | | - self.data = loaded |
| 67 | | - except (OSError, ValueError): |
| 68 | | - self.data = {} |
| 134 | + if path: |
| 135 | + os.makedirs(os.path.dirname(path), exist_ok=True) |
| 136 | + self.db = sqlite3.connect(path or ":memory:") |
| 137 | + self.db.row_factory = sqlite3.Row |
| 138 | + self.db.executescript(SCHEMA) |
| 139 | + self.fuzz = fuzz |
| 140 | + self.set_retention(retention) |
| 141 | + if legacy_path: |
| 142 | + self._import_json(legacy_path) |
| 143 | + |
| 144 | + def set_retention(self, retention): |
| 145 | + """Zielwert für FSRS: wie sicher eine Karte beim nächsten Termin noch sitzen soll.""" |
| 146 | + if isinstance(retention, str): |
| 147 | + retention = RETENTION.get(retention, RETENTION[DEFAULT_RETENTION]) |
| 148 | + self.scheduler = fsrs.Scheduler( |
| 149 | + desired_retention=float(retention), |
| 150 | + learning_steps=(), # keine Wiederholung im Minutentakt; „Nochmal“ regelt again_day |
| 151 | + relearning_steps=(), |
| 152 | + maximum_interval=MAX_DAYS, |
| 153 | + enable_fuzzing=self.fuzz, |
| 154 | + ) |
| 155 | + |
| 156 | + # --- Speicher ------------------------------------------------------------ |
| 157 | + |
| 158 | + def _rows(self, course): |
| 159 | + query = "SELECT * FROM cards WHERE kind = ? AND source = ?" |
| 160 | + return {row["key"]: row for row in self.db.execute(query, (KIND_LINE, course.title))} |
| 161 | + |
| 162 | + def _row(self, course, line_id): |
| 163 | + query = "SELECT * FROM cards WHERE kind = ? AND source = ? AND key = ?" |
| 164 | + return self.db.execute(query, (KIND_LINE, course.title, line_id)).fetchone() |
| 69 | 165 | |
| 70 | | - def save(self): |
| 71 | | - if not self.path: |
| 166 | + def _merge(self, keep, drop): |
| 167 | + """Karte ``drop`` in ``keep`` aufgehen lassen; ihre Versuche bleiben erhalten.""" |
| 168 | + self.db.execute("UPDATE reviews SET card_id = ? WHERE card_id = ?", (keep, drop)) |
| 169 | + self.db.execute("DELETE FROM cards WHERE id = ?", (drop,)) |
| 170 | + |
| 171 | + def _import_json(self, path): |
| 172 | + """Lernstand aus ``training.json`` (feste Stufenleiter) einmal übernehmen. |
| 173 | + |
| 174 | + Die Stabilität ist der letzte Abstand der Leiter, die Schwierigkeit mittel (5 von 10). |
| 175 | + Fälligkeit und ein offenes „Nochmal“ von heute bleiben, wie sie waren. |
| 176 | + """ |
| 177 | + if self.db.execute("SELECT 1 FROM meta WHERE key = 'imported_json'").fetchone(): |
| 178 | + return |
| 179 | + if not os.path.exists(path): |
| 180 | + return |
| 181 | + try: |
| 182 | + with open(path, encoding="utf-8") as fh: |
| 183 | + data = json.load(fh) |
| 184 | + except (OSError, ValueError): |
| 72 | 185 | return |
| 73 | | - os.makedirs(os.path.dirname(self.path), exist_ok=True) |
| 74 | | - tmp = self.path + ".tmp" |
| 75 | | - with open(tmp, "w") as fh: |
| 76 | | - json.dump(self.data, fh, indent=1, sort_keys=True) |
| 77 | | - os.replace(tmp, self.path) |
| 186 | + for title, cards in (data.items() if isinstance(data, dict) else ()): |
| 187 | + for line_id, card in cards.items(): |
| 188 | + step = card.get("step", -1) |
| 189 | + days = LEGACY_LADDER[min(step, len(LEGACY_LADDER) - 1)] if step >= 0 else 1 |
| 190 | + due = _midnight(_date(card.get("due")) or datetime.date.today()) |
| 191 | + seen = card.get("seen") |
| 192 | + retry = card.get("retry") or {} |
| 193 | + self.db.execute( |
| 194 | + "INSERT OR IGNORE INTO cards (kind, source, key, created, state, step, stability," |
| 195 | + " difficulty, due, last_review, again_day, slip) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?)", |
| 196 | + (KIND_LINE, title, line_id, card.get("first") or datetime.date.today().isoformat(), |
| 197 | + int(fsrs.State.Review), float(days), 5.0, due.isoformat(), |
| 198 | + _utc(datetime.datetime.fromisoformat(seen)).isoformat() if seen else None, |
| 199 | + retry.get("day"), retry.get("slip")), |
| 200 | + ) |
| 201 | + self.db.execute("INSERT INTO meta (key, value) VALUES ('imported_json', ?)", |
| 202 | + (datetime.datetime.now().isoformat(timespec="seconds"),)) |
| 203 | + self.db.commit() |
| 204 | + |
| 205 | + # --- Abfragen ------------------------------------------------------------ |
| 78 | 206 | |
| 79 | 207 | def card(self, course, line_id): |
| 80 | | - return self.data.get(course.title, {}).get(line_id) |
| 208 | + """Gespeicherte Karte als dict, ``due_day`` als Ortsdatum – oder None, wenn neu.""" |
| 209 | + row = self._row(course, line_id) |
| 210 | + if row is None: |
| 211 | + return None |
| 212 | + card = dict(row) |
| 213 | + card["due_day"] = _local_day(row["due"]).isoformat() |
| 214 | + return card |
| 215 | + |
| 216 | + def _due_day(self, row, today): |
| 217 | + if row["again_day"] == today.isoformat(): |
| 218 | + return today |
| 219 | + return _local_day(row["due"]) |
| 81 | 220 | |
| 82 | 221 | def _migrate(self, course, ids, today=None): |
| 83 | 222 | """Lernstand von Linien übertragen, deren Kennung sich geändert hat. |
| @@ -88,52 +227,59 @@ class Progress: |
| 88 | 227 | (die Hauptvariante) und ist gleich fällig, damit die neuen Züge bald drankommen. |
| 89 | 228 | ``ids`` in Kursreihenfolge. |
| 90 | 229 | """ |
| 91 | | - cards = self.data.get(course.title) |
| 92 | | - if not cards: |
| 230 | + rows = self._rows(course) |
| 231 | + if not rows: |
| 93 | 232 | return |
| 94 | 233 | today = today or datetime.date.today() |
| 95 | 234 | changed = False |
| 96 | | - for old in [i for i in cards if i not in ids]: |
| 235 | + for old in [i for i in rows if i not in ids]: |
| 236 | + row = rows[old] |
| 97 | 237 | target = max((i for i in ids if i and old.startswith(i + " ")), key=len, default=None) |
| 98 | 238 | if target is None: |
| 99 | 239 | target = next((i for i in ids if i.startswith(old + " ")), None) |
| 100 | | - if target is None or target in cards: |
| 240 | + if target is None or target in rows: |
| 101 | 241 | continue |
| 102 | | - card = cards.pop(old) |
| 103 | | - card["due"] = min(card.get("due", today.isoformat()), today.isoformat()) |
| 104 | | - cards[target] = card |
| 105 | | - changed = True |
| 106 | | - continue |
| 107 | | - card = cards.pop(old) |
| 108 | | - existing = cards.get(target) |
| 109 | | - if existing is None or (card.get("due", "") < existing.get("due", "")): |
| 110 | | - cards[target] = card |
| 242 | + due = min(row["due"], _midnight(today).isoformat()) |
| 243 | + self.db.execute("UPDATE cards SET key = ?, due = ? WHERE id = ?", (target, due, row["id"])) |
| 244 | + else: |
| 245 | + existing = rows.get(target) |
| 246 | + if existing is None: |
| 247 | + self.db.execute("UPDATE cards SET key = ? WHERE id = ?", (target, row["id"])) |
| 248 | + elif _instant(row["due"]) < _instant(existing["due"]): |
| 249 | + self._merge(row["id"], existing["id"]) |
| 250 | + self.db.execute("UPDATE cards SET key = ? WHERE id = ?", (target, row["id"])) |
| 251 | + else: |
| 252 | + self._merge(existing["id"], row["id"]) |
| 253 | + del rows[old] |
| 254 | + rows = self._rows(course) |
| 111 | 255 | changed = True |
| 112 | 256 | if changed: |
| 113 | | - self.save() |
| 257 | + self.db.commit() |
| 114 | 258 | |
| 115 | 259 | def _order(self, course, today): |
| 116 | 260 | """Linien nach Dringlichkeit. |
| 117 | 261 | |
| 118 | 262 | Gruppen: 0 fällig, 1 neu (bis zum Tageslimit), 2 noch nicht fällig, 3 neu über dem Limit. |
| 119 | 263 | Gruppe 2 und 3 sind freiwilliges Weiterüben, wenn für heute alles geschafft ist. |
| 264 | + Innerhalb der Fälligen kommt zuerst, was am längsten wartet – ein „Nochmal“ von eben |
| 265 | + also nach den anderen. |
| 120 | 266 | """ |
| 121 | 267 | all_lines = lines(course) |
| 122 | 268 | self._migrate(course, [line_id for line_id, _m in all_lines], today) |
| 123 | | - cards = self.data.get(course.title, {}) |
| 124 | | - started = sum(1 for c in cards.values() if c.get("first") == today.isoformat()) |
| 269 | + rows = self._rows(course) |
| 270 | + started = sum(1 for row in rows.values() if row["created"] == today.isoformat()) |
| 125 | 271 | allowance = max(0, NEW_PER_DAY - started) |
| 126 | 272 | ranked = [] |
| 127 | 273 | for index, (line_id, moves) in enumerate(all_lines): |
| 128 | | - card = cards.get(line_id) |
| 129 | | - if card is None: |
| 274 | + row = rows.get(line_id) |
| 275 | + if row is None: |
| 130 | 276 | group = 1 if allowance > 0 else 3 |
| 131 | 277 | allowance -= group == 1 |
| 132 | 278 | ranked.append(((group, datetime.date.min, "", index), line_id, moves)) |
| 133 | 279 | continue |
| 134 | | - due = _date(card.get("due")) or today |
| 280 | + due = self._due_day(row, today) |
| 135 | 281 | group = 0 if due <= today else 2 |
| 136 | | - ranked.append(((group, due, card.get("seen", ""), index), line_id, moves)) |
| 282 | + ranked.append(((group, due, row["last_review"] or "", index), line_id, moves)) |
| 137 | 283 | ranked.sort(key=lambda item: item[0]) |
| 138 | 284 | return ranked |
| 139 | 285 | |
| @@ -160,40 +306,63 @@ class Progress: |
| 160 | 306 | ersten Ausrutscher, statt die längst sicheren ersten Züge noch einmal zu verlangen. |
| 161 | 307 | """ |
| 162 | 308 | today = today or datetime.date.today() |
| 163 | | - retry = (self.card(course, line_id) or {}).get("retry") |
| 164 | | - if not retry or retry.get("day") != today.isoformat(): |
| 309 | + row = self._row(course, line_id) |
| 310 | + if row is None or row["again_day"] != today.isoformat() or row["slip"] is None: |
| 165 | 311 | return None |
| 166 | | - return max(0, retry["slip"] - 2) |
| 312 | + return max(0, row["slip"] - 2) |
| 167 | 313 | |
| 168 | | - def record(self, course, line_id, grade, now=None, slip=None): |
| 314 | + # --- Eintragen ----------------------------------------------------------- |
| 315 | + |
| 316 | + def record(self, course, line_id, grade, now=None, slip=None, |
| 317 | + errors=None, hints=None, blunders=None, duration_ms=None): |
| 169 | 318 | """Ergebnis eintragen (GOOD, HARD, AGAIN oder True/False); Tage bis zur nächsten Wiederholung. |
| 170 | 319 | |
| 171 | | - Gut: eine Stufe höher. Schwer: Stufe bleibt, gleicher Abstand wie zuletzt (neu: 1 Tag). |
| 172 | | - Nochmal: zurück auf Anfang und gleich wieder fällig (0 Tage). ``slip`` ist der Halbzug |
| 173 | | - des ersten Ausrutschers; nach „Nochmal“ beginnt die Linie heute kurz davor (``retry_from``). |
| 320 | + FSRS rechnet den Termin. Nochmal: zusätzlich heute noch einmal fällig (0 Tage). |
| 321 | + ``slip`` ist der Halbzug des ersten Ausrutschers; nach „Nochmal“ beginnt die Linie |
| 322 | + heute kurz davor (``retry_from``). Fehler, Hinweise, Patzer und Dauer landen im |
| 323 | + Protokoll (``reviews``), aus dem sich FSRS später nachjustieren lässt. |
| 174 | 324 | """ |
| 175 | 325 | grade = GOOD if grade is True else AGAIN if grade is False else grade |
| 176 | 326 | now = now or datetime.datetime.now() |
| 177 | | - cards = self.data.setdefault(course.title, {}) |
| 178 | | - card = cards.setdefault(line_id, {"step": -1, "lapses": 0, "first": now.date().isoformat()}) |
| 179 | | - if grade == GOOD: |
| 180 | | - card["step"] = min(card.get("step", -1) + 1, len(LADDER) - 1) |
| 181 | | - days = LADDER[card["step"]] |
| 182 | | - elif grade == HARD: |
| 183 | | - card["step"] = max(card.get("step", -1), 0) |
| 184 | | - days = LADDER[card["step"]] |
| 327 | + today = now.date() |
| 328 | + row = self._row(course, line_id) |
| 329 | + if row is None: |
| 330 | + card = fsrs.Card() |
| 185 | 331 | else: |
| 186 | | - card["step"] = -1 |
| 187 | | - card["lapses"] = card.get("lapses", 0) + 1 |
| 188 | | - days = 0 |
| 189 | | - if grade == AGAIN and slip is not None: |
| 190 | | - card["retry"] = {"slip": slip, "day": now.date().isoformat()} |
| 332 | + card = fsrs.Card( |
| 333 | + card_id=row["id"], state=fsrs.State(row["state"]), step=row["step"], |
| 334 | + stability=row["stability"], difficulty=row["difficulty"], |
| 335 | + due=_instant(row["due"]), last_review=_instant(row["last_review"]), |
| 336 | + ) |
| 337 | + card, _log = self.scheduler.review_card(card, RATINGS[grade], review_datetime=_utc(now), |
| 338 | + review_duration=duration_ms) |
| 339 | + again = grade == AGAIN |
| 340 | + state = (int(card.state), card.step, card.stability, card.difficulty, card.due.isoformat(), |
| 341 | + card.last_review.isoformat(), today.isoformat() if again else None, |
| 342 | + slip if again else None) |
| 343 | + if row is None: |
| 344 | + cursor = self.db.execute( |
| 345 | + "INSERT INTO cards (kind, source, key, created, state, step, stability, difficulty," |
| 346 | + " due, last_review, again_day, slip) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", |
| 347 | + (KIND_LINE, course.title, line_id, today.isoformat()) + state, |
| 348 | + ) |
| 349 | + card_id = cursor.lastrowid |
| 191 | 350 | else: |
| 192 | | - card.pop("retry", None) |
| 193 | | - card["due"] = (now.date() + datetime.timedelta(days=days)).isoformat() |
| 194 | | - card["seen"] = now.isoformat(timespec="seconds") |
| 195 | | - self.save() |
| 196 | | - return days |
| 351 | + card_id = row["id"] |
| 352 | + self.db.execute( |
| 353 | + "UPDATE cards SET state = ?, step = ?, stability = ?, difficulty = ?, due = ?," |
| 354 | + " last_review = ?, again_day = ?, slip = ? WHERE id = ?", |
| 355 | + state + (card_id,), |
| 356 | + ) |
| 357 | + self.db.execute( |
| 358 | + "INSERT INTO reviews (card_id, at, rating, errors, hints, blunders, duration_ms)" |
| 359 | + " VALUES (?, ?, ?, ?, ?, ?, ?)", |
| 360 | + (card_id, _utc(now).isoformat(), int(RATINGS[grade]), errors, hints, blunders, duration_ms), |
| 361 | + ) |
| 362 | + self.db.commit() |
| 363 | + if again: |
| 364 | + return 0 |
| 365 | + return max(1, (card.due.astimezone().date() - today).days) |
| 197 | 366 | |
| 198 | 367 | |
| 199 | 368 | def played_line(course, moves, target=None): |