Hermes Bot Oz commited on
Commit
e006b7a
·
unverified ·
2 Parent(s): 750a0912144ff0

Release develop → main

Browse files

DOX hierarchy + v0.7 TinyBard context-aware features + Anishinaabe aesthetic.

Co-Authored-By: Oz <oz-agent@warp.dev>

.agents/tasks/TASK.2026-06-10.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: TinyBard TTS Integration and Mood Customization
2
+
3
+ - Branch: feat/tinybard-tts-moods
4
+ - Date: 2026-06-10
5
+
6
+ ## Chain-of-Draft
7
+
8
+ 1. Initialize task file.
9
+ 2. Read TinyBard codebase.
10
+ 3. Design TTS model integration.
11
+ 4. Add mood prompts.
12
+ 5. Prefix option labels.
13
+ 6. Verify and deploy.
14
+
15
+ ####
16
+ Proceeding with implementation.
llms.txt CHANGED
@@ -1,33 +1,27 @@
1
- # Build Small Hackathon — PRD
2
- # Project Requirements Document
3
 
4
- > Three Gradio apps targeting all tracks + maximum badges + sponsor prizes.
5
- > Hack window: June 5-15, 2026. Deadline: June 15.
6
 
7
- > This file is the master PRD and stays English-only. Per-project UIs and
8
- > READMEs may use additional stylistic content for their own artifacts; this
9
- > doc does not enumerate those choices.
10
 
11
- ---
12
-
13
- ## Overview
14
 
15
  - **Name:** Build Small Hackathon 2026 — Team nbiish
16
  - **Version:** 0.7.0 — Cedar-Copper Edition (Context-Aware LLM)
17
- - **Aesthetic:** Cedar-copper visual language — sky-to-sunrise palette (water-blue → cedar → copper → sun-amber → birch-cream), biophilic motifs, sky-to-water gradient banners. Shared CSS variables live in `shared/cedar_copper_tokens.py`.
18
- - **Purpose:** Win prizes across tracks, badges, and sponsor categories by building delightful, useful AI apps that run locally.
19
- - **UX:** Gradio web apps (gr.Blocks + mount_gradio_app custom frontends), hosted on HF Spaces.
20
 
21
- ---
22
 
23
- ## Rules
24
 
25
- ### Naming & Comments
26
 
27
  - Descriptive project names: CritterCalm, FocusFriend, TinyBard
28
  - Docstrings on all public functions. Comments on non-obvious logic.
29
 
30
- ### Always
31
 
32
  - Models ≤ 32B total params per project
33
  - Gradio app hosted as HF Space
@@ -36,23 +30,21 @@
36
  - Python 3.10+ with pinned requirements
37
  - Cedar-copper aesthetic consistency across all UIs (palette tokens in `shared/cedar_copper_tokens.py`)
38
 
39
- ### Never
40
 
41
  - Cloud API calls in production path
42
  - Hardcoded secrets or API keys
43
  - Models > 32B params
44
  - Default Gradio look without customization attempt
45
 
46
- ### If
47
 
48
- - If custom frontend is feasible → use `mount_gradio_app` for Off-Brand badge
49
- - If model ≤ 4B → tag Tiny Titan eligible
50
- - If using llama.cpp runtime → tag Llama Champion
51
- - If fine-tuning is done → publish model to HF Hub
52
 
53
- ---
54
-
55
- ## Infrastructure
56
 
57
  ### Gradio 6.0 + MCP Server
58
 
@@ -70,11 +62,11 @@
70
  - Spaces managed via: `hf repos create <name> --type space --space-sdk gradio --public`.
71
  - Deploy: `git remote add hf https://huggingface.co/spaces/<user>/<space>` then `git push hf main`.
72
  - HF README metadata: `colorTo` must be one of `[red, yellow, green, blue, indigo, purple, pink, gray]` (no `emerald`/`amber`).
73
- - HF README metadata: `emoji` must match `/\p{Extended_Pictographic}/u` — only the standard emoji block is allowed; decorative Unicode glyphs (solar/astrological/typographic symbols) fail validation. Use a real emoji.
74
 
75
  ### Inference Architecture (v0.7+)
76
 
77
- - **All LLM inference** is now via the **Hugging Face Inference API** (serverless). No more local GGUF, no `llama-cpp-python` compile step.
78
  - Shared module: `shared/inference_client.py` provides `cooldown_status()`, `cooldown_active()`, `generate()`, `chat_messages()`, and `force_clear_cooldown()`.
79
  - **TinyBard model:** `meta-llama/Llama-3.2-1B-Instruct` via `featherless-ai` provider (only provider supporting this model).
80
  - **Other projects:** `Qwen/Qwen2.5-1.5B-Instruct` (free tier, fast, well-suited to chat). Override via `INFERENCE_MODEL`.
@@ -98,17 +90,26 @@
98
 
99
  ### Local Servers (optional)
100
 
101
- Local servers were used during v0.4 development for visual inspection. v0.5+ prefers iterating on the live HF Spaces (which use your HF/Modal compute credits). Local servers can still be run for dev:
 
 
 
 
102
 
103
- | Project | URL | Stack | HF Space |
104
- |---|---|---|---|
105
- | TinyBard | http://localhost:7861/ | FastAPI + Gradio Blocks | nbiish/tinybard |
106
- | FocusFriend | http://localhost:7862/ | Gradio 6.0 | nbiish/focusfriend |
107
- | CritterCalm | http://localhost:7863/ | Gradio 6.0 | nbiish/crittercalm |
 
 
108
 
109
- ---
110
 
111
- ## Projects
 
 
 
112
 
113
  ### 1. CritterCalm (Backyard AI)
114
 
@@ -130,7 +131,7 @@ Local servers were used during v0.4 development for visual inspection. v0.5+ pre
130
 
131
  ### 3. TinyBard (Thousand Token Wood + Tiny Titan + Llama Champion)
132
 
133
- - **Status:** ✅ COMPLETE. Deployed. Context-aware LLM generation verified live.
134
  - **Concept:** ≤4B LLM generates unique interactive text adventures in a CRT terminal aesthetic. Nanaboozhoo trickster narrator.
135
  - **Stack:** Llama-3.2-1B-Instruct via HF Inference API (featherless-ai provider) + procedural fallback engine
136
  - **Features Implemented:**
@@ -147,12 +148,8 @@ Local servers were used during v0.4 development for visual inspection. v0.5+ pre
147
  - **Provider:** featherless-ai (only provider supporting Llama-3.2-1B-Instruct)
148
  - **Environment Variables:** INFERENCE_MODEL=meta-llama/Llama-3.2-1B-Instruct, INFERENCE_PROVIDER=featherless-ai
149
 
150
- ---
151
-
152
  ## TODO
153
 
154
- > Keep tasks atomic and testable.
155
-
156
  ### In Progress
157
 
158
  - [ ] Test CritterCalm voice cloning pipeline end-to-end
@@ -172,8 +169,8 @@ Local servers were used during v0.4 development for visual inspection. v0.5+ pre
172
  - [x] Monorepo structure with projects/ directory + shared/ aesthetic module
173
  - [x] INTELLIGENCE.md — full hackathon landscape analysis
174
  - [x] SUBMISSION_DRAFTS.md — social posts + Field Notes drafts
175
- - [x] HF CLI installed + skills configured (`hf skills add --global`)
176
- - [x] llama-cpp-python installed (conda-forge v0.3.16) — for reference; v0.5+ uses HF Inference API
177
  - [x] Local verification: all 3 apps run on ports 7861/7862/7863
178
  - [x] TinyBard end-to-end game loop verified (start → choose → next scene)
