"""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'
{svg}
' lines = [ "### Mind Map ready", "", f"{len(branches)} main branch(es) and " f"{sum(len(subs) for _label, subs in branches)} detail(s). Every line of " "your outline is drawn, in order, clockwise from the top.", ] tips = key_word_tips(topic_text, branches) if tips: lines.extend(["", *[f"- {tip}" for tip in tips]]) lines.extend( [ "", "**Recall it:** cover the map and redraw it on paper from memory: the " "centre first, then each main branch in its colour, then the details. " "Compare, and add a small picture to any branch you missed.", ] ) svg = render_svg(topic_text, branches) return "\n".join(lines), f'
{svg}
' def mind_map_files(topic: str, outline: str) -> Any: try: topic_text, branches = _mind_map_parts(topic, outline) except ValueError as exc: raise gr.Error(str(exc)) from exc sheet = ( outline_markdown(topic_text, branches) + "\n\n" + build_review_markdown(date.today()) ) svg = render_svg(topic_text, branches) return _study_sheet(sheet, "mind-map", extra=((".svg", svg + "\n"),)) def practice_mind_map(topic: str, outline: str) -> tuple[Any, ...]: """Open the map's recall cards in the Practice tab.""" try: topic_text, branches = _mind_map_parts(topic, outline) except ValueError as exc: return _practice_blocked(f"**Input issue:** {exc}") return _practice_from_cards( mind_map.practice_cards(topic_text, branches), f"_Practicing your **{_md_cell(topic_text)}** Mind Map: the main " "branches first, then each branch's details._", ) def save_mind_map_to_library( topic: str, outline: str, name: str, library: Any ) -> tuple[Any, ...]: try: topic_text, branches = _mind_map_parts(topic, outline) except ValueError as exc: return (library, f"**Input issue:** {exc}", *_library_unchanged()) return _save_to_library( library, study_library.KIND_MINDMAP, name, study_library.content_key(study_library.KIND_MINDMAP, topic_text.casefold()), mind_map.practice_cards(topic_text, branches), "", topic_text, ) def mind_map_center_cue(topic: str) -> tuple[Any, Any]: """Send the central topic to the Image tab as a cue for one bold symbol.""" topic_text = " ".join((topic or "").split()) if not topic_text: return gr.update(), gr.update() return ( gr.Tabs(selected="image"), f"one bold, colourful symbol that stands for {topic_text}, centred on a " "plain page", ) EXAMPLE_IMAGE_CUE = ( "a giant wedge of cheese wearing a golden crown, dancing on a rooftop " "at sunset" ) EXAMPLE_IMAGE_CUE_TWO = ( "a bright red doormat floating above a chessboard, lit by a single " "spotlight" ) def load_example_image_cue() -> str: return EXAMPLE_IMAGE_CUE def load_second_image_cue() -> str: return EXAMPLE_IMAGE_CUE_TWO def _size_option(pixels: int) -> str: """Return the dropdown label for a pixel size.""" return next( (option for option in IMAGE_SIZE_OPTIONS if option.startswith(str(pixels))), IMAGE_SIZE_OPTIONS[0], ) def _size_from_label(label: str) -> int: token = str(label or "").strip().split(" ")[0] return int(token) if token.isdigit() else DEFAULT_IMAGE_SIZE def draw_local_image( cue: str, style: str, size_label: str, steps: float, seed: float ) -> tuple[str, Any | None]: """Draw one optional local image draft from an editable cue.""" size = _size_from_label(size_label) try: seed_value = int(seed) except (TypeError, ValueError): seed_value = -1 try: image, info = generate_cue_image( cue, style=style, size=size, steps=int(steps), seed=seed_value, ) except ValueError as exc: return f"**Input issue:** {exc}", None except LocalImageError as exc: return f"**Image model issue:** {exc.public_message}", None except Exception: return ( "**Image issue:** The local image model could not draw this cue. Try " "a shorter cue, a smaller size, fewer steps, or use the text-only " "route.", None, ) status = "\n".join( [ "### Local image draft" if not PUBLIC_DEMO else "### Image draft", "", ( f"Generated in **{info['seconds']}s** with `{info['model']}` on " f"`{info['device']}`." if PUBLIC_DEMO else f"Generated on this computer in **{info['seconds']}s** with " f"`{info['model']}` on `{info['device']}`." ), "", f"Seed `{info['seed']}`, {info['size']} × {info['size']} px, " f"{info['steps']} steps.", "", "This is an AI visual draft, not a factual illustration. Regenerate " "with a new seed or edit the cue if it misses the mnemonic point.", ] ) if info.get("dropped"): status += ( "\n\n**The cue was longer than the image model can read**, so these " f"words were not drawn: _{info['dropped']}_. Shorten the cue to one " "subject, one action, and one place." ) return status, image def _gpu_quota_message(exc: Exception) -> str | None: """A friendly status if ``exc`` is a ZeroGPU quota or availability error.""" text = str(exc).casefold() if "quota" in text or "zerogpu" in text or "no gpu" in text: return ( "**The free GPU is not available to you right now.** This Space gives " "each visitor a small daily ZeroGPU allowance, and it is used up (or " "the GPU is busy). Try again later, sign in to Hugging Face for a " "larger allowance, or run the app on your own computer. Everything " "except drawing still works." ) return None def _gpu_wrapped(handler: Any) -> Any: """Ask ZeroGPU for a GPU slice around one Draw when hosted on a Space. The decorator does nothing outside a ZeroGPU Space, and the local app never imports it. The image model is preloaded once for the Space, so only the sampling itself runs inside the allocated window. """ if not PUBLIC_DEMO: return handler try: import spaces except Exception: return handler gpu_handler = spaces.GPU(duration=60)(handler) def guarded(*args: Any) -> Any: try: return gpu_handler(*args) except Exception as exc: message = _gpu_quota_message(exc) if message is None: raise return message, None return guarded image_draw_handler = _gpu_wrapped(draw_local_image) def draw_and_keep( cue: str, style: str, size_label: str, steps: float, seed: float, history: list[Any] | None, ) -> tuple[Any, ...]: """Draw, then add the picture to the recent drafts, in one round trip. Only the drawing runs inside the GPU window. Outputs: status, image, history, gallery. """ status, image = image_draw_handler(cue, style, size_label, steps, seed) return (status, image, *append_image_history(image, history)) # --------------------------------------------------------------------------- # Combined handlers: each click is one server round trip, not a .then chain # --------------------------------------------------------------------------- def _number_view( status: str, rows: Any, story: str, *before: Any ) -> tuple[Any, ...]: """A drafted Numbers table plus its follow-ups. Outputs: (*before, status, table, story, illustrate box, scene picker, study sheet, generated-line record). """ return ( *before, status, rows, story, *number_scene_choices(rows, story), remember_story_lines(rows), ) def draft_number_view( number_text: str, use_model: bool, saved: Any = None, chunking: str = CHUNK_PAIRS, ) -> tuple[Any, ...]: return _number_view( *draft_number_candidates(number_text, use_model, saved, chunking) ) def example_number_view( saved: Any = None, chunking: str = CHUNK_PAIRS ) -> tuple[Any, ...]: """Outputs: number, model box, then the _number_view outputs.""" number, use_model, status, rows, story = _example_number(saved, chunking) return _number_view(status, rows, story, number, use_model) def build_number_view( number_text: str, table: Any, use_model: bool, anchor_mode: str, palace_text: str, last_lines: Any, chunking: str, palaces: Any, library: Any, ) -> tuple[Any, ...]: """Build the story, refresh the scene picker, and run the palace check. Outputs: status, table, story, line record, illustrate box, scene picker, study sheet, palace routes. """ status, rows, story, record = build_number_story( number_text, table, use_model, anchor_mode, palace_text, last_lines, chunking ) palaces, noted = note_palace_use( study_library.KIND_NUMBER, number_text, rows, anchor_mode, palace_text, status, palaces, library, chunking, ) if isinstance(noted, str): status = noted return (status, rows, story, record, *number_scene_choices(rows, story), palaces) def _list_view(status: str, rows: Any, story: str, *before: Any) -> tuple[Any, ...]: """A drafted list table plus its follow-ups (same order as _number_view).""" return ( *before, status, rows, story, *list_scene_choices(rows, story), remember_story_lines(rows), ) def draft_list_view(list_text: str, use_model: bool) -> tuple[Any, ...]: return _list_view(*draft_list_candidates(list_text, use_model)) def example_list_view() -> tuple[Any, ...]: """Outputs: list text, model box, then the _list_view outputs.""" text, use_model, status, rows, story = _example_list() return _list_view(status, rows, story, text, use_model) def build_list_view( list_text: str, table: Any, use_model: bool, anchor_mode: str, palace_text: str, last_lines: Any, palaces: Any, library: Any, ) -> tuple[Any, ...]: """Build the list story, refresh the scene picker, run the palace check.""" status, rows, story, record = build_list_story( list_text, table, use_model, anchor_mode, palace_text, last_lines ) palaces, noted = note_palace_use( study_library.KIND_LIST, list_text, rows, anchor_mode, palace_text, status, palaces, library, ) if isinstance(noted, str): status = noted return (status, rows, story, record, *list_scene_choices(rows, story), palaces) def build_mind_map_view( topic: str, outline: str, view: str = MIND_VIEW_FULL ) -> tuple[Any, Any, Any]: """Draw the map and hide a download that no longer matches it.""" return (*build_mind_map(topic, outline, view), _hidden_file()) def example_mind_map_view() -> tuple[Any, ...]: """Outputs: topic, outline, view, status, map, files.""" return ( MIND_MAP_EXAMPLE_TOPIC, MIND_MAP_EXAMPLE, MIND_VIEW_FULL, *build_mind_map_view(MIND_MAP_EXAMPLE_TOPIC, MIND_MAP_EXAMPLE), ) def load_browser_views( saved: Any, library: Any, palaces: Any, stats: Any ) -> tuple[Any, ...]: """Fill every view kept in browser storage when the page opens. Outputs: saved-word table, the five library views, both route pickers, trainer's hardest-numbers table. """ return ( saved_word_rows(saved), *_library_view(library), *refresh_route_pickers(palaces), trainer_hardest(stats, saved), ) # One key for every browser-stored value, made once per process. BROWSER_SECRET = _browser_secret() # Read the pronunciation dictionary in the background, so the first draft # does not wait for it. It reads only the bundled files. threading.Thread( target=warm_up_dictionary, name="dictionary-warm-up", daemon=True ).start() # Requests that do not touch a model run side by side. The text model and the # image pipeline each hold their own lock, and Draw keeps a limit of one. QUEUE_CONCURRENCY = 4 # delete_cache: every hour, drop Gradio's copies of files older than a day. with gr.Blocks( title="Memory Studio · picture it, remember it", delete_cache=(3600, 86400), ) as demo: # Saved words live in this browser's local storage, never on the server. personal_words = gr.BrowserState( {}, storage_key=SAVED_WORDS_KEY, secret=BROWSER_SECRET ) # So do library items and their review dates. library_state = gr.BrowserState( {}, storage_key=study_library.LIBRARY_KEY, secret=BROWSER_SECRET ) # And the 00-99 trainer's per-number results (counts only, no study text). trainer_stats = gr.BrowserState( {}, storage_key=peg_trainer.TRAINER_STATS_KEY, secret=BROWSER_SECRET ) # And saved palace routes, plus which item was last placed on each route. palace_state = gr.BrowserState( {}, storage_key=palace_routes.PALACES_KEY, secret=BROWSER_SECRET ) gr.HTML( f"""
Memory Studio · picture it, remember it

