Enhance music generation functionality by introducing a tape-length slider and progress tracking. Updated app.py to manage chunk lengths and progress callbacks, while frontend files now include a slider for selecting tape length and a progress bar to visualize the brewing process. Improved user experience during audio generation with real-time feedback on progress.
Browse files- app.py +113 -20
- frontend/index.html +14 -0
- frontend/main.js +14 -4
- frontend/style.css +91 -0
- frontend/ui.js +55 -1
app.py
CHANGED
|
@@ -33,13 +33,26 @@ ROOT = Path(__file__).parent
|
|
| 33 |
FRONTEND = ROOT / "frontend"
|
| 34 |
|
| 35 |
ENGINE = os.getenv("LOFINITY_ENGINE", "musicgen")
|
| 36 |
-
# 30s is musicgen-small's single-shot max (1500 tokens
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434")
|
| 39 |
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "llama3.2:3b")
|
| 40 |
|
| 41 |
app = Server(title="LoFinity")
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
# --- prompt enrichment (Ollama) ----------------------------------------------
|
| 44 |
|
| 45 |
ENRICH_SYSTEM = """\
|
|
@@ -162,57 +175,131 @@ def encode_wav(samples, rate: int) -> str:
|
|
| 162 |
return f"data:audio/wav;base64,{b64}"
|
| 163 |
|
| 164 |
|
| 165 |
-
def
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
import torch
|
| 168 |
|
| 169 |
processor, model, device = load_musicgen()
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
with torch.no_grad():
|
| 174 |
audio = model.generate(
|
| 175 |
**inputs,
|
| 176 |
do_sample=True,
|
| 177 |
guidance_scale=3.0,
|
| 178 |
-
max_new_tokens=int(
|
| 179 |
)
|
| 180 |
return audio[0, 0].cpu().float().numpy()
|
| 181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
try:
|
| 183 |
-
samples =
|
| 184 |
except Exception as e: # noqa: BLE001
|
| 185 |
if device == "mps":
|
| 186 |
print(f"[lofinity] mps generation failed ({e!r}), retrying on cpu")
|
| 187 |
model.to("cpu")
|
| 188 |
-
samples =
|
| 189 |
else:
|
| 190 |
raise
|
| 191 |
-
return samples,
|
| 192 |
|
| 193 |
|
| 194 |
-
def stub_engine(_music_prompt: str) -> tuple:
|
| 195 |
-
"""A short audible tone — handy when developing without the heavy model.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
import numpy as np
|
| 197 |
|
| 198 |
rate = 22050
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
|
| 205 |
# --- API -----------------------------------------------------------------------
|
| 206 |
|
| 207 |
|
| 208 |
@app.api(name="generate_song", concurrency_limit=1)
|
| 209 |
-
def generate_song(prompt: str) -> dict:
|
| 210 |
import ambience
|
| 211 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
music_prompt, title, bed = enrich_prompt(prompt)
|
| 213 |
-
print(f"[lofinity] brewing {title!r} :: {music_prompt} [+ {bed}]")
|
| 214 |
engine = stub_engine if ENGINE == "stub" else musicgen_engine
|
| 215 |
-
samples, rate = engine(
|
|
|
|
|
|
|
|
|
|
| 216 |
try:
|
| 217 |
samples = ambience.mix(samples, rate, bed)
|
| 218 |
except Exception as e: # noqa: BLE001 — a dry tape beats a failed vend
|
|
@@ -223,6 +310,12 @@ def generate_song(prompt: str) -> dict:
|
|
| 223 |
return {"title": title, "audio": encode_wav(samples, rate)}
|
| 224 |
|
| 225 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
@app.get("/")
|
| 227 |
async def homepage():
|
| 228 |
return FileResponse(FRONTEND / "index.html")
|
|
|
|
| 33 |
FRONTEND = ROOT / "frontend"
|
| 34 |
|
| 35 |
ENGINE = os.getenv("LOFINITY_ENGINE", "musicgen")
|
| 36 |
+
# 30s is musicgen-small's single-shot max (1500 tokens). Longer tapes are
|
| 37 |
+
# stitched from 30s chunks: each one re-seeds the model with the last OVERLAP_S
|
| 38 |
+
# of the track so it keeps playing from there. musicgen-small's context is 2048
|
| 39 |
+
# tokens (~41s at 50 tok/s), so a 6s seed + 30s of new audio (1800 tokens) fits.
|
| 40 |
+
CHUNK_S = 30 # length of each musicgen single-shot
|
| 41 |
+
OVERLAP_S = 6 # tail fed back as the continuation seed
|
| 42 |
+
SEAM_S = 0.4 # equal-power crossfade at each stitch, to hide the join
|
| 43 |
+
# the lengths the tape-length slider offers; the API snaps any value to one
|
| 44 |
+
ALLOWED_SECONDS = (30, 60, 90)
|
| 45 |
+
DEFAULT_SECONDS = int(os.getenv("LOFINITY_DURATION", "30"))
|
| 46 |
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434")
|
| 47 |
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "llama3.2:3b")
|
| 48 |
|
| 49 |
app = Server(title="LoFinity")
|
| 50 |
|
| 51 |
+
# How far along the current brew is, in whole 30s chunks. generate_song runs one
|
| 52 |
+
# at a time (concurrency_limit=1), so a single shared counter is enough; the
|
| 53 |
+
# frontend polls /api/progress to fill its brewing bar.
|
| 54 |
+
_PROGRESS = {"done": 0, "total": 1}
|
| 55 |
+
|
| 56 |
# --- prompt enrichment (Ollama) ----------------------------------------------
|
| 57 |
|
| 58 |
ENRICH_SYSTEM = """\
|
|
|
|
| 175 |
return f"data:audio/wav;base64,{b64}"
|
| 176 |
|
| 177 |
|
| 178 |
+
def _rms(x) -> float:
|
| 179 |
+
import numpy as np
|
| 180 |
+
|
| 181 |
+
return float(np.sqrt(np.mean(np.square(x)))) if len(x) else 0.0
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _match_rms(chunk, target: float):
|
| 185 |
+
"""Scale a fresh continuation to the first chunk's loudness. MusicGen
|
| 186 |
+
continuations drift quieter each round; re-leveling keeps a long tape even."""
|
| 187 |
+
r = _rms(chunk)
|
| 188 |
+
if r < 1e-6 or target < 1e-6:
|
| 189 |
+
return chunk
|
| 190 |
+
return chunk * min(4.0, target / r) # cap the boost so a quiet tail can't blow up
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _stitch(base, tail, rate: int):
|
| 194 |
+
"""Append `tail` to `base` with a short equal-power crossfade at the seam."""
|
| 195 |
+
import numpy as np
|
| 196 |
+
|
| 197 |
+
seam = int(SEAM_S * rate)
|
| 198 |
+
if seam <= 0 or len(base) < seam or len(tail) < seam:
|
| 199 |
+
return np.concatenate([base, tail])
|
| 200 |
+
t = np.linspace(0.0, 1.0, seam)
|
| 201 |
+
fade_out, fade_in = np.cos(t * np.pi / 2), np.sin(t * np.pi / 2)
|
| 202 |
+
blended = base[-seam:] * fade_out + tail[:seam] * fade_in
|
| 203 |
+
return np.concatenate([base[:-seam], blended, tail[seam:]])
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def musicgen_engine(music_prompt: str, seconds: int = CHUNK_S, progress_cb=None) -> tuple:
|
| 207 |
+
"""Returns (samples, sample_rate). Tapes longer than one 30s shot are built
|
| 208 |
+
by re-seeding the model with the last OVERLAP_S and stitching the chunks.
|
| 209 |
+
progress_cb(done, total) is called after each chunk finishes."""
|
| 210 |
import torch
|
| 211 |
|
| 212 |
processor, model, device = load_musicgen()
|
| 213 |
+
rate = model.config.audio_encoder.sampling_rate
|
| 214 |
+
overlap = int(OVERLAP_S * rate)
|
| 215 |
+
rounds = max(0, round(seconds / CHUNK_S) - 1) # 30->0, 60->1, 90->2
|
| 216 |
+
total = rounds + 1
|
| 217 |
+
|
| 218 |
+
def shot(dev, seed=None, new_s=CHUNK_S):
|
| 219 |
+
if seed is None:
|
| 220 |
+
inputs = processor(text=[music_prompt], padding=True, return_tensors="pt")
|
| 221 |
+
else:
|
| 222 |
+
inputs = processor(
|
| 223 |
+
audio=seed, sampling_rate=rate, text=[music_prompt],
|
| 224 |
+
padding=True, return_tensors="pt",
|
| 225 |
+
)
|
| 226 |
+
inputs = inputs.to(dev)
|
| 227 |
with torch.no_grad():
|
| 228 |
audio = model.generate(
|
| 229 |
**inputs,
|
| 230 |
do_sample=True,
|
| 231 |
guidance_scale=3.0,
|
| 232 |
+
max_new_tokens=int(new_s * 50), # ~50 tokens per second
|
| 233 |
)
|
| 234 |
return audio[0, 0].cpu().float().numpy()
|
| 235 |
|
| 236 |
+
def build(dev):
|
| 237 |
+
track = shot(dev) # first 30s straight from the prompt
|
| 238 |
+
if progress_cb:
|
| 239 |
+
progress_cb(1, total)
|
| 240 |
+
base_rms = _rms(track)
|
| 241 |
+
for i in range(rounds):
|
| 242 |
+
out = shot(dev, seed=track[-overlap:]) # continue from the last 6s
|
| 243 |
+
fresh = _match_rms(out[overlap:], base_rms) # drop the re-encoded seed
|
| 244 |
+
track = _stitch(track, fresh, rate)
|
| 245 |
+
if progress_cb:
|
| 246 |
+
progress_cb(i + 2, total)
|
| 247 |
+
print(f"[lofinity] stitched chunk {i + 2}/{total}")
|
| 248 |
+
return track
|
| 249 |
+
|
| 250 |
try:
|
| 251 |
+
samples = build(device)
|
| 252 |
except Exception as e: # noqa: BLE001
|
| 253 |
if device == "mps":
|
| 254 |
print(f"[lofinity] mps generation failed ({e!r}), retrying on cpu")
|
| 255 |
model.to("cpu")
|
| 256 |
+
samples = build("cpu")
|
| 257 |
else:
|
| 258 |
raise
|
| 259 |
+
return samples, rate
|
| 260 |
|
| 261 |
|
| 262 |
+
def stub_engine(_music_prompt: str, seconds: int = CHUNK_S, progress_cb=None) -> tuple:
|
| 263 |
+
"""A short audible tone — handy when developing without the heavy model.
|
| 264 |
+
Honors `seconds` and fakes per-chunk timing so the length slider and the
|
| 265 |
+
brewing progress bar can be exercised without MusicGen."""
|
| 266 |
+
import time
|
| 267 |
+
|
| 268 |
import numpy as np
|
| 269 |
|
| 270 |
rate = 22050
|
| 271 |
+
total = max(1, round(seconds / CHUNK_S))
|
| 272 |
+
for i in range(total):
|
| 273 |
+
time.sleep(0.8) # pretend each 30s chunk takes a moment to render
|
| 274 |
+
if progress_cb:
|
| 275 |
+
progress_cb(i + 1, total)
|
| 276 |
+
secs = float(seconds)
|
| 277 |
+
t = np.arange(int(rate * secs)) / rate
|
| 278 |
+
fade = np.minimum(1.0, np.minimum(t * 4, (secs - t) * 4))
|
| 279 |
+
# a slow wobble so a longer stub is audibly (and visibly) longer
|
| 280 |
+
return 0.25 * fade * np.sin(2 * np.pi * 220 * t) * (0.8 + 0.2 * np.sin(t)), rate
|
| 281 |
|
| 282 |
|
| 283 |
# --- API -----------------------------------------------------------------------
|
| 284 |
|
| 285 |
|
| 286 |
@app.api(name="generate_song", concurrency_limit=1)
|
| 287 |
+
def generate_song(prompt: str, seconds: int = DEFAULT_SECONDS) -> dict:
|
| 288 |
import ambience
|
| 289 |
|
| 290 |
+
# snap whatever the slider sends to a length we can actually build
|
| 291 |
+
seconds = min(ALLOWED_SECONDS, key=lambda s: abs(s - int(seconds)))
|
| 292 |
+
# reset progress up front, BEFORE the (sometimes slow) Ollama enrich step, so
|
| 293 |
+
# a poll arriving early sees this brew at 0% rather than the last one at 100%
|
| 294 |
+
chunks = max(1, round(seconds / CHUNK_S))
|
| 295 |
+
_PROGRESS.update(done=0, total=chunks)
|
| 296 |
music_prompt, title, bed = enrich_prompt(prompt)
|
| 297 |
+
print(f"[lofinity] brewing {title!r} ({seconds}s) :: {music_prompt} [+ {bed}]")
|
| 298 |
engine = stub_engine if ENGINE == "stub" else musicgen_engine
|
| 299 |
+
samples, rate = engine(
|
| 300 |
+
music_prompt, seconds, progress_cb=lambda d, t: _PROGRESS.update(done=d, total=t)
|
| 301 |
+
)
|
| 302 |
+
_PROGRESS.update(done=chunks, total=chunks)
|
| 303 |
try:
|
| 304 |
samples = ambience.mix(samples, rate, bed)
|
| 305 |
except Exception as e: # noqa: BLE001 — a dry tape beats a failed vend
|
|
|
|
| 310 |
return {"title": title, "audio": encode_wav(samples, rate)}
|
| 311 |
|
| 312 |
|
| 313 |
+
@app.get("/api/progress")
|
| 314 |
+
def progress() -> dict:
|
| 315 |
+
"""Chunks finished / total for the brew currently running, for the UI bar."""
|
| 316 |
+
return dict(_PROGRESS)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
@app.get("/")
|
| 320 |
async def homepage():
|
| 321 |
return FileResponse(FRONTEND / "index.html")
|
frontend/index.html
CHANGED
|
@@ -89,6 +89,19 @@
|
|
| 89 |
maxlength="200"
|
| 90 |
placeholder="rainy night in kyoto, soft piano, vinyl crackle..."
|
| 91 |
></textarea>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
<div id="generating" class="hidden">
|
| 93 |
<div class="grow-loader" aria-hidden="true">
|
| 94 |
<span class="sprout">
|
|
@@ -104,6 +117,7 @@
|
|
| 104 |
<i class="stem"></i><i class="leaf l"></i><i class="leaf r"></i><i class="bloom"></i>
|
| 105 |
</span>
|
| 106 |
</div>
|
|
|
|
| 107 |
<p class="led-status">
|
| 108 |
BREWING YOUR BEAT<span class="dots">...</span>
|
| 109 |
</p>
|
|
|
|
| 89 |
maxlength="200"
|
| 90 |
placeholder="rainy night in kyoto, soft piano, vinyl crackle..."
|
| 91 |
></textarea>
|
| 92 |
+
<div id="length-row">
|
| 93 |
+
<span class="len-label">LENGTH</span>
|
| 94 |
+
<input
|
| 95 |
+
id="length-slider"
|
| 96 |
+
type="range"
|
| 97 |
+
min="0"
|
| 98 |
+
max="2"
|
| 99 |
+
step="1"
|
| 100 |
+
value="0"
|
| 101 |
+
aria-label="tape length"
|
| 102 |
+
/>
|
| 103 |
+
<span id="length-value">0:30</span>
|
| 104 |
+
</div>
|
| 105 |
<div id="generating" class="hidden">
|
| 106 |
<div class="grow-loader" aria-hidden="true">
|
| 107 |
<span class="sprout">
|
|
|
|
| 117 |
<i class="stem"></i><i class="leaf l"></i><i class="leaf r"></i><i class="bloom"></i>
|
| 118 |
</span>
|
| 119 |
</div>
|
| 120 |
+
<div id="brew-bar" aria-hidden="true"><span id="brew-bar-fill"></span></div>
|
| 121 |
<p class="led-status">
|
| 122 |
BREWING YOUR BEAT<span class="dots">...</span>
|
| 123 |
</p>
|
frontend/main.js
CHANGED
|
@@ -482,9 +482,19 @@ try {
|
|
| 482 |
let generateFn = null;
|
| 483 |
|
| 484 |
const ui = initUI({
|
| 485 |
-
generate: (prompt) => {
|
| 486 |
if (!generateFn) return Promise.reject(new Error("backend not connected"));
|
| 487 |
-
return generateFn(prompt);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
},
|
| 489 |
onRequestClose: () => {
|
| 490 |
if (view.mode === "machine") closeMachineView();
|
|
@@ -508,8 +518,8 @@ const ui = initUI({
|
|
| 508 |
import("https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js")
|
| 509 |
.then(async ({ Client }) => {
|
| 510 |
const client = await Client.connect(window.location.origin);
|
| 511 |
-
generateFn = async (prompt) => {
|
| 512 |
-
const result = await client.predict("/generate_song", { prompt });
|
| 513 |
const data = result.data[0];
|
| 514 |
const dataUri = data.audio;
|
| 515 |
if (!dataUri) throw new Error("no audio in response");
|
|
|
|
| 482 |
let generateFn = null;
|
| 483 |
|
| 484 |
const ui = initUI({
|
| 485 |
+
generate: (prompt, seconds) => {
|
| 486 |
if (!generateFn) return Promise.reject(new Error("backend not connected"));
|
| 487 |
+
return generateFn(prompt, seconds);
|
| 488 |
+
},
|
| 489 |
+
// chunks-done/total for the brewing bar; a plain GET, independent of the
|
| 490 |
+
// gradio client so it answers while a generation is in flight
|
| 491 |
+
getProgress: async () => {
|
| 492 |
+
try {
|
| 493 |
+
const r = await fetch("/api/progress");
|
| 494 |
+
return r.ok ? await r.json() : null;
|
| 495 |
+
} catch {
|
| 496 |
+
return null;
|
| 497 |
+
}
|
| 498 |
},
|
| 499 |
onRequestClose: () => {
|
| 500 |
if (view.mode === "machine") closeMachineView();
|
|
|
|
| 518 |
import("https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js")
|
| 519 |
.then(async ({ Client }) => {
|
| 520 |
const client = await Client.connect(window.location.origin);
|
| 521 |
+
generateFn = async (prompt, seconds) => {
|
| 522 |
+
const result = await client.predict("/generate_song", { prompt, seconds });
|
| 523 |
const data = result.data[0];
|
| 524 |
const dataUri = data.audio;
|
| 525 |
if (!dataUri) throw new Error("no audio in response");
|
frontend/style.css
CHANGED
|
@@ -447,6 +447,72 @@ body {
|
|
| 447 |
opacity: 0.5;
|
| 448 |
}
|
| 449 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
#prompt-input.shake {
|
| 451 |
animation: shake 0.4s ease;
|
| 452 |
}
|
|
@@ -520,6 +586,30 @@ body {
|
|
| 520 |
box-shadow: 0 0 6px rgba(93, 255, 141, 0.25);
|
| 521 |
}
|
| 522 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
.sprout {
|
| 524 |
position: relative;
|
| 525 |
width: 18px;
|
|
@@ -907,6 +997,7 @@ body {
|
|
| 907 |
#error-msg.hidden,
|
| 908 |
#controls-row.hidden,
|
| 909 |
#prompt-input.hidden,
|
|
|
|
| 910 |
#generating.hidden,
|
| 911 |
#cassette-stage.hidden {
|
| 912 |
display: none;
|
|
|
|
| 447 |
opacity: 0.5;
|
| 448 |
}
|
| 449 |
|
| 450 |
+
/* tape-length slider — green-on-LED to match the dot-matrix screen */
|
| 451 |
+
#length-row {
|
| 452 |
+
display: flex;
|
| 453 |
+
align-items: center;
|
| 454 |
+
gap: 10px;
|
| 455 |
+
margin-top: 12px;
|
| 456 |
+
font-family: "DotGothic16", monospace;
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
.len-label {
|
| 460 |
+
flex: none;
|
| 461 |
+
font-size: 0.74rem;
|
| 462 |
+
letter-spacing: 0.12em;
|
| 463 |
+
color: #3fd470;
|
| 464 |
+
opacity: 0.85;
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
#length-value {
|
| 468 |
+
flex: none;
|
| 469 |
+
min-width: 34px;
|
| 470 |
+
text-align: right;
|
| 471 |
+
font-size: 0.84rem;
|
| 472 |
+
letter-spacing: 0.06em;
|
| 473 |
+
color: #5dff8d;
|
| 474 |
+
text-shadow: 0 0 6px rgba(93, 255, 141, 0.5);
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
#length-slider {
|
| 478 |
+
flex: 1;
|
| 479 |
+
-webkit-appearance: none;
|
| 480 |
+
appearance: none;
|
| 481 |
+
height: 6px;
|
| 482 |
+
border-radius: 3px;
|
| 483 |
+
background: rgba(93, 255, 141, 0.18);
|
| 484 |
+
border: 1px solid rgba(93, 255, 141, 0.25);
|
| 485 |
+
outline: none;
|
| 486 |
+
cursor: pointer;
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
#length-slider::-webkit-slider-thumb {
|
| 490 |
+
-webkit-appearance: none;
|
| 491 |
+
appearance: none;
|
| 492 |
+
width: 16px;
|
| 493 |
+
height: 16px;
|
| 494 |
+
border-radius: 50%;
|
| 495 |
+
background: #5dff8d;
|
| 496 |
+
box-shadow: 0 0 8px rgba(93, 255, 141, 0.85);
|
| 497 |
+
border: none;
|
| 498 |
+
cursor: pointer;
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
#length-slider::-moz-range-thumb {
|
| 502 |
+
width: 16px;
|
| 503 |
+
height: 16px;
|
| 504 |
+
border-radius: 50%;
|
| 505 |
+
background: #5dff8d;
|
| 506 |
+
box-shadow: 0 0 8px rgba(93, 255, 141, 0.85);
|
| 507 |
+
border: none;
|
| 508 |
+
cursor: pointer;
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
#length-slider:disabled {
|
| 512 |
+
opacity: 0.45;
|
| 513 |
+
cursor: default;
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
#prompt-input.shake {
|
| 517 |
animation: shake 0.4s ease;
|
| 518 |
}
|
|
|
|
| 586 |
box-shadow: 0 0 6px rgba(93, 255, 141, 0.25);
|
| 587 |
}
|
| 588 |
|
| 589 |
+
/* brew progress — fills in whole 30s-chunk steps as the backend stitches them
|
| 590 |
+
(e.g. a 1 min tape jumps to 50% when the first chunk lands). */
|
| 591 |
+
#brew-bar {
|
| 592 |
+
position: relative;
|
| 593 |
+
width: 80%;
|
| 594 |
+
max-width: 230px;
|
| 595 |
+
height: 6px;
|
| 596 |
+
margin: 16px auto 0;
|
| 597 |
+
border-radius: 3px;
|
| 598 |
+
background: rgba(93, 255, 141, 0.15);
|
| 599 |
+
border: 1px solid rgba(93, 255, 141, 0.25);
|
| 600 |
+
overflow: hidden;
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
#brew-bar-fill {
|
| 604 |
+
display: block;
|
| 605 |
+
width: 0%;
|
| 606 |
+
height: 100%;
|
| 607 |
+
border-radius: 3px;
|
| 608 |
+
background: #5dff8d;
|
| 609 |
+
box-shadow: 0 0 8px rgba(93, 255, 141, 0.6);
|
| 610 |
+
transition: width 0.3s ease;
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
.sprout {
|
| 614 |
position: relative;
|
| 615 |
width: 18px;
|
|
|
|
| 997 |
#error-msg.hidden,
|
| 998 |
#controls-row.hidden,
|
| 999 |
#prompt-input.hidden,
|
| 1000 |
+
#length-row.hidden,
|
| 1001 |
#generating.hidden,
|
| 1002 |
#cassette-stage.hidden {
|
| 1003 |
display: none;
|
frontend/ui.js
CHANGED
|
@@ -8,6 +8,7 @@ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
| 8 |
|
| 9 |
export function initUI({
|
| 10 |
generate,
|
|
|
|
| 11 |
onRequestClose,
|
| 12 |
onRequestCloseCollection,
|
| 13 |
onRequestCloseGameboy,
|
|
@@ -18,9 +19,22 @@ export function initUI({
|
|
| 18 |
const gameboyModal = $("gameboy-modal");
|
| 19 |
const playWaitBtn = $("play-while-waiting");
|
| 20 |
const input = $("prompt-input");
|
|
|
|
|
|
|
|
|
|
| 21 |
const coinBtn = $("coin-button");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
const controlsRow = $("controls-row");
|
| 23 |
const generating = $("generating");
|
|
|
|
| 24 |
const cassetteStage = $("cassette-stage");
|
| 25 |
const cassette = $("cassette");
|
| 26 |
const cassetteTitle = $("cassette-title");
|
|
@@ -77,11 +91,13 @@ export function initUI({
|
|
| 77 |
generating.classList.toggle("hidden", stage !== "generating");
|
| 78 |
cassetteStage.classList.toggle("hidden", stage !== "cassette");
|
| 79 |
playWaitBtn.classList.toggle("hidden", stage !== "generating");
|
|
|
|
| 80 |
input.classList.toggle("hidden", stage === "cassette");
|
| 81 |
input.disabled = stage === "generating";
|
| 82 |
if (stage === "prompt") {
|
| 83 |
controlsRow.classList.remove("inserting");
|
| 84 |
coinBtn.disabled = false;
|
|
|
|
| 85 |
}
|
| 86 |
}
|
| 87 |
|
|
@@ -95,6 +111,35 @@ export function initUI({
|
|
| 95 |
errorMsg.classList.remove("hidden");
|
| 96 |
}
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
async function startGeneration() {
|
| 99 |
if (busy) return;
|
| 100 |
const prompt = input.value.trim();
|
|
@@ -108,14 +153,18 @@ export function initUI({
|
|
| 108 |
busy = true;
|
| 109 |
errorMsg.classList.add("hidden");
|
| 110 |
coinBtn.disabled = true;
|
|
|
|
| 111 |
controlsRow.classList.add("inserting");
|
| 112 |
await delay(1200); // the wadōkaichin makes its way into the slot
|
| 113 |
setStage("generating");
|
| 114 |
onGeneratingChange(true);
|
|
|
|
| 115 |
try {
|
| 116 |
// hold the brewing moment even if the backend is fast
|
| 117 |
-
const
|
|
|
|
| 118 |
sessionTapes.unshift(result); // newest first, kept only for this session
|
|
|
|
| 119 |
loadCassette(result);
|
| 120 |
busy = false;
|
| 121 |
setStage("cassette");
|
|
@@ -125,6 +174,7 @@ export function initUI({
|
|
| 125 |
setStage("prompt");
|
| 126 |
showError("the machine jammed — try again?");
|
| 127 |
} finally {
|
|
|
|
| 128 |
onGeneratingChange(false);
|
| 129 |
syncPill();
|
| 130 |
}
|
|
@@ -445,6 +495,10 @@ export function initUI({
|
|
| 445 |
|
| 446 |
// --- modal controls ---------------------------------------------------------
|
| 447 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
coinBtn.addEventListener("click", startGeneration);
|
| 449 |
input.addEventListener("keydown", (e) => {
|
| 450 |
if (e.key === "Enter" && !e.shiftKey) {
|
|
|
|
| 8 |
|
| 9 |
export function initUI({
|
| 10 |
generate,
|
| 11 |
+
getProgress,
|
| 12 |
onRequestClose,
|
| 13 |
onRequestCloseCollection,
|
| 14 |
onRequestCloseGameboy,
|
|
|
|
| 19 |
const gameboyModal = $("gameboy-modal");
|
| 20 |
const playWaitBtn = $("play-while-waiting");
|
| 21 |
const input = $("prompt-input");
|
| 22 |
+
const lengthRow = $("length-row");
|
| 23 |
+
const lengthSlider = $("length-slider");
|
| 24 |
+
const lengthValue = $("length-value");
|
| 25 |
const coinBtn = $("coin-button");
|
| 26 |
+
|
| 27 |
+
// slider stops → (seconds sent to the backend, label on the screen). 1 min and
|
| 28 |
+
// 1.5 min are stitched from 30s chunks (the backend continues from the last 6s).
|
| 29 |
+
const LENGTHS = [
|
| 30 |
+
{ seconds: 30, label: "0:30" },
|
| 31 |
+
{ seconds: 60, label: "1:00" },
|
| 32 |
+
{ seconds: 90, label: "1:30" },
|
| 33 |
+
];
|
| 34 |
+
const selectedLength = () => LENGTHS[Number(lengthSlider.value)] ?? LENGTHS[0];
|
| 35 |
const controlsRow = $("controls-row");
|
| 36 |
const generating = $("generating");
|
| 37 |
+
const brewFill = $("brew-bar-fill");
|
| 38 |
const cassetteStage = $("cassette-stage");
|
| 39 |
const cassette = $("cassette");
|
| 40 |
const cassetteTitle = $("cassette-title");
|
|
|
|
| 91 |
generating.classList.toggle("hidden", stage !== "generating");
|
| 92 |
cassetteStage.classList.toggle("hidden", stage !== "cassette");
|
| 93 |
playWaitBtn.classList.toggle("hidden", stage !== "generating");
|
| 94 |
+
lengthRow.classList.toggle("hidden", stage !== "prompt");
|
| 95 |
input.classList.toggle("hidden", stage === "cassette");
|
| 96 |
input.disabled = stage === "generating";
|
| 97 |
if (stage === "prompt") {
|
| 98 |
controlsRow.classList.remove("inserting");
|
| 99 |
coinBtn.disabled = false;
|
| 100 |
+
lengthSlider.disabled = false;
|
| 101 |
}
|
| 102 |
}
|
| 103 |
|
|
|
|
| 111 |
errorMsg.classList.remove("hidden");
|
| 112 |
}
|
| 113 |
|
| 114 |
+
// --- brewing progress bar -------------------------------------------------
|
| 115 |
+
|
| 116 |
+
let brewTimer = null;
|
| 117 |
+
|
| 118 |
+
function setBrewProgress(frac) {
|
| 119 |
+
brewFill.style.width = `${Math.max(0, Math.min(1, frac)) * 100}%`;
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
// poll the backend for chunks-done while a tape brews; fills in 30s steps
|
| 123 |
+
function startBrewPolling() {
|
| 124 |
+
setBrewProgress(0);
|
| 125 |
+
if (!getProgress) return;
|
| 126 |
+
let sawFresh = false; // guard against reading the previous brew's leftover 100%
|
| 127 |
+
brewTimer = setInterval(async () => {
|
| 128 |
+
const p = await getProgress();
|
| 129 |
+
if (!p || !p.total) return;
|
| 130 |
+
if (!sawFresh) {
|
| 131 |
+
if (p.done < p.total) sawFresh = true; // this brew has actually started
|
| 132 |
+
else return; // a stale "complete" from the last tape — ignore it
|
| 133 |
+
}
|
| 134 |
+
setBrewProgress(p.done / p.total);
|
| 135 |
+
}, 600);
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
function stopBrewPolling() {
|
| 139 |
+
if (brewTimer) clearInterval(brewTimer);
|
| 140 |
+
brewTimer = null;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
async function startGeneration() {
|
| 144 |
if (busy) return;
|
| 145 |
const prompt = input.value.trim();
|
|
|
|
| 153 |
busy = true;
|
| 154 |
errorMsg.classList.add("hidden");
|
| 155 |
coinBtn.disabled = true;
|
| 156 |
+
lengthSlider.disabled = true; // lock the length in once the coin drops
|
| 157 |
controlsRow.classList.add("inserting");
|
| 158 |
await delay(1200); // the wadōkaichin makes its way into the slot
|
| 159 |
setStage("generating");
|
| 160 |
onGeneratingChange(true);
|
| 161 |
+
startBrewPolling();
|
| 162 |
try {
|
| 163 |
// hold the brewing moment even if the backend is fast
|
| 164 |
+
const seconds = selectedLength().seconds;
|
| 165 |
+
const [result] = await Promise.all([generate(prompt, seconds), delay(2600)]);
|
| 166 |
sessionTapes.unshift(result); // newest first, kept only for this session
|
| 167 |
+
setBrewProgress(1); // the tape's here — top the bar off
|
| 168 |
loadCassette(result);
|
| 169 |
busy = false;
|
| 170 |
setStage("cassette");
|
|
|
|
| 174 |
setStage("prompt");
|
| 175 |
showError("the machine jammed — try again?");
|
| 176 |
} finally {
|
| 177 |
+
stopBrewPolling();
|
| 178 |
onGeneratingChange(false);
|
| 179 |
syncPill();
|
| 180 |
}
|
|
|
|
| 495 |
|
| 496 |
// --- modal controls ---------------------------------------------------------
|
| 497 |
|
| 498 |
+
lengthSlider.addEventListener("input", () => {
|
| 499 |
+
lengthValue.textContent = selectedLength().label;
|
| 500 |
+
});
|
| 501 |
+
|
| 502 |
coinBtn.addEventListener("click", startGeneration);
|
| 503 |
input.addEventListener("keydown", (e) => {
|
| 504 |
if (e.key === "Enter" && !e.shiftKey) {
|