179
  - [x] FocusFriend chat verified (user message → Pip reply)
@@ -192,58 +189,30 @@ Local servers were used during v0.4 development for visual inspection. v0.5+ pre
192
  - [x] **v0.7: Git workflow** — worktree isolation, develop→main merge, HF Space deployment
193
  - [x] **v0.7: Stale worktrees/branches cleaned up** — all merged branches deleted
194
 
195
- ---
196
-
197
- ## Short-term Goals
198
-
199
- - Record demo videos (2-3 min each) — show unique story generation, verb-based choices, context-aware narrative
200
- - Post to social media
201
- - Write Field Notes blog posts (3 — one per project)
202
- - Share agent traces for Sharing is Caring badge
203
- - Polish UIs for demo appeal
204
- - Test CritterCalm voice cloning end-to-end
205
- - Test FocusFriend all 4 modes (Chat, Focus, Breathe, Meditate) with real model
206
-
207
- ---
208
-
209
- ## Git Workflow & Development Process
210
-
211
- ### Worktree Isolation
212
-
213
- Every feature/fix is developed in an isolated git worktree:
214
- - Branch naming: `<type>/<scope>-<slug>` (e.g., `feat/tinybard-context-aware`, `fix/inference-cooldown`)
215
- - Worktree path: sibling of main repo (e.g., `../tinybard-context-aware`)
216
- - One task = one branch = one worktree. No exceptions.
217
-
218
- ### Two-Hop Merge Strategy
219
-
220
- All work follows: `feature/*` → `develop` → `main`
221
-
222
- 1. **Feature → develop**: Integrate and verify on `develop` branch
223
- 2. **Develop → main**: Only after all features merged and verified on `develop`
224
- 3. **Never skip develop**: All worktree work lands on `develop` first for cross-feature assembly
225
 
226
- ### Pre-Merge Checklist
227
 
228
- - Native ecosystem gates pass (e.g., `cargo clippy`, `tsc`, `ruff`)
229
- - Security gates pass (`gitleaks`, `detect-secrets`)
230
- - Smoke-test the change in the worktree
231
- - Ask user: "Ready to merge `<branch>` → `develop`? [diff summary]. Confirm?"
232
 
233
- ### Post-Merge Cleanup
 
 
 
 
234
 
235
- - Remove merged worktree: `git worktree remove <worktree-path>`
236
- - Delete feature branch: `git branch -d <type>/<scope>-<slug>`
237
- - Verify: `git worktree list` shows only main repo, `git branch` shows no merged-feature rows
238
 
239
- ### Current State
 
 
 
240
 
241
- - `develop` = `main` = `94d7081` (in sync)
242
- - HF remote = `94d7081` (no diff)
243
- - All stale worktrees and merged branches cleaned up
244
- - Ready for hackathon submission (June 15, 2026)
245
 
246
- ---
 
 
247
 
248
  ## Reference
249
 
@@ -261,29 +230,10 @@ All work follows: `feature/*` → `develop` → `main`
261
  - TinyBard Provider: featherless-ai (only provider supporting Llama-3.2-1B-Instruct)
262
  - TinyBard Working URL: https://router.huggingface.co/featherless-ai/v1/chat/completions
263
 
264
- ---
265
-
266
- ## Anishinaabe Solarpunk Aesthetic
267
-
268
- All three apps share a unified visual language rooted in Anishinaabe culture:
269
-
270
- ### Visual Identity
271
-
272
- - **Palette:** sky-to-sunrise — water-blue (`#1B4965`) → cedar-bark (`#3D2A2A`) → copper (`#8B3A1F`) → sun-amber (`#F2A93B`) → birch-cream (`#F5F1E8`)
273
- - **Syllabics:** Canadian Aboriginal ᐴ / ᔔ used as section framings
274
- - **Symbols:** ☼ sun · ☘ clover · ❀ florette · ◈ ◆ ◇ circuit diamonds
275
- - **Typography:** EB Garamond serif headers + Inter sans + JetBrains Mono for terminal/UI
276
- - **CRT Terminal:** Scanline effects, phosphor glow, monospace terminal for TinyBard
277
-
278
- ### Cultural Elements
279
-
280
- - **Nanaboozhoo narrator**: Trickster/transformer voice in all TinyBard LLM prompts
281
- - **Anishinaabemowin labels**: NOOSISKAAZOWIN (Health), DIBIK (Step), AADIZOOKAAN (Story), INAABANDA'IWIN (Choose)
282
- - **Biophilic motifs**: Cedar bark textures, birch cream backgrounds, water-blue accents
283
- - **Solarpunk optimism**: Technology in harmony with nature, not against it
284
 
285
- ### Implementation
286
-
287
- - **Tokens module:** `shared/cedar_copper_tokens.py` — CSS variables, color palette, typography
288
- - **TinyBard CRT:** Custom CSS with scanline animation, phosphor glow, terminal green accents
289
- - **Shared across apps**: Consistent section framings, button styles, card layouts
 
1
+ # Build Small Hackathon — DOX
 
2
 
3
+ ## Purpose
 
4
 
5
+ Three Gradio apps targeting all tracks + maximum badges + sponsor prizes. Hack window: June 5–15, 2026.
 
 
6
 
7
+ ## Ownership
 
 
8
 
9
  - **Name:** Build Small Hackathon 2026 — Team nbiish
10
  - **Version:** 0.7.0 — Cedar-Copper Edition (Context-Aware LLM)
11
+ - **Operator:** nbiish
12
+
13
+ ## Local Contracts
14
 
15
+ ### Aesthetic
16
 
17
+ Cedar-copper visual language — sky-to-sunrise palette (water-blue → cedar → copper → sun-amber → birch-cream), biophilic motifs, sky-to-water gradient banners. Shared CSS variables live in `shared/cedar_copper_tokens.py`.
18
 
19
+ ### Rules — Naming & Comments
20
 
21
  - Descriptive project names: CritterCalm, FocusFriend, TinyBard
22
  - Docstrings on all public functions. Comments on non-obvious logic.
23
 
24
+ ### Rules — Always
25
 
26
  - Models ≤ 32B total params per project
27
  - Gradio app hosted as HF Space
 
30
  - Python 3.10+ with pinned requirements
31
  - Cedar-copper aesthetic consistency across all UIs (palette tokens in `shared/cedar_copper_tokens.py`)
32
 
33
+ ### Rules — Never
34
 
35
  - Cloud API calls in production path
36
  - Hardcoded secrets or API keys
37
  - Models > 32B params
38
  - Default Gradio look without customization attempt
39
 
40
+ ### Rules — If
41
 
42
+ - Custom frontend feasible → use `mount_gradio_app` for Off-Brand badge
43
+ - Model ≤ 4B → tag Tiny Titan eligible
44
+ - Using llama.cpp runtime → tag Llama Champion
45
+ - Fine-tuning done → publish model to HF Hub
46
 
47
+ ## Work Guidance
 
 
48
 
49
  ### Gradio 6.0 + MCP Server
50
 
 
62
  - Spaces managed via: `hf repos create <name> --type space --space-sdk gradio --public`.
63
  - Deploy: `git remote add hf https://huggingface.co/spaces/<user>/<space>` then `git push hf main`.
64
  - HF README metadata: `colorTo` must be one of `[red, yellow, green, blue, indigo, purple, pink, gray]` (no `emerald`/`amber`).
65
+ - HF README metadata: `emoji` must match `/\p{Extended_Pictographic}/u` — only the standard emoji block is allowed. Use a real emoji.
66
 
67
  ### Inference Architecture (v0.7+)
68
 
