Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111#!/usr/bin/env python3"""KittenTTS HTTP server: POST /tts -> WAV, POST /tts-stream -> one-shot URL,GET /stream/<token> -> finished WAV (single fetch), GET /health.
The stream endpoints let an mpd client pull synthesized audio directly overHTTP (mpd's built-in http input plugin) instead of staging a WAV into themusic directory. Synthesis happens up front in /tts-stream; the returned URLserves the finished bytes on exactly one fetch and is then discarded."""import ioimport osimport threadingimport time
import numpy as npimport soundfile as sffrom fastapi import FastAPIfrom fastapi.responses import Response
app = FastAPI(title="kittentts")
_model = None_model_lock = None
# token -> (wav_bytes, expires_at)_stream_store = {}_stream_lock = threading.Lock()_TTL_SECONDS = 300.0
def _load_model(): global _model, _model_lock if _model_lock is None: _model_lock = threading.Lock() with _model_lock: if _model is None: from kittentts import KittenTTS
_model = KittenTTS( "KittenML/kitten-tts-mini-0.8", cache_dir="/models/hf", ) return _model
def _synthesize(text, voice, speed): """Synthesize text and return finished WAV bytes (24 kHz float).""" model = _load_model() audio = model.generate(text, voice=voice, speed=speed, clean_text=True) buf = io.BytesIO() sf.write(buf, np.asarray(audio, dtype=np.float32), 24000, format="WAV", subtype="FLOAT") return buf.getvalue()
@app.get("/health")def health(): return {"status": "ok", "model_loaded": _model is not None}
@app.post("/tts")def tts(body: dict): text = str(body.get("text", "")).strip() if not text: return Response(status_code=400, content="missing text") voice = body.get("voice") or "Jasper" speed = float(body.get("speed", 1.0)) return Response(content=_synthesize(text, voice, speed), media_type="audio/wav")
@app.post("/tts-stream")def tts_stream(body: dict): """Synthesize now, return a one-shot URL for mpd to fetch the finished WAV.
Response: {"token": "...", "url": "http://<host>/stream/<token>"} The client should pass `url` to mpd (add + play). `base_url` in the request overrides the host used to build the URL (use the host mpd can reach). """ text = str(body.get("text", "")).strip() if not text: return Response(status_code=400, content="missing text") voice = body.get("voice") or "Jasper" speed = float(body.get("speed", 1.0)) base_url = str(body.get("base_url") or "").rstrip("/")
wav = _synthesize(text, voice, speed) token = os.urandom(16).hex() with _stream_lock: _sweep_expired() _stream_store[token] = (wav, time.monotonic() + _TTL_SECONDS)
url = f"{base_url}/stream/{token}" if base_url else f"/stream/{token}" return {"token": token, "url": url}
def _sweep_expired(): now = time.monotonic() expired = [t for t, (_, exp) in _stream_store.items() if exp < now] for t in expired: _stream_store.pop(t, None)
@app.get("/stream/{token}")def stream(token: str): """Serve a stored finished WAV on a single fetch, then discard it.""" with _stream_lock: item = _stream_store.pop(token, None) if item is None: return Response(status_code=404, content="token unknown or expired") wav, _exp = item return Response(content=wav, media_type="audio/wav")