#!/usr/bin/env python3 """WebSocket bidirectional-streaming TTS server for TTS-V4. python stream_server.py --model-dir /path/to/TTS-V4 --port 8765 Protocol (ws://host:port/v1/tts/stream): client -> {"type":"start","voice":"bank_collection_female","sample_rate":8000|16000|24000, "mode":"icl"|"xvec","segment":"sentence"|"token","speed":1.0,"temperature":0.8,"seed":0} (or "ref_audio_b64" + "ref_text" instead of "voice" for a custom real reference) client -> {"type":"text","text":"..."} (any number, any granularity, e.g. LLM tokens) client -> {"type":"end"} (no more text) | {"type":"cancel"} (barge-in) server -> {"type":"started","sample_rate":..,"format":"pcm_s16le","channels":1} server -> binary audio chunks (PCM 16-bit little endian mono) server -> {"type":"done","stats":{...}} | {"type":"error","message":...} """ import argparse import asyncio import base64 import json import os import tempfile import threading import time import numpy as np import soxr import uvicorn from fastapi import FastAPI, WebSocket, WebSocketDisconnect from stream_engine import StreamingTTS app = FastAPI() ENGINE = None ARGS = None @app.get('/health') def health(): return dict(status='ok' if ENGINE else 'loading', voices=sorted(ENGINE.voice_info) if ENGINE else [], sample_rate=ENGINE.sample_rate if ENGINE else None) def pcm16(x): return (np.clip(x, -1, 1) * 32767).astype('