Update app.py
Browse files
app.py
CHANGED
|
@@ -27,7 +27,7 @@ def pick_writable_dir(candidates):
|
|
| 27 |
probe.unlink(missing_ok=True)
|
| 28 |
return p
|
| 29 |
except Exception as e:
|
| 30 |
-
errs.append(f"{p}: {type(e).
|
| 31 |
raise RuntimeError("No writable dir. Tried:\n " + "\n ".join(errs))
|
| 32 |
|
| 33 |
ENV_DIR = os.getenv("TTS_DATA_DIR")
|
|
@@ -79,6 +79,10 @@ STREAM_BATCH_MS = int(os.getenv("STREAM_BATCH_MS", "100")) # ~100 ms
|
|
| 79 |
|
| 80 |
DEFAULT_CH = 1 # mono
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
# Input clamp (basic DoS protection)
|
| 83 |
MAX_TEXT_CHARS = int(os.getenv("MAX_TEXT_CHARS", "800"))
|
| 84 |
|
|
@@ -234,10 +238,13 @@ async def piper_stream_raw(
|
|
| 234 |
length_scale: float,
|
| 235 |
noise_scale: float,
|
| 236 |
noise_w: float,
|
|
|
|
|
|
|
| 237 |
):
|
| 238 |
"""
|
| 239 |
-
|
| 240 |
-
|
|
|
|
| 241 |
"""
|
| 242 |
cmd = build_piper_cmd(text, voice, to_stdout=True,
|
| 243 |
length_scale=length_scale, noise_scale=noise_scale, noise_w=noise_w)
|
|
@@ -266,29 +273,72 @@ async def piper_stream_raw(
|
|
| 266 |
stderr_task = asyncio.create_task(pump_stderr())
|
| 267 |
total = 0
|
| 268 |
|
| 269 |
-
# framing
|
| 270 |
bytes_per_ms = max(1, int(sr * channels * 2 / 1000))
|
| 271 |
-
|
|
|
|
|
|
|
| 272 |
buf = bytearray()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
try:
|
| 275 |
while True:
|
| 276 |
-
chunk = await proc.stdout.read(
|
| 277 |
-
if
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
await proc.wait()
|
| 294 |
await stderr_task
|
|
@@ -333,8 +383,8 @@ def health():
|
|
| 333 |
# optional environment versions
|
| 334 |
try:
|
| 335 |
import numpy, onnxruntime as ort
|
| 336 |
-
numpy_version = numpy.
|
| 337 |
-
onnxruntime_version = ort.
|
| 338 |
except Exception:
|
| 339 |
numpy_version = onnxruntime_version = None
|
| 340 |
|
|
@@ -525,6 +575,9 @@ async def ws_tts(ws: WebSocket):
|
|
| 525 |
voice = DEFAULT_VOICE
|
| 526 |
length_scale, noise_scale, noise_w = 1.08, 0.35, 0.90
|
| 527 |
voice_sr = 22050 # will be set from config on init
|
|
|
|
|
|
|
|
|
|
| 528 |
|
| 529 |
try:
|
| 530 |
while True:
|
|
@@ -535,7 +588,7 @@ async def ws_tts(ws: WebSocket):
|
|
| 535 |
continue
|
| 536 |
ev = data.get("event")
|
| 537 |
if ev == "init":
|
| 538 |
-
# optional shared-secret over WS: accept via
|
| 539 |
token = (data.get("token") or "")
|
| 540 |
if AUTH_SHARED_SECRET and token != AUTH_SHARED_SECRET:
|
| 541 |
await ws.send_text(json.dumps({"event": "error", "detail": "unauthorized"}))
|
|
@@ -550,10 +603,17 @@ async def ws_tts(ws: WebSocket):
|
|
| 550 |
if "length_scale" not in data and "rate_wpm" in data:
|
| 551 |
try:
|
| 552 |
rate_wpm = int(data.get("rate_wpm", 165))
|
| 553 |
-
# crude monotonic mapping: faster WPM → smaller length_scale
|
| 554 |
length_scale = max(0.70, min(1.40, 165.0 / max(100, rate_wpm)))
|
| 555 |
except Exception:
|
| 556 |
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
try:
|
| 558 |
info = ensure_voice(voice)
|
| 559 |
voice_sr = int(info.get("sr", 22050))
|
|
@@ -571,7 +631,10 @@ async def ws_tts(ws: WebSocket):
|
|
| 571 |
if len(text) > MAX_TEXT_CHARS:
|
| 572 |
await ws.send_text(json.dumps({"event":"error","detail": f"text too long (>{MAX_TEXT_CHARS})"}))
|
| 573 |
continue
|
| 574 |
-
await piper_stream_raw(
|
|
|
|
|
|
|
|
|
|
| 575 |
# ignore others
|
| 576 |
except WebSocketDisconnect:
|
| 577 |
return
|
|
@@ -586,4 +649,4 @@ async def ws_tts(ws: WebSocket):
|
|
| 586 |
pass
|
| 587 |
|
| 588 |
if __name__ == "__main__":
|
| 589 |
-
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")), reload=False)
|
|
|
|
| 27 |
probe.unlink(missing_ok=True)
|
| 28 |
return p
|
| 29 |
except Exception as e:
|
| 30 |
+
errs.append(f"{p}: {type(e).__name__}({e})")
|
| 31 |
raise RuntimeError("No writable dir. Tried:\n " + "\n ".join(errs))
|
| 32 |
|
| 33 |
ENV_DIR = os.getenv("TTS_DATA_DIR")
|
|
|
|
| 79 |
|
| 80 |
DEFAULT_CH = 1 # mono
|
| 81 |
|
| 82 |
+
# NEW: Prebuffer to avoid pauses (synthesize immediately, start streaming later)
|
| 83 |
+
PREBUFFER_MS = int(os.getenv("PREBUFFER_MS", "6000")) # ~6s buffer before first bytes
|
| 84 |
+
PREBUFFER_MAX_WAIT_MS = int(os.getenv("PREBUFFER_MAX_WAIT_MS", "15000")) # fail-safe cap
|
| 85 |
+
|
| 86 |
# Input clamp (basic DoS protection)
|
| 87 |
MAX_TEXT_CHARS = int(os.getenv("MAX_TEXT_CHARS", "800"))
|
| 88 |
|
|
|
|
| 238 |
length_scale: float,
|
| 239 |
noise_scale: float,
|
| 240 |
noise_w: float,
|
| 241 |
+
prebuffer_ms: int,
|
| 242 |
+
prebuffer_max_wait_ms: int,
|
| 243 |
):
|
| 244 |
"""
|
| 245 |
+
Synthesize immediately; stream in *batched, clock-paced* frames:
|
| 246 |
+
- Accumulate audio until `prebuffer_ms` (or `prebuffer_max_wait_ms` elapses).
|
| 247 |
+
- Then send fixed batches of STREAM_BATCH_MS at a steady cadence.
|
| 248 |
"""
|
| 249 |
cmd = build_piper_cmd(text, voice, to_stdout=True,
|
| 250 |
length_scale=length_scale, noise_scale=noise_scale, noise_w=noise_w)
|
|
|
|
| 273 |
stderr_task = asyncio.create_task(pump_stderr())
|
| 274 |
total = 0
|
| 275 |
|
| 276 |
+
# framing + pacing
|
| 277 |
bytes_per_ms = max(1, int(sr * channels * 2 / 1000))
|
| 278 |
+
batch_bytes = max(bytes_per_ms, int(STREAM_BATCH_MS * bytes_per_ms))
|
| 279 |
+
target_prebuffer_bytes = max(0, int(prebuffer_ms) * bytes_per_ms)
|
| 280 |
+
|
| 281 |
buf = bytearray()
|
| 282 |
+
started_streaming = False
|
| 283 |
+
first_audio_ts = None
|
| 284 |
+
pace_start_t = None
|
| 285 |
+
batches_sent = 0
|
| 286 |
|
| 287 |
try:
|
| 288 |
while True:
|
| 289 |
+
chunk = await proc.stdout.read(8192)
|
| 290 |
+
if chunk:
|
| 291 |
+
if first_audio_ts is None:
|
| 292 |
+
first_audio_ts = time.time()
|
| 293 |
+
buf.extend(chunk)
|
| 294 |
+
|
| 295 |
+
# Flip to streaming once prebuffer is satisfied (or the fail-safe wait elapsed)
|
| 296 |
+
if not started_streaming:
|
| 297 |
+
enough = (len(buf) >= target_prebuffer_bytes) if target_prebuffer_bytes > 0 else True
|
| 298 |
+
waited = False
|
| 299 |
+
if first_audio_ts is not None and prebuffer_max_wait_ms > 0:
|
| 300 |
+
waited = ((time.time() - first_audio_ts) * 1000.0) >= prebuffer_max_wait_ms
|
| 301 |
+
if enough or waited:
|
| 302 |
+
started_streaming = True
|
| 303 |
+
pace_start_t = time.time()
|
| 304 |
+
batches_sent = 0
|
| 305 |
+
|
| 306 |
+
# If streaming, emit batches on schedule
|
| 307 |
+
if started_streaming:
|
| 308 |
+
while len(buf) >= batch_bytes:
|
| 309 |
+
due_t = pace_start_t + (batches_sent * STREAM_BATCH_MS) / 1000.0
|
| 310 |
+
sleep_s = due_t - time.time()
|
| 311 |
+
if sleep_s > 0:
|
| 312 |
+
await asyncio.sleep(sleep_s)
|
| 313 |
+
await ws.send_bytes(buf[:batch_bytes])
|
| 314 |
+
del buf[:batch_bytes]
|
| 315 |
+
total += batch_bytes
|
| 316 |
+
batches_sent += 1
|
| 317 |
+
continue
|
| 318 |
+
|
| 319 |
+
# EOF from Piper
|
| 320 |
+
if not started_streaming and len(buf) > 0:
|
| 321 |
+
started_streaming = True
|
| 322 |
+
pace_start_t = time.time()
|
| 323 |
+
batches_sent = 0
|
| 324 |
+
|
| 325 |
+
# Flush any remaining bytes in paced batches
|
| 326 |
+
while len(buf) >= batch_bytes:
|
| 327 |
+
due_t = pace_start_t + (batches_sent * STREAM_BATCH_MS) / 1000.0
|
| 328 |
+
sleep_s = due_t - time.time()
|
| 329 |
+
if sleep_s > 0:
|
| 330 |
+
await asyncio.sleep(sleep_s)
|
| 331 |
+
await ws.send_bytes(buf[:batch_bytes])
|
| 332 |
+
del buf[:batch_bytes]
|
| 333 |
+
total += batch_bytes
|
| 334 |
+
batches_sent += 1
|
| 335 |
+
|
| 336 |
+
# Send any tail (less than a full batch) now
|
| 337 |
+
if len(buf) > 0:
|
| 338 |
+
await ws.send_bytes(bytes(buf))
|
| 339 |
+
total += len(buf)
|
| 340 |
+
buf.clear()
|
| 341 |
+
break # done reading
|
| 342 |
|
| 343 |
await proc.wait()
|
| 344 |
await stderr_task
|
|
|
|
| 383 |
# optional environment versions
|
| 384 |
try:
|
| 385 |
import numpy, onnxruntime as ort
|
| 386 |
+
numpy_version = numpy.__version__
|
| 387 |
+
onnxruntime_version = ort.__version__
|
| 388 |
except Exception:
|
| 389 |
numpy_version = onnxruntime_version = None
|
| 390 |
|
|
|
|
| 575 |
voice = DEFAULT_VOICE
|
| 576 |
length_scale, noise_scale, noise_w = 1.08, 0.35, 0.90
|
| 577 |
voice_sr = 22050 # will be set from config on init
|
| 578 |
+
# NEW: defaults (client can override in init)
|
| 579 |
+
prebuffer_ms = PREBUFFER_MS
|
| 580 |
+
prebuffer_max_wait_ms = PREBUFFER_MAX_WAIT_MS
|
| 581 |
|
| 582 |
try:
|
| 583 |
while True:
|
|
|
|
| 588 |
continue
|
| 589 |
ev = data.get("event")
|
| 590 |
if ev == "init":
|
| 591 |
+
# optional shared-secret over WS: accept via token field
|
| 592 |
token = (data.get("token") or "")
|
| 593 |
if AUTH_SHARED_SECRET and token != AUTH_SHARED_SECRET:
|
| 594 |
await ws.send_text(json.dumps({"event": "error", "detail": "unauthorized"}))
|
|
|
|
| 603 |
if "length_scale" not in data and "rate_wpm" in data:
|
| 604 |
try:
|
| 605 |
rate_wpm = int(data.get("rate_wpm", 165))
|
|
|
|
| 606 |
length_scale = max(0.70, min(1.40, 165.0 / max(100, rate_wpm)))
|
| 607 |
except Exception:
|
| 608 |
pass
|
| 609 |
+
# NEW: allow client override for prebuffer knobs
|
| 610 |
+
if "prebuffer_ms" in data:
|
| 611 |
+
try: prebuffer_ms = max(0, int(data["prebuffer_ms"]))
|
| 612 |
+
except Exception: pass
|
| 613 |
+
if "prebuffer_max_wait_ms" in data:
|
| 614 |
+
try: prebuffer_max_wait_ms = max(0, int(data["prebuffer_max_wait_ms"]))
|
| 615 |
+
except Exception: pass
|
| 616 |
+
|
| 617 |
try:
|
| 618 |
info = ensure_voice(voice)
|
| 619 |
voice_sr = int(info.get("sr", 22050))
|
|
|
|
| 631 |
if len(text) > MAX_TEXT_CHARS:
|
| 632 |
await ws.send_text(json.dumps({"event":"error","detail": f"text too long (>{MAX_TEXT_CHARS})"}))
|
| 633 |
continue
|
| 634 |
+
await piper_stream_raw(
|
| 635 |
+
text, voice, ws, voice_sr, DEFAULT_CH, length_scale, noise_scale, noise_w,
|
| 636 |
+
prebuffer_ms, prebuffer_max_wait_ms
|
| 637 |
+
)
|
| 638 |
# ignore others
|
| 639 |
except WebSocketDisconnect:
|
| 640 |
return
|
|
|
|
| 649 |
pass
|
| 650 |
|
| 651 |
if __name__ == "__main__":
|
| 652 |
+
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")), reload=False)
|