Update app.py
Browse files12345678913 unmodified lines2324252627282912 unmodified lines42434445464724 unmodified lines7273747576777879808140 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414514614715 unmodified lines1631641651661671682 unmodified lines17117217317417517617717817918018118215 unmodified lines198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233import os, json, time, asyncio, tempfile, structfrom typing import AsyncGenerator, Dict, Any, Optionalfrom fastapi import FastAPI, Request, Query, UploadFilefrom fastapi.responses import JSONResponse, StreamingResponse, FileResponseimport websockets # NEW# === Directories ===BASE_DIR = os.environ.get("BASE_DIR", "/tmp/brain_app")13 unmodified linesNOISE_SCALE = float(os.environ.get("NOISE_SCALE", "0.33"))NOISE_W = float(os.environ.get("NOISE_W", "0.92"))app = FastAPI(title="Brain Space (STT→TTS coordinator)", version="3.2.0")log_queue: "asyncio.Queue[Dict[str, Any]]" = asyncio.Queue()def write_event(event: Dict[str, Any]) -> None:12 unmodified linesr = max(80, min(320, rate_wpm))return round(base / float(r), 3)# ---------- Health ----------@app.get("/health")def health():24 unmodified linesreturn StreamingResponse(gen(), media_type="text/event-stream",headers={"Cache-Control":"no-cache","Connection":"keep-alive"})# ---------- TTS proxy (file-mode, not live) ----------async def _proxy_tts_wav_stream(text: str, voice: str, rate_wpm: Optional[int],noise_scale: float, noise_w: float) -> StreamingResponse:import httpxlength_scale = rate_to_length_scale(rate_wpm) if rate_wpm is not None else rate_to_length_scale(BASE_WPM)params = {"text": text,40 unmodified lineswrite_event({"type":"tts_post","len":len(text),"voice":voice,"rate_wpm":rate_wpm})return await _proxy_tts_wav_stream(text, voice, rate_wpm, noise_s, noise_wgt)# ---------- NEW: true LIVE streaming via TTS WebSocket ----------def _wav_header(sr: int, ch: int, bits: int = 16) -> bytes:byte_rate = sr * ch * (bits // 8)block_align = ch * (bits // 8)# streaming data size; many players accept 0xFFFFFFFF as "unknown length"data_size = 0xFFFFFFFFriff_size = 36 + data_sizereturn b"".join([b"RIFF", struct.pack("<I", riff_size), b"WAVE",b"fmt ", struct.pack("<I", 16), struct.pack("<H", 1),struct.pack("<H", ch), struct.pack("<I", sr),struct.pack("<I", byte_rate), struct.pack("<H", block_align),struct.pack("<H", bits),b"data", struct.pack("<I", data_size),])def _tts_ws_url() -> str:base = TTS_BASE.rstrip("/")return base.replace("http://", "ws://").replace("https://", "wss://") + "/ws/tts"@app.get("/tts/say.stream.wav")async def tts_say_stream_wav(text: str = Query(..., description="Text to synthesize (live)"),15 unmodified linestry:ws_url = _tts_ws_url()ws = await websockets.connect(ws_url, ping_interval=None, max_size=8_000_000)# initawait ws.send(json.dumps({"event": "init",2 unmodified lines"noise_scale": noise_scale,"noise_w": noise_w,}))sr, ch = 22050, 1# wait for ready -> send header immediately so client can startwhile True:m = await ws.recv()if isinstance(m, (bytes, bytearray)):# ignore stray audio until we know sr/chcontinuetry:evt = json.loads(m)15 unmodified lineswhile True:try:msg = await ws.recv()except websockets.exceptions.ConnectionClosedOK:breakexcept websockets.exceptions.ConnectionClosedError:breakif isinstance(msg, (bytes, bytearray)):# raw PCM16 frame from TTS; just yieldif msg:yield msgcontinue# control eventtry:evt = json.loads(msg)except Exception:continuekind = evt.get("event")if kind in ("done", "end"):breakif kind == "error":# propagate as bytes (don’t raise; avoid chunk abort)detail = evt.get("detail", "tts error")yield f'ERROR: {detail}'.encode("utf-8")break# ignore logsexcept Exception as e:# Log, but don't raise (raising here aborts chunked stream & causes 'incomplete chunked read')write_event({"type":"tts_stream_err","err":str(e)})# a tiny trailing pad keeps some clients happyyield b""finally:try:12345678910111213 unmodified lines2627282930313212 unmodified lines45464748495051525354555657585960616263646566676869707172737475767778798081828324 unmodified lines10810911011111211311411511611711840 unmodified lines15916016116216316416516615 unmodified lines1821831841851861871882 unmodified lines19119219319419519619719819920020120220315 unmodified lines219220221222223224225226227228229230231232233234235236237238239240241242243244245246247# brain_app.py — Brain Space: STT → TTS coordinator + LIVE TTS streaming proxyimport os, json, time, asyncio, tempfilefrom typing import AsyncGenerator, Dict, Any, Optionalfrom fastapi import FastAPI, Request, Query, UploadFilefrom fastapi.responses import JSONResponse, StreamingResponse, FileResponseimport httpximport websockets# === Directories ===BASE_DIR = os.environ.get("BASE_DIR", "/tmp/brain_app")13 unmodified linesNOISE_SCALE = float(os.environ.get("NOISE_SCALE", "0.33"))NOISE_W = float(os.environ.get("NOISE_W", "0.92"))app = FastAPI(title="Brain Space (STT→TTS coordinator)", version="3.1.0")log_queue: "asyncio.Queue[Dict[str, Any]]" = asyncio.Queue()def write_event(event: Dict[str, Any]) -> None:12 unmodified linesr = max(80, min(320, rate_wpm))return round(base / float(r), 3)def _tts_ws_url() -> str:"""Build the TTS WebSocket URL from TTS_BASE.e.g. https://Percy3822-ActualTTS.hf.space -> wss://Percy3822-ActualTTS.hf.space/ws/tts"""base = (TTS_BASE or "").rstrip("/")if base.startswith("https://"):return "wss://" + base[len("https://"):] + "/ws/tts"if base.startswith("http://"):return "ws://" + base[len("http://"):] + "/ws/tts"return (base + "/ws/tts") if not base.endswith("/ws/tts") else basedef _wav_header(sr: int, ch: int) -> bytes:"""Minimal PCM16 WAV header with large data size for streaming."""bits = 16byte_rate = sr * ch * (bits // 8)block_align = ch * (bits // 8)data_size = 0x7FFFFFFFriff_size = (36 + data_size) & 0xFFFFFFFFreturn (b"RIFF" +riff_size.to_bytes(4, "little") +b"WAVE" +b"fmt " + (16).to_bytes(4, "little") +(1).to_bytes(2, "little") + # PCM(ch).to_bytes(2, "little") +(sr).to_bytes(4, "little") +(byte_rate).to_bytes(4, "little") +(block_align).to_bytes(2, "little") +(bits).to_bytes(2, "little") +b"data" + data_size.to_bytes(4, "little"))# ---------- Health ----------@app.get("/health")def health():24 unmodified linesreturn StreamingResponse(gen(), media_type="text/event-stream",headers={"Cache-Control":"no-cache","Connection":"keep-alive"})# ---------- TTS proxy streaming (/tts/say.wav) ----------# GET: /tts/say.wav?text=...&voice=...&rate_wpm=165# POST: JSON {"text": "...", "voice": "...", "rate_wpm": 165}async def _proxy_tts_wav_stream(text: str, voice: str, rate_wpm: Optional[int],noise_scale: float, noise_w: float) -> StreamingResponse:length_scale = rate_to_length_scale(rate_wpm) if rate_wpm is not None else rate_to_length_scale(BASE_WPM)params = {"text": text,40 unmodified lineswrite_event({"type":"tts_post","len":len(text),"voice":voice,"rate_wpm":rate_wpm})return await _proxy_tts_wav_stream(text, voice, rate_wpm, noise_s, noise_wgt)# ---------- LIVE TTS WS → HTTP WAV streaming ----------# GET: /tts/say.stream.wav?text=...&voice=...&rate_wpm=165@app.get("/tts/say.stream.wav")async def tts_say_stream_wav(text: str = Query(..., description="Text to synthesize (live)"),15 unmodified linestry:ws_url = _tts_ws_url()ws = await websockets.connect(ws_url, ping_interval=None, max_size=8_000_000)# initawait ws.send(json.dumps({"event": "init",2 unmodified lines"noise_scale": noise_scale,"noise_w": noise_w,}))sr, ch = 22050, 1# wait for ready -> send WAV header immediatelywhile True:m = await ws.recv()if isinstance(m, (bytes, bytearray)):# ignore until we know sr/chcontinuetry:evt = json.loads(m)15 unmodified lineswhile True:try:msg = await ws.recv()except websockets.exceptions.ConnectionClosed:breakif isinstance(msg, (bytes, bytearray)):if msg:yield msgcontinuetry:evt = json.loads(msg)except Exception:continuek = evt.get("event")if k in ("done", "end"):breakif k == "error":d = evt.get("detail", "tts error")yield f'ERROR: {d}'.encode("utf-8")break# ignore logsexcept Exception as e:write_event({"type":"tts_stream_err","err":str(e)})yield b""finally:try:
app.py+54-40