69
+ - **All LLM inference** via the **Hugging Face Inference API** (serverless). No local GGUF, no `llama-cpp-python` compile step.
70
  - Shared module: `shared/inference_client.py` provides `cooldown_status()`, `cooldown_active()`, `generate()`, `chat_messages()`, and `force_clear_cooldown()`.
71
  - **TinyBard model:** `meta-llama/Llama-3.2-1B-Instruct` via `featherless-ai` provider (only provider supporting this model).
72
  - **Other projects:** `Qwen/Qwen2.5-1.5B-Instruct` (free tier, fast, well-suited to chat). Override via `INFERENCE_MODEL`.
 
90
 
91
  ### Local Servers (optional)
92
 
93
+ - TinyBard: http://localhost:7861/ — FastAPI + Gradio Blocks — nbiish/tinybard
94
+ - FocusFriend: http://localhost:7862/ — Gradio 6.0 — nbiish/focusfriend
95
+ - CritterCalm: http://localhost:7863/ — Gradio 6.0 — nbiish/crittercalm
96
+
97
+ ### Short-term Goals
98
 
99
+ - Record demo videos (2-3 min each) — show unique story generation, verb-based choices, context-aware narrative
100
+ - Post to social media
101
+ - Write Field Notes blog posts (3 — one per project)
102
+ - Share agent traces for Sharing is Caring badge
103
+ - Polish UIs for demo appeal
104
+ - Test CritterCalm voice cloning end-to-end
105
+ - Test FocusFriend all 4 modes (Chat, Focus, Breathe, Meditate) with real model
106
 
107
+ ## Verification
108
 
109
+ - All 3 apps deployed to HF Spaces and accessible
110
+ - Cooldown system active in `shared/inference_client.py`
111
+ - Cedar-copper aesthetic consistent across all UIs
112
+ - No hardcoded secrets; no cloud API calls in production path
113
 
114
  ### 1. CritterCalm (Backyard AI)
115
 
 
131
 
132
  ### 3. TinyBard (Thousand Token Wood + Tiny Titan + Llama Champion)
133
 
134
+ - **Status:** COMPLETE. Deployed. Context-aware LLM generation verified live.
135
  - **Concept:** ≤4B LLM generates unique interactive text adventures in a CRT terminal aesthetic. Nanaboozhoo trickster narrator.
136
  - **Stack:** Llama-3.2-1B-Instruct via HF Inference API (featherless-ai provider) + procedural fallback engine
137
  - **Features Implemented:**
 
148
  - **Provider:** featherless-ai (only provider supporting Llama-3.2-1B-Instruct)
149
  - **Environment Variables:** INFERENCE_MODEL=meta-llama/Llama-3.2-1B-Instruct, INFERENCE_PROVIDER=featherless-ai
150
 
 
 
151
  ## TODO
152
 
 
 
153
  ### In Progress
154
 
155
  - [ ] Test CritterCalm voice cloning pipeline end-to-end
 
169
  - [x] Monorepo structure with projects/ directory + shared/ aesthetic module
170
  - [x] INTELLIGENCE.md — full hackathon landscape analysis
171
  - [x] SUBMISSION_DRAFTS.md — social posts + Field Notes drafts
172
+ - [x] HF CLI installed + skills configured
173
+ - [x] llama-cpp-python installed — for reference; v0.5+ uses HF Inference API
174
  - [x] Local verification: all 3 apps run on ports 7861/7862/7863
175
  - [x] TinyBard end-to-end game loop verified (start → choose → next scene)
176
  - [x] FocusFriend chat verified (user message → Pip reply)
 
189
  - [x] **v0.7: Git workflow** — worktree isolation, develop→main merge, HF Space deployment
190
  - [x] **v0.7: Stale worktrees/branches cleaned up** — all merged branches deleted
191
 
192
+ ## Anishinaabe Solarpunk Aesthetic
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
+ All three apps share a unified visual language rooted in Anishinaabe culture.
195
 
196
+ ### Visual Identity
 
 
 
197
 
198
+ - **Palette:** sky-to-sunrise — water-blue (`#1B4965`) → cedar-bark (`#3D2A2A`) → copper (`#8B3A1F`) → sun-amber (`#F2A93B`) → birch-cream (`#F5F1E8`)
199
+ - **Syllabics:** Canadian Aboriginal ᐴ / ᔔ used as section framings
200
+ - **Symbols:** sun · clover · florette · circuit diamonds
201
+ - **Typography:** EB Garamond serif headers + Inter sans + JetBrains Mono for terminal/UI
202
+ - **CRT Terminal:** Scanline effects, phosphor glow, monospace terminal for TinyBard
203
 
204
+ ### Cultural Elements
 
 
205
 
206
+ - **Nanaboozhoo narrator**: Trickster/transformer voice in all TinyBard LLM prompts
207
+ - **Anishinaabemowin labels**: NOOSISKAAZOWIN (Health), DIBIK (Step), AADIZOOKAAN (Story), INAABANDA'IWIN (Choose)
208
+ - **Biophilic motifs**: Cedar bark textures, birch cream backgrounds, water-blue accents
209
+ - **Solarpunk optimism**: Technology in harmony with nature, not against it
210
 
211
+ ### Implementation
 
 
 
212
 
213
+ - **Tokens module:** `shared/cedar_copper_tokens.py` — CSS variables, color palette, typography
214
+ - **TinyBard CRT:** Custom CSS with scanline animation, phosphor glow, terminal green accents
215
+ - **Shared across apps**: Consistent section framings, button styles, card layouts
216
 
217
  ## Reference
218
 
 
230
  - TinyBard Provider: featherless-ai (only provider supporting Llama-3.2-1B-Instruct)
231
  - TinyBard Working URL: https://router.huggingface.co/featherless-ai/v1/chat/completions
232
 
233
+ ## Child DOX Index
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
 
