""" Doomscroll TTS - Kokoro-82M serving API. Runs on HF Spaces free CPU tier. ~0.5-1.5s/sentence. """ import io import os import logging import numpy as np import soundfile as sf from fastapi import FastAPI, HTTPException, Header, Response from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Field from typing import Optional logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") log = logging.getLogger("tts") API_KEY = os.environ.get("API_KEY", "") # if empty, auth is disabled (dev only) ALLOWED_VOICES = { "af_bella", "am_michael", "af_nicole", "af_sarah", "am_adam", "bf_emma", "af_heart", "bm_george", } app = FastAPI(title="Doomscroll TTS") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["*"], max_age=86400, ) _pipeline = None def get_pipeline(): """Lazy-load Kokoro pipeline. First call ~10-20s (downloads model), then cached.""" global _pipeline if _pipeline is None: log.info("Loading Kokoro pipeline...") from kokoro import KPipeline # lang_code 'a' = American English (covers all af_*/am_* voices) # 'b' = British English (bf_*/bm_*) _pipeline = KPipeline(lang_code="a") log.info("Kokoro pipeline ready.") return _pipeline class TTSRequest(BaseModel): text: str = Field(min_length=1, max_length=2000) voice: str = "af_bella" speed: float = Field(default=1.0, ge=0.5, le=3.0) def check_auth(authorization: Optional[str]) -> None: if not API_KEY: return # auth disabled if not authorization or not authorization.startswith("Bearer "): raise HTTPException(status_code=401, detail="Missing Bearer token") if authorization[7:] != API_KEY: raise HTTPException(status_code=401, detail="Invalid API key") @app.get("/") def root(): return { "name": "doomscroll-tts", "ok": True, "endpoints": ["/tts", "/warmup"], "voices": sorted(ALLOWED_VOICES), } @app.get("/warmup") def warmup(): """Keep the Space alive and load the model. Hit this from a cron every few minutes.""" try: get_pipeline() return {"ok": True, "warm": True} except Exception as e: log.exception("warmup failed") return {"ok": False, "error": str(e)} @app.post("/tts") def tts(req: TTSRequest, authorization: Optional[str] = Header(None)): check_auth(authorization) if req.voice not in ALLOWED_VOICES: raise HTTPException(status_code=400, detail=f"voice must be one of {sorted(ALLOWED_VOICES)}") # Pick pipeline by voice prefix (a = american, b = british) voice_prefix = req.voice[1] # e.g. 'f' from 'af_bella' -> use lang 'a' lang_code = req.voice[0] if req.voice[0] in ("a", "b") else "a" try: pipe = get_pipeline() # Kokoro KPipeline yields (graphemes, phonemes, audio) tuples per chunk. # For a single sentence we expect one chunk; concatenate defensively. chunks = [] for _gs, _ps, audio in pipe(req.text, voice=req.voice, speed=req.speed): chunks.append(audio) if not chunks: raise HTTPException(status_code=500, detail="Empty audio output") full = np.concatenate([np.asarray(c, dtype=np.float32) for c in chunks]) if len(chunks) > 1 else np.asarray(chunks[0], dtype=np.float32) # Encode to WAV in memory at Kokoro's native 24 kHz buf = io.BytesIO() sf.write(buf, full, 24000, format="WAV", subtype="PCM_16") wav = buf.getvalue() return Response( content=wav, media_type="audio/wav", headers={ "Content-Length": str(len(wav)), "X-TTS-Voice": req.voice, "X-TTS-Speed": str(req.speed), "Cache-Control": "public, max-age=604800, immutable", }, ) except HTTPException: raise except Exception as e: log.exception("tts failed") raise HTTPException(status_code=500, detail=str(e))