Hermes Bot commited on
feat(tinybard): add Kokoro TTS audio with custom voices & option prefixes
Browse files- .agents/tasks/TASK.2026-06-10.md +16 -0
- projects/tinybard/app.py +311 -79
- projects/tinybard/static/main.js +23 -0
.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.
|
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 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 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 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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":
|
| 1069 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1070 |
"genre": genre,
|
|
|
|
|
|
|
| 1071 |
}
|
| 1072 |
|
| 1073 |
-
|
|
|
|
| 1074 |
|
| 1075 |
# Health delta: ask LLM for consequence, fall back to procedural
|
| 1076 |
-
health_delta = _llm_health_delta(genre,
|
| 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":
|
| 1084 |
-
"choices": [],
|
| 1085 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1086 |
}
|
| 1087 |
|
| 1088 |
instruction = (
|
| 1089 |
-
f"The player chose: '{
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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":
|
| 1103 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/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) {
|