235
+ - `projects/llms.txt` — Three hackathon Gradio apps (CritterCalm, FocusFriend, TinyBard)
236
+ - `projects/crittercalm/llms.txt` — Backyard AI pet calming app
237
+ - `projects/focusfriend/llms.txt` — Focus and mindfulness companion
238
+ - `projects/tinybard/llms.txt` — Interactive text adventure generator
239
+ - `shared/llms.txt` — Shared inference client and cedar-copper aesthetic tokens
projects/crittercalm/llms.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CritterCalm — DOX
2
+
3
+ ## Purpose
4
+
5
+ Backyard AI pet calming app. Generates calming scripts for pets using LLM inference, with optional voice cloning via OmniVoice + Kokoro TTS.
6
+
7
+ ## Ownership
8
+
9
+ - **Status:** Code complete. Deployed. HF Inference API + cooldowns wired. Voice cloning still requires local install.
10
+ - **GitHub:** github.com/nbiish/crittercalm
11
+ - **HF Space:** huggingface.co/spaces/nbiish/crittercalm
12
+ - **Standalone repo:** /Volumes/1tb-sandisk/code-external/crittercalm-repo
13
+
14
+ ## Local Contracts
15
+
16
+ - **Stack:** OmniVoice (0.6B, local optional) + Kokoro TTS (82M, local optional) + Qwen2.5-7B (default) via HF Inference API
17
+ - **Badges:** Off the Grid, Well-Tuned (TBD), Field Notes, Off-Brand
18
+ - Default model: Qwen2.5-7B (override via `CRITTERCALM_MODEL`)
19
+ - Cooldown: 12s (override via `CRITTERCALM_COOLDOWN_SECONDS`)
20
+
21
+ ## Work Guidance
22
+
23
+ - `app.py` — Main Gradio app entry point
24
+ - `content/` — Script generator and templates
25
+ - `voice_cloning/` — OmniVoice cloner
26
+ - `utils/` — Audio utilities
27
+
28
+ ## Verification
29
+
30
+ - UI renders all 3 tabs
31
+ - Script generation works with and without inference
32
+ - Voice cloning pipeline functions when local dependencies available
projects/focusfriend/llms.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FocusFriend — DOX
2
+
3
+ ## Purpose
4
+
5
+ Focus and mindfulness companion. Four modes: Chat, Focus, Breathe, Meditate. Powered by Qwen2.5-7B via HF Inference API.
6
+
7
+ ## Ownership
8
+
9
+ - **Status:** Code complete. Deployed. HF Inference API + cooldowns wired. Gradio 6 Chatbot dict-format fixed.
10
+ - **GitHub:** github.com/nbiish/focusfriend
11
+ - **HF Space:** huggingface.co/spaces/nbiish/focusfriend
12
+ - **Standalone repo:** /Volumes/1tb-sandisk/code-external/focusfriend-repo
13
+
14
+ ## Local Contracts
15
+
16
+ - **Stack:** Qwen2.5-7B (default) via HF Inference API
17
+ - **Badges:** Off-Brand (sun-amber custom theme), Field Notes, Cooldowns badge
18
+ - Default model: Qwen2.5-7B (override via `FOCUSFRIEND_MODEL`)
19
+ - Cooldown: 10s (override via `FOCUSFRIEND_COOLDOWN_SECONDS`)
20
+
21
+ ## Work Guidance
22
+
23
+ - `app.py` — Main Gradio app entry point
24
+ - `character/` — ASCII art and personality definitions
25
+ - `inference/` — LLM integration layer
26
+ - `modes/` — Chat, Focus, Breathe, Meditate mode implementations
27
+
28
+ ## Verification
29
+
30
+ - All 4 modes render and respond
31
+ - Chat produces Pip replies with correct dict format
32
+ - Cedar-copper theme renders with sun-amber accent
projects/llms.txt ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Projects — DOX
2
+
3
+ ## Purpose
4
+
5
+ Three hackathon Gradio apps, each targeting specific badges and tracks.
6
+
7
+ ## Ownership
8
+
9
+ - Each project owns its own app.py, modules, requirements, and HF Space
10
+ - Shared inference and aesthetic code lives in `shared/`
11
+
12
+ ## Local Contracts
13
+
14
+ - Each project must be deployable as an independent HF Space
15
+ - Apps inherit cedar-copper aesthetic from `shared/cedar_copper_tokens.py`
16
+ - Inference via `shared/inference_client.py` — always-fallback pattern
17
+
18
+ ## Work Guidance
19
+
20
+ - Iterate on live HF Spaces, not localhost
21
+ - Per-project model override env vars: `TINYBARD_MODEL`, `FOCUSFRIEND_MODEL`, `CRITTERCALM_MODEL`
22
+ - Per-project cooldown env vars: `TINYBARD_COOLDOWN_SECONDS`, etc.
23
+
24
+ ## Verification
25
+
26
+ - Each app deploys to its HF Space without errors
27
+ - Cooldown system active per project
28
+ - Cedar-copper aesthetic renders correctly
29
+
30
+ ## Child DOX Index
31
+
32
+ - `crittercalm/llms.txt` — Backyard AI pet calming app
33
+ - `focusfriend/llms.txt` — Focus and mindfulness companion
34
+ - `tinybard/llms.txt` — Interactive text adventure generator
projects/tinybard/app.py CHANGED
@@ -83,6 +83,203 @@ def last_inference_status() -> dict:
83
  }
84
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  # ---------------------------------------------------------------------------
87
  # Procedural Fallback Adventure Engine
88
  # ---------------------------------------------------------------------------
@@ -200,7 +397,10 @@ def _parse_messages(genre: str, history: List[Dict[str, str]], next_instruction:
200
  "Keep descriptions atmospheric but concise (2-3 sentences). "
201
  "Be unpredictable — every story beat should surprise. "
202
  "Never repeat the same scene twice. "
203
- "Focus on action, mystery, and choice. Do not offer numbered choices unless asked."
 
 
 
204
  )
205
  msgs: List[Dict[str, str]] = [{"role": "system", "content": system}]
206
 
@@ -638,6 +838,18 @@ def create_gradio_app() -> gr.Blocks:
638
  elem_classes=["asp-choices"],
639
  )
640
 
 
 
 
 
 
 
 
 
 
 
 
 
641
  # Choice text input (fallback / custom choice)
642
  with gr.Group(elem_classes=["asp-section"]):
643
  gr.HTML('<div class="asp-label">\u1434 NINDANOKIMAA / TYPE YOUR ACTION \u1514</div>')
@@ -751,24 +963,12 @@ def create_gradio_app() -> gr.Blocks:
751
  genre = (genre or "fantasy").lower()
752
  if genre not in ["fantasy", "scifi", "cyberpunk"]:
753
  genre = "fantasy"
754
-
755
- instruction = "Narrate the beginning of the adventure. What happens first? Do not offer choices yet."
756
- story = generate_llm_story(genre, [], instruction)
757
- if not story:
758
- result = generate_procedural_step(genre, 0, 100)
759
- return (
760
- result["story"], result["choices"], result["health"],
761
- result["step"], result["game_over"],
762
- json.dumps(result.get("history", []))
763
- )
764
-
765
- history = [{"role": "narrator", "text": story}]
766
- choices = generate_llm_choices(genre, story, history)
767
- if len(choices) < 2:
768
- fallback = generate_procedural_step(genre, 0, 100)
769
- choices = fallback["choices"]
770
-
771
- return (story, choices[:3], 100, 1, False, json.dumps(history))
772
 
773
  def api_make_choice(choice: str, genre: str, step: int, health: int, history_json: str):
774
  """Submit a player choice to advance the story. Exposed as MCP tool."""
@@ -777,44 +977,12 @@ def create_gradio_app() -> gr.Blocks:
777
  history = json.loads(history_json)
778
  except Exception:
779
  history = []
780
-
781
- step = int(step or 0)
782
- health = int(health or 100)
783
-
784
- history.append({"role": "player", "text": choice})
785
-
786
- health_delta = _llm_health_delta(genre, choice, history)
787
- new_health = max(0, min(100, health + health_delta))
788
-
789
- if new_health <= 0:
790
- instruction = "The player has run out of health. Narrate a quick, dramatic end. Game Over."
791
- story = generate_llm_story(genre, history, instruction)
792
- return (
793
- story or "Your strength fails. The adventure ends in darkness.",
794
- [], 0, step + 1, True, json.dumps(history)
795
- )
796
-
797
- instruction = (
798
- f"The player chose: '{choice}'. "
799
- "Narrate what happens next as a direct consequence of this action. "
800
- "Be specific to their choice — reference what they did and its immediate result."
801
  )
802
- story = generate_llm_story(genre, history, instruction)
803
- if not story:
804
- result = generate_procedural_step(genre, step, health, choice)
805
- return (
806
- result["story"], result["choices"], result["health"],
807
- result["step"], result["game_over"],
808
- json.dumps(result.get("history", history))
809
- )
810
-
811
- history.append({"role": "narrator", "text": story})
812
-
813
- choices = generate_llm_choices(genre, story, history)
814
- if len(choices) < 2:
815
- choices = ["Move forward", "Look around", "Rest a moment"]
816
-
817
- return (story, choices[:3], new_health, step + 1, False, json.dumps(history))
818
 
819
  # Helper: resolve choice from radio or text input
820
  def resolve_choice(choice_text, choice_radio_val):
@@ -832,21 +1000,21 @@ def create_gradio_app() -> gr.Blocks:
832
  return (
833
  "Please type or select a choice before making your move.",
834
  gr.update(), 100, 0, False, "[]",
835
- "", gr.update()
836
  )
