Spaces:
Running on Zero
Running on Zero
Download peg_trainer.py from prasadpatil25/memory-studio: direct link, hf CLI and curl.
- Browser
- Download file 6.74 kB
-
https://huggingface.co/spaces/prasadpatil25/memory-studio/resolve/main/peg_trainer.py
- Command line
-
hf download hf://spaces/prasadpatil25/memory-studio/peg_trainer.py
-
curl -L -o peg_trainer.py https://huggingface.co/spaces/prasadpatil25/memory-studio/resolve/main/peg_trainer.py
6.74 kB
| """The 00-99 trainer: drill the learner's Major System words both ways. | |
| A peg list only works when each number always calls up the same word, so the | |
| trainer checks typed answers against the learner's own word (saved words first, | |
| then the curated starter). Per-number results are kept in the learner's browser | |
| (``gr.BrowserState``) as plain counts; no study text is stored or logged here. | |
| """ | |
| from __future__ import annotations | |
| import random | |
| import re | |
| from typing import Any | |
| from mnemonic_core import check_word_for_chunk | |
| TRAINER_STATS_KEY = "memory-studio-trainer-v1" | |
| TO_WORD = "Number → word" | |
| TO_NUMBER = "Word → number" | |
| MIXED = "Mixed" | |
| DIRECTIONS = (TO_WORD, TO_NUMBER, MIXED) | |
| COUNT_CHOICES = ("10", "20", "50", "All") | |
| RECENT_RESULTS = 5 | |
| MAX_SECONDS_PER_CARD = 60.0 | |
| _PART = re.compile(r"^(\d{1,2})(?:\s*-\s*(\d{1,2}))?$") | |
| def parse_codes(text: str) -> list[str]: | |
| """'00-19, 42, 7' -> ordered unique codes. Width is kept: 7 and 07 differ. | |
| Raises ValueError with a plain-language message for anything else. | |
| """ | |
| # "00 - 19" becomes "00-19"; then commas, semicolons, and spaces separate. | |
| joined = re.sub(r"\s*[-–]\s*", "-", text or "") | |
| codes: list[str] = [] | |
| for piece in re.split(r"[,;\s]+", joined): | |
| if piece: | |
| match = _PART.match(piece) | |
| if not match: | |
| raise ValueError( | |
| f"'{piece}' is not a number or range. Use numbers such as " | |
| "00-99, 00-19, 0-9, or 7, 42, 85." | |
| ) | |
| start, end = match.group(1), match.group(2) or match.group(1) | |
| if len(start) != len(end): | |
| raise ValueError( | |
| f"'{piece}' mixes one- and two-digit numbers. In the Major " | |
| "System 7 (key) and 07 (sock) are different pegs, so write " | |
| "0-9 or 00-09." | |
| ) | |
| if int(end) < int(start): | |
| raise ValueError(f"'{piece}' runs backwards; write the smaller number first.") | |
| width = len(start) | |
| for value in range(int(start), int(end) + 1): | |
| codes.append(str(value).zfill(width)) | |
| codes = list(dict.fromkeys(codes)) | |
| if not codes: | |
| raise ValueError("Enter the numbers to drill, for example 00-99 or 00-19.") | |
| return codes | |
| def _clean_entry(raw: Any) -> dict[str, Any] | None: | |
| if not isinstance(raw, dict): | |
| return None | |
| try: | |
| tries = max(int(raw.get("tries", 0)), 0) | |
| misses = min(max(int(raw.get("misses", 0)), 0), tries) | |
| except (TypeError, ValueError): | |
| return None | |
| recent = "".join(ch for ch in str(raw.get("recent", "")) if ch in "01") | |
| return {"tries": tries, "misses": misses, "recent": recent[-RECENT_RESULTS:]} | |
| def clean_stats(stats: Any) -> dict[str, dict[str, Any]]: | |
| """Valid per-code records from browser storage, which can hold anything.""" | |
| if not isinstance(stats, dict): | |
| return {} | |
| cleaned = {} | |
| for code, raw in stats.items(): | |
| code = str(code) | |
| entry = _clean_entry(raw) | |
| if entry is not None and re.fullmatch(r"\d{1,2}", code): | |
| cleaned[code] = entry | |
| return cleaned | |
| def record_result(stats: Any, code: str, correct: bool) -> dict[str, dict[str, Any]]: | |
| stats = clean_stats(stats) | |
| entry = stats.get(code, {"tries": 0, "misses": 0, "recent": ""}) | |
| stats[code] = { | |
| "tries": entry["tries"] + 1, | |
| "misses": entry["misses"] + (0 if correct else 1), | |
| "recent": (entry["recent"] + ("1" if correct else "0"))[-RECENT_RESULTS:], | |
| } | |
| return stats | |
| def weakness(entry: dict[str, Any] | None) -> float: | |
| """Share of recent answers missed; a number never drilled counts as 0.5.""" | |
| if not entry or not entry["recent"]: | |
| return 0.5 | |
| recent = entry["recent"] | |
| return recent.count("0") / len(recent) | |
| def select_codes( | |
| codes: list[str], count: int | None, stats: Any, hardest_first: bool | |
| ) -> list[str]: | |
| """Pick the session's numbers (weakest first if asked), in shuffled order.""" | |
| pool = list(codes) | |
| random.shuffle(pool) | |
| if hardest_first: | |
| cleaned = clean_stats(stats) | |
| pool.sort(key=lambda code: -weakness(cleaned.get(code))) | |
| chosen = pool[:count] if count else pool | |
| random.shuffle(chosen) | |
| return chosen | |
| def _normalise_word(text: str) -> str: | |
| text = " ".join(str(text or "").casefold().split()) | |
| return re.sub(r"^(a|an|the)\s+", "", text).strip(" .!?") | |
| def same_word(answer: str, peg: str) -> bool: | |
| """True for the peg word itself, ignoring case, articles, and a plural.""" | |
| answer, peg = _normalise_word(answer), _normalise_word(peg) | |
| if not answer or not peg: | |
| return False | |
| return answer in {peg, peg + "s", peg + "es"} or peg in {answer + "s", answer + "es"} | |
| def check_answer( | |
| direction: str, code: str, word: str, answer: str | |
| ) -> tuple[bool, str]: | |
| """Return (correct, note). The note explains a near miss, if any.""" | |
| typed = str(answer or "").strip() | |
| if not typed: | |
| return False, "skipped" | |
| if direction == TO_NUMBER: | |
| digits = re.sub(r"\s+", "", typed) | |
| if digits == code: | |
| return True, "" | |
| if digits.isdigit() and digits.lstrip("0") == code.lstrip("0"): | |
| return False, ( | |
| f"close: **{word}** is `{code}`, not `{digits}`. In the Major " | |
| "System a leading zero is its own sound (the s in sock), so the " | |
| "two are different pegs." | |
| ) | |
| return False, "" | |
| if same_word(typed, word): | |
| return True, "" | |
| encodes, _check = check_word_for_chunk(_normalise_word(typed), code) | |
| if encodes: | |
| return False, ( | |
| f"**{_normalise_word(typed)}** also encodes `{code}`, but your peg is " | |
| f"**{word}**. A peg list needs the same word every time; to switch, " | |
| "save the new word for this number in the Numbers tab." | |
| ) | |
| return False, "" | |
| def hardest_rows( | |
| stats: Any, words: dict[str, str], limit: int = 15 | |
| ) -> list[list[str]]: | |
| """Numbers missed recently, weakest first: [number, word, recent, all-time].""" | |
| cleaned = clean_stats(stats) | |
| missed = [ | |
| (code, entry) | |
| for code, entry in cleaned.items() | |
| if "0" in entry["recent"] | |
| ] | |
| missed.sort(key=lambda pair: (-weakness(pair[1]), -pair[1]["misses"], pair[0])) | |
| rows = [] | |
| for code, entry in missed[:limit]: | |
| recent = entry["recent"] | |
| rows.append( | |
| [ | |
| code, | |
| words.get(code, ""), | |
| f"{recent.count('1')}/{len(recent)} right", | |
| f"{entry['tries'] - entry['misses']}/{entry['tries']} right", | |
| ] | |
| ) | |
| return rows | |