Spaces:
Paused
Paused
Commit ·
c5bd25e
1
Parent(s): 37bfdc1
feat: add LFM2.5-Audio end-to-end Q&A variant
Browse files- inference_lfm.py: LFM2.5-Audio-1.5B module (audio-in -> text+audio-out)
- app_lfm.py: app variant using LFM for Q&A instead of 3-model pipeline
- requirements_lfm.txt: deps including liquid-audio package
- Deployed to HF Space: DrSquare/MomsVoiceLFM (A10G GPU)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- app_lfm.py +1171 -0
- inference_lfm.py +106 -0
- requirements_lfm.txt +20 -0
app_lfm.py
ADDED
|
@@ -0,0 +1,1171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import html
|
| 3 |
+
import math
|
| 4 |
+
import re
|
| 5 |
+
import struct
|
| 6 |
+
import wave
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import time
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from tts import split_into_chunks, generate_audio_stream
|
| 12 |
+
from inference import transcribe_audio, answer_story_question
|
| 13 |
+
from inference_lfm import answer_question_audio, SAMPLE_RATE as LFM_SR
|
| 14 |
+
from voice_clone import load_default_profile, list_saved_profiles
|
| 15 |
+
|
| 16 |
+
# Create directories for sample audio files
|
| 17 |
+
os.makedirs("sample_sounds", exist_ok=True)
|
| 18 |
+
|
| 19 |
+
# Generate relaxing audio chime waveforms procedurally
|
| 20 |
+
# This runs fully client/server-side with standard Python, eliminating mock limits or Torch wait times
|
| 21 |
+
def generate_chimes_wav(filename, duration=120, melody_type="lullaby"):
|
| 22 |
+
sample_rate = 16000
|
| 23 |
+
n_samples = int(duration * sample_rate)
|
| 24 |
+
|
| 25 |
+
with wave.open(filename, 'wb') as wav_file:
|
| 26 |
+
wav_file.setnchannels(1)
|
| 27 |
+
wav_file.setsampwidth(2)
|
| 28 |
+
wav_file.setframerate(sample_rate)
|
| 29 |
+
|
| 30 |
+
# Pentatonic cozy scales
|
| 31 |
+
if melody_type == "lullaby":
|
| 32 |
+
notes = [261.63, 293.66, 329.63, 392.00, 440.00] # C4, D4, E4, G4, A4
|
| 33 |
+
elif melody_type == "adventure":
|
| 34 |
+
notes = [196.00, 246.94, 293.63, 329.63, 392.00] # G3, B3, D4, E4, G4
|
| 35 |
+
else:
|
| 36 |
+
notes = [220.00, 261.63, 293.66, 329.63, 392.00] # A3, C4, D4, E4, G4
|
| 37 |
+
|
| 38 |
+
for i in range(n_samples):
|
| 39 |
+
# cycle notes based on melody speed
|
| 40 |
+
note_speed = sample_rate * 1.5 if melody_type == "lullaby" else sample_rate * 1.2
|
| 41 |
+
note_idx = int((i / note_speed) % len(notes))
|
| 42 |
+
freq = notes[note_idx]
|
| 43 |
+
|
| 44 |
+
# envelope to prevent crackles
|
| 45 |
+
sample_in_note = i % int(note_speed)
|
| 46 |
+
envelope = 1.0
|
| 47 |
+
if sample_in_note < 1200: # attack
|
| 48 |
+
envelope = sample_in_note / 1200
|
| 49 |
+
else: # decay
|
| 50 |
+
decay_length = note_speed - 1200
|
| 51 |
+
envelope = max(0.0, 1.0 - (sample_in_note - 1200) / decay_length)
|
| 52 |
+
|
| 53 |
+
# Synthesize voice-harmonic chime
|
| 54 |
+
val = math.sin(2 * math.pi * freq * i / sample_rate)
|
| 55 |
+
val += 0.45 * math.sin(2 * math.pi * (freq * 1.5) * i / sample_rate)
|
| 56 |
+
val += 0.25 * math.sin(2 * math.pi * (freq * 2.0) * i / sample_rate)
|
| 57 |
+
val = val / 1.7 * envelope
|
| 58 |
+
|
| 59 |
+
packed_val = struct.pack('<h', int(val * 16384))
|
| 60 |
+
wav_file.writeframes(packed_val)
|
| 61 |
+
|
| 62 |
+
# Generate a short placeholder chime for the preview widget's initial value
|
| 63 |
+
_preview_chime_path = "sample_sounds/cloned_preview.wav"
|
| 64 |
+
if not os.path.exists(_preview_chime_path):
|
| 65 |
+
generate_chimes_wav(_preview_chime_path, duration=15, melody_type="lullaby")
|
| 66 |
+
|
| 67 |
+
COVERS_DIR = Path(__file__).parent / "assets" / "covers"
|
| 68 |
+
|
| 69 |
+
def cover_path(slug: str) -> str:
|
| 70 |
+
p = COVERS_DIR / f"{slug}.png"
|
| 71 |
+
return f"/gradio_api/file={p.resolve().as_posix()}"
|
| 72 |
+
|
| 73 |
+
def load_books_from_stories(stories_dir="stories"):
|
| 74 |
+
books = []
|
| 75 |
+
story_files = sorted(
|
| 76 |
+
f for f in os.listdir(stories_dir) if f.endswith(".txt")
|
| 77 |
+
) if os.path.isdir(stories_dir) else []
|
| 78 |
+
|
| 79 |
+
for i, filename in enumerate(story_files):
|
| 80 |
+
title = filename.replace(".txt", "").replace("_", " ")
|
| 81 |
+
slug = filename.replace(".txt", "")
|
| 82 |
+
synopsis = ""
|
| 83 |
+
try:
|
| 84 |
+
with open(os.path.join(stories_dir, filename), encoding="utf-8") as f:
|
| 85 |
+
lines = [l.strip() for l in f.readlines() if l.strip()]
|
| 86 |
+
synopsis = " ".join(lines[1:4]) if len(lines) > 1 else lines[0] if lines else ""
|
| 87 |
+
except Exception:
|
| 88 |
+
pass
|
| 89 |
+
|
| 90 |
+
books.append({
|
| 91 |
+
"id": str(i + 1),
|
| 92 |
+
"title": title,
|
| 93 |
+
"author": "Public Domain",
|
| 94 |
+
"cover_url": cover_path(slug),
|
| 95 |
+
"voice_name": "Mom's Voice",
|
| 96 |
+
"duration": 0,
|
| 97 |
+
"elapsed_time": 0,
|
| 98 |
+
"synopsis": synopsis,
|
| 99 |
+
"category": "Children's Story",
|
| 100 |
+
"is_cloned": False,
|
| 101 |
+
"percentage": 0,
|
| 102 |
+
"audio_path": None,
|
| 103 |
+
"story_path": os.path.join(stories_dir, filename),
|
| 104 |
+
})
|
| 105 |
+
return books
|
| 106 |
+
|
| 107 |
+
mock_books = load_books_from_stories()
|
| 108 |
+
|
| 109 |
+
mock_voices = [
|
| 110 |
+
{
|
| 111 |
+
"id": "v1",
|
| 112 |
+
"name": "Mom's Voice",
|
| 113 |
+
"avatar_url": "👩🦳",
|
| 114 |
+
"description": "Warm, soft, with a natural soothing cadence. Best for bedtime stories.",
|
| 115 |
+
"gender": "Female",
|
| 116 |
+
"created_date": "2026-06-01",
|
| 117 |
+
"status": "ready"
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"id": "v2",
|
| 121 |
+
"name": "Grandpa Joseph",
|
| 122 |
+
"avatar_url": "👴",
|
| 123 |
+
"description": "Deep, resonant, with an occasional comforting chuckle. Perfect for classic adventure stories.",
|
| 124 |
+
"gender": "Male",
|
| 125 |
+
"created_date": "2026-06-03",
|
| 126 |
+
"status": "ready"
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"id": "v3",
|
| 130 |
+
"name": "Aunt Sarah",
|
| 131 |
+
"avatar_url": "👩",
|
| 132 |
+
"description": "Bubbly, expressive, brilliant at acting out funny character voices.",
|
| 133 |
+
"gender": "Female",
|
| 134 |
+
"created_date": "2026-06-06",
|
| 135 |
+
"status": "processing"
|
| 136 |
+
}
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
with open(os.path.join(os.path.dirname(__file__), "static", "style.css"), encoding="utf-8") as _f:
|
| 140 |
+
css_code = _f.read()
|
| 141 |
+
|
| 142 |
+
def generate_dashboard_html(books_list):
|
| 143 |
+
featured = books_list[0]
|
| 144 |
+
others = books_list[1:]
|
| 145 |
+
featured_js_title = featured['title'].replace("'", "\\'").replace('"', '\\"')
|
| 146 |
+
|
| 147 |
+
html = f"""
|
| 148 |
+
<div style="margin-bottom: 24px;">
|
| 149 |
+
<span style="font-size: 11px; text-transform: uppercase; letter-spacing: 2px; color: #f5841f; font-weight: 600;">Welcome Back, Sarah</span>
|
| 150 |
+
<h2 class="serif-header" style="font-size: 28px; margin-top: 4px; margin-bottom: 16px;">Explore Your Warm Audiobook Shelves</h2>
|
| 151 |
+
</div>
|
| 152 |
+
|
| 153 |
+
<!-- Hero Spotlight Section -->
|
| 154 |
+
<div class="hero-spotlight" style="display: flex; flex-direction: row; gap: 32px; align-items: center; margin-bottom: 32px; flex-wrap: wrap; cursor: pointer;" onclick="
|
| 155 |
+
var tabs = document.querySelectorAll('button[role=tab]');
|
| 156 |
+
if (tabs.length > 1) {{ tabs[1].click(); }}
|
| 157 |
+
setTimeout(function() {{
|
| 158 |
+
var radios = document.querySelectorAll('.library-book-selector input[type=radio]');
|
| 159 |
+
radios.forEach(function(r) {{
|
| 160 |
+
if(r.value === '{featured_js_title}') {{
|
| 161 |
+
r.checked = true;
|
| 162 |
+
r.dispatchEvent(new Event('input', {{bubbles: true}}));
|
| 163 |
+
r.dispatchEvent(new Event('change', {{bubbles: true}}));
|
| 164 |
+
}}
|
| 165 |
+
}});
|
| 166 |
+
}}, 300);
|
| 167 |
+
">
|
| 168 |
+
<div style="flex: 1; min-width: 200px; max-width: 280px; text-align: center;">
|
| 169 |
+
<img src="{featured['cover_url']}" style="width: 180px; height: 260px; object-fit: cover; border-radius: 16px; box-shadow: 0 8px 24px rgba(0,0,0,0.3); transform: rotate(-2deg);" referrerPolicy="no-referrer" />
|
| 170 |
+
</div>
|
| 171 |
+
<div style="flex: 2; min-width: 300px; display: flex; flex-direction: column; justify-content: space-between; gap: 16px;">
|
| 172 |
+
<div>
|
| 173 |
+
<span class="badge-featured" style="margin-bottom: 8px;">Featured Clone</span>
|
| 174 |
+
<h3 class="serif-header" style="color: white !important; font-size: 28px; margin: 4px 0;">{featured['title']}</h3>
|
| 175 |
+
<p style="color: #6f6257;">by <span style="font-style: italic; color: #ddc1b0;">{featured['author']}</span></p>
|
| 176 |
+
<p style="color: #cbd5e1; font-size: 13.5px; line-height: 1.6; margin-top: 8px;">{featured['synopsis']}</p>
|
| 177 |
+
</div>
|
| 178 |
+
|
| 179 |
+
<div style="display: flex; gap: 12px; flex-wrap: wrap; font-size: 12px; color: #e2e8f0;">
|
| 180 |
+
<span style="background: rgba(255,255,255,0.1); padding: 4px 10px; border-radius: 8px;">⏱️ 20 Min Remaining</span>
|
| 181 |
+
<span style="background: rgba(255,255,255,0.1); padding: 4px 10px; border-radius: 8px; font-weight: 600; color: #ffd3a6;">🎙️ Narrator: {featured['voice_name']}</span>
|
| 182 |
+
<span style="background: rgba(255,255,255,0.1); padding: 4px 10px; border-radius: 8px;">⭐ Editorial Spotlight</span>
|
| 183 |
+
</div>
|
| 184 |
+
</div>
|
| 185 |
+
</div>
|
| 186 |
+
|
| 187 |
+
<div>
|
| 188 |
+
<h4 class="serif-header" style="font-size: 20px; margin-bottom: 16px;">Continue Reading with Channeled Voices</h4>
|
| 189 |
+
<div class="book-shelf-grid">
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
for bk in books_list:
|
| 193 |
+
js_safe_title = bk['title'].replace("'", "\\'").replace('"', '\\"')
|
| 194 |
+
html += f"""
|
| 195 |
+
<div class="shelf-card" style="cursor: pointer;" onclick="
|
| 196 |
+
// Switch to My Library tab (2nd tab button)
|
| 197 |
+
var tabs = document.querySelectorAll('button[role=tab]');
|
| 198 |
+
if (tabs.length > 1) {{ tabs[1].click(); }}
|
| 199 |
+
// Select book in hidden radio
|
| 200 |
+
setTimeout(function() {{
|
| 201 |
+
var radios = document.querySelectorAll('.library-book-selector input[type=radio]');
|
| 202 |
+
radios.forEach(function(r) {{
|
| 203 |
+
if(r.value === '{js_safe_title}') {{
|
| 204 |
+
r.checked = true;
|
| 205 |
+
r.dispatchEvent(new Event('input', {{bubbles: true}}));
|
| 206 |
+
r.dispatchEvent(new Event('change', {{bubbles: true}}));
|
| 207 |
+
}}
|
| 208 |
+
}});
|
| 209 |
+
}}, 300);
|
| 210 |
+
">
|
| 211 |
+
<div>
|
| 212 |
+
<img src="{bk['cover_url']}" class="cover-image" referrerPolicy="no-referrer" />
|
| 213 |
+
</div>
|
| 214 |
+
<div style="display: flex; flex-direction: column; justify-content: space-between; flex: 1; min-width: 0;">
|
| 215 |
+
<div>
|
| 216 |
+
<div style="display: flex; justify-content: space-between; font-size: 10px; font-weight: 700; color: #f5841f;">
|
| 217 |
+
<span>{bk['category']}</span>
|
| 218 |
+
<span>{bk['percentage']}%</span>
|
| 219 |
+
</div>
|
| 220 |
+
<h5 class="serif-header" style="font-size: 14px; margin: 4px 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{bk['title']}</h5>
|
| 221 |
+
<p style="font-size: 11.5px; color: #6f6257; margin-bottom: 8px;">by {bk['author']}</p>
|
| 222 |
+
</div>
|
| 223 |
+
<div>
|
| 224 |
+
<div class="progress-bar-bg" style="margin-bottom: 6px;">
|
| 225 |
+
<div class="progress-bar-fill" style="width: {bk['percentage']}%"></div>
|
| 226 |
+
</div>
|
| 227 |
+
<div style="display: flex; justify-content: space-between; font-size: 11px; color: #6f6257;">
|
| 228 |
+
<span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">🎙️ {bk['voice_name']}</span>
|
| 229 |
+
</div>
|
| 230 |
+
</div>
|
| 231 |
+
</div>
|
| 232 |
+
</div>
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
html += """
|
| 236 |
+
</div>
|
| 237 |
+
</div>
|
| 238 |
+
"""
|
| 239 |
+
return html
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def generate_library_html(books_list, query="", category_filt="All", empty_mode=False):
|
| 243 |
+
if empty_mode:
|
| 244 |
+
return """
|
| 245 |
+
<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 64px 16px; text-align: center; max-width: 440px; margin: 0 auto;">
|
| 246 |
+
<div style="position: relative; width: 90px; height: 90px; border-radius: 50%; background: #ede8e3; border: 1px dashed #ddc1b0; display: flex; align-items: center; justify-content: center; margin-bottom: 24px;">
|
| 247 |
+
<span style="font-size: 32px;">📚</span>
|
| 248 |
+
<span style="position: absolute; font-size: 20px; bottom: -4px; right: -4px;">🎙️</span>
|
| 249 |
+
</div>
|
| 250 |
+
<h3 class="serif-header" style="font-size: 22px; margin-bottom: 8px;">Your Bookshelf is Waiting to be Voiced</h3>
|
| 251 |
+
<p style="font-size: 13.5px; color: #6f6257; line-height: 1.5; margin-bottom: 24px;">
|
| 252 |
+
Choose a comforting companion, clone their warm voice, and hear any classical or modern tale come to life immediately.
|
| 253 |
+
</p>
|
| 254 |
+
<div style="display: flex; gap: 12px; width: 100%;">
|
| 255 |
+
<span style="flex: 1; padding: 12px; background: #944a00; color: white; border-radius: 12px; font-weight: 700; font-size: 13px;">Use 'Clone Voice' tab to craft a companion</span>
|
| 256 |
+
</div>
|
| 257 |
+
</div>
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
filtered = []
|
| 261 |
+
for bk in books_list:
|
| 262 |
+
match_query = (query.lower() in bk["title"].lower()) or (query.lower() in bk["author"].lower()) or (query.lower() in bk["voice_name"].lower())
|
| 263 |
+
match_cat = True
|
| 264 |
+
|
| 265 |
+
if category_filt == "In Progress":
|
| 266 |
+
match_cat = 0 < bk["percentage"] < 100
|
| 267 |
+
elif category_filt == "Completed":
|
| 268 |
+
match_cat = bk["percentage"] == 100
|
| 269 |
+
|
| 270 |
+
if match_query and match_cat:
|
| 271 |
+
filtered.append(bk)
|
| 272 |
+
|
| 273 |
+
if len(filtered) == 0:
|
| 274 |
+
return """
|
| 275 |
+
<div style="text-align: center; padding: 48px; border: 1px dashed #ebdccb; border-radius: 16px;">
|
| 276 |
+
<span style="font-size: 28px;">🔍</span>
|
| 277 |
+
<p style="font-size: 14px; color: #6f6257; margin-top: 8px;">No audiobooks match your search criteria.</p>
|
| 278 |
+
</div>
|
| 279 |
+
"""
|
| 280 |
+
|
| 281 |
+
html_out = """<div class="book-shelf-grid">"""
|
| 282 |
+
for bk in filtered:
|
| 283 |
+
safe_title = html.escape(bk['title'])
|
| 284 |
+
js_safe_title = bk['title'].replace("'", "\\'").replace('"', '\\"')
|
| 285 |
+
html_out += f"""
|
| 286 |
+
<div class="shelf-card group" style="flex-direction: column; gap: 0; padding: 0; overflow: hidden; cursor: pointer;" onclick="
|
| 287 |
+
var radios = document.querySelectorAll('.library-book-selector input[type=radio]');
|
| 288 |
+
radios.forEach(function(r) {{
|
| 289 |
+
if(r.value === '{js_safe_title}') {{
|
| 290 |
+
r.checked = true;
|
| 291 |
+
r.dispatchEvent(new Event('input', {{bubbles: true}}));
|
| 292 |
+
r.dispatchEvent(new Event('change', {{bubbles: true}}));
|
| 293 |
+
}}
|
| 294 |
+
}});
|
| 295 |
+
">
|
| 296 |
+
<div style="position: relative; aspect-ratio: 3/4; overflow: hidden; height: 200px;">
|
| 297 |
+
<img src="{bk['cover_url']}" style="width: 100%; height: 100%; object-fit: cover;" referrerPolicy="no-referrer" />
|
| 298 |
+
<div style="position: absolute; top: 12px; right: 12px; background: rgba(255,255,255,0.95); padding: 4px 10px; border-radius: 8px; font-weight: 700; font-size: 11px; border: 1px solid #ebdccb; color: #1c1c19;">
|
| 299 |
+
{bk['percentage']}%
|
| 300 |
+
</div>
|
| 301 |
+
<div style="position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(0deg, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0) 100%); padding: 12px; color: white;">
|
| 302 |
+
<span style="font-size: 9px; text-transform: uppercase; letter-spacing: 1.5px; font-weight: 700; color: #f5841f;">{bk['category']}</span>
|
| 303 |
+
<h5 class="serif-header" style="color: white !important; font-size: 15px; margin: 2px 0 0 0; text-overflow: ellipsis; white-space: nowrap; overflow: hidden;">{safe_title}</h5>
|
| 304 |
+
</div>
|
| 305 |
+
</div>
|
| 306 |
+
<div style="padding: 16px; display: flex; flex-direction: column; gap: 10px;">
|
| 307 |
+
<div style="display: flex; justify-content: space-between; font-size: 11px; align-items: center;">
|
| 308 |
+
<span style="color: #6f6257;">Narrator:</span>
|
| 309 |
+
<span style="font-weight: 600; color: #944a00;">🌟 {bk['voice_name']}</span>
|
| 310 |
+
</div>
|
| 311 |
+
<div class="progress-bar-bg">
|
| 312 |
+
<div class="progress-bar-fill" style="width: {bk['percentage']}%"></div>
|
| 313 |
+
</div>
|
| 314 |
+
<div style="text-align: center; padding: 6px 0; font-size: 12px; font-weight: 700; color: #944a00;">
|
| 315 |
+
▶️ Tap to Play
|
| 316 |
+
</div>
|
| 317 |
+
</div>
|
| 318 |
+
</div>
|
| 319 |
+
"""
|
| 320 |
+
html_out += "</div>"
|
| 321 |
+
return html_out
|
| 322 |
+
|
| 323 |
+
def load_paragraphs(story_path: str) -> list:
|
| 324 |
+
try:
|
| 325 |
+
with open(story_path, encoding="utf-8") as f:
|
| 326 |
+
raw = f.read()
|
| 327 |
+
paras = [p.strip() for p in raw.split("\n\n") if p.strip()]
|
| 328 |
+
return paras
|
| 329 |
+
except Exception:
|
| 330 |
+
return []
|
| 331 |
+
|
| 332 |
+
def render_story_text(paragraphs: list, current_idx: int) -> str:
|
| 333 |
+
if not paragraphs:
|
| 334 |
+
return ""
|
| 335 |
+
result = """<div style="max-height: 420px; overflow-y: auto; padding: 4px 2px; margin-top: 12px;">"""
|
| 336 |
+
for i, para in enumerate(paragraphs):
|
| 337 |
+
safe_para = html.escape(para)
|
| 338 |
+
if i == current_idx:
|
| 339 |
+
result += f"""<p style="font-family: 'Playfair Display', Georgia, serif; font-size: 13px; line-height: 1.8; color: #FAF7F2; background: rgba(245,132,31,0.18); border-left: 3px solid #f5841f; padding: 8px 12px; border-radius: 6px; margin: 6px 0;">{safe_para}</p>"""
|
| 340 |
+
else:
|
| 341 |
+
result += f"""<p style="font-family: 'Playfair Display', Georgia, serif; font-size: 13px; line-height: 1.8; color: #94a3b8; padding: 4px 12px; margin: 4px 0;">{safe_para}</p>"""
|
| 342 |
+
result += "</div>"
|
| 343 |
+
return result
|
| 344 |
+
|
| 345 |
+
def render_cloned_voices_html(voices_list):
|
| 346 |
+
markup = """<div class="book-shelf-grid">"""
|
| 347 |
+
for v in voices_list:
|
| 348 |
+
status_color = "#16a34a" if v["status"] == "ready" else "#d97706"
|
| 349 |
+
status_bg = "#f0fdf4" if v["status"] == "ready" else "#fef3c7"
|
| 350 |
+
safe_name = html.escape(v['name'])
|
| 351 |
+
safe_desc = html.escape(v['description'])
|
| 352 |
+
voice_id = html.escape(v.get('profile_id', v['id']))
|
| 353 |
+
|
| 354 |
+
onclick = f"""onclick="
|
| 355 |
+
const sel = document.querySelector('#voice_selector textarea, #voice_selector input');
|
| 356 |
+
if (sel) {{
|
| 357 |
+
sel.value = '{voice_id}';
|
| 358 |
+
sel.dispatchEvent(new Event('input', {{bubbles: true}}));
|
| 359 |
+
sel.dispatchEvent(new Event('change', {{bubbles: true}}));
|
| 360 |
+
}}
|
| 361 |
+
document.querySelectorAll('.voice-card-selected').forEach(c => c.classList.remove('voice-card-selected'));
|
| 362 |
+
this.classList.add('voice-card-selected');
|
| 363 |
+
" """
|
| 364 |
+
|
| 365 |
+
markup += f"""
|
| 366 |
+
<div class="shelf-card" style="align-items: center; cursor: pointer;" {onclick}>
|
| 367 |
+
<div style="width: 48px; height: 48px; border-radius: 50%; background: #ede8e3; border: 1px solid #ddc1b0; font-size: 24px; display: flex; align-items: center; justify-content: center; shrink-0: 0;">
|
| 368 |
+
{v['avatar_url']}
|
| 369 |
+
</div>
|
| 370 |
+
<div style="min-width: 0; flex: 1;">
|
| 371 |
+
<div style="display: flex; justify-content: space-between; align-items: center; gap: 6px;">
|
| 372 |
+
<h5 class="serif-header" style="font-size: 14.5px; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{safe_name}</h5>
|
| 373 |
+
<span style="font-size: 9px; font-weight: 700; text-transform: uppercase; padding: 2px 6px; border-radius: 4px; color: {status_color}; background: {status_bg};">
|
| 374 |
+
{v['status']}
|
| 375 |
+
</span>
|
| 376 |
+
</div>
|
| 377 |
+
<p style="font-size: 11.5px; color: #6f6257; margin: 4px 0 0 0; clamp: 2; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;">
|
| 378 |
+
{safe_desc}
|
| 379 |
+
</p>
|
| 380 |
+
<div style="border-top: 1px solid rgba(148,74,0,0.08); padding-top: 6px; margin-top: 6px; display: flex; justify-content: space-between; font-size: 10px; color: #6f6257;">
|
| 381 |
+
<span>Gender: {v['gender']}</span>
|
| 382 |
+
<span>Created: {v['created_date']}</span>
|
| 383 |
+
</div>
|
| 384 |
+
</div>
|
| 385 |
+
</div>
|
| 386 |
+
"""
|
| 387 |
+
markup += "</div>"
|
| 388 |
+
return markup
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
# Load default voice profile from Voice_Profile/ (if any saved from previous sessions)
|
| 392 |
+
_default_profile_id = load_default_profile()
|
| 393 |
+
_saved_profiles = list_saved_profiles()
|
| 394 |
+
if _default_profile_id:
|
| 395 |
+
_default_voice_name = next(
|
| 396 |
+
(p["voice_name"] for p in _saved_profiles if p["profile_id"] == _default_profile_id),
|
| 397 |
+
"Cloned Voice"
|
| 398 |
+
)
|
| 399 |
+
print(f"[MomsVoice] Default voice profile loaded: {_default_profile_id} ({_default_voice_name})")
|
| 400 |
+
else:
|
| 401 |
+
_default_voice_name = None
|
| 402 |
+
print("[MomsVoice] No saved voice profile — using stock voice as default.")
|
| 403 |
+
|
| 404 |
+
# Preload models at startup for fast response
|
| 405 |
+
print("[MomsVoice] Preloading Qwen3-TTS 0.6B CustomVoice model...")
|
| 406 |
+
from voice_clone import get_custom_voice_model
|
| 407 |
+
get_custom_voice_model()
|
| 408 |
+
print("[MomsVoice] TTS model ready.")
|
| 409 |
+
|
| 410 |
+
print("[MomsVoice] Preloading Whisper-small ASR model...")
|
| 411 |
+
from inference import get_asr_pipeline, get_qa_model
|
| 412 |
+
get_asr_pipeline()
|
| 413 |
+
print("[MomsVoice] ASR model ready.")
|
| 414 |
+
|
| 415 |
+
print("[MomsVoice] Preloading Qwen2.5-3B-Instruct Q&A model...")
|
| 416 |
+
get_qa_model()
|
| 417 |
+
print("[MomsVoice] Q&A model ready. All models preloaded.")
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
# Gradio Application Core setup
|
| 421 |
+
with gr.Blocks(title="MomsVoice", css=css_code) as demo:
|
| 422 |
+
|
| 423 |
+
books_state = gr.State(mock_books)
|
| 424 |
+
voices_state = gr.State(mock_voices)
|
| 425 |
+
paragraphs_state = gr.State([])
|
| 426 |
+
tts_chunks_state = gr.State([])
|
| 427 |
+
voice_profile_state = gr.State(_default_profile_id)
|
| 428 |
+
|
| 429 |
+
gr.HTML("""
|
| 430 |
+
<div style="display: flex; align-items: center; justify-content: space-between; padding: 16px 0; border-bottom: 1px solid #ebdccb; margin-bottom: 24px; flex-wrap: wrap; gap: 16px;">
|
| 431 |
+
<div style="display: flex; align-items: center; gap: 12px;">
|
| 432 |
+
<div style="width: 42px; height: 42px; background-color: #944a00; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 20px;">
|
| 433 |
+
💿
|
| 434 |
+
</div>
|
| 435 |
+
<div>
|
| 436 |
+
<h1 class="serif-header" style="font-size: 22px; margin: 0; line-height: 1;">VoiceBook</h1>
|
| 437 |
+
<span style="font-size: 10px; color: #f5841f; font-weight: 700; text-transform: uppercase; letter-spacing: 1.5px;">AI Bedtime Story Narrator</span>
|
| 438 |
+
</div>
|
| 439 |
+
</div>
|
| 440 |
+
<div style="display: flex; align-items: center; gap: 6px; font-size: 11.5px; color: #6f6257; font-family: monospace;">
|
| 441 |
+
<span>Hugging Face Space Node:</span>
|
| 442 |
+
<span style="color: #16a34a; font-weight: 700;">● Active</span>
|
| 443 |
+
</div>
|
| 444 |
+
</div>
|
| 445 |
+
""")
|
| 446 |
+
|
| 447 |
+
with gr.Tabs() as main_tabs:
|
| 448 |
+
|
| 449 |
+
# TAB 1: Explore Dashboard
|
| 450 |
+
with gr.TabItem("🏛️ Explore Space") as explore_tab:
|
| 451 |
+
dashboard_container = gr.HTML(value=generate_dashboard_html(mock_books))
|
| 452 |
+
gr.HTML("""<div style="margin-top: 24px; text-align: center;"><span style="font-size: 12px; color:#6f6257;">🎧 Head over to <b>My Library</b> and tap any book to start listening!</span></div>""")
|
| 453 |
+
|
| 454 |
+
# TAB 2: Library + Player (통합)
|
| 455 |
+
with gr.TabItem("📚 My Library") as library_tab:
|
| 456 |
+
with gr.Row():
|
| 457 |
+
# Left: book grid
|
| 458 |
+
with gr.Column(scale=3):
|
| 459 |
+
with gr.Row():
|
| 460 |
+
with gr.Column(scale=3):
|
| 461 |
+
search_input = gr.Textbox(placeholder="Search by title, author, or voice...", label="Filter", show_label=False)
|
| 462 |
+
with gr.Column(scale=1):
|
| 463 |
+
category_filter = gr.Radio(["All", "In Progress", "Completed"], value="All", label="Progress", show_label=False)
|
| 464 |
+
|
| 465 |
+
shelf_grid = gr.HTML(value=generate_library_html(mock_books))
|
| 466 |
+
|
| 467 |
+
# Hidden radio — book cards click this via JS onclick
|
| 468 |
+
book_titles_list = [b["title"] for b in mock_books]
|
| 469 |
+
book_selector = gr.Radio(
|
| 470 |
+
choices=book_titles_list,
|
| 471 |
+
value=None,
|
| 472 |
+
label="",
|
| 473 |
+
show_label=False,
|
| 474 |
+
elem_classes="library-book-selector",
|
| 475 |
+
visible=False,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
# Right: player panel
|
| 479 |
+
with gr.Column(scale=2, elem_classes="dark-card-container"):
|
| 480 |
+
gr.HTML("""
|
| 481 |
+
<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px dashed rgba(255,255,255,0.15); padding-bottom: 12px; margin-bottom: 16px;">
|
| 482 |
+
<span style="font-size: 10px; text-transform: uppercase; letter-spacing: 2px; color: #f5841f; font-weight: 700;">Now Playing</span>
|
| 483 |
+
<span style="background: rgba(22, 163, 74, 0.2); padding: 2px 6px; border-radius: 6px; font-size: 9px; font-family: monospace; color: #4ade80;">SYNCHRONIZED PITCH</span>
|
| 484 |
+
</div>
|
| 485 |
+
""")
|
| 486 |
+
|
| 487 |
+
player_title_info = gr.HTML("""
|
| 488 |
+
<div style="text-align: center; margin-bottom: 24px; margin-top: 16px; padding: 32px 0;">
|
| 489 |
+
<span style="font-size: 48px;">📖</span>
|
| 490 |
+
<h3 style="font-family: 'Playfair Display', Georgia, serif; font-size: 18px; margin: 12px 0 4px; color:#FAF7F2;">Select a story</h3>
|
| 491 |
+
<p style="font-size: 12px; color: #94a3b8; font-style: italic;">Tap any book on the left to begin</p>
|
| 492 |
+
</div>
|
| 493 |
+
""")
|
| 494 |
+
|
| 495 |
+
player_audio_control = gr.Audio(
|
| 496 |
+
visible=False, interactive=False,
|
| 497 |
+
label="Audio Stream",
|
| 498 |
+
type="numpy",
|
| 499 |
+
streaming=False,
|
| 500 |
+
autoplay=True,
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
player_status_bar = gr.HTML("""
|
| 504 |
+
<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">
|
| 505 |
+
<span style="width: 8px; height: 8px; border-radius: 50%; background: #94a3b8; display: inline-block;"></span>
|
| 506 |
+
<span style="font-size: 11px; color: #94a3b8; font-family: monospace;">SELECT A STORY</span>
|
| 507 |
+
</div>
|
| 508 |
+
""")
|
| 509 |
+
|
| 510 |
+
with gr.Row():
|
| 511 |
+
play_btn = gr.Button("▶️ Play", variant="primary", scale=1, visible=False)
|
| 512 |
+
pause_btn = gr.Button("⏸ Pause", variant="secondary", scale=1, visible=False)
|
| 513 |
+
resume_btn = gr.Button("↩️ Resume Story", variant="secondary", scale=2, visible=False)
|
| 514 |
+
|
| 515 |
+
with gr.Row():
|
| 516 |
+
ask_btn = gr.Button("❓ Ask a Question", variant="primary", scale=2, visible=False)
|
| 517 |
+
|
| 518 |
+
chunk_status = gr.HTML("""
|
| 519 |
+
<div style="margin-top: 8px; font-size: 10px; color: #64748b; font-family: monospace; text-align: center;">
|
| 520 |
+
Chunk 0 / 0
|
| 521 |
+
</div>
|
| 522 |
+
""")
|
| 523 |
+
|
| 524 |
+
story_finished_panel = gr.HTML("""
|
| 525 |
+
<div style="margin-top: 12px; padding: 16px; background: rgba(245,132,31,0.1); border: 1px solid rgba(245,132,31,0.3); border-radius: 14px; text-align: center;">
|
| 526 |
+
<span style="font-size: 28px;">🎉</span>
|
| 527 |
+
<h4 style="font-family: 'Playfair Display', Georgia, serif; color: #ffd3a6; margin: 8px 0 4px;">Story Complete!</h4>
|
| 528 |
+
<p style="font-size: 12px; color: #94a3b8; margin-bottom: 12px;">Tap another book to start a new story.</p>
|
| 529 |
+
</div>
|
| 530 |
+
""", visible=False)
|
| 531 |
+
|
| 532 |
+
# Story text display + slider
|
| 533 |
+
story_text_display = gr.HTML(visible=False)
|
| 534 |
+
timeline_slider = gr.Slider(minimum=0, maximum=100, step=1, value=0, label="📍 Story position (paragraph)", visible=False)
|
| 535 |
+
|
| 536 |
+
# Q&A Panel
|
| 537 |
+
qa_panel = gr.HTML("""
|
| 538 |
+
<div style="margin-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); padding-top: 16px;">
|
| 539 |
+
<h4 style="font-family: 'Playfair Display', Georgia, serif; font-size: 14px; margin-bottom: 12px; color: #FAF7F2;">❓ Ask About the Story</h4>
|
| 540 |
+
</div>
|
| 541 |
+
""", visible=False)
|
| 542 |
+
|
| 543 |
+
with gr.Group(visible=False) as qa_input_group:
|
| 544 |
+
question_audio = gr.Audio(
|
| 545 |
+
sources=["microphone"], type="filepath",
|
| 546 |
+
label="🎤 Ask your question — answer generates when you stop recording",
|
| 547 |
+
show_label=True, streaming=False,
|
| 548 |
+
elem_id="qa_audio_input",
|
| 549 |
+
)
|
| 550 |
+
question_text = gr.Textbox(visible=False)
|
| 551 |
+
submit_question_btn = gr.Button("🔍 Get Answer in Narrator's Voice", variant="primary", elem_id="qa_submit_btn")
|
| 552 |
+
|
| 553 |
+
answer_display = gr.HTML(visible=False)
|
| 554 |
+
answer_audio = gr.Audio(label="Answer in Narrator's Voice", interactive=False, visible=False, autoplay=True)
|
| 555 |
+
|
| 556 |
+
# TAB 3: Clone Voice Studio
|
| 557 |
+
with gr.TabItem("🎙️ Clone Voice Studio") as clone_tab:
|
| 558 |
+
with gr.Row():
|
| 559 |
+
with gr.Column(scale=1, elem_classes="card-container"):
|
| 560 |
+
gr.HTML("""
|
| 561 |
+
<h3 class="serif-header" style="font-size: 18px; margin-bottom: 4px; display: flex; align-items: center; gap: 8px;">🧙 Voice Details Form</h3>
|
| 562 |
+
<p style="font-size: 12px; color: #6f6257; margin-bottom: 20px;">Provide a comforting nickname and details below to prepare vocal weights matching.</p>
|
| 563 |
+
""")
|
| 564 |
+
|
| 565 |
+
new_voice_name = gr.Textbox(placeholder="Enter a descriptive nickname (e.g., Grandma Judy, Dad)...", label="Voice Nickname")
|
| 566 |
+
new_voice_gender = gr.Radio(["Female", "Male"], value="Female", label="Voice Gender Avatar")
|
| 567 |
+
|
| 568 |
+
gr.HTML("""
|
| 569 |
+
<div style="margin: 16px 0; padding: 12px; background: white; border-radius: 12px; border: 1px solid #ebdccb; font-size: 12px;">
|
| 570 |
+
<strong style="color: #6f6257; text-transform: uppercase; font-size: 10px; display: block; margin-bottom: 4px;">Story Script to read aloud:</strong>
|
| 571 |
+
<p style="font-family: Georgia, serif; font-style: italic; color: #1c1c19; margin: 0; line-height: 1.4;">
|
| 572 |
+
"Deep within the ancient forest, the giant oak tree stood. Its roots whispered stories of forgotten eras. 'Close your eyes,' the wind hummed softly, 'for our beautiful journey begins tonight.'"
|
| 573 |
+
</p>
|
| 574 |
+
</div>
|
| 575 |
+
""")
|
| 576 |
+
|
| 577 |
+
mic_recorder = gr.Audio(sources=["microphone"], type="filepath", label="Record speaking story prompt (Min 10 seconds sample)")
|
| 578 |
+
extract_btn = gr.Button("🪄 Analyze & Synthesize Customized Vocal Profile", variant="primary")
|
| 579 |
+
|
| 580 |
+
with gr.Column(scale=1, elem_classes="card-container"):
|
| 581 |
+
gr.HTML("""
|
| 582 |
+
<h3 class="serif-header" style="font-size: 18px; margin-bottom: 4px;">Status Pipeline Visualizer</h3>
|
| 583 |
+
<p style="font-size: 12px; color: #6f6257; margin-bottom: 16px;">Track extraction, de-noising, and pitch tuning.</p>
|
| 584 |
+
""")
|
| 585 |
+
|
| 586 |
+
cloning_progress_msg = gr.HTML("""
|
| 587 |
+
<div style="text-align: center; padding: 32px 0;">
|
| 588 |
+
<span style="font-size: 42px;">🎙️</span>
|
| 589 |
+
<p style="margin-top: 12px; font-size: 14px; color: #6f6257;">Fill parameters on the left and read the story script aloud to begin extraction.</p>
|
| 590 |
+
</div>
|
| 591 |
+
""")
|
| 592 |
+
|
| 593 |
+
voice_cloning_success_panel = gr.HTML(visible=False)
|
| 594 |
+
voice_sample_preview_widget = gr.Audio(value="sample_sounds/cloned_preview.wav", visible=False, label="Pre-listening synthesized vocal pitch weights match preview", interactive=False)
|
| 595 |
+
add_to_library_btn = gr.Button("✨ Synced successfully! Bind Companion Voice to Inventory", visible=False)
|
| 596 |
+
|
| 597 |
+
gr.HTML("""
|
| 598 |
+
<div style="margin-top: 32px; border-top: 1px solid #ebdccb; padding-top: 24px;">
|
| 599 |
+
<h4 class="serif-header" style="font-size: 18px; margin-bottom: 16px;">Currently Available Voices</h4>
|
| 600 |
+
<p style="font-size: 11px; color: #6f6257; margin-bottom: 12px;">Click a voice card to select it as the narrator.</p>
|
| 601 |
+
</div>
|
| 602 |
+
""")
|
| 603 |
+
cloned_voices_list_grid = gr.HTML(value=render_cloned_voices_html(mock_voices))
|
| 604 |
+
voice_selector = gr.Textbox(visible=False, elem_id="voice_selector")
|
| 605 |
+
|
| 606 |
+
# TAB 4: Profile
|
| 607 |
+
with gr.TabItem("⚙️ Profile") as profile_tab:
|
| 608 |
+
with gr.Row():
|
| 609 |
+
with gr.Column(scale=1, elem_classes="card-container"):
|
| 610 |
+
gr.HTML("""
|
| 611 |
+
<div style="text-align: center; margin-bottom: 24px;">
|
| 612 |
+
<div style="width: 72px; height: 72px; border-radius: 50%; background: #944a00; color: white; font-size: 36px; display: flex; align-items: center; justify-content: center; margin: 0 auto 12px auto;">
|
| 613 |
+
👩💻
|
| 614 |
+
</div>
|
| 615 |
+
<h3 class="serif-header" style="font-size: 18px; margin: 0;">Your Profile</h3>
|
| 616 |
+
<p style="font-size: 11.5px; color: #6f6257; margin-top: 2px;">ReadBookMom — Hugging Face Hackathon 2026</p>
|
| 617 |
+
</div>
|
| 618 |
+
""")
|
| 619 |
+
|
| 620 |
+
gr.HTML("""
|
| 621 |
+
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; text-align: center;">
|
| 622 |
+
<div style="background: white; border: 1px solid #ebdccb; border-radius: 12px; padding: 10px;">
|
| 623 |
+
<span style="font-size: 18px; display: block;">📚</span>
|
| 624 |
+
<strong style="font-size: 15px; display: block; color: #1c1c19;">5</strong>
|
| 625 |
+
<span style="font-size: 9px; text-transform: uppercase; color: #6f6257;">Stories</span>
|
| 626 |
+
</div>
|
| 627 |
+
<div style="background: white; border: 1px solid #ebdccb; border-radius: 12px; padding: 10px;">
|
| 628 |
+
<span style="font-size: 18px; display: block;">🧠</span>
|
| 629 |
+
<strong style="font-size: 15px; display: block; color: #1c1c19;">3</strong>
|
| 630 |
+
<span style="font-size: 9px; text-transform: uppercase; color: #6f6257;">Models</span>
|
| 631 |
+
</div>
|
| 632 |
+
<div style="background: white; border: 1px solid #ebdccb; border-radius: 12px; padding: 10px;">
|
| 633 |
+
<span style="font-size: 18px; display: block;">🎙️</span>
|
| 634 |
+
<strong style="font-size: 15px; display: block; color: #1c1c19;">Qwen3</strong>
|
| 635 |
+
<span style="font-size: 9px; text-transform: uppercase; color: #6f6257;">TTS Engine</span>
|
| 636 |
+
</div>
|
| 637 |
+
</div>
|
| 638 |
+
""")
|
| 639 |
+
|
| 640 |
+
with gr.Column(scale=1, elem_classes="card-container"):
|
| 641 |
+
gr.HTML("""
|
| 642 |
+
<h3 class="serif-header" style="font-size: 18px; margin-bottom: 4px;">Model Pipeline</h3>
|
| 643 |
+
<p style="font-size: 12px; color: #6f6257; margin-bottom: 16px;">Active AI models powering the app.</p>
|
| 644 |
+
""")
|
| 645 |
+
|
| 646 |
+
gr.HTML("""
|
| 647 |
+
<div style="padding: 12px; background: white; border-radius: 12px; border: 1px solid #ebdccb;">
|
| 648 |
+
<div style="font-size: 11.5px; color: #1c1c19; line-height: 2;">
|
| 649 |
+
🎙️ <strong>Voice Cloning:</strong> Qwen3-TTS-1.7B-Base (bfloat16)<br>
|
| 650 |
+
🗣️ <strong>Stock TTS:</strong> Qwen3-TTS-0.6B-CustomVoice<br>
|
| 651 |
+
👂 <strong>ASR:</strong> Whisper-small<br>
|
| 652 |
+
🧠 <strong>Q&A:</strong> Qwen2.5-3B-Instruct
|
| 653 |
+
</div>
|
| 654 |
+
</div>
|
| 655 |
+
""")
|
| 656 |
+
|
| 657 |
+
# REACTIVE LOGIC
|
| 658 |
+
|
| 659 |
+
# 1. Search / filter shelf
|
| 660 |
+
def filter_books_shelf(query, category, current_books):
|
| 661 |
+
return generate_library_html(current_books, query=query, category_filt=category)
|
| 662 |
+
|
| 663 |
+
search_input.change(filter_books_shelf, inputs=[search_input, category_filter, books_state], outputs=shelf_grid)
|
| 664 |
+
category_filter.change(filter_books_shelf, inputs=[search_input, category_filter, books_state], outputs=shelf_grid)
|
| 665 |
+
|
| 666 |
+
# 2. Book card click → load into player
|
| 667 |
+
def handle_book_select(title_chosen, current_inventory, profile_id):
|
| 668 |
+
if not title_chosen:
|
| 669 |
+
return [gr.update()] * 12
|
| 670 |
+
selected = next((b for b in current_inventory if b["title"] == title_chosen), current_inventory[0])
|
| 671 |
+
|
| 672 |
+
# Show cloned voice name if profile exists
|
| 673 |
+
from voice_clone import has_profile, list_saved_profiles as _list_profiles
|
| 674 |
+
if profile_id and has_profile(profile_id):
|
| 675 |
+
saved = _list_profiles()
|
| 676 |
+
voice_label = next(
|
| 677 |
+
(p["voice_name"] for p in saved if p["profile_id"] == profile_id),
|
| 678 |
+
"Cloned Voice"
|
| 679 |
+
)
|
| 680 |
+
narrator_label = f"🎙️ {voice_label}"
|
| 681 |
+
narrator_color = "#4ade80"
|
| 682 |
+
else:
|
| 683 |
+
narrator_label = f"🔊 {selected['voice_name']} (stock)"
|
| 684 |
+
narrator_color = "#ffd3a6"
|
| 685 |
+
|
| 686 |
+
safe_title = html.escape(selected['title'])
|
| 687 |
+
safe_author = html.escape(selected['author'])
|
| 688 |
+
player_html = f"""
|
| 689 |
+
<div style="text-align: center; margin-bottom: 16px; margin-top: 8px;">
|
| 690 |
+
<img src="{selected['cover_url']}" style="width: 110px; height: 155px; object-fit: cover; border-radius: 12px; box-shadow: 0 4px 16px rgba(0,0,0,0.4); margin-bottom: 12px;" />
|
| 691 |
+
<h3 style="font-family: 'Playfair Display', Georgia, serif; font-size: 20px; margin:0; color:#FAF7F2;">{safe_title}</h3>
|
| 692 |
+
<p style="font-size: 12px; color: #94a3b8; font-style: italic; margin-top:2px;">by {safe_author}</p>
|
| 693 |
+
<span style="display: inline-block; background: rgba(245, 132, 31, 0.15); color: {narrator_color}; font-size: 10.5px; font-weight: 700; padding: 3px 8px; border-radius: 999px; margin-top: 6px;">Active Narrator: {narrator_label}</span>
|
| 694 |
+
</div>
|
| 695 |
+
"""
|
| 696 |
+
paras = load_paragraphs(selected["story_path"])
|
| 697 |
+
total = max(len(paras) - 1, 0)
|
| 698 |
+
tts_chunks = split_into_chunks("\n\n".join(paras))
|
| 699 |
+
chunk_html = f"""<div style="margin-top: 8px; font-size: 10px; color: #64748b; font-family: monospace; text-align: center;">{len(tts_chunks)} chunks ready — tap Play</div>"""
|
| 700 |
+
status_html = """
|
| 701 |
+
<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">
|
| 702 |
+
<span style="width: 8px; height: 8px; border-radius: 50%; background: #94a3b8; display: inline-block;"></span>
|
| 703 |
+
<span style="font-size: 11px; color: #94a3b8; font-family: monospace;">READY</span>
|
| 704 |
+
</div>
|
| 705 |
+
"""
|
| 706 |
+
story_html = render_story_text(paras, 0)
|
| 707 |
+
return (
|
| 708 |
+
player_html,
|
| 709 |
+
gr.Audio(visible=True),
|
| 710 |
+
status_html,
|
| 711 |
+
chunk_html,
|
| 712 |
+
gr.Button(visible=True), # play_btn
|
| 713 |
+
gr.Button(visible=False), # pause_btn
|
| 714 |
+
gr.Button(visible=False), # ask_btn
|
| 715 |
+
gr.HTML(visible=False), # story_finished_panel
|
| 716 |
+
paras, # paragraphs_state
|
| 717 |
+
tts_chunks, # tts_chunks_state
|
| 718 |
+
gr.HTML(value=story_html, visible=True), # story_text_display
|
| 719 |
+
gr.Slider(minimum=0, maximum=total, step=1, value=0, visible=True), # timeline_slider
|
| 720 |
+
)
|
| 721 |
+
|
| 722 |
+
book_selector.change(
|
| 723 |
+
handle_book_select,
|
| 724 |
+
inputs=[book_selector, books_state, voice_profile_state],
|
| 725 |
+
outputs=[player_title_info, player_audio_control, player_status_bar, chunk_status,
|
| 726 |
+
play_btn, pause_btn, ask_btn, story_finished_panel,
|
| 727 |
+
paragraphs_state, tts_chunks_state, story_text_display, timeline_slider]
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
# 3. Extract vocal weights trigger
|
| 731 |
+
def animate_cloning_pipeline(v_name, v_gender, recorder_data, progress=gr.Progress()):
|
| 732 |
+
if not v_name.strip():
|
| 733 |
+
return (
|
| 734 |
+
"""<div style="padding: 12px; background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; border-radius: 12px; font-size: 12px; font-weight: 600;">
|
| 735 |
+
Please provide a comforting nickname for your cloning candidate.
|
| 736 |
+
</div>""",
|
| 737 |
+
gr.HTML(visible=False),
|
| 738 |
+
gr.Audio(visible=False),
|
| 739 |
+
gr.Button(visible=False),
|
| 740 |
+
None,
|
| 741 |
+
)
|
| 742 |
+
if recorder_data is None:
|
| 743 |
+
return (
|
| 744 |
+
"""<div style="padding: 12px; background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; border-radius: 12px; font-size: 12px; font-weight: 600;">
|
| 745 |
+
Microphone recording sample missing. Speak some script lines!
|
| 746 |
+
</div>""",
|
| 747 |
+
gr.HTML(visible=False),
|
| 748 |
+
gr.Audio(visible=False),
|
| 749 |
+
gr.Button(visible=False),
|
| 750 |
+
None,
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
from voice_clone import create_voice_profile, synthesize_cloned_preview
|
| 754 |
+
import soundfile as sf
|
| 755 |
+
|
| 756 |
+
progress(0.1, desc="Extracting speaker embedding from recording...")
|
| 757 |
+
try:
|
| 758 |
+
profile_id = create_voice_profile(recorder_data, voice_name=v_name.strip())
|
| 759 |
+
except Exception as e:
|
| 760 |
+
import logging, traceback
|
| 761 |
+
logging.getLogger(__name__).exception("Voice cloning failed")
|
| 762 |
+
return (
|
| 763 |
+
f"""<div style="padding: 12px; background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; border-radius: 12px; font-size: 12px; font-weight: 600;">
|
| 764 |
+
Voice cloning failed: {html.escape(str(e))}
|
| 765 |
+
</div>""",
|
| 766 |
+
gr.HTML(visible=False),
|
| 767 |
+
gr.Audio(visible=False),
|
| 768 |
+
gr.Button(visible=False),
|
| 769 |
+
None,
|
| 770 |
+
)
|
| 771 |
+
|
| 772 |
+
progress(0.7, desc="Generating voice preview...")
|
| 773 |
+
try:
|
| 774 |
+
preview_wav, preview_sr = synthesize_cloned_preview(profile_id)
|
| 775 |
+
preview_path = f"sample_sounds/clone_preview_{profile_id}.wav"
|
| 776 |
+
sf.write(preview_path, preview_wav, preview_sr)
|
| 777 |
+
except Exception as e:
|
| 778 |
+
import logging
|
| 779 |
+
logging.getLogger(__name__).exception("Preview synthesis failed")
|
| 780 |
+
preview_path = None
|
| 781 |
+
|
| 782 |
+
progress(1.0, desc="Voice cloned successfully!")
|
| 783 |
+
|
| 784 |
+
safe_name = html.escape(v_name)
|
| 785 |
+
avatar = "👩" if v_gender == "Female" else "👨"
|
| 786 |
+
|
| 787 |
+
cloned_card_html = f"""
|
| 788 |
+
<div style="background: white; border: 1px solid #ebdccb; padding: 24px; border-radius: 16px; margin: 16px 0;">
|
| 789 |
+
<div style="display: flex; gap: 16px; align-items: center; margin-bottom: 12px;">
|
| 790 |
+
<div style="width: 48px; height: 48px; border-radius: 50%; background: #944a00; color: white; display: flex; align-items: center; justify-content: center; font-size: 24px;">
|
| 791 |
+
{avatar}
|
| 792 |
+
</div>
|
| 793 |
+
<div>
|
| 794 |
+
<h4 class="serif-header" style="font-size: 16px; margin: 0;">{safe_name} <span style="font-size: 9px; background: #f0fdf4; color: #16a34a; padding: 2px 6px; border-radius: 4px; font-weight:700;">Cloned successfully</span></h4>
|
| 795 |
+
<p style="font-size: 11px; color:#6f6257; margin-top:2px;">Synthesized today using Qwen3-TTS voice cloning</p>
|
| 796 |
+
</div>
|
| 797 |
+
</div>
|
| 798 |
+
<div style="background:#FAF7F2; border-left: 3px solid #f5841f; padding: 10px; font-family: Georgia, serif; font-style: italic; font-size: 12px; color: #1c1c19;">
|
| 799 |
+
Voice profile ready. Select a story and tap Play to hear narration in this voice.
|
| 800 |
+
</div>
|
| 801 |
+
</div>
|
| 802 |
+
"""
|
| 803 |
+
|
| 804 |
+
return (
|
| 805 |
+
gr.HTML(visible=False),
|
| 806 |
+
gr.HTML(value=cloned_card_html, visible=True),
|
| 807 |
+
gr.Audio(value=preview_path, visible=preview_path is not None),
|
| 808 |
+
gr.Button(visible=True),
|
| 809 |
+
profile_id,
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
extract_btn.click(
|
| 813 |
+
animate_cloning_pipeline,
|
| 814 |
+
inputs=[new_voice_name, new_voice_gender, mic_recorder],
|
| 815 |
+
outputs=[cloning_progress_msg, voice_cloning_success_panel, voice_sample_preview_widget, add_to_library_btn, voice_profile_state]
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
# 4. Add cloned voice to inventory
|
| 819 |
+
def save_new_cloned_voice(v_name, v_gender, list_voices, current_profile_id):
|
| 820 |
+
avatar = "👩" if v_gender == "Female" else "👨"
|
| 821 |
+
new_voice_item = {
|
| 822 |
+
"id": f"v-{time.time()}",
|
| 823 |
+
"name": v_name,
|
| 824 |
+
"avatar_url": avatar,
|
| 825 |
+
"description": f"Custom cloned {v_gender.lower()} companion voice. Highly optimized.",
|
| 826 |
+
"gender": v_gender,
|
| 827 |
+
"created_date": "2026-06-06",
|
| 828 |
+
"status": "ready",
|
| 829 |
+
"profile_id": current_profile_id,
|
| 830 |
+
}
|
| 831 |
+
updated = [new_voice_item] + list_voices
|
| 832 |
+
return (
|
| 833 |
+
updated,
|
| 834 |
+
render_cloned_voices_html(updated),
|
| 835 |
+
gr.HTML(visible=True, value="""<div style="text-align: center; padding: 32px 0;"><span style="font-size:42px;">🎙️</span><p style="margin-top:12px; font-size:14px; color:#6f6257;">Vocal profile saved successfully!</p></div>"""),
|
| 836 |
+
gr.HTML(visible=False),
|
| 837 |
+
gr.Audio(visible=False),
|
| 838 |
+
gr.Button(visible=False),
|
| 839 |
+
gr.Textbox(value="")
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
add_to_library_btn.click(
|
| 843 |
+
save_new_cloned_voice,
|
| 844 |
+
inputs=[new_voice_name, new_voice_gender, voices_state, voice_profile_state],
|
| 845 |
+
outputs=[voices_state, cloned_voices_list_grid, cloning_progress_msg, voice_cloning_success_panel, voice_sample_preview_widget, add_to_library_btn, new_voice_name]
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
# Voice card selection — update voice_profile_state when a card is clicked
|
| 849 |
+
def handle_voice_select(selected_id, voices):
|
| 850 |
+
"""Map selected voice ID to profile_id for TTS."""
|
| 851 |
+
if not selected_id:
|
| 852 |
+
return gr.update()
|
| 853 |
+
# Check if it matches a saved profile ID directly
|
| 854 |
+
from voice_clone import has_profile
|
| 855 |
+
if has_profile(selected_id):
|
| 856 |
+
return selected_id
|
| 857 |
+
# Check if it matches a voice in the list with a profile_id
|
| 858 |
+
for v in voices:
|
| 859 |
+
if v.get('profile_id') == selected_id or v.get('id') == selected_id:
|
| 860 |
+
pid = v.get('profile_id')
|
| 861 |
+
if pid and has_profile(pid):
|
| 862 |
+
return pid
|
| 863 |
+
# No valid profile — use stock voice (None)
|
| 864 |
+
return None
|
| 865 |
+
|
| 866 |
+
voice_selector.change(
|
| 867 |
+
handle_voice_select,
|
| 868 |
+
inputs=[voice_selector, voices_state],
|
| 869 |
+
outputs=[voice_profile_state]
|
| 870 |
+
)
|
| 871 |
+
|
| 872 |
+
# 5. Play button — streams TTS audio chunk by chunk
|
| 873 |
+
def stream_tts(tts_chunks, paras, profile_id):
|
| 874 |
+
import logging as _log
|
| 875 |
+
_log.getLogger(__name__).info("stream_tts called with profile_id=%s", profile_id)
|
| 876 |
+
|
| 877 |
+
voice_mode = "🎙️ Cloned Voice" if profile_id else "🔊 Stock Voice"
|
| 878 |
+
_status_playing = f"""
|
| 879 |
+
<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">
|
| 880 |
+
<span style="width: 8px; height: 8px; border-radius: 50%; background: #4ade80; display: inline-block;"></span>
|
| 881 |
+
<span style="font-size: 11px; color: #4ade80; font-family: monospace;">PLAYING — {voice_mode}</span>
|
| 882 |
+
</div>
|
| 883 |
+
"""
|
| 884 |
+
_status_done = """
|
| 885 |
+
<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">
|
| 886 |
+
<span style="width: 8px; height: 8px; border-radius: 50%; background: #94a3b8; display: inline-block;"></span>
|
| 887 |
+
<span style="font-size: 11px; color: #94a3b8; font-family: monospace;">DONE</span>
|
| 888 |
+
</div>
|
| 889 |
+
"""
|
| 890 |
+
|
| 891 |
+
n_paras = len(paras) if paras else 1
|
| 892 |
+
|
| 893 |
+
if not tts_chunks:
|
| 894 |
+
yield (gr.update(), _status_done,
|
| 895 |
+
"<div style='text-align:center;font-size:10px;color:#64748b;font-family:monospace;margin-top:8px;'>No content loaded</div>",
|
| 896 |
+
gr.Button(visible=True), gr.Button(visible=False), gr.Button(visible=False),
|
| 897 |
+
gr.Slider(value=0), render_story_text(paras, 0) if paras else "",
|
| 898 |
+
gr.HTML(visible=False),
|
| 899 |
+
gr.HTML(visible=False), gr.Group(visible=False), gr.Button(visible=False))
|
| 900 |
+
return
|
| 901 |
+
|
| 902 |
+
n = len(tts_chunks)
|
| 903 |
+
yield (gr.update(), _status_playing,
|
| 904 |
+
f"<div style='text-align:center;font-size:10px;color:#4ade80;font-family:monospace;margin-top:8px;'>Generating chunk 1 / {n}…</div>",
|
| 905 |
+
gr.Button(visible=False), gr.Button(visible=True), gr.Button(visible=False),
|
| 906 |
+
gr.Slider(value=0), render_story_text(paras, 0) if paras else "",
|
| 907 |
+
gr.HTML(visible=False),
|
| 908 |
+
gr.HTML(visible=False), gr.Group(visible=False), gr.Button(visible=False))
|
| 909 |
+
|
| 910 |
+
for sample_rate, wav, i, total, err in generate_audio_stream(tts_chunks, voice_profile_id=profile_id):
|
| 911 |
+
# Map chunk index to paragraph index
|
| 912 |
+
para_idx = min(int(i * n_paras / total), n_paras - 1) if total > 0 else 0
|
| 913 |
+
if err:
|
| 914 |
+
yield (gr.update(), f"<div style='color:#ef4444;font-size:11px;'>Error on chunk {i+1}: {err}</div>", "",
|
| 915 |
+
gr.Button(visible=True), gr.Button(visible=False), gr.Button(visible=False),
|
| 916 |
+
gr.Slider(value=para_idx), gr.update(), gr.HTML(visible=False),
|
| 917 |
+
gr.HTML(visible=False), gr.Group(visible=False), gr.Button(visible=False))
|
| 918 |
+
return
|
| 919 |
+
para_idx = min(int(i * n_paras / total), n_paras - 1) if total > 0 else 0
|
| 920 |
+
next_label = f"chunk {i+2} / {total}" if i + 1 < total else "last chunk"
|
| 921 |
+
chunk_html = f"<div style='text-align:center;font-size:10px;color:#4ade80;font-family:monospace;margin-top:8px;'>▶ Playing chunk {i+1} / {total} — generating {next_label}</div>"
|
| 922 |
+
is_last = (i + 1 >= total)
|
| 923 |
+
yield ((sample_rate, wav), _status_playing, chunk_html,
|
| 924 |
+
gr.Button(visible=False), gr.Button(visible=True), gr.Button(visible=True),
|
| 925 |
+
gr.Slider(value=para_idx), render_story_text(paras, para_idx),
|
| 926 |
+
gr.HTML(visible=is_last),
|
| 927 |
+
gr.HTML(visible=False), gr.Group(visible=False), gr.Button(visible=False))
|
| 928 |
+
|
| 929 |
+
done_html = f"<div style='text-align:center;font-size:10px;color:#94a3b8;font-family:monospace;margin-top:8px;'>✅ {n} chunks complete</div>"
|
| 930 |
+
yield (gr.update(), _status_done, done_html,
|
| 931 |
+
gr.Button(visible=True), gr.Button(visible=False), gr.Button(visible=False),
|
| 932 |
+
gr.Slider(value=max(n_paras - 1, 0)), render_story_text(paras, max(n_paras - 1, 0)),
|
| 933 |
+
gr.HTML(visible=True),
|
| 934 |
+
gr.HTML(visible=False), gr.Group(visible=False), gr.Button(visible=False))
|
| 935 |
+
|
| 936 |
+
play_event = play_btn.click(
|
| 937 |
+
stream_tts,
|
| 938 |
+
inputs=[tts_chunks_state, paragraphs_state, voice_profile_state],
|
| 939 |
+
outputs=[player_audio_control, player_status_bar, chunk_status, play_btn, pause_btn, ask_btn,
|
| 940 |
+
timeline_slider, story_text_display, story_finished_panel,
|
| 941 |
+
qa_panel, qa_input_group, resume_btn]
|
| 942 |
+
)
|
| 943 |
+
|
| 944 |
+
# 6. Pause button — PAUSED state
|
| 945 |
+
def enter_paused_state(slider_val, paras):
|
| 946 |
+
total = len(paras) if paras else 1
|
| 947 |
+
chunk_html = f"""<div style="margin-top: 8px; font-size: 10px; color: #f59e0b; font-family: monospace; text-align: center;">Paragraph {int(slider_val) + 1} / {total} — paused</div>"""
|
| 948 |
+
status_html = """
|
| 949 |
+
<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">
|
| 950 |
+
<span style="width: 8px; height: 8px; border-radius: 50%; background: #f59e0b; display: inline-block;"></span>
|
| 951 |
+
<span style="font-size: 11px; color: #f59e0b; font-family: monospace;">PAUSED</span>
|
| 952 |
+
</div>
|
| 953 |
+
"""
|
| 954 |
+
return (
|
| 955 |
+
status_html,
|
| 956 |
+
chunk_html,
|
| 957 |
+
gr.Button(visible=True),
|
| 958 |
+
gr.Button(visible=False),
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
pause_btn.click(
|
| 962 |
+
enter_paused_state,
|
| 963 |
+
inputs=[timeline_slider, paragraphs_state],
|
| 964 |
+
outputs=[player_status_bar, chunk_status, play_btn, pause_btn],
|
| 965 |
+
cancels=[play_event]
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
# 7. Timeline slider → highlight current paragraph
|
| 969 |
+
def update_story_highlight(slider_val, paras):
|
| 970 |
+
idx = int(slider_val)
|
| 971 |
+
total = len(paras)
|
| 972 |
+
chunk_html = f"""<div style="margin-top: 8px; font-size: 10px; color: #64748b; font-family: monospace; text-align: center;">Paragraph {idx + 1} / {total}</div>"""
|
| 973 |
+
return render_story_text(paras, idx), chunk_html
|
| 974 |
+
|
| 975 |
+
timeline_slider.change(update_story_highlight, inputs=[timeline_slider, paragraphs_state], outputs=[story_text_display, chunk_status])
|
| 976 |
+
|
| 977 |
+
# 8. Ask button — PAUSED-ASKING state
|
| 978 |
+
def enter_asking_state():
|
| 979 |
+
status_html = """
|
| 980 |
+
<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">
|
| 981 |
+
<span style="width: 8px; height: 8px; border-radius: 50%; background: #f59e0b; display: inline-block; animation: pulse 1s infinite;"></span>
|
| 982 |
+
<span style="font-size: 11px; color: #f59e0b; font-family: monospace;">PAUSED — ASKING</span>
|
| 983 |
+
</div>
|
| 984 |
+
"""
|
| 985 |
+
return (
|
| 986 |
+
status_html,
|
| 987 |
+
gr.Button(visible=False),
|
| 988 |
+
gr.Button(visible=False),
|
| 989 |
+
gr.Button(visible=False),
|
| 990 |
+
gr.Button(visible=True),
|
| 991 |
+
gr.HTML(visible=True),
|
| 992 |
+
gr.Group(visible=True),
|
| 993 |
+
gr.HTML(visible=False),
|
| 994 |
+
gr.Audio(visible=False),
|
| 995 |
+
)
|
| 996 |
+
|
| 997 |
+
ask_btn.click(
|
| 998 |
+
enter_asking_state,
|
| 999 |
+
inputs=[],
|
| 1000 |
+
outputs=[player_status_bar, play_btn, pause_btn, ask_btn, resume_btn, qa_panel, qa_input_group, answer_display, answer_audio],
|
| 1001 |
+
cancels=[play_event],
|
| 1002 |
+
js="""() => {
|
| 1003 |
+
// Auto-start microphone recording after a brief delay for UI to render
|
| 1004 |
+
setTimeout(() => {
|
| 1005 |
+
const recordBtn = document.querySelector('#qa_audio_input button[aria-label="Record"], #qa_audio_input button.record-button, .qa-audio-group button[aria-label="Record"]');
|
| 1006 |
+
if (recordBtn) { recordBtn.click(); }
|
| 1007 |
+
else {
|
| 1008 |
+
// Fallback: find any record button inside the audio component
|
| 1009 |
+
const btns = document.querySelectorAll('button');
|
| 1010 |
+
for (const b of btns) {
|
| 1011 |
+
if (b.getAttribute('aria-label') === 'Record' || b.textContent.includes('Record')) {
|
| 1012 |
+
b.click(); break;
|
| 1013 |
+
}
|
| 1014 |
+
}
|
| 1015 |
+
}
|
| 1016 |
+
}, 500);
|
| 1017 |
+
}"""
|
| 1018 |
+
)
|
| 1019 |
+
|
| 1020 |
+
# 9. Submit question — LFM2.5-Audio end-to-end (single model: audio-in → audio+text-out)
|
| 1021 |
+
def handle_question_submit(question_txt, question_audio_path, paragraphs, slider_val, profile_id):
|
| 1022 |
+
q_txt = (question_txt or "").strip()
|
| 1023 |
+
has_audio = question_audio_path is not None and question_audio_path != ""
|
| 1024 |
+
|
| 1025 |
+
if not q_txt and not has_audio:
|
| 1026 |
+
answer_html = """
|
| 1027 |
+
<div style="padding: 10px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 10px; font-size: 12px; color: #991b1b;">
|
| 1028 |
+
Please type a question or record one with the microphone.
|
| 1029 |
+
</div>
|
| 1030 |
+
"""
|
| 1031 |
+
return gr.HTML(value=answer_html, visible=True), gr.Audio(visible=False)
|
| 1032 |
+
|
| 1033 |
+
# Build story context from paragraphs
|
| 1034 |
+
story_context = "\n\n".join(paragraphs) if paragraphs else ""
|
| 1035 |
+
|
| 1036 |
+
# Use LFM2.5-Audio end-to-end: accepts audio/text → produces text+audio answer
|
| 1037 |
+
import uuid
|
| 1038 |
+
import soundfile as sf
|
| 1039 |
+
import logging as _log
|
| 1040 |
+
|
| 1041 |
+
try:
|
| 1042 |
+
answer_text, waveform, sr = answer_question_audio(
|
| 1043 |
+
question_audio_path=question_audio_path if has_audio else None,
|
| 1044 |
+
question_text=q_txt if q_txt and not has_audio else None,
|
| 1045 |
+
story_context=story_context,
|
| 1046 |
+
max_new_tokens=200,
|
| 1047 |
+
)
|
| 1048 |
+
if not answer_text:
|
| 1049 |
+
answer_text = "Hmm, I'm not sure about that! Let's keep listening to find out."
|
| 1050 |
+
except Exception as e:
|
| 1051 |
+
answer_text = f"Oops, I couldn't think of an answer right now. Let's keep reading! ({type(e).__name__})"
|
| 1052 |
+
waveform = None
|
| 1053 |
+
sr = LFM_SR
|
| 1054 |
+
_log.getLogger(__name__).exception("LFM Q&A failed: %s", e)
|
| 1055 |
+
|
| 1056 |
+
# Save audio if LFM produced it
|
| 1057 |
+
answer_audio_path_out = None
|
| 1058 |
+
if waveform is not None:
|
| 1059 |
+
answer_audio_path_out = f"sample_sounds/qa_answer_{uuid.uuid4().hex[:8]}.wav"
|
| 1060 |
+
sf.write(answer_audio_path_out, waveform, sr)
|
| 1061 |
+
|
| 1062 |
+
# Display question text (transcribe if needed for display only)
|
| 1063 |
+
display_question = q_txt
|
| 1064 |
+
if not display_question and has_audio:
|
| 1065 |
+
display_question = "(audio question)"
|
| 1066 |
+
|
| 1067 |
+
safe_answer = html.escape(answer_text)
|
| 1068 |
+
safe_question = html.escape(display_question)
|
| 1069 |
+
answer_html = f"""
|
| 1070 |
+
<div style="margin-top: 12px; padding: 16px; background: rgba(240,253,244,0.1); border: 1px solid rgba(187,247,208,0.3); border-radius: 14px;">
|
| 1071 |
+
<div style="font-size: 10px; font-weight: 700; text-transform: uppercase; color: #4ade80; margin-bottom: 6px;">Answer (LFM2.5-Audio)</div>
|
| 1072 |
+
<div style="font-family: 'Playfair Display', Georgia, serif; font-style: italic; color: #FAF7F2; font-size: 13px; line-height: 1.6;">
|
| 1073 |
+
“{safe_answer}”
|
| 1074 |
+
</div>
|
| 1075 |
+
<div style="margin-top: 8px; font-size: 10px; color: #94a3b8;">
|
| 1076 |
+
Q: <em>{safe_question}</em>
|
| 1077 |
+
</div>
|
| 1078 |
+
</div>
|
| 1079 |
+
"""
|
| 1080 |
+
if answer_audio_path_out:
|
| 1081 |
+
return gr.HTML(value=answer_html, visible=True), gr.Audio(value=answer_audio_path_out, visible=True)
|
| 1082 |
+
return gr.HTML(value=answer_html, visible=True), gr.Audio(visible=False)
|
| 1083 |
+
|
| 1084 |
+
submit_question_btn.click(
|
| 1085 |
+
handle_question_submit,
|
| 1086 |
+
inputs=[question_text, question_audio, paragraphs_state, timeline_slider, voice_profile_state],
|
| 1087 |
+
outputs=[answer_display, answer_audio]
|
| 1088 |
+
)
|
| 1089 |
+
|
| 1090 |
+
# Auto-submit when voice recording completes
|
| 1091 |
+
# In Gradio 5.35, .stop_recording may not pass audio value reliably.
|
| 1092 |
+
# Use .stop_recording with a small delay via JS to click the submit button.
|
| 1093 |
+
question_audio.stop_recording(
|
| 1094 |
+
fn=None,
|
| 1095 |
+
inputs=None,
|
| 1096 |
+
outputs=None,
|
| 1097 |
+
js="""() => {
|
| 1098 |
+
// Wait for audio value to be committed, then click submit
|
| 1099 |
+
setTimeout(() => {
|
| 1100 |
+
const btn = document.querySelector('#qa_submit_btn button, #qa_submit_btn');
|
| 1101 |
+
if (btn) btn.click();
|
| 1102 |
+
}, 500);
|
| 1103 |
+
}"""
|
| 1104 |
+
)
|
| 1105 |
+
|
| 1106 |
+
# .change() as primary Python handler — fires after audio value is committed
|
| 1107 |
+
def auto_submit_on_audio(audio_path, question_txt, paragraphs, slider_val, profile_id):
|
| 1108 |
+
"""Auto-submit when a recording is available."""
|
| 1109 |
+
if not audio_path:
|
| 1110 |
+
return gr.update(), gr.update()
|
| 1111 |
+
return handle_question_submit(question_txt, audio_path, paragraphs, slider_val, profile_id)
|
| 1112 |
+
|
| 1113 |
+
question_audio.change(
|
| 1114 |
+
auto_submit_on_audio,
|
| 1115 |
+
inputs=[question_audio, question_text, paragraphs_state, timeline_slider, voice_profile_state],
|
| 1116 |
+
outputs=[answer_display, answer_audio]
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
# 10. Resume button — dismiss Q&A panel, show Play to continue
|
| 1120 |
+
def enter_resume_state():
|
| 1121 |
+
status_html = """
|
| 1122 |
+
<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">
|
| 1123 |
+
<span style="width: 8px; height: 8px; border-radius: 50%; background: #94a3b8; display: inline-block;"></span>
|
| 1124 |
+
<span style="font-size: 11px; color: #94a3b8; font-family: monospace;">READY — Tap Play to continue</span>
|
| 1125 |
+
</div>
|
| 1126 |
+
"""
|
| 1127 |
+
return (
|
| 1128 |
+
status_html,
|
| 1129 |
+
gr.Button(visible=True), # play_btn
|
| 1130 |
+
gr.Button(visible=False), # pause_btn
|
| 1131 |
+
gr.Button(visible=True), # ask_btn — keep visible so user can ask again
|
| 1132 |
+
gr.Button(visible=False), # resume_btn
|
| 1133 |
+
gr.HTML(visible=False), # qa_panel
|
| 1134 |
+
gr.Group(visible=False), # qa_input_group
|
| 1135 |
+
gr.HTML(visible=False), # answer_display
|
| 1136 |
+
gr.Audio(visible=False), # answer_audio
|
| 1137 |
+
gr.Textbox(value=""), # question_text — clear previous question
|
| 1138 |
+
None, # question_audio — clear previous recording
|
| 1139 |
+
)
|
| 1140 |
+
|
| 1141 |
+
resume_btn.click(
|
| 1142 |
+
enter_resume_state,
|
| 1143 |
+
inputs=[],
|
| 1144 |
+
outputs=[player_status_bar, play_btn, pause_btn, ask_btn, resume_btn, qa_panel, qa_input_group, answer_display, answer_audio, question_text, question_audio]
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
# 11. Pause playback when switching to other tabs
|
| 1148 |
+
def pause_on_tab_switch():
|
| 1149 |
+
status_html = """
|
| 1150 |
+
<div style="margin-top: 12px; display: flex; align-items: center; gap: 10px; justify-content: center;">
|
| 1151 |
+
<span style="width: 8px; height: 8px; border-radius: 50%; background: #f59e0b; display: inline-block;"></span>
|
| 1152 |
+
<span style="font-size: 11px; color: #f59e0b; font-family: monospace;">PAUSED</span>
|
| 1153 |
+
</div>
|
| 1154 |
+
"""
|
| 1155 |
+
return status_html, gr.Button(visible=True), gr.Button(visible=False)
|
| 1156 |
+
|
| 1157 |
+
explore_tab.select(
|
| 1158 |
+
pause_on_tab_switch,
|
| 1159 |
+
inputs=[],
|
| 1160 |
+
outputs=[player_status_bar, play_btn, pause_btn],
|
| 1161 |
+
cancels=[play_event]
|
| 1162 |
+
)
|
| 1163 |
+
clone_tab.select(
|
| 1164 |
+
pause_on_tab_switch,
|
| 1165 |
+
inputs=[],
|
| 1166 |
+
outputs=[player_status_bar, play_btn, pause_btn],
|
| 1167 |
+
cancels=[play_event]
|
| 1168 |
+
)
|
| 1169 |
+
|
| 1170 |
+
if __name__ == "__main__":
|
| 1171 |
+
demo.queue().launch(allowed_paths=[str(Path(__file__).parent / "assets")])
|
inference_lfm.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LFM2.5-Audio-1.5B inference module — end-to-end audio Q&A.
|
| 3 |
+
|
| 4 |
+
Replaces the 3-model pipeline (Whisper ASR + Qwen Q&A + Qwen TTS) with a single
|
| 5 |
+
multimodal model that accepts audio/text input and produces audio+text output.
|
| 6 |
+
"""
|
| 7 |
+
import logging
|
| 8 |
+
import torch
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
_processor = None
|
| 14 |
+
_model = None
|
| 15 |
+
|
| 16 |
+
HF_REPO = "LiquidAI/LFM2.5-Audio-1.5B"
|
| 17 |
+
SAMPLE_RATE = 24000
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_lfm_model():
|
| 21 |
+
"""Load LFM2.5-Audio-1.5B model. Cached after first call."""
|
| 22 |
+
global _processor, _model
|
| 23 |
+
if _model is None:
|
| 24 |
+
from liquid_audio import LFM2AudioModel, LFM2AudioProcessor
|
| 25 |
+
|
| 26 |
+
logger.info("Loading %s...", HF_REPO)
|
| 27 |
+
_processor = LFM2AudioProcessor.from_pretrained(HF_REPO).eval()
|
| 28 |
+
_model = LFM2AudioModel.from_pretrained(HF_REPO).eval()
|
| 29 |
+
logger.info("LFM2.5-Audio loaded.")
|
| 30 |
+
return _processor, _model
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def answer_question_audio(
|
| 34 |
+
question_audio_path: str | None = None,
|
| 35 |
+
question_text: str | None = None,
|
| 36 |
+
story_context: str = "",
|
| 37 |
+
max_new_tokens: int = 200,
|
| 38 |
+
) -> tuple[str, np.ndarray | None, int]:
|
| 39 |
+
"""
|
| 40 |
+
Answer a question about the story using LFM2.5-Audio end-to-end.
|
| 41 |
+
|
| 42 |
+
Accepts either audio input (child's voice) or text input.
|
| 43 |
+
Returns (answer_text, audio_waveform_or_None, sample_rate).
|
| 44 |
+
"""
|
| 45 |
+
from liquid_audio import ChatState, LFMModality
|
| 46 |
+
|
| 47 |
+
processor, model = get_lfm_model()
|
| 48 |
+
|
| 49 |
+
chat = ChatState(processor)
|
| 50 |
+
|
| 51 |
+
# System prompt with story context
|
| 52 |
+
chat.new_turn("system")
|
| 53 |
+
system_prompt = (
|
| 54 |
+
"You are a friendly storyteller answering a child's question about a bedtime story. "
|
| 55 |
+
"Answer in 1-2 short, simple sentences using warm, age-appropriate language. "
|
| 56 |
+
"Only use information from the story context below.\n\n"
|
| 57 |
+
f"Story context:\n{story_context[:3000]}"
|
| 58 |
+
)
|
| 59 |
+
chat.add_text(system_prompt)
|
| 60 |
+
chat.end_turn()
|
| 61 |
+
|
| 62 |
+
# User turn — audio or text
|
| 63 |
+
chat.new_turn("user")
|
| 64 |
+
if question_audio_path:
|
| 65 |
+
import torchaudio
|
| 66 |
+
wav, sr = torchaudio.load(question_audio_path)
|
| 67 |
+
# Resample to 16kHz if needed (model expects 16kHz input)
|
| 68 |
+
if sr != 16000:
|
| 69 |
+
wav = torchaudio.functional.resample(wav, sr, 16000)
|
| 70 |
+
sr = 16000
|
| 71 |
+
chat.add_audio(wav, sr)
|
| 72 |
+
elif question_text:
|
| 73 |
+
chat.add_text(question_text)
|
| 74 |
+
else:
|
| 75 |
+
return "Please ask a question!", None, SAMPLE_RATE
|
| 76 |
+
chat.end_turn()
|
| 77 |
+
|
| 78 |
+
# Generate answer
|
| 79 |
+
chat.new_turn("assistant")
|
| 80 |
+
text_out = []
|
| 81 |
+
audio_out = []
|
| 82 |
+
|
| 83 |
+
for t in model.generate_interleaved(
|
| 84 |
+
**chat,
|
| 85 |
+
max_new_tokens=max_new_tokens,
|
| 86 |
+
audio_temperature=1.0,
|
| 87 |
+
audio_top_k=4,
|
| 88 |
+
):
|
| 89 |
+
if t.numel() == 1:
|
| 90 |
+
text_out.append(t)
|
| 91 |
+
else:
|
| 92 |
+
audio_out.append(t)
|
| 93 |
+
|
| 94 |
+
# Decode text
|
| 95 |
+
answer_text = ""
|
| 96 |
+
if text_out:
|
| 97 |
+
answer_text = "".join(processor.text.decode(t) for t in text_out).strip()
|
| 98 |
+
|
| 99 |
+
# Decode audio
|
| 100 |
+
waveform = None
|
| 101 |
+
if audio_out and len(audio_out) > 1:
|
| 102 |
+
audio_codes = torch.stack(audio_out[:-1], 1).unsqueeze(0)
|
| 103 |
+
waveform_tensor = processor.decode(audio_codes)
|
| 104 |
+
waveform = waveform_tensor.cpu().numpy().squeeze()
|
| 105 |
+
|
| 106 |
+
return answer_text, waveform, SAMPLE_RATE
|
requirements_lfm.txt
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.35.0
|
| 2 |
+
transformers
|
| 3 |
+
torch
|
| 4 |
+
accelerate
|
| 5 |
+
bitsandbytes
|
| 6 |
+
soundfile
|
| 7 |
+
numpy
|
| 8 |
+
librosa
|
| 9 |
+
torchaudio
|
| 10 |
+
|
| 11 |
+
# LFM2.5-Audio end-to-end model
|
| 12 |
+
liquid-audio
|
| 13 |
+
|
| 14 |
+
# Qwen3-TTS (voice cloning + stock voice for narration)
|
| 15 |
+
qwen-tts>=0.1.1
|
| 16 |
+
huggingface-hub>=0.23.0
|
| 17 |
+
|
| 18 |
+
# FlashAttention-2 — install separately on GPU machines:
|
| 19 |
+
# pip install flash-attn --no-build-isolation
|
| 20 |
+
# Falls back to SDPA (PyTorch native) if not available.
|