837
- story, choices, h, s, go, hist = api_make_choice(resolved, genre, step, health, history_json)
838
- return story, choices, h, s, go, hist, "", gr.update(choices=choices or [], value=None)
839
 
840
  # Start Game: call api_start_game, clear choice input, update radio
841
  def handle_start_game(genre):
842
- story, choices, h, s, go, hist = api_start_game(genre)
843
- return story, choices, h, s, go, hist, "", gr.update(choices=choices or [], value=None)
844
 
845
  # UI start game button: also updates choices radio and clears text
846
  start_btn.click(
847
  fn=handle_start_game,
848
  inputs=[genre_input],
849
- outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output, choice_text_input, choice_radio],
850
  api_name="start_game",
851
  )
852
 
@@ -854,7 +1022,7 @@ def create_gradio_app() -> gr.Blocks:
854
  choice_btn.click(
855
  fn=handle_make_choice,
856
  inputs=[choice_text_input, choice_radio, genre_input, step_input, health_input, history_input],
857
- outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output, choice_text_input, choice_radio],
858
  api_name="make_choice",
859
  )
860
 
@@ -899,7 +1067,7 @@ def create_gradio_app() -> gr.Blocks:
899
  def handle_load(slot_name):
900
  import urllib.request
901
  if not slot_name or not slot_name.strip():
902
- return "Enter a slot name to load.", gr.update(), 100, 0, False, "[]", ""
903
  try:
904
  payload = json.dumps({"slot_name": slot_name.strip()}).encode()
905
  req = urllib.request.Request(
@@ -911,7 +1079,7 @@ def create_gradio_app() -> gr.Blocks:
911
  with urllib.request.urlopen(req) as resp:
912
  result = json.loads(resp.read())
913
  if result.get("status") != "ok":
914
- return f"Load failed: {result.get('message', 'Unknown error')}", gr.update(), 100, 0, False, "[]", ""
915
  choices = result.get("choices", [])
916
  history = result.get("history", [])
917
  story = ""
@@ -928,14 +1096,15 @@ def create_gradio_app() -> gr.Blocks:
928
  result.get("game_over", False),
929
  json.dumps(history),
930
  f"Loaded '{result.get('slot_name', slot_name)}'",
 
931
  )
932
  except Exception as e:
933
- return f"Load failed: {e}", gr.update(), 100, 0, False, "[]", ""
934
 
935
  load_btn.click(
936
  fn=handle_load,
937
  inputs=[save_slot_input],
938
- outputs=[story_output, choice_radio, health_output, step_output, game_over_output, history_input, save_status],
939
  )
940
 
941
  return blocks
@@ -1055,53 +1224,116 @@ def _llm_health_delta(genre: str, choice: str, history: List[Dict]) -> int:
1055
 
1056
  def _run_turn(choice: str, genre: str, step: int, health: int, history: List[Dict]) -> dict:
1057
  """Single source of truth for one adventure turn."""
 
 
 
1058
  if step == 0:
1059
  instruction = "Narrate the beginning of the adventure. What happens first? Do not offer choices yet."
1060
  story = generate_llm_story(genre, [], instruction)
1061
  if not story:
1062
- return generate_procedural_step(genre, 0, 100)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1063
  history = [{"role": "narrator", "text": story}]
1064
  choices = generate_llm_choices(genre, story, history)
1065
  if len(choices) < 2:
1066
  choices = ["Explore the area", "Check your equipment", "Proceed carefully"]
 
 
 
 
 
1067
  return {
1068
- "story": story, "choices": choices[:3], "health": 100,
1069
- "step": 1, "game_over": False, "history": history,
 
 
 
 
1070
  "genre": genre,
 
 
1071
  }
1072
 
1073
- history.append({"role": "player", "text": choice})
 
1074
 
1075
  # Health delta: ask LLM for consequence, fall back to procedural
1076
- health_delta = _llm_health_delta(genre, choice, history)
1077
  new_health = max(0, min(100, health + health_delta))
1078
 
1079
  if new_health <= 0:
1080
  instruction = "The player has run out of health. Narrate a quick, dramatic end. Game Over."
1081
  story = generate_llm_story(genre, history, instruction)
 
 
 
1082
  return {
1083
- "story": story or "Your strength fails. The adventure ends in darkness.",
1084
- "choices": [], "health": 0, "step": step + 1, "game_over": True,
1085
- "history": history, "genre": genre,
 
 
 
 
 
 
1086
  }
1087
 
1088
  instruction = (
1089
- f"The player chose: '{choice}'. "
1090
  "Narrate what happens next as a direct consequence of this action. "
1091
  "Be specific to their choice — reference what they did and its immediate result."
1092
  )
1093
  story = generate_llm_story(genre, history, instruction)
1094
  if not story:
1095
- return generate_procedural_step(genre, step, health, choice)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1096
  history.append({"role": "narrator", "text": story})
1097
 
1098
  choices = generate_llm_choices(genre, story, history)
1099
  if len(choices) < 2:
1100
  choices = ["Move forward", "Look around", "Rest a moment"]
 
 
 
 
 
1101
  return {
1102
- "story": story, "choices": choices[:3], "health": new_health,
1103
- "step": step + 1, "game_over": False, "history": history,
 
 
 
 
1104
  "genre": genre,
 
 
1105
  }
1106
 
1107
 
 
83
  }
84
 
85
 