Turn numbers, words, and lists into pictures you can recall.

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.

No model required Edit every suggestion Download a study sheet
""" ) if PUBLIC_DEMO: gr.Markdown( "**Online version: where your text goes.** What you type is " "processed on this Hugging Face Space's servers, not on your device. " "The app does not save it, but avoid pasting secrets or private " "notes. For full privacy, run Memory Studio on your own computer " "(see **Guide & privacy**).", elem_classes="ms-note", ) with gr.Tabs(selected="start", overflow_behavior="wrap") as tabs: with gr.TabItem("Start here", id="start"): with gr.Row(elem_classes="ms-stack"): start_due = gr.Markdown(elem_classes="ms-note") start_open_library = gr.Button( "Open My library", variant="primary", size="sm", scale=0, min_width=170, visible=False, ) gr.Markdown( """ ### Pick a starting point Every option below works without a model and fills the next tab with an editable example. """ ) with gr.Row(equal_height=True): with gr.Column(elem_classes="ms-card", min_width=220): gr.Markdown( "### 🔢 Numbers\n" "Split a number into pairs, threes, or your own groups " "and give each chunk a vivid word and image." ) start_numbers = gr.Button( "Try 314159", variant="primary", size="sm" ) with gr.Column(elem_classes="ms-card", min_width=220): gr.Markdown( "### 📝 Ordered list\n" "Turn a shopping list, recipe, or outline into a linked " "story that keeps its order." ) start_list = gr.Button( "Try a grocery list", variant="primary", size="sm" ) with gr.Column(elem_classes="ms-card", min_width=220): gr.Markdown( "### 🧩 Word card\n" "Build a sound-alike, a scene, and a recall question for " "any word or concept." ) start_word = gr.Button( "Try “Pomodoro”", variant="primary", size="sm" ) with gr.Column(elem_classes="ms-card", min_width=220): gr.Markdown( "### 🎯 Recall practice\n" "Test yourself card by card, in the original order, with " "no model involved." ) start_practice_card = gr.Button( "Start practicing", variant="primary", size="sm" ) with gr.Column(elem_classes="ms-card", min_width=220): gr.Markdown( "### 🗺️ Mind Map\n" "Put a topic in the centre and its key words on coloured " "branches, all on one page." ) start_mind_map = gr.Button( "Try a Mind Map", variant="primary", size="sm" ) with gr.Column(elem_classes="ms-card", min_width=220): gr.Markdown( "### 🔁 00–99 trainer\n" "Drill your number words both ways until each one comes " "back in a couple of seconds." ) start_trainer_card = gr.Button( "Drill 00–19", variant="primary", size="sm" ) with gr.Column(elem_classes="ms-card", min_width=220): gr.Markdown( "### 👥 Names & dates\n" "Link a name to a face feature, or a date to its event, " "with pictures you can recall." ) start_names_card = gr.Button( "Try names & faces", variant="primary", size="sm" ) gr.Markdown("### How it works") gr.HTML( """
1
Draft
Use the deterministic curated words or an optional local-AI draft. Nothing is final.
2
Edit
Replace any word, image cue, or route with one that is vivid for you. The app re-checks the order.
3
Build & practice
Get a linked story you can read aloud, a recall prompt, and a Markdown study sheet you can keep.
""", elem_id="ms-how", ) gr.Markdown( "**No model needed.** The deterministic route downloads nothing " "and never calls a model. Optional AI drafts are off by default; " "turn one on inside a tab only when you want a suggestion.", elem_classes="ms-note", ) gr.Markdown( """ ### 🎨 Buzan's golden rules for making a picture stick Tony Buzan's **"golden rules"** turn an ordinary picture into one you can recall at will. Use them whenever you draft or edit an image cue or story line. * **Movement**: make it do something: flying, bursting, rolling, colliding. * **Association**: glue this picture to the one before it (or to its palace spot) so one triggers the next. * **Sensuality**: give it a sound, smell, taste, or feel; the more senses it uses, the deeper it sticks. * **Humour**: funny, ridiculous, or embarrassing pictures are remembered far longer than boring ones. * **Imagination**: exaggerate. Make it huge, glowing, upside-down, or doing the impossible. * **Number**: give it a number or count so you recall its position in the sequence. * **Symbolism**: stand for its meaning with a single, clear object (a crown = royalty, a key = unlocking). * **Colour**: make it brightly coloured; one vivid colour beats ten grey ones. * **Order**: keep items in a fixed sequence so you can jump straight to position 17 without counting from one. * **Positive**: positive or aspirational images last better than dark or frightening ones. * **Exaggeration**: nothing should be life-size; make it colossal or microscopic, fast or slow-motion. * **Sexuality**: use magnetism, romance, or tension if it fits your picture (keep it tasteful and respectful). In practice: pick three of these for every image cue: one for what it does, one for how it looks, and one for how it links to the picture before it. """, elem_classes="ms-note", ) with gr.Accordion("Optional AI status", open=False): gr.Markdown(model_status_markdown(hosted=PUBLIC_DEMO)) gr.Markdown(image_model_status_markdown(hosted=PUBLIC_DEMO)) with gr.TabItem("My library", id="library"): gr.Markdown( """ ### Reviews that come back on time Save a story or card here and the library follows Buzan's review rhythm for you: about 10 minutes after you learn it, then 1 day, 1 week, 1 month, and 4 months later. Recall each item from memory when it is due. """ ) library_summary = gr.Markdown(LIBRARY_EMPTY) library_table = gr.Dataframe( headers=["Name", "Type", "Next step", "Due", "Reviews done"], datatype=["str", "str", "str", "str", "str"], type="array", value=[], interactive=False, wrap=True, ) with gr.Row(elem_classes="ms-stack"): library_pick = gr.Dropdown( label="Item", choices=[], value=None, scale=3 ) library_review = gr.Button( "Review this item", variant="primary", size="sm", scale=0, min_width=170, ) library_remove = gr.Button( "Remove from library", variant="stop", size="sm", scale=0, min_width=170, ) library_status = gr.Markdown() gr.Markdown( "**How the schedule moves.** A review counts when the item is due. " "Recall every card and the item moves to the next step. Miss any " "card and it comes back tomorrow, restarting from the 1-day " "review, so repair the weak pictures first. After the 4-month " "review, the library checks it every 6 months.\n\n" "**Where it is kept.** Only in this browser's local storage, like " "your saved words. It is not written to the app's disk, and " "clearing site data removes it. Names are shown here instead of " "the content, so the list does not give the answers away." + ( " In the online version the library can reset when the Space " "restarts." if PUBLIC_DEMO and not os.getenv("MEMORY_BROWSER_SECRET") else "" ), elem_classes="ms-muted", ) with gr.TabItem("Numbers", id="numbers"): gr.Markdown( """ ### 1 · Enter a number Leading zeros are kept. Up to 40 digits are split into chunks, each with one picture; the table order is locked to the digit order. """, ) gr.Markdown( """ #### ✨ Make every picture vivid: Buzan's golden rules Pick three rules per image cue: **Movement** (make it do something) • **Association** (link it to the picture before it) • **Sensuality** (give it a sound, smell, or feel) • **Humour** (make it funny or absurd) • **Imagination** (exaggerate: huge, glowing, upside-down) • **Number** (give it a position) • **Symbolism** (one clear object) • **Colour** (one bright colour) • **Order** (fixed sequence) • **Positive** (positive images last longer) • **Exaggeration** (colossal or microscopic) • **Sexuality** (magnetism or tension, tasteful and respectful). In practice: one rule for *what it does*, one for *how it looks*, one for *how it links to the previous picture*. """, elem_classes="ms-muted", ) with gr.Row(elem_classes="ms-stack"): number_input = gr.Textbox( label="Number", placeholder="Try 314159, 0042, or 0412 555 019", lines=1, scale=4, ) number_example = gr.Button( "Try 314159", size="sm", scale=0, min_width=140 ) number_chunking = gr.Radio( label="How to split", choices=list(CHUNK_MODES), value=CHUNK_PAIRS, info=( "Pairs use the 00-99 words. Threes give fewer, longer words " "(314 = meter). Where I put spaces follows your own groups, " "for example 0412 555 019 or 19/11/2026; a group of four or " "more digits is split into pairs." ), ) number_use_model = gr.Checkbox( label="Optional: draft rows with the local text model", value=False, info=( "First AI draft may download public model weights. Leave " "unchecked for the deterministic curated set." ), ) number_generate = gr.Button( "Draft candidate rows", variant="primary" ) number_status = gr.Markdown() number_table = gr.Dataframe( headers=NUMBER_HEADERS, datatype=["str"] * len(NUMBER_HEADERS), type="array", value=[], interactive=True, wrap=True, column_widths=["8%", "12%", "24%", "38%", "11%", "7%"], label="Review and edit every Word, Image cue, and Story line", ) # The story lines the app generated last, to tell them from edits. number_story_lines = gr.State([]) with gr.Accordion("My saved words (this browser)", open=False): gr.Markdown( "After a story builds, **Save these words** remembers each " "checked word as your personal default for that chunk. Drafts " "use your saved words first, and the **00–99 trainer** tab " "drills them. They are stored only in this browser's local " "storage.", elem_classes="ms-muted", ) number_saved_table = gr.Dataframe( headers=["Chunk", "Word", "Image cue"], datatype=["str", "str", "str"], type="array", value=[], interactive=False, wrap=True, ) number_forget = gr.Button( "Forget all saved words", size="sm", variant="stop" ) with gr.Accordion("Find other words for a chunk", open=False): with gr.Row(elem_classes="ms-stack"): number_lookup_code = gr.Textbox( label="Digits (1-4)", placeholder="31", max_lines=1, scale=3, ) number_lookup_button = gr.Button( "Find words", size="sm", scale=0, min_width=140 ) number_lookup_result = gr.Markdown() number_lookup_button.click( lookup_major_words, inputs=[number_lookup_code], outputs=[number_lookup_result], ) number_lookup_code.submit( lookup_major_words, inputs=[number_lookup_code], outputs=[number_lookup_result], ) with gr.Accordion( "Optional: anchor each image to a palace or pegs", open=False ): number_anchor = gr.Radio( label="Anchor", choices=list(ANCHOR_MODES), value=ANCHOR_PALACE, info=( "A palace uses places you know. Pegs are fixed numbered " "images, so you can jump straight to any position." ), ) with gr.Column() as number_palace_box: ( number_route_pick, number_route_delete, number_palace, number_route_name, number_route_save, number_route_note, ) = _route_controls() number_anchor.change( lambda mode: gr.update(visible=mode == ANCHOR_PALACE), inputs=[number_anchor], outputs=[number_palace_box], ) with gr.Row(): number_build = gr.Button( "Check my edits and build the story", variant="primary", scale=3, ) with gr.Group(visible=False) as number_illustrate_box: gr.Markdown( "**Optional picture.** The story is the mnemonic; a picture " "is a hint for one tricky scene. Pick a scene to open its cue " "in the Image tab, where you can edit it and draw.", elem_classes="ms-muted", ) with gr.Row(elem_classes="ms-stack"): number_scene = gr.Dropdown( label="Scene to draw", choices=[], value=None, scale=3, ) number_illustrate = gr.Button( "Open in Image tab", size="sm", scale=0, min_width=180, ) number_story = gr.Markdown() with gr.Row(elem_classes="ms-stack"): number_library_name = gr.Textbox( label="Name in My library (optional)", placeholder="e.g. Pi, bike lock, Mum's phone", max_lines=1, scale=3, ) number_library_save = gr.Button( "Save to my library", size="sm", variant="secondary", scale=0, min_width=180, ) with gr.Row(): number_practice = gr.Button( "Practice these cards", size="sm", variant="primary", scale=0, min_width=180, ) number_save_words = gr.Button( "Save these words", size="sm", variant="secondary", scale=0, min_width=160, ) number_sheet_button = gr.Button( "Download study sheet (.md)", size="sm", variant="secondary", scale=0, min_width=200, ) number_clear = gr.ClearButton( [ number_input, number_status, number_table, number_story, number_palace, number_library_name, ], value="Clear", size="sm", scale=0, min_width=110, ) number_sheet = gr.File( label="Study sheet", show_label=False, interactive=False, visible=False, file_count="multiple", ) number_draft_outputs = [ number_status, number_table, number_story, number_illustrate_box, number_scene, number_sheet, number_story_lines, ] for number_draft_event in (number_generate.click, number_input.submit): number_draft_event( draft_number_view, inputs=[ number_input, number_use_model, personal_words, number_chunking, ], outputs=number_draft_outputs, ) number_example.click( example_number_view, inputs=[personal_words, number_chunking], outputs=[number_input, number_use_model, *number_draft_outputs], ) number_build.click( build_number_view, inputs=[ number_input, number_table, number_use_model, number_anchor, number_palace, number_story_lines, number_chunking, palace_state, library_state, ], outputs=[ number_status, number_table, number_story, number_story_lines, number_illustrate_box, number_scene, number_sheet, palace_state, ], ) number_clear.click( lambda: ( gr.Group(visible=False), gr.Dropdown(choices=[], value=None), _hidden_file(), ), inputs=None, outputs=[number_illustrate_box, number_scene, number_sheet], ) number_sheet_button.click( _number_sheet, inputs=[number_story], outputs=[number_sheet] ) with gr.TabItem("00–99 trainer", id="trainer"): gr.Markdown( """ ### Make your number words automatic The Major System pays off once every number calls up the same word instantly, and every word its number. Drill a small range, then widen it. Answers are checked against your saved words, or the starter words where you have none. """ ) with gr.Row(elem_classes="ms-stack"): trainer_range = gr.Textbox( label="Numbers to drill", value="00-99", placeholder="00-99, 00-19, 0-9, or 7, 42, 85", max_lines=1, scale=2, ) trainer_direction = gr.Radio( label="Direction", choices=list(peg_trainer.DIRECTIONS), value=peg_trainer.TO_WORD, scale=2, ) trainer_count = gr.Dropdown( label="Cards", choices=list(peg_trainer.COUNT_CHOICES), value="20", scale=1, min_width=110, ) with gr.Row(elem_classes="ms-stack"): trainer_hardest_first = gr.Checkbox( label="Weakest numbers first (uses your past results)", value=False, ) trainer_start = gr.Button( "Start drill", variant="primary", scale=0, min_width=170 ) trainer_progress = gr.Markdown() trainer_prompt = gr.Markdown(TRAINER_IDLE) with gr.Row(visible=False, elem_classes="ms-stack") as trainer_answer_row: trainer_answer = gr.Textbox( label="Your answer", max_lines=1, scale=3, ) trainer_check = gr.Button( "Check", variant="primary", scale=0, min_width=110 ) trainer_skip = gr.Button( "I don't know", scale=0, min_width=140 ) trainer_feedback = gr.Markdown(elem_classes="ms-answer") trainer_summary = gr.Markdown(visible=False) trainer_retry = gr.Button( "Retry the missed ones", variant="primary", visible=False ) with gr.Accordion("Numbers you miss most (this browser)", open=False): gr.Markdown( "Based on your last five answers for each number. Results " "stay in this browser's local storage, like your saved words.", elem_classes="ms-muted", ) trainer_hardest_table = gr.Dataframe( headers=["Number", "Word", "Last 5", "All time"], datatype=["str", "str", "str", "str"], type="array", value=[], interactive=False, wrap=True, ) with gr.Row(): trainer_reset = gr.Button( "Clear trainer results", size="sm", variant="stop", scale=0 ) trainer_reset_status = gr.Markdown() trainer_state = gr.State({}) trainer_session_outputs = [ trainer_state, trainer_progress, trainer_prompt, trainer_feedback, trainer_answer, trainer_answer_row, trainer_summary, trainer_retry, ] with gr.TabItem("Word card", id="word"): gr.Markdown( """ ### 1 · Enter a word or concept Add context or a definition **you trust** to keep the factual anchor honest. Without context, the app will not invent a definition: the card stays label-only and the meaning row remains an editing prompt. """ ) with gr.Row(elem_classes="ms-stack"): word_term = gr.Textbox( label="Word or concept", placeholder="Try a term, a name, or a short phrase", lines=1, scale=4, ) word_example = gr.Button( "Try “Pomodoro”", size="sm", scale=0, min_width=160 ) word_context = gr.Textbox( label="Optional context or definition you trust", placeholder=( "Paste a definition from a source you trust, or a short note " "about what this term means in your context." ), lines=4, info=( "Used only as the factual anchor. Leave blank for a label-only " "mnemonic." ), ) word_use_model = gr.Checkbox( label="Optional: draft card fields with the local text model", value=False, info="Leave unchecked for an editable no-model worksheet.", ) word_draft = gr.Button("Draft card fields", variant="primary") word_status = gr.Markdown() word_table = gr.Dataframe( headers=WORD_HEADERS, datatype=["str"] * len(WORD_HEADERS), type="array", value=[], interactive=True, wrap=True, column_widths=["32%", "68%"], label="Edit any field freely", ) word_assemble = gr.Button("Assemble my card", variant="primary") word_card = gr.Markdown() with gr.Row(): word_picture = gr.Button( "Draw this card", size="sm", variant="secondary", scale=0, min_width=160, ) word_library_save = gr.Button( "Save to my library", size="sm", variant="secondary", scale=0, min_width=180, ) word_sheet_button = gr.Button( "Download study sheet (.md)", size="sm", variant="secondary", scale=0, min_width=200, ) word_clear = gr.ClearButton( [ word_term, word_context, word_status, word_table, word_card, ], value="Clear", size="sm", scale=0, min_width=110, ) word_sheet = gr.File( label="Study sheet", show_label=False, interactive=False, visible=False, file_count="multiple", ) word_draft.click( draft_word_fields, inputs=[word_term, word_context, word_use_model], outputs=[word_status, word_table, word_card], ) word_term.submit( draft_word_fields, inputs=[word_term, word_context, word_use_model], outputs=[word_status, word_table, word_card], ) word_example.click( _example_word, inputs=None, outputs=[ word_term, word_context, word_use_model, word_status, word_table, word_card, ], ) word_assemble.click( assemble_word_outputs, inputs=[word_term, word_context, word_table], outputs=[word_status, word_table, word_card], ) word_sheet_button.click( _word_sheet, inputs=[word_card], outputs=[word_sheet] ) for word_event in ( word_draft.click, word_term.submit, word_assemble.click, word_example.click, word_clear.click, ): word_event(_hidden_file, inputs=None, outputs=[word_sheet]) with gr.TabItem("Ordered list", id="list"): gr.Markdown( f""" ### 1 · Enter an ordered list Put one item per line, or use commas on a single line. Numbered and bulleted lists are accepted. Up to {MAX_LIST_ITEMS} items are supported. The table order is the story order; the build step refuses to silently drop an original item. """ ) list_input = gr.Textbox( label="Ordered list", placeholder="milk\neggs\ncoffee\n\nor: milk, eggs, coffee", lines=6, ) list_use_model = gr.Checkbox( label="Optional: draft image cues with the local text model", value=False, info="Leave unchecked for editable creative prompts.", ) with gr.Row(elem_classes="ms-stack"): list_generate = gr.Button( "Draft image cues", variant="primary", scale=2 ) list_example = gr.Button( "Try a grocery list", size="sm", scale=0, min_width=180 ) list_status = gr.Markdown() list_table = gr.Dataframe( headers=LIST_HEADERS, datatype=["str"] * len(LIST_HEADERS), type="array", value=[], interactive=True, wrap=True, column_widths=["6%", "20%", "30%", "44%"], label="Review and edit the image cues and story lines", ) list_story_lines = gr.State([]) with gr.Accordion( "Optional: anchor each image to a palace or pegs", open=False ): list_anchor = gr.Radio( label="Anchor", choices=list(ANCHOR_MODES), value=ANCHOR_PALACE, info=( "A palace uses places you know. Pegs are fixed numbered " "images, so you can jump straight to any position." ), ) with gr.Column() as list_palace_box: ( list_route_pick, list_route_delete, list_palace, list_route_name, list_route_save, list_route_note, ) = _route_controls() list_anchor.change( lambda mode: gr.update(visible=mode == ANCHOR_PALACE), inputs=[list_anchor], outputs=[list_palace_box], ) list_build = gr.Button( "Check my edits and build the story", variant="primary" ) with gr.Group(visible=False) as list_illustrate_box: gr.Markdown( "**Optional picture.** The story is the mnemonic; a picture " "is a hint for one tricky scene. Pick a scene to open its cue " "in the Image tab, where you can edit it and draw.", elem_classes="ms-muted", ) with gr.Row(elem_classes="ms-stack"): list_scene = gr.Dropdown( label="Scene to draw", choices=[], value=None, scale=3, ) list_illustrate = gr.Button( "Open in Image tab", size="sm", scale=0, min_width=180, ) list_story = gr.Markdown() with gr.Row(elem_classes="ms-stack"): list_library_name = gr.Textbox( label="Name in My library (optional)", placeholder="e.g. Speech outline, Saturday shopping", max_lines=1, scale=3, ) list_library_save = gr.Button( "Save to my library", size="sm", variant="secondary", scale=0, min_width=180, ) with gr.Row(): list_practice = gr.Button( "Practice these cards", size="sm", variant="primary", scale=0, min_width=180, ) list_sheet_button = gr.Button( "Download study sheet (.md)", size="sm", variant="secondary", scale=0, min_width=200, ) list_clear = gr.ClearButton( [ list_input, list_status, list_table, list_story, list_palace, list_library_name, ], value="Clear", size="sm", scale=0, min_width=110, ) list_sheet = gr.File( label="Study sheet", show_label=False, interactive=False, visible=False, file_count="multiple", ) list_draft_outputs = [ list_status, list_table, list_story, list_illustrate_box, list_scene, list_sheet, list_story_lines, ] for list_draft_event in (list_generate.click, list_input.submit): list_draft_event( draft_list_view, inputs=[list_input, list_use_model], outputs=list_draft_outputs, ) list_example.click( example_list_view, inputs=None, outputs=[list_input, list_use_model, *list_draft_outputs], ) list_build.click( build_list_view, inputs=[ list_input, list_table, list_use_model, list_anchor, list_palace, list_story_lines, palace_state, library_state, ], outputs=[ list_status, list_table, list_story, list_story_lines, list_illustrate_box, list_scene, list_sheet, palace_state, ], ) list_clear.click( lambda: ( gr.Group(visible=False), gr.Dropdown(choices=[], value=None), _hidden_file(), ), inputs=None, outputs=[list_illustrate_box, list_scene, list_sheet], ) list_sheet_button.click( _list_sheet, inputs=[list_story], outputs=[list_sheet] ) with gr.TabItem("Names & dates", id="namesdates"): with gr.Tabs(): with gr.TabItem("Names & faces", id="names"): gr.Markdown( """ ### Remember who is who One person per line: **name | face feature | where you met** (the last two are optional here, but each card needs at least one). The app drafts a sound-alike for the name; you link it to the feature you will see next time. """ ) with gr.Row(elem_classes="ms-stack"): people_input = gr.Textbox( label="People", placeholder=( "Margaret Chen | big round glasses | finance team" ), lines=4, scale=4, ) people_example = gr.Button( "Try an example", size="sm", scale=0, min_width=150 ) gr.Markdown( "_Names are personal details. They stay in this session " "unless you save the cards to My library in this " "browser; the app never writes them to its disk or logs._", elem_classes="ms-muted", ) people_draft = gr.Button("Draft name cards", variant="primary") people_status = gr.Markdown() people_table = gr.Dataframe( headers=names_dates.NAME_HEADERS, datatype=["str"] * len(names_dates.NAME_HEADERS), type="array", value=[], interactive=True, wrap=True, column_widths=["16%", "18%", "18%", "33%", "15%"], label="Edit every face feature, sound-alike, and scene", ) people_build = gr.Button( "Check and build the cards", variant="primary" ) people_card = gr.Markdown() with gr.Row(elem_classes="ms-stack"): people_library_name = gr.Textbox( label="Name in My library (optional)", placeholder="e.g. New team, Sam's party", max_lines=1, scale=3, ) people_library_save = gr.Button( "Save to my library", size="sm", scale=0, min_width=180, ) with gr.Row(): people_practice = gr.Button( "Practice these cards", size="sm", variant="primary", scale=0, min_width=180, ) people_sheet_button = gr.Button( "Download study sheet (.md)", size="sm", scale=0, min_width=200, ) people_sheet = gr.File( show_label=False, interactive=False, visible=False, file_count="multiple", ) people_draft.click( draft_people, inputs=[people_input], outputs=[people_status, people_table, people_card], ) people_example.click( lambda: (PEOPLE_EXAMPLE, *draft_people(PEOPLE_EXAMPLE)), inputs=None, outputs=[people_input, people_status, people_table, people_card], ) people_build.click( build_people, inputs=[people_input, people_table], outputs=[people_status, people_table, people_card], ) people_sheet_button.click( lambda text: _study_sheet(text, "names-and-faces"), inputs=[people_card], outputs=[people_sheet], ) with gr.TabItem("Dates", id="dates"): gr.Markdown( """ ### Remember when it happened One event per line: **event | date**. Years, numeric dates, and month names work (1066, 14/03, 20 July 1969). The digits keep the order you typed, become Major System words (your saved words first), and link to the event. """ ) with gr.Row(elem_classes="ms-stack"): events_input = gr.Textbox( label="Events", placeholder="Battle of Hastings | 1066", lines=4, scale=4, ) events_example = gr.Button( "Try an example", size="sm", scale=0, min_width=150 ) events_draft = gr.Button("Draft date cards", variant="primary") events_status = gr.Markdown() events_table = gr.Dataframe( headers=names_dates.DATE_HEADERS, datatype=["str"] * len(names_dates.DATE_HEADERS), type="array", value=[], interactive=True, wrap=True, column_widths=["18%", "14%", "12%", "18%", "38%"], label="Edit the Words (one per chunk, comma-separated) and scenes", ) events_build = gr.Button( "Check and build the cards", variant="primary" ) events_card = gr.Markdown() with gr.Row(elem_classes="ms-stack"): events_library_name = gr.Textbox( label="Name in My library (optional)", placeholder="e.g. History exam, Family birthdays", max_lines=1, scale=3, ) events_library_save = gr.Button( "Save to my library", size="sm", scale=0, min_width=180, ) with gr.Row(): events_practice = gr.Button( "Practice these cards", size="sm", variant="primary", scale=0, min_width=180, ) events_sheet_button = gr.Button( "Download study sheet (.md)", size="sm", scale=0, min_width=200, ) events_sheet = gr.File( show_label=False, interactive=False, visible=False, file_count="multiple", ) events_draft.click( draft_events, inputs=[events_input, personal_words], outputs=[events_status, events_table, events_card], ) events_example.click( lambda saved: (EVENTS_EXAMPLE, *draft_events(EVENTS_EXAMPLE, saved)), inputs=[personal_words], outputs=[events_input, events_status, events_table, events_card], ) events_build.click( build_events, inputs=[events_input, events_table], outputs=[events_status, events_table, events_card], ) events_sheet_button.click( lambda text: _study_sheet(text, "dates"), inputs=[events_card], outputs=[events_sheet], ) with gr.TabItem("Mind Map", id="mindmap"): gr.Markdown( f""" ### Map a topic on one page The topic goes in the centre, main ideas become thick coloured branches, and details hang off thinner ones. Write **one key word per line**. Lines with no indent are main branches; indented lines (two spaces or a tab) are details of the line above. Up to {MAX_MAIN_BRANCHES} main branches with {MAX_SUB_BRANCHES} details each. No model is used. """ ) with gr.Row(elem_classes="ms-stack"): mind_topic = gr.Textbox( label="Central topic", placeholder="Memory", max_lines=1, scale=3, ) mind_example = gr.Button( "Try an example", size="sm", scale=0, min_width=160 ) mind_outline = gr.Textbox( label="Branches: one key word per line, details indented", placeholder="Imagination\n colour\n movement\nAssociation\n link", lines=10, ) mind_build = gr.Button("Draw my Mind Map", variant="primary") mind_status = gr.Markdown() mind_show = gr.Radio( label="Show", choices=list(MIND_VIEWS), value=MIND_VIEW_FULL, info=( "Test yourself: hide the details or every branch word, " "recall each ?, then switch back to check." ), ) mind_view = gr.HTML() with gr.Row(elem_classes="ms-stack"): mind_library_name = gr.Textbox( label="Name in My library (optional)", placeholder="Defaults to the central topic", max_lines=1, scale=3, ) mind_library_save = gr.Button( "Save to my library", size="sm", scale=0, min_width=180 ) with gr.Row(): mind_practice = gr.Button( "Practice these cards", size="sm", variant="primary", scale=0, min_width=180, ) mind_center = gr.Button( "Draw a central image", size="sm", scale=0, min_width=190, ) mind_download = gr.Button( "Download (.svg + .md)", size="sm", variant="secondary", scale=0, min_width=200, ) mind_files = gr.File( label="Mind Map files", show_label=False, interactive=False, visible=False, file_count="multiple", ) for mind_event in (mind_build.click, mind_topic.submit): mind_event( build_mind_map_view, inputs=[mind_topic, mind_outline, mind_show], outputs=[mind_status, mind_view, mind_files], ) # .input: only the learner's own switch redraws, not a reset below. mind_show.input( build_mind_map, inputs=[mind_topic, mind_outline, mind_show], outputs=[mind_status, mind_view], ) mind_example.click( example_mind_map_view, inputs=None, outputs=[ mind_topic, mind_outline, mind_show, mind_status, mind_view, mind_files, ], ) mind_download.click( mind_map_files, inputs=[mind_topic, mind_outline], outputs=[mind_files], ) with gr.TabItem("Practice", id="practice"): gr.Markdown( """ ### Test yourself, in order The best way in is **Practice these cards** in any builder (Numbers, Ordered list, Names & dates, Mind Map), or **Review this item** in My library: they use your own words and cues. You can also paste a number or list here; a pasted number uses your saved words, else the starter words. No model is involved. """ ) with gr.Row(elem_classes="ms-stack"): practice_kind = gr.Dropdown( label="What are you practicing?", choices=list(PRACTICE_KINDS), value=PRACTICE_NUMBER, scale=1, ) practice_text = gr.Textbox( label="Number or ordered list", placeholder="314159 or milk, eggs, coffee", lines=3, scale=2, ) with gr.Row(elem_classes="ms-stack"): practice_start_btn = gr.Button( "Start practice", variant="primary", scale=2 ) practice_example_btn = gr.Button( "Try 314159", size="sm", scale=0, min_width=150 ) practice_progress = gr.Markdown() practice_prompt = gr.Markdown( "**Enter a number or list above, then click Start practice.** " "Cards stay in the original order and are never scored on a server." ) practice_answer = gr.Markdown( visible=False, elem_classes="ms-answer" ) practice_reveal = gr.Button("Reveal answer", visible=False) with gr.Row(visible=False) as practice_grade_row: practice_knew_btn = gr.Button("I knew it", variant="primary") practice_missed_btn = gr.Button("Missed it") practice_summary = gr.Markdown(visible=False) practice_state = gr.State({}) practice_outputs = [ practice_state, practice_progress, practice_prompt, practice_answer, practice_reveal, practice_grade_row, practice_summary, ] practice_start_btn.click( start_practice, inputs=[practice_kind, practice_text, personal_words], outputs=practice_outputs, ) practice_text.submit( start_practice, inputs=[practice_kind, practice_text, personal_words], outputs=practice_outputs, ) practice_reveal.click( reveal_practice, inputs=[practice_state], outputs=[ practice_state, practice_answer, practice_reveal, practice_grade_row, ], ) library_view_outputs = [ library_summary, library_table, library_pick, start_due, start_open_library, ] practice_knew_btn.click( lambda state, library: grade_and_record(state, library, True), inputs=[practice_state, library_state], outputs=[*practice_outputs, library_state, *library_view_outputs], ) practice_missed_btn.click( lambda state, library: grade_and_record(state, library, False), inputs=[practice_state, library_state], outputs=[*practice_outputs, library_state, *library_view_outputs], ) practice_example_btn.click( start_practice_example, inputs=None, outputs=[practice_kind, practice_text, *practice_outputs], ) image_intro_note = ( "This Space preloads the weights at startup " f"({IMAGE_MODEL_DOWNLOAD_NOTE}) and runs them on a shared free GPU; " "a busy queue or the daily GPU quota can delay a picture." if PUBLIC_DEMO else ( f"First use downloads public weights ({IMAGE_MODEL_DOWNLOAD_NOTE}). " f"On CPU, {DEFAULT_IMAGE_SIZE} × {DEFAULT_IMAGE_SIZE} with " f"{DEFAULT_IMAGE_STEPS} steps is a practical starting point; larger " "sizes and more steps take longer. Everything stays on this computer." ) ) with gr.TabItem("Image (optional)", id="image"): gr.Markdown( f""" ### Draw a mnemonic image from a cue Paste an image cue from a story, or write a new scene. In the Numbers or Ordered list tab, build the story first, then pick a scene and click **Open in Image tab** to send its cue here. Draw one scene at a time: the image model reads only about 75 tokens (roughly 50 words), so long cues are shortened and the dropped words are listed. This tab is **optional**: the text-only and no-model routes never load the image model. **Model:** `{IMAGE_MODEL_ID}`. {image_intro_note} """ ) gr.Markdown(image_model_status_markdown(hosted=PUBLIC_DEMO)) gr.HTML( """
Cue-writing tips
""" ) with gr.Row(elem_classes="ms-stack"): image_cue = gr.Textbox( label="Image cue / scene", placeholder=( "Try: a giant wedge of cheese wearing a golden crown, " "dancing on a rooftop at sunset" ), lines=3, scale=3, ) with gr.Column(scale=2): image_style = gr.Dropdown( label="Visual style", choices=list(IMAGE_STYLES), value=IMAGE_STYLES[0], ) image_size = gr.Dropdown( label="Size", choices=list(IMAGE_SIZE_OPTIONS), value=_size_option(DEFAULT_IMAGE_SIZE), ) image_steps = gr.Slider( label="Denoising steps", minimum=MIN_IMAGE_STEPS, maximum=MAX_IMAGE_STEPS, step=1, value=DEFAULT_IMAGE_STEPS, info=( "More steps can add detail but take longer. " + ( "The shared GPU handles this quickly." if PUBLIC_DEMO else f"On CPU, {DEFAULT_IMAGE_STEPS} steps is a practical starting point." ) ), ) image_seed = gr.Number( label="Seed (-1 = random)", value=-1, precision=0, info="Keep a seed to reproduce or compare an image.", ) with gr.Row(elem_classes="ms-stack"): image_draw = gr.Button( "Draw on this Space" if PUBLIC_DEMO else "Draw locally", variant="primary", scale=2, ) image_example = gr.Button("Example: crown cheese", size="sm") image_example_two = gr.Button("Example: red doormat", size="sm") image_status = gr.Markdown() image_output = gr.Image( label="Image draft" if PUBLIC_DEMO else "Local image draft", type="pil", height=420, interactive=False, buttons=["download", "fullscreen"], elem_id="ms-image", ) image_history = gr.State([]) with gr.Accordion( "Recent drafts (this session, newest first)", open=False ): image_gallery = gr.Gallery( label="Recent drafts", columns=4, height=260, object_fit="cover", show_label=False, interactive=False, ) gr.Markdown( "Only the last eight drafts are kept in this browser " "session. Download any picture you want to keep.", elem_classes="ms-muted", ) number_illustrate.click( illustrate_scene, inputs=[number_scene], outputs=[tabs, image_cue], ) list_illustrate.click( illustrate_scene, inputs=[list_scene], outputs=[tabs, image_cue], ) image_draw.click( draw_and_keep, concurrency_limit=1, inputs=[ image_cue, image_style, image_size, image_steps, image_seed, image_history, ], outputs=[image_status, image_output, image_history, image_gallery], ).then( # Bring the finished picture into view. Inside a host frame this # scrolls the app, so a draft added below the fold is seen at once. fn=None, js="() => { const el = document.getElementById('ms-image'); if (el) el.scrollIntoView({ block: 'center', behavior: 'smooth' }); }", ) image_example.click(load_example_image_cue, outputs=[image_cue]) image_example_two.click(load_second_image_cue, outputs=[image_cue]) with gr.Accordion("Image model, license, and limits", open=False): gr.Markdown( f""" - **Model:** `{IMAGE_MODEL_ID}` - **License:** {IMAGE_MODEL_LICENSE_NOTE} - **Model card:** <{IMAGE_MODEL_CARD_URL}> - **First use:** downloads {IMAGE_MODEL_DOWNLOAD_NOTE} of public weights; later runs use the local cache. No token or account is required for this public repository. - **Device:** CUDA or Apple MPS if available, otherwise CPU. CPU generation can take tens of seconds to a few minutes. - **Resources:** expect a few GB of RAM while the model is loaded. Close other memory-heavy apps if generation fails. - **Safety:** this model does **not** bundle a safety checker when loaded here. It can produce distorted or inappropriate images and may reflect biases in its training data. Treat outputs as personal memory sketches, not factual illustrations, and follow the license use restrictions. - **Privacy:** the app does not print or save your cue. Images are displayed by the local Gradio server and are not uploaded; use the download button if you want to keep one. """ ) with gr.TabItem("Guide & privacy", id="guide"): gr.Markdown( re.sub( r"(?m)^ {16}", "", f""" ## How to use the workbench 1. **Draft** suggestions with the no-model route or the optional local text model. The **Start here** tab fills in an example with one click. 2. **Inspect and edit** the table. Replace any word, image, or cue with a personal association. 3. **Build** the story. The app re-checks number words, refuses to silently drop list items, and writes a linked story: each image does something to the previous one, with a sound or feeling. Rewrite any line in the **Story line** column and rebuild; your lines are kept. The story is the mnemonic. 4. **Anchor** (optional) each image to a Memory Palace route you know, or to a peg system: Number-Rhyme (1 bun, 2 shoe...), Number-Shape (1 candle, 2 swan...), or Major System pegs. 5. **Practice** with **Practice these cards**. Each card asks for the next image in the chain, then the digits it encodes. Say the answer out loud, reveal it, and mark whether you knew it. 6. **Review** on the schedule shown under each story: about 10 minutes after learning, then 1 day, 1 week, 1 month, and 3-6 months later. The download includes a calendar file with the dates. 7. **Optionally draw a scene.** Pick one scene under a built story and click **Open in Image tab**. **Whole chain in one picture** is offered for every story (long chains use a compact list of the key pictures, plus parts of four). The Word card has **Draw this card**. Pictures are hints, not a replacement for the story. **Numbers:** after a story builds, **Save these words** keeps your words in this browser, so your personal 00-99 list grows as you use it. **Find other words for a chunk** lists common dictionary words for any 1-4 digits. The **00–99 trainer** drills those words both ways, times each answer, and remembers which numbers you miss most. **Names & dates:** for names, pick one face feature and link a sound-alike of the name to it; practice runs face to name. For dates, the digits become your Major words, linked to the event. **Mind Map:** put a topic in the centre and one key word per line on branches. Indented lines become details. To review, set **Show** to hide the details or every branch, recall each **?**, then switch back; or use **Practice these cards** and save the map to **My library**. The deterministic route is the reliable baseline: curated Major words, a linked story, palace or peg anchors, Mind Maps, and recall prompts. The models only add optional drafts. ## Keep your work Each builder has **Download study sheet (.md)**. It writes the story, anchors, recall prompt, and review schedule (or the assembled word card) to a Markdown file, plus a calendar file (.ics) with the review dates. The Mind Map downloads as .svg and .md. Drafts are not saved automatically: if you close the page without downloading, they are gone. The only things kept are the word list, the **My library** items and palace routes you choose to save, and the trainer's per-number results, in this browser's local storage. The library shows which reviews are due, so you can skip the calendar file if you prefer. Pictures use the image download button, and only the last eight stay in the in-session gallery. ## Common questions **Do I need to download a model?** No. Curated Major-System words, ordered stories, Memory Palace routes, study sheets, and practice all work with no model at all. Models are opt-in extras. **Is anything saved or sent anywhere?** {"This online version processes what you type on this Space's servers. The app does not save it, but a hosted page cannot promise on-device privacy: do not paste secrets or private notes. Run the app locally for that." if PUBLIC_DEMO else f"{BIND_NOTE} The app does not intentionally log or save your study material. Inference stays on this computer after any model download."} Study-sheet files are temporary display files; download the ones you want to keep. **Why did a word fail the Major System check?** The Major System maps consonant **sounds**. The check looks the word up in the CMU Pronouncing Dictionary (American English) and shows what it reads, for example "dictionary reads 626" for *change*. Words it does not know fall back to an approximate spelling check. If your accent differs, say the word aloud and choose one that fits your pronunciation. **Why does a picture miss part of my cue?** Small image models are impressionistic. Shorten the cue, change the seed, add steps, or edit the scene. The picture is a visual draft, never evidence. **Can I use my own associations?** Yes, that is the point. Every word, cue, palace stop, and card field is editable. Personal images usually work better than generic ones. ## Major System reference {MAJOR_HELP} ## Optional text model - **Model ID:** `{MODEL_ID}` - **License:** {MODEL_LICENSE_NOTE} - **First use:** downloads public model weights from Hugging Face; later runs use the {"Space's" if PUBLIC_DEMO else "local"} cache. No token or account is required for these public repositories. - **Default size:** SmolLM2-360M-Instruct. The download is roughly 0.7 GB; expect higher runtime memory. CPU works but is slower. - **Larger option:** set `MEMORY_MODEL` to `HuggingFaceTB/SmolLM2-1.7B-Instruct` for a larger draft model. The download is roughly 3.4 GB; a CUDA or Apple-silicon GPU is helpful and more RAM is needed. - **Device:** selected when weights load (CUDA or MPS if available, otherwise CPU). {"Drafts run on this Space's servers, not on your device." if PUBLIC_DEMO else "All inference stays on this computer."} - **Dependencies:** {"available in this environment" if dependencies_available() else "not installed; the no-model route is active"}. The model files are public, but check the current Hugging Face model card for the exact license and usage terms before redistributing weights or building a product around them. ## Optional image model - **Model ID:** `{IMAGE_MODEL_ID}` - **License:** {IMAGE_MODEL_LICENSE_NOTE} - **Model card:** <{IMAGE_MODEL_CARD_URL}> - **First use:** downloads {IMAGE_MODEL_DOWNLOAD_NOTE} of public weights; later runs use the {"Space's" if PUBLIC_DEMO else "local"} cache. No token or account is required. - **Speed:** {"The online version runs the model on a shared free GPU; busy periods may queue and a daily quota applies." if PUBLIC_DEMO else f"{DEFAULT_IMAGE_SIZE} × {DEFAULT_IMAGE_SIZE} with {DEFAULT_IMAGE_STEPS} steps is a practical CPU starting point; larger sizes and more steps take longer. A CUDA or Apple-silicon GPU is much faster."} - **Limits:** small image models are impressionistic, may omit or distort parts of the cue, and have no bundled safety checker. Treat every picture as an editable visual draft, not a factual illustration. - **Dependencies:** {"available in this environment" if image_dependencies_available() else "not installed; the text-only route remains active"}. ## Privacy {PRIVACY_SECTION} ## Accuracy and limits - The Major System maps **sounds**, not letters. The checker uses the CMU Pronouncing Dictionary (American English), and an approximate spelling check only for words it does not contain. Read every word aloud in your own accent. - A failing candidate is never silently accepted. The number build stops until every chunk has a matching word. - Image cues and stories are memory aids, not definitions. This app does not verify technical meanings. - AI images are optional visual drafts. They can change or omit details and may reflect model biases; they are not evidence or factual illustrations. - The story has one line per row, in order, with each key word in bold, so nothing is dropped. A model-written line is used only if it names its own image; only the bold words carry digits. - The review schedule lists dates and a calendar file; the app does not track your reviews or send reminders. - Data: CMUdict (BSD-style license) and a common-word frequency list derived from the public-domain 12dicts lists are bundled in `data/` with their notices. ## Curated starting words These are suggestions to edit, not an official vocabulary. Each passes the dictionary check; pronounce each word and replace anything that does not fit your accent or personal imagery. """, ) ) with gr.Accordion("Browse the curated 00-99 words", open=False): gr.Dataframe( headers=["Chunk", "Word", "Image cue"], datatype=["str", "str", "str"], type="array", value=curated_major_rows(), interactive=False, wrap=True, ) start_numbers.click( start_with_numbers, inputs=[personal_words, number_chunking], outputs=[tabs, number_input, number_use_model, *number_draft_outputs], ) start_list.click( start_with_list, inputs=None, outputs=[tabs, list_input, list_use_model, *list_draft_outputs], ) start_word.click( start_with_word, inputs=None, outputs=[ tabs, word_term, word_context, word_use_model, word_status, word_table, word_card, ], ) word_picture.click( word_card_scene, inputs=[word_term, word_context, word_table], outputs=[tabs, image_cue], ) mind_center.click( mind_map_center_cue, inputs=[mind_topic], outputs=[tabs, image_cue] ) start_mind_map.click( lambda: (gr.Tabs(selected="mindmap"), *example_mind_map_view()), inputs=None, outputs=[ tabs, mind_topic, mind_outline, mind_show, mind_status, mind_view, mind_files, ], ) mind_practice.click( practice_mind_map, inputs=[mind_topic, mind_outline], outputs=[tabs, mind_status, practice_kind, practice_text, *practice_outputs], ) mind_library_save.click( save_mind_map_to_library, inputs=[mind_topic, mind_outline, mind_library_name, library_state], outputs=[library_state, mind_status, *library_view_outputs], ) number_save_words.click( save_number_words, inputs=[number_input, number_table, personal_words, number_chunking], outputs=[personal_words, number_status, number_saved_table], ) number_forget.click( forget_saved_words, inputs=None, outputs=[personal_words, number_status, number_saved_table], ) demo.load( load_browser_views, inputs=[personal_words, library_state, palace_state, trainer_stats], outputs=[ number_saved_table, *library_view_outputs, number_route_pick, list_route_pick, trainer_hardest_table, ], ) for ( route_pick, route_delete, route_stops, route_name_box, route_save, route_note, route_anchor, ) in ( ( number_route_pick, number_route_delete, number_palace, number_route_name, number_route_save, number_route_note, number_anchor, ), ( list_route_pick, list_route_delete, list_palace, list_route_name, list_route_save, list_route_note, list_anchor, ), ): # .input fires only when the learner picks, not when the list refreshes. route_pick.input( use_saved_route, inputs=[route_pick, palace_state], outputs=[route_anchor, route_stops, route_name_box, route_note], ) route_save.click( save_route_handler, inputs=[route_name_box, route_stops, palace_state], outputs=[palace_state, number_route_pick, list_route_pick, route_note], ) route_name_box.submit( save_route_handler, inputs=[route_name_box, route_stops, palace_state], outputs=[palace_state, number_route_pick, list_route_pick, route_note], ) route_delete.click( delete_route_handler, inputs=[route_pick, palace_state], outputs=[palace_state, number_route_pick, list_route_pick, route_note], ) trainer_start_inputs = [ trainer_range, trainer_direction, trainer_count, trainer_hardest_first, personal_words, trainer_stats, ] trainer_start.click( start_trainer, inputs=trainer_start_inputs, outputs=trainer_session_outputs ) trainer_range.submit( start_trainer, inputs=trainer_start_inputs, outputs=trainer_session_outputs ) trainer_check_outputs = [ trainer_state, trainer_stats, trainer_progress, trainer_prompt, trainer_feedback, trainer_answer, trainer_answer_row, trainer_summary, trainer_retry, trainer_hardest_table, ] for trainer_event in (trainer_check.click, trainer_answer.submit): trainer_event( check_trainer_answer, inputs=[trainer_state, trainer_answer, trainer_stats, personal_words], outputs=trainer_check_outputs, ) trainer_skip.click( lambda state, stats, saved: check_trainer_answer(state, "", stats, saved), inputs=[trainer_state, trainer_stats, personal_words], outputs=trainer_check_outputs, ) trainer_retry.click( retry_trainer_misses, inputs=[trainer_state], outputs=trainer_session_outputs, ) trainer_reset.click( reset_trainer_stats, inputs=None, outputs=[trainer_stats, trainer_hardest_table, trainer_reset_status], ) start_trainer_card.click( start_with_trainer, inputs=[personal_words, trainer_stats], outputs=[ tabs, trainer_range, trainer_direction, trainer_count, trainer_hardest_first, *trainer_session_outputs, ], ) start_names_card.click( lambda: ( gr.Tabs(selected="namesdates"), PEOPLE_EXAMPLE, *draft_people(PEOPLE_EXAMPLE), ), inputs=None, outputs=[tabs, people_input, people_status, people_table, people_card], ) number_library_save.click( save_number_to_library, inputs=[ number_input, number_table, number_library_name, library_state, number_chunking, ], outputs=[library_state, number_status, *library_view_outputs], ) list_library_save.click( save_list_to_library, inputs=[list_input, list_table, list_library_name, library_state], outputs=[library_state, list_status, *library_view_outputs], ) word_library_save.click( lambda term, context, table, library: save_word_to_library( term, context, table, "", library ), inputs=[word_term, word_context, word_table, library_state], outputs=[library_state, word_status, *library_view_outputs], ) library_review.click( review_library_item, inputs=[library_pick, library_state], outputs=[tabs, library_status, *practice_outputs], ) library_remove.click( remove_library_item, inputs=[library_pick, library_state], outputs=[library_state, library_status, *library_view_outputs], ) start_open_library.click( lambda: gr.Tabs(selected="library"), inputs=None, outputs=[tabs] ) number_practice.click( practice_number_table, inputs=[number_input, number_table, number_chunking], outputs=[tabs, number_status, practice_kind, practice_text, *practice_outputs], ) list_practice.click( practice_list_table, inputs=[list_input, list_table], outputs=[tabs, list_status, practice_kind, practice_text, *practice_outputs], ) people_practice.click( practice_people, inputs=[people_input, people_table], outputs=[tabs, people_status, practice_kind, practice_text, *practice_outputs], ) events_practice.click( practice_events, inputs=[events_input, events_table], outputs=[tabs, events_status, practice_kind, practice_text, *practice_outputs], ) people_library_save.click( save_people_to_library, inputs=[people_input, people_table, people_library_name, library_state], outputs=[library_state, people_status, *library_view_outputs], ) events_library_save.click( save_events_to_library, inputs=[events_input, events_table, events_library_name, library_state], outputs=[library_state, events_status, *library_view_outputs], ) start_practice_card.click( start_with_practice, inputs=None, outputs=[ tabs, practice_kind, practice_text, *practice_outputs, ], ) gr.Markdown( f""" --- **No paid API · editable output.** **Text model:** `{MODEL_ID}` (optional; no-model mode always available). **Image model:** `{IMAGE_MODEL_ID}` (optional; text-only route always available). {"**Privacy:** online version; submissions are processed on this Space's servers, not on your device." if PUBLIC_DEMO else ("**Privacy:** localhost only; " if LOCAL_ONLY else f"**Privacy:** listening on `{LISTEN_HOST}` (your network); ") + "no sharing link; submitted text and image cues are not intentionally logged or saved."} """ ) # A hosted Space pays the model download during startup, so the first visitor's # Draw is fast and fits inside one ZeroGPU window. Local runs stay lazy. if PUBLIC_DEMO: # Text generation needs a GPU window on ZeroGPU, like image drawing. use_zero_gpu() # Out of GPU quota? The backup text model answers on CPU; say so. local_llm.on_fallback = lambda: gr.Warning( "The free GPU allowance is used up, so the smaller backup model " "(SmolLM2-360M, on CPU) wrote this draft. Its lines may be weaker." ) warm_up_text_model() warm_up_image_model() if __name__ == "__main__": # Local runs stay private to this computer. A hosted Space must bind 0.0.0.0. host = LISTEN_HOST port_text = ( os.getenv("MEMORY_STUDIO_PORT") or os.getenv("PORT") or "" ).strip() server_port = int(port_text) if port_text.isdigit() else None demo.queue(default_concurrency_limit=QUEUE_CONCURRENCY).launch( server_name=host, server_port=server_port, share=False, show_error=False, theme=APP_THEME, css=APP_CSS, head=APP_HEAD, )