"""Memory Studio: a local-first, editable mnemonic workbench. The default route needs no model: it uses deterministic Major-System tools, curated starting words, and a complete linked story. An optional small Hugging Face text model can draft candidates, stories, and word-card text on this computer. A separate optional local image model can draw a cue. AI output is always an editable draft, never an authority. Run: python -m venv .venv # Windows PowerShell: .venv\\Scripts\\Activate.ps1 # macOS/Linux: source .venv/bin/activate pip install -r requirements.txt python memory_studio.py Optional model selection (PowerShell): $env:MEMORY_MODEL = "HuggingFaceTB/SmolLM2-1.7B-Instruct" $env:MEMORY_IMAGE_MODEL = "your-org/your-diffusers-model" python memory_studio.py """ from __future__ import annotations import getpass import hashlib import os import re import secrets import shutil import tempfile import random import threading import time from collections import Counter from datetime import date from pathlib import Path from typing import Any # Disable Gradio analytics before importing it. Keep all inference and content # on this machine; the app never creates a sharing link. os.environ["GRADIO_ANALYTICS_ENABLED"] = "False" import gradio as gr from local_image import ( DEFAULT_IMAGE_SIZE, DEFAULT_IMAGE_STEPS, IMAGE_MODEL_CARD_URL, IMAGE_MODEL_DOWNLOAD_NOTE, IMAGE_MODEL_ID, IMAGE_MODEL_LICENSE_NOTE, IMAGE_SIZE_OPTIONS, IMAGE_STYLES, LocalImageError, MAX_IMAGE_STEPS, MIN_IMAGE_STEPS, dependencies_available as image_dependencies_available, generate_cue_image, image_model_status_markdown, warm_up as warm_up_image_model, ) import local_llm from local_llm import use_zero_gpu, warm_up as warm_up_text_model from local_llm import ( MODEL_ID, MODEL_LICENSE_NOTE, LocalModelError, ask_list_cues, ask_number_candidates, STORY_EXAMPLE_LINES, ask_story_lines, ask_word_fields, dependencies_available, model_status_markdown, parse_indexed_cues, parse_number_rows, parse_word_sections, ) from mind_map import key_word_tips, outline_markdown, parse_outline, render_svg from pronunciation import warm_up as warm_up_dictionary, words_for_code import mind_map import names_dates import palace_routes import peg_trainer import study_library from mind_map import MAX_MAIN_BRANCHES, MAX_SUB_BRANCHES from mnemonic_core import ( MAJOR_HELP, MAX_LIST_ITEMS, MAX_WORD_CONTEXT_LENGTH, MAX_WORD_TERM_LENGTH, WORD_FIELD_NAMES, ChainItem, NumberRow, assemble_word_card, build_ordered_chain, ANCHOR_MODES, ANCHOR_PALACE, CHUNK_MODES, CHUNK_PAIRS, CHUNK_SPACES, CHUNK_TRIPLES, auto_story_lines, chain_scene_parts, chain_scene_prompt, link_scene_prompts, build_anchor_markdown, build_review_ics, build_review_markdown, build_recall_markdown, check_word_for_chunk, curated_candidate, curated_major_rows, number_blockers, number_input_note, parse_item_list, parse_palace_stops, split_number, table_to_rows, validate_list_rows, validate_number_rows, word_card_practice, word_default_drafts, ) NUMBER_HEADERS = ["Chunk", "Word", "Image cue", "Story line", "Check", "Source"] LIST_HEADERS = ["#", "Item", "Image cue", "Story line"] STORY_LINE_COLUMN = 3 # same index in both tables WORD_HEADERS = ["Field", "Draft (edit freely)"] # A Hugging Face Space is a public demo: requests run on the Space, not on the # visitor's device. Detect it so the UI never claims on-device privacy it cannot # keep. Set MEMORY_PUBLIC_DEMO=1 to force the same wording elsewhere. PUBLIC_DEMO = ( os.getenv("MEMORY_PUBLIC_DEMO", "").strip().lower() in {"1", "true", "yes"} or bool(os.getenv("SPACE_ID", "").strip()) ) LISTEN_HOST = os.getenv("MEMORY_HOST", "").strip() or ( "0.0.0.0" if PUBLIC_DEMO else "127.0.0.1" ) LOCAL_ONLY = LISTEN_HOST in {"127.0.0.1", "localhost", "::1"} BIND_NOTE = ( "The Gradio server binds to `127.0.0.1`; `share=False`; no public link is " "created." if LOCAL_ONLY else f"The server listens on `{LISTEN_HOST}` because `MEMORY_HOST` is set, so " "other devices on your network can open it. Unset `MEMORY_HOST` to keep it " "on this computer only. `share=False`; no public link is created." ) PRIVACY_SECTION = ( """- This is the **online version**. Prompts, numbers, lists, and image cues are sent to Hugging Face and processed on the Space's servers, not on your device. - The Space has no user accounts and this app does not write study material to disk. Hugging Face may keep standard server and runtime logs. - Do not enter secrets, private notes, or anything you would not post publicly. - Model weights are public downloads, and generation uses the Space's shared free GPU. There is no paid inference API or API key. - For truly on-device use, run the same app locally: the repository is the same code, and local mode binds to `127.0.0.1` with `share=False`. - Gradio analytics and Hugging Face Hub telemetry are disabled in this app.""" if PUBLIC_DEMO else f"""- {BIND_NOTE} - Gradio analytics and Hugging Face Hub telemetry are disabled in this app. - The app does not persist or intentionally log submitted study material. Model loading prints only the model ID and device. - Image cues and generated pictures stay on this computer; they are not uploaded. Gradio may keep temporary display files while the app runs, so download a picture if you want to keep it. - Inference is on-device after the model download. There is no paid endpoint, API key, metered service, or mandatory account.""" ) NUMBER_ACCURACY = ( "The Major System is phonetic. Words are checked against the CMU " "Pronouncing Dictionary (American English); words it does not know fall " "back to an approximate spelling check. Say each word aloud in your own " "accent and replace any that do not fit. Only the bold image words in the " "story carry digits; the other words in each story line are glue, not " "digits. Replace any word, picture, or line with a personal one." ) LIST_ACCURACY = ( "Image cues are memory aids, not definitions. Keep the exact item order and " "verify technical meanings in a source you trust. Replace any cue or story " "link with one that is more vivid for you." ) # --------------------------------------------------------------------------- # Look and feel # --------------------------------------------------------------------------- # System fonts only: the app makes no third-party font requests. APP_THEME = gr.themes.Soft( primary_hue=gr.themes.colors.indigo, secondary_hue=gr.themes.colors.fuchsia, neutral_hue=gr.themes.colors.slate, radius_size=gr.themes.sizes.radius_lg, font=[ "system-ui", "-apple-system", "Segoe UI", "Roboto", "Helvetica Neue", "Arial", "sans-serif", ], font_mono=["ui-monospace", "SFMono-Regular", "Consolas", "monospace"], ) APP_CSS = """ .gradio-container { max-width: 1180px !important; margin: 0 auto !important; } /* On Hugging Face Spaces the app runs inside an iframe that the host page marks scrolling="no" and sizes to the content height at load. A picture drawn later can push the page past that fixed height, leaving the picture cut off with no way to reach the rest. When the app detects it is embedded it caps itself to the frame height and scrolls inside the frame, so every part of a draft stays reachable. */ .ms-embedded .gradio-container { max-height: 100vh; max-height: 100dvh; overflow-y: auto !important; /* Keep the scroll behaviour but hide the scrollbar track and thumb, so the embedded app does not show its own scrollbar next to the host page's. */ scrollbar-width: none; -ms-overflow-style: none; } .ms-embedded .gradio-container::-webkit-scrollbar { display: none; } #ms-hero { position: relative; overflow: hidden; padding: 34px 36px; border-radius: 22px; color: #ffffff; background: radial-gradient(900px 380px at 88% -30%, rgba(255,255,255,.30), transparent 62%), linear-gradient(135deg, #312e81 0%, #6d28d9 56%, #a21caf 100%); box-shadow: 0 20px 44px -26px rgba(49, 46, 129, .85); } /* Gradio paints every descendant of a prose block with the body text colour (.gradio-container .prose *). That rule outranks a bare class, so the banner text that sits on the purple gradient keeps its id-scoped colour. */ #ms-hero .ms-kicker { text-transform: uppercase; letter-spacing: .16em; font-size: .72rem; font-weight: 700; color: #ffffff; opacity: .88; } #ms-hero h1 { margin: .45rem 0 .6rem; color: #ffffff; font-size: clamp(1.7rem, 4vw, 2.7rem); line-height: 1.08; } #ms-hero p { margin: 0; max-width: 46rem; color: rgba(255,255,255,.94); font-size: 1rem; line-height: 1.55; } .ms-chips { display: flex; flex-wrap: wrap; gap: .45rem; margin-top: 1.1rem; } #ms-hero .ms-chip { border: 1px solid rgba(255,255,255,.35); background: rgba(255,255,255,.14); border-radius: 999px; padding: .28rem .72rem; color: #ffffff; font-size: .78rem; font-weight: 600; } .ms-card { border: 1px solid var(--border-color-primary, #e2e8f0); background: var(--block-background-fill, #ffffff); border-radius: 16px; padding: 18px 18px 10px; height: 100%; } .ms-card h3 { margin: .1rem 0 .35rem; font-size: 1.02rem; } .ms-card p { margin: .2rem 0 .6rem; opacity: .85; font-size: .9rem; line-height: 1.45; } .ms-step { display: flex; gap: .75rem; align-items: flex-start; margin: .55rem 0; } #ms-how .ms-step-num { flex: 0 0 1.75rem; height: 1.75rem; border-radius: 50%; background: #4f46e5; color: #ffffff; font-weight: 700; font-size: .85rem; display: flex; align-items: center; justify-content: center; } .ms-muted { opacity: .78; font-size: .88rem; } .ms-note.block, .ms-note:not(.prose) { border-left: 3px solid #8b5cf6 !important; padding: .3rem 0 .3rem .8rem; } /* Gradio applies elem_classes to both the block and the inner prose node. */ .ms-note.prose { border-left: 0 !important; padding: 0 !important; } .ms-mindmap { border-radius: 18px; overflow: hidden; } .ms-mindmap svg { display: block; } /* Keep a drawn picture fully visible: Gradio's preview sizes the image to the frame, and a frame sized with width:auto can leave the picture at zero width until it finishes decoding. Let the picture use its own natural size, scaled down to fit the block, so it is never collapsed or cropped. */ #ms-image .image-frame img { width: auto; height: auto; max-width: 100%; max-height: min(70vh, 100%); object-fit: contain; } .ms-answer { border: 1px dashed var(--border-color-primary, #cbd5e1); border-radius: 12px; padding: 10px 14px; } @media (max-width: 640px) { .html-container:has(#ms-hero) { padding-left: 0 !important; padding-right: 0 !important; } #ms-hero { padding: 18px 16px; border-radius: 16px; } #ms-hero .ms-kicker { font-size: .58rem; letter-spacing: .08em; line-height: 1.35; } #ms-hero h1 { font-size: 1.5rem; line-height: 1.12; margin: .3rem 0 .45rem; } #ms-hero p { font-size: .9rem; line-height: 1.45; } .ms-chips { margin-top: .8rem; gap: .35rem; } .ms-chip { font-size: .7rem; padding: .22rem .6rem; } .ms-card { padding: 14px 14px 8px; } /* Touch targets: Gradio's small buttons are 26 px tall by default. */ button.sm { min-height: 40px; padding: .4rem .7rem; font-size: .82rem; line-height: 1.2; } [role="tab"] { min-height: 38px; } .label-wrap { min-height: 40px !important; padding: 0 .25rem; } button:has(svg) { min-width: 36px; min-height: 36px; } .reset-button { min-width: 36px; min-height: 36px; } .add-row-button { min-height: 40px !important; } .settings { min-height: 32px; } /* Primary field/action rows read better as one column on phones. */ .ms-stack { flex-direction: column !important; gap: .55rem !important; } .ms-stack > * { width: 100% !important; min-width: 0 !important; } /* Dataframes keep readable columns and scroll inside their card instead of stretching the page. contain:inline-size stops the table's intrinsic width from propagating up through the flex ancestors. */ .table-wrap { contain: inline-size; width: 100% !important; } .virtual-table-viewport { max-width: 100% !important; overflow-x: auto !important; } .header-table th { font-size: .75rem; padding-left: .25rem; padding-right: .25rem; } .header-table .cell-wrap { padding: 4px 2px !important; } .header-table .header-content { gap: 0 !important; } .header-table .header { white-space: nowrap; word-break: normal; overflow-wrap: normal; } .header-cell button[aria-label="Open cell menu"] { display: none !important; } /* 16 px inputs stop iOS Safari from zooming when a field is focused. */ input, textarea, select { font-size: 16px !important; } } """ # Mark the page when it runs inside a host frame (Hugging Face Spaces embeds the # app this way). The flag turns on the scroll rules above so late content, such # as a picture drawn after the frame was sized, always stays reachable. APP_HEAD = """ """ # --------------------------------------------------------------------------- # One-click examples and study-sheet export # --------------------------------------------------------------------------- NUMBER_EXAMPLE = "314159" LIST_EXAMPLE = "milk, eggs, coffee, bread, apples" WORD_EXAMPLE_TERM = "Pomodoro" WORD_EXAMPLE_CONTEXT = ( "A focus method: work for 25 minutes, then take a 5-minute break." ) def _example_number( saved: Any = None, chunking: str = CHUNK_PAIRS ) -> tuple[str, bool, str, list[list[str]], str]: status, rows, story = draft_number_candidates( NUMBER_EXAMPLE, False, saved, chunking ) return NUMBER_EXAMPLE, False, status, rows, story def _example_list() -> tuple[str, bool, str, list[list[str]], str]: status, rows, story = draft_list_candidates(LIST_EXAMPLE, False) return LIST_EXAMPLE, False, status, rows, story def _example_word() -> tuple[str, str, bool, str, list[list[str]], str]: rows = [ ["Meaning anchor", WORD_EXAMPLE_CONTEXT], [ "Sound / keyword association", "Sound cue (not a meaning): “pomo” + “doro” → a pom-pom bouncing " "along a dough row.", ], [ "Visual image", "A giant tomato-shaped kitchen timer wearing boxing gloves, pounding " "a row of dough on a counter.", ], [ "Mini-story", "The timer rings, karate-chops the dough row, flips an hourglass, then " "takes a five-minute tea break.", ], [ "Memory Palace placement", "Kitchen counter beside the stove: hear the bell, smell warm dough, and " "watch the sand run out.", ], [ "Active-recall question", "Without looking: what does Pomodoro mean, and which two sounds and " "image hold it?", ], ] status, filled_rows, card = assemble_word_outputs( WORD_EXAMPLE_TERM, WORD_EXAMPLE_CONTEXT, rows ) return ( WORD_EXAMPLE_TERM, WORD_EXAMPLE_CONTEXT, False, status, filled_rows, card, ) SHEET_ROOT = Path(tempfile.gettempdir()) / "memory-studio-sheets" SHEET_MAX_AGE_SECONDS = 3600 def _hidden_file() -> Any: """Hide a study-sheet download that no longer matches the table.""" return gr.update(value=None, visible=False) def _prune_old_sheets() -> None: """Delete study-sheet folders older than an hour; ignore any failure.""" cutoff = time.time() - SHEET_MAX_AGE_SECONDS try: for folder in SHEET_ROOT.iterdir(): if folder.is_dir() and folder.stat().st_mtime < cutoff: shutil.rmtree(folder, ignore_errors=True) except OSError: pass def _study_sheet( markdown_text: str, stem: str, extra: tuple[tuple[str, str], ...] = () ) -> Any: """Write a downloadable Markdown sheet only when the user asks for one.""" text = (markdown_text or "").strip() if not text: raise gr.Error("Build the story (or assemble the card) first, then download it.") safe = re.sub(r"[^a-z0-9]+", "-", (stem or "study-sheet").casefold()) safe = safe.strip("-")[:40] or "study-sheet" SHEET_ROOT.mkdir(parents=True, exist_ok=True) _prune_old_sheets() folder = Path(tempfile.mkdtemp(prefix="sheet-", dir=SHEET_ROOT)) path = folder / f"{safe}.md" path.write_text(text + "\n", encoding="utf-8") calendar = folder / f"{safe}-reviews.ics" calendar.write_text( build_review_ics(date.today(), safe.replace("-", " ")), encoding="utf-8", newline="", ) paths = [str(path), str(calendar)] for suffix, content in extra: extra_path = folder / f"{safe}{suffix}" extra_path.write_text(content, encoding="utf-8") paths.append(str(extra_path)) return gr.update(value=paths, visible=True) def _number_sheet(text: str) -> Any: return _study_sheet(text, "number-story") def _list_sheet(text: str) -> Any: return _study_sheet(text, "ordered-list-story") def _word_sheet(text: str) -> Any: return _study_sheet(text, "word-card") # --------------------------------------------------------------------------- # Practice mode (no model, no scoring server-side; state stays in the session) # --------------------------------------------------------------------------- PRACTICE_NUMBER = "Numbers and chunks" PRACTICE_LIST = "Ordered list" PRACTICE_KINDS = (PRACTICE_NUMBER, PRACTICE_LIST) def _chain_practice_items( entries: list[tuple[str, str, str]], ) -> list[dict[str, str]]: """Cards that walk the chain forward: recall each image from the previous. ``entries`` are ordered (label, image cue, digit code) tuples; the code is empty for list items. This mirrors how the story is recalled: start at the first image, follow each link, then decode the digits. """ items: list[dict[str, str]] = [] for index, (label, cue, code) in enumerate(entries): if index == 0: prompt = "What is the **first** image in the chain?" else: prompt = f"What image comes after **{entries[index - 1][0]}**?" if code: prompt += " Then decode its digits." answer = f"**{label}**" if cue: answer += f": {cue}" if code: answer += f" → `{code}`" items.append({"prompt": prompt, "answer": answer}) return items def _practice_items( kind: str, text: str, saved: Any = None ) -> tuple[list[dict[str, str]], str]: """Cards from pasted text: saved words, else curated. Returns (cards, full).""" if kind == PRACTICE_NUMBER: chunks = split_number(text) personal = _saved_words_for(chunks, saved) entries = [] for chunk in chunks: word, cue = ( personal.get(chunk) or curated_candidate(chunk) or ("(no word)", "") ) entries.append((word, cue, chunk)) return _chain_practice_items(entries), "".join(chunks) entries = [(item, "", "") for item in parse_item_list(text)] return _chain_practice_items(entries), "" def _practice_outputs( items: list[dict[str, str]], full: str = "", note: str = "" ) -> tuple[Any, ...]: state: dict[str, Any] = { "items": items, "index": 0, "known": 0, "missed": [], "revealed": False, "full": full, } prompt = _practice_prompt(items[0]) if note: prompt = f"{note}\n\n{prompt}" return ( state, _practice_progress(state), prompt, _hidden_answer(), gr.update(visible=True), gr.update(visible=False), gr.update(value="", visible=False), ) def _practice_error(message: str) -> tuple[Any, ...]: return ( {}, "", message, _hidden_answer(), gr.update(visible=False), gr.update(visible=False), gr.update(value="", visible=False), ) def _number_table_cards( number_text: str, table: Any, chunking: str = CHUNK_PAIRS ) -> tuple[list[dict[str, str]], str, list[str]]: """Cards from the learner's own checked Numbers table. Returns (cards, digits, problems); raises ValueError for a bad number. """ chunks = split_number(number_text, chunking) reviewed, errors = validate_number_rows(chunks, table) problems = errors or number_blockers(reviewed) if problems: return [], "", problems entries = [(row.word, row.link or row.image, row.chunk) for row in reviewed] return _chain_practice_items(entries), "".join(chunks), [] def _list_table_cards( table: Any, ) -> tuple[list[dict[str, str]], list[str], list[str]]: """Cards from the learner's own list table. Returns (cards, items, problems).""" reviewed, errors = validate_list_rows(table) if errors: return [], [], errors entries = [(row.item, row.link or row.cue, "") for row in reviewed] return _chain_practice_items(entries), [row.item for row in reviewed], [] def practice_number_table( number_text: str, table: Any, chunking: str = CHUNK_PAIRS ) -> tuple[Any, ...]: """Practice the learner's own checked words, in chain order.""" try: cards, digits, problems = _number_table_cards(number_text, table, chunking) except ValueError as exc: return (gr.update(), f"**Input issue:** {exc}", gr.update(), gr.update(), *_practice_error("")) if problems: message = _issue_markdown( "Fix the table before practicing", problems + ["Practice uses your own words, so every row must pass."], ) return (gr.update(), message, gr.update(), gr.update(), *_practice_error("")) return ( gr.Tabs(selected="practice"), gr.update(), PRACTICE_NUMBER, digits, *_practice_outputs( cards, digits, "_Practicing the words from your Numbers table._" ), ) def practice_list_table(list_text: str, table: Any) -> tuple[Any, ...]: """Practice the learner's own list table and cues, in order.""" cards, items, problems = _list_table_cards(table) if problems: message = _issue_markdown("Fix the table before practicing", problems) return (gr.update(), message, gr.update(), gr.update(), *_practice_error("")) return ( gr.Tabs(selected="practice"), gr.update(), PRACTICE_LIST, "\n".join(items), *_practice_outputs( cards, "", "_Practicing the items and cues from your Ordered list table._" ), ) def _practice_progress(state: dict[str, Any]) -> str: items = state.get("items") or [] total = len(items) position = min(state.get("index", 0) + 1, total) known = state.get("known", 0) missed = len(state.get("missed") or []) return ( f"**Card {position} of {total}** · {known} recalled · " f"{missed} to review" ) def _practice_prompt(item: dict[str, str]) -> str: return f"### {item['prompt']}\n\nSay the answer out loud, then reveal it." def _hidden_answer() -> Any: return gr.update(value="", visible=False) def start_practice(kind: str, text: str, saved: Any = None) -> tuple[Any, ...]: try: if kind not in PRACTICE_KINDS: raise ValueError("Choose numbers or an ordered list.") items, full = _practice_items(kind, str(text or "").strip(), saved) except ValueError as exc: return _practice_error(f"**Input issue:** {exc}") note = ( "_Pasted number: practicing your saved words where you have them, " "otherwise the curated starter words. To practice a table you just " "edited, use **Practice these cards** in the Numbers tab._" if kind == PRACTICE_NUMBER else "" ) return _practice_outputs(items, full, note) def reveal_practice(state: dict[str, Any]) -> tuple[Any, ...]: items = (state or {}).get("items") or [] index = (state or {}).get("index", 0) if not items or index >= len(items): # Nothing to reveal, or the session already finished. return ( state, gr.update(), gr.update(visible=False), gr.update(visible=False), ) updated = {**state, "revealed": True} return ( updated, gr.update(value=items[index]["answer"], visible=True), gr.update(visible=False), gr.update(visible=True), ) def _practice_summary_text(state: dict[str, Any]) -> str: """The end-of-session summary, or "" while the session is still running.""" state = state or {} items = state.get("items") or [] total = len(items) if not items or state.get("index", 0) < total: return "" known = state.get("known", 0) missed = state.get("missed") or [] lines = [ "### Session complete", "", f"You recalled **{known}/{total}** card(s) on this pass.", ] if state.get("full"): lines.extend(["", f"Full number, decoded in order: `{state['full']}`"]) if missed: lines.extend(["", "#### Review these", ""]) for item_index in missed: item = items[item_index] lines.append(f"- {item['prompt']} → {item['answer']}") else: lines.extend(["", "Nothing to review. Try a longer set or a new number."]) lines.extend( [ "", "_Cards stayed in the original order, just like the story. " "Repeat the set until every card feels automatic._", ] ) return "\n".join(lines) def grade_practice(state: dict[str, Any], knew: bool) -> tuple[Any, ...]: items = (state or {}).get("items") or [] if not items or not state.get("revealed"): return ( state, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), ) index = state["index"] total = len(items) known = state["known"] + (1 if knew else 0) missed = list(state.get("missed") or []) if not knew: missed.append(index) next_index = index + 1 if next_index >= total: finished = { **state, "index": next_index, "known": known, "missed": missed, "revealed": False, } return ( finished, f"**{total} of {total} reviewed** · {known} recalled · " f"{len(missed)} to review", gr.update(value="", visible=False), _hidden_answer(), gr.update(visible=False), gr.update(visible=False), gr.update(value=_practice_summary_text(finished), visible=True), ) updated = { **state, "index": next_index, "known": known, "missed": missed, "revealed": False, } return ( updated, _practice_progress(updated), _practice_prompt(items[next_index]), _hidden_answer(), gr.update(visible=True), gr.update(visible=False), gr.update(value="", visible=False), ) def append_image_history( image: Any, history: list[Any] | None ) -> tuple[list[Any], Any]: """Keep the last eight drafts, newest first (as the gallery's label says).""" items = list(history or []) if image is None: return items, gr.update() items = [image, *items][:8] return items, items # --------------------------------------------------------------------------- # My library: saved items with review dates, kept only in the learner's browser # --------------------------------------------------------------------------- LIBRARY_EMPTY = ( "Your library is empty. Build a number story, a list story, or a word card, " "give it a name, and click **Save to my library**. This tab then tells you " "which reviews are due." ) def _library_view(library: Any) -> tuple[Any, ...]: """Refresh every library display: summary, table, picker, Start banner.""" today = date.today() items = study_library.clean_library(library) due = study_library.due_count(items, today) pairs = study_library.choices(items, today) if not items: summary = LIBRARY_EMPTY banner = ( "**My library:** save a story or card and this spot shows which " "reviews are due." ) else: next_id, next_item = study_library.sorted_items(items, today)[0] summary = ( f"### {due} due today · {len(items)} saved\n\n" + ( "Pick an item and click **Review this item**. Due items are listed " "first." if due else f"Nothing is due. Next up: **{_md_cell(next_item['name'])}**, " f"{study_library.due_text(next_item, today)}." ) ) banner = ( f"### 📅 {due} review(s) due today\n\nOpen **My library** to keep " "them on schedule." if due else f"**My library:** nothing due today. Next review: " f"**{_md_cell(next_item['name'])}**, " f"{study_library.due_text(next_item, today)}." ) return ( summary, study_library.table_rows(items, today), gr.Dropdown(choices=pairs, value=pairs[0][1] if pairs else None), banner, gr.update(visible=due > 0), ) def _library_unchanged() -> tuple[Any, ...]: return tuple(gr.update() for _ in range(5)) def _save_to_library( library: Any, kind: str, name: str, key: str, cards: list[dict[str, str]], full: str, default_name: str, ) -> tuple[Any, ...]: """Add or update a library item. A blank ``name`` keeps an existing item's name, and gives a new item ``default_name``.""" today = date.today() try: items, item_id, updated = study_library.add_item( library, kind, str(name or ""), key, cards, full, today, default_name ) except ValueError as exc: return (library, f"**Library full:** {exc}", *_library_unchanged()) item = items[item_id] title = _md_cell(item["name"]) if updated: message = ( f"### Updated in My library\n\n**{title}** now uses the cards in this " "table. Its review schedule did not change: next is the " f"{study_library.step_label(item['step'])}, " f"{study_library.due_text(item, today)}." ) else: message = ( f"### Saved to My library\n\n**{title}** ({len(cards)} card(s)) is " "ready for its first review in about 10 minutes: open **My library** " "and click **Review this item**. After that, the library brings it " "back after 1 day, 1 week, 1 month, and 4 months." ) message += ( "\n\n_The library is kept only in this browser; clearing site data " "removes it._" ) return (items, message, *_library_view(items)) def save_number_to_library( number_text: str, table: Any, name: str, library: Any, chunking: str = CHUNK_PAIRS, ) -> tuple[Any, ...]: """Save the checked Numbers table as a library item.""" try: cards, digits, problems = _number_table_cards(number_text, table, chunking) except ValueError as exc: return (library, f"**Input issue:** {exc}", *_library_unchanged()) if problems: return ( library, _issue_markdown("Fix the table before saving", problems), *_library_unchanged(), ) return _save_to_library( library, study_library.KIND_NUMBER, name, study_library.content_key(study_library.KIND_NUMBER, digits), cards, digits, f"Number · {len(digits)} digits", ) def save_list_to_library( list_text: str, table: Any, name: str, library: Any ) -> tuple[Any, ...]: """Save the checked Ordered list table as a library item.""" cards, items, problems = _list_table_cards(table) if problems: return ( library, _issue_markdown("Fix the table before saving", problems), *_library_unchanged(), ) return _save_to_library( library, study_library.KIND_LIST, name, study_library.content_key( study_library.KIND_LIST, "\n".join(item.casefold() for item in items) ), cards, "", f"List · {len(items)} items", ) def save_word_to_library( term: str, context: str, table: Any, name: str, library: Any ) -> tuple[Any, ...]: """Save the filled-in word card as a library item.""" try: term_text, context_text = _validate_word_inputs(term, context) cards = word_card_practice(term_text, context_text, table) except ValueError as exc: return (library, f"**Input issue:** {exc}", *_library_unchanged()) return _save_to_library( library, study_library.KIND_WORD, name, study_library.content_key(study_library.KIND_WORD, term_text.casefold()), cards, "", term_text, ) def review_library_item(item_id: Any, library: Any) -> tuple[Any, ...]: """Open the chosen library item in the Practice tab.""" items = study_library.clean_library(library) item = items.get(str(item_id or "")) if item is None: return ( gr.update(), "Choose an item from your library first.", *(gr.update() for _ in range(7)), ) today = date.today() due = study_library.is_due(item, today) note = ( f"_Reviewing **{_md_cell(item['name'])}** from My library: " f"{study_library.step_label(item['step'])}" + ( ", due today. Your result moves it along the schedule._" if due else f". It is not due until {study_library.due_text(item, today)}, " "so this practice will not change its schedule._" ) ) outputs = list(_practice_outputs(item["cards"], item["full"], note)) outputs[0] = {**outputs[0], "library_id": str(item_id), "library_due": due} return (gr.Tabs(selected="practice"), "", *outputs) def remove_library_item(item_id: Any, library: Any) -> tuple[Any, ...]: items = study_library.clean_library(library) item = items.pop(str(item_id or ""), None) if item is None: return (library, "Choose an item to remove.", *_library_unchanged()) return ( items, f"Removed **{_md_cell(item['name'])}** from your library.", *_library_view(items), ) def _library_review_note( state: dict[str, Any], library: Any ) -> tuple[dict[str, Any], Any, str, bool]: """When a library practice session ends, log it and set the next review. Returns (state, library, note for the summary or "", library changed). """ state = state or {} cards = state.get("items") or [] item_id = state.get("library_id") finished = cards and state.get("index", 0) >= len(cards) if not item_id or not finished or state.get("library_recorded"): return state, library, "", False state = {**state, "library_recorded": True} today = date.today() items = study_library.clean_library(library) item = items.get(item_id) if item is None: return state, library, "", False missed = bool(state.get("missed")) title = _md_cell(item["name"]) if not state.get("library_due"): note = ( f"**My library:** **{title}** was not due, so its schedule did not " f"change. Next review: {study_library.due_text(item, today)}." ) return state, library, note, False item = items[item_id] = study_library.record_review(item, not missed, today) if missed: note = ( f"**My library:** some cards were missed, so repair those pictures " "(edit the table, then **Save to my library** again to update the " f"cards). **{title}** comes back tomorrow, and the review rhythm " "restarts from the 1-day review." ) else: note = ( f"**My library:** review logged. **{title}** is next due for its " f"{study_library.step_label(item['step'])}, " f"{study_library.due_text(item, today)}." ) return state, items, note, True def grade_and_record( state: dict[str, Any], library: Any, knew: bool ) -> tuple[Any, ...]: """Grade one card and, if that ends a library review, log it, in one step. Outputs: the seven practice outputs, then the library and its five views. """ outputs = list(grade_practice(state, knew)) summary = _practice_summary_text(outputs[0]) new_state, library, note, changed = _library_review_note(outputs[0], library) outputs[0] = new_state if note: outputs[6] = gr.update(value=f"{summary}\n\n{note}", visible=True) views = _library_view(library) if changed else _library_unchanged() return (*outputs, library, *views) # --------------------------------------------------------------------------- # 00-99 trainer: drill the learner's own number words, both ways # --------------------------------------------------------------------------- TRAINER_IDLE = ( "**Choose the numbers to drill, then click Start drill.** Answers are typed " "and checked against your saved words (or the starter words where you have " "none). Press Enter to answer; an empty answer counts as a miss." ) def _trainer_words(codes: list[str], saved: Any) -> dict[str, tuple[str, str, bool]]: """code -> (word, cue, is your saved word), saved words first.""" personal = _saved_words_for(codes, saved) words: dict[str, tuple[str, str, bool]] = {} for code in codes: if code in personal: words[code] = (*personal[code], True) else: curated = curated_candidate(code) if curated: words[code] = (*curated, False) return words def _trainer_prompt(card: dict[str, Any]) -> str: if card["direction"] == peg_trainer.TO_NUMBER: return ( f"### Which number is **{_md_cell(card['word'])}**?\n\n" "Type the digits (keep a leading zero) and press Enter." ) return ( f"### What is your word for **{card['code']}**?\n\n" "Type the word and press Enter." ) def _trainer_progress(state: dict[str, Any]) -> str: cards = state.get("cards") or [] results = state.get("results") or [] right = sum(result["correct"] for result in results) position = min(len(results) + 1, len(cards)) return ( f"**Card {position} of {len(cards)}** · {right} right · " f"{len(results) - right} missed" ) def trainer_hardest(stats: Any, saved: Any) -> list[list[str]]: codes = list(peg_trainer.clean_stats(stats)) words = {code: entry[0] for code, entry in _trainer_words(codes, saved).items()} return peg_trainer.hardest_rows(stats, words) def _trainer_session(cards: list[dict[str, Any]], note: str) -> tuple[Any, ...]: """Outputs that open a drill: state, progress, prompt, feedback, answer box, answer row, summary, retry button.""" state = {"cards": cards, "results": [], "shown": time.time(), "seconds": 0.0} return ( state, _trainer_progress(state), f"{note}\n\n{_trainer_prompt(cards[0])}" if note else _trainer_prompt(cards[0]), "", gr.update(value=""), gr.update(visible=True), gr.update(value="", visible=False), gr.update(visible=False), ) def _trainer_error(message: str) -> tuple[Any, ...]: return ( {}, "", message, "", gr.update(value=""), gr.update(visible=False), gr.update(value="", visible=False), gr.update(visible=False), ) def start_trainer( range_text: str, direction: str, count: str, hardest_first: bool, saved: Any, stats: Any, ) -> tuple[Any, ...]: """Start a drill over the chosen numbers.""" try: codes = peg_trainer.parse_codes(range_text) except ValueError as exc: return _trainer_error(f"**Input issue:** {exc}") if direction not in peg_trainer.DIRECTIONS: direction = peg_trainer.TO_WORD words = _trainer_words(codes, saved) limit = int(count) if str(count).isdigit() else None chosen = peg_trainer.select_codes( [code for code in codes if code in words], limit, stats, bool(hardest_first) ) cards = [] for code in chosen: word, cue, own = words[code] card_direction = ( random.choice((peg_trainer.TO_WORD, peg_trainer.TO_NUMBER)) if direction == peg_trainer.MIXED else direction ) cards.append( {"code": code, "word": word, "cue": cue, "own": own, "direction": card_direction} ) own_count = sum(card["own"] for card in cards) note = f"_{len(cards)} card(s), shuffled" if hardest_first and peg_trainer.clean_stats(stats): note += ", weakest numbers first" note += ( f". {own_count} use your saved words" + (", the rest the starter words" if own_count < len(cards) else "") + "._" ) if own_count < len(cards): note += ( "\n\n_Tip: a peg list sticks best with words you chose. Save your own " "words in the Numbers tab and the trainer uses them._" ) return _trainer_session(cards, note) def retry_trainer_misses(state: dict[str, Any]) -> tuple[Any, ...]: """Drill the cards missed in the last session again, reshuffled.""" cards = (state or {}).get("cards") or [] missed_codes = [r["code"] for r in (state or {}).get("results") or [] if not r["correct"]] retry = [dict(card) for card in cards if card["code"] in missed_codes] if not retry: return _trainer_error("Nothing missed in the last drill. Start a new one.") random.shuffle(retry) return _trainer_session(retry, f"_Retrying the {len(retry)} card(s) you missed._") def check_trainer_answer( state: dict[str, Any], answer: str, stats: Any, saved: Any ) -> tuple[Any, ...]: """Mark one typed answer, record it, and show the next card.""" state = state or {} cards = state.get("cards") or [] results = list(state.get("results") or []) if not cards or len(results) >= len(cards): return ( state, stats, *(gr.update() for _ in range(7)), gr.update(), ) card = cards[len(results)] correct, note = peg_trainer.check_answer( card["direction"], card["code"], card["word"], answer ) elapsed = min(time.time() - state.get("shown", time.time()), peg_trainer.MAX_SECONDS_PER_CARD) stats = peg_trainer.record_result(stats, card["code"], correct) results.append({"code": card["code"], "correct": correct}) seconds = state.get("seconds", 0.0) + elapsed state = {**state, "results": results, "shown": time.time(), "seconds": seconds} pair = f"**{card['code']} = {_md_cell(card['word'])}**" if correct: feedback = f"✓ {pair} · {elapsed:.1f} s" else: typed = _md_cell(str(answer or "").strip()[:60]) opening = f"✗ You typed _{typed}_." if typed and note != "skipped" else "✗ Skipped." feedback = f"{opening} {pair}" if card["cue"]: feedback += f": {_md_cell(card['cue'])}" feedback += ". See it once more before the next card." if note and note != "skipped": feedback += f"\n\n{note}" if len(results) < len(cards): return ( state, stats, _trainer_progress(state), _trainer_prompt(cards[len(results)]), feedback, gr.update(value=""), gr.update(visible=True), gr.update(value="", visible=False), gr.update(visible=False), trainer_hardest(stats, saved), ) right = sum(result["correct"] for result in results) missed = [cards[i] for i, result in enumerate(results) if not result["correct"]] lines = [ "### Drill complete", "", f"You got **{right}/{len(cards)}** right, averaging " f"**{seconds / len(cards):.1f} s** per card.", ] if missed: lines.extend( [ "", "#### Missed", "", "| Number | Word | Picture |", "|---:|---|---|", *( f"| `{c['code']}` | **{_md_cell(c['word'])}** | {_md_cell(c['cue'])} |" for c in missed ), "", "Picture each one vividly, then click **Retry the missed ones**.", ] ) lines.extend( [ "", "_A peg is automatic when it comes back right in about 3 seconds or " "less. Drill a small range until it is, then widen it._", ] ) return ( state, stats, f"**{len(cards)} of {len(cards)} answered** · {right} right · " f"{len(cards) - right} missed", "", feedback, gr.update(value=""), gr.update(visible=False), gr.update(value="\n".join(lines), visible=True), gr.update(visible=bool(missed)), trainer_hardest(stats, saved), ) def reset_trainer_stats() -> tuple[Any, list[list[str]], str]: return {}, [], "Trainer results cleared from this browser." def start_with_trainer(saved: Any, stats: Any) -> tuple[Any, ...]: """Start here: a 10-card drill over 00-19, number to word.""" return ( gr.Tabs(selected="trainer"), "00-19", peg_trainer.TO_WORD, "10", False, *start_trainer("00-19", peg_trainer.TO_WORD, "10", False, saved, stats), ) # --------------------------------------------------------------------------- # Names & faces, and Dates (no model; deterministic drafts you edit) # --------------------------------------------------------------------------- PEOPLE_EXAMPLE = ( "Margaret Chen | big round glasses | finance team\n" "Benjamin Okafor | shaved head, wide smile | Sam's party\n" "Olivia Ruiz | freckles | climbing gym" ) EVENTS_EXAMPLE = ( "Battle of Hastings | 1066\n" "Moon landing | 20 July 1969\n" "Mum's birthday | 14 March" ) def _practice_from_cards( cards: list[dict[str, str]], note: str ) -> tuple[Any, ...]: """Open cards in the Practice tab: (tabs, status, kind, text, *practice).""" return ( gr.Tabs(selected="practice"), gr.update(), gr.update(), gr.update(), *_practice_outputs(cards, "", note), ) def _practice_blocked(message: str) -> tuple[Any, ...]: return (gr.update(), message, gr.update(), gr.update(), *_practice_error("")) def draft_people(text: str) -> tuple[str, list[list[str]], str]: try: people = names_dates.parse_people(text) rows, notes = names_dates.draft_people_rows(people) except ValueError as exc: return f"**Input issue:** {exc}", [], "" for row in rows: if not row[1]: row[1] = names_dates.FEATURE_HINT parts = [ "### Draft ready", "", f"{len(rows)} person(s). For each one, pick **one** face feature you will " "notice next time, check the **Sound-alike** (say it aloud: does it " "sound like the name to you?), and make the **Link scene** your own. " "Then click **Check and build the cards**.", "", "_Sound-alikes come from the pronunciation dictionary (American " "English). Pieces are joined with + and name parts with /._", ] if notes: parts.extend(["", "#### Other sound-alikes and gaps", ""]) parts.extend(f"- {note}" for note in notes) return "\n".join(parts), rows, "" def _people_checked( text: str, table: Any ) -> tuple[list[list[str]], list[str], str]: """(rows, notes, error markdown) for the Names table.""" try: people = names_dates.parse_people(text) except ValueError as exc: return [], [], f"**Input issue:** {exc}" rows, errors, notes = names_dates.validate_people_rows( [name for name, _f, _c in people], table ) if errors: return [], notes, _issue_markdown("Fix these first", errors) return rows, notes, "" def build_people(text: str, table: Any) -> tuple[str, Any, str]: rows, notes, error = _people_checked(text, table) if error: return error, _current_rows(table), "" status = ["### Cards ready", "", f"{len(rows)} person(s), in the order you entered."] if notes: status.extend(["", *[f"- {note}" for note in notes]]) card = ( f"{names_dates.people_markdown(rows)}\n\n" f"{build_review_markdown(date.today())}" ) return "\n".join(status), rows, card def practice_people(text: str, table: Any) -> tuple[Any, ...]: rows, _notes, error = _people_checked(text, table) if error: return _practice_blocked(error) return _practice_from_cards( names_dates.people_practice(rows), "_Practicing your Names & faces cards: read the clue, say the name._", ) def save_people_to_library( text: str, table: Any, name: str, library: Any ) -> tuple[Any, ...]: rows, _notes, error = _people_checked(text, table) if error: return (library, error, *_library_unchanged()) return _save_to_library( library, study_library.KIND_NAMES, name, study_library.content_key( study_library.KIND_NAMES, "\n".join(row[0].casefold() for row in rows) ), names_dates.people_practice(rows), "", f"Names · {len(rows)} people", ) def _date_word_lookup(saved: Any) -> Any: def word_for(chunk: str) -> tuple[str, str] | None: return _saved_words_for([chunk], saved).get(chunk) or curated_candidate(chunk) return word_for def draft_events(text: str, saved: Any = None) -> tuple[str, list[list[str]], str]: try: events = names_dates.parse_events(text) rows, notes = names_dates.draft_event_rows(events, _date_word_lookup(saved)) except ValueError as exc: return f"**Input issue:** {exc}", [], "" parts = [ "### Draft ready", "", f"{len(rows)} event(s). Each date's digits are split into chunks in the " "order you typed them (month names become two digits, so March = 03), " "and each chunk gets your saved word or the starter word. Edit the " "**Words** (comma-separated, one per chunk) and the **Link scene**, then " "click **Check and build the cards**.", ] if notes: parts.extend(["", *[f"- {note}" for note in notes]]) return "\n".join(parts), rows, "" def _events_checked( text: str, table: Any ) -> tuple[list[dict[str, Any]], list[str], str]: try: events = names_dates.parse_events(text) reviewed, errors, notes = names_dates.validate_event_rows(events, table) except ValueError as exc: return [], [], f"**Input issue:** {exc}" if errors: return [], notes, _issue_markdown( "Fix these first", errors + ["The cards were not built because a wrong word would change the date."], ) return reviewed, notes, "" def build_events(text: str, table: Any) -> tuple[str, Any, str]: reviewed, notes, error = _events_checked(text, table) if error: return error, _current_rows(table), "" status = [ "### Cards ready", "", f"All {len(reviewed)} date(s) pass the Major-System check, in the order " "you entered.", ] if notes: status.extend(["", *[f"- {note}" for note in notes]]) card = ( f"{names_dates.events_markdown(reviewed)}\n\n" f"{build_review_markdown(date.today())}" ) return "\n".join(status), names_dates.event_rows_for_table(reviewed), card def practice_events(text: str, table: Any) -> tuple[Any, ...]: reviewed, _notes, error = _events_checked(text, table) if error: return _practice_blocked(error) return _practice_from_cards( names_dates.event_practice(reviewed), "_Practicing your Dates cards: see the event, recall the pictures, " "decode the date._", ) def save_events_to_library( text: str, table: Any, name: str, library: Any ) -> tuple[Any, ...]: reviewed, _notes, error = _events_checked(text, table) if error: return (library, error, *_library_unchanged()) return _save_to_library( library, study_library.KIND_DATES, name, study_library.content_key( study_library.KIND_DATES, "\n".join(f"{r['event'].casefold()}|{r['when']}" for r in reviewed), ), names_dates.event_practice(reviewed), "", f"Dates · {len(reviewed)} events", ) # --------------------------------------------------------------------------- # Saved palace routes, and a warning when a route is reused too soon # --------------------------------------------------------------------------- def _route_controls() -> tuple[Any, ...]: """The palace box: saved-route picker, stops, and save-as-route row. Returns (picker, delete button, stops box, name box, save button, note). """ with gr.Row(elem_classes="ms-stack"): pick = gr.Dropdown( label="My routes", choices=[], value=None, info="Pick a saved route to fill in its stops.", scale=3, ) delete = gr.Button( "Delete route", size="sm", variant="stop", scale=0, min_width=140 ) stops = gr.Textbox( label="One familiar place per line, in order", placeholder="front door\nhallway\nkitchen\n...", lines=3, info=( "One stop per image keeps the order complete. Leave empty to build " "the story without a palace." ), ) with gr.Row(elem_classes="ms-stack"): name = gr.Textbox( label="Save these stops as a route", placeholder="e.g. Home, Walk to work", max_lines=1, scale=3, ) save = gr.Button("Save route", size="sm", scale=0, min_width=140) note = gr.Markdown(elem_classes="ms-muted") return pick, delete, stops, name, save, note def _route_dropdown(palaces: Any, value: str | None = None) -> Any: return gr.Dropdown(choices=palace_routes.choices(palaces), value=value) def refresh_route_pickers(palaces: Any) -> tuple[Any, Any]: return _route_dropdown(palaces), _route_dropdown(palaces) def use_saved_route(route_id: Any, palaces: Any) -> tuple[Any, Any, Any, str]: """Fill the palace box with a saved route and switch the anchor to it.""" route = palace_routes.clean(palaces)["routes"].get(str(route_id or "")) if route is None: return gr.update(), gr.update(), gr.update(), "" return ( gr.update(value=ANCHOR_PALACE), gr.update(value="\n".join(route["stops"]), visible=True), gr.update(value=route["name"]), f"Using **{_md_cell(route['name'])}**, {len(route['stops'])} stops. " "Edit the stops below for this story, or save them under a new name.", ) def save_route_handler( name: str, palace_text: str, palaces: Any ) -> tuple[Any, ...]: """Save the stops in the palace box under a name.""" try: stops = parse_palace_stops(palace_text) data, route_id, updated = palace_routes.save_route(palaces, name, stops) except ValueError as exc: return (palaces, gr.update(), gr.update(), f"**Route not saved:** {exc}") route = data["routes"][route_id] message = ( f"{'Updated' if updated else 'Saved'} **{_md_cell(route['name'])}** " f"({len(route['stops'])} stops) in this browser. Pick it from **My " "routes** in the Numbers or Ordered list tab." ) return (data, _route_dropdown(data), _route_dropdown(data), message) def delete_route_handler(route_id: Any, palaces: Any) -> tuple[Any, ...]: data, removed = palace_routes.delete_route(palaces, route_id) if removed is None: return (palaces, gr.update(), gr.update(), "Pick a saved route to delete.") return ( data, _route_dropdown(data), _route_dropdown(data), f"Deleted the route **{_md_cell(removed)}**. Stories already built " "are not changed.", ) def _palace_item( kind: str, input_text: str, table: Any, library: Any, chunking: str ) -> tuple[str, str] | None: """(item key, label) for the item just built, or None if it is not valid. The label never quotes the content: it is the item's library name, if the learner saved it, else its size ("a 9-digit number"). """ try: if kind == study_library.KIND_NUMBER: _cards, digits, problems = _number_table_cards( input_text, table, chunking ) key = study_library.content_key(kind, digits) label = f"a {len(digits)}-digit number" else: _cards, items, problems = _list_table_cards(table) key = study_library.content_key( kind, "\n".join(item.casefold() for item in items) ) label = f"a {len(items)}-item list" except ValueError: return None if problems: return None for item in study_library.clean_library(library).values(): if item["kind"] == kind and item["key"] == key: label = f"**{_md_cell(item['name'])}**" break return key, label def note_palace_use( kind: str, input_text: str, table: Any, anchor_mode: str, palace_text: str, status: str, palaces: Any, library: Any, chunking: str = CHUNK_PAIRS, ) -> tuple[Any, Any]: """After a palace build: warn if the route holds another recent item, then record that this item now lives there.""" if anchor_mode != ANCHOR_PALACE or not str(status or "").startswith( "### Check complete" ): return palaces, gr.update() try: stops = parse_palace_stops(palace_text) except ValueError: return palaces, gr.update() found = _palace_item(kind, input_text, table, library, chunking) if not stops or found is None: return palaces, gr.update() key, label = found today = date.today() others = palace_routes.recent_other_uses(palaces, stops, key, today) data = palace_routes.record_use(palaces, stops, key, label, today) if not others: return data, gr.update() name = palace_routes.route_name(data, stops) route = f"**{_md_cell(name)}**" if name else "This palace route" # Prefer the item's current library name, in case it was saved after its build. library_names = { item["key"]: f"**{_md_cell(item['name'])}**" for item in study_library.clean_library(library).values() } held = "; ".join( f"{library_names.get(use['item'], use['label'])} " f"({palace_routes.days_ago(use['date'], today)})" for use in others[:3] ) warning = ( f"**Palace check:** {route} already holds {held}. New pictures on the " "same stops tend to blur with the old ones (\"ghosting\"). If you want to " "keep both, give this one its own route; otherwise wait about " f"{palace_routes.GHOST_DAYS} days before reusing these stops." ) return data, f"{status}\n\n{warning}" # --------------------------------------------------------------------------- # Start-here shortcuts (switch tab and fill in an editable example) # --------------------------------------------------------------------------- def start_with_numbers( saved: Any = None, chunking: str = CHUNK_PAIRS ) -> tuple[Any, ...]: """Open the Numbers tab with the example drafted (see example_number_view).""" return (gr.update(selected="numbers"), *example_number_view(saved, chunking)) def start_with_list() -> tuple[Any, ...]: """Open the Ordered list tab with the example drafted.""" return (gr.update(selected="list"), *example_list_view()) def start_with_word() -> tuple[Any, ...]: term, context, use_model, status, rows, card = _example_word() return ( gr.update(selected="word"), term, context, use_model, status, rows, card, ) def start_with_practice() -> tuple[Any, ...]: return ( gr.update(selected="practice"), PRACTICE_NUMBER, NUMBER_EXAMPLE, *start_practice(PRACTICE_NUMBER, NUMBER_EXAMPLE), ) def start_practice_example() -> tuple[Any, ...]: return ( PRACTICE_NUMBER, NUMBER_EXAMPLE, *start_practice(PRACTICE_NUMBER, NUMBER_EXAMPLE), ) def _md_cell(text: str) -> str: return (text or "").replace("|", "\\|").replace("\n", " ").strip() def _issue_markdown(title: str, items: list[str]) -> str: if not items: return f"### {title}" return "\n".join([f"### {title}", ""] + [f"- {item}" for item in items]) def _current_rows(table: Any) -> list[list[str]]: return table_to_rows(table) def _chain_items_from_table(table: Any, kind: str) -> list[ChainItem]: items: list[ChainItem] = [] for row in _current_rows(table): row = list(row) + [""] * 6 code = row[0] if kind == "number" else "" if row[1]: items.append( ChainItem(label=row[1], cue=row[2], code=code, link=row[STORY_LINE_COLUMN]) ) return items def _scene_choice_label(index: int, code: str, subject: str, detail: str) -> str: if len(detail) > 70: detail = detail[:67].rstrip() + "…" if len(subject) > 32: subject = subject[:29].rstrip() + "…" head = " · ".join(part for part in (str(index), code, subject) if part) return f"{head}: {detail}" def _scene_choices(table: Any, kind: str) -> list[tuple[str, str]]: """Picture prompts: each link as one frozen moment, plus the whole chain in one picture when it is short enough for the image model.""" items = _chain_items_from_table(table, kind) if not items: return [] autos = auto_story_lines(items) moments = link_scene_prompts(items) choices: list[tuple[str, str]] = [] whole = chain_scene_prompt(items) seen = {whole} count = f"{len(items)} image" + ("" if len(items) == 1 else "s") choices.append((f"Whole chain in one picture ({count})", whole)) # Long chains crowd one picture, so also offer parts of four. for first, last, prompt in chain_scene_parts(items): if prompt not in seen: seen.add(prompt) choices.append((f"Images {first}-{last} in one picture", prompt)) for index, item in enumerate(items): link = " ".join(item.link.split()) # A line the learner (or model) wrote describes their own scene. prompt = link if index and link and link != autos[index] else moments[index] if prompt in seen: continue seen.add(prompt) choices.append( (_scene_choice_label(index + 1, item.code, item.label, prompt), prompt) ) return choices def number_scene_choices(table: Any, story: str) -> tuple[Any, Any, Any]: """Show one optional illustration picker after a number story is built.""" choices = _scene_choices(table, "number") if (story or "").strip() else [] return ( gr.Group(visible=bool(choices)), gr.Dropdown(choices=choices, value=choices[0][1] if choices else None), _hidden_file(), ) def list_scene_choices(table: Any, story: str) -> tuple[Any, Any, Any]: """Show one optional illustration picker after a list story is built.""" choices = _scene_choices(table, "list") if (story or "").strip() else [] return ( gr.Group(visible=bool(choices)), gr.Dropdown(choices=choices, value=choices[0][1] if choices else None), _hidden_file(), ) def remember_story_lines(table: Any) -> list[str]: """Record the generated lines just drafted, so a rebuild can tell them apart from lines the learner has since edited.""" return [ (list(row) + [""] * 6)[STORY_LINE_COLUMN] for row in _current_rows(table) ] def _add_story_lines(rows: list[list[str]], kind: str) -> None: """Insert a generated story line into each drafted row (column 3).""" items = [ ChainItem(label=row[1], cue=row[2], code=row[0] if kind == "number" else "") for row in rows ] for row, line in zip(rows, auto_story_lines(items)): row.insert(STORY_LINE_COLUMN, line) MAX_STORY_LINE_WORDS = 45 def _names_image(label: str, text: str) -> bool: """True if ``text`` names the image word, allowing a plural (lip/lips).""" needle = re.escape(" ".join(label.casefold().split())) pattern = r"(? tuple[list[str], list[str | None], list[str]]: """Decide each row's story line. A blank cell, or one still holding the line the app generated last time, gets a fresh generated line (so it follows any word you changed). Anything else is your line and is kept. The optional model may fill only the generated lines. Returns (lines, generated-record, status notes). """ autos = auto_story_lines(items, start_place) previous = list(last_generated) if isinstance(last_generated, list) else [] lines: list[str] = [] record: list[str | None] = [] for index, item in enumerate(items): cell = " ".join(item.link.split()) prior = previous[index] if index < len(previous) else None if not cell or cell == prior: lines.append(autos[index]) record.append(autos[index]) else: lines.append(cell) record.append(None) notes: list[str] = [] generated = [index for index, value in enumerate(record) if value is not None] if use_model and generated: try: raw = ask_story_lines([(item.label, item.cue) for item in items], kind) parsed = parse_indexed_cues(raw, len(items)) replaced = 0 for index in generated: line = " ".join(parsed.get(index, "").split()) if ( line and line not in STORY_EXAMPLE_LINES and _names_image(items[index].label, line) # A link must also touch the previous picture... and (index == 0 or _names_image(items[index - 1].label, line)) # ...must not give away the next one before its turn... and ( index + 1 >= len(items) or _names_image(items[index].label, items[index + 1].label) or not _names_image(items[index + 1].label, line) ) # ...and must stay short enough to read in one breath. and len(line.split()) <= MAX_STORY_LINE_WORDS ): lines[index] = line record[index] = None # keep it like your own line replaced += 1 notes.append( f"The local model wrote {replaced} of {len(generated)} story " "line(s); each one links its own image to the one before it. " "The rest use the built-in " "lines. Edit any line, or clear it to get a fresh one." if replaced else "The local model's story lines were not usable (each line " "must link its own image to the one before it, without giving " "away the next one), so the built-in " "lines are shown." ) except LocalModelError as exc: notes.append( f"The local model was not used: {exc.public_message} The built-in " "story lines are shown." ) except Exception: notes.append( "The local model was not used because an unexpected error " "occurred. The built-in story lines are shown." ) for index, value in enumerate(record): if value is not None: continue needed = [items[index].label] if index: needed.insert(0, items[index - 1].label) missing = [ label for label in needed if not _names_image(label, lines[index]) ] if missing: notes.append( f"Row {index + 1}'s story line does not mention " + " or ".join(f"**{label}**" for label in missing) + ". If you changed a word, update the line or clear it to get a " "fresh one." ) return lines, record, notes def word_card_scene(term: str, context: str, table: Any) -> tuple[Any, Any]: """Send the word card's own picture (Visual image + Mini-story) to the Image tab. Worksheet prompts that were never filled in are not used.""" prompts = { field.casefold(): text for field, text in word_default_drafts((term or "").strip(), (context or "").strip()) } fields: dict[str, str] = {} for row in _current_rows(table): row = list(row) + ["", ""] key = row[0].strip().casefold() value = " ".join(row[1].split()) if value and value != prompts.get(key): fields.setdefault(key, value) image = fields.get("visual image", "") story = fields.get("mini-story", "") if not image and not story: gr.Warning( "Fill in the Visual image (or Mini-story) row with your own picture " "first, then draw the card." ) return gr.update(), gr.update() first_story_sentence = re.split(r"(?<=[.!?])\s", story, maxsplit=1)[0] if story else "" cue = ". ".join(part.rstrip(". ") for part in (image, first_story_sentence) if part) return gr.Tabs(selected="image"), cue def illustrate_scene(scene: Any) -> tuple[Any, Any]: """Open the Image tab with one checked scene cue, ready to edit and draw.""" cue = str(scene or "").strip() if not cue: return gr.update(), gr.update() return gr.Tabs(selected="image"), cue def _list_cue_prompts(items: list[str]) -> list[str]: """No-model creative prompts, not generated definitions or facts.""" templates = ( "Make it huge, brightly colored, and moving; add a loud sound.", "Give it an impossible texture and a strong smell; make it wobble.", "Shrink it, then make it explode back to giant size.", "Put it in a ridiculous container that is much too small.", "Make it spin, bounce, or roll toward the next image.", "Give it a face and a comic expression; make it shout.", "Cover it in something unexpected: glitter, slime, or snow.", "Turn it into a giant version that blocks a doorway.", "Give it a bright spotlight and a dramatic entrance.", "Make it interact with the previous image in a surprising way.", ) return [templates[index % len(templates)] for index in range(len(items))] # --------------------------------------------------------------------------- # Personal word list (kept in the learner's own browser via gr.BrowserState) # --------------------------------------------------------------------------- SAVED_WORDS_KEY = "memory-studio-saved-words-v1" def _browser_secret() -> str: """Key that encrypts saved words in the browser's local storage. Gradio's default key changes on every restart, which would make saved words unreadable. Locally a stable key is derived from this install (nothing is written to disk). A hosted demo uses a per-process key unless MEMORY_BROWSER_SECRET is set, so visitors' saved words reset on restart. """ configured = os.getenv("MEMORY_BROWSER_SECRET", "").strip() if configured: return configured if PUBLIC_DEMO: return secrets.token_urlsafe(24) try: user = getpass.getuser() except Exception: user = "local" seed = f"memory-studio:{Path(__file__).resolve()}:{user}" return hashlib.sha256(seed.encode("utf-8")).hexdigest()[:32] def _saved_words_for( chunks: list[str], saved: Any ) -> dict[str, tuple[str, str]]: """Saved (word, cue) pairs for these chunks that still pass the check.""" found: dict[str, tuple[str, str]] = {} if not isinstance(saved, dict): return found for chunk in chunks: entry = saved.get(chunk) if not isinstance(entry, (list, tuple)) or not entry: continue word = str(entry[0] or "").strip()[:80] cue = str(entry[1] or "").strip()[:300] if len(entry) > 1 else "" if word and check_word_for_chunk(word, chunk)[0]: found[chunk] = (word, cue) return found def saved_word_rows(saved: Any) -> list[list[str]]: if not isinstance(saved, dict): return [] rows = [] for chunk in sorted(saved, key=lambda key: (len(str(key)), str(key))): entry = saved[chunk] if isinstance(entry, (list, tuple)) and entry: cue = str(entry[1]) if len(entry) > 1 else "" rows.append([str(chunk), str(entry[0]), cue]) return rows def save_number_words( number_text: str, table: Any, saved: Any, chunking: str = CHUNK_PAIRS ) -> tuple[Any, str, list[list[str]]]: """Remember every checked word in the table as the learner's default.""" current = dict(saved) if isinstance(saved, dict) else {} try: chunks = split_number(number_text, chunking) except ValueError as exc: return current, f"**Input issue:** {exc}", saved_word_rows(current) reviewed, errors = validate_number_rows(chunks, table) if errors: return ( current, _issue_markdown("Table needs attention", errors), saved_word_rows(current), ) stored, skipped = [], [] for row in reviewed: if row.word and row.check.startswith("match"): current[row.chunk] = [row.word, row.image] stored.append(row.chunk) else: skipped.append(row.chunk) lines = [ "### Words saved in this browser", "", f"Saved {len(stored)} word(s): " + (", ".join(f"`{chunk}`" for chunk in stored) or "none") + ". They are used first the next time a draft meets the same chunk.", ] if skipped: lines.append( "Not saved (word missing or failing the check): " + ", ".join(f"`{chunk}`" for chunk in skipped) + "." ) lines.append( "Saved words stay in this browser's local storage; they are not " "written to the app's disk." ) return current, "\n".join(lines), saved_word_rows(current) def forget_saved_words() -> tuple[Any, str, list[list[str]]]: return {}, "### Saved words cleared\n\nThis browser no longer stores any words.", [] def lookup_major_words(code_text: str) -> str: """List common dictionary words that encode a chunk, most frequent first.""" code = re.sub(r"\s", "", code_text or "") if not re.fullmatch(r"\d{1,4}", code): return "**Input issue:** enter 1 to 4 digits, for example `31`." words = words_for_code(code, 40) if not words: return ( f"No common dictionary word encodes `{code}`. Try two short words " "(for example an adjective + noun), or a personal name you can picture." ) return "\n".join( [ f"**Common words for `{code}`** (most frequent first):", "", ", ".join(words), "", "_Pick a concrete thing you can picture, then type it into the " "table's Word column. Pronunciations are American English; say the " "word aloud in your accent._", ] ) # Endings that usually mark an adverb, a verb form, or an abstract noun. _ABSTRACT_ENDINGS = ( "ly", "ing", "ed", "ness", "ity", "tion", "sion", "ment", "ous", "ive", "ful", "less", "ize", "ise", ) def _picturable_first(words: list[str]) -> list[str]: """Most common first, but move the first likely-concrete word to the front. A rough spelling heuristic: it prefers "angel" over "initially". The learner still sees every option and picks the picture. """ for index, word in enumerate(words): if not word.endswith(_ABSTRACT_ENDINGS): return [word, *words[:index], *words[index + 1 :]] return list(words) def draft_number_candidates( number_text: str, use_model: bool, saved: Any = None, chunking: str = CHUNK_PAIRS, ) -> tuple[str, list[list[str]], str]: """Draft an editable table: saved words first, then model, then curated (00-99) or common dictionary words (longer chunks).""" try: chunks = split_number(number_text, chunking) except ValueError as exc: return f"**Input issue:** {exc}", [], "" personal = _saved_words_for(chunks, saved) model_chunks = [chunk for chunk in dict.fromkeys(chunks) if chunk not in personal] accepted: dict[str, tuple[str, str]] = {} rejected: list[tuple[str, str, str]] = [] missing: list[str] = [] model_note = "" if use_model and not model_chunks: model_note = ( "Every chunk already has one of your saved words, so the local " "model was not needed." ) elif use_model: try: raw = ask_number_candidates(model_chunks) candidates = parse_number_rows(raw, model_chunks) if not candidates: model_note = ( "The local model returned no parseable rows. Curated starting " "words are shown instead." ) for chunk, (word, image) in candidates.items(): ok, check = check_word_for_chunk(word, chunk) if ok: accepted[chunk] = (word, image) else: rejected.append((chunk, word, check)) missing = [chunk for chunk in model_chunks if chunk not in candidates] if candidates: model_note = ( f"The local model returned candidates for " f"{len(candidates)}/{len(model_chunks)} chunk(s). " f"{len(accepted)} passed the Major-System check." ) except LocalModelError as exc: model_note = ( "Optional local model was not used: " f"{exc.public_message}" ) except Exception: model_note = ( "Optional local model was not used because an unexpected error " "occurred. Curated starting words are shown." ) else: model_note = ( "No-model mode: chunks without a saved word use a curated starting " "word (00-99) or a common dictionary word (longer chunks). Replace " "any word or cue with a personal association." ) rows: list[list[str]] = [] dictionary_options: dict[str, list[str]] = {} for chunk in chunks: if chunk in personal: word, image = personal[chunk] _ok, check = check_word_for_chunk(word, chunk) rows.append([chunk, word, image, check, "your saved word"]) continue if chunk in accepted: word, image = accepted[chunk] _ok, check = check_word_for_chunk(word, chunk) rows.append([chunk, word, image, check, "local model + check"]) continue curated = curated_candidate(chunk) if curated: word, image = curated source = "curated starter" if chunk in missing: source += " (model missed chunk)" _ok, check = check_word_for_chunk(word, chunk) rows.append([chunk, word, image, check, source]) continue # Longer chunks (000-999): a common dictionary word, if any. options = dictionary_options.setdefault( chunk, _picturable_first(words_for_code(chunk, 6)) ) if options: word = options[0] _ok, check = check_word_for_chunk(word, chunk) rows.append([chunk, word, f"a giant {word}", check, "common word"]) else: rows.append([chunk, "", "", "needs a word", "your entry"]) _add_story_lines(rows, "number") for row in rows: if not row[1]: row[STORY_LINE_COLUMN] = "" # written once the learner adds a word status_parts = [ "### Draft ready", "", f"{len(chunks)} chunk(s). Review the **Word**, **Image cue**, and " "**Story line** columns, " "edit any cell, then click **Check my edits and build the story**. " "Words are checked with a pronunciation dictionary, or an approximate " "spelling check for words it does not know.", "", model_note, ] if personal: status_parts.extend( ["", f"{sum(chunk in personal for chunk in chunks)} chunk(s) use your saved words."] ) status_parts.extend( [ "", "**Chunks:** " + " · ".join(f"`{chunk}`" for chunk in chunks), ] ) input_note = number_input_note(number_text) if input_note: status_parts.extend(["", input_note]) used_dictionary = { chunk: options for chunk, options in dictionary_options.items() if options and any(row[0] == chunk and row[5] == "common word" for row in rows) } if used_dictionary: status_parts.extend( [ "", "#### Words from the dictionary", "", "There is no curated word for these chunks, so the most common " "word is drafted. Common words include verbs and abstract words; " "swap in the one you can picture best.", "", "| Chunk | Drafted | Other options |", "|---:|---|---|", ] ) for chunk, options in used_dictionary.items(): status_parts.append( f"| `{chunk}` | {_md_cell(options[0])} | " f"{_md_cell(', '.join(options[1:]) or '(none)')} |" ) no_word = list(dict.fromkeys(row[0] for row in rows if not row[1])) if no_word: status_parts.extend( [ "", "**Needs your word:** no common word encodes " + ", ".join(f"`{chunk}`" for chunk in no_word) + ". Type a word whose consonant sounds give those digits (the " "check uses the full pronunciation dictionary), or " + ( "add a space inside that group in the number and draft again." if chunking == CHUNK_SPACES else "set **How to split** to **Where I put spaces** and " "group those digits your own way." ), ] ) if rejected: status_parts.extend( [ "", "#### Model candidates not auto-accepted", "", "The starting suggestion stayed in the table. If you believe the " "checker is wrong, copy the model word into the Word column and " "verify it aloud.", "", "| Chunk | Model word | Checker result |", "|---:|---|---|", ] ) for chunk, word, check in rejected: status_parts.append(f"| `{chunk}` | {_md_cell(word)} | {_md_cell(check)} |") if missing and accepted: status_parts.extend( [ "", "Model rows missing for: " + ", ".join(f"`{chunk}`" for chunk in missing) + ". Starting words were used for those chunks.", ] ) status_parts.extend( [ "", "**Order is locked to the digits.** Do not add or remove rows; " "regenerate if the number changes.", ] ) return "\n".join(status_parts), rows, "" def build_number_story( number_text: str, table: Any, use_model: bool, anchor_mode: str, palace_text: str, last_lines: Any = None, chunking: str = CHUNK_PAIRS, ) -> tuple[Any, ...]: """Build the number story; also returns the generated-line record.""" result = _build_number_story( number_text, table, use_model, anchor_mode, palace_text, last_lines, chunking ) return result if len(result) == 4 else (*result, gr.update()) def _build_number_story( number_text: str, table: Any, use_model: bool, anchor_mode: str, palace_text: str, last_lines: Any, chunking: str, ) -> tuple[Any, ...]: """Re-check edited rows, preserve order, and build complete story outputs.""" current_rows = _current_rows(table) try: chunks = split_number(number_text, chunking) except ValueError as exc: return f"**Input issue:** {exc}", current_rows, "" reviewed, errors = validate_number_rows(chunks, table) if errors: return _issue_markdown("Table needs attention", errors), current_rows, "" blockers = number_blockers(reviewed) reviewed_rows = [row.as_list() for row in reviewed] if blockers: return ( _issue_markdown( "Fix these before using the story", blockers + [ "The story was not built because an unchecked word would " "silently change the digits." ], ), reviewed_rows, "", ) try: stops = parse_palace_stops(palace_text) except ValueError as exc: return f"**Input issue:** {exc}", reviewed_rows, "" chain_items = [ ChainItem(label=row.word, cue=row.image, code=row.chunk, link=row.link) for row in reviewed ] start_place = stops[0] if anchor_mode == ANCHOR_PALACE and stops else "" lines, record, notes = _resolve_story_lines( chain_items, last_lines, start_place, use_model, "number" ) for row, item, line in zip(reviewed, chain_items, lines): row.link = item.link = line reviewed_rows = [row.as_list() for row in reviewed] status_parts = [ "### Check complete", "", f"All {len(reviewed)} chunk(s) pass the Major-System check. " "The story keeps the digit order.", ] input_note = number_input_note(number_text) if input_note: status_parts.extend(["", input_note]) for note in notes: status_parts.extend(["", note]) story_parts = [ "## Number \u2192 Major System", "", f"**Input:** `{number_text.strip()}`", "", build_ordered_chain(chain_items, start_place=start_place), ] palace = build_anchor_markdown(chain_items, anchor_mode, stops) if palace: story_parts.extend(["", palace]) story_parts.extend( [ "", build_recall_markdown("number", len(reviewed)), "", build_review_markdown(date.today()), "", "### Accuracy note", "", NUMBER_ACCURACY, ] ) return "\n".join(status_parts), reviewed_rows, "\n".join(story_parts), record def draft_list_candidates( list_text: str, use_model: bool ) -> tuple[str, list[list[str]], str]: """Draft editable image cues while preserving the learner's item order.""" try: items = parse_item_list(list_text) except ValueError as exc: return f"**Input issue:** {exc}", [], "" prompts = _list_cue_prompts(items) cues = list(prompts) model_note = "" supplied_count = 0 if use_model: try: raw = ask_list_cues(items) parsed = parse_indexed_cues(raw, len(items)) supplied_count = len(parsed) for index, cue in parsed.items(): if cue.casefold().strip() == items[index].casefold().strip(): continue cues[index] = cue missing_indices = [ index + 1 for index in range(len(items)) if index not in parsed ] if parsed: model_note = ( f"The local model supplied {supplied_count}/{len(items)} cue(s). " "Rows without a usable model cue keep a no-model editing prompt." ) if missing_indices: model_note += ( " Missing cue index/indices: " + ", ".join(str(index) for index in missing_indices) + "." ) else: model_note = ( "The local model returned no parseable cues. No-model editing " "prompts are shown instead." ) except LocalModelError as exc: model_note = ( "Optional local model was not used: " f"{exc.public_message}" ) except Exception: model_note = ( "Optional local model was not used because an unexpected error " "occurred. No-model editing prompts are shown." ) else: model_note = ( "No-model mode: each cue is a creative prompt to complete, not a " "generated description. Edit any cue with your own concrete image." ) rows = [ [str(index), item, cue] for index, (item, cue) in enumerate(zip(items, cues), 1) ] _add_story_lines(rows, "list") status_parts = [ "### Draft ready", "", f"{len(items)} item(s). The table order is the story order. Edit the " "**Image cue** and **Story line** columns freely, then click **Check my " "edits and build the story**.", "", model_note, "", "Keep every item row. If you need to correct an item label, update the " "list input as well so the source and table agree.", ] return "\n".join(status_parts), rows, "" def build_list_story( list_text: str, table: Any, use_model: bool, anchor_mode: str, palace_text: str, last_lines: Any = None, ) -> tuple[Any, ...]: """Build the list story; also returns the generated-line record.""" result = _build_list_story( list_text, table, use_model, anchor_mode, palace_text, last_lines ) return result if len(result) == 4 else (*result, gr.update()) def _build_list_story( list_text: str, table: Any, use_model: bool, anchor_mode: str, palace_text: str, last_lines: Any, ) -> tuple[Any, ...]: """Build a complete ordered list story from the edited cue table.""" current_rows = _current_rows(table) try: items = parse_item_list(list_text) except ValueError as exc: return f"**Input issue:** {exc}", current_rows, "" reviewed, errors = validate_list_rows(table) if errors: return _issue_markdown("Table needs attention", errors), current_rows, "" if len(reviewed) != len(items): return ( _issue_markdown( "Table needs attention", [ f"The table has {len(reviewed)} row(s) but the list has " f"{len(items)} item(s). Do not add or remove rows; regenerate " "from the list input if the list changed.", ], ), current_rows, "", ) original_counts = Counter(item.casefold() for item in items) table_counts = Counter(row.item.casefold() for row in reviewed) missing_counts = original_counts - table_counts if missing_counts: missing_labels = [] for label, count in missing_counts.items(): suffix = f" (x{count})" if count > 1 else "" missing_labels.append(f"**{label}**{suffix}") return ( _issue_markdown( "An original list item is missing", [ "The table no longer contains: " + ", ".join(missing_labels) + ".", "To prevent an accidental omission, the story was not built. " "Restore the item(s), or edit the list input and regenerate so " "the source and table agree.", ], ), [row.as_list() for row in reviewed], "", ) extra_counts = table_counts - original_counts extra_note = "" if extra_counts: extra_labels = [] for label, count in extra_counts.items(): suffix = f" (x{count})" if count > 1 else "" extra_labels.append(f"**{label}**{suffix}") extra_note = ( "The table contains extra item(s) not in the list input: " + ", ".join(extra_labels) + ". They are kept in the story; update the list input if you want " "the source to match." ) try: stops = parse_palace_stops(palace_text) except ValueError as exc: return f"**Input issue:** {exc}", [row.as_list() for row in reviewed], "" chain_items = [ ChainItem(label=row.item, cue=row.cue, link=row.link) for row in reviewed ] start_place = stops[0] if anchor_mode == ANCHOR_PALACE and stops else "" lines, record, notes = _resolve_story_lines( chain_items, last_lines, start_place, use_model, "list" ) for row, item, line in zip(reviewed, chain_items, lines): row.link = item.link = line status_parts = [ "### Check complete", "", f"All {len(reviewed)} item(s) are present in the table order.", ] if extra_note: status_parts.extend(["", extra_note]) for note in notes: status_parts.extend(["", note]) story_parts = [ "## Ordered list \u2192 story", "", build_ordered_chain(chain_items, start_place=start_place), ] palace = build_anchor_markdown(chain_items, anchor_mode, stops) if palace: story_parts.extend(["", palace]) story_parts.extend( [ "", build_recall_markdown("list", len(reviewed)), "", build_review_markdown(date.today()), "", "### Accuracy note", "", LIST_ACCURACY, ] ) return ( "\n".join(status_parts), [row.as_list() for row in reviewed], "\n".join(story_parts), record, ) def _validate_word_inputs(term: str, context: str) -> tuple[str, str]: term_text = (term or "").strip() context_text = (context or "").strip() if not term_text: raise ValueError("Enter a word or concept first.") if len(term_text) > MAX_WORD_TERM_LENGTH: raise ValueError( f"Keep the word or concept under {MAX_WORD_TERM_LENGTH} characters." ) if len(context_text) > MAX_WORD_CONTEXT_LENGTH: raise ValueError( f"Keep the optional context under {MAX_WORD_CONTEXT_LENGTH} characters." ) return term_text, context_text def _replace_word_field( rows: list[list[str]], field: str, value: str ) -> None: for row in rows: if row[0] == field: row[1] = value return def draft_word_fields( term: str, context: str, use_model: bool ) -> tuple[str, list[list[str]], str]: """Create an editable, no-fact-invention word card worksheet or model draft.""" try: term_text, context_text = _validate_word_inputs(term, context) except ValueError as exc: return f"**Input issue:** {exc}", [], "" rows = [list(pair) for pair in word_default_drafts(term_text, context_text)] if not use_model: return ( "\n".join( [ "### No-model worksheet ready", "", "Each row is an editing prompt, not a generated association or " "definition. Fill in the Draft column with your own sound-alike, " "image, story, location, and recall question, then assemble the " "card.", "", "No definition was invented. Add context you trust, or keep the " "card label-only.", ] ), rows, "", ) try: raw = ask_word_fields(term_text, context_text) sections, preamble = parse_word_sections(raw) except LocalModelError as exc: return ( "\n".join( [ "### No-model worksheet ready", "", "Optional local model was not used: " f"{exc.public_message}", "", "The editable prompts below are still usable.", ] ), rows, "", ) except Exception: return ( "\n".join( [ "### No-model worksheet ready", "", "The local model draft could not be read because an unexpected " "error occurred. The editable prompts below are still usable.", ] ), rows, "", ) supplied: list[str] = [] for field in WORD_FIELD_NAMES: if field == "Meaning anchor": continue value = sections.get(field, "").strip() if value: _replace_word_field(rows, field, value) supplied.append(field) model_meaning = sections.get("Meaning anchor", "").strip() unverified_meaning = False if not context_text and model_meaning: if "no definition supplied" not in model_meaning.casefold(): rows.append( [ "Unverified model meaning (do not treat as fact)", model_meaning, ] ) unverified_meaning = True elif context_text and model_meaning: pass # The learner's supplied context remains the factual anchor. if not sections: unstructured = preamble or raw.strip() if unstructured: rows.append(["Model draft (unstructured)", unstructured]) status_note = ( "The model did not follow the field labels; its text is preserved in " "the extra row. The six rows above remain editable prompts." ) else: status_note = ( f"The model supplied {len(supplied)}/{len(WORD_FIELD_NAMES) - 1} " "non-meaning field(s). Missing fields keep editing prompts." ) if preamble: rows.append(["Model notes (unstructured)", preamble]) status_parts = [ "### Draft ready", "", status_note, "", "Edit every cell freely, then click **Assemble my card**. The app cannot " "verify definitions; check technical meanings in a source you trust.", ] if context_text: status_parts.append( "Your supplied context is used as the meaning anchor. The model's " "meaning text was not substituted for it." ) else: status_parts.append( "No context was supplied, so no definition was accepted as fact." ) if unverified_meaning: status_parts.append( "The model's own meaning text is shown separately and labeled " "unverified. Do not treat it as a definition." ) return "\n".join(status_parts), rows, "" def assemble_word_outputs( term: str, context: str, table: Any ) -> tuple[str, list[list[str]], str]: """Assemble the edited word-card fields into a Markdown card.""" current_rows = _current_rows(table) try: term_text, context_text = _validate_word_inputs(term, context) card, missing = assemble_word_card(term_text, context_text, table) except ValueError as exc: return f"**Input issue:** {exc}", current_rows, "" status_parts = [ "### Card assembled", "", "Review the accuracy note at the bottom. Definitions are not verified by " "this app.", ] if missing: status_parts.extend( [ "", "Not filled in: " + ", ".join(missing) + ". Add these for a " "complete card.", ] ) card = f"{card}\n\n{build_review_markdown(date.today())}" return "\n".join(status_parts), current_rows, card # --------------------------------------------------------------------------- # Mind Map (deterministic SVG; no model) # --------------------------------------------------------------------------- MIND_MAP_EXAMPLE_TOPIC = "Memory" MIND_MAP_EXAMPLE = """Imagination exaggerate colour movement Association link pegs palace Review 10 minutes 1 day 1 week Numbers Major System shapes """ MAX_MIND_TOPIC_LENGTH = 40 def _mind_map_parts(topic: str, outline: str) -> tuple[str, list[tuple[str, list[str]]]]: topic_text = " ".join((topic or "").split()) if not topic_text: raise ValueError("Enter a central topic: a short word or phrase.") if len(topic_text) > MAX_MIND_TOPIC_LENGTH: raise ValueError( f"Keep the central topic under {MAX_MIND_TOPIC_LENGTH} characters." ) return topic_text, parse_outline(outline) MIND_VIEW_FULL = "Full map" MIND_VIEW_DETAILS = "Hide the details" MIND_VIEW_ALL = "Hide every branch" MIND_VIEWS = (MIND_VIEW_FULL, MIND_VIEW_DETAILS, MIND_VIEW_ALL) _MIND_HIDE = { MIND_VIEW_FULL: mind_map.HIDE_NONE, MIND_VIEW_DETAILS: mind_map.HIDE_DETAILS, MIND_VIEW_ALL: mind_map.HIDE_ALL, } def build_mind_map( topic: str, outline: str, view: str = MIND_VIEW_FULL ) -> tuple[str, str]: """Draw the outline as a Mind Map (or a recall view of it).""" try: topic_text, branches = _mind_map_parts(topic, outline) except ValueError as exc: return f"**Input issue:** {exc}", "" hide = _MIND_HIDE.get(view, mind_map.HIDE_NONE) if hide: hidden = ( "every branch word" if hide == mind_map.HIDE_ALL else "the details" ) status = ( f"### Recall test: {hidden} hidden\n\n" "Each **?** keeps its colour, place, and length. Say or write the " "hidden word for every **?**, going clockwise from the top, then " "switch **Show** back to **Full map** to check. Repair any branch you " "missed with a small picture." ) svg = mind_map.render_svg(topic_text, branches, hide) return status, f'
Build editable mnemonic cards with the Major System, link them into a complete ordered story, and optionally place them along a Memory Palace. Every suggestion stays yours to inspect and replace.