86
+ def strip_option_prefix(choice: str) -> str:
87
+ """Strip 'Option one: ', 'Option 1: ', etc. prefixes from choice text."""
88
+ import re
89
+ cleaned = re.sub(r"^(option\s+(one|two|three|\d+)[\s:\-]*)\s*", "", choice, flags=re.IGNORECASE)
90
+ return cleaned.strip()
91
+
92
+
93
+ def get_kokoro_model_paths():
94
+ """Download (if not cached) and return paths to Kokoro ONNX model and voices bin."""
95
+ from huggingface_hub import hf_hub_download
96
+ repo_id = "fastrtc/kokoro-onnx"
97
+ try:
98
+ onnx_path = hf_hub_download(repo_id=repo_id, filename="kokoro-v1.0.onnx")
99
+ voices_path = hf_hub_download(repo_id=repo_id, filename="voices-v1.0.bin")
100
+ return onnx_path, voices_path
101
+ except Exception as e:
102
+ log.error(f"Failed to download/load Kokoro model from Hugging Face: {e}")
103
+ return None, None
104
+
105
+
106
+ _kokoro_client = None
107
+
108
+
109
+ def get_kokoro_client():
110
+ global _kokoro_client
111
+ if _kokoro_client is not None:
112
+ return _kokoro_client
113
+
114
+ try:
115
+ import pathlib
116
+ import ctypes
117
+ import espeakng_loader
118
+ from phonemizer.backend.espeak.wrapper import EspeakWrapper
119
+
120
+ # 1. Patch set_data_path
121
+ if not hasattr(EspeakWrapper, "set_data_path"):
122
+ @classmethod
123
+ def set_data_path(cls, path):
124
+ cls._data_path = pathlib.Path(path) if path else None
125
+ EspeakWrapper.set_data_path = set_data_path
126
+
127
+ # 2. Patch ctypes.cdll.LoadLibrary globally to fix espeak_Initialize NULL crash on macOS
128
+ if not hasattr(ctypes.cdll, "_orig_load_library"):
129
+ orig_load = ctypes.cdll.LoadLibrary
130
+ ctypes.cdll._orig_load_library = orig_load
131
+
132
+ def patched_load_library(path, *args, **kwargs):
133
+ lib = orig_load(path, *args, **kwargs)
134
+ if "libespeak-ng" in str(path) or "espeak" in str(path):
135
+ orig_initialize = lib.espeak_Initialize
136
+ def patched_initialize(output, buflength, path_arg, options):
137
+ if not path_arg:
138
+ d_path = espeakng_loader.get_data_path()
139
+ path_arg = d_path.encode('utf-8')
140
+ return orig_initialize(output, buflength, path_arg, options)
141
+ lib.espeak_Initialize = patched_initialize
142
+ return lib
143
+ ctypes.cdll.LoadLibrary = patched_load_library
144
+
145
+ except Exception as patch_err:
146
+ log.warning(f"Failed to patch phonemizer/ctypes: {patch_err}")
147
+
148
+ onnx_path, voices_path = get_kokoro_model_paths()
149
+ if not onnx_path or not voices_path:
150
+ log.warning("Kokoro model files are not available.")
151
+ return None
152
+
153
+ try:
154
+ from kokoro_onnx import Kokoro
155
+ _kokoro_client = Kokoro(onnx_path, voices_path)
156
+ log.info("Kokoro TTS successfully initialized for TinyBard ✓")
157
+ return _kokoro_client
158
+ except Exception as e:
159
+ log.error(f"Failed to initialize Kokoro client: {e}")
160
+ return None
161
+
162
+ def cleanup_old_audio(audio_dir: Path, max_age_seconds: int = 300):
163
+ """Delete audio files older than max_age_seconds to save disk space."""
164
+ import time
165
+ try:
166
+ now = time.time()
167
+ for f in audio_dir.glob("*.wav"):
168
+ if f.is_file() and (now - f.stat().st_mtime) > max_age_seconds:
169
+ try:
170
+ f.unlink()
171
+ except Exception:
172
+ pass
173
+ except Exception as e:
174
+ log.warning(f"Error during audio cleanup: {e}")
175
+
176
+
177
+ MOOD_MAPPING = {
178
+ "cutesy": {"voice": "af_nicole", "speed": 1.1},
179
+ "fun": {"voice": "af_heart", "speed": 1.05},
180
+ "adventurous": {"voice": "af_sarah", "speed": 1.0},
181
+ "mystery": {"voice": "af_bella", "speed": 0.85},
182
+ "sci-fi": {"voice": "am_michael", "speed": 0.95},
183
+ "cyberpunk": {"voice": "am_michael", "speed": 1.05},
184
+ }
185
+
186
+
187
+ def clean_tts_text(text: str) -> str:
188
+ cleaned = text.replace("*", "").replace("_", "").replace("`", "")
189
+ import re
190
+ cleaned = re.sub(r"\[MOOD:\s*[^\]]+\]", "", cleaned, flags=re.IGNORECASE)
191
+ return cleaned.strip()
192
+
193
+
194
+ def generate_tts_for_turn(story_text: str, choices: List[str], genre: str) -> tuple[Optional[str], Optional[str]]:
195
+ """
196
+ Generate TTS audio for the given story and choices.
197
+ Returns (relative_url, local_filepath) or (None, None) if failed.
198
+ """
199
+ import uuid
200
+ import numpy as np
201
+ import soundfile as sf
202
+ import re
203
+
204
+ audio_dir = STATIC_DIR / "audio"
205
+ audio_dir.mkdir(parents=True, exist_ok=True)
206
+ cleanup_old_audio(audio_dir)
207
+
208
+ kokoro = get_kokoro_client()
209
+ if not kokoro:
210
+ log.warning("Kokoro client not initialized, skipping TTS generation.")
211
+ return None, None
212
+
213
+ mood_match = re.search(r"\[MOOD:\s*([a-zA-Z0-9_\-]+)\]", story_text)
214
+ if mood_match:
215
+ mood = mood_match.group(1).lower()
216
+ else:
217
+ if genre == "cyberpunk":
218
+ mood = "cyberpunk"
219
+ elif genre == "scifi":
220
+ mood = "sci-fi"
221
+ elif genre == "fantasy":
222
+ mood = "adventurous"
223
+ else:
224
+ mood = "fun"
225
+
226
+ clean_story = re.sub(r"\[MOOD:\s*[a-zA-Z0-9_\-]+\]", "", story_text).strip()
227
+ clean_story = clean_tts_text(clean_story)
228
+
229
+ script_parts = [clean_story]
230
+
231
+ prefixed_choices_text = []
232
+ prefixes = ["Option one", "Option two", "Option three"]
233
+ for i, choice in enumerate(choices[:3]):
234
+ clean_choice = strip_option_prefix(choice)
235
+ prefixed_choices_text.append(f"{prefixes[i]}: {clean_choice}")
236
+
237
+ if prefixed_choices_text:
238
+ script_parts.append(" ".join(prefixed_choices_text))
239
+
240
+ full_script = "\n\n".join(script_parts)
241
+ log.info(f"Generating TTS for mood '{mood}':\n{full_script}")
242
+
243
+ mood_config = MOOD_MAPPING.get(mood, {"voice": "af_sarah", "speed": 1.0})
244
+ voice = mood_config["voice"]
245
+ speed = mood_config["speed"]
246
+
247
+ try:
248
+ sentences = []
249
+ for p in full_script.split("\n\n"):
250
+ for s in p.split("."):
251
+ s_strip = s.strip()
252
+ if s_strip:
253
+ sentences.append(s_strip + ".")
254
+
255
+ chunks = []
256
+ sample_rate = 24000
257
+ for i, sentence in enumerate(sentences):
258
+ samples, sr = kokoro.create(
259
+ text=sentence,
260
+ voice=voice,
261
+ speed=speed,
262
+ lang="en-us"
263
+ )
264
+ chunks.append(samples)
265
+ sample_rate = sr
266
+
267
+ if not chunks:
268
+ return None, None
269
+
270
+ audio_data = np.concatenate(chunks)
271
+
272
+ filename = f"turn_{uuid.uuid4().hex}.wav"
273
+ output_path = audio_dir / filename
274
+ sf.write(str(output_path), audio_data, sample_rate)
275
+
276
+ log.info(f"TTS generated successfully: {output_path}")
277
+ return f"/static/audio/{filename}", str(output_path)
278
+ except Exception as e:
279
+ log.exception(f"Failed to generate TTS audio: {e}")
280
+ return None, None
281
+
282
+
283
  # ---------------------------------------------------------------------------
284
  # Procedural Fallback Adventure Engine
285
  # ---------------------------------------------------------------------------
 
397
  "Keep descriptions atmospheric but concise (2-3 sentences). "
398
  "Be unpredictable — every story beat should surprise. "
399
  "Never repeat the same scene twice. "
400
+ "Focus on action, mystery, and choice. Do not offer numbered choices unless asked. "
401
+ "At the very end of your response, append a single tag indicating the mood of this scene "
402
+ "from one of these: [MOOD: cutesy], [MOOD: adventurous], [MOOD: mystery], [MOOD: sci-fi], [MOOD: cyberpunk], [MOOD: fun]. "
403
+ "Choose the mood that best fits the scene. Example: 'You step into the dark corridor. [MOOD: mystery]'"
404
  )
405
  msgs: List[Dict[str, str]] = [{"role": "system", "content": system}]
406
 
 
838
  elem_classes=["asp-choices"],
839
  )
840
 
841
+ # Audio Player (auto-plays TTS if available)
842
+ with gr.Group(elem_classes=["asp-section"]):
843
+ gr.HTML('<div class="asp-label">\u1434 AADIZOOKAAN-MADWEEWEBINIGAN / AUDIO NARRATOR \u1514</div>')
844
+ audio_output = gr.Audio(
845
+ label=None,
846
+ show_label=False,
847
+ autoplay=True, # Automatically plays on updates
848
+ interactive=False,
849
+ type="filepath",
850
+ elem_classes=["asp-audio"],
851
+ )
852
+
853
  # Choice text input (fallback / custom choice)
