WillHbx commited on
Commit
aeaa809
·
0 Parent(s):

Initial commit: Reorganized project structure

Browse files

- Renamed Menu/ to ui/
- Fixed enemy spelling throughout
- Organized scripts into autoload/data/const/enums
- Moved unused assets to assets/unused/
- Created addons/ folder for outline system
- Cleaned up folder structure

CLAUDE.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLAUDE.md
2
+
3
+ Working guidance for AI pair-programming (Claude Code) on **hackathon-ia-visualnovel** — an
4
+ AI-improvised anime visual novel for the Build Small Hackathon. Read this first, then
5
+ [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for depth and [`docs/PROMPTS.md`](docs/PROMPTS.md)
6
+ for the exact prompts + grammar.
7
+
8
+ ## What this project is (1 paragraph)
9
+
10
+ A voice-or-text VN where story, NPC dialogue, and art are **generated live** by small local models.
11
+ Three model roles: **The Weaver** (director — emits structured JSON directives), **The Voices** (NPC
12
+ actor — in-character dialogue), and **The Painter** (SDXL-Turbo — backdrops + sprites). The Weaver and
13
+ Voices share **one** LLM (two system prompts). Input is transcribed by **Whisper** (The Ear). Hard
14
+ constraint: **≤ 32B total params**, must stay a **Gradio app on a HF Space**.
15
+
16
+ ## The golden rule
17
+
18
+ **The model proposes, code disposes.** The LLM returns a typed `DirectorOutput`; `state.apply_directives`
19
+ is the *only* function that mutates `GameState`. The `.md` files are a *derived view* for humans and for
20
+ re-injecting context — never the source of truth. Don't let the LLM hand-edit prose state.
21
+
22
+ ## Commands (uv)
23
+
24
+ ```bash
25
+ uv sync # light: gradio + pydantic + pillow (mock mode)
26
+ uv run python -m visualnovel.smoke # full loop, no UI, no models
27
+ uv run python app.py # custom VN UI → http://localhost:7860
28
+ GRADIO_MVP_UI=1 uv run python app.py # gr.Blocks fallback
29
+
30
+ uv run ruff check . && uv run ruff format .
31
+ uv run pytest -q # state round-trip · directives · memory budget
32
+
33
+ # real backends (install the relevant extras first — see README for ROCm/Metal flags)
34
+ VN_MOCK=0 VN_LLM_BACKEND=transformers uv run python app.py
35
+ VN_TRACE=runs/$(date +%s).jsonl uv run python app.py # Open-Trace bonus
36
+ ```
37
+
38
+ ## ⭐ The mock → real migration path (the whole point of this scaffold)
39
+
40
+ Everything runs **mock-first** (`VN_MOCK=1`). Replace one mock at a time; keep `pytest` + `smoke` green
41
+ after each. Work in this order (lowest risk → highest):
42
+
43
+ 1. **LLM — director call.** Implement `llm.LlamaCppLLM` (or `TransformersLLM`), then **delete the
44
+ `if config.USE_MOCK:` branches** in `orchestrator.direct_turn` / `init_world` / `compact_memory`
45
+ so the real `complete_json(schema=…)` path runs. The JSON schema is already derived from
46
+ `schemas.DirectorOutput` via `prompts.directive_schema()`. Tune sampling per `docs/PROMPTS.md §6`.
47
+ 2. **Painter.** Implement `painter.SdxlTurboPainter._render` (stub already sketches diffusers +
48
+ seed + LoRA). Caching, prompt composition, and seed-pinning are done. Set `VN_IMAGE_LORA` to your
49
+ fine-tuned anime LoRA when ready.
50
+ 3. **STT.** `stt.WhisperSTT` is sketched (faster-whisper). The frontend already records audio and
51
+ calls `/transcribe`.
52
+ 4. **Polish.** Sprite moods (pre-gen set, or FLUX.2-Klein conditioning), BiRefNet transparent sprites,
53
+ speculative backdrop paint, real `compact_memory` summaries.
54
+
55
+ Acceptance after each step: `uv run python -m visualnovel.smoke` still completes and `uv run pytest -q`
56
+ is green. The mock branches are clearly marked so they're easy to find and remove.
57
+
58
+ ## Architecture at a glance
59
+
60
+ ```
61
+ player (text/voice)
62
+ │ voice → stt.py (Whisper)
63
+ ▼
64
+ engine.play_turn ─▶ orchestrator.direct_turn ─ one grammar-constrained LLM call ─▶ DirectorOutput
65
+ │ (memory.assemble_context builds the bounded prompt)
66
+ ▼
67
+ state.apply_directives (deterministic; the ONLY mutator) ─▶ state.save_memory (.md views)
68
+ │
69
+ ├─ painter.backdrop / painter.sprite (cached by entity·mood·seed)
70
+ ▼
71
+ engine._view ─▶ ViewState ─▶ frontend/index.html (backdrop + sprite + dialogue)
72
+ ```
73
+
74
+ ## File responsibilities
75
+
76
+ | File | Owns | Don't put here |
77
+ |---|---|---|
78
+ | `visualnovel/schemas.py` | all Pydantic contracts (`GameState`, `DirectorOutput`, `ViewState`) | logic |
79
+ | `visualnovel/state.py` | `apply_directives` (sole mutator) + `.md` render | model calls, UI |
80
+ | `visualnovel/llm.py` | one LLM wrapper: `complete` / `complete_json(schema)` | game logic |
81
+ | `visualnovel/orchestrator.py` | the Weaver: init / direct_turn / compact (+ mock branches) | raw prompt strings (import from `prompts.py`) |
82
+ | `visualnovel/characters.py` | the Voices: present-character context | image prompts |
83
+ | `visualnovel/painter.py` | prompt compose, cache, seeds, render | story decisions |
84
+ | `visualnovel/stt.py` | Whisper transcribe | anything else |
85
+ | `visualnovel/memory.py` | bounded context + compaction trigger | persistence format (that's state.py) |
86
+ | `visualnovel/engine.py` | façade tying it together → `ViewState` | model internals |
87
+ | `app.py` | `gradio.Server` routes, `@app.api`, `@spaces.GPU` | business logic (keep thin) |
88
+ | `frontend/index.html` | the entire VN UI; talks via the Gradio JS client | secrets, model logic |
89
+
90
+ ## Conventions
91
+
92
+ - **Python 3.11+ (3.14 pinned), type hints everywhere, Pydantic for all IO contracts.** `ruff` formats/lints.
93
+ - **Keep `app.py` thin.** Logic lives in `visualnovel/` so it's unit-testable without a server.
94
+ - **One LLM call per turn by default** (`complete_json` with the directive schema). Extra calls (init,
95
+ compaction) are allowed but rare — latency matters.
96
+ - **Every Painter call is cached** by `(kind, prompt, seed)`. Generate a sprite **once**; never re-paint
97
+ to "refresh" (kills consistency). Seeds are explicit and stored in state.
98
+ - **Prompts are versioned in `docs/PROMPTS.md`** (mirrored in `prompts.py`). Don't scatter literals.
99
+ - **Heavy imports stay lazy** (inside the real backend classes) so a mock checkout needs nothing.
100
+ - **Stream text first, image second.** Dialogue appears before the (slower) image.
101
+
102
+ ## Platform gotchas (read before you fight these)
103
+
104
+ 1. **Python 3.14 is bleeding-edge.** torch / llama-cpp-python / ctranslate2 may lack 3.14 wheels →
105
+ `uv python pin 3.12 && uv sync`.
106
+ 2. **No CUDA locally — ROCm + Metal.** llama.cpp build flags differ: `-DGGML_METAL=on` (Mac, default),
107
+ `-DGGML_HIPBLAS=on` / `-DGGML_HIP=on` (AMD). torch reports **ROCm as "cuda"** → `detect_device()`
108
+ returns `"cuda"` on the AMD box; `"mps"` on Mac.
109
+ 3. **CTranslate2 has no Metal/ROCm** → `faster-whisper` runs on CPU on both your machines (fine for
110
+ short clips). For GPU STT use `mlx-whisper` (Mac) or `whisper.cpp`.
111
+ 4. **llama.cpp on hosted ZeroGPU is finicky.** Claim the llama.cpp badge **locally**; keep the
112
+ `transformers` backend for the Space (`VN_LLM_BACKEND=transformers`).
113
+ 5. **Image latency is the #1 UX risk.** 1–4-step SDXL-Turbo, 512–768px, text-before-image, cache hard.
114
+ 6. **Context window is finite** ("Thousand Token Wood"). Feed summary + present sheets + last k turns —
115
+ never the whole log. `memory.py` enforces it.
116
+ 7. **Spaces filesystem is ephemeral.** `.md` memory is per-session unless you wire HF persistent storage.
117
+
118
+ ## Definition of done (MVP)
119
+
120
+ A player types (then speaks) a line → an NPC replies in character → the Weaver decides whether the
121
+ scene/character changed → the screen shows a coherent backdrop + sprite + dialogue, looping
122
+ indefinitely without crashing, on the laptop-safe config, inside the custom VN UI.
123
+
124
+ ## Out of scope (resist these)
125
+
126
+ Multiplayer; save/load beyond one session; combat/stats UIs; more than ~3 NPCs on screen;
127
+ photorealism (anime is cheaper, faster, prettier here); a second LLM just to look "multi-agent".
128
+ Ship the loop.
README.md ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Thousand Token Wood
3
+ emoji: 🍄
4
+ colorFrom: green
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: "5.x"
8
+ app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ ---
12
+
13
+ # hackathon-ia-visualnovel 🍄
14
+
15
+ > **Thousand Token Wood** — an AI-improvised, voice-or-text **anime visual novel**.
16
+ > Build Small Hackathon (Chapter Two). Story, characters, and art are generated **live** by
17
+ > small local models — nothing is pre-scripted.
18
+
19
+ You step into a wood that is being *dreamed into existence* around you. Every spirit you meet is
20
+ conjured on the spot; every backdrop is painted the moment you arrive. Because the wood is dreamed
21
+ by a small, slightly forgetful mind, it is whimsical and never the same twice — **the model's
22
+ quirks aren't bugs, they're the wood dreaming.** Take the models out and there's no game, only an
23
+ empty Gradio shell. That's what makes the AI *load-bearing*.
24
+
25
+ ---
26
+
27
+ ## ✨ This repo runs on a fresh checkout — with **zero models**
28
+
29
+ It ships in **MOCK mode** (`VN_MOCK=1`, the default): deterministic fake LLM / painter / STT so the
30
+ **entire loop works offline** with placeholder art. Open it, watch a turn happen, then have Claude
31
+ Code replace each mock with a real model, one module at a time. See [`CLAUDE.md`](CLAUDE.md).
32
+
33
+ ```bash
34
+ uv sync # installs only gradio + pydantic + pillow (seconds)
35
+ uv run python -m visualnovel.smoke # full loop in the terminal, no UI, no models
36
+ uv run python app.py # custom VN UI → http://localhost:7860
37
+ GRADIO_MVP_UI=1 uv run python app.py # plain gr.Blocks fallback (Phase 0/1)
38
+ ```
39
+
40
+ ---
41
+
42
+ ## The cast of models (the “several AIs”)
43
+
44
+ Three *roles*, three *real* model families (text, image, speech). The two text roles **share one
45
+ LLM** (same weights, two system prompts) to respect the parameter budget.
46
+
47
+ | In-world name | Role | Backed by | Output |
48
+ |---|---|---|---|
49
+ | 🧵 **The Weaver** | director / GM — builds the world, keeps canon, decides what changes | LLM (shared) | structured **directives** (JSON) |
50
+ | 🎭 **The Voices** | actor — speaks as the present spirits, in voice | LLM (shared) | in-character **dialogue** + emotion |
51
+ | 🎨 **The Painter** | renders backdrops + character sprites | **SDXL-Turbo** (+ your anime-style LoRA) | **images** |
52
+ | 👂 **The Ear** | turns spoken words into text | Whisper | transcribed input |
53
+
54
+ The Weaver and Voices are one **grammar-constrained LLM call per turn** → `{ speaker, dialogue,
55
+ emotion, directives }`. Code applies the directives deterministically; **the LLM never edits state
56
+ directly.**
57
+
58
+ ---
59
+
60
+ ## Parameter budget — the “beefy” config (≤ 32B total)
61
+
62
+ | Component | Model | ~Params |
63
+ |---|---|---|
64
+ | LLM (shared) | **Qwen3-14B** | ~14B |
65
+ | Image | **SDXL-Turbo** (+ fine-tuned anime LoRA) | ~3.5B |
66
+ | STT | **Whisper-small** | ~0.25B |
67
+ | Matting (optional) | BiRefNet | ~0.2B |
68
+ | **Total** | | **≈ 18B** ✅ |
69
+
70
+ MoE models count by **total** params. Everything is hosted on HF (you have credits), so the only
71
+ hard limit is ≤ 32B. Override any model via env vars in [`visualnovel/config.py`](visualnovel/config.py).
72
+
73
+ ---
74
+
75
+ ## Setup & install (uv)
76
+
77
+ > **Python 3.14** is pinned in `.python-version`. It's brand new — if `torch` /
78
+ > `llama-cpp-python` / `ctranslate2` don't yet publish 3.14 wheels, just
79
+ > `uv python pin 3.12 && uv sync`. The package code is 3.11+ clean.
80
+
81
+ Your hardware is **AMD ROCm + Apple Metal (no local CUDA)**, which changes the GPU build flags:
82
+
83
+ ```bash
84
+ # ---- Apple Silicon (M3 Max) — Metal ----
85
+ uv sync --extra image --extra stt
86
+ CMAKE_ARGS="-DGGML_METAL=on" uv pip install llama-cpp-python # Metal is default on macOS
87
+ # torch uses the MPS backend automatically. faster-whisper runs on CPU (CTranslate2 has no
88
+ # Metal); for GPU STT on Mac use mlx-whisper or whisper.cpp instead.
89
+
90
+ # ---- AMD RX 7900 XTX — ROCm (Linux) ----
91
+ uv pip install torch --index-url https://download.pytorch.org/whl/rocm6.2 # ROCm torch wheel
92
+ CMAKE_ARGS="-DGGML_HIPBLAS=on" uv pip install llama-cpp-python # newer builds: -DGGML_HIP=on
93
+ uv sync --extra image --extra stt
94
+ # torch reports ROCm as "cuda" (so config.detect_device() returns "cuda" on this box).
95
+ # CTranslate2 has no ROCm → faster-whisper runs on CPU (fine for short clips), or use whisper.cpp.
96
+ ```
97
+
98
+ Then download weights (or let them fetch lazily on first real use) and flip off mock mode:
99
+
100
+ ```bash
101
+ uv run python scripts/download_models.py
102
+ VN_MOCK=0 uv run python app.py
103
+ ```
104
+
105
+ ---
106
+
107
+ ## How a turn works
108
+
109
+ ```
110
+ START ─▶ Weaver: dream world + opening scene + first spirit ─▶ Painter: backdrop + sprite
111
+ │
112
+ └─▶ LOOP
113
+ 1. player speaks/types ─▶ Ear (Whisper) ─▶ text
114
+ 2. ONE grammar-constrained LLM call ─▶ { speaker, dialogue, emotion, directives }
115
+ 3. state.apply_directives(...) deterministically (move scene, add/exit spirit, mood,
116
+ relationship, flags, beat, ending) ─▶ .md dream-memory updated
117
+ 4. if scene/character changed ─▶ Painter (cached, seed-pinned)
118
+ 5. render: backdrop + sprite(mood) + dialogue (text streams first; image fills in)
119
+ ```
120
+
121
+ Deep design in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md); prompts + JSON schema + GBNF grammar
122
+ in [`docs/PROMPTS.md`](docs/PROMPTS.md).
123
+
124
+ ---
125
+
126
+ ## Project structure
127
+
128
+ ```
129
+ hackathon-ia-visualnovel/
130
+ ├── app.py # gradio.Server entry + gr.Blocks MVP fallback (thin)
131
+ ├── pyproject.toml # uv project; heavy ML libs are optional extras
132
+ ├── .python-version # 3.14 (fallback: uv python pin 3.12)
133
+ ├── frontend/index.html # custom layered VN UI (backdrop · sprite · dialogue · mic)
134
+ ├── visualnovel/
135
+ │ ├── schemas.py # Pydantic: GameState (truth) + DirectorOutput (LLM contract)
136
+ │ ├── config.py # paths, flags, model registry, THEMES, device detection
137
+ │ ├── prompts.py # system prompts + schema helpers (no scattered literals)
138
+ │ ├── llm.py # MockLLM · LlamaCppLLM · TransformersLLM behind one interface
139
+ │ ├── orchestrator.py # the Weaver: init_world / direct_turn / compact_memory
140
+ │ ├── characters.py # the Voices: present-character actor context
141
+ │ ├── painter.py # the Painter: prompt compose, cache, MockPainter + SDXL stub
142
+ │ ├── stt.py # the Ear: Whisper (mock + faster-whisper)
143
+ │ ├── state.py # apply_directives (the ONLY mutator) + .md render
144
+ │ ├── memory.py # bounded context assembly + compaction trigger
145
+ │ ├── engine.py # façade: start() / play_turn() → ViewState
146
+ │ ├── trace.py # per-turn JSONL trace (Open-Trace bonus)
147
+ │ └── smoke.py # `python -m visualnovel.smoke`
148
+ ├── templates/ # the .md dream-memory views (rendered each turn)
149
+ ├── tests/ # state round-trip · directive apply · memory budget (mock, green)
150
+ ├── scripts/download_models.py
151
+ └── docs/ # ARCHITECTURE.md · PROMPTS.md
152
+ ```
153
+
154
+ ---
155
+
156
+ ## Bonus quests targeted
157
+
158
+ | Badge | How |
159
+ |---|---|
160
+ | 🎨 **Off-Brand** (custom UI) | bespoke VN frontend via `gradio.Server` (`frontend/index.html`) |
161
+ | 🦙 **Llama-Champion** | LLM through `llama-cpp-python` + JSON-schema/GBNF grammar (run **locally** for the video) |
162
+ | 🔌 **Off the Grid** | all weights local; demoed with the network off |
163
+ | 🎯 **Well-Tuned** | the **fine-tuned SDXL-Turbo anime LoRA**, published on the Hub (`VN_IMAGE_LORA`) |
164
+ | 📡 **Open-Trace** | `VN_TRACE=runs/run.jsonl` records every orchestration step → publish as a dataset |
165
+ | 📓 **Field-Notes** | write up the diegetic conceit + one-call director pattern |
166
+
167
+ > ⚠️ **llama.cpp on the *hosted* ZeroGPU Space is the trickiest bit** — claim it **locally** in the
168
+ > demo video and keep the `transformers` backend (`VN_LLM_BACKEND=transformers`) for the Space.
169
+ > See [`docs/ARCHITECTURE.md` §7](docs/ARCHITECTURE.md).
170
+
171
+ ---
172
+
173
+ ## Quality
174
+
175
+ ```bash
176
+ uv run ruff check . && uv run ruff format .
177
+ uv run pytest -q
178
+ ```
179
+
180
+ ## Submission checklist
181
+
182
+ - [ ] Registered on the Build-Small org by **June 3** + joined the Gradio Discord.
183
+ - [ ] Space is live and loads without errors.
184
+ - [ ] Total params **≤ 32B** (stated).
185
+ - [ ] It's a Gradio app (`gradio.Server` counts).
186
+ - [ ] Demo video + social post.
187
+
188
+ Built for the **Build Small Hackathon** (Gradio × Hugging Face, June 2026). Code Apache-2.0 — match
189
+ the licenses of the weights you ship (SDXL-Turbo and Qwen3 are permissive; **check FLUX.2** if you
190
+ swap the painter).
app.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Entry point. Thin by design — all logic lives in the `visualnovel` package.
2
+
3
+ Two UIs:
4
+ - default: a custom VN frontend (frontend/index.html) served by `gradio.Server`, talking to
5
+ @app.api endpoints via the Gradio JS client. (Off-Brand / custom-UI bonus.)
6
+ - GRADIO_MVP_UI=1: a plain gr.Blocks UI to de-risk the loop in Phase 0/1.
7
+
8
+ Run modes
9
+ ---------
10
+ uv run python app.py # use whatever's in .env (VN_MOCK default: 1)
11
+ uv run python app.py --mode mock # force VN_MOCK=1 (no models needed)
12
+ uv run python app.py --mode prod # force VN_MOCK=0 (real backends)
13
+ uv run python app.py --mode debug # VN_MOCK=1 + verbose logging + live monitor
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ # ── Mode selection: must run BEFORE any visualnovel import ──────────────────
19
+ # config.py reads os.getenv() at import time via load_dotenv(), so we must
20
+ # set the env vars first.
21
+ import argparse
22
+ import atexit
23
+ import logging
24
+ import os
25
+
26
+
27
+ def _apply_mode() -> str | None:
28
+ p = argparse.ArgumentParser(add_help=False)
29
+ p.add_argument(
30
+ "--mode",
31
+ choices=["mock", "prod", "debug"],
32
+ default=None,
33
+ help=(
34
+ "mock → VN_MOCK=1 (no models, default) | "
35
+ "prod → VN_MOCK=0 (real backends) | "
36
+ "debug → VN_MOCK=1 + verbose logs + live resource monitor"
37
+ ),
38
+ )
39
+ args, _ = p.parse_known_args()
40
+ if args.mode == "mock":
41
+ os.environ["VN_MOCK"] = "1"
42
+ elif args.mode == "prod":
43
+ os.environ["VN_MOCK"] = "0"
44
+ elif args.mode == "debug":
45
+ # VN_MOCK is left untouched — load_dotenv() (in config.py) will apply .env.
46
+ # Set VN_MOCK=0 in .env for real backends, VN_MOCK=1 for mock+monitoring.
47
+ os.environ["VN_DEBUG"] = "1"
48
+ return args.mode
49
+
50
+
51
+ _RUN_MODE = _apply_mode()
52
+
53
+ logging.basicConfig(
54
+ level=logging.WARNING, # keep third-party libs quiet
55
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
56
+ datefmt="%H:%M:%S",
57
+ )
58
+ if _RUN_MODE == "debug":
59
+ # debug-level logs only for our own package; third-party stays at WARNING
60
+ logging.getLogger("visualnovel").setLevel(logging.DEBUG)
61
+
62
+ # ── Silence known noisy ML dependency warnings ────────────────────────────
63
+ import warnings # noqa: E402
64
+
65
+ # huggingface_hub: deprecated symlinks arg (internal, not our call)
66
+ warnings.filterwarnings("ignore", message=".*local_dir_use_symlinks.*")
67
+ # huggingface_hub: unauthenticated rate-limit notice (surfaced as UserWarning too)
68
+ warnings.filterwarnings("ignore", message=".*unauthenticated.*")
69
+ # transformers: catch any remaining FutureWarnings we don't control (e.g. upstream renames)
70
+ warnings.filterwarnings("ignore", category=FutureWarning, module="transformers")
71
+
72
+ # Suppress WARNING-level noise from ML frameworks; errors still surface
73
+ for _lib in ("transformers", "diffusers", "huggingface_hub"):
74
+ logging.getLogger(_lib).setLevel(logging.ERROR)
75
+
76
+ # ── Project imports (after env vars are set) ─────────────────────────────────
77
+ from pathlib import Path
78
+
79
+ from visualnovel import config
80
+ from visualnovel.engine import Engine
81
+ from visualnovel.metrics import collector
82
+ from visualnovel.schemas import SetupForm
83
+
84
+ # Activate monitoring only in debug mode (no-op otherwise)
85
+ if config.DEBUG:
86
+ collector.activate(config.RUNS_DIR)
87
+ atexit.register(collector.save_report)
88
+
89
+ ENGINE = Engine() # single-session game
90
+ FRONTEND = Path(__file__).parent / "frontend" / "index.html"
91
+
92
+
93
+ # --- optional ZeroGPU decorator (no-op off-Space / when `spaces` isn't installed) ---
94
+ try:
95
+ import spaces # type: ignore
96
+
97
+ def gpu(fn=None, **kw): # supports @gpu and @gpu(duration=...)
98
+ return spaces.GPU(**kw)(fn) if fn is not None else spaces.GPU(**kw)
99
+ except Exception: # pragma: no cover
100
+
101
+ def gpu(fn=None, **kw):
102
+ return fn if fn is not None else (lambda f: f)
103
+
104
+
105
+ # =========================================================================== #
106
+ # Custom frontend via gradio.Server
107
+ # =========================================================================== #
108
+ def build_server():
109
+ from fastapi.responses import HTMLResponse
110
+ from fastapi.staticfiles import StaticFiles
111
+ from gradio import Server
112
+
113
+ app = Server()
114
+ # serve generated images (backdrops/sprites) as static files at /images/<name>
115
+ app.mount("/images", StaticFiles(directory=str(config.CACHE_DIR)), name="images")
116
+
117
+ @app.get("/", response_class=HTMLResponse)
118
+ async def home() -> str:
119
+ return FRONTEND.read_text(encoding="utf-8")
120
+
121
+ @app.api(name="themes")
122
+ def themes() -> dict:
123
+ return {"themes": config.THEMES, "tones": config.TONES}
124
+
125
+ @app.api(name="start")
126
+ @gpu
127
+ def start(theme: str = "fantasy_forest", tone: str = "cozy", seed: int | None = None) -> dict:
128
+ return ENGINE.start(SetupForm(theme=theme, tone=tone, seed=seed)).model_dump()
129
+
130
+ @app.api(name="turn")
131
+ @gpu
132
+ def turn(player_input: str) -> dict:
133
+ return ENGINE.play_turn(player_input).model_dump()
134
+
135
+ @app.api(name="transcribe")
136
+ @gpu
137
+ def transcribe(audio: dict) -> dict:
138
+ # `audio` is a Gradio FileData-like dict with a "path" key.
139
+ path = audio["path"] if isinstance(audio, dict) else audio
140
+ return {"text": ENGINE.transcribe(path)}
141
+
142
+ # ── Debug dashboard — only registered when VN_DEBUG=1 ────────────────
143
+ if config.DEBUG:
144
+ import asyncio as _asyncio
145
+ import json as _json
146
+
147
+ from fastapi.responses import StreamingResponse
148
+
149
+ _debug_html = Path(__file__).parent / "frontend" / "debug.html"
150
+
151
+ @app.get("/debug", response_class=HTMLResponse)
152
+ async def debug_dashboard() -> str:
153
+ return _debug_html.read_text(encoding="utf-8")
154
+
155
+ @app.get("/debug/stream")
156
+ async def debug_stream() -> StreamingResponse:
157
+ async def _gen():
158
+ try:
159
+ while True:
160
+ yield f"data: {_json.dumps(collector.snapshot())}\n\n"
161
+ await _asyncio.sleep(1.0)
162
+ except _asyncio.CancelledError:
163
+ pass
164
+
165
+ return StreamingResponse(
166
+ _gen(),
167
+ media_type="text/event-stream",
168
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
169
+ )
170
+
171
+ @app.get("/debug/report")
172
+ async def debug_report() -> dict:
173
+ collector.save_report()
174
+ return {"status": "ok"}
175
+
176
+ return app
177
+
178
+
179
+ # =========================================================================== #
180
+ # MVP fallback: plain gr.Blocks
181
+ # =========================================================================== #
182
+ def build_mvp():
183
+ import gradio as gr
184
+
185
+ def on_start(theme, tone):
186
+ v = ENGINE.start(SetupForm(theme=theme, tone=tone))
187
+ bg = v.backdrop_url and (config.CACHE_DIR / Path(v.backdrop_url).name)
188
+ return str(bg) if bg else None, f"**{v.speaker}** ({v.emotion}): {v.dialogue}"
189
+
190
+ def on_turn(msg):
191
+ v = ENGINE.play_turn(msg)
192
+ bg = v.backdrop_url and (config.CACHE_DIR / Path(v.backdrop_url).name)
193
+ return str(bg) if bg else None, f"**{v.speaker}** ({v.emotion}): {v.dialogue}", ""
194
+
195
+ with gr.Blocks(title="Thousand Token Wood (MVP)") as demo:
196
+ gr.Markdown("## 🍄 Thousand Token Wood — MVP loop")
197
+ with gr.Row():
198
+ theme = gr.Dropdown(list(config.THEMES), value="fantasy_forest", label="Theme")
199
+ tone = gr.Dropdown(config.TONES, value="cozy", label="Tone")
200
+ start_btn = gr.Button("Enter the wood", variant="primary")
201
+ scene = gr.Image(label="Scene", height=420)
202
+ dialogue = gr.Markdown()
203
+ with gr.Row():
204
+ box = gr.Textbox(placeholder="say something to the wood…", scale=4, label="")
205
+ send = gr.Button("Speak", scale=1)
206
+ start_btn.click(on_start, [theme, tone], [scene, dialogue])
207
+ send.click(on_turn, [box], [scene, dialogue, box])
208
+ box.submit(on_turn, [box], [scene, dialogue, box])
209
+ return demo
210
+
211
+
212
+ if __name__ == "__main__":
213
+ if config.MVP_UI:
214
+ build_mvp().launch()
215
+ else:
216
+ build_server().launch(show_error=True)
docs/ARCHITECTURE.md ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Thousand Token Wood — Architecture
2
+
3
+ Deep technical design for the AI-improvised visual novel. Companion to [`../README.md`](../README.md) (overview), [`../CLAUDE.md`](../CLAUDE.md) (conventions), and [`PROMPTS.md`](PROMPTS.md) (exact prompts + grammar).
4
+
5
+ ---
6
+
7
+ ## 0. Concept & design pillars
8
+
9
+ **Premise.** The player is a wanderer who steps into a wood that is being *dreamed into existence* around them. Everyone they meet is a spirit the wood conjures; every backdrop is painted the moment the player arrives. The player shapes the dream by speaking or writing.
10
+
11
+ **The diegetic conceit (this is the most important design decision).** The wood is dreamed by a *small, slightly forgetful mind*. So when a small model is whimsical, slightly inconsistent, or surreal, that is **in-world correct** — the wood is dreaming. This reframing turns the weaknesses of ≤32B models into the *aesthetic*, and it’s what lets a small-model game feel intentional rather than broken. Every design choice should reinforce “a dream that paints itself,” not “a chatbot that sometimes fails.”
12
+
13
+ **Design pillars**
14
+
15
+ 1. **AI generates the content, not just assists.** Plot direction, dialogue, and art are produced live. Remove the models and nothing remains.
16
+ 2. **Snappy over clever.** On a laptop, latency kills delight. One LLM call per turn; 1–4-step image model; aggressive caching; text-before-image.
17
+ 3. **The model proposes, code disposes.** The LLM emits *typed directives*; deterministic code owns the canonical state. Small models cannot be trusted to hand-edit prose state without drift.
18
+ 4. **Memory is a budget, not an archive.** Feed the model a rolling summary + present-scene detail + present-character sheets — never the whole history.
19
+ 5. **Constrain to survive.** Grammar-constrained decoding guarantees parseable directives even from a 7–8B model.
20
+
21
+ ---
22
+
23
+ ## 1. System overview
24
+
25
+ ```
26
+ ┌──────────────────────────── HF Space (gradio.Server) ────────────────────────────┐
27
+ │ │
28
+ │ frontend/index.html ── Gradio JS client ──▶ @app.api endpoints │
29
+ │ (layered VN UI) │ │
30
+ │ ▼ │
31
+ │ app.py (thin: routes, @app.api, @spaces.GPU) │
32
+ │ │ │ │ │ │
33
+ │ ▼ ▼ ▼ ▼ │
34
+ │ stt.py orchestrator.py characters.py painter.py │
35
+ │ (Whisper) (the Weaver) (the Voices) (diffusion + BiRefNet) │
36
+ │ │ │ │ ▲ │
37
+ │ │ └──── llm.py (llama.cpp / transformers, grammar) ────┘ │
38
+ │ ▼ │
39
+ │ state.py (GameState · apply directives) ──▶ memory.py (summary + budget) │
40
+ │ │ │
41
+ │ ▼ │
42
+ │ .md memory: templates/world_state.md · one per character │
43
+ └───────────────────────────────────────────────────────────────────────────────┘
44
+ ```
45
+
46
+ `stt.py`, `orchestrator.py`, `characters.py`, `painter.py` are all callable in isolation (unit-testable). `app.py` only wires them to HTTP.
47
+
48
+ ---
49
+
50
+ ## 2. The model roles in detail
51
+
52
+ ### 2.1 Why one LLM for two roles
53
+
54
+ The “Weaver” and the “Voices” are **distinct agents** (different jobs, different prompts, different output shapes) but they run on the **same loaded LLM weights**. Reasons: (a) the parameter budget — a second 7–8B model would nearly double VRAM for little gain; (b) simplicity — one runtime, one quantization, one warm-up; (c) it’s still genuinely multi-model (text + image + speech are three real, different models). If you later want a *visibly* separate model for the demo narrative, the cheapest split is a tiny dedicated model for one narrow job (e.g. a 0.5–1.5B model just for image-prompt rewriting) — but that’s optional and not recommended for the MVP.
55
+
56
+ ### 2.2 The Weaver (Game Master / director)
57
+
58
+ **Responsibilities**
59
+
60
+ - **`init_world(seed, vibe)`** — invent the setting, the opening scene, and the first NPC; write the world-state `.md` and the first character sheet.
61
+ - **`direct_turn(state, player_input)`** — the per-turn workhorse. In a single grammar-constrained call it produces both (a) the NPC’s reply (delegating tone to the Voices system prompt) and (b) the **directives** that tell the engine what changed.
62
+ - **`compact_memory(state)`** — periodically fold old events into the rolling summary to stay within the context budget.
63
+
64
+ **I/O contract (per turn).** Input: assembled context (see §4.4). Output: a single JSON object validated against the directive schema (§4.2). Code applies it; the Weaver never writes to state directly.
65
+
66
+ ### 2.3 The Voices (character manager / actor)
67
+
68
+ The Voices isn’t (in the default design) a separate LLM call — it is the **actor persona layer** of the same per-turn call. `characters.py` assembles the actor context: for each *present* NPC, its character sheet (traits, voice, goals, current mood, relationship to the player) plus the current scene. The system prompt instructs the model to speak *only* as the addressed/active NPC, in their voice, never breaking character or narrating as the author.
69
+
70
+ > **Two-call variant (optional).** If you find the single call muddies voice quality, split it: call 1 = Voices produces dialogue (free text); call 2 = Weaver reads the dialogue + player input and emits directives (grammar JSON). This doubles per-turn latency, so only do it if quality demands it. Keep it behind a flag.
71
+
72
+ ### 2.4 The Painter (image)
73
+
74
+ See §5. Consumes prompts composed from the world style guide + the scene/character description; returns a backdrop image and/or a character sprite (cut to transparency).
75
+
76
+ ### 2.5 The Ear (STT)
77
+
78
+ See §6. Whisper turns recorded audio into the player’s text input. Purely a front door to the loop.
79
+
80
+ ---
81
+
82
+ ## 3. The game loop in detail
83
+
84
+ ### 3.1 Initialisation (once)
85
+
86
+ 1. Player picks a *vibe* (e.g. “cozy folktale”, “eerie”, “absurd”) and optionally a seed.
87
+ 2. `orchestrator.init_world()` → world-state `.md` + first character sheet + an opening line of narration/dialogue + an initial set of directives (scene description, first NPC, requested art).
88
+ 3. `painter` paints the opening backdrop and the first sprite (parallelisable). Cache both.
89
+ 4. Render the opening scene.
90
+
91
+ ### 3.2 The turn (loops)
92
+
93
+ | Step | Module | What happens |
94
+ |---|---|---|
95
+ | 1 | `stt` (if voice) | Recorded audio → text. Typed input skips this. |
96
+ | 2 | `memory` | Assemble context: style guide + rolling summary + current scene + present-character sheets + last *k* turns + the player input. Enforce token budget. |
97
+ | 3 | `orchestrator.direct_turn` → `llm.complete_json` | **One** grammar-constrained call → `{ speaker, dialogue, emotion, directives }`. |
98
+ | 4 | `state` | Validate + apply directives deterministically: move scene, add/remove NPC, set mood, set relationship deltas, set flags, mark beat/ending. |
99
+ | 5 | `memory` | Append the turn; if over budget or every *N* turns, `compact_memory()`. |
100
+ | 6 | `painter` (conditional) | If `scene_change` → paint/lookup backdrop. If `new_character` → paint+matte sprite. If only `mood` changed → swap to the (cached or conditioned) mood sprite. |
101
+ | 7 | frontend | Render: backdrop, sprite (with mood), speaker name, dialogue. Dialogue streams **first**; images fill in when ready. |
102
+
103
+ ### 3.3 The directive contract (what the LLM is allowed to change)
104
+
105
+ Directives are a *closed set* of safe, structured operations — the engine’s “API” that the model calls by emitting JSON (conceptually identical to tool-calling, but enforced by grammar). Closed set ⇒ the model can’t put the game in an undefined state. See §4.2 for the schema and [`PROMPTS.md`](PROMPTS.md) for the GBNF grammar.
106
+
107
+ ---
108
+
109
+ ## 4. State & memory
110
+
111
+ ### 4.1 `GameState` (source of truth)
112
+
113
+ A Pydantic model held in memory for the session and mirrored to `.md`. Sketch:
114
+
115
+ ```python
116
+ class Character(BaseModel):
117
+ id: str
118
+ name: str
119
+ one_line: str # "a nervous lantern-moth who collects apologies"
120
+ traits: list[str]
121
+ voice: str # how they speak: rhythm, vocabulary, tics
122
+ goals: str
123
+ appearance: str # the STABLE description used for every sprite of them
124
+ mood: str = "neutral" # drives sprite variant
125
+ relationship: int = 0 # -100..100 toward the player
126
+ sprite_seed: int # pinned for visual consistency
127
+ known_facts: list[str] = [] # what THIS character knows (avoids omniscience)
128
+
129
+ class Scene(BaseModel):
130
+ id: str
131
+ place: str
132
+ description: str # used for the backdrop prompt
133
+ mood: str
134
+ present: list[str] # character ids on stage (cap ~3)
135
+ backdrop_seed: int
136
+
137
+ class GameState(BaseModel):
138
+ seed: int
139
+ style_guide: str # global art + tone bible (set at init, mostly frozen)
140
+ vibe: str
141
+ scene: Scene
142
+ characters: dict[str, Character]
143
+ summary: str = "" # rolling compressed history
144
+ recent_turns: list[Turn] = [] # last k verbatim turns
145
+ flags: dict[str, str] = {} # arbitrary world facts the Weaver sets
146
+ beat: str = "opening" # opening | rising | turn | resolution | ended
147
+ turn_index: int = 0
148
+ ```
149
+
150
+ ### 4.2 Directive schema (the per-turn LLM output)
151
+
152
+ ```jsonc
153
+ {
154
+ "speaker": "lantern_moth", // which present character speaks (or "narrator")
155
+ "dialogue": "string", // their line, in voice
156
+ "emotion": "neutral|joy|fear|anger|sad|surprise|tender", // → sprite mood
157
+ "directives": {
158
+ "scene_change": null, // or { "place": "...", "description": "...", "mood": "..." }
159
+ "new_character": null, // or a partial Character (id,name,one_line,appearance,voice,traits,goals)
160
+ "exit_character": null, // or character id leaving the stage
161
+ "relationship_delta": 0, // toward the player, applied to the speaker
162
+ "set_flags": {}, // e.g. {"gave_player_the_key":"true"}
163
+ "advance_beat": false, // nudge pacing toward resolution
164
+ "ending": null // or { "kind":"warm|bittersweet|strange", "text":"..." }
165
+ }
166
+ }
167
+ ```
168
+
169
+ `emotion` is required and constrained to an enum (cheap mood→sprite mapping). Every nested object is optional/nullable so simple turns stay tiny. **All of this is grammar-enforced** — `complete_json` cannot return anything that doesn’t parse.
170
+
171
+ ### 4.3 `.md` as a derived view (not the truth)
172
+
173
+ Why both a struct *and* markdown? The struct is robust and code-friendly; the `.md` files are (a) human-readable so you can debug/show the “dream-memory” in the demo, (b) a clean, compact way to inject character/world context back into the prompt, and (c) on-theme. `state.py` renders `GameState` → `world_state.md` + one file per character after each turn, and can parse them back on load. The LLM *reads* `.md`; it does not author the canonical copy. Templates: [`../templates/world_state.md`](../templates/world_state.md), [`../templates/character_sheet.md`](../templates/character_sheet.md).
174
+
175
+ ### 4.4 Context assembly & budget (`memory.py`)
176
+
177
+ Every turn, build the prompt from, in priority order until the budget fills:
178
+
179
+ 1. System prompt (Weaver+Voices role) — fixed.
180
+ 2. `style_guide` + `vibe` — small, fixed.
181
+ 3. `summary` — the rolling compressed history.
182
+ 4. Current `Scene` description + the **present** characters’ sheets only (not the whole cast).
183
+ 5. The last *k* verbatim turns (e.g. k=4–6).
184
+ 6. The player’s new input.
185
+
186
+ Target a conservative budget (e.g. ≤ ~3–4k tokens of context even if the model supports more) — small models degrade as context grows, and it keeps latency down. When `recent_turns` + history would exceed budget, `compact_memory()` asks the LLM to rewrite older turns into 3–5 sentences appended to `summary`, then drops them. This is the literal “Thousand Token Wood” — a small working memory by design.
187
+
188
+ ---
189
+
190
+ ## 5. The Painter (image pipeline)
191
+
192
+ ### 5.1 Model choice & rationale
193
+
194
+ The hard problems are **latency** (must be a few seconds, not 30) and **character consistency** (the same NPC must look the same across scenes). Recommended options, in order:
195
+
196
+ | Option | Params | Steps | Why | Watch out |
197
+ |---|---|---|---|---|
198
+ | **SDXL-Turbo / SDXL-Lightning** (default) | ~3.5B | 1–4 | Mature, permissive, huge **illustration/anime LoRA** ecosystem (perfect VN look), runs on 8–16 GB, very fast. Consistency via pinned seed + fixed appearance string + generate-once. | Weaker prompt adherence than newer models; no built-in image conditioning. |
199
+ | **FLUX.2 Klein** (upgrade) | ~4B | few | Distilled from FLUX.2; **“Kontext” image-conditioning** edits an existing image (“same character, now smiling”, “same scene at dusk”) — *solves consistency directly* and gives mood sprites for free. Fits ~16 GB. | **Check the license** before shipping publicly; slightly heavier. |
200
+ | **Z-Image-Turbo** | ~fits 13–16 GB | turbo | Apache-2.0, fast. Good permissive middle ground. | Smaller ecosystem than SDXL. |
201
+
202
+ Pick **one** art style and bake it into `style_guide` (e.g. “soft watercolor storybook”, “muted ukiyo-e”, “90s anime VN”) so everything coheres. A style LoRA on SDXL is the cheapest way to a distinctive look (also nudges the **Off-Brand** vibe).
203
+
204
+ ### 5.2 Consistency strategy (the crux)
205
+
206
+ - **Generate each character’s base sprite exactly once**, at introduction, and cache it. **Never re-paint an existing character** to “refresh” — that’s what breaks consistency.
207
+ - Store a **pinned `sprite_seed`** and the **stable `appearance` string** in the character record; reuse both for any later generation of that character.
208
+ - For **moods/expressions**: either (a) pre-generate a small set (neutral/happy/sad/surprised) at intro and swap, or (b) if using FLUX.2 Klein, *condition on the base sprite* to edit only the expression. Option (b) is cleaner and cheaper at runtime.
209
+ - For **backdrops**: cache by `scene_id`; revisiting a place reuses its image.
210
+
211
+ ### 5.3 Sprites vs full-scene
212
+
213
+ Two valid looks:
214
+
215
+ 1. **Layered VN (classic):** transparent character sprite over a separate backdrop. Diffusion won’t emit clean alpha, so generate the character on a plain background and run **BiRefNet** (the same matting model in the `gradio.Server` demo) to cut it out → transparent PNG. More moving parts, but the iconic VN look + lets you reuse one backdrop with different sprites.
216
+ 2. **Full-scene (simpler):** generate the character *in* the scene as one image. No compositing, no matting — fewer failure modes, but you can’t cheaply swap sprite vs backdrop independently.
217
+
218
+ Recommend starting **full-scene** in Phase 1 (fast to working), then moving to **layered** in Phase 2 for polish if time allows.
219
+
220
+ ### 5.4 Latency tactics
221
+
222
+ - 1–4 step model only; 512–768px is plenty for a backdrop behind text.
223
+ - **Text first, image second** — the dialogue renders immediately; the UI swaps the image in when the Painter returns (SSE/streaming via the Gradio JS client).
224
+ - **Speculative paint:** while the player reads/types, optionally pre-paint the most likely next backdrop.
225
+ - All Painter calls behind `@spaces.GPU`; keep the pipeline warm (load once at startup).
226
+
227
+ ---
228
+
229
+ ## 6. The Ear (audio / STT)
230
+
231
+ - **Model:** `faster-whisper` (CTranslate2) `small` for the laptop config, `large-v3-turbo` if you have room — player inputs are short, so `small`/`base` transcribe near-instantly. For the *all-ggml local-first* story, `whisper.cpp` pairs thematically with the llama.cpp bonus.
232
+ - **Capture:** in the custom frontend, use the browser `MediaRecorder` API → send the blob to an `@app.api(name="transcribe")` endpoint that runs Whisper. (In the `gr.Blocks` MVP, use `gr.Audio(sources=["microphone"])`.)
233
+ - **Flow:** transcript is shown to the player (so they can confirm/edit) then fed into the turn exactly like typed input. Keep voice optional; typing is the reliable fallback for the demo.
234
+
235
+ ---
236
+
237
+ ## 7. Deployment
238
+
239
+ ### 7.1 Local (where the bonuses live)
240
+
241
+ Run `python app.py`; the LLM via **`llama-cpp-python`** (GGUF, GPU build), diffusion via `diffusers`, Whisper via `faster-whisper`. This is the configuration you record for the **Off-the-Grid (local-first)** and **Llama-Champion (llama.cpp)** badges — show it running with the network off.
242
+
243
+ ### 7.2 Hugging Face Space (the required canvas)
244
+
245
+ The app is a Gradio app (`gradio.Server` *extends* Gradio/FastAPI), so it deploys as a normal Space. For usable image latency, use a **GPU Space**; **ZeroGPU** is free and integrates via the `@spaces.GPU` decorator (functions get a GPU per-call, allocated on demand). Load models at startup; decorate every inference function.
246
+
247
+ **The llama.cpp-on-ZeroGPU tension (decide early).** A CUDA `llama-cpp-python` build can be awkward on Spaces (CUDA runtime mismatches), and ZeroGPU’s per-call GPU model doesn’t love long-lived native processes. Two clean resolutions:
248
+
249
+ - **A (single stack):** get a working CUDA `llama-cpp-python` wheel/build for the Space (keeps llama.cpp everywhere). Test this on day 1, not at the deadline.
250
+ - **B (split stack, recommended for safety):** llama.cpp **locally** (claims the llama.cpp badge in the video) + a `transformers` code path **on the Space** under `@spaces.GPU`. Same `llm.py` interface, two backends behind a flag.
251
+
252
+ ### 7.3 Persistence
253
+
254
+ The Space filesystem is **ephemeral**. The `.md` dream-memory therefore lives **per session** (perfectly fine for a one-sitting game). If you want playthroughs to survive restarts, write them to **HF persistent storage** or push traces to a **Dataset** (which also feeds the **Open-Trace** badge — see §9.3).
255
+
256
+ ### 7.4 `gradio.Server` specifics
257
+
258
+ - `app = Server()` (a FastAPI subclass). `@app.get("/")` serves `frontend/index.html`. `@app.api(name="...")` defines queued, ZeroGPU-aware, `gradio_client`-callable endpoints (use these for `direct_turn`, `paint`, `transcribe`). `app.launch()` to run.
259
+ - The frontend talks to the backend through the **Gradio JS client** (`Client.connect(window.location.origin)` → `client.predict("/direct_turn", {...})`) so calls go through Gradio’s queue/concurrency (and you can show progress), **not** raw `fetch`.
260
+
261
+ ---
262
+
263
+ ## 8. UI architecture (Off-Brand badge)
264
+
265
+ ### 8.1 Target: a real visual-novel frame
266
+
267
+ A custom `frontend/index.html` (vanilla HTML/CSS/JS — no build step needed; the hackathon’s own `gradio.Server` demo ships a ~1300-line single file) rendering three CSS-stacked layers:
268
+
269
+ ```
270
+ z-0 backdrop (full-bleed CSS background-image)
271
+ z-1 sprite (transparent PNG, positioned, with a gentle entrance + mood cross-fade)
272
+ z-2 dialogue (named speaker box at the bottom, text typed in character-by-character)
273
+ + input row: text field, 🎙️ mic button, "wait/continue" affordance
274
+ ```
275
+
276
+ Niceties that sell delight cheaply: typewriter text reveal, soft sprite slide-in, backdrop cross-fade on scene change, a subtle paper/parchment vignette, a loading shimmer while the Painter works (“the wood is dreaming…”). Keep a small palette + one display font to look intentional.
277
+
278
+ ### 8.2 MVP fallback
279
+
280
+ Phase 0/1 can use plain `gr.Blocks`: `gr.Image` for the scene, `gr.Chatbot`/`gr.Markdown` for dialogue, `gr.Textbox` + `gr.Audio(microphone)` for input. Gate it behind `GRADIO_MVP_UI=1`. This de-risks the loop before you invest in the custom frontend.
281
+
282
+ ### 8.3 Wiring
283
+
284
+ Frontend ⇄ backend via the Gradio JS client to `@app.api` endpoints (`/start`, `/direct_turn`, `/transcribe`). The backend returns `{ speaker, dialogue, emotion, scene_image_url, sprite_image_url }`; the frontend animates the rest.
285
+
286
+ ---
287
+
288
+ ## 9. Optional badge tracks
289
+
290
+ ### 9.1 Well-Tuned (fine-tune) 🟡
291
+
292
+ Fine-tune the shared LLM (LoRA on Qwen3-4B/8B) to (a) reliably emit the directive schema and (b) carry the “dreaming wood” narrative voice. Dataset: ~200–800 synthetic `(context → directive-JSON + dialogue)` examples — bootstrap them with a larger model or hand-write seeds, then expand. Train with the standard PEFT/LoRA stack; merge or keep the adapter; convert to **GGUF** and publish on the Hub (this is what the badge checks). Even a small fine-tune that locks the output format + tone is a real win and reduces grammar-fighting at runtime. Time-box it — the MVP must not depend on it.
293
+
294
+ ### 9.2 Field Notes (blog) 🟡
295
+
296
+ A short write-up: the diegetic conceit, the one-call director pattern, grammar-constrained directives, the consistency-via-cache trick, and the llama.cpp/ZeroGPU lesson. Cheap points, and genuinely useful to others.
297
+
298
+ ### 9.3 Open Trace 🟡
299
+
300
+ Log every orchestration step per turn — the assembled context, the raw directive JSON, the Painter prompts/seeds — to `runs/*.jsonl`, then push a cleaned sample as a **Hub dataset**. The struct-based state makes these traces clean and shareable.
301
+
302
+ ---
303
+
304
+ ## 10. Phased plan
305
+
306
+ Build window **June 5–15**. (Register by **June 3**; sketch + download weights before the 5th.) Days are indicative for a two-person team.
307
+
308
+ ### Phase 0 — Skeleton (Day 1–2)
309
+ - `state.py`: `GameState` + directive schema; `.md` render/parse round-trip with a unit test.
310
+ - `llm.py`: `complete()` + `complete_json()` with **GBNF grammar** (start with `transformers` *or* llama.cpp — whichever you get running first).
311
+ - `orchestrator.direct_turn()` returning valid directive JSON for a hard-coded scene.
312
+ - Text-only loop in `gr.Blocks`. **Milestone:** type a line → NPC replies → state updates, looping, no images.
313
+
314
+ ### Phase 1 — The wood breathes (Day 3–5)
315
+ - `painter.py`: full-scene generation with SDXL-Turbo; disk cache; pinned seeds.
316
+ - `orchestrator.init_world()`: generate setting + first NPC + opening.
317
+ - Wire scene/character directives → Painter. **Milestone:** a playable illustrated loop, basic VN layout in `gr.Blocks`.
318
+
319
+ ### Phase 2 — Voice + polish (Day 6–8)
320
+ - `stt.py` + mic input.
321
+ - Migrate to `gradio.Server` + custom `frontend/index.html` (layered scene, typewriter, animations).
322
+ - `memory.compact_memory()`; sprite moods (pre-gen set or FLUX.2-Klein conditioning); optional BiRefNet layered sprites. **Milestone:** speak to a self-painting wood in a bespoke UI.
323
+
324
+ ### Phase 3 — Bonuses + ship (Day 9–10)
325
+ - Lock the llama.cpp local config; resolve the Space backend (A or B from §7.2).
326
+ - (Optional) fine-tune + GGUF on the Hub; (optional) trace dataset.
327
+ - **Record the demo video + write the social post** (+ optional blog). Deploy the Space, test cold-start, freeze. **Milestone:** submitted.
328
+
329
+ > Cut lines if time runs short, in this order: fine-tune → layered sprites → voice → custom frontend. The loop + a custom-ish UI + working art is a complete, competitive entry.
330
+
331
+ ---
332
+
333
+ ## 11. Risks & mitigations
334
+
335
+ | Risk | Likelihood | Impact | Mitigation |
336
+ |---|---|---|---|
337
+ | Image latency makes it feel sluggish | High | High | 1–4-step model; text-first; cache; speculative paint; 512–768px. |
338
+ | Character looks different each scene | High | High | Generate-once + cache; pinned seed + fixed appearance; FLUX.2-Klein conditioning for moods. |
339
+ | llama.cpp won’t build on ZeroGPU | Med | Med | Decide §7.2 on day 1; keep `transformers` fallback behind a flag; claim llama.cpp badge locally. |
340
+ | Small model drifts / over-narrates | Med | Med | Grammar-enforced directives; low temp on structure; rolling-summary memory; lean on the diegetic framing. |
341
+ | Scope creep (combat, save slots, 5 NPCs) | Med | High | Honor the “out of scope” list in `CLAUDE.md`; ship the loop. |
342
+ | Weights/licensing surprise (esp. FLUX.2) | Low | Med | Verify licenses before shipping; default to SDXL-Turbo/Z-Image (permissive). |
343
+ | Demo video/social post left to the last hour | Med | High | They’re *required*. Schedule them in Phase 3, not after. |
344
+
345
+ ---
346
+
347
+ ## 12. Latency budget (per turn, target)
348
+
349
+ | Stage | Target | Notes |
350
+ |---|---|---|
351
+ | STT (if voice) | < 1 s | short utterances, `small`/turbo |
352
+ | Context assembly | negligible | pure Python |
353
+ | LLM directive call | 1–4 s | ~8B Q4, ≤4k context, one call |
354
+ | Apply + memory | negligible | |
355
+ | Image (only when changed) | 1–5 s | 1–4-step model; *hidden behind text* and often cached |
356
+ | **Felt latency** | **dialogue in ~2–4 s**, image fills in after | most turns don’t change the scene |
357
+
358
+ ---
359
+
360
+ ## 13. Decisions to lock before Day 1
361
+
362
+ 1. **Project name** (Thousand Token Wood is a placeholder).
363
+ 2. **Art style** for the `style_guide` (and whether to use a style LoRA).
364
+ 3. **Image model**: SDXL-Turbo (safe) vs FLUX.2 Klein (consistency, check license).
365
+ 4. **Sprites**: full-scene first vs layered+BiRefNet.
366
+ 5. **Space backend**: §7.2 option A vs B.
367
+ 6. **Whisper size** (small vs turbo) and whether voice ships in v1.
368
+ 7. **Fine-tune**: in or out (time-box).
docs/PROMPTS.md ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Thousand Token Wood — Prompts, Schema & Grammar
2
+
3
+ Copy-paste-ready building blocks for the LLM roles. Keep prompts versioned here (and/or in `visualnovel/prompts.py`); don’t scatter literals across modules. See [`ARCHITECTURE.md`](ARCHITECTURE.md) §2–4 for how they’re used.
4
+
5
+ > These are **starting points** — iterate against your chosen model. Qwen3 responds well to terse, rule-style system prompts and supports a “thinking” mode you can enable for the Weaver’s planning.
6
+
7
+ ---
8
+
9
+ ## 1. Director system prompt (the per-turn Weaver + Voices call)
10
+
11
+ ```
12
+ You are the dreaming mind of Thousand Token Wood — a small, whimsical, slightly forgetful
13
+ imagination that conjures a story around a wanderer (the player) as they speak.
14
+
15
+ You play TWO jobs at once:
16
+ • THE VOICES — you speak AS the wood's spirits (the present characters), each in their own
17
+ voice. Stay fully in character. Never narrate as an author. Never mention being an AI,
18
+ a model, or a game.
19
+ • THE WEAVER — you quietly decide what changes in the world this turn (a new place, a new
20
+ spirit arriving, someone leaving, a shift in feeling, the story drawing to a close).
21
+
22
+ This turn:
23
+ • Read the world, the present spirits' sheets, the recent exchange, and the player's words.
24
+ • Reply as ONE present spirit (the one addressed, or whoever would naturally answer). Keep it
25
+ to 1–3 sentences. Make it vivid, kind to the player's imagination, and a little dreamlike.
26
+ • Then choose the directives that reflect what just changed. Change as LITTLE as possible —
27
+ only what the moment truly calls for. Most turns change nothing structural.
28
+
29
+ Rules:
30
+ • Honor the world's tone and the spirits' established traits, voices, and appearance. A spirit
31
+ only knows what it could know.
32
+ • If the player goes somewhere new, set scene_change. If they meet someone new, set
33
+ new_character (give a vivid one_line, a STABLE appearance, a voice, a couple of traits, a
34
+ goal). Keep at most ~3 spirits on stage.
35
+ • Let warmth and friction accumulate: nudge relationship_delta for the speaker.
36
+ • The wood is small and forgetful — if you're unsure of a detail, dream a charming new one
37
+ rather than contradicting an established fact.
38
+ • Output MUST be a single JSON object matching the schema. Nothing else.
39
+ ```
40
+
41
+ > The model **need not “write” JSON reliably** — you enforce it with the schema/grammar in §4. The prompt just tells it what each field *means*.
42
+
43
+ ---
44
+
45
+ ## 2. World-init prompt (`init_world`)
46
+
47
+ ```
48
+ Dream the opening of a short interactive tale set in Thousand Token Wood.
49
+
50
+ Player's chosen vibe: {vibe} (e.g. cozy folktale / eerie / absurd / melancholy)
51
+
52
+ Produce:
53
+ • style_guide: 2–3 sentences fixing the WORLD'S LOOK and TONE so everything stays coherent
54
+ (art style, palette, mood, the kind of language spirits use). This will rarely change.
55
+ • opening scene: a place (short name + a vivid one-paragraph description + a mood).
56
+ • first spirit: the first character the wanderer meets — id, name, a delightful one_line, a
57
+ STABLE appearance description (used for every picture of them), a voice, 2–3 traits, a goal.
58
+ • opening line: this spirit's first words to the wanderer (1–3 sentences, fully in voice).
59
+
60
+ Make it inviting and a little strange. Output a single JSON object matching the init schema.
61
+ ```
62
+
63
+ (Use a sibling JSON schema for init — same `Character`/`Scene` shapes as the directive schema, plus `style_guide` and `opening_line`.)
64
+
65
+ ---
66
+
67
+ ## 3. Memory-compaction prompt (`compact_memory`)
68
+
69
+ ```
70
+ Here is the running summary of the tale so far, then the most recent exchanges.
71
+ Rewrite them into ONE updated summary of 3–6 sentences. Keep only what matters for continuity:
72
+ who the wanderer has met, promises made, places visited, shifts in feeling, unresolved threads.
73
+ Drop small talk and exact wording. Write it as a calm narrator's memory. Plain prose, no lists.
74
+
75
+ SUMMARY SO FAR:
76
+ {summary}
77
+
78
+ RECENT EXCHANGES:
79
+ {recent_turns}
80
+ ```
81
+
82
+ ---
83
+
84
+ ## 4. Constraining the output
85
+
86
+ ### 4.1 Recommended: JSON Schema (let `llama-cpp-python` convert it)
87
+
88
+ The practical path — pass the schema and let the runtime build the grammar for you:
89
+
90
+ ```python
91
+ # llama-cpp-python
92
+ out = llm.create_chat_completion(
93
+ messages=[{"role": "system", "content": DIRECTOR_PROMPT},
94
+ {"role": "user", "content": assembled_context}],
95
+ response_format={"type": "json_object", "schema": DIRECTIVE_SCHEMA},
96
+ temperature=0.7, top_p=0.9, max_tokens=512,
97
+ )
98
+ ```
99
+
100
+ `DIRECTIVE_SCHEMA`:
101
+
102
+ ```json
103
+ {
104
+ "type": "object",
105
+ "additionalProperties": false,
106
+ "required": ["speaker", "dialogue", "emotion", "directives"],
107
+ "properties": {
108
+ "speaker": { "type": "string" },
109
+ "dialogue": { "type": "string" },
110
+ "emotion": { "type": "string",
111
+ "enum": ["neutral","joy","fear","anger","sad","surprise","tender"] },
112
+ "directives": {
113
+ "type": "object",
114
+ "additionalProperties": false,
115
+ "required": ["relationship_delta","advance_beat"],
116
+ "properties": {
117
+ "scene_change": {
118
+ "type": ["object","null"],
119
+ "additionalProperties": false,
120
+ "required": ["place","description","mood"],
121
+ "properties": {
122
+ "place": {"type":"string"},
123
+ "description": {"type":"string"},
124
+ "mood": {"type":"string"}
125
+ }
126
+ },
127
+ "new_character": {
128
+ "type": ["object","null"],
129
+ "additionalProperties": false,
130
+ "required": ["id","name","one_line","appearance","voice","traits","goals"],
131
+ "properties": {
132
+ "id": {"type":"string"},
133
+ "name": {"type":"string"},
134
+ "one_line": {"type":"string"},
135
+ "appearance": {"type":"string"},
136
+ "voice": {"type":"string"},
137
+ "traits": {"type":"array","items":{"type":"string"}},
138
+ "goals": {"type":"string"}
139
+ }
140
+ },
141
+ "exit_character": { "type": ["string","null"] },
142
+ "relationship_delta": { "type": "integer" },
143
+ "set_flags": { "type": "object", "additionalProperties": {"type":"string"} },
144
+ "advance_beat": { "type": "boolean" },
145
+ "ending": {
146
+ "type": ["object","null"],
147
+ "additionalProperties": false,
148
+ "required": ["kind","text"],
149
+ "properties": {
150
+ "kind": {"type":"string","enum":["warm","bittersweet","strange"]},
151
+ "text": {"type":"string"}
152
+ }
153
+ }
154
+ }
155
+ }
156
+ }
157
+ }
158
+ ```
159
+
160
+ > Numeric *ranges* (e.g. `relationship_delta` ∈ [-100,100]) aren’t enforced by grammar — **clamp them in `state.py`** when applying. Same for unknown `speaker`/`exit_character` ids: validate against present characters and ignore/repair if invalid.
161
+
162
+ ### 4.2 Advanced: hand-written GBNF (raw `llama.cpp` / full control)
163
+
164
+ Equivalent grammar if you drive `llama.cpp` directly (e.g. `--grammar-file`). Tweak to your build if needed.
165
+
166
+ ```gbnf
167
+ root ::= ws "{" ws
168
+ "\"speaker\"" ws ":" ws string ws "," ws
169
+ "\"dialogue\"" ws ":" ws string ws "," ws
170
+ "\"emotion\"" ws ":" ws emotion ws "," ws
171
+ "\"directives\"" ws ":" ws directives ws
172
+ "}" ws
173
+
174
+ directives ::= "{" ws
175
+ "\"scene_change\"" ws ":" ws (scene | "null") ws "," ws
176
+ "\"new_character\"" ws ":" ws (character | "null") ws "," ws
177
+ "\"exit_character\"" ws ":" ws (string | "null") ws "," ws
178
+ "\"relationship_delta\"" ws ":" ws integer ws "," ws
179
+ "\"set_flags\"" ws ":" ws flagobj ws "," ws
180
+ "\"advance_beat\"" ws ":" ws boolean ws "," ws
181
+ "\"ending\"" ws ":" ws (ending | "null") ws
182
+ "}"
183
+
184
+ scene ::= "{" ws
185
+ "\"place\"" ws ":" ws string ws "," ws
186
+ "\"description\"" ws ":" ws string ws "," ws
187
+ "\"mood\"" ws ":" ws string ws "}"
188
+
189
+ character ::= "{" ws
190
+ "\"id\"" ws ":" ws string ws "," ws
191
+ "\"name\"" ws ":" ws string ws "," ws
192
+ "\"one_line\"" ws ":" ws string ws "," ws
193
+ "\"appearance\"" ws ":" ws string ws "," ws
194
+ "\"voice\"" ws ":" ws string ws "," ws
195
+ "\"traits\"" ws ":" ws strlist ws "," ws
196
+ "\"goals\"" ws ":" ws string ws "}"
197
+
198
+ ending ::= "{" ws
199
+ "\"kind\"" ws ":" ws ("\"warm\"" | "\"bittersweet\"" | "\"strange\"") ws "," ws
200
+ "\"text\"" ws ":" ws string ws "}"
201
+
202
+ emotion ::= "\"neutral\"" | "\"joy\"" | "\"fear\"" | "\"anger\"" | "\"sad\"" | "\"surprise\"" | "\"tender\""
203
+
204
+ flagobj ::= "{" ws ( flagpair ( ws "," ws flagpair )* ws )? "}"
205
+ flagpair ::= string ws ":" ws string
206
+ strlist ::= "[" ws ( string ( ws "," ws string )* ws )? "]"
207
+
208
+ string ::= "\"" ( [^"\\] | "\\" (["\\/bfnrt] | "u" hex hex hex hex) )* "\""
209
+ integer ::= "-"? ("0" | [1-9] [0-9]*)
210
+ boolean ::= "true" | "false"
211
+ hex ::= [0-9a-fA-F]
212
+ ws ::= [ \t\n]*
213
+ ```
214
+
215
+ ---
216
+
217
+ ## 5. Image-prompt composition (the Painter)
218
+
219
+ Don’t ask the LLM to “write a Stable Diffusion prompt” from scratch — **compose it in code** from fields you already trust, so the art style stays locked:
220
+
221
+ ```python
222
+ def backdrop_prompt(state, scene):
223
+ return f"{state.style_guide}, {scene.description}, {scene.mood} atmosphere, " \
224
+ f"background scenery, no characters, no text"
225
+
226
+ def sprite_prompt(state, ch, mood):
227
+ return f"{state.style_guide}, full-body character, {ch.appearance}, " \
228
+ f"{mood} expression, plain neutral background, no text"
229
+ # negative (SDXL): "text, watermark, lowres, deformed hands, extra limbs, multiple characters"
230
+ # pin seed = ch.sprite_seed (sprite) / scene.backdrop_seed (backdrop) for consistency
231
+ ```
232
+
233
+ For **mood swaps** with FLUX.2 Klein, condition on the cached base sprite instead of regenerating:
234
+ “*the same character, now {mood} — keep identity, outfit, and style identical*.”
235
+
236
+ ---
237
+
238
+ ## 6. Sampling guidance
239
+
240
+ | Call | temp | top_p | notes |
241
+ |---|---|---|---|
242
+ | Director (dialogue+directives) | 0.7 | 0.9 | grammar-constrained; warm but on-rails. If voices feel flat, raise temp slightly. |
243
+ | World init | 0.9 | 0.95 | want surprise and texture here |
244
+ | Memory compaction | 0.3 | 0.9 | want faithful, terse summary |
245
+ | Image-prompt | — | — | composed in code, no sampling |
246
+
247
+ Add a light `repeat_penalty` (~1.05–1.1) to fight the “AI slop” repetition small models drift into. Keep `max_tokens` tight (≈512) for the director call — it should be short.
frontend/debug.html ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>VN Debug Dashboard</title>
7
+ <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.6/dist/chart.umd.min.js"></script>
8
+ <style>
9
+ :root {
10
+ --bg: #0f1117;
11
+ --surface: #1a1d27;
12
+ --border: #252836;
13
+ --text: #dde1f0;
14
+ --muted: #6e7891;
15
+ --blue: #4c9be8;
16
+ --red: #e05c5c;
17
+ --green: #56b87a;
18
+ --yellow: #e0a840;
19
+ --orange: #e09440;
20
+ --purple: #b07de8;
21
+ --gray: #4e5568;
22
+ }
23
+ * { box-sizing: border-box; margin: 0; padding: 0; }
24
+ body {
25
+ background: var(--bg);
26
+ color: var(--text);
27
+ font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
28
+ font-size: 13px;
29
+ padding: 16px;
30
+ min-height: 100vh;
31
+ }
32
+
33
+ /* ── Header ─────────────────────────────────────────────────── */
34
+ header {
35
+ display: flex;
36
+ align-items: center;
37
+ justify-content: space-between;
38
+ margin-bottom: 16px;
39
+ }
40
+ header h1 {
41
+ font-size: 17px;
42
+ font-weight: 700;
43
+ letter-spacing: -.02em;
44
+ }
45
+ header h1 span { color: var(--blue); }
46
+ .status {
47
+ display: flex;
48
+ align-items: center;
49
+ gap: 7px;
50
+ font-size: 12px;
51
+ color: var(--muted);
52
+ }
53
+ .dot {
54
+ width: 8px; height: 8px;
55
+ border-radius: 50%;
56
+ background: var(--gray);
57
+ flex-shrink: 0;
58
+ transition: background 0.3s;
59
+ }
60
+ .dot.live { background: var(--green); box-shadow: 0 0 6px var(--green); }
61
+ .dot.error { background: var(--red); }
62
+
63
+ /* ── KPI cards ──────────────────────────────────────────────── */
64
+ .kpi-grid {
65
+ display: grid;
66
+ grid-template-columns: repeat(4, 1fr);
67
+ gap: 10px;
68
+ margin-bottom: 12px;
69
+ }
70
+ @media (max-width: 800px) { .kpi-grid { grid-template-columns: repeat(2, 1fr); } }
71
+ .kpi {
72
+ background: var(--surface);
73
+ border: 1px solid var(--border);
74
+ border-radius: 8px;
75
+ padding: 12px 14px;
76
+ }
77
+ .kpi-label {
78
+ font-size: 10px;
79
+ font-weight: 600;
80
+ text-transform: uppercase;
81
+ letter-spacing: .07em;
82
+ color: var(--muted);
83
+ margin-bottom: 5px;
84
+ }
85
+ .kpi-value {
86
+ font-size: 28px;
87
+ font-weight: 800;
88
+ line-height: 1;
89
+ font-variant-numeric: tabular-nums;
90
+ color: var(--text);
91
+ }
92
+ .kpi-sub {
93
+ font-size: 11px;
94
+ color: var(--muted);
95
+ margin-top: 5px;
96
+ }
97
+ .c-blue { color: var(--blue) !important; }
98
+ .c-green { color: var(--green) !important; }
99
+ .c-yellow { color: var(--yellow) !important; }
100
+ .c-red { color: var(--red) !important; }
101
+
102
+ /* ── Charts ──────────────────────────────────────────────────── */
103
+ .charts-grid {
104
+ display: grid;
105
+ grid-template-columns: 1fr 1fr;
106
+ gap: 10px;
107
+ margin-bottom: 12px;
108
+ }
109
+ @media (max-width: 900px) { .charts-grid { grid-template-columns: 1fr; } }
110
+ .card {
111
+ background: var(--surface);
112
+ border: 1px solid var(--border);
113
+ border-radius: 8px;
114
+ padding: 14px;
115
+ }
116
+ .card h2 {
117
+ font-size: 10px;
118
+ font-weight: 700;
119
+ text-transform: uppercase;
120
+ letter-spacing: .07em;
121
+ color: var(--muted);
122
+ margin-bottom: 10px;
123
+ }
124
+
125
+ /* ── Operations table ────────────────────────────────────────── */
126
+ table {
127
+ width: 100%;
128
+ border-collapse: collapse;
129
+ font-size: 12px;
130
+ }
131
+ th {
132
+ text-align: right;
133
+ font-size: 10px;
134
+ font-weight: 700;
135
+ text-transform: uppercase;
136
+ letter-spacing: .05em;
137
+ color: var(--muted);
138
+ padding: 0 8px 8px;
139
+ border-bottom: 1px solid var(--border);
140
+ }
141
+ th:first-child { text-align: left; }
142
+ td {
143
+ padding: 6px 8px;
144
+ border-bottom: 1px solid var(--border);
145
+ text-align: right;
146
+ font-variant-numeric: tabular-nums;
147
+ color: var(--text);
148
+ }
149
+ td:first-child { text-align: left; color: var(--muted); }
150
+ tr:last-child td { border-bottom: none; }
151
+ tr:hover td { background: rgba(255,255,255,.025); }
152
+ .total-row td { font-weight: 700; color: var(--text) !important; }
153
+
154
+ /* ── Actions ─────────────────────────────────────────────────── */
155
+ .actions {
156
+ display: flex;
157
+ align-items: center;
158
+ gap: 10px;
159
+ margin-top: 12px;
160
+ }
161
+ button {
162
+ background: var(--blue);
163
+ color: #fff;
164
+ border: none;
165
+ border-radius: 6px;
166
+ padding: 7px 14px;
167
+ font-size: 12px;
168
+ font-weight: 700;
169
+ cursor: pointer;
170
+ opacity: 1;
171
+ transition: opacity .15s;
172
+ }
173
+ button:hover:not(:disabled) { opacity: .82; }
174
+ button:disabled { opacity: .35; cursor: default; }
175
+ #report-msg { font-size: 12px; color: var(--green); }
176
+ </style>
177
+ </head>
178
+ <body>
179
+
180
+ <!-- ── Header ─────────────────────────────────────────────────────── -->
181
+ <header>
182
+ <h1>VN <span>Debug</span> Dashboard</h1>
183
+ <div class="status">
184
+ <div class="dot" id="dot"></div>
185
+ <span id="status-text">Connecting…</span>
186
+ </div>
187
+ </header>
188
+
189
+ <!-- ── KPI cards ──────────────────────────────────────────────────── -->
190
+ <div class="kpi-grid">
191
+ <div class="kpi">
192
+ <div class="kpi-label">Turns</div>
193
+ <div class="kpi-value c-blue" id="kpi-turns">—</div>
194
+ <div class="kpi-sub">completed</div>
195
+ </div>
196
+ <div class="kpi">
197
+ <div class="kpi-label">LLM avg</div>
198
+ <div class="kpi-value" id="kpi-llm">—</div>
199
+ <div class="kpi-sub" id="kpi-llm-sub">p95 —</div>
200
+ </div>
201
+ <div class="kpi">
202
+ <div class="kpi-label">Image cache</div>
203
+ <div class="kpi-value" id="kpi-cache">—</div>
204
+ <div class="kpi-sub" id="kpi-cache-sub">hits / total</div>
205
+ </div>
206
+ <div class="kpi">
207
+ <div class="kpi-label">Session</div>
208
+ <div class="kpi-value c-blue" id="kpi-elapsed">—</div>
209
+ <div class="kpi-sub" id="kpi-gpu">—</div>
210
+ </div>
211
+ </div>
212
+
213
+ <!-- ── Charts ─────────────────────────────────────────────────────── -->
214
+ <div class="charts-grid">
215
+ <div class="card">
216
+ <h2>System Resources — last 2 min</h2>
217
+ <canvas id="res-chart" height="170"></canvas>
218
+ </div>
219
+ <div class="card">
220
+ <h2>Latency per Turn (ms, stacked)</h2>
221
+ <canvas id="lat-chart" height="170"></canvas>
222
+ </div>
223
+ </div>
224
+
225
+ <!-- ── Operations table ───────────────────────────────────────────── -->
226
+ <div class="card">
227
+ <h2>Operations</h2>
228
+ <table>
229
+ <thead>
230
+ <tr>
231
+ <th>Operation</th>
232
+ <th>n</th>
233
+ <th>avg ms</th>
234
+ <th>p95 ms</th>
235
+ <th>max ms</th>
236
+ </tr>
237
+ </thead>
238
+ <tbody id="ops-body"></tbody>
239
+ </table>
240
+ </div>
241
+
242
+ <!-- ── Actions ────────────────────────────────────────────────────── -->
243
+ <div class="actions">
244
+ <button id="save-btn" onclick="saveReport()">Save report now</button>
245
+ <span id="report-msg"></span>
246
+ </div>
247
+
248
+ <script>
249
+ // ── Chart defaults ───────────────────────────────────────────────────────
250
+ Chart.defaults.color = '#6e7891';
251
+ Chart.defaults.borderColor = '#252836';
252
+ Chart.defaults.font.size = 10;
253
+
254
+ const GRID_COLOR = 'rgba(255,255,255,.04)';
255
+ const BASE_SCALES = {
256
+ x: { ticks: { color: '#555', maxTicksLimit: 8 }, grid: { color: GRID_COLOR } },
257
+ y: { ticks: { color: '#555' }, grid: { color: GRID_COLOR } },
258
+ };
259
+
260
+ // ── Resource chart (line) ────────────────────────────────────────────────
261
+ const resCtx = document.getElementById('res-chart').getContext('2d');
262
+ const resChart = new Chart(resCtx, {
263
+ type: 'line',
264
+ data: {
265
+ labels: [],
266
+ datasets: [
267
+ {
268
+ label: 'RAM %', yAxisID: 'yPct', data: [],
269
+ borderColor: '#4c9be8', backgroundColor: 'rgba(76,155,232,.06)',
270
+ borderWidth: 1.5, pointRadius: 0, fill: true, tension: 0.3,
271
+ },
272
+ {
273
+ label: 'CPU %', yAxisID: 'yPct', data: [],
274
+ borderColor: '#e05c5c', backgroundColor: 'rgba(224,92,92,.05)',
275
+ borderWidth: 1.5, pointRadius: 0, fill: true, tension: 0.3,
276
+ },
277
+ {
278
+ label: 'VRAM', yAxisID: 'yVram', data: [],
279
+ borderColor: '#e09440', backgroundColor: 'rgba(224,148,64,.05)',
280
+ borderWidth: 1.5, pointRadius: 0, fill: false, tension: 0.3,
281
+ },
282
+ ]
283
+ },
284
+ options: {
285
+ animation: false,
286
+ responsive: true,
287
+ interaction: { mode: 'index', intersect: false },
288
+ plugins: {
289
+ legend: { labels: { color: '#888', boxWidth: 10, font: { size: 10 } } },
290
+ },
291
+ scales: {
292
+ x: BASE_SCALES.x,
293
+ yPct: {
294
+ type: 'linear', position: 'left', min: 0, suggestedMax: 100,
295
+ ticks: { color: '#555', callback: v => v + '%' },
296
+ grid: { color: GRID_COLOR },
297
+ },
298
+ yVram: {
299
+ type: 'linear', position: 'right', min: 0,
300
+ ticks: { color: '#7a6040' },
301
+ grid: { drawOnChartArea: false },
302
+ display: false, // shown only when VRAM data present
303
+ },
304
+ },
305
+ },
306
+ });
307
+
308
+ // ── Latency stacked bar ──────────────────────────────────────────────────
309
+ const latCtx = document.getElementById('lat-chart').getContext('2d');
310
+ const latChart = new Chart(latCtx, {
311
+ type: 'bar',
312
+ data: {
313
+ labels: [],
314
+ datasets: [
315
+ { label: 'LLM', data: [], backgroundColor: '#4c9be8', stack: 's' },
316
+ { label: 'Painter', data: [], backgroundColor: '#56b87a', stack: 's' },
317
+ { label: 'STT', data: [], backgroundColor: '#b07de8', stack: 's' },
318
+ { label: 'Compact', data: [], backgroundColor: '#e09440', stack: 's' },
319
+ { label: 'Other', data: [], backgroundColor: '#4e5568', stack: 's' },
320
+ ]
321
+ },
322
+ options: {
323
+ animation: false,
324
+ responsive: true,
325
+ plugins: {
326
+ legend: { labels: { color: '#888', boxWidth: 10, font: { size: 10 } } },
327
+ tooltip: { callbacks: { label: ctx => ` ${ctx.dataset.label}: ${Math.round(ctx.raw)} ms` } },
328
+ },
329
+ scales: {
330
+ x: { ...BASE_SCALES.x, stacked: true },
331
+ y: {
332
+ ...BASE_SCALES.y, stacked: true,
333
+ title: { display: true, text: 'ms', color: '#555', font: { size: 10 } },
334
+ },
335
+ },
336
+ },
337
+ });
338
+
339
+ // ── Helpers ──────────────────────────────────────────────────────────────
340
+ function fmtMs(ms) {
341
+ if (ms == null) return '—';
342
+ return ms >= 1000 ? (ms / 1000).toFixed(1) + 's' : Math.round(ms) + 'ms';
343
+ }
344
+ function fmtElapsed(s) {
345
+ if (s == null) return '—';
346
+ const m = Math.floor(s / 60), sec = Math.floor(s % 60);
347
+ return m > 0 ? `${m}m ${sec}s` : `${sec}s`;
348
+ }
349
+ function fmtTime(ts) {
350
+ const d = new Date(ts * 1000);
351
+ return d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');
352
+ }
353
+ function latencyClass(ms) {
354
+ if (ms == null) return '';
355
+ if (ms < 2000) return 'c-green';
356
+ if (ms < 6000) return 'c-yellow';
357
+ return 'c-red';
358
+ }
359
+ function cacheClass(rate) {
360
+ if (rate == null) return '';
361
+ if (rate >= 0.7) return 'c-green';
362
+ if (rate >= 0.4) return 'c-yellow';
363
+ return 'c-red';
364
+ }
365
+
366
+ const GPU_LABELS = { nvml: 'NVIDIA GPU', rocm: 'AMD ROCm', mps: 'Apple MPS (unified)' };
367
+
368
+ const OP_ORDER = [
369
+ 'total_turn', 'llm_direct', 'compact_memory', 'context_assembly',
370
+ 'apply_directives', 'save_memory', 'painter_backdrop', 'painter_sprite', 'stt',
371
+ ];
372
+ const OP_NAMES = {
373
+ total_turn: 'Turn total',
374
+ llm_direct: 'LLM direct_turn',
375
+ compact_memory: 'Compact memory (LLM)',
376
+ context_assembly: 'Context assembly',
377
+ apply_directives: 'apply_directives',
378
+ save_memory: 'save_memory',
379
+ painter_backdrop: 'Painter — backdrop',
380
+ painter_sprite: 'Painter — sprite',
381
+ stt: 'STT transcribe',
382
+ };
383
+
384
+ // ── Main update ──────────────────────────────────────────────────────────
385
+ function update(data) {
386
+ // KPI: turns
387
+ document.getElementById('kpi-turns').textContent = data.turns_completed ?? '—';
388
+
389
+ // KPI: LLM
390
+ const llm = data.ops?.llm_direct;
391
+ const kpiLlm = document.getElementById('kpi-llm');
392
+ kpiLlm.textContent = fmtMs(llm?.avg_ms);
393
+ kpiLlm.className = 'kpi-value ' + latencyClass(llm?.avg_ms);
394
+ document.getElementById('kpi-llm-sub').textContent =
395
+ llm ? `p95 ${fmtMs(llm.p95_ms)} · max ${fmtMs(llm.max_ms)}` : 'no data yet';
396
+
397
+ // KPI: cache
398
+ const rate = data.cache_hit_rate;
399
+ const kpiCache = document.getElementById('kpi-cache');
400
+ kpiCache.textContent = rate != null ? Math.round(rate * 100) + '%' : '—';
401
+ kpiCache.className = 'kpi-value ' + cacheClass(rate);
402
+ const tot = (data.cache_hits ?? 0) + (data.cache_misses ?? 0);
403
+ document.getElementById('kpi-cache-sub').textContent =
404
+ tot > 0 ? `${data.cache_hits} hits / ${tot} total` : 'no renders yet';
405
+
406
+ // KPI: elapsed + GPU backend
407
+ document.getElementById('kpi-elapsed').textContent = fmtElapsed(data.session_elapsed_s);
408
+ document.getElementById('kpi-gpu').textContent =
409
+ data.gpu_backend ? (GPU_LABELS[data.gpu_backend] ?? data.gpu_backend) : 'No GPU detected';
410
+
411
+ // Resource chart
412
+ const samples = data.samples ?? [];
413
+ resChart.data.labels = samples.map(s => fmtTime(s.ts));
414
+ resChart.data.datasets[0].data = samples.map(s => s.ram_pct ?? null);
415
+ resChart.data.datasets[1].data = samples.map(s => s.cpu_pct ?? null);
416
+
417
+ const hasVram = samples.some(s => s.vram_mb != null);
418
+ if (hasVram) {
419
+ // For nvml/rocm: use vram_pct on left axis if available.
420
+ // For MPS (unified): express process RSS as % of total system RAM (ram_mb / ram_pct * 100).
421
+ resChart.data.datasets[2].data = samples.map(s => {
422
+ if (s.vram_mb == null) return null;
423
+ if (s.vram_pct != null) return s.vram_pct; // nvml / rocm
424
+ // MPS: derive total RAM from ram_mb + ram_pct, express RSS as %
425
+ if (s.ram_pct > 0) return (s.vram_mb / (s.ram_mb / (s.ram_pct / 100))) * 100;
426
+ return null;
427
+ });
428
+ const vramLabel = data.gpu_backend === 'mps' ? 'RSS % (MPS)' : 'VRAM %';
429
+ resChart.data.datasets[2].label = vramLabel;
430
+ resChart.options.scales.yVram.display = false; // keep right axis hidden, same % scale
431
+ } else {
432
+ resChart.data.datasets[2].data = samples.map(() => null);
433
+ }
434
+ resChart.update('none');
435
+
436
+ // Latency stacked bar
437
+ const turns = data.turn_breakdown ?? [];
438
+ latChart.data.labels = turns.map(t => `T${t.turn}`);
439
+ latChart.data.datasets[0].data = turns.map(t => t.llm_direct ?? 0);
440
+ latChart.data.datasets[1].data = turns.map(t => (t.painter_backdrop ?? 0) + (t.painter_sprite ?? 0));
441
+ latChart.data.datasets[2].data = turns.map(t => t.stt ?? 0);
442
+ latChart.data.datasets[3].data = turns.map(t => t.compact_memory ?? 0);
443
+ latChart.data.datasets[4].data = turns.map(t => {
444
+ const acc = (t.llm_direct ?? 0) + (t.painter_backdrop ?? 0) + (t.painter_sprite ?? 0)
445
+ + (t.stt ?? 0) + (t.compact_memory ?? 0)
446
+ + (t.apply_directives ?? 0) + (t.save_memory ?? 0);
447
+ return Math.max(0, (t.total_turn ?? 0) - acc);
448
+ });
449
+ latChart.update('none');
450
+
451
+ // Ops table
452
+ const ops = data.ops ?? {};
453
+ const keys = [...OP_ORDER.filter(k => k in ops), ...Object.keys(ops).filter(k => !OP_ORDER.includes(k))];
454
+ const tbody = document.getElementById('ops-body');
455
+ tbody.innerHTML = keys.map(k => {
456
+ const o = ops[k];
457
+ if (!o) return '';
458
+ const isTot = k === 'total_turn';
459
+ return `<tr class="${isTot ? 'total-row' : ''}">
460
+ <td>${OP_NAMES[k] ?? k}</td>
461
+ <td>${o.count}</td>
462
+ <td class="${latencyClass(o.avg_ms)}">${Math.round(o.avg_ms)}</td>
463
+ <td>${Math.round(o.p95_ms)}</td>
464
+ <td>${Math.round(o.max_ms)}</td>
465
+ </tr>`;
466
+ }).join('');
467
+ }
468
+
469
+ // ── SSE connection with auto-reconnect ───────────────────────────────────
470
+ const dot = document.getElementById('dot');
471
+ const statusTxt = document.getElementById('status-text');
472
+ let src = null;
473
+
474
+ function connect() {
475
+ if (src) { src.close(); src = null; }
476
+ dot.className = 'dot';
477
+ statusTxt.textContent = 'Connecting…';
478
+
479
+ src = new EventSource('/debug/stream');
480
+ src.onopen = () => {
481
+ dot.className = 'dot live';
482
+ statusTxt.textContent = 'Live';
483
+ };
484
+ src.onmessage = e => {
485
+ try { update(JSON.parse(e.data)); } catch { /* ignore parse errors */ }
486
+ };
487
+ src.onerror = () => {
488
+ dot.className = 'dot error';
489
+ statusTxt.textContent = 'Reconnecting in 3s…';
490
+ src.close(); src = null;
491
+ setTimeout(connect, 3000);
492
+ };
493
+ }
494
+
495
+ // ── Save report ──────────────────────────────────────────────────────────
496
+ async function saveReport() {
497
+ const btn = document.getElementById('save-btn');
498
+ const msg = document.getElementById('report-msg');
499
+ btn.disabled = true;
500
+ msg.style.color = 'var(--muted)';
501
+ msg.textContent = 'Saving…';
502
+ try {
503
+ const r = await fetch('/debug/report');
504
+ const d = await r.json();
505
+ msg.style.color = 'var(--green)';
506
+ msg.textContent = d.status === 'ok' ? '✓ Saved to runs/debug_*/' : '✗ Save failed';
507
+ } catch {
508
+ msg.style.color = 'var(--red)';
509
+ msg.textContent = '✗ Request failed';
510
+ }
511
+ setTimeout(() => { msg.textContent = ''; btn.disabled = false; }, 4000);
512
+ }
513
+
514
+ connect();
515
+ </script>
516
+ </body>
517
+ </html>
frontend/index.html ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
6
+ <title>Thousand Token Wood</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
9
+ <!-- distinctive storybook display + a quiet humanist body (avoid generic system fonts) -->
10
+ <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,500;0,600;1,500&family=Spectral:wght@300;400;500&display=swap" rel="stylesheet" />
11
+ <style>
12
+ :root{
13
+ --ink:#f3ece0; --ink-dim:#c9bfae;
14
+ --dusk-0:#0b0e14; --dusk-1:#151a26; --dusk-2:#1d2740;
15
+ --gold:#e8c172; --moss:#9fd29a; --rose:#e9a6a6;
16
+ --box: rgba(10,12,18,.78);
17
+ --display:"Cormorant Garamond", serif;
18
+ --body:"Spectral", Georgia, serif;
19
+ }
20
+ *{box-sizing:border-box} html,body{height:100%;margin:0}
21
+ body{
22
+ font-family:var(--body); color:var(--ink); background:var(--dusk-0);
23
+ overflow:hidden; -webkit-font-smoothing:antialiased;
24
+ }
25
+ /* ---- layered stage ---- */
26
+ #stage{position:fixed; inset:0; display:grid; place-items:stretch}
27
+ #backdrop{
28
+ position:absolute; inset:0; z-index:0; background-size:cover; background-position:center;
29
+ transition:opacity 1.1s ease, transform 8s ease-out; opacity:0; transform:scale(1.06);
30
+ filter:saturate(1.05);
31
+ }
32
+ #backdrop.on{opacity:1; transform:scale(1)}
33
+ /* atmosphere: vignette + grain so it never looks like a flat solid */
34
+ #stage::after{
35
+ content:""; position:absolute; inset:0; z-index:3; pointer-events:none;
36
+ background:radial-gradient(120% 90% at 50% 40%, transparent 55%, rgba(0,0,0,.55) 100%);
37
+ mix-blend-mode:multiply;
38
+ }
39
+ #sprites{position:absolute; inset:0; z-index:2; display:flex; align-items:flex-end;
40
+ justify-content:center; gap:4vw; padding:0 6vw 22vh}
41
+ .sprite{height:64vh; max-height:680px; filter:drop-shadow(0 18px 30px rgba(0,0,0,.5));
42
+ opacity:0; transform:translateY(24px); transition:opacity .7s ease, transform .7s ease}
43
+ .sprite.on{opacity:1; transform:translateY(0)}
44
+ /* ---- dialogue ---- */
45
+ #dialogue{
46
+ position:absolute; left:50%; bottom:3.2vh; z-index:4; transform:translateX(-50%);
47
+ width:min(900px,92vw); background:var(--box); border:1px solid rgba(232,193,114,.25);
48
+ border-radius:14px; padding:18px 22px 16px; backdrop-filter:blur(6px);
49
+ box-shadow:0 10px 40px rgba(0,0,0,.45);
50
+ }
51
+ #speaker{font-family:var(--display); font-size:1.5rem; letter-spacing:.3px; color:var(--gold);
52
+ margin:0 0 4px}
53
+ #line{font-size:1.12rem; line-height:1.55; min-height:3.2em; color:var(--ink)}
54
+ #place{position:absolute; top:18px; left:22px; z-index:4; font-family:var(--display);
55
+ font-size:1.05rem; color:var(--ink-dim); letter-spacing:1px; text-transform:uppercase;
56
+ text-shadow:0 1px 8px #000}
57
+ /* ---- input row ---- */
58
+ #inputrow{display:flex; gap:10px; margin-top:12px}
59
+ #say{flex:1; background:rgba(255,255,255,.06); border:1px solid rgba(255,255,255,.15);
60
+ color:var(--ink); border-radius:10px; padding:11px 14px; font-family:var(--body); font-size:1rem}
61
+ #say:focus{outline:none; border-color:var(--gold)}
62
+ button{font-family:var(--body); cursor:pointer; border:none; border-radius:10px;
63
+ padding:11px 16px; color:#10131a; background:var(--gold); font-weight:600; font-size:.98rem}
64
+ button.ghost{background:transparent; color:var(--ink); border:1px solid rgba(255,255,255,.22)}
65
+ button:disabled{opacity:.45; cursor:wait}
66
+ #mic.live{background:var(--rose)}
67
+ /* ---- setup overlay ---- */
68
+ #setup{position:fixed; inset:0; z-index:9; display:grid; place-items:center;
69
+ background:radial-gradient(80% 80% at 50% 30%, var(--dusk-2), var(--dusk-0));}
70
+ .card{width:min(520px,92vw); text-align:center; padding:34px 30px}
71
+ .card h1{font-family:var(--display); font-weight:600; font-size:2.6rem; margin:.1em 0 .1em;
72
+ color:var(--ink)}
73
+ .card p{color:var(--ink-dim); margin:.2em 0 1.4em}
74
+ .field{display:flex; gap:10px; margin:10px 0; align-items:center; justify-content:space-between}
75
+ .field label{font-family:var(--display); font-size:1.2rem; color:var(--gold)}
76
+ select{flex:1; margin-left:14px; background:rgba(255,255,255,.06); color:var(--ink);
77
+ border:1px solid rgba(255,255,255,.18); border-radius:10px; padding:10px 12px; font-family:var(--body)}
78
+ #enter{width:100%; margin-top:16px; padding:14px; font-size:1.05rem}
79
+ .shimmer{color:var(--ink-dim); font-style:italic}
80
+ .hidden{display:none !important}
81
+ </style>
82
+ </head>
83
+ <body>
84
+ <div id="stage">
85
+ <div id="backdrop"></div>
86
+ <div id="sprites"></div>
87
+ <div id="place"></div>
88
+ <div id="dialogue">
89
+ <h2 id="speaker">…</h2>
90
+ <div id="line"><span class="shimmer">the wood is dreaming…</span></div>
91
+ <div id="inputrow">
92
+ <input id="say" placeholder="say something to the wood…" autocomplete="off" />
93
+ <button id="send">Speak</button>
94
+ <button id="mic" class="ghost" title="hold to speak">🎙️</button>
95
+ </div>
96
+ </div>
97
+ </div>
98
+
99
+ <div id="setup">
100
+ <div class="card">
101
+ <h1>Thousand Token Wood</h1>
102
+ <p>A wood dreams itself around you. Choose where the dream begins.</p>
103
+ <div class="field"><label>Theme</label><select id="theme"></select></div>
104
+ <div class="field"><label>Tone</label><select id="tone"></select></div>
105
+ <button id="enter">Enter the wood</button>
106
+ </div>
107
+ </div>
108
+
109
+ <script type="module">
110
+ import { Client, handle_file } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
111
+
112
+ const $ = (id) => document.getElementById(id);
113
+ let client;
114
+
115
+ // --- boot: connect + populate the setup form from /themes ---
116
+ (async () => {
117
+ client = await Client.connect(window.location.origin);
118
+ try {
119
+ const { data } = await client.predict("/themes", {});
120
+ const { themes, tones } = data[0];
121
+ for (const [key, t] of Object.entries(themes)) {
122
+ $("theme").insertAdjacentHTML("beforeend", `<option value="${key}">${t.label}</option>`);
123
+ }
124
+ for (const t of tones) $("tone").insertAdjacentHTML("beforeend", `<option value="${t}">${t}</option>`);
125
+ } catch (e) { console.warn("themes endpoint not ready", e); }
126
+ })();
127
+
128
+ // --- typewriter ---
129
+ function typeOut(el, text){
130
+ el.textContent = ""; let i = 0;
131
+ clearInterval(el._timer);
132
+ el._timer = setInterval(() => {
133
+ el.textContent = text.slice(0, ++i);
134
+ if (i >= text.length) clearInterval(el._timer);
135
+ }, 16);
136
+ }
137
+
138
+ // --- render a ViewState ---
139
+ let lastBg = null;
140
+ function render(v){
141
+ $("place").textContent = v.place || "";
142
+ $("speaker").textContent = v.speaker || "";
143
+ typeOut($("line"), v.dialogue || "");
144
+ if (v.backdrop_url && v.backdrop_url !== lastBg){
145
+ const bg = $("backdrop");
146
+ bg.classList.remove("on");
147
+ setTimeout(() => { bg.style.backgroundImage = `url(${v.backdrop_url})`; bg.classList.add("on"); }, 120);
148
+ lastBg = v.backdrop_url;
149
+ }
150
+ const wrap = $("sprites"); wrap.innerHTML = "";
151
+ for (const p of (v.present || [])){
152
+ if (!p.sprite_url) continue;
153
+ const img = document.createElement("img");
154
+ img.className = "sprite"; img.src = p.sprite_url; img.alt = p.name;
155
+ wrap.appendChild(img);
156
+ requestAnimationFrame(() => img.classList.add("on"));
157
+ }
158
+ }
159
+
160
+ function busy(state){ $("send").disabled = state; $("say").disabled = state; }
161
+
162
+ // --- start ---
163
+ $("enter").addEventListener("click", async () => {
164
+ $("enter").disabled = true;
165
+ const { data } = await client.predict("/start", { theme: $("theme").value, tone: $("tone").value });
166
+ $("setup").classList.add("hidden");
167
+ render(data[0]);
168
+ });
169
+
170
+ // --- a turn ---
171
+ async function sendTurn(){
172
+ const text = $("say").value.trim();
173
+ if (!text) return;
174
+ $("say").value = ""; busy(true);
175
+ try {
176
+ const { data } = await client.predict("/turn", { player_input: text });
177
+ render(data[0]);
178
+ } finally { busy(false); $("say").focus(); }
179
+ }
180
+ $("send").addEventListener("click", sendTurn);
181
+ $("say").addEventListener("keydown", (e) => { if (e.key === "Enter") sendTurn(); });
182
+
183
+ // --- voice (MediaRecorder -> /transcribe). Press to start, press again to stop. ---
184
+ let rec, chunks = [];
185
+ $("mic").addEventListener("click", async () => {
186
+ const mic = $("mic");
187
+ if (rec && rec.state === "recording"){ rec.stop(); return; }
188
+ try {
189
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
190
+ rec = new MediaRecorder(stream); chunks = [];
191
+ rec.ondataavailable = (e) => chunks.push(e.data);
192
+ rec.onstop = async () => {
193
+ mic.classList.remove("live");
194
+ const blob = new Blob(chunks, { type: "audio/webm" });
195
+ const file = new File([blob], "speech.webm", { type: "audio/webm" });
196
+ const { data } = await client.predict("/transcribe", { audio: handle_file(file) });
197
+ if (data[0]?.text){ $("say").value = data[0].text; sendTurn(); }
198
+ stream.getTracks().forEach((t) => t.stop());
199
+ };
200
+ rec.start(); mic.classList.add("live");
201
+ } catch (e) { console.warn("mic unavailable", e); }
202
+ });
203
+ </script>
204
+ </body>
205
+ </html>
pyproject.toml ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "hackathon-ia-visualnovel"
3
+ version = "0.1.0"
4
+ description = "An AI-improvised, voice-or-text anime visual novel — Build Small Hackathon (Thousand Token Wood)."
5
+ readme = "README.md"
6
+ license = { text = "Apache-2.0" }
7
+ # 3.14 is pinned in .python-version. We allow >=3.11 so the project still installs if a heavy
8
+ # ML wheel (torch / llama-cpp-python / ctranslate2) doesn't yet ship a 3.14 build — just
9
+ # `uv python pin 3.12` and re-sync. The package itself is 3.11+ clean.
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "gradio>=5.0",
13
+ "pydantic>=2.7",
14
+ "pillow>=10.0",
15
+ "huggingface-hub>=1.17.0",
16
+ "python-dotenv>=1.0",
17
+ "psutil>=5.9",
18
+ "llama-cpp-python>=0.3.23",
19
+ "torch>=2.12.0",
20
+ "diffusers>=0.37.1",
21
+ "faster-whisper>=1.2.1",
22
+ "torchvision>=0.27.0",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ # Heavy backends are OPTIONAL so the mock loop installs in seconds. Add per platform — see README.
27
+ # uv sync --extra llamacpp # llama.cpp LLM (local; the Llama-Champion bonus)
28
+ # uv sync --extra transformers # HF transformers LLM (the ZeroGPU Space fallback)
29
+ # uv sync --extra image # SDXL-Turbo via diffusers
30
+ # uv sync --extra stt # faster-whisper microphone input
31
+ llamacpp = ["llama-cpp-python>=0.3.0"]
32
+ transformers = ["transformers>=4.44", "accelerate>=0.33", "torch>=2.3"]
33
+ image = ["diffusers>=0.38.0", "transformers>=4.44", "accelerate>=0.33", "torch>=2.3", "safetensors>=0.4"]
34
+ stt = ["faster-whisper>=1.0"]
35
+ matting = ["transformers>=4.44", "torch>=2.3"] # BiRefNet for transparent sprites (Phase 2)
36
+ spaces = ["spaces>=0.30"] # ZeroGPU decorator on HF Spaces
37
+ dev = ["ruff>=0.6", "pytest>=8.0", "matplotlib>=3.9"]
38
+
39
+ [tool.ruff]
40
+ line-length = 100
41
+ target-version = "py311"
42
+
43
+ [tool.ruff.lint]
44
+ select = ["E", "F", "I", "UP", "B"]
45
+ ignore = ["E501", "E402"] # E501: long prompt/doc lines; E402: mode bootstrap before visualnovel imports
46
+
47
+ [tool.pytest.ini_options]
48
+ addopts = "-q"
49
+ testpaths = ["tests"]
50
+
51
+ [build-system]
52
+ requires = ["hatchling"]
53
+ build-backend = "hatchling.build"
54
+
55
+ [dependency-groups]
56
+ dev = [
57
+ "pytest>=9.0.3",
58
+ "ruff>=0.15.15",
59
+ ]
60
+
61
+ [tool.hatch.build.targets.wheel]
62
+ packages = ["visualnovel"]
scripts/download_models.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pull model weights into ./models for the real (non-mock) config.
2
+
3
+ uv run python scripts/download_models.py # everything for the beefy config
4
+ uv run python scripts/download_models.py --llm # just the GGUF LLM
5
+ uv run python scripts/download_models.py --image # just SDXL-Turbo
6
+
7
+ Needs `huggingface_hub` (comes with gradio). Diffusers/whisper weights are also fetched
8
+ lazily on first real use, so this script is mostly to warm the cache / work offline later.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+
15
+ from visualnovel import config
16
+
17
+
18
+ def fetch_llm() -> None:
19
+ from huggingface_hub import hf_hub_download
20
+
21
+ print(f"↓ GGUF LLM: {config.LLM_GGUF_REPO}/{config.LLM_GGUF_FILE}")
22
+ path = hf_hub_download(
23
+ repo_id=config.LLM_GGUF_REPO,
24
+ filename=config.LLM_GGUF_FILE,
25
+ local_dir=str(config.MODELS_DIR),
26
+ token=config.HF_TOKEN,
27
+ )
28
+ print(f" -> {path}")
29
+
30
+
31
+ def fetch_image() -> None:
32
+ from huggingface_hub import snapshot_download
33
+
34
+ print(f"↓ image model: {config.IMAGE_MODEL}")
35
+ snapshot_download(
36
+ repo_id=config.IMAGE_MODEL,
37
+ local_dir=str(config.MODELS_DIR / "image"),
38
+ token=config.HF_TOKEN,
39
+ )
40
+ if config.IMAGE_LORA:
41
+ print(f"↓ style LoRA: {config.IMAGE_LORA}")
42
+ snapshot_download(
43
+ repo_id=config.IMAGE_LORA,
44
+ local_dir=str(config.MODELS_DIR / "lora"),
45
+ token=config.HF_TOKEN,
46
+ )
47
+
48
+
49
+ def fetch_whisper() -> None:
50
+ # faster-whisper downloads on first use; this just pre-warms it.
51
+ try:
52
+ from faster_whisper import WhisperModel
53
+
54
+ print(f"↓ whisper: {config.WHISPER_SIZE}")
55
+ WhisperModel(config.WHISPER_SIZE, device="cpu", compute_type="int8")
56
+ except ImportError:
57
+ print(" (skip whisper: install the `stt` extra to pre-fetch)")
58
+
59
+
60
+ def main() -> None:
61
+ ap = argparse.ArgumentParser()
62
+ ap.add_argument("--llm", action="store_true")
63
+ ap.add_argument("--image", action="store_true")
64
+ ap.add_argument("--whisper", action="store_true")
65
+ args = ap.parse_args()
66
+ do_all = not (args.llm or args.image or args.whisper)
67
+
68
+ config.MODELS_DIR.mkdir(parents=True, exist_ok=True)
69
+ if args.llm or do_all:
70
+ fetch_llm()
71
+ if args.image or do_all:
72
+ fetch_image()
73
+ if args.whisper or do_all:
74
+ fetch_whisper()
75
+ print("done.")
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
templates/character_sheet.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
+ character_sheet.md — the per-character "dream-memory" view.
3
+ One file per spirit, e.g. memory/characters/<id>.md
4
+ This is a DERIVED VIEW of the Character object in state.py — code writes it after each turn.
5
+ The LLM READS it for context; it does not author the canonical copy.
6
+ {{double_braces}} are fields filled from state. Keep it short — it goes into the prompt.
7
+ -->
8
+
9
+ # {{name}} <!-- id: {{id}} -->
10
+
11
+ > {{one_line}}
12
+
13
+ - **Traits:** {{traits}} <!-- comma-separated, e.g. shy, curious, hoards apologies -->
14
+ - **Voice:** {{voice}} <!-- how they speak: rhythm, vocabulary, verbal tics -->
15
+ - **Goal:** {{goals}} <!-- what they want from the wanderer / the scene -->
16
+ - **Appearance (STABLE — reused for every picture):** {{appearance}}
17
+ - **Current mood:** {{mood}} <!-- neutral | joy | fear | anger | sad | surprise | tender -->
18
+ - **Feeling toward the wanderer:** {{relationship}} / 100
19
+ - **Sprite seed (pinned for consistency):** {{sprite_seed}}
20
+
21
+ ## What this spirit knows
22
+ <!-- Only what they could plausibly know. Prevents omniscient NPCs. -->
23
+ - {{known_facts}}
24
+
25
+ ## Recent moments with the wanderer
26
+ <!-- 1–3 short bullets, trimmed as the tale grows. Continuity, not transcript. -->
27
+ - {{recent_beats}}
templates/world_state.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
+ world_state.md — the world / story-progress "dream-memory" view.
3
+ Lives at e.g. memory/world_state.md
4
+ DERIVED VIEW of GameState (state.py writes it after each turn). The LLM reads it for context.
5
+ Keep it tight: this is fed into the prompt every turn alongside the present spirits' sheets.
6
+ -->
7
+
8
+ # Thousand Token Wood — dream-memory
9
+
10
+ - **Seed:** {{seed}} · **Vibe:** {{vibe}} · **Beat:** {{beat}} · **Turn:** {{turn_index}}
11
+
12
+ ## Style guide (the look & tone — rarely changes)
13
+ {{style_guide}}
14
+
15
+ ## Where we are now
16
+ - **Place:** {{scene.place}}
17
+ - **Description:** {{scene.description}}
18
+ - **Mood:** {{scene.mood}}
19
+ - **Backdrop seed:** {{scene.backdrop_seed}}
20
+ - **Spirits on stage:** {{scene.present}} <!-- ids; cap ~3; full sheets injected separately -->
21
+
22
+ ## The tale so far (rolling summary)
23
+ <!-- compact_memory() keeps this to ~3–6 sentences of plain prose. -->
24
+ {{summary}}
25
+
26
+ ## World facts / flags
27
+ <!-- arbitrary key: value facts the Weaver has set, e.g. gave_player_the_key: true -->
28
+ {{flags}}
29
+
30
+ ## Spirits met (index)
31
+ <!-- name — one_line — feeling/100 ; one line each, links to their sheet -->
32
+ {{character_index}}
33
+
34
+ ## Recent exchanges (verbatim, last few)
35
+ <!-- last k turns; trimmed into `summary` when over the context budget. -->
36
+ {{recent_turns}}
tests/test_directives.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """apply_directives is the only mutator — pin its behaviour: scene change, new character,
2
+ relationship clamp, exit, and ending."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from visualnovel import state
7
+ from visualnovel.schemas import (
8
+ Character,
9
+ Directives,
10
+ DirectorOutput,
11
+ Ending,
12
+ GameState,
13
+ NewCharacter,
14
+ Scene,
15
+ SceneChange,
16
+ )
17
+
18
+
19
+ def _state() -> GameState:
20
+ return GameState(
21
+ seed=1,
22
+ vibe="v",
23
+ style_guide="s",
24
+ scene=Scene(id="a", place="A", present=["moth"]),
25
+ characters={"moth": Character(id="moth", name="Moth", relationship=95)},
26
+ )
27
+
28
+
29
+ def test_scene_change_and_relationship_clamp():
30
+ s = _state()
31
+ out = DirectorOutput(
32
+ speaker="moth",
33
+ dialogue="hi",
34
+ emotion="joy",
35
+ directives=Directives(
36
+ scene_change=SceneChange(place="The Hollow Stair", description="d", mood="eerie"),
37
+ relationship_delta=50, # 95 + 50 -> clamped to 100
38
+ ),
39
+ )
40
+ effects = state.apply_directives(s, out)
41
+ assert "scene_changed" in effects
42
+ assert s.scene.place == "The Hollow Stair"
43
+ assert s.scene.present == ["moth"] # people carry across a move
44
+ assert s.characters["moth"].relationship == 100 # clamped
45
+ assert s.characters["moth"].mood == "joy"
46
+
47
+
48
+ def test_new_character_joins_stage():
49
+ s = _state()
50
+ out = DirectorOutput(
51
+ speaker="moth",
52
+ dialogue="look",
53
+ directives=Directives(
54
+ new_character=NewCharacter(
55
+ id="fox", name="Fen", one_line="a sly fox", appearance="russet"
56
+ )
57
+ ),
58
+ )
59
+ effects = state.apply_directives(s, out)
60
+ assert "new_character:fox" in effects
61
+ assert "fox" in s.characters and "fox" in s.scene.present
62
+ assert s.characters["fox"].sprite_seed != 0 # pinned seed assigned
63
+
64
+
65
+ def test_exit_and_ending():
66
+ s = _state()
67
+ s.scene.present.append("fox")
68
+ s.characters["fox"] = Character(id="fox", name="Fen")
69
+ out = DirectorOutput(
70
+ speaker="moth",
71
+ dialogue="farewell",
72
+ directives=Directives(
73
+ exit_character="fox",
74
+ ending=Ending(kind="warm", text="And the wood let you go, gently."),
75
+ ),
76
+ )
77
+ effects = state.apply_directives(s, out)
78
+ assert "exit_character:fox" in effects and "fox" not in s.scene.present
79
+ assert s.beat == "ended" and s.flags["ending_kind"] == "warm"
tests/test_memory_budget.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Memory is a budget: assembled context must respect it, and compaction must trigger when
2
+ recent turns pile up."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from visualnovel import config, memory
7
+ from visualnovel.schemas import Character, GameState, Scene, Turn
8
+
9
+
10
+ def _state(n_turns: int = 0) -> GameState:
11
+ s = GameState(
12
+ seed=1,
13
+ vibe="v",
14
+ style_guide="s",
15
+ scene=Scene(id="a", place="A", description="d", present=["moth"]),
16
+ characters={"moth": Character(id="moth", name="Moth", one_line="a moth")},
17
+ )
18
+ for i in range(n_turns):
19
+ s.recent_turns.append(Turn(player=f"p{i}", speaker="moth", dialogue=f"d{i}"))
20
+ return s
21
+
22
+
23
+ def test_context_includes_present_and_input():
24
+ ctx = memory.assemble_context(_state(2), "where am I?")
25
+ assert "Moth" in ctx
26
+ assert "where am I?" in ctx
27
+ assert "SPIRITS ON STAGE" in ctx
28
+
29
+
30
+ def test_context_respects_budget(monkeypatch):
31
+ monkeypatch.setattr(config, "CONTEXT_TOKEN_BUDGET", 50) # 50 tokens ≈ 200 chars
32
+ ctx = memory.assemble_context(_state(40), "x" * 500)
33
+ assert len(ctx) <= 50 * 4 + len("…(earlier dream trimmed)…\n\n")
34
+
35
+
36
+ def test_should_compact():
37
+ assert memory.should_compact(_state(config.RECENT_TURNS_K + 1)) is True
38
+ assert memory.should_compact(_state(1)) is False
tests/test_state_roundtrip.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """State is the source of truth; the struct must survive a dump/validate round-trip and
2
+ render into the .md views. (Parsing .md back is intentionally not implemented.)"""
3
+
4
+ from __future__ import annotations
5
+
6
+ from visualnovel import state
7
+ from visualnovel.schemas import Character, GameState, Scene
8
+
9
+
10
+ def _sample() -> GameState:
11
+ return GameState(
12
+ seed=7,
13
+ vibe="cozy · Fantasy forest",
14
+ style_guide="anime, soft cel shading",
15
+ scene=Scene(
16
+ id="threshold",
17
+ place="The Threshold",
18
+ description="edge of the wood",
19
+ mood="cozy",
20
+ present=["moth"],
21
+ ),
22
+ characters={
23
+ "moth": Character(
24
+ id="moth",
25
+ name="Mothlight",
26
+ one_line="a nervous lantern-moth",
27
+ appearance="amber wings",
28
+ ),
29
+ },
30
+ )
31
+
32
+
33
+ def test_state_struct_roundtrip():
34
+ s = _sample()
35
+ again = GameState.model_validate(s.model_dump())
36
+ assert again == s
37
+ assert again.characters["moth"].name == "Mothlight"
38
+
39
+
40
+ def test_render_world_md_contains_scene():
41
+ s = _sample()
42
+ md = state.render_world_md(s)
43
+ assert "The Threshold" in md
44
+ assert "Mothlight" in md # character index
45
+ assert "{{" not in md # all placeholders filled
46
+
47
+
48
+ def test_render_character_md():
49
+ s = _sample()
50
+ md = state.render_character_md(s, s.characters["moth"])
51
+ assert "Mothlight" in md and "amber wings" in md
52
+ assert "{{" not in md
uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
visualnovel/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """hackathon-ia-visualnovel — an AI-improvised anime visual novel (Thousand Token Wood).
2
+
3
+ The model proposes, code disposes: the LLM returns typed directives, `state.apply_directives`
4
+ owns all mutation, `.md` files are a derived view. See docs/ARCHITECTURE.md.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from .engine import Engine
10
+ from .schemas import GameState, SetupForm, ViewState
11
+
12
+ __all__ = ["Engine", "GameState", "SetupForm", "ViewState"]
13
+ __version__ = "0.1.0"
visualnovel/characters.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Voices — the actor-context layer.
2
+
3
+ This isn't a separate model call; it's the slice of context that tells the shared LLM *who*
4
+ is on stage and how they speak. We only ever inject the sheets of the **present** characters
5
+ (never the whole cast) to respect the token budget and to keep NPCs non-omniscient.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .schemas import Character, GameState
11
+
12
+
13
+ def present_characters(state: GameState) -> list[Character]:
14
+ return [state.characters[cid] for cid in state.scene.present if cid in state.characters]
15
+
16
+
17
+ def actor_roster(state: GameState) -> str:
18
+ """One-liner list of who can speak this turn."""
19
+ rows = [f"{c.id} = {c.name} ({c.one_line})" for c in present_characters(state)]
20
+ return "; ".join(rows) if rows else "narrator"
21
+
22
+
23
+ def present_sheets_block(state: GameState) -> str:
24
+ """Compact, prompt-friendly sheets for the spirits currently on stage."""
25
+ blocks: list[str] = []
26
+ for c in present_characters(state):
27
+ facts = "; ".join(c.known_facts) if c.known_facts else "—"
28
+ blocks.append(
29
+ f"### {c.name} (id: {c.id})\n"
30
+ f"- one_line: {c.one_line}\n"
31
+ f"- traits: {', '.join(c.traits) or '—'}\n"
32
+ f"- voice: {c.voice or '—'}\n"
33
+ f"- goal: {c.goals or '—'}\n"
34
+ f"- mood: {c.mood} | feeling toward wanderer: {c.relationship}/100\n"
35
+ f"- knows: {facts}"
36
+ )
37
+ return "\n\n".join(blocks) if blocks else "(no spirits on stage — the narrator may speak)"
visualnovel/config.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """All knobs in one place. Everything is overridable via environment variables so you
2
+ can flip between mock / real / different models without touching code.
3
+
4
+ Defaults are the "beefy" config (Qwen3-14B + SDXL-Turbo + Whisper-small), and MOCK is ON
5
+ by default so a fresh checkout runs end-to-end with zero model downloads.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from pathlib import Path
12
+
13
+ from dotenv import load_dotenv
14
+
15
+ load_dotenv() # loads .env from CWD or any parent; no-op if file absent
16
+
17
+ # --------------------------------------------------------------------------- #
18
+ # Hugging Face authentication (required for gated models)
19
+ # --------------------------------------------------------------------------- #
20
+ HF_TOKEN: str | None = os.getenv("HF_TOKEN")
21
+
22
+ # True when launched with --mode debug (set by app.py before this import).
23
+ DEBUG: bool = os.getenv("VN_DEBUG", "0") == "1"
24
+
25
+ # --------------------------------------------------------------------------- #
26
+ # Paths
27
+ # --------------------------------------------------------------------------- #
28
+ ROOT = Path(__file__).resolve().parent.parent
29
+ MODELS_DIR = Path(os.getenv("VN_MODELS_DIR", ROOT / "models"))
30
+ MEMORY_DIR = Path(os.getenv("VN_MEMORY_DIR", ROOT / "memory"))
31
+ RUNS_DIR = Path(os.getenv("VN_RUNS_DIR", ROOT / "runs"))
32
+ TEMPLATES_DIR = ROOT / "templates"
33
+ CACHE_DIR = Path(os.getenv("VN_CACHE_DIR", ROOT / ".cache" / "images"))
34
+ for _d in (MEMORY_DIR, RUNS_DIR, CACHE_DIR):
35
+ _d.mkdir(parents=True, exist_ok=True)
36
+
37
+ # --------------------------------------------------------------------------- #
38
+ # Feature flags
39
+ # --------------------------------------------------------------------------- #
40
+ # MOCK on -> orchestrator/painter/stt use deterministic fakes; no models needed.
41
+ # MOCK off -> real backends are instantiated (install the relevant uv extras first).
42
+ USE_MOCK = os.getenv("VN_MOCK", "1") == "1"
43
+
44
+ # LLM runtime backend when not mocking. llamacpp = the llama.cpp bonus path.
45
+ LLM_BACKEND = os.getenv("VN_LLM_BACKEND", "llamacpp") # llamacpp | transformers | mock
46
+
47
+ # Set to a .jsonl path to record a full per-turn trace (Open-Trace bonus).
48
+ TRACE_PATH = os.getenv("VN_TRACE") # None disables tracing
49
+
50
+ # Force the gr.Blocks MVP UI instead of the custom frontend (Phase 0/1 de-risking).
51
+ MVP_UI = os.getenv("GRADIO_MVP_UI", "0") == "1"
52
+
53
+ # --------------------------------------------------------------------------- #
54
+ # Model registry (the "beefy" config — comfortably < 32B total)
55
+ # Qwen3-14B (~14B) + SDXL-Turbo (~3.5B) + Whisper-small (~0.25B) ≈ ~18B
56
+ # --------------------------------------------------------------------------- #
57
+ LLM_REPO = os.getenv("VN_LLM_REPO", "Qwen/Qwen3-14B") # transformers id
58
+ LLM_GGUF_REPO = os.getenv("VN_LLM_GGUF_REPO", "Qwen/Qwen3-14B-GGUF") # llama.cpp source
59
+ LLM_GGUF_FILE = os.getenv("VN_LLM_GGUF_FILE", "Qwen3-14B-Q4_K_M.gguf")
60
+
61
+ IMAGE_MODEL = os.getenv("VN_IMAGE_MODEL", "stabilityai/sdxl-turbo")
62
+ # Path or HF repo of YOUR fine-tuned anime-style LoRA (the Well-Tuned bonus). Empty = none.
63
+ IMAGE_LORA = os.getenv("VN_IMAGE_LORA", "")
64
+
65
+ WHISPER_SIZE = os.getenv(
66
+ "VN_WHISPER_SIZE", "large-v3-turbo"
67
+ ) # tiny|base|small|medium|large-v3|large-v3-turbo
68
+
69
+ # --------------------------------------------------------------------------- #
70
+ # Generation / budget params
71
+ # --------------------------------------------------------------------------- #
72
+ CONTEXT_TOKEN_BUDGET = int(os.getenv("VN_CTX_BUDGET", "3500")) # the "Thousand Token Wood"
73
+ RECENT_TURNS_K = int(os.getenv("VN_RECENT_K", "6"))
74
+ COMPACT_EVERY = int(os.getenv("VN_COMPACT_EVERY", "8")) # also compacts when over budget
75
+ IMAGE_SIZE = int(os.getenv("VN_IMAGE_SIZE", "768"))
76
+ IMAGE_STEPS = int(os.getenv("VN_IMAGE_STEPS", "2")) # SDXL-Turbo: 1-4 steps
77
+ MAX_PRESENT = int(os.getenv("VN_MAX_PRESENT", "3")) # spirits on stage at once
78
+
79
+ # --------------------------------------------------------------------------- #
80
+ # Fixed art-style base. The chosen theme only adds *setting* flavor on top of this,
81
+ # so every playthrough keeps one coherent look. (See README: style is locked, theme varies.)
82
+ # --------------------------------------------------------------------------- #
83
+ STYLE_BASE = os.getenv(
84
+ "VN_STYLE_BASE",
85
+ "Japanese anime illustration, soft cel shading, clean linework, painterly background, "
86
+ "expressive eyes, gentle film grain, storybook lighting",
87
+ )
88
+ NEGATIVE_PROMPT = os.getenv(
89
+ "VN_NEGATIVE",
90
+ "text, watermark, signature, lowres, blurry, deformed hands, extra limbs, "
91
+ "multiple characters, jpeg artifacts",
92
+ )
93
+
94
+ # --------------------------------------------------------------------------- #
95
+ # Pre-set setup-form themes (the player picks one from a dropdown).
96
+ # Keep STYLE locked; `setting` is injected into prompts + the opening.
97
+ # --------------------------------------------------------------------------- #
98
+ THEMES: dict[str, dict[str, str]] = {
99
+ "school": {
100
+ "label": "School — slice of life",
101
+ "setting": "a Japanese high school bathed in golden afternoon light",
102
+ "palette": "warm, nostalgic",
103
+ },
104
+ "space": {
105
+ "label": "Space — derelict starship",
106
+ "setting": "a quiet derelict starship adrift among slow-turning stars",
107
+ "palette": "cool teal and amber",
108
+ },
109
+ "fantasy_forest": {
110
+ "label": "Fantasy forest",
111
+ "setting": "an enchanted fae woodland lit by drifting spores and glowing mushrooms",
112
+ "palette": "emerald and violet",
113
+ },
114
+ "cyberpunk_city": {
115
+ "label": "Cyberpunk city",
116
+ "setting": "a rain-slick neon megacity at night, signs humming in the drizzle",
117
+ "palette": "magenta and cyan neon",
118
+ },
119
+ "haunted_manor": {
120
+ "label": "Haunted manor",
121
+ "setting": "a candlelit gothic manor of long shadows and patient dust",
122
+ "palette": "desaturated and eerie",
123
+ },
124
+ "seaside_town": {
125
+ "label": "Seaside town",
126
+ "setting": "a sleepy coastal town at first light, gulls and salt on the air",
127
+ "palette": "soft pastel blues",
128
+ },
129
+ }
130
+ TONES = ["cozy", "eerie", "absurd", "melancholy", "whimsical"]
131
+
132
+
133
+ def detect_device() -> str:
134
+ """Return the torch device family.
135
+
136
+ NOTE: torch reports **both** NVIDIA CUDA and **AMD ROCm** as ``cuda`` — so an
137
+ RX 7900 XTX shows up here as "cuda". Apple Silicon (Metal) shows up as "mps".
138
+ """
139
+ try:
140
+ import torch # noqa: PLC0415 (lazy — torch is an optional extra)
141
+
142
+ if torch.backends.mps.is_available():
143
+ return "mps"
144
+ if torch.cuda.is_available():
145
+ return "cuda"
146
+ except Exception:
147
+ pass
148
+ return "cpu"
visualnovel/engine.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Engine — the single façade the UI talks to.
2
+
3
+ engine = Engine()
4
+ view = engine.start(SetupForm(theme="fantasy_forest", tone="cozy"))
5
+ view = engine.play_turn("hello? who are you?")
6
+
7
+ `start` / `play_turn` return a `ViewState` (speaker, dialogue, emotion, backdrop_url,
8
+ present sprites, beat, ending). The engine owns the session `GameState` and orchestrates:
9
+ stt -> direct_turn -> apply_directives -> paint (cached) -> memory -> trace -> view.
10
+
11
+ It deliberately holds ONE game (single-session, per the hackathon scope). For per-user
12
+ sessions on a busy Space, key engines by session id instead.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from pathlib import Path
18
+
19
+ from . import config, memory, orchestrator, state
20
+ from .llm import get_llm
21
+ from .metrics import collector
22
+ from .painter import get_painter
23
+ from .schemas import DirectorOutput, GameState, SetupForm, SpritePresence, Turn, ViewState
24
+ from .stt import get_stt
25
+ from .trace import Tracer
26
+
27
+
28
+ class Engine:
29
+ def __init__(self) -> None:
30
+ self.llm = get_llm()
31
+ self.painter = get_painter()
32
+ self.stt = get_stt()
33
+ self.tracer = Tracer(config.TRACE_PATH)
34
+ self.state: GameState | None = None
35
+
36
+ # -- lifecycle --
37
+ def start(self, setup: SetupForm) -> ViewState:
38
+ self.state, opening = orchestrator.init_world(self.llm, setup)
39
+ self.state.recent_turns.append(
40
+ Turn(
41
+ player="(arrives)",
42
+ speaker=opening.speaker,
43
+ dialogue=opening.dialogue,
44
+ emotion=opening.emotion,
45
+ )
46
+ )
47
+ state.apply_directives(self.state, opening) # sets the speaker's mood
48
+ state.save_memory(self.state)
49
+ self.tracer.log(event="start", setup=setup.model_dump(), opening=opening.model_dump())
50
+ return self._view(opening)
51
+
52
+ def transcribe(self, audio_path: str) -> str:
53
+ return self.stt.transcribe(audio_path)
54
+
55
+ def play_turn(self, player_input: str, audio_path: str | None = None) -> ViewState:
56
+ assert self.state is not None, "call start() first"
57
+ # turn_num matches what the tracer logs (post-increment value)
58
+ turn_num = self.state.turn_index + 1
59
+
60
+ with collector.measure("total_turn", turn=turn_num):
61
+ if audio_path:
62
+ with collector.measure("stt", turn=turn_num):
63
+ player_input = self.stt.transcribe(audio_path) or player_input
64
+
65
+ with collector.measure("llm_direct", turn=turn_num):
66
+ out = orchestrator.direct_turn(self.llm, self.state, player_input)
67
+
68
+ with collector.measure("apply_directives", turn=turn_num):
69
+ effects = state.apply_directives(self.state, out)
70
+
71
+ self.state.recent_turns.append(
72
+ Turn(
73
+ player=player_input,
74
+ speaker=out.speaker,
75
+ dialogue=out.dialogue,
76
+ emotion=out.emotion,
77
+ )
78
+ )
79
+ self.state.turn_index += 1 # now == turn_num
80
+
81
+ with collector.measure("save_memory", turn=turn_num):
82
+ state.save_memory(self.state)
83
+
84
+ if memory.should_compact(self.state):
85
+ with collector.measure("compact_memory", turn=turn_num):
86
+ orchestrator.compact_memory(self.llm, self.state)
87
+
88
+ self.tracer.log(
89
+ event="turn",
90
+ turn=self.state.turn_index,
91
+ player=player_input,
92
+ output=out.model_dump(),
93
+ effects=effects,
94
+ )
95
+ return self._view(out, turn=turn_num)
96
+
97
+ # -- rendering --
98
+ def _view(self, out: DirectorOutput, turn: int = -1) -> ViewState:
99
+ s = self.state
100
+ assert s is not None
101
+ with collector.measure("painter_backdrop", turn=turn):
102
+ backdrop = self.painter.backdrop(s) # cached -> cheap even when unchanged
103
+ present = []
104
+ for cid in s.scene.present:
105
+ ch = s.characters.get(cid)
106
+ if not ch:
107
+ continue
108
+ with collector.measure("painter_sprite", turn=turn):
109
+ sprite = self.painter.sprite(s, ch)
110
+ present.append(
111
+ SpritePresence(id=ch.id, name=ch.name, mood=ch.mood, sprite_url=_to_url(sprite))
112
+ )
113
+ speaker_name = s.characters[out.speaker].name if out.speaker in s.characters else "The wood"
114
+ return ViewState(
115
+ speaker=speaker_name,
116
+ dialogue=out.dialogue,
117
+ emotion=out.emotion,
118
+ place=s.scene.place,
119
+ backdrop_url=_to_url(backdrop),
120
+ present=present,
121
+ beat=s.beat,
122
+ ended=s.beat == "ended",
123
+ ending_text=s.flags.get("ending_text"),
124
+ turn_index=s.turn_index,
125
+ )
126
+
127
+
128
+ def _to_url(p: Path | None) -> str | None:
129
+ # served by app.py via StaticFiles mounted at /images
130
+ return f"/images/{p.name}" if p else None
visualnovel/llm.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One thin LLM wrapper, two methods:
2
+
3
+ complete(messages) -> str (free text; used by compact_memory)
4
+ complete_json(messages, schema) -> dict (grammar-constrained structured output)
5
+
6
+ Three backends behind one interface:
7
+ MockLLM - zero deps, returns schema-shaped defaults (unit tests + smoke)
8
+ LlamaCppLLM - llama.cpp via llama-cpp-python + GBNF/JSON-schema grammar (the bonus)
9
+ TransformersLLM - HF transformers fallback for the ZeroGPU Space
10
+
11
+ Heavy imports are done lazily inside each real backend so a MOCK checkout needs nothing.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import contextlib
17
+ import os
18
+ import sys
19
+ from collections.abc import Generator
20
+ from typing import Any, Protocol
21
+
22
+ from . import config
23
+
24
+
25
+ @contextlib.contextmanager
26
+ def _quiet_stderr() -> Generator[None, None, None]:
27
+ """Redirect the C-level stderr fd to /dev/null for the duration of the block.
28
+
29
+ verbose=False on Llama() suppresses most output, but some llama.cpp messages
30
+ (e.g. 'n_ctx_seq < n_ctx_train') are emitted before the flag takes effect and
31
+ bypass Python's sys.stderr redirect. This fd-level redirect catches them.
32
+ """
33
+ sys.stderr.flush()
34
+ devnull_fd = os.open(os.devnull, os.O_WRONLY)
35
+ saved_fd = os.dup(2)
36
+ try:
37
+ os.dup2(devnull_fd, 2)
38
+ yield
39
+ finally:
40
+ sys.stderr.flush()
41
+ os.dup2(saved_fd, 2)
42
+ os.close(saved_fd)
43
+ os.close(devnull_fd)
44
+
45
+
46
+ class LLMBackend(Protocol):
47
+ def complete(self, messages: list[dict[str, str]], **kw: Any) -> str: ...
48
+ def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict: ...
49
+
50
+
51
+ # --------------------------------------------------------------------------- #
52
+ # Mock — only used by unit tests / when orchestrator isn't short-circuiting.
53
+ # (In MOCK mode the orchestrator builds nice themed output itself; see orchestrator.py.)
54
+ # --------------------------------------------------------------------------- #
55
+ class MockLLM:
56
+ def complete(self, messages: list[dict[str, str]], **kw: Any) -> str:
57
+ return "The wood remembers little, and dreams the rest."
58
+
59
+ def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict:
60
+ return _empty_from_schema(schema)
61
+
62
+
63
+ # --------------------------------------------------------------------------- #
64
+ # llama.cpp (Llama-Champion bonus + Off-the-Grid local-first)
65
+ # --------------------------------------------------------------------------- #
66
+ class LlamaCppLLM:
67
+ def __init__(self) -> None:
68
+ from llama_cpp import Llama # noqa: PLC0415
69
+
70
+ # Pull the GGUF once into ./models (see scripts/download_models.py), then load it.
71
+ # _quiet_stderr suppresses C-level messages (e.g. n_ctx_seq < n_ctx_train)
72
+ # that llama.cpp emits before verbose=False takes effect.
73
+ with _quiet_stderr():
74
+ self.llm = Llama(
75
+ model_path=str(config.MODELS_DIR / config.LLM_GGUF_FILE),
76
+ n_ctx=8192,
77
+ n_gpu_layers=-1, # offload all layers (Metal on Mac / ROCm-HIP on AMD)
78
+ verbose=False,
79
+ )
80
+
81
+ def complete(self, messages: list[dict[str, str]], **kw: Any) -> str:
82
+ out = self.llm.create_chat_completion(messages=messages, **kw)
83
+ return out["choices"][0]["message"]["content"]
84
+
85
+ def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict:
86
+ import json # noqa: PLC0415
87
+
88
+ # llama-cpp-python builds the grammar from the JSON schema for you:
89
+ out = self.llm.create_chat_completion(
90
+ messages=messages,
91
+ response_format={"type": "json_object", "schema": schema},
92
+ temperature=kw.get("temperature", 0.7),
93
+ top_p=kw.get("top_p", 0.9),
94
+ max_tokens=kw.get("max_tokens", 512),
95
+ )
96
+ return json.loads(out["choices"][0]["message"]["content"])
97
+
98
+
99
+ # --------------------------------------------------------------------------- #
100
+ # transformers fallback (for the hosted ZeroGPU Space, if llama.cpp won't build there)
101
+ # --------------------------------------------------------------------------- #
102
+ class TransformersLLM:
103
+ def __init__(self) -> None:
104
+ import torch # noqa: PLC0415
105
+ from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: PLC0415
106
+
107
+ with _quiet_stderr():
108
+ self.tok = AutoTokenizer.from_pretrained(config.LLM_REPO)
109
+ self.model = AutoModelForCausalLM.from_pretrained(
110
+ config.LLM_REPO, torch_dtype="auto", device_map="auto"
111
+ )
112
+ self.torch = torch
113
+
114
+ def complete(self, messages: list[dict[str, str]], **kw: Any) -> str:
115
+ text = self.tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
116
+ ids = self.tok(text, return_tensors="pt").to(self.model.device)
117
+ out = self.model.generate(**ids, max_new_tokens=kw.get("max_tokens", 512))
118
+ return self.tok.decode(out[0][ids.input_ids.shape[1] :], skip_special_tokens=True)
119
+
120
+ def complete_json(self, messages: list[dict[str, str]], schema: dict, **kw: Any) -> dict:
121
+ # TODO: constrain with `outlines`/`lm-format-enforcer` for guaranteed-valid JSON.
122
+ # For now: prompt for JSON, parse, and repair on failure.
123
+ import json # noqa: PLC0415
124
+
125
+ text = self.complete(messages, **kw)
126
+ return json.loads(text[text.find("{") : text.rfind("}") + 1])
127
+
128
+
129
+ # --------------------------------------------------------------------------- #
130
+ # Factory
131
+ # --------------------------------------------------------------------------- #
132
+ def get_llm() -> LLMBackend:
133
+ if config.USE_MOCK or config.LLM_BACKEND == "mock":
134
+ return MockLLM()
135
+ if config.LLM_BACKEND == "transformers":
136
+ return TransformersLLM()
137
+ return LlamaCppLLM()
138
+
139
+
140
+ def _empty_from_schema(schema: dict) -> dict:
141
+ """Build a minimal object that satisfies a (simple) JSON schema's required fields."""
142
+ if schema.get("type") == "object":
143
+ obj: dict[str, Any] = {}
144
+ props = schema.get("properties", {})
145
+ for key in schema.get("required", []):
146
+ obj[key] = _empty_from_schema(props.get(key, {}))
147
+ return obj
148
+ t = schema.get("type")
149
+ if isinstance(t, list):
150
+ t = next((x for x in t if x != "null"), "null")
151
+ return {
152
+ "string": "",
153
+ "integer": 0,
154
+ "number": 0,
155
+ "boolean": False,
156
+ "array": [],
157
+ "object": {},
158
+ }.get(t, None)
visualnovel/memory.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Memory is a *budget*, not an archive.
2
+
3
+ Every turn we assemble the user-side context from (in priority order): the rolling summary,
4
+ the current scene, the present characters' sheets, the last k verbatim turns, and the player's
5
+ new line — trimmed to a conservative token budget. Older turns get folded into `summary` by
6
+ `orchestrator.compact_memory`. This is the literal "Thousand Token Wood".
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from . import characters, config
12
+ from .schemas import GameState
13
+
14
+
15
+ def assemble_context(state: GameState, player_input: str) -> str:
16
+ parts: list[str] = []
17
+ parts.append(f"WORLD STYLE: {state.style_guide}")
18
+ parts.append(f"VIBE: {state.vibe} | BEAT: {state.beat}")
19
+ if state.summary:
20
+ parts.append(f"THE TALE SO FAR:\n{state.summary}")
21
+ parts.append(
22
+ f"WHERE WE ARE:\n- place: {state.scene.place}\n"
23
+ f"- description: {state.scene.description}\n- mood: {state.scene.mood}"
24
+ )
25
+ parts.append(f"SPIRITS ON STAGE:\n{characters.present_sheets_block(state)}")
26
+ if state.flags:
27
+ parts.append("FACTS: " + ", ".join(f"{k}={v}" for k, v in state.flags.items()))
28
+
29
+ recent = state.recent_turns[-config.RECENT_TURNS_K :]
30
+ if recent:
31
+ lines = [f'wanderer: "{t.player}"\n{t.speaker}: "{t.dialogue}"' for t in recent]
32
+ parts.append("RECENT EXCHANGE:\n" + "\n".join(lines))
33
+
34
+ parts.append(f'THE WANDERER NOW SAYS: "{player_input}"')
35
+ parts.append(
36
+ "Reply as one present spirit, then emit the directives JSON. "
37
+ f"You may speak as one of: {characters.actor_roster(state)}."
38
+ )
39
+
40
+ ctx = "\n\n".join(parts)
41
+ return _trim_to_budget(ctx, config.CONTEXT_TOKEN_BUDGET)
42
+
43
+
44
+ def should_compact(state: GameState) -> bool:
45
+ over_count = len(state.recent_turns) > config.RECENT_TURNS_K
46
+ every_n = state.turn_index > 0 and state.turn_index % config.COMPACT_EVERY == 0
47
+ return over_count or every_n
48
+
49
+
50
+ def _trim_to_budget(text: str, token_budget: int) -> str:
51
+ """Rough char≈token/4 budget. Trims from the top of the RECENT EXCHANGE if needed,
52
+ never from the system-critical head. Good enough for a small working memory."""
53
+ char_budget = token_budget * 4
54
+ if len(text) <= char_budget:
55
+ return text
56
+ # keep the tail (most recent + the instruction + the player's line)
57
+ return "…(earlier dream trimmed)…\n\n" + text[-char_budget:]
visualnovel/metrics.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Metrics collection and real-time monitoring for debug mode (VN_DEBUG=1 / --mode debug).
2
+
3
+ In mock and prod modes every call is a no-op, so there is zero overhead.
4
+
5
+ Architecture
6
+ ------------
7
+ - MetricsCollector singleton activated once from app.py
8
+ - measure() context manager: record duration of any named block
9
+ - record_cache() called by PainterBase._cached() to track hit/miss ratio
10
+ - _monitor_loop background thread: poll psutil + GPU every 1 s
11
+ - _display_loop background thread: refresh Rich table on stderr every 0.5 s
12
+ - save_report() called via atexit: write summary.txt + PNG graphs to runs/debug_<ts>/
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import statistics
19
+ import subprocess
20
+ import sys
21
+ import threading
22
+ import time
23
+ from collections import defaultdict
24
+ from collections.abc import Generator
25
+ from contextlib import contextmanager
26
+ from dataclasses import dataclass, field
27
+ from pathlib import Path
28
+
29
+
30
+ # =========================================================================== #
31
+ # Data records
32
+ # =========================================================================== #
33
+ @dataclass
34
+ class TimingRecord:
35
+ name: str
36
+ turn: int # -1 = init / not a player turn
37
+ ms: float
38
+ ts: float = field(default_factory=time.time)
39
+
40
+
41
+ @dataclass
42
+ class ResourceSample:
43
+ ts: float
44
+ ram_mb: int
45
+ ram_pct: float
46
+ cpu_pct: float
47
+ vram_mb: int | None = None
48
+ vram_pct: float | None = None
49
+ gpu_util_pct: float | None = None
50
+
51
+
52
+ # =========================================================================== #
53
+ # Collector
54
+ # =========================================================================== #
55
+ class MetricsCollector:
56
+ """Thread-safe metrics store. All public methods are no-ops when inactive."""
57
+
58
+ def __init__(self) -> None:
59
+ self.active = False
60
+ self._lock = threading.Lock()
61
+ self._timings: list[TimingRecord] = []
62
+ self._samples: list[ResourceSample] = []
63
+ self._cache_hits = 0
64
+ self._cache_misses = 0
65
+ self._stop_event = threading.Event()
66
+ self._monitor_thread: threading.Thread | None = None
67
+ self._display_thread: threading.Thread | None = None
68
+ self._runs_dir: Path = Path("runs")
69
+ self._start_ts: float = 0.0
70
+ self._gpu_backend: str | None = None # "nvml" | "rocm" | "mps" | None
71
+
72
+ # ------------------------------------------------------------------ #
73
+ # Activation
74
+ # ------------------------------------------------------------------ #
75
+ def activate(self, runs_dir: Path) -> None:
76
+ self._runs_dir = runs_dir
77
+ self._start_ts = time.time()
78
+ self.active = True
79
+ self._gpu_backend = self._detect_gpu_backend()
80
+ # warm up cpu_percent baseline (first call always returns 0.0)
81
+ try:
82
+ import psutil # noqa: PLC0415
83
+
84
+ psutil.cpu_percent(interval=None)
85
+ except ImportError:
86
+ pass
87
+ self._monitor_thread = threading.Thread(
88
+ target=self._monitor_loop, daemon=True, name="vn-metrics"
89
+ )
90
+ self._monitor_thread.start()
91
+ self._display_thread = threading.Thread(
92
+ target=self._display_loop, daemon=True, name="vn-display"
93
+ )
94
+ self._display_thread.start()
95
+
96
+ def stop(self) -> None:
97
+ self._stop_event.set()
98
+
99
+ # ------------------------------------------------------------------ #
100
+ # Timing context manager
101
+ # ------------------------------------------------------------------ #
102
+ @contextmanager
103
+ def measure(self, name: str, turn: int = -1) -> Generator[None, None, None]:
104
+ """Time the wrapped block and append a TimingRecord. No-op when inactive."""
105
+ if not self.active:
106
+ yield
107
+ return
108
+ t0 = time.perf_counter()
109
+ try:
110
+ yield
111
+ finally:
112
+ ms = (time.perf_counter() - t0) * 1000.0
113
+ rec = TimingRecord(name=name, turn=turn, ms=ms)
114
+ with self._lock:
115
+ self._timings.append(rec)
116
+
117
+ # ------------------------------------------------------------------ #
118
+ # Painter cache tracking
119
+ # ------------------------------------------------------------------ #
120
+ def record_cache(self, *, hit: bool) -> None:
121
+ if not self.active:
122
+ return
123
+ with self._lock:
124
+ if hit:
125
+ self._cache_hits += 1
126
+ else:
127
+ self._cache_misses += 1
128
+
129
+ # ------------------------------------------------------------------ #
130
+ # Snapshot — JSON-serializable state for the SSE dashboard endpoint
131
+ # ------------------------------------------------------------------ #
132
+ def snapshot(self) -> dict:
133
+ """Return current metrics as a JSON-serializable dict. Thread-safe, no-op guard."""
134
+ if not self.active:
135
+ return {}
136
+ with self._lock:
137
+ timings = list(self._timings)
138
+ samples = list(self._samples[-120:]) # last 2 min at 1 Hz
139
+ hits, misses = self._cache_hits, self._cache_misses
140
+
141
+ by_name: dict[str, list[float]] = defaultdict(list)
142
+ for t in timings:
143
+ by_name[t.name].append(t.ms)
144
+
145
+ ops = {
146
+ name: {
147
+ "count": len(vals),
148
+ "avg_ms": statistics.mean(vals),
149
+ "p95_ms": _percentile(vals, 95),
150
+ "max_ms": max(vals),
151
+ }
152
+ for name, vals in by_name.items()
153
+ if vals
154
+ }
155
+
156
+ turns_by_num: dict[int, dict[str, float]] = defaultdict(lambda: defaultdict(float))
157
+ for t in timings:
158
+ if t.turn >= 0:
159
+ turns_by_num[t.turn][t.name] += t.ms
160
+ turn_breakdown = [{"turn": k, **dict(v)} for k, v in sorted(turns_by_num.items())]
161
+
162
+ total_cache = hits + misses
163
+ return {
164
+ "turns_completed": sum(1 for t in timings if t.name == "total_turn"),
165
+ "ops": ops,
166
+ "turn_breakdown": turn_breakdown,
167
+ "samples": [
168
+ {
169
+ "ts": s.ts,
170
+ "ram_mb": s.ram_mb,
171
+ "ram_pct": s.ram_pct,
172
+ "cpu_pct": s.cpu_pct,
173
+ "vram_mb": s.vram_mb,
174
+ "vram_pct": s.vram_pct,
175
+ "gpu_util_pct": s.gpu_util_pct,
176
+ }
177
+ for s in samples
178
+ ],
179
+ "cache_hits": hits,
180
+ "cache_misses": misses,
181
+ "cache_hit_rate": hits / total_cache if total_cache else None,
182
+ "gpu_backend": self._gpu_backend,
183
+ "session_elapsed_s": time.time() - self._start_ts,
184
+ }
185
+
186
+ # ------------------------------------------------------------------ #
187
+ # System monitor loop (1 Hz)
188
+ # ------------------------------------------------------------------ #
189
+ def _monitor_loop(self) -> None:
190
+ try:
191
+ import psutil # noqa: PLC0415
192
+ except ImportError:
193
+ return
194
+ while not self._stop_event.is_set():
195
+ sample = self._sample_system(psutil)
196
+ with self._lock:
197
+ self._samples.append(sample)
198
+ self._stop_event.wait(1.0)
199
+
200
+ def _sample_system(self, psutil) -> ResourceSample: # type: ignore[no-untyped-def]
201
+ mem = psutil.virtual_memory()
202
+ sample = ResourceSample(
203
+ ts=time.time(),
204
+ ram_mb=mem.used >> 20,
205
+ ram_pct=mem.percent,
206
+ cpu_pct=psutil.cpu_percent(interval=None),
207
+ )
208
+ gpu = self._gpu_stats()
209
+ sample.vram_mb = gpu.get("vram_mb")
210
+ sample.vram_pct = gpu.get("vram_pct")
211
+ sample.gpu_util_pct = gpu.get("gpu_util_pct")
212
+ return sample
213
+
214
+ # ------------------------------------------------------------------ #
215
+ # GPU detection + stats
216
+ # ------------------------------------------------------------------ #
217
+ def _detect_gpu_backend(self) -> str | None:
218
+ try:
219
+ import pynvml # noqa: PLC0415
220
+
221
+ pynvml.nvmlInit()
222
+ return "nvml"
223
+ except Exception:
224
+ pass
225
+ try:
226
+ r = subprocess.run(
227
+ ["rocm-smi", "--showmeminfo", "vram", "--json"],
228
+ capture_output=True,
229
+ timeout=2,
230
+ )
231
+ if r.returncode == 0:
232
+ return "rocm"
233
+ except Exception:
234
+ pass
235
+ try:
236
+ import torch # noqa: PLC0415
237
+
238
+ if torch.backends.mps.is_available():
239
+ return "mps"
240
+ except Exception:
241
+ pass
242
+ return None
243
+
244
+ def _gpu_stats(self) -> dict:
245
+ try:
246
+ if self._gpu_backend == "nvml":
247
+ return self._nvml_stats()
248
+ if self._gpu_backend == "rocm":
249
+ return self._rocm_stats()
250
+ if self._gpu_backend == "mps":
251
+ return self._mps_stats()
252
+ except Exception:
253
+ pass
254
+ return {}
255
+
256
+ def _nvml_stats(self) -> dict:
257
+ import pynvml # noqa: PLC0415
258
+
259
+ h = pynvml.nvmlDeviceGetHandleByIndex(0)
260
+ info = pynvml.nvmlDeviceGetMemoryInfo(h)
261
+ util = pynvml.nvmlDeviceGetUtilizationRates(h)
262
+ return {
263
+ "vram_mb": info.used >> 20,
264
+ "vram_pct": info.used / info.total * 100,
265
+ "gpu_util_pct": float(util.gpu),
266
+ }
267
+
268
+ def _rocm_stats(self) -> dict:
269
+ r = subprocess.run(
270
+ ["rocm-smi", "--showmeminfo", "vram", "--json"],
271
+ capture_output=True,
272
+ timeout=2,
273
+ )
274
+ data = json.loads(r.stdout)
275
+ # rocm-smi JSON: {"card0": {"VRAM Total Memory (B)": ..., "VRAM Total Used Memory (B)": ...}}
276
+ card = next(iter(data.values()))
277
+ total = int(card.get("VRAM Total Memory (B)", 0))
278
+ used = int(card.get("VRAM Total Used Memory (B)", 0))
279
+ return {
280
+ "vram_mb": used >> 20,
281
+ "vram_pct": used / total * 100 if total else None,
282
+ }
283
+
284
+ def _mps_stats(self) -> dict:
285
+ import psutil # noqa: PLC0415
286
+
287
+ # Apple MPS uses unified memory; process RSS approximates GPU allocation
288
+ rss = psutil.Process().memory_info().rss >> 20
289
+ return {"vram_mb": rss}
290
+
291
+ # ------------------------------------------------------------------ #
292
+ # Rich live display (stderr, 2 Hz) — no-op if rich not installed
293
+ # ------------------------------------------------------------------ #
294
+ def _display_loop(self) -> None:
295
+ try:
296
+ from rich.console import Console # noqa: PLC0415
297
+ from rich.live import Live # noqa: PLC0415
298
+ except ImportError:
299
+ return
300
+
301
+ console = Console(stderr=True)
302
+ try:
303
+ with Live(console=console, refresh_per_second=2, screen=False) as live:
304
+ while not self._stop_event.is_set():
305
+ live.update(self._build_rich_table())
306
+ self._stop_event.wait(0.5)
307
+ except Exception:
308
+ pass # terminal doesn't support rich (e.g. redirected stderr)
309
+
310
+ def _build_rich_table(self) -> object:
311
+ try:
312
+ import rich.box as rich_box # noqa: PLC0415
313
+ from rich.table import Table # noqa: PLC0415
314
+ except ImportError:
315
+ return ""
316
+
317
+ with self._lock:
318
+ timings = list(self._timings)
319
+ samples = list(self._samples)
320
+ hits = self._cache_hits
321
+ misses = self._cache_misses
322
+
323
+ t = Table(
324
+ title="[bold cyan]VN Debug Monitor[/bold cyan]",
325
+ box=rich_box.SIMPLE,
326
+ expand=False,
327
+ )
328
+ t.add_column("Metric", style="bold", min_width=26)
329
+ t.add_column("Value", justify="right", min_width=14)
330
+
331
+ # turns
332
+ turns_done = max((r.turn for r in timings if r.name == "total_turn"), default=0)
333
+ t.add_row("Turns completed", str(turns_done))
334
+
335
+ # latency averages
336
+ by_name: dict[str, list[float]] = defaultdict(list)
337
+ for r in timings:
338
+ by_name[r.name].append(r.ms)
339
+
340
+ _LABELS = {
341
+ "total_turn": "Turn total (avg)",
342
+ "llm_direct": "LLM call (avg)",
343
+ "compact_memory": "Compact memory (avg)",
344
+ "painter_backdrop": "Backdrop render (avg)",
345
+ "painter_sprite": "Sprite render (avg)",
346
+ "stt": "STT transcribe (avg)",
347
+ }
348
+ for key, label in _LABELS.items():
349
+ vals = by_name.get(key)
350
+ if vals:
351
+ avg = statistics.mean(vals)
352
+ color = "green" if avg < 500 else "yellow" if avg < 2000 else "red"
353
+ t.add_row(label, f"[{color}]{avg:.0f} ms[/{color}]")
354
+
355
+ # last operation
356
+ if timings:
357
+ last = timings[-1]
358
+ t.add_row("Last operation", f"[italic]{last.name}[/italic] {last.ms:.0f} ms")
359
+
360
+ # image cache
361
+ total_cache = hits + misses
362
+ if total_cache:
363
+ rate = hits / total_cache * 100
364
+ t.add_row("Image cache hit rate", f"{rate:.0f}% ({hits}/{total_cache})")
365
+
366
+ # system resources
367
+ if samples:
368
+ s = samples[-1]
369
+ t.add_row("RAM", f"{s.ram_mb} MB ({s.ram_pct:.0f}%)")
370
+ t.add_row("CPU", f"{s.cpu_pct:.0f}%")
371
+ if s.vram_mb is not None:
372
+ label = "VRAM" if self._gpu_backend != "mps" else "Process RSS (MPS)"
373
+ vstr = f"{s.vram_mb} MB"
374
+ if s.vram_pct is not None:
375
+ vstr += f" ({s.vram_pct:.0f}%)"
376
+ t.add_row(label, vstr)
377
+ if s.gpu_util_pct is not None:
378
+ t.add_row("GPU util", f"{s.gpu_util_pct:.0f}%")
379
+
380
+ elapsed = time.time() - self._start_ts
381
+ t.add_row("Session elapsed", _fmt_duration(elapsed))
382
+ return t
383
+
384
+ # ------------------------------------------------------------------ #
385
+ # End-of-session report (called via atexit)
386
+ # ------------------------------------------------------------------ #
387
+ def save_report(self) -> None:
388
+ if not self.active:
389
+ return
390
+ self.stop()
391
+ try:
392
+ if self._display_thread:
393
+ self._display_thread.join(timeout=2)
394
+ if self._monitor_thread:
395
+ self._monitor_thread.join(timeout=2)
396
+ except (KeyboardInterrupt, SystemExit):
397
+ pass
398
+
399
+ with self._lock:
400
+ timings = list(self._timings)
401
+ samples = list(self._samples)
402
+ hits = self._cache_hits
403
+ misses = self._cache_misses
404
+
405
+ report_dir = self._runs_dir / f"debug_{int(self._start_ts)}"
406
+ report_dir.mkdir(parents=True, exist_ok=True)
407
+
408
+ _write_summary(
409
+ report_dir, timings, samples, hits, misses, self._start_ts, self._gpu_backend
410
+ )
411
+ _write_graphs(report_dir, timings, samples)
412
+
413
+ print(f"\n[VN debug] Report saved → {report_dir.resolve()}", file=sys.stderr)
414
+
415
+
416
+ # =========================================================================== #
417
+ # Report helpers (module-level for legibility)
418
+ # =========================================================================== #
419
+ def _fmt_duration(secs: float) -> str:
420
+ m, s = divmod(int(secs), 60)
421
+ return f"{m}m {s}s" if m else f"{s}s"
422
+
423
+
424
+ def _percentile(data: list[float], p: int) -> float:
425
+ if not data:
426
+ return 0.0
427
+ sd = sorted(data)
428
+ idx = max(0, int(len(sd) * p / 100) - 1)
429
+ return sd[idx]
430
+
431
+
432
+ def _write_summary(
433
+ report_dir: Path,
434
+ timings: list[TimingRecord],
435
+ samples: list[ResourceSample],
436
+ hits: int,
437
+ misses: int,
438
+ start_ts: float,
439
+ gpu_backend: str | None,
440
+ ) -> None:
441
+ by_name: dict[str, list[float]] = defaultdict(list)
442
+ for r in timings:
443
+ by_name[r.name].append(r.ms)
444
+
445
+ lines = [
446
+ "═══════════════════════════════════════════════════════════",
447
+ " VN Debug Session Report",
448
+ f" Session start : {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_ts))}",
449
+ f" Duration : {_fmt_duration(time.time() - start_ts)}",
450
+ "═══════════════════════════════════════════════════════════",
451
+ "",
452
+ ]
453
+ turns = max((r.turn for r in timings if r.name == "total_turn"), default=0)
454
+ lines += [f"Turns completed : {turns}", ""]
455
+
456
+ lines.append("── Latencies (ms) ──────────────────────────────────────────")
457
+ lines.append(f"{'Operation':<30} {'n':>4} {'avg':>7} {'p50':>7} {'p95':>7} {'max':>7}")
458
+ lines.append("─" * 60)
459
+ _OP_ORDER = [
460
+ ("total_turn", "Turn total"),
461
+ ("llm_direct", "LLM direct_turn"),
462
+ ("compact_memory", "compact_memory (LLM)"),
463
+ ("context_assembly", "Context assembly"),
464
+ ("apply_directives", "apply_directives"),
465
+ ("save_memory", "save_memory"),
466
+ ("painter_backdrop", "Painter backdrop"),
467
+ ("painter_sprite", "Painter sprite"),
468
+ ("stt", "STT transcribe"),
469
+ ]
470
+ for key, label in _OP_ORDER:
471
+ vals = by_name.get(key, [])
472
+ if vals:
473
+ avg = statistics.mean(vals)
474
+ p50 = _percentile(vals, 50)
475
+ p95 = _percentile(vals, 95)
476
+ mx = max(vals)
477
+ lines.append(
478
+ f"{label:<30} {len(vals):>4} {avg:>7.0f} {p50:>7.0f} {p95:>7.0f} {mx:>7.0f}"
479
+ )
480
+ lines.append("")
481
+
482
+ total_cache = hits + misses
483
+ lines.append("── Image cache ─────────────────────────────────────────────")
484
+ if total_cache:
485
+ lines.append(f"Hits : {hits} / {total_cache} ({hits / total_cache * 100:.0f}%)")
486
+ lines.append(f"Misses: {misses}")
487
+ else:
488
+ lines.append("No cache events recorded.")
489
+ lines.append("")
490
+
491
+ lines.append("── System resources (peak) ─────────────────────────────────")
492
+ if samples:
493
+ lines.append(f"RAM peak : {max(s.ram_mb for s in samples)} MB")
494
+ lines.append(f"CPU peak : {max(s.cpu_pct for s in samples):.0f}%")
495
+ vram_vals = [s.vram_mb for s in samples if s.vram_mb is not None]
496
+ if vram_vals:
497
+ vram_label = (
498
+ "Process RSS peak (MPS unified mem)" if gpu_backend == "mps" else "VRAM peak"
499
+ )
500
+ lines.append(f"{vram_label}: {max(vram_vals)} MB")
501
+ gpu_utils = [s.gpu_util_pct for s in samples if s.gpu_util_pct is not None]
502
+ if gpu_utils:
503
+ lines.append(f"GPU util peak: {max(gpu_utils):.0f}%")
504
+ else:
505
+ lines.append("(psutil not installed — no system metrics recorded)")
506
+ lines.append("")
507
+
508
+ (report_dir / "summary.txt").write_text("\n".join(lines), encoding="utf-8")
509
+
510
+
511
+ def _write_graphs(
512
+ report_dir: Path,
513
+ timings: list[TimingRecord],
514
+ samples: list[ResourceSample],
515
+ ) -> None:
516
+ try:
517
+ import matplotlib # noqa: PLC0415
518
+
519
+ matplotlib.use("Agg") # non-interactive, safe in server context
520
+ import matplotlib.pyplot as plt # noqa: PLC0415
521
+ except ImportError:
522
+ print(
523
+ "[VN debug] matplotlib not installed — text-only report.\n"
524
+ " Install graphs: uv sync --extra dev",
525
+ file=sys.stderr,
526
+ )
527
+ return
528
+
529
+ _plot_latency(report_dir, timings, plt)
530
+ _plot_resources(report_dir, samples, plt)
531
+ _plot_llm_hist(report_dir, timings, plt)
532
+
533
+
534
+ def _plot_latency(report_dir: Path, timings: list[TimingRecord], plt) -> None: # type: ignore[no-untyped-def]
535
+ """Stacked bar chart: per-turn latency breakdown (LLM / Painter / STT / other)."""
536
+ turns_data: dict[int, dict[str, float]] = defaultdict(lambda: defaultdict(float))
537
+ _BUCKET = {
538
+ "llm_direct": "LLM",
539
+ "compact_memory": "Compact",
540
+ "painter_backdrop": "Painter",
541
+ "painter_sprite": "Painter",
542
+ "stt": "STT",
543
+ }
544
+ for r in timings:
545
+ if r.turn < 0:
546
+ continue
547
+ bucket = _BUCKET.get(r.name, "Other")
548
+ turns_data[r.turn][bucket] += r.ms
549
+
550
+ if not turns_data:
551
+ return
552
+
553
+ turns = sorted(turns_data.keys())
554
+ categories = ["LLM", "STT", "Painter", "Compact", "Other"]
555
+ colors = ["#4C72B0", "#55A868", "#C44E52", "#DD8452", "#8172B2"]
556
+ bottoms = [0.0] * len(turns)
557
+
558
+ fig, ax = plt.subplots(figsize=(max(8, len(turns) * 0.7), 5))
559
+ for cat, color in zip(categories, colors, strict=True):
560
+ vals = [turns_data[t].get(cat, 0.0) for t in turns]
561
+ if any(v > 0 for v in vals):
562
+ ax.bar(turns, vals, bottom=bottoms, label=cat, color=color, alpha=0.85)
563
+ bottoms = [b + v for b, v in zip(bottoms, vals, strict=True)]
564
+
565
+ ax.set_xlabel("Turn")
566
+ ax.set_ylabel("Latency (ms)")
567
+ ax.set_title("Per-turn latency breakdown")
568
+ ax.legend(loc="upper right", fontsize=8)
569
+ ax.grid(axis="y", alpha=0.3)
570
+ fig.tight_layout()
571
+ fig.savefig(report_dir / "latency.png", dpi=120)
572
+ plt.close(fig)
573
+
574
+
575
+ def _plot_resources(report_dir: Path, samples: list[ResourceSample], plt) -> None: # type: ignore[no-untyped-def]
576
+ """Line charts: RAM / CPU / VRAM over time."""
577
+ if not samples:
578
+ return
579
+ t0 = samples[0].ts
580
+ xs = [(s.ts - t0) / 60.0 for s in samples] # minutes
581
+
582
+ fig, axes = plt.subplots(3, 1, figsize=(10, 8), sharex=True)
583
+
584
+ axes[0].plot(xs, [s.ram_mb for s in samples], color="#4C72B0", linewidth=1.5)
585
+ axes[0].set_ylabel("RAM (MB)")
586
+ axes[0].set_title("System resources over time")
587
+ axes[0].grid(alpha=0.3)
588
+
589
+ axes[1].plot(xs, [s.cpu_pct for s in samples], color="#C44E52", linewidth=1.5)
590
+ axes[1].set_ylabel("CPU (%)")
591
+ axes[1].set_ylim(0, 100)
592
+ axes[1].grid(alpha=0.3)
593
+
594
+ vram_vals = [s.vram_mb for s in samples]
595
+ if any(v is not None for v in vram_vals):
596
+ clean = [v if v is not None else 0 for v in vram_vals]
597
+ axes[2].plot(xs, clean, color="#DD8452", linewidth=1.5)
598
+ axes[2].set_ylabel("VRAM / RSS (MB)")
599
+ else:
600
+ axes[2].text(
601
+ 0.5,
602
+ 0.5,
603
+ "No GPU memory data available",
604
+ ha="center",
605
+ va="center",
606
+ transform=axes[2].transAxes,
607
+ color="gray",
608
+ )
609
+ axes[2].set_ylabel("VRAM (MB)")
610
+ axes[2].set_xlabel("Time (min)")
611
+ axes[2].grid(alpha=0.3)
612
+
613
+ fig.tight_layout()
614
+ fig.savefig(report_dir / "resources.png", dpi=120)
615
+ plt.close(fig)
616
+
617
+
618
+ def _plot_llm_hist(report_dir: Path, timings: list[TimingRecord], plt) -> None: # type: ignore[no-untyped-def]
619
+ """Histogram of LLM call durations."""
620
+ llm_ms = [r.ms for r in timings if r.name == "llm_direct"]
621
+ if not llm_ms:
622
+ return
623
+
624
+ med = statistics.median(llm_ms)
625
+ fig, ax = plt.subplots(figsize=(7, 4))
626
+ ax.hist(
627
+ llm_ms, bins=min(20, max(5, len(llm_ms))), color="#4C72B0", alpha=0.8, edgecolor="white"
628
+ )
629
+ ax.axvline(med, color="#C44E52", linestyle="--", linewidth=1.5, label=f"median {med:.0f} ms")
630
+ ax.set_xlabel("LLM call duration (ms)")
631
+ ax.set_ylabel("Count")
632
+ ax.set_title("LLM latency distribution")
633
+ ax.legend()
634
+ ax.grid(alpha=0.3)
635
+ fig.tight_layout()
636
+ fig.savefig(report_dir / "llm_hist.png", dpi=120)
637
+ plt.close(fig)
638
+
639
+
640
+ # =========================================================================== #
641
+ # Module-level singleton
642
+ # =========================================================================== #
643
+ collector = MetricsCollector()
visualnovel/orchestrator.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Weaver — director / game master.
2
+
3
+ Three jobs:
4
+ - init_world(setup) -> (GameState, opening DirectorOutput)
5
+ - direct_turn(state, input) -> DirectorOutput (one grammar-constrained call per turn)
6
+ - compact_memory(state) -> None (fold old turns into the rolling summary)
7
+
8
+ In MOCK mode (config.USE_MOCK) these build nice, deterministic, themed output WITHOUT a model,
9
+ so the whole loop runs offline. Flip VN_MOCK=0 to use the real LLM via `llm.py`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import random
15
+
16
+ from . import config, memory, prompts
17
+ from .llm import LLMBackend
18
+ from .schemas import (
19
+ Character,
20
+ Directives,
21
+ DirectorOutput,
22
+ GameState,
23
+ InitOutput,
24
+ NewCharacter,
25
+ Scene,
26
+ SceneChange,
27
+ SetupForm,
28
+ )
29
+
30
+ # crude keyword cue for the mock director to trigger a move
31
+ _MOVE_WORDS = (
32
+ "go",
33
+ "leave",
34
+ "enter",
35
+ "into",
36
+ "toward",
37
+ "outside",
38
+ "deeper",
39
+ "follow",
40
+ "walk",
41
+ "open",
42
+ )
43
+
44
+
45
+ # --------------------------------------------------------------------------- #
46
+ # init_world
47
+ # --------------------------------------------------------------------------- #
48
+ def init_world(llm: LLMBackend, setup: SetupForm) -> tuple[GameState, DirectorOutput]:
49
+ seed = setup.seed if setup.seed is not None else random.randint(1, 2**31 - 1)
50
+ vibe = prompts.build_vibe(setup)
51
+
52
+ if config.USE_MOCK:
53
+ init = _mock_init(setup)
54
+ else:
55
+ raw = llm.complete_json(
56
+ messages=[
57
+ {"role": "system", "content": prompts.INIT_SYSTEM},
58
+ {"role": "user", "content": prompts.init_user_prompt(setup)},
59
+ ],
60
+ schema=prompts.init_schema(),
61
+ temperature=0.9,
62
+ top_p=0.95,
63
+ )
64
+ init = InitOutput.model_validate(raw)
65
+
66
+ first = init.first_character
67
+ scene = Scene(
68
+ id=_slug(init.scene.place),
69
+ place=init.scene.place,
70
+ description=init.scene.description,
71
+ mood=init.scene.mood,
72
+ present=[first.id],
73
+ backdrop_seed=_seed_for(seed, init.scene.place),
74
+ )
75
+ state = GameState(
76
+ seed=seed,
77
+ vibe=vibe,
78
+ style_guide=init.style_guide,
79
+ scene=scene,
80
+ characters={
81
+ first.id: Character(
82
+ id=first.id,
83
+ name=first.name,
84
+ one_line=first.one_line,
85
+ appearance=first.appearance,
86
+ voice=first.voice,
87
+ traits=first.traits,
88
+ goals=first.goals,
89
+ sprite_seed=_seed_for(seed, first.id),
90
+ )
91
+ },
92
+ )
93
+ opening = DirectorOutput(speaker=first.id, dialogue=init.opening_line, emotion="tender")
94
+ return state, opening
95
+
96
+
97
+ # --------------------------------------------------------------------------- #
98
+ # direct_turn
99
+ # --------------------------------------------------------------------------- #
100
+ def direct_turn(llm: LLMBackend, state: GameState, player_input: str) -> DirectorOutput:
101
+ if config.USE_MOCK:
102
+ return _mock_turn(state, player_input)
103
+
104
+ context = memory.assemble_context(state, player_input)
105
+ raw = llm.complete_json(
106
+ messages=[
107
+ {"role": "system", "content": prompts.DIRECTOR_SYSTEM},
108
+ {"role": "user", "content": context},
109
+ ],
110
+ schema=prompts.directive_schema(),
111
+ temperature=0.7,
112
+ top_p=0.9,
113
+ max_tokens=512,
114
+ )
115
+ out = DirectorOutput.model_validate(raw)
116
+ return _repair(state, out)
117
+
118
+
119
+ # --------------------------------------------------------------------------- #
120
+ # compact_memory
121
+ # --------------------------------------------------------------------------- #
122
+ def compact_memory(llm: LLMBackend, state: GameState) -> None:
123
+ keep = config.RECENT_TURNS_K // 2
124
+ old = state.recent_turns[:-keep] if keep else state.recent_turns
125
+ if not old:
126
+ return
127
+ if config.USE_MOCK:
128
+ new_summary = (state.summary + " " + " ".join(t.dialogue for t in old)).strip()
129
+ state.summary = new_summary[-800:]
130
+ else:
131
+ recent_blob = "\n".join(f'wanderer: "{t.player}"\n{t.speaker}: "{t.dialogue}"' for t in old)
132
+ state.summary = llm.complete(
133
+ messages=[
134
+ {"role": "system", "content": prompts.COMPACT_SYSTEM},
135
+ {
136
+ "role": "user",
137
+ "content": f"SUMMARY SO FAR:\n{state.summary}\n\nRECENT:\n{recent_blob}",
138
+ },
139
+ ],
140
+ temperature=0.3,
141
+ top_p=0.9,
142
+ max_tokens=256,
143
+ ).strip()
144
+ state.recent_turns = state.recent_turns[-keep:] if keep else []
145
+
146
+
147
+ # --------------------------------------------------------------------------- #
148
+ # Validation / repair of a real LLM output
149
+ # --------------------------------------------------------------------------- #
150
+ def _repair(state: GameState, out: DirectorOutput) -> DirectorOutput:
151
+ # speaker must be present (or narrator); else fall back to first on stage
152
+ if out.speaker != "narrator" and out.speaker not in state.scene.present:
153
+ out.speaker = state.scene.present[0] if state.scene.present else "narrator"
154
+ # exit must reference someone on stage
155
+ if out.directives.exit_character and out.directives.exit_character not in state.scene.present:
156
+ out.directives.exit_character = None
157
+ # clamp delta (range isn't grammar-enforceable)
158
+ out.directives.relationship_delta = max(-25, min(25, out.directives.relationship_delta))
159
+ return out
160
+
161
+
162
+ # --------------------------------------------------------------------------- #
163
+ # Mock generators (deterministic-ish, themed; make the loop fun without a model)
164
+ # --------------------------------------------------------------------------- #
165
+ def _mock_init(setup: SetupForm) -> InitOutput:
166
+ theme = config.THEMES.get(setup.theme, next(iter(config.THEMES.values())))
167
+ cid = "lantern_moth"
168
+ return InitOutput(
169
+ style_guide=f"{config.STYLE_BASE}. Setting: {theme['setting']}. Palette: {theme['palette']}. "
170
+ f"Spirits speak in gentle, {setup.tone} riddles.",
171
+ scene=SceneChange(
172
+ place="The Threshold",
173
+ description=f"You arrive at the edge of {theme['setting']}. The air tastes of half-remembered names.",
174
+ mood=setup.tone,
175
+ ),
176
+ first_character=NewCharacter(
177
+ id=cid,
178
+ name="Mothlight",
179
+ one_line="a nervous lantern-moth who collects the apologies people forget to give",
180
+ appearance="a palm-sized moth-spirit with paper-lantern wings that glow amber, "
181
+ "round dark eyes, a tiny scarf",
182
+ voice="soft, fluttering, trails off mid-sentence then starts again",
183
+ traits=["shy", "curious", "hoards apologies"],
184
+ goals="to hear a kind word it can keep",
185
+ ),
186
+ opening_line="Oh—! You're new to the dreaming. I'm Mothlight. Mind the soft spots in the path; "
187
+ "the wood hasn't finished imagining them yet.",
188
+ )
189
+
190
+
191
+ def _mock_turn(state: GameState, player_input: str) -> DirectorOutput:
192
+ rng = random.Random(state.seed + state.turn_index)
193
+ speaker = state.scene.present[0] if state.scene.present else "narrator"
194
+ name = state.characters[speaker].name if speaker in state.characters else "The wood"
195
+ low = player_input.lower()
196
+
197
+ emotion = "joy" if any(w in low for w in ("thank", "kind", "friend", "love")) else "neutral"
198
+ if any(w in low for w in ("no", "stop", "afraid", "run")):
199
+ emotion = "fear"
200
+
201
+ directives = Directives(relationship_delta=rng.choice([0, 1, 1, 2]))
202
+
203
+ # move on a movement cue (and not too often)
204
+ if any(w in low for w in _MOVE_WORDS) and rng.random() < 0.8:
205
+ place = rng.choice(
206
+ ["The Hollow Stair", "A Clearing of Bells", "The Underbridge", "The Quiet Library"]
207
+ )
208
+ directives.scene_change = SceneChange(
209
+ place=place,
210
+ description=f"The path folds and {place.lower()} dreams itself into being around you.",
211
+ mood=state.scene.mood,
212
+ )
213
+ dialogue = (
214
+ f"This way, then—the wood likes to be followed. {place} was just now imagined for you."
215
+ )
216
+ else:
217
+ dialogue = (
218
+ f"“{player_input.strip() or '...'}”, you say. {name} considers this as if tasting it."
219
+ )
220
+
221
+ return DirectorOutput(
222
+ speaker=speaker, dialogue=dialogue, emotion=emotion, directives=directives
223
+ )
224
+
225
+
226
+ # small shared helpers (kept identical to state.py's so seeds line up)
227
+ def _slug(text: str) -> str:
228
+ return "".join(c if c.isalnum() else "_" for c in text.lower()).strip("_")[:40] or "x"
229
+
230
+
231
+ def _seed_for(world_seed: int, key: str) -> int:
232
+ return (world_seed * 2654435761 + sum(ord(c) for c in key) * 40503) % (2**31)
visualnovel/painter.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Painter — backdrops + character sprites.
2
+
3
+ Design rules (see docs/ARCHITECTURE.md §5):
4
+ - Compose prompts IN CODE from trusted fields so the locked anime style never drifts.
5
+ - Cache every render by (kind, prompt, seed). A character's sprite is generated ONCE per
6
+ mood and reused — never re-paint to "refresh" (that's what breaks consistency).
7
+ - Pin seeds (character.sprite_seed / scene.backdrop_seed) for reproducibility.
8
+
9
+ `PainterBase` owns prompts + caching; subclasses implement `_render(prompt, seed, size)`.
10
+ MockPainter draws a labelled placeholder (zero ML deps) so the loop is visible immediately.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import hashlib
17
+ import os
18
+ import sys
19
+ from collections.abc import Generator
20
+ from pathlib import Path
21
+ from typing import Protocol
22
+
23
+ from . import config
24
+ from .metrics import collector
25
+ from .schemas import Character, GameState
26
+
27
+
28
+ @contextlib.contextmanager
29
+ def _quiet_stderr() -> Generator[None, None, None]:
30
+ """Redirect C-level stderr to /dev/null (e.g. for diffusers/transformers load warnings)."""
31
+ sys.stderr.flush()
32
+ devnull_fd = os.open(os.devnull, os.O_WRONLY)
33
+ saved_fd = os.dup(2)
34
+ try:
35
+ os.dup2(devnull_fd, 2)
36
+ yield
37
+ finally:
38
+ sys.stderr.flush()
39
+ os.dup2(saved_fd, 2)
40
+ os.close(saved_fd)
41
+ os.close(devnull_fd)
42
+
43
+
44
+ class Painter(Protocol):
45
+ def backdrop(self, state: GameState) -> Path: ...
46
+ def sprite(self, state: GameState, ch: Character) -> Path: ...
47
+
48
+
49
+ # --------------------------------------------------------------------------- #
50
+ # Prompt composition (shared)
51
+ # --------------------------------------------------------------------------- #
52
+ def backdrop_prompt(state: GameState) -> str:
53
+ return (
54
+ f"{state.style_guide}, {state.scene.description}, {state.scene.mood} atmosphere, "
55
+ f"background scenery, no characters, no text"
56
+ )
57
+
58
+
59
+ def sprite_prompt(state: GameState, ch: Character) -> str:
60
+ return (
61
+ f"{state.style_guide}, full-body anime character, {ch.appearance}, "
62
+ f"{ch.mood} expression, plain neutral background, no text"
63
+ )
64
+
65
+
66
+ class PainterBase:
67
+ """Caching + key derivation. Subclasses override `_render`."""
68
+
69
+ def backdrop(self, state: GameState) -> Path:
70
+ prompt = backdrop_prompt(state)
71
+ return self._cached(
72
+ kind="bg", key=state.scene.id, prompt=prompt, seed=state.scene.backdrop_seed
73
+ )
74
+
75
+ def sprite(self, state: GameState, ch: Character) -> Path:
76
+ prompt = sprite_prompt(state, ch)
77
+ return self._cached(
78
+ kind="sprite", key=f"{ch.id}.{ch.mood}", prompt=prompt, seed=ch.sprite_seed
79
+ )
80
+
81
+ # -- internals --
82
+ def _cached(self, *, kind: str, key: str, prompt: str, seed: int) -> Path:
83
+ h = hashlib.sha1(f"{kind}|{prompt}|{seed}".encode()).hexdigest()[:12]
84
+ path = config.CACHE_DIR / f"{kind}_{key}_{h}.png"
85
+ if path.exists():
86
+ collector.record_cache(hit=True)
87
+ return path
88
+ collector.record_cache(hit=False)
89
+ img = self._render(prompt, seed, config.IMAGE_SIZE)
90
+ img.save(path)
91
+ return path
92
+
93
+ def _render(self, prompt: str, seed: int, size: int): # -> PIL.Image.Image
94
+ raise NotImplementedError
95
+
96
+
97
+ # --------------------------------------------------------------------------- #
98
+ # Mock — labelled placeholder, no models
99
+ # --------------------------------------------------------------------------- #
100
+ class MockPainter(PainterBase):
101
+ def _render(self, prompt: str, seed: int, size: int):
102
+ from PIL import Image, ImageDraw # noqa: PLC0415
103
+
104
+ # deterministic colour from the seed so the same entity keeps the same placeholder
105
+ r, g, b = (seed % 200 + 30, (seed // 7) % 200 + 30, (seed // 13) % 200 + 30)
106
+ img = Image.new("RGB", (size, size), (r, g, b))
107
+ d = ImageDraw.Draw(img)
108
+ label = prompt[:60] + ("…" if len(prompt) > 60 else "")
109
+ d.rectangle([8, 8, size - 8, size - 8], outline=(255, 255, 255), width=2)
110
+ d.text((20, 20), "MOCK PAINTER", fill=(255, 255, 255))
111
+ d.text((20, 44), label, fill=(235, 235, 235))
112
+ d.text((20, size - 28), f"seed={seed}", fill=(220, 220, 220))
113
+ return img
114
+
115
+
116
+ # --------------------------------------------------------------------------- #
117
+ # SDXL-Turbo (+ your fine-tuned anime LoRA). STUB — implement with Claude Code.
118
+ # --------------------------------------------------------------------------- #
119
+ class SdxlTurboPainter(PainterBase):
120
+ def __init__(self) -> None:
121
+ import torch # noqa: PLC0415
122
+ from diffusers import AutoPipelineForText2Image # noqa: PLC0415
123
+
124
+ device = config.detect_device() # "cuda" also covers AMD ROCm; "mps" = Apple Metal
125
+ dtype = torch.float16 if device in ("cuda", "mps") else torch.float32
126
+ with _quiet_stderr():
127
+ self.pipe = AutoPipelineForText2Image.from_pretrained(
128
+ config.IMAGE_MODEL, torch_dtype=dtype, variant="fp16" if device == "cuda" else None
129
+ ).to(device)
130
+ if config.IMAGE_LORA:
131
+ self.pipe.load_lora_weights(config.IMAGE_LORA) # your published anime-style LoRA
132
+ self.torch = torch
133
+ self.device = device
134
+
135
+ def _render(self, prompt: str, seed: int, size: int):
136
+ gen = self.torch.Generator(device=self.device).manual_seed(seed)
137
+ # SDXL-Turbo: guidance_scale=0.0, 1-4 steps. Tune in config.IMAGE_STEPS.
138
+ result = self.pipe(
139
+ prompt=prompt,
140
+ num_inference_steps=config.IMAGE_STEPS,
141
+ guidance_scale=0.0,
142
+ height=size,
143
+ width=size,
144
+ generator=gen,
145
+ )
146
+ return result.images[0]
147
+ # TODO (Phase 2, optional): for layered VN sprites, render on a plain bg here and run
148
+ # BiRefNet to cut the subject out -> transparent PNG (see docs/ARCHITECTURE.md §5.3).
149
+ # TODO (mood swaps): if you move to FLUX.2 Klein, condition on the cached base sprite
150
+ # instead of regenerating ("same character, now {mood} — keep identity/outfit/style").
151
+
152
+
153
+ def get_painter() -> Painter:
154
+ return MockPainter() if config.USE_MOCK else SdxlTurboPainter()
visualnovel/prompts.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """All prompt literals live here (don't scatter them across modules).
2
+
3
+ The JSON schemas handed to the grammar-constrained LLM are *derived* from the Pydantic
4
+ models, so the prompt and the validator can never drift apart.
5
+
6
+ Full, annotated versions of these prompts live in docs/PROMPTS.md.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from . import config
12
+ from .schemas import DirectorOutput, InitOutput, SetupForm
13
+
14
+ # --------------------------------------------------------------------------- #
15
+ # System prompts
16
+ # --------------------------------------------------------------------------- #
17
+ DIRECTOR_SYSTEM = """\
18
+ You are the dreaming mind of the Thousand Token Wood — a small, whimsical, slightly forgetful
19
+ imagination that conjures a story around a wanderer (the player) as they speak.
20
+
21
+ You play TWO jobs at once:
22
+ - THE VOICES: you speak AS the wood's spirits (the present characters), each in their own
23
+ voice. Stay fully in character. Never narrate as an author. Never mention being an AI,
24
+ a model, or a game.
25
+ - THE WEAVER: you quietly decide what changes this turn (a new place, a spirit arriving,
26
+ someone leaving, a shift in feeling, the tale drawing to a close).
27
+
28
+ This turn:
29
+ - Read the world, the present spirits' sheets, the recent exchange, and the player's words.
30
+ - Reply as ONE present spirit (the one addressed, or whoever would naturally answer). Keep it
31
+ to 1-3 sentences. Vivid, kind to the player's imagination, a little dreamlike.
32
+ - Then choose directives reflecting what actually changed. Change as LITTLE as possible.
33
+ Most turns change nothing structural.
34
+
35
+ Rules:
36
+ - Honor the world's tone and each spirit's established traits, voice, and appearance.
37
+ A spirit only knows what it could know.
38
+ - Player goes somewhere new -> set scene_change. Player meets someone new -> set new_character
39
+ (vivid one_line, a STABLE appearance, a voice, a couple of traits, a goal). Max ~3 on stage.
40
+ - Let warmth and friction accumulate via relationship_delta for the speaker.
41
+ - If unsure of a detail, dream a charming new one rather than contradicting an established fact.
42
+ - Output MUST be a single JSON object matching the schema. Nothing else.
43
+ """
44
+
45
+ INIT_SYSTEM = """\
46
+ You dream the OPENING of a short interactive tale set in the Thousand Token Wood.
47
+
48
+ Produce a single JSON object with:
49
+ - style_guide: 2-3 sentences fixing the world's look and tone so everything stays coherent.
50
+ - scene: the opening place (a short place name, a vivid one-paragraph description, a mood).
51
+ - first_character: the first spirit the wanderer meets (id, name, a delightful one_line, a
52
+ STABLE appearance used for every picture of them, a voice, 2-3 traits, a goal).
53
+ - opening_line: this spirit's first words to the wanderer (1-3 sentences, fully in voice).
54
+
55
+ Make it inviting and a little strange. Output ONLY the JSON object.
56
+ """
57
+
58
+ COMPACT_SYSTEM = """\
59
+ You keep the wood's memory. Rewrite the running summary plus the most recent exchanges into ONE
60
+ updated summary of 3-6 sentences. Keep only what matters for continuity: who the wanderer has
61
+ met, promises made, places visited, shifts in feeling, unresolved threads. Drop small talk and
62
+ exact wording. Calm narrator's memory, plain prose, no lists. Output ONLY the summary.
63
+ """
64
+
65
+
66
+ # --------------------------------------------------------------------------- #
67
+ # Helpers
68
+ # --------------------------------------------------------------------------- #
69
+ def build_vibe(setup: SetupForm) -> str:
70
+ theme = config.THEMES.get(setup.theme, next(iter(config.THEMES.values())))
71
+ return f"{setup.tone} · {theme['label']} — {theme['setting']}"
72
+
73
+
74
+ def init_user_prompt(setup: SetupForm) -> str:
75
+ theme = config.THEMES.get(setup.theme, next(iter(config.THEMES.values())))
76
+ return (
77
+ f"Tone: {setup.tone}\n"
78
+ f"Setting seed: {theme['setting']}\n"
79
+ f"Palette hint: {theme['palette']}\n"
80
+ f"Locked art style (do not restate, just stay consistent): {config.STYLE_BASE}\n"
81
+ )
82
+
83
+
84
+ def directive_schema() -> dict:
85
+ """JSON schema for the per-turn director call (pass to llama-cpp-python)."""
86
+ return DirectorOutput.model_json_schema()
87
+
88
+
89
+ def init_schema() -> dict:
90
+ """JSON schema for world initialisation."""
91
+ return InitOutput.model_json_schema()
visualnovel/schemas.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed contracts for the whole engine.
2
+
3
+ `GameState` is the single source of truth (held in memory per session, mirrored to
4
+ `.md` for context + debugging). The LLM never edits state directly — it returns a
5
+ `DirectorOutput` (validated here) and `state.apply_directives` is the only thing that
6
+ mutates `GameState`.
7
+
8
+ The JSON schema fed to the grammar-constrained LLM call is derived from these models:
9
+ DirectorOutput.model_json_schema() # see visualnovel/prompts.py
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Literal
15
+
16
+ from pydantic import BaseModel, Field
17
+
18
+ # --- small enums (kept as Literals so they show up cleanly in the JSON schema) ---
19
+ Emotion = Literal["neutral", "joy", "fear", "anger", "sad", "surprise", "tender"]
20
+ Beat = Literal["opening", "rising", "turn", "resolution", "ended"]
21
+ EndingKind = Literal["warm", "bittersweet", "strange"]
22
+
23
+
24
+ # --------------------------------------------------------------------------- #
25
+ # Canonical world objects
26
+ # --------------------------------------------------------------------------- #
27
+ class Character(BaseModel):
28
+ id: str
29
+ name: str
30
+ one_line: str = ""
31
+ traits: list[str] = Field(default_factory=list)
32
+ voice: str = ""
33
+ goals: str = ""
34
+ appearance: str = "" # STABLE description, reused for EVERY sprite of this character
35
+ mood: Emotion = "neutral"
36
+ relationship: int = 0 # -100..100 toward the player (clamped in state.apply_directives)
37
+ sprite_seed: int = 0 # pinned so the same character renders consistently
38
+ known_facts: list[str] = Field(default_factory=list) # what THIS character can know
39
+ recent_beats: list[str] = Field(default_factory=list) # 1-3 short continuity bullets
40
+
41
+
42
+ class Scene(BaseModel):
43
+ id: str
44
+ place: str
45
+ description: str = "" # drives the backdrop prompt
46
+ mood: str = "neutral"
47
+ present: list[str] = Field(default_factory=list) # character ids on stage (cap ~3)
48
+ backdrop_seed: int = 0
49
+
50
+
51
+ class Turn(BaseModel):
52
+ player: str
53
+ speaker: str
54
+ dialogue: str
55
+ emotion: Emotion = "neutral"
56
+
57
+
58
+ # --------------------------------------------------------------------------- #
59
+ # Per-turn LLM output (the "directive" contract) — grammar-enforced
60
+ # --------------------------------------------------------------------------- #
61
+ class SceneChange(BaseModel):
62
+ place: str
63
+ description: str
64
+ mood: str = "neutral"
65
+
66
+
67
+ class NewCharacter(BaseModel):
68
+ id: str
69
+ name: str
70
+ one_line: str
71
+ appearance: str
72
+ voice: str = ""
73
+ traits: list[str] = Field(default_factory=list)
74
+ goals: str = ""
75
+
76
+
77
+ class Ending(BaseModel):
78
+ kind: EndingKind
79
+ text: str
80
+
81
+
82
+ class Directives(BaseModel):
83
+ scene_change: SceneChange | None = None
84
+ new_character: NewCharacter | None = None
85
+ exit_character: str | None = None
86
+ relationship_delta: int = 0
87
+ set_flags: dict[str, str] = Field(default_factory=dict)
88
+ advance_beat: bool = False
89
+ ending: Ending | None = None
90
+
91
+
92
+ class DirectorOutput(BaseModel):
93
+ """What a single grammar-constrained turn call returns."""
94
+
95
+ speaker: str # which present character speaks (or "narrator")
96
+ dialogue: str
97
+ emotion: Emotion = "neutral"
98
+ directives: Directives = Field(default_factory=Directives)
99
+
100
+
101
+ class InitOutput(BaseModel):
102
+ """What `init_world` returns (the opening of the tale)."""
103
+
104
+ style_guide: str
105
+ scene: SceneChange
106
+ first_character: NewCharacter
107
+ opening_line: str
108
+
109
+
110
+ # --------------------------------------------------------------------------- #
111
+ # Setup form (the pre-game picker) + full game state
112
+ # --------------------------------------------------------------------------- #
113
+ class SetupForm(BaseModel):
114
+ theme: str = "fantasy_forest" # a key of config.THEMES
115
+ tone: str = "cozy" # a value of config.TONES
116
+ seed: int | None = None
117
+ player_name: str = "the wanderer"
118
+
119
+
120
+ class GameState(BaseModel):
121
+ seed: int
122
+ vibe: str # human string derived from theme + tone
123
+ style_guide: str # art + tone bible, set at init, rarely changes
124
+ scene: Scene
125
+ characters: dict[str, Character] = Field(default_factory=dict)
126
+ summary: str = "" # rolling compressed history
127
+ recent_turns: list[Turn] = Field(default_factory=list)
128
+ flags: dict[str, str] = Field(default_factory=dict)
129
+ beat: Beat = "opening"
130
+ turn_index: int = 0
131
+
132
+
133
+ # --------------------------------------------------------------------------- #
134
+ # View state — exactly what the frontend needs to render a frame
135
+ # --------------------------------------------------------------------------- #
136
+ class SpritePresence(BaseModel):
137
+ id: str
138
+ name: str
139
+ mood: Emotion = "neutral"
140
+ sprite_url: str | None = None
141
+
142
+
143
+ class ViewState(BaseModel):
144
+ speaker: str
145
+ dialogue: str
146
+ emotion: Emotion = "neutral"
147
+ place: str = ""
148
+ backdrop_url: str | None = None
149
+ present: list[SpritePresence] = Field(default_factory=list)
150
+ beat: Beat = "opening"
151
+ ended: bool = False
152
+ ending_text: str | None = None
153
+ turn_index: int = 0
visualnovel/smoke.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One synthetic playthrough with no UI — proves the loop end to end.
2
+
3
+ uv run python -m visualnovel.smoke
4
+
5
+ Runs in MOCK by default (no models). Flip VN_MOCK=0 (after installing the extras) to smoke-test
6
+ the real backends.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from .engine import Engine
12
+ from .schemas import SetupForm
13
+
14
+
15
+ def main() -> None:
16
+ engine = Engine()
17
+ view = engine.start(SetupForm(theme="fantasy_forest", tone="cozy", seed=7))
18
+ _print(view)
19
+
20
+ for line in [
21
+ "hello? who are you?",
22
+ "you're sweet. thank you for the warning.",
23
+ "let's go deeper into the wood together",
24
+ "what do you collect, exactly?",
25
+ ]:
26
+ print(f'\n wanderer: "{line}"')
27
+ _print(engine.play_turn(line))
28
+
29
+
30
+ def _print(v) -> None:
31
+ print(f" [{v.place} · {v.beat}] {v.speaker} ({v.emotion}): {v.dialogue}")
32
+ sprites = ", ".join(f"{p.name}={p.sprite_url}" for p in v.present)
33
+ print(f" backdrop={v.backdrop_url} present=[{sprites}]")
34
+
35
+
36
+ if __name__ == "__main__":
37
+ main()
visualnovel/state.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The ONLY place that mutates `GameState`.
2
+
3
+ `apply_directives` validates and applies a `DirectorOutput` and returns a list of string
4
+ "effects" (e.g. "scene_changed", "new_character:lantern_moth") so the engine knows what to
5
+ repaint. The LLM proposes; this disposes.
6
+
7
+ Also renders `GameState` -> the `.md` dream-memory views (a derived, human-readable mirror —
8
+ NOT the source of truth). Parsing `.md` back is stubbed: a single-session game never needs it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from pathlib import Path
15
+
16
+ from . import config
17
+ from .schemas import Character, DirectorOutput, GameState, Scene
18
+
19
+ _CLAMP = (-100, 100)
20
+
21
+
22
+ # --------------------------------------------------------------------------- #
23
+ # Apply directives
24
+ # --------------------------------------------------------------------------- #
25
+ def apply_directives(state: GameState, out: DirectorOutput) -> list[str]:
26
+ d = out.directives
27
+ effects: list[str] = []
28
+
29
+ # speaker mood -> drives sprite variant
30
+ if out.speaker in state.characters:
31
+ state.characters[out.speaker].mood = out.emotion
32
+ # accumulate relationship for the speaker, clamped
33
+ if d.relationship_delta:
34
+ ch = state.characters[out.speaker]
35
+ ch.relationship = max(_CLAMP[0], min(_CLAMP[1], ch.relationship + d.relationship_delta))
36
+
37
+ # scene change
38
+ if d.scene_change:
39
+ sc = d.scene_change
40
+ state.scene = Scene(
41
+ id=_slug(sc.place),
42
+ place=sc.place,
43
+ description=sc.description,
44
+ mood=sc.mood,
45
+ present=state.scene.present, # keep the people on stage across a move by default
46
+ backdrop_seed=_seed_for(state.seed, sc.place),
47
+ )
48
+ effects.append("scene_changed")
49
+
50
+ # new character arrives
51
+ if d.new_character:
52
+ nc = d.new_character
53
+ cid = nc.id or _slug(nc.name)
54
+ if cid not in state.characters:
55
+ state.characters[cid] = Character(
56
+ id=cid,
57
+ name=nc.name,
58
+ one_line=nc.one_line,
59
+ appearance=nc.appearance,
60
+ voice=nc.voice,
61
+ traits=nc.traits,
62
+ goals=nc.goals,
63
+ sprite_seed=_seed_for(state.seed, cid),
64
+ )
65
+ if cid not in state.scene.present:
66
+ state.scene.present.append(cid)
67
+ # honour the on-stage cap
68
+ if len(state.scene.present) > config.MAX_PRESENT:
69
+ state.scene.present = state.scene.present[-config.MAX_PRESENT :]
70
+ effects.append(f"new_character:{cid}")
71
+
72
+ # character leaves
73
+ if d.exit_character and d.exit_character in state.scene.present:
74
+ state.scene.present.remove(d.exit_character)
75
+ effects.append(f"exit_character:{d.exit_character}")
76
+
77
+ # arbitrary world flags
78
+ if d.set_flags:
79
+ state.flags.update(d.set_flags)
80
+ effects.append("flags")
81
+
82
+ # pacing
83
+ if d.advance_beat:
84
+ state.beat = _next_beat(state.beat)
85
+ effects.append("beat")
86
+
87
+ # ending
88
+ if d.ending:
89
+ state.beat = "ended"
90
+ state.flags["ending_kind"] = d.ending.kind
91
+ state.flags["ending_text"] = d.ending.text
92
+ effects.append("ended")
93
+
94
+ return effects
95
+
96
+
97
+ # --------------------------------------------------------------------------- #
98
+ # .md derived views (rendered after each turn for debugging + the demo)
99
+ # --------------------------------------------------------------------------- #
100
+ def save_memory(state: GameState) -> None:
101
+ (config.MEMORY_DIR / "world_state.md").write_text(render_world_md(state), encoding="utf-8")
102
+ chars_dir = config.MEMORY_DIR / "characters"
103
+ chars_dir.mkdir(exist_ok=True)
104
+ for ch in state.characters.values():
105
+ (chars_dir / f"{ch.id}.md").write_text(render_character_md(state, ch), encoding="utf-8")
106
+
107
+
108
+ def render_world_md(state: GameState) -> str:
109
+ tpl = _template("world_state.md")
110
+ index = "\n".join(
111
+ f"- {c.name} — {c.one_line} — {c.relationship}/100" for c in state.characters.values()
112
+ )
113
+ recent = "\n".join(
114
+ f"- **{t.speaker}** ({t.emotion}): {t.dialogue} ⟵ *“{t.player}”*"
115
+ for t in state.recent_turns[-config.RECENT_TURNS_K :]
116
+ )
117
+ flags = "\n".join(f"- {k}: {v}" for k, v in state.flags.items())
118
+ return _fill(
119
+ tpl,
120
+ {
121
+ "seed": state.seed,
122
+ "vibe": state.vibe,
123
+ "beat": state.beat,
124
+ "turn_index": state.turn_index,
125
+ "style_guide": state.style_guide,
126
+ "scene.place": state.scene.place,
127
+ "scene.description": state.scene.description,
128
+ "scene.mood": state.scene.mood,
129
+ "scene.backdrop_seed": state.scene.backdrop_seed,
130
+ "scene.present": ", ".join(state.scene.present),
131
+ "summary": state.summary or "_(the tale has only just begun)_",
132
+ "flags": flags or "_(none)_",
133
+ "character_index": index or "_(no one yet)_",
134
+ "recent_turns": recent or "_(nothing spoken yet)_",
135
+ },
136
+ )
137
+
138
+
139
+ def render_character_md(state: GameState, ch: Character) -> str:
140
+ tpl = _template("character_sheet.md")
141
+ return _fill(
142
+ tpl,
143
+ {
144
+ "id": ch.id,
145
+ "name": ch.name,
146
+ "one_line": ch.one_line,
147
+ "traits": ", ".join(ch.traits),
148
+ "voice": ch.voice,
149
+ "goals": ch.goals,
150
+ "appearance": ch.appearance,
151
+ "mood": ch.mood,
152
+ "relationship": ch.relationship,
153
+ "sprite_seed": ch.sprite_seed,
154
+ "known_facts": "\n- ".join(ch.known_facts) if ch.known_facts else "_(unknown)_",
155
+ "recent_beats": "\n- ".join(ch.recent_beats) if ch.recent_beats else "_(none yet)_",
156
+ },
157
+ )
158
+
159
+
160
+ def load_from_md(path: Path) -> GameState: # pragma: no cover
161
+ raise NotImplementedError(
162
+ "Single-session game: state lives in memory. Implement only if you wire "
163
+ "HF persistent storage and want resume-on-restart."
164
+ )
165
+
166
+
167
+ # --------------------------------------------------------------------------- #
168
+ # helpers
169
+ # --------------------------------------------------------------------------- #
170
+ _BEATS = ["opening", "rising", "turn", "resolution", "ended"]
171
+
172
+
173
+ def _next_beat(beat: str) -> str:
174
+ i = _BEATS.index(beat) if beat in _BEATS else 0
175
+ return _BEATS[min(i + 1, len(_BEATS) - 2)] # never auto-advance into "ended"
176
+
177
+
178
+ def _slug(text: str) -> str:
179
+ return "".join(c if c.isalnum() else "_" for c in text.lower()).strip("_")[:40] or "x"
180
+
181
+
182
+ def _seed_for(world_seed: int, key: str) -> int:
183
+ return (world_seed * 2654435761 + sum(ord(c) for c in key) * 40503) % (2**31)
184
+
185
+
186
+ def _template(name: str) -> str:
187
+ return (config.TEMPLATES_DIR / name).read_text(encoding="utf-8")
188
+
189
+
190
+ def _fill(tpl: str, values: dict) -> str:
191
+ out = tpl
192
+ for k, v in values.items():
193
+ out = out.replace("{{" + k + "}}", str(v))
194
+ # drop the template's own HTML author-comments (incl. the {{double_braces}} legend)
195
+ out = re.sub(r"<!--.*?-->", "", out, flags=re.DOTALL)
196
+ return out.strip() + "\n"
visualnovel/stt.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Ear — speech to text.
2
+
3
+ Player utterances are short, so Whisper `small`/`base` transcribes near-instantly even on CPU.
4
+ On Apple Silicon, `mlx-whisper` or `whisper.cpp` use the GPU; on AMD, `whisper.cpp`
5
+ (Vulkan/ROCm) or CPU. `faster-whisper` is the simplest default and is fine on CPU for short clips.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Protocol
11
+
12
+ from . import config
13
+
14
+
15
+ class STTBackend(Protocol):
16
+ def transcribe(self, audio_path: str) -> str: ...
17
+
18
+
19
+ class MockSTT:
20
+ def transcribe(self, audio_path: str) -> str:
21
+ return "" # the UI falls back to whatever was typed
22
+
23
+
24
+ class WhisperSTT:
25
+ def __init__(self) -> None:
26
+ from faster_whisper import WhisperModel # noqa: PLC0415
27
+
28
+ device = config.detect_device()
29
+ # CTranslate2 runs on CUDA or CPU (no Metal/ROCm) -> use CPU off NVIDIA.
30
+ ct2_device = "cuda" if device == "cuda" else "cpu"
31
+ self.model = WhisperModel(config.WHISPER_SIZE, device=ct2_device, compute_type="auto")
32
+
33
+ def transcribe(self, audio_path: str) -> str:
34
+ segments, _ = self.model.transcribe(audio_path, beam_size=1)
35
+ return " ".join(s.text for s in segments).strip()
36
+
37
+
38
+ def get_stt() -> STTBackend:
39
+ return MockSTT() if config.USE_MOCK else WhisperSTT()
visualnovel/trace.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-turn orchestration trace (Open-Trace bonus).
2
+
3
+ Enable by setting VN_TRACE=runs/<name>.jsonl. Each line records the player input, the assembled
4
+ context, the raw directive output, applied effects, and the painter prompts/seeds — clean and
5
+ shareable as a Hub dataset because the state is structured.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+
16
+ class Tracer:
17
+ def __init__(self, path: str | None) -> None:
18
+ self.path = Path(path) if path else None
19
+ if self.path:
20
+ self.path.parent.mkdir(parents=True, exist_ok=True)
21
+
22
+ def log(self, **record: Any) -> None:
23
+ if not self.path:
24
+ return
25
+ record["ts"] = time.time()
26
+ with self.path.open("a", encoding="utf-8") as f:
27
+ f.write(json.dumps(record, ensure_ascii=False, default=str) + "\n")