diff --git "a/memory_studio.py" "b/memory_studio.py" --- "a/memory_studio.py" +++ "b/memory_studio.py" @@ -1,2795 +1,3329 @@ -"""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 ordered storyboard. 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 os -import re -import tempfile -from collections import Counter -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, -) -from local_llm import ( - MODEL_ID, - MODEL_LICENSE_NOTE, - LocalModelError, - ask_list_cues, - ask_list_story, - ask_number_candidates, - ask_number_story, - ask_scene_story, - ask_word_fields, - dependencies_available, - model_status_markdown, - parse_indexed_cues, - parse_number_rows, - parse_word_sections, - text_mentions_in_order, -) -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, - build_palace_markdown, - build_recall_markdown, - check_word_for_chunk, - curated_candidate, - curated_major_rows, - number_blockers, - parse_item_list, - parse_palace_stops, - split_number, - table_to_rows, - validate_list_rows, - validate_number_rows, - word_default_drafts, -) - -NUMBER_HEADERS = ["Chunk", "Word", "Image cue", "Check (approx.)", "Source"] -LIST_HEADERS = ["#", "Item", "Image cue"] -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()) -) - -PRIVACY_SECTION = ( - """- This is a **hosted public demo**. 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 """- The Gradio server binds to `127.0.0.1`; `share=False`; no public - link is created. -- 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, while this automatic check uses spelling " - "patterns. Say each word aloud and review unusual words yourself. Only the " - "bold image words in the checked order and storyboard are intended to carry " - "digits; a model story may contain extra decorative words, so treat it as a " - "draft. Add or replace any association 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; } -#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); -} -#ms-hero .ms-kicker { - text-transform: uppercase; - letter-spacing: .16em; - font-size: .72rem; - font-weight: 700; - 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-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-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-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; } -} -""" - -# --------------------------------------------------------------------------- -# 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() -> tuple[str, bool, str, list[list[str]], str]: - status, rows, story = draft_number_candidates(NUMBER_EXAMPLE, False) - 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, - ) - - -def _study_sheet(markdown_text: str, stem: 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 first, then create the study sheet.") - safe = re.sub(r"[^a-z0-9]+", "-", (stem or "study-sheet").casefold()) - safe = safe.strip("-")[:40] or "study-sheet" - folder = Path(tempfile.mkdtemp(prefix="memory-studio-sheet-")) - path = folder / f"{safe}.md" - path.write_text(text + "\n", encoding="utf-8") - return gr.update(value=str(path), 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 _practice_items(kind: str, text: str) -> list[dict[str, str]]: - if kind == PRACTICE_NUMBER: - items: list[dict[str, str]] = [] - for chunk in split_number(text): - curated = curated_candidate(chunk) - if curated: - word, cue = curated - answer = f"**{word}** — {cue}" - else: - answer = "_No curated word for this chunk yet._" - items.append( - { - "prompt": f"What word and image does `{chunk}` map to?", - "answer": answer, - } - ) - return items - - entries = parse_item_list(text) - total = len(entries) - return [ - {"prompt": f"What is item {index} of {total}?", "answer": f"**{item}**"} - for index, item in enumerate(entries, 1) - ] - - -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) -> tuple[Any, ...]: - try: - if kind not in PRACTICE_KINDS: - raise ValueError("Choose numbers or an ordered list.") - items = _practice_items(kind, str(text or "").strip()) - except ValueError as exc: - return ( - {}, - "", - f"**Input issue:** {exc}", - _hidden_answer(), - gr.update(visible=False), - gr.update(visible=False), - gr.update(value="", visible=False), - ) - - state: dict[str, Any] = { - "items": items, - "index": 0, - "known": 0, - "missed": [], - "revealed": False, - } - return ( - state, - _practice_progress(state), - _practice_prompt(items[0]), - _hidden_answer(), - gr.update(visible=True), - gr.update(visible=False), - gr.update(value="", visible=False), - ) - - -def reveal_practice(state: dict[str, Any]) -> tuple[Any, ...]: - items = (state or {}).get("items") or [] - if not items: - return ( - state, - gr.update(), - gr.update(visible=False), - gr.update(visible=False), - ) - index = state.get("index", 0) - updated = {**state, "revealed": True} - return ( - updated, - gr.update(value=items[index]["answer"], visible=True), - gr.update(visible=False), - gr.update(visible=True), - ) - - -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, - } - lines = [ - "### Session complete", - "", - f"You recalled **{known}/{total}** card(s) on this pass.", - ] - 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 ( - 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="\n".join(lines), 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]: - items = list(history or []) - if image is None: - return items, gr.update() - items.append(image) - items = items[-8:] - return items, items - - -def _practice_knew(state: dict[str, Any]) -> tuple[Any, ...]: - return grade_practice(state, True) - - -def _practice_missed(state: dict[str, Any]) -> tuple[Any, ...]: - return grade_practice(state, False) - - -# --------------------------------------------------------------------------- -# Start-here shortcuts (switch tab and fill in an editable example) -# --------------------------------------------------------------------------- - - -def start_with_numbers() -> tuple[Any, ...]: - number, use_model, status, rows, story = _example_number() - return ( - gr.update(selected="numbers"), - number, - use_model, - status, - rows, - story, - ) - - -def start_with_list() -> tuple[Any, ...]: - text, use_model, status, rows, story = _example_list() - return ( - gr.update(selected="list"), - text, - use_model, - status, - rows, - story, - ) - - -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 _scene_prompt(subject: str, cue: str) -> str: - """Turn a checked row into one image prompt without inventing detail.""" - subject_text = " ".join(str(subject or "").split()) - cue_text = " ".join(str(cue or "").split()) - if not cue_text: - return subject_text - if not subject_text or subject_text.casefold() in cue_text.casefold(): - return cue_text - return f"{subject_text}: {cue_text}" - - -def _scene_choice_label( - index: int, code: str, subject: str, cue: str -) -> str: - detail = cue or subject - if len(detail) > 64: - detail = detail[:61].rstrip() + "…" - subject_text = subject - if len(subject_text) > 32: - subject_text = subject_text[:29].rstrip() + "…" - parts = [str(index)] - if code: - parts.append(str(code)) - if subject_text: - parts.append(subject_text) - head = " · ".join(parts) - return f"{head} — {detail}" if detail else head - - -def _scene_choices( - rows: list[list[str]], kind: str -) -> list[tuple[str, str]]: - """Build dropdown (label, prompt) pairs from checked storyboard rows.""" - choices: list[tuple[str, str]] = [] - for index, row in enumerate(rows, 1): - if kind == "number": - if len(row) < 3: - continue - code, subject, cue = row[0], row[1], row[2] - else: - if len(row) < 3: - continue - code, subject, cue = "", row[1], row[2] - prompt = _scene_prompt(subject, cue) - if not prompt: - continue - choices.append( - (_scene_choice_label(index, code, subject, cue), prompt) - ) - return choices - - -def number_scene_choices(table: Any, story: str) -> tuple[Any, Any]: - """Show one optional illustration picker after a number story is built.""" - choices = ( - _scene_choices(_current_rows(table), "number") - if (story or "").strip() - else [] - ) - return ( - gr.Group(visible=bool(choices)), - gr.Dropdown(choices=choices, value=None), - ) - - -def list_scene_choices(table: Any, story: str) -> tuple[Any, Any]: - """Show one optional illustration picker after a list story is built.""" - choices = ( - _scene_choices(_current_rows(table), "list") - if (story or "").strip() - else [] - ) - return ( - gr.Group(visible=bool(choices)), - gr.Dropdown(choices=choices, value=None), - ) - - -def illustrate_scene(scene: Any) -> tuple[Any, str]: - """Open the Image tab with one or more checked scene cues prefilled.""" - cues: list[str] = [] - if isinstance(scene, list): - cues = [str(s or "").strip() for s in scene if str(s or "").strip()] - elif str(scene or "").strip(): - cues = [str(scene).strip()] - return gr.Tabs(selected="image"), "\n\n".join(cues) - - -def select_all_scenes(table: Any, story: str, kind: str) -> Any: - """Check every scene in the multiselect picker (all checked rows).""" - if not (story or "").strip(): - return gr.update(value=[]) - choices = _scene_choices(_current_rows(table), kind) - return gr.update(value=[choice[1] for choice in choices]) - - -def _combine_scenes_template(cues: list[str]) -> str: - """Deterministic single-scene prompt that keeps every cue, in order.""" - chain = "; then ".join(cues) - return ( - "A single continuous illustrated memory chain, read left to right: " - f"{chain}. Exaggerated scale, bold colors, one scene, vivid and " - "bizarre, no text or words in the picture." - ) - - -def _selected_scene_rows( - selection: Any, table: Any, kind: str -) -> list[tuple[str, str]]: - """Map the multiselect value back to (subject, cue) rows, in table order. - - An empty selection means "all checked rows", which mirrors the picker's - select-all behavior. - """ - rows = _current_rows(table) - selected_values = selection if isinstance(selection, list) else [selection] - wanted = [str(v or "").strip() for v in selected_values if str(v or "").strip()] - picked: list[tuple[str, str]] = [] - for row in rows: - if len(row) < 3: - continue - if kind == "number": - code, subject, cue = row[0], row[1], row[2] - else: - code, subject, cue = "", row[1], row[2] - subject_text = " ".join(str(subject or "").split()) - cue_text = " ".join(str(cue or "").split()) - prompt = _scene_prompt(subject_text, cue_text) - if not prompt: - continue - if wanted and prompt not in wanted: - continue - picked.append((subject_text, prompt)) - return picked - - -def combine_scenes( - selection: Any, table: Any, story: str, use_model: bool, kind: str -) -> tuple[Any, str, str]: - """Weave the selected scenes into one story prompt for the Image tab. - - Uses the optional local text model when requested and validates that every - selected element survives, in order; otherwise falls back to the - deterministic template. Never invents or drops a scene silently. - """ - if not (story or "").strip(): - return ( - gr.Tabs(selected=("numbers" if kind == "number" else "list")), - "", - "### Nothing to combine yet\n\nBuild the story first, then combine the scenes.", - ) - picked = _selected_scene_rows(selection, table, kind) - if not picked: - return ( - gr.Tabs(selected=("numbers" if kind == "number" else "list")), - "", - "### No scenes selected\n\nPick at least one scene (or **Select all scenes**) and try again.", - ) - cues = [cue for _, cue in picked] - subjects = [subject for subject, _ in picked] - template = _combine_scenes_template(cues) - story_text = template - note = ( - f"Combined {len(picked)} scene(s) with the deterministic template — every " - "cue is included, in order. Tick the local text-model box above to draft this with the model." - ) - if use_model: - try: - model_story = ask_scene_story(picked, kind=kind).strip() - in_order, problem_label = text_mentions_in_order(subjects, model_story) - if len(model_story) >= 40 and in_order: - story_text = model_story - note = ( - f"Combined {len(picked)} scene(s) with the local text model. " - "Every chain element was found in order, but the model may " - "still paraphrase; the checked table remains the strict reference." - ) - elif len(model_story) < 40: - note = ( - "The local model's combined story was too short to be useful, " - "so the deterministic template was used instead." - ) - else: - note = ( - "The local model's combined story was not used because it did not " - f"keep every chain element in order (problem: **{problem_label}**). " - "The deterministic template was used instead." - ) - except LocalModelError as exc: - note = ( - "The local model was not used: " - f"{exc.public_message} The deterministic template was used instead." - ) - except Exception: - note = ( - "The local model was not used because an unexpected error occurred. " - "The deterministic template was used instead." - ) - return ( - gr.Tabs(selected="image"), - story_text, - f"### Combined story prompt ready\n\n{note}", - ) - - -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))] - - -def draft_number_candidates(number_text: str, use_model: bool) -> tuple[str, list[list[str]], str]: - """Draft an editable candidate table from curated words and/or the model.""" - try: - chunks = split_number(number_text) - except ValueError as exc: - return f"**Input issue:** {exc}", [], "" - - accepted: dict[str, tuple[str, str]] = {} - rejected: list[tuple[str, str, str]] = [] - missing: list[str] = [] - model_note = "" - - if use_model: - try: - raw = ask_number_candidates(chunks) - candidates = parse_number_rows(raw, 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 chunks if chunk not in candidates] - if candidates: - model_note = ( - f"The local model returned candidates for " - f"{len(candidates)}/{len(chunks)} chunk(s). " - f"{len(accepted)} passed the approximate checker." - ) - 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: every chunk uses a curated starting word. Replace any " - "word or cue with a personal association." - ) - - rows: list[list[str]] = [] - for chunk in chunks: - if chunk in accepted: - word, image = accepted[chunk] - rows.append([chunk, word, image, "match (approx.)", "local model + check"]) - continue - curated = curated_candidate(chunk) - if curated: - word, image = curated - source = "curated starter" - if chunk in missing: - source += " (model missed chunk)" - rows.append([chunk, word, image, "match (approx.)", source]) - else: # pragma: no cover - the curated set covers 0-9 and 00-99 - rows.append([chunk, "", "", "needs a word", "your entry"]) - - status_parts = [ - "### Draft ready", - "", - f"{len(chunks)} chunk(s). Review the **Word** and **Image cue** columns, " - "edit any cell, then click **Check my edits and build the story**. " - "The checker is spelling-based and approximate.", - "", - model_note, - ] - - if rejected: - status_parts.extend( - [ - "", - "#### Model candidates not auto-accepted", - "", - "The curated 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) - + ". Curated 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 _checked_order_table(rows: list[NumberRow]) -> str: - lines = [ - "### Checked order", - "", - "| # | Chunk | Word | Image cue |", - "|---:|---:|---|---|", - ] - for index, row in enumerate(rows, 1): - cue = _md_cell(row.image) or "_(add a cue)_" - lines.append( - f"| {index} | `{row.chunk}` | **{_md_cell(row.word)}** | {cue} |" - ) - return "\n".join(lines) - - -def build_number_story( - number_text: str, - table: Any, - use_model: bool, - palace_text: str, -) -> tuple[str, list[list[str]], str]: - """Re-check edited rows, preserve order, and build complete story outputs.""" - current_rows = _current_rows(table) - try: - chunks = split_number(number_text) - 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) - for row in reviewed - ] - status_parts = [ - "### Check complete", - "", - f"All {len(reviewed)} chunk(s) pass the approximate spelling check. " - "The checked order is preserved below.", - ] - story_parts = [ - "## Number \u2192 Major System", - "", - f"**Input:** `{number_text.strip()}`", - "", - _checked_order_table(reviewed), - ] - - if use_model: - try: - model_story = ask_number_story( - [(row.chunk, row.word, row.image) for row in reviewed] - ) - in_order, problem_label = text_mentions_in_order( - [row.word for row in reviewed], model_story - ) - if len(model_story) < 40: - status_parts.extend( - [ - "", - "The local model's story was too short to be useful; the " - "complete no-model storyboard is shown instead.", - ] - ) - elif not in_order: - status_parts.extend( - [ - "", - "The local model's story was not used because it did not " - f"keep every word in order (problem: **{problem_label}**). " - "The complete no-model storyboard is shown instead.", - ] - ) - else: - story_parts.extend( - [ - "", - "### Model-assisted story (draft)", - "", - model_story, - "", - "_All listed words were found in order, but the model may " - "still add decorative words. Use the checked order and " - "storyboard as the strict reference._", - ] - ) - status_parts.extend( - ["", "The local model's story passed the omission/order check."] - ) - except LocalModelError as exc: - status_parts.extend( - [ - "", - "The local model story was not generated: " - f"{exc.public_message} The no-model storyboard below is complete.", - ] - ) - except Exception: - status_parts.extend( - [ - "", - "The local model story was not generated because an unexpected " - "error occurred. The no-model storyboard below is complete.", - ] - ) - - story_parts.extend( - [ - "", - build_ordered_chain(chain_items, title="Deterministic storyboard"), - ] - ) - - palace = build_palace_markdown(chain_items, stops) - if palace: - story_parts.extend(["", palace]) - - story_parts.extend( - [ - "", - build_recall_markdown("number", len(reviewed)), - "", - "### Accuracy note", - "", - NUMBER_ACCURACY, - ] - ) - return "\n".join(status_parts), reviewed_rows, "\n".join(story_parts) - - -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) - ] - status_parts = [ - "### Draft ready", - "", - f"{len(items)} item(s). The table order is the story order. Edit the " - "**Image cue** column 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 _list_order_table(rows: list[Any]) -> str: - lines = [ - "### Checked order", - "", - "| # | Item | Image cue |", - "|---:|---|---|", - ] - for index, row in enumerate(rows, 1): - item = _md_cell(row.item) - cue = _md_cell(row.cue) or "_(add a cue)_" - lines.append(f"| {index} | **{item}** | {cue} |") - return "\n".join(lines) - - -def build_list_story( - list_text: str, - table: Any, - use_model: bool, - palace_text: str, -) -> tuple[str, list[list[str]], str]: - """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) for row in reviewed] - status_parts = [ - "### Check complete", - "", - f"All {len(reviewed)} item(s) are present in the table order.", - ] - if extra_note: - status_parts.extend(["", extra_note]) - story_parts = [ - "## Ordered list \u2192 story", - "", - _list_order_table(reviewed), - ] - - if use_model: - try: - model_story = ask_list_story( - [(row.item, row.cue) for row in reviewed] - ) - in_order, problem_label = text_mentions_in_order( - [row.item for row in reviewed], model_story - ) - if len(model_story) < 40: - status_parts.extend( - [ - "", - "The local model's story was too short to be useful; the " - "complete no-model storyboard is shown instead.", - ] - ) - elif not in_order: - status_parts.extend( - [ - "", - "The local model's story was not used because it did not " - "keep every item in order (problem: " - f"**{problem_label}**). The complete no-model storyboard is " - "shown instead.", - ] - ) - else: - story_parts.extend( - [ - "", - "### Model-assisted story (draft)", - "", - model_story, - "", - "_All listed items were found in order, but the model may " - "still add connecting words. Use the checked order and " - "storyboard as the strict reference._", - ] - ) - status_parts.extend( - ["", "The local model's story passed the omission/order check."] - ) - except LocalModelError as exc: - status_parts.extend( - [ - "", - "The local model story was not generated: " - f"{exc.public_message} The no-model storyboard below is complete.", - ] - ) - except Exception: - status_parts.extend( - [ - "", - "The local model story was not generated because an unexpected " - "error occurred. The no-model storyboard below is complete.", - ] - ) - - story_parts.extend( - ["", build_ordered_chain(chain_items, title="Deterministic storyboard")] - ) - palace = build_palace_markdown(chain_items, stops) - if palace: - story_parts.extend(["", palace]) - story_parts.extend( - [ - "", - build_recall_markdown("list", len(reviewed)), - "", - "### Accuracy note", - "", - LIST_ACCURACY, - ] - ) - return "\n".join(status_parts), [row.as_list() for row in reviewed], "\n".join(story_parts) - - -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.", - ] - ) - return "\n".join(status_parts), current_rows, card - - -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.", - ] - ) - return status, image - - -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 - return spaces.GPU(duration=60)(handler) - - -image_draw_handler = _gpu_wrapped(draw_local_image) - - -with gr.Blocks(title="Memory Studio - editable mnemonic workbench") as demo: - gr.HTML( - f""" -
-
Memory Studio · {"public demo" if PUBLIC_DEMO else "local-first mnemonic workbench"}
-

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( - "### Public demo\n\n" - "**Anything you type here is sent to this Hugging Face Space and " - "processed on its servers, not on your device.** The app does not " - "save it, but a hosted demo cannot offer the on-device privacy of " - "running it yourself. Do not paste secrets or private notes. Run " - "the app locally for private use.", - elem_classes="ms-note", - ) - - with gr.Tabs(selected="start", overflow_behavior="wrap") as tabs: - with gr.TabItem("Start here", id="start"): - 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 two-digit chunks and give each one 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" - ) - - 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 complete storyboard, a recall - prompt, and a Markdown study sheet you can keep.
-
- """ - ) - 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", - ) - 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("Numbers", id="numbers"): - gr.Markdown( - """ - ### 1 · Enter a number - Leading zeros are kept. Up to 40 digits are split into two-digit - chunks; an odd final digit stays a single chunk. The table order is - locked to the digit order. - """ - ) - with gr.Row(elem_classes="ms-stack"): - number_input = gr.Textbox( - label="Number", - placeholder="Try 314159 or 0042", - lines=1, - scale=4, - ) - number_example = gr.Button( - "Try 314159", size="sm", scale=0, min_width=140 - ) - 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, - label="Review and edit every Word and Image cue", - ) - with gr.Accordion("Optional Memory Palace route", open=False): - number_palace = gr.Textbox( - label="One familiar place per line, in order", - placeholder=( - "front door\nhallway\nkitchen\n..." - ), - lines=3, - info=( - "Add one familiar stop per image to place the chain along " - "a route. You can also paste a comma-separated route." - ), - ) - 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 images.** The story is the mnemonic; use pictures " - "only as hints for scenes. **Combine into one story** weaves " - "your checked rows into a single ordered picture story for the " - "Image tab (tick the model box above to draft it with the local " - "text model; the deterministic template is used otherwise).", - elem_classes="ms-muted", - ) - with gr.Row(elem_classes="ms-stack"): - number_scene = gr.Dropdown( - label="Illustrate scenes", - choices=[], - value=None, - scale=3, - multiselect=True, - info=( - "Pick one or more checked rows to open their cues in " - "the Image tab." - ), - ) - number_select_all = gr.Button( - "Select all scenes", - size="sm", - variant="secondary", - scale=0, - min_width=150, - ) - number_illustrate = gr.Button( - "Illustrate this scene", - size="sm", - scale=0, - min_width=180, - ) - number_combine = gr.Button( - "Combine into one story", - size="sm", - variant="secondary", - scale=0, - min_width=190, - ) - number_story = gr.Markdown() - - with gr.Row(): - 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, - ], - value="Clear", - size="sm", - scale=0, - min_width=110, - ) - number_sheet = gr.File( - label="Study sheet", - show_label=False, - interactive=False, - visible=False, - ) - - number_generate.click( - draft_number_candidates, - inputs=[number_input, number_use_model], - outputs=[number_status, number_table, number_story], - ).then( - number_scene_choices, - inputs=[number_table, number_story], - outputs=[number_illustrate_box, number_scene], - ) - number_input.submit( - draft_number_candidates, - inputs=[number_input, number_use_model], - outputs=[number_status, number_table, number_story], - ).then( - number_scene_choices, - inputs=[number_table, number_story], - outputs=[number_illustrate_box, number_scene], - ) - number_example.click( - _example_number, - inputs=None, - outputs=[ - number_input, - number_use_model, - number_status, - number_table, - number_story, - ], - ).then( - number_scene_choices, - inputs=[number_table, number_story], - outputs=[number_illustrate_box, number_scene], - ) - number_build.click( - build_number_story, - inputs=[ - number_input, - number_table, - number_use_model, - number_palace, - ], - outputs=[number_status, number_table, number_story], - ).then( - number_scene_choices, - inputs=[number_table, number_story], - outputs=[number_illustrate_box, number_scene], - ) - number_clear.click( - lambda: ( - gr.Group(visible=False), - gr.Dropdown(choices=[], value=None), - ), - inputs=None, - outputs=[number_illustrate_box, number_scene], - ) - number_sheet_button.click( - _number_sheet, inputs=[number_story], outputs=[number_sheet] - ) - - 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_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, - ) - - 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] - ) - - 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=["10%", "28%", "62%"], - label="Review and edit the image cues", - ) - with gr.Accordion("Optional Memory Palace route", open=False): - list_palace = gr.Textbox( - label="One familiar place per line, in order", - placeholder=( - "front door\nhallway\nkitchen\n..." - ), - lines=3, - info="One stop per item keeps the order complete.", - ) - 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 images.** The story is the mnemonic; use pictures " - "only as hints for scenes. **Combine into one story** weaves " - "your checked rows into a single ordered picture story for the " - "Image tab (tick the model box above to draft it with the local " - "text model; the deterministic template is used otherwise).", - elem_classes="ms-muted", - ) - with gr.Row(elem_classes="ms-stack"): - list_scene = gr.Dropdown( - label="Illustrate scenes", - choices=[], - value=None, - scale=3, - multiselect=True, - info=( - "Pick one or more checked rows to open their cues in " - "the Image tab." - ), - ) - list_select_all = gr.Button( - "Select all scenes", - size="sm", - variant="secondary", - scale=0, - min_width=150, - ) - list_illustrate = gr.Button( - "Illustrate this scene", - size="sm", - scale=0, - min_width=180, - ) - list_combine = gr.Button( - "Combine into one story", - size="sm", - variant="secondary", - scale=0, - min_width=190, - ) - list_story = gr.Markdown() - - with gr.Row(): - 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, - ], - value="Clear", - size="sm", - scale=0, - min_width=110, - ) - list_sheet = gr.File( - label="Study sheet", - show_label=False, - interactive=False, - visible=False, - ) - - list_generate.click( - draft_list_candidates, - inputs=[list_input, list_use_model], - outputs=[list_status, list_table, list_story], - ).then( - list_scene_choices, - inputs=[list_table, list_story], - outputs=[list_illustrate_box, list_scene], - ) - list_input.submit( - draft_list_candidates, - inputs=[list_input, list_use_model], - outputs=[list_status, list_table, list_story], - ).then( - list_scene_choices, - inputs=[list_table, list_story], - outputs=[list_illustrate_box, list_scene], - ) - list_example.click( - _example_list, - inputs=None, - outputs=[ - list_input, - list_use_model, - list_status, - list_table, - list_story, - ], - ).then( - list_scene_choices, - inputs=[list_table, list_story], - outputs=[list_illustrate_box, list_scene], - ) - list_build.click( - build_list_story, - inputs=[list_input, list_table, list_use_model, list_palace], - outputs=[list_status, list_table, list_story], - ).then( - list_scene_choices, - inputs=[list_table, list_story], - outputs=[list_illustrate_box, list_scene], - ) - list_clear.click( - lambda: ( - gr.Group(visible=False), - gr.Dropdown(choices=[], value=None), - ), - inputs=None, - outputs=[list_illustrate_box, list_scene], - ) - list_sheet_button.click( - _list_sheet, inputs=[list_story], outputs=[list_sheet] - ) - - with gr.TabItem("Practice", id="practice"): - gr.Markdown( - """ - ### Test yourself, in order - Paste the same number or list you built. Practice uses the curated - Major-System words and never calls a model. Cards stay in the - original order so the mnemonic chain is preserved. - """ - ) - 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], - outputs=practice_outputs, - ) - practice_text.submit( - start_practice, - inputs=[practice_kind, practice_text], - outputs=practice_outputs, - ) - practice_reveal.click( - reveal_practice, - inputs=[practice_state], - outputs=[ - practice_state, - practice_answer, - practice_reveal, - practice_grade_row, - ], - ) - practice_knew_btn.click( - _practice_knew, - inputs=[practice_state], - outputs=practice_outputs, - ) - practice_missed_btn.click( - _practice_missed, - inputs=[practice_state], - outputs=practice_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 storyboard, or write a new scene. In the - Numbers or Ordered list tab, build the story first, then use - **Illustrate this scene** to send one checked cue here. - - 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"], - ) - 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_select_all.click( - lambda table, story: select_all_scenes(table, story, "number"), - inputs=[number_table, number_story], - outputs=[number_scene], - ) - list_select_all.click( - lambda table, story: select_all_scenes(table, story, "list"), - inputs=[list_table, list_story], - outputs=[list_scene], - ) - number_combine.click( - lambda selection, table, story, use_model: combine_scenes( - selection, table, story, use_model, "number" - ), - inputs=[number_scene, number_table, number_story, number_use_model], - outputs=[tabs, image_cue, image_status], - ) - list_combine.click( - lambda selection, table, story, use_model: combine_scenes( - selection, table, story, use_model, "list" - ), - inputs=[list_scene, list_table, list_story, list_use_model], - outputs=[tabs, image_cue, image_status], - ) - 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( - image_draw_handler, - inputs=[ - image_cue, - image_style, - image_size, - image_steps, - image_seed, - ], - outputs=[image_status, image_output], - ).then( - append_image_history, - inputs=[image_output, image_history], - outputs=[image_history, image_gallery], - ) - 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 keeps the order explicit. The - story is the mnemonic. - 4. **Practice** in the Practice tab. Say each answer out loud, - reveal it, and mark whether you knew it. Cards stay in the - original order and nothing is scored on a server. - 5. **Optionally illustrate scenes.** After the story builds, a - multiselect picker lists your checked rows. Choose one or - more, or click **Select all scenes**, then click - **Illustrate this scene** to open their cues in the Image - tab, one blank line apart — or click **Combine into one - story** to weave your checked rows (or your selection) into - a single ordered picture story for the Image tab. Tick the - local text-model box above to draft the combined story with - the model (order-checked; falls back to the deterministic - template otherwise). Only pictures you ask for use the - image model; images are hints for tricky scenes, not a - replacement story. Draw each scene separately. - - The deterministic route is the reliable baseline: curated Major - words, a complete storyboard, a Memory Palace route, and recall - prompts. The models only add optional drafts. - - ## Keep your work - - Each builder has **Download study sheet (.md)**. It writes the - story, palace route, and recall prompt (or the assembled word - card) to a Markdown file you can open in any notes app, print, or - paste into flashcards. Nothing is saved automatically: if you - close the page without downloading, the draft is gone. 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 public demo 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 "The local app binds to `127.0.0.1` only, creates no sharing link, and 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 check maps common English spelling patterns, while the Major - System maps consonant **sounds**. Say the word aloud; unusual - spellings, silent letters, accents, and proper nouns can trip the - approximation. You can replace the word with 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:** {"This demo 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 automatic - checker uses common English spelling patterns; it is approximate. - Read every word aloud and review unusual words, accents, digraphs, - and proper nouns. - - 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 deterministic storyboard is complete by construction. A model - story is only shown if every checked word/item appears in order; - even then it can contain extra decorative words. - - This prototype does not schedule spaced repetition. Download a - study sheet to keep a card, and repeat the Practice tab at your - own intervals. - - ## Curated starting words - - These are suggestions to edit, not an official vocabulary. The - automatic check is approximate; 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=None, - outputs=[ - tabs, - number_input, - number_use_model, - number_status, - number_table, - number_story, - ], - ) - start_list.click( - start_with_list, - inputs=None, - outputs=[ - tabs, - list_input, - list_use_model, - list_status, - list_table, - list_story, - ], - ) - start_word.click( - start_with_word, - inputs=None, - outputs=[ - tabs, - word_term, - word_context, - word_use_model, - word_status, - word_table, - word_card, - ], - ) - 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:** public hosted demo — submissions are processed on this Space's servers, not on your device." if PUBLIC_DEMO else "**Privacy:** localhost only; 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: - warm_up_image_model() - - -if __name__ == "__main__": - # Local runs stay private to this computer. A hosted Space must bind 0.0.0.0. - host = os.getenv("MEMORY_HOST", "").strip() or ( - "0.0.0.0" if PUBLIC_DEMO else "127.0.0.1" - ) - 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=1).launch( - server_name=host, - server_port=server_port, - share=False, - show_error=False, - theme=APP_THEME, - css=APP_CSS, - ) - - +"""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 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, +) +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 words_for_code +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, + auto_story_lines, + 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_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 a **hosted public demo**. 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; } +#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); +} +#ms-hero .ms-kicker { + text-transform: uppercase; + letter-spacing: .16em; + font-size: .72rem; + font-weight: 700; + 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-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-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; } +.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; } +} +""" + +# --------------------------------------------------------------------------- +# 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) -> tuple[str, bool, str, list[list[str]], str]: + status, rows, story = draft_number_candidates(NUMBER_EXAMPLE, False, saved) + 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 practice_number_table(number_text: str, table: Any) -> tuple[Any, ...]: + """Practice the learner's own checked words, in chain order.""" + try: + chunks = split_number(number_text) + except ValueError as exc: + return (gr.update(), f"**Input issue:** {exc}", gr.update(), gr.update(), + *_practice_error("")) + reviewed, errors = validate_number_rows(chunks, table) + problems = errors or number_blockers(reviewed) + 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("")) + entries = [(row.word, row.link or row.image, row.chunk) for row in reviewed] + return ( + gr.Tabs(selected="practice"), + gr.update(), + PRACTICE_NUMBER, + "".join(chunks), + *_practice_outputs( + _chain_practice_items(entries), + "".join(chunks), + "_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.""" + reviewed, errors = validate_list_rows(table) + if errors: + message = _issue_markdown("Fix the table before practicing", errors) + return (gr.update(), message, gr.update(), gr.update(), *_practice_error("")) + entries = [(row.item, row.link or row.cue, "") for row in reviewed] + return ( + gr.Tabs(selected="practice"), + gr.update(), + PRACTICE_LIST, + "\n".join(row.item for row in reviewed), + *_practice_outputs( + _chain_practice_items(entries), + "", + "_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 [] + if not items: + return ( + state, + gr.update(), + gr.update(visible=False), + gr.update(visible=False), + ) + index = state.get("index", 0) + updated = {**state, "revealed": True} + return ( + updated, + gr.update(value=items[index]["answer"], visible=True), + gr.update(visible=False), + gr.update(visible=True), + ) + + +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, + } + 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 ( + 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="\n".join(lines), 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]: + items = list(history or []) + if image is None: + return items, gr.update() + items.append(image) + items = items[-8:] + return items, items + + +def _practice_knew(state: dict[str, Any]) -> tuple[Any, ...]: + return grade_practice(state, True) + + +def _practice_missed(state: dict[str, Any]) -> tuple[Any, ...]: + return grade_practice(state, False) + + +# --------------------------------------------------------------------------- +# Start-here shortcuts (switch tab and fill in an editable example) +# --------------------------------------------------------------------------- + + +def start_with_numbers(saved: Any = None) -> tuple[Any, ...]: + number, use_model, status, rows, story = _example_number(saved) + return ( + gr.update(selected="numbers"), + number, + use_model, + status, + rows, + story, + ) + + +def start_with_list() -> tuple[Any, ...]: + text, use_model, status, rows, story = _example_list() + return ( + gr.update(selected="list"), + text, + use_model, + status, + rows, + story, + ) + + +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) + if whole: + choices.append((f"Whole chain in one picture ({len(items)} images)", whole)) + seen = {whole} + 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) + + +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) + ): + 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 names its own image. 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 name its own image), 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 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 +) -> 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) + 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._", + ] + ) + + +def draft_number_candidates( + number_text: str, use_model: bool, saved: Any = None +) -> tuple[str, list[list[str]], str]: + """Draft an editable table: saved words first, then model or curated.""" + try: + chunks = split_number(number_text) + 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. Replace any word or cue with a personal association." + ) + + rows: list[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]) + else: # pragma: no cover - the curated set covers 0-9 and 00-99 + rows.append([chunk, "", "", "needs a word", "your entry"]) + _add_story_lines(rows, "number") + + 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."] + ) + input_note = number_input_note(number_text) + if input_note: + status_parts.extend(["", input_note]) + + if rejected: + status_parts.extend( + [ + "", + "#### Model candidates not auto-accepted", + "", + "The curated 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) + + ". Curated 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, +) -> 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 + ) + 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, +) -> tuple[Any, ...]: + """Re-check edited rows, preserve order, and build complete story outputs.""" + current_rows = _current_rows(table) + try: + chunks = split_number(number_text) + 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) + + +def build_mind_map(topic: str, outline: str) -> tuple[str, str]: + """Draw the outline as a Mind Map and suggest how to recall it.""" + try: + topic_text, branches = _mind_map_parts(topic, outline) + except ValueError as exc: + return f"**Input issue:** {exc}", "" + 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 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_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 + return spaces.GPU(duration=60)(handler) + + +image_draw_handler = _gpu_wrapped(draw_local_image) + + +# delete_cache: every hour, drop Gradio's copies of files older than a day. +with gr.Blocks( + title="Memory Studio - editable mnemonic workbench", + 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() + ) + gr.HTML( + f""" +
+
Memory Studio · {"public demo" if PUBLIC_DEMO else "local-first mnemonic workbench"}
+

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( + "### Public demo\n\n" + "**Anything you type here is sent to this Hugging Face Space and " + "processed on its servers, not on your device.** The app does not " + "save it, but a hosted demo cannot offer the on-device privacy of " + "running it yourself. Do not paste secrets or private notes. Run " + "the app locally for private use.", + elem_classes="ms-note", + ) + + with gr.Tabs(selected="start", overflow_behavior="wrap") as tabs: + with gr.TabItem("Start here", id="start"): + 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 two-digit chunks and give each one 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" + ) + + 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.
+
+ """ + ) + 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", + ) + 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("Numbers", id="numbers"): + gr.Markdown( + """ + ### 1 · Enter a number + Leading zeros are kept. Up to 40 digits are split into two-digit + chunks; an odd final digit stays a single chunk. The table order is + locked to the digit order. + """ + ) + with gr.Row(elem_classes="ms-stack"): + number_input = gr.Textbox( + label="Number", + placeholder="Try 314159 or 0042", + lines=1, + scale=4, + ) + number_example = gr.Button( + "Try 314159", size="sm", scale=0, min_width=140 + ) + 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. 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." + ), + ) + number_palace = 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." + ), + ) + number_anchor.change( + lambda mode: gr.update(visible=mode == ANCHOR_PALACE), + inputs=[number_anchor], + outputs=[number_palace], + ) + 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(): + 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, + ], + 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_generate.click( + draft_number_candidates, + inputs=[number_input, number_use_model, personal_words], + outputs=[number_status, number_table, number_story], + ).then( + number_scene_choices, + inputs=[number_table, number_story], + outputs=[number_illustrate_box, number_scene, number_sheet], + ).then( + remember_story_lines, + inputs=[number_table], + outputs=[number_story_lines], + ) + number_input.submit( + draft_number_candidates, + inputs=[number_input, number_use_model, personal_words], + outputs=[number_status, number_table, number_story], + ).then( + number_scene_choices, + inputs=[number_table, number_story], + outputs=[number_illustrate_box, number_scene, number_sheet], + ).then( + remember_story_lines, + inputs=[number_table], + outputs=[number_story_lines], + ) + number_example.click( + _example_number, + inputs=[personal_words], + outputs=[ + number_input, + number_use_model, + number_status, + number_table, + number_story, + ], + ).then( + number_scene_choices, + inputs=[number_table, number_story], + outputs=[number_illustrate_box, number_scene, number_sheet], + ).then( + remember_story_lines, + inputs=[number_table], + outputs=[number_story_lines], + ) + number_build.click( + build_number_story, + inputs=[ + number_input, + number_table, + number_use_model, + number_anchor, + number_palace, + number_story_lines, + ], + outputs=[number_status, number_table, number_story, number_story_lines], + ).then( + number_scene_choices, + inputs=[number_table, number_story], + outputs=[number_illustrate_box, number_scene, number_sheet], + ) + 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("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_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." + ), + ) + list_palace = 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." + ), + ) + list_anchor.change( + lambda mode: gr.update(visible=mode == ANCHOR_PALACE), + inputs=[list_anchor], + outputs=[list_palace], + ) + 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(): + 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, + ], + 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_generate.click( + draft_list_candidates, + inputs=[list_input, list_use_model], + outputs=[list_status, list_table, list_story], + ).then( + list_scene_choices, + inputs=[list_table, list_story], + outputs=[list_illustrate_box, list_scene, list_sheet], + ).then( + remember_story_lines, + inputs=[list_table], + outputs=[list_story_lines], + ) + list_input.submit( + draft_list_candidates, + inputs=[list_input, list_use_model], + outputs=[list_status, list_table, list_story], + ).then( + list_scene_choices, + inputs=[list_table, list_story], + outputs=[list_illustrate_box, list_scene, list_sheet], + ).then( + remember_story_lines, + inputs=[list_table], + outputs=[list_story_lines], + ) + list_example.click( + _example_list, + inputs=None, + outputs=[ + list_input, + list_use_model, + list_status, + list_table, + list_story, + ], + ).then( + list_scene_choices, + inputs=[list_table, list_story], + outputs=[list_illustrate_box, list_scene, list_sheet], + ).then( + remember_story_lines, + inputs=[list_table], + outputs=[list_story_lines], + ) + list_build.click( + build_list_story, + inputs=[ + list_input, + list_table, + list_use_model, + list_anchor, + list_palace, + list_story_lines, + ], + outputs=[list_status, list_table, list_story, list_story_lines], + ).then( + list_scene_choices, + inputs=[list_table, list_story], + outputs=[list_illustrate_box, list_scene, list_sheet], + ) + 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("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_view = gr.HTML() + with gr.Row(): + 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, + inputs=[mind_topic, mind_outline], + outputs=[mind_status, mind_view], + ).then(_hidden_file, inputs=None, outputs=[mind_files]) + mind_example.click( + lambda: (MIND_MAP_EXAMPLE_TOPIC, MIND_MAP_EXAMPLE), + inputs=None, + outputs=[mind_topic, mind_outline], + ).then( + build_mind_map, + inputs=[mind_topic, mind_outline], + outputs=[mind_status, mind_view], + ).then(_hidden_file, inputs=None, outputs=[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 the Numbers or + Ordered list tab: it uses your own words and cues. You can also + paste a number or list here; a pasted number uses the curated + starter words. Each card asks for the next image in the chain, + then the digits it encodes. 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, + ], + ) + practice_knew_btn.click( + _practice_knew, + inputs=[practice_state], + outputs=practice_outputs, + ) + practice_missed_btn.click( + _practice_missed, + inputs=[practice_state], + outputs=practice_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"], + ) + 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( + image_draw_handler, + inputs=[ + image_cue, + image_style, + image_size, + image_steps, + image_seed, + ], + outputs=[image_status, image_output], + ).then( + append_image_history, + inputs=[image_output, image_history], + outputs=[image_history, image_gallery], + ) + 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**. Pictures are hints for tricky + scenes, 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. + + **Mind Map:** put a topic in the centre and one key word per line + on branches. Indented lines become details. Cover the map and + redraw it from memory to review. + + 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 thing kept is the + word list you choose to save, in this browser's local storage. + 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 public demo 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:** {"This demo 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], + outputs=[ + tabs, + number_input, + number_use_model, + number_status, + number_table, + number_story, + ], + ).then( + number_scene_choices, + inputs=[number_table, number_story], + outputs=[number_illustrate_box, number_scene, number_sheet], + ).then( + remember_story_lines, + inputs=[number_table], + outputs=[number_story_lines], + ) + start_list.click( + start_with_list, + inputs=None, + outputs=[ + tabs, + list_input, + list_use_model, + list_status, + list_table, + list_story, + ], + ).then( + list_scene_choices, + inputs=[list_table, list_story], + outputs=[list_illustrate_box, list_scene, list_sheet], + ).then( + remember_story_lines, + inputs=[list_table], + outputs=[list_story_lines], + ) + start_word.click( + start_with_word, + inputs=None, + outputs=[ + tabs, + word_term, + word_context, + word_use_model, + word_status, + word_table, + word_card, + ], + ) + mind_center.click( + mind_map_center_cue, inputs=[mind_topic], outputs=[tabs, image_cue] + ) + start_mind_map.click( + lambda: (gr.Tabs(selected="mindmap"), MIND_MAP_EXAMPLE_TOPIC, MIND_MAP_EXAMPLE), + inputs=None, + outputs=[tabs, mind_topic, mind_outline], + ).then( + build_mind_map, + inputs=[mind_topic, mind_outline], + outputs=[mind_status, mind_view], + ) + number_save_words.click( + save_number_words, + inputs=[number_input, number_table, personal_words], + 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( + saved_word_rows, inputs=[personal_words], outputs=[number_saved_table] + ) + number_practice.click( + practice_number_table, + inputs=[number_input, number_table], + 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], + ) + 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:** public hosted demo — 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: + 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=1).launch( + server_name=host, + server_port=server_port, + share=False, + show_error=False, + theme=APP_THEME, + css=APP_CSS, + ) + +