854
  with gr.Group(elem_classes=["asp-section"]):
855
  gr.HTML('<div class="asp-label">\u1434 NINDANOKIMAA / TYPE YOUR ACTION \u1514</div>')
 
963
  genre = (genre or "fantasy").lower()
964
  if genre not in ["fantasy", "scifi", "cyberpunk"]:
965
  genre = "fantasy"
966
+ res = _run_turn(choice="", genre=genre, step=0, health=100, history=[])
967
+ return (
968
+ res["story"], res["choices"], res["health"],
969
+ res["step"], res["game_over"], json.dumps(res["history"]),
970
+ res.get("audio_path")
971
+ )
 
 
 
 
 
 
 
 
 
 
 
 
972
 
973
  def api_make_choice(choice: str, genre: str, step: int, health: int, history_json: str):
974
  """Submit a player choice to advance the story. Exposed as MCP tool."""
 
977
  history = json.loads(history_json)
978
  except Exception:
979
  history = []
980
+ res = _run_turn(choice=choice, genre=genre, step=step, health=health, history=history)
981
+ return (
982
+ res["story"], res["choices"], res["health"],
983
+ res["step"], res["game_over"], json.dumps(res["history"]),
984
+ res.get("audio_path")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
985
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986
 
987
  # Helper: resolve choice from radio or text input
988
  def resolve_choice(choice_text, choice_radio_val):
 
1000
  return (
1001
  "Please type or select a choice before making your move.",
1002
  gr.update(), 100, 0, False, "[]",
1003
+ "", gr.update(), None
1004
  )
1005
+ story, choices, h, s, go, hist, audio_path = api_make_choice(resolved, genre, step, health, history_json)
1006
+ return story, choices, h, s, go, hist, "", gr.update(choices=choices or [], value=None), audio_path
1007
 
1008
  # Start Game: call api_start_game, clear choice input, update radio
1009
  def handle_start_game(genre):
1010
+ story, choices, h, s, go, hist, audio_path = api_start_game(genre)
1011
+ return story, choices, h, s, go, hist, "", gr.update(choices=choices or [], value=None), audio_path
1012
 
1013
  # UI start game button: also updates choices radio and clears text
1014
  start_btn.click(
1015
  fn=handle_start_game,
1016
  inputs=[genre_input],
1017
+ outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output, choice_text_input, choice_radio, audio_output],
1018
  api_name="start_game",
1019
  )
1020
 
 
1022
  choice_btn.click(
1023
  fn=handle_make_choice,
1024
  inputs=[choice_text_input, choice_radio, genre_input, step_input, health_input, history_input],
1025
+ outputs=[story_output, choices_output, health_output, step_output, game_over_output, history_output, choice_text_input, choice_radio, audio_output],
1026
  api_name="make_choice",
1027
  )
1028
 
 
1067
  def handle_load(slot_name):
1068
  import urllib.request
1069
  if not slot_name or not slot_name.strip():
1070
+ return "Enter a slot name to load.", gr.update(), 100, 0, False, "[]", "", None
1071
  try:
1072
  payload = json.dumps({"slot_name": slot_name.strip()}).encode()
1073
  req = urllib.request.Request(
 
1079
  with urllib.request.urlopen(req) as resp:
1080
  result = json.loads(resp.read())
1081
  if result.get("status") != "ok":
1082
+ return f"Load failed: {result.get('message', 'Unknown error')}", gr.update(), 100, 0, False, "[]", "", None
1083
  choices = result.get("choices", [])
1084
  history = result.get("history", [])
1085
  story = ""
 
1096
  result.get("game_over", False),
1097
  json.dumps(history),
1098
  f"Loaded '{result.get('slot_name', slot_name)}'",
1099
+ None,
1100
  )
1101
  except Exception as e:
1102
+ return f"Load failed: {e}", gr.update(), 100, 0, False, "[]", "", None
1103
 
1104
  load_btn.click(
1105
  fn=handle_load,
1106
  inputs=[save_slot_input],
1107
+ outputs=[story_output, choice_radio, health_output, step_output, game_over_output, history_input, save_status, audio_output],
1108
  )
1109
 
1110
  return blocks
 
1224
 
1225
  def _run_turn(choice: str, genre: str, step: int, health: int, history: List[Dict]) -> dict:
1226
  """Single source of truth for one adventure turn."""
1227
+ import re
1228
+ prefixes = ["Option one", "Option two", "Option three"]
1229
+
1230
  if step == 0:
1231
  instruction = "Narrate the beginning of the adventure. What happens first? Do not offer choices yet."
1232
  story = generate_llm_story(genre, [], instruction)
1233
  if not story:
1234
+ res = generate_procedural_step(genre, 0, 100)
1235
+ formatted_choices = [f"{prefixes[i]}: {strip_option_prefix(ch)}" for i, ch in enumerate(res["choices"][:3])]
1236
+ audio_url, audio_path = generate_tts_for_turn(res["story"], formatted_choices, genre)
1237
+ return {
1238
+ "story": res["story"],
1239
+ "choices": formatted_choices,
1240
+ "health": 100,
1241
+ "step": 1,
1242
+ "game_over": False,
1243
+ "history": res.get("history", []),
1244
+ "genre": genre,
1245
+ "audio_url": audio_url,
1246
+ "audio_path": audio_path,
1247
+ }
1248
+
1249
  history = [{"role": "narrator", "text": story}]
1250
  choices = generate_llm_choices(genre, story, history)
1251
  if len(choices) < 2:
1252
  choices = ["Explore the area", "Check your equipment", "Proceed carefully"]
1253
+
1254
+ formatted_choices = [f"{prefixes[i]}: {strip_option_prefix(ch)}" for i, ch in enumerate(choices[:3])]
1255
+ audio_url, audio_path = generate_tts_for_turn(story, formatted_choices, genre)
1256
+ clean_story = re.sub(r"\[MOOD:\s*[a-zA-Z0-9_\-]+\]", "", story).strip()
1257
+
1258
  return {
1259
+ "story": clean_story,
1260
+ "choices": formatted_choices,
1261
+ "health": 100,
1262
+ "step": 1,
1263
+ "game_over": False,
1264
+ "history": history,
1265
  "genre": genre,
1266
+ "audio_url": audio_url,
1267
+ "audio_path": audio_path,
1268
  }
1269
 
1270
+ clean_choice = strip_option_prefix(choice)
1271
+ history.append({"role": "player", "text": clean_choice})
1272
 
1273
  # Health delta: ask LLM for consequence, fall back to procedural
1274
+ health_delta = _llm_health_delta(genre, clean_choice, history)
1275
  new_health = max(0, min(100, health + health_delta))
1276
 
1277
  if new_health <= 0:
1278
  instruction = "The player has run out of health. Narrate a quick, dramatic end. Game Over."
1279
  story = generate_llm_story(genre, history, instruction)
1280
+ final_story = story or "Your strength fails. The adventure ends in darkness."
1281
+ audio_url, audio_path = generate_tts_for_turn(final_story, [], genre)
1282
+ clean_story = re.sub(r"\[MOOD:\s*[a-zA-Z0-9_\-]+\]", "", final_story).strip()
1283
  return {
1284
+ "story": clean_story,
1285
+ "choices": [],
1286
+ "health": 0,
1287
+ "step": step + 1,
1288
+ "game_over": True,
1289
+ "history": history,
1290
+ "genre": genre,
1291
+ "audio_url": audio_url,
1292
+ "audio_path": audio_path,
1293
  }
1294
 
1295
  instruction = (
1296
+ f"The player chose: '{clean_choice}'. "
1297
  "Narrate what happens next as a direct consequence of this action. "
1298
  "Be specific to their choice — reference what they did and its immediate result."
1299
  )
1300
  story = generate_llm_story(genre, history, instruction)
1301
  if not story:
1302
+ res = generate_procedural_step(genre, step, health, clean_choice)
1303
+ formatted_choices = [f"{prefixes[i]}: {strip_option_prefix(ch)}" for i, ch in enumerate(res["choices"][:3])]
1304
+ audio_url, audio_path = generate_tts_for_turn(res["story"], formatted_choices, genre)
1305
+ return {
1306
+ "story": res["story"],
1307
+ "choices": formatted_choices,
1308
+ "health": res["health"],
1309
+ "step": res["step"],
1310
+ "game_over": res["game_over"],
1311
+ "history": res.get("history", history),
1312
+ "genre": genre,
1313
+ "audio_url": audio_url,
1314
+ "audio_path": audio_path,
1315
+ }
1316
+
1317
  history.append({"role": "narrator", "text": story})
1318
 
1319
  choices = generate_llm_choices(genre, story, history)
1320
  if len(choices) < 2:
1321
  choices = ["Move forward", "Look around", "Rest a moment"]
1322
+
1323
+ formatted_choices = [f"{prefixes[i]}: {strip_option_prefix(ch)}" for i, ch in enumerate(choices[:3])]
1324
+ audio_url, audio_path = generate_tts_for_turn(story, formatted_choices, genre)
1325
+ clean_story = re.sub(r"\[MOOD:\s*[a-zA-Z0-9_\-]+\]", "", story).strip()
1326
+
1327
  return {
1328
+ "story": clean_story,
1329
+ "choices": formatted_choices,
1330
+ "health": new_health,
1331
+ "step": step + 1,
1332
+ "game_over": False,
1333
+ "history": history,
1334
  "genre": genre,
1335
+ "audio_url": audio_url,
1336
+ "audio_path": audio_path,
1337
  }
1338
 
1339
 
projects/tinybard/llms.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TinyBard — DOX
2
+
3
+ ## Purpose
4
+
5
+ Interactive text adventure generator. ≤4B LLM generates 5-min adventures in a CRT terminal aesthetic. Targets Tiny Titan + Llama Champion badges.
6
+
7
+ ## Ownership
8
+
9
+ - **Status:** Code complete. Deployed. HF Inference API + cooldowns wired. Local test verified.
10
+ - **GitHub:** github.com/nbiish/tinybard
11
+ - **HF Space:** huggingface.co/spaces/nbiish/tinybard
12
+
13
+ ## Local Contracts
14
+
15
+ - **Stack:** Qwen2.5-1.5B (default) via HF Inference API + procedural fallback engine
16
+ - **Badges:** Thousand Token Wood, Tiny Titan, Llama Champion
17
+ - Default model: Qwen2.5-1.5B (override via `TINYBARD_MODEL`)
18
+ - Cooldown: 6s (override via `TINYBARD_COOLDOWN_SECONDS`)
19
+
20
+ ## Work Guidance
21
+
22
+ - `app.py` — Main Gradio app entry point
23
+ - `static/` — Custom CRT terminal HTML/CSS/JS frontend
24
+ - Procedural fallback engine generates adventures when inference unavailable
25
+ - Game loop: start → choose → next scene
26
+
27
+ ## Verification
28
+
29
+ - End-to-end game loop works (start → choose → next scene)
30
+ - Procedural fallback generates content when no HF_TOKEN
31
+ - Cooldown UI shows in footer
32
+ - CRT terminal aesthetic renders correctly
projects/tinybard/static/main.js CHANGED
@@ -18,6 +18,17 @@ let gameState = {
18
  saveSlot: null
19
  };
20
 
 
 
 
 
 
 
 
 
 
 
 
21
  // ---------------------------------------------------------------------------
22
  // DOM refs
23
  // ---------------------------------------------------------------------------
@@ -148,6 +159,10 @@ async function startGame(genre) {
148
  storyEl.textContent = data.story;
149
  output.appendChild(storyEl);
150
 
 
 
 
 
151
  if (data.game_over) {
152
  endGame(data);
153
  } else {
@@ -184,6 +199,10 @@ async function handleChoice(choice) {
184
  storyEl.textContent = data.story;
185
  output.appendChild(storyEl);
186
 
 
 
 
 
187
  if (data.game_over) {
188
  endGame(data);
189
  } else {
@@ -533,6 +552,10 @@ async function loadSavedGame(slotName) {
533
  output.appendChild(storyEl);
534
  }
535
 
 
 
 
 
536
  if (data.game_over) {
537
  endGame(data);
538
  } else if (data.choices && data.choices.length > 0) {
 
18
  saveSlot: null
19
  };
20
 
21
+ let currentAudio = null;
22
+
23
+ function playTtsAudio(url) {
24
+ if (currentAudio) {
25
+ currentAudio.pause();
26
+ currentAudio = null;
27
+ }
28
+ currentAudio = new Audio(url);
29
+ currentAudio.play().catch(e => console.log("Audio play failed or interrupted:", e));
30
+ }
31
+
32
  // ---------------------------------------------------------------------------
33
  // DOM refs
34
  // ---------------------------------------------------------------------------
 
159
  storyEl.textContent = data.story;
160
  output.appendChild(storyEl);
161
 
162
+ if (data.audio_url) {
163
+ playTtsAudio(data.audio_url);
164
+ }
165
+
166
  if (data.game_over) {
167
  endGame(data);
168
  } else {
 
199
  storyEl.textContent = data.story;
200
  output.appendChild(storyEl);
201
 
202
+ if (data.audio_url) {
203
+ playTtsAudio(data.audio_url);
204
+ }
205
+
206
  if (data.game_over) {
207
  endGame(data);
208
  } else {
 
552
  output.appendChild(storyEl);
553
  }
554
 
555
+ if (data.audio_url) {
556
+ playTtsAudio(data.audio_url);
557
+ }
558
+
559
  if (data.game_over) {
560
  endGame(data);
561
  } else if (data.choices && data.choices.length > 0) {
shared/llms.txt ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shared — DOX
2
+
3
+ ## Purpose
4
+
5
+ Cross-project modules: inference client and cedar-copper aesthetic tokens used by all three apps.
6
+
7
+ ## Ownership
8
+
9
+ - Inference client: `inference_client.py`
10
+ - Aesthetic tokens: `cedar_copper_tokens.py`
11
+
12
+ ## Local Contracts
13
+
14
+ - `inference_client.py` provides `cooldown_status()`, `cooldown_active()`, `generate()`, and `chat_messages()`
15
+ - Default model: `Qwen/Qwen2.5-1.5B-Instruct`. Override via `INFERENCE_MODEL`.
16
+ - All LLM calls have always-fallback to procedural/template output
17
+ - `cedar_copper_tokens.py` exports CSS variables for the sky-to-sunrise palette
18
+
19
+ ## Work Guidance
20
+
21
+ - Changes here affect all three apps — test across CritterCalm, FocusFriend, TinyBard
22
+ - Cooldown defaults: tinybard 6s, focusfriend 10s, crittercalm 12s
23
+ - Override via per-project env vars or global `INFERENCE_COOLDOWN_SECONDS`
24
+
25
+ ## Verification
26
+
27
+ - Inference client loads without errors
28
+ - Cooldown system respects per-project timing
29
+ - Cedar-copper tokens render consistent palette across all apps