diff --git a/API_DOCS.md b/API_DOCS.md index fe4d5d35..6de0eb31 100644 --- a/API_DOCS.md +++ b/API_DOCS.md @@ -1 +1,151 @@ -Coming soon \ No newline at end of file +# StyleTTS2 HTTP Streaming API Documentation + +## Overview + +The HTTP Streaming API provides text-to-speech synthesis with real-time audio streaming. The server uses Flask and returns WAV audio data. + +## Base URL + +``` +http://localhost:5000 +``` + +## Endpoints + +### GET / + +Returns API documentation in HTML format. + +--- + +### POST /api/v1/stream + +Synthesizes speech from text with streaming audio response. + +**Request Body (form-data):** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `text` | string | Yes | Text to synthesize | +| `voice` | string | Yes | Voice ID (see available voices below) | +| `steps` | integer | No | Diffusion steps (default: 7, higher = better quality) | + +**Response:** +- Content-Type: `audio/x-wav` +- Streams WAV audio data in chunks + +**Example with curl:** + +```bash +curl -X POST http://localhost:5000/api/v1/stream \ + -d "text=Hello, this is a test of the streaming API." \ + -d "voice=f-us-1" \ + -d "steps=7" \ + --output output.wav +``` + +**Example with Python:** + +```python +import requests + +response = requests.post( + "http://localhost:5000/api/v1/stream", + data={ + "text": "Hello, this is a test.", + "voice": "f-us-1", + "steps": 7 + }, + stream=True +) + +with open("output.wav", "wb") as f: + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) +``` + +--- + +### POST /api/v1/static + +Synthesizes speech from text and returns complete audio file. + +**Request Body (form-data):** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `text` | string | Yes | Text to synthesize | +| `voice` | string | Yes | Voice ID | + +**Response:** +- Content-Type: `audio/wav` +- Returns complete WAV file + +**Example:** + +```bash +curl -X POST http://localhost:5000/api/v1/static \ + -d "text=Hello world" \ + -d "voice=m-us-1" \ + --output output.wav +``` + +--- + +## Available Voices + +| Voice ID | Description | +|----------|-------------| +| `f-us-1` | Female US English #1 | +| `f-us-2` | Female US English #2 | +| `f-us-3` | Female US English #3 | +| `f-us-4` | Female US English #4 | +| `m-us-1` | Male US English #1 | +| `m-us-2` | Male US English #2 | +| `m-us-3` | Male US English #3 | +| `m-us-4` | Male US English #4 | + +--- + +## Error Responses + +All errors return JSON with an `error` field: + +```json +{ + "error": "Missing required fields. Please include \"text\" and \"voice\" in your request." +} +``` + +**Common errors:** +- `400`: Missing required fields or invalid voice selection + +--- + +## Testing + +Use the provided test client: + +```bash +# List available voices +python test_api_client.py --list-voices + +# Check server status +python test_api_client.py --check-server + +# Synthesize speech +python test_api_client.py -t "Hello world" -v f-us-1 -o output.wav + +# With custom diffusion steps +python test_api_client.py -t "Hello world" -v m-us-2 -o output.wav -s 10 +``` + +--- + +## Starting the Server + +```bash +python api.py +``` + +The server starts on `http://0.0.0.0:5000` by default. \ No newline at end of file diff --git a/README.md b/README.md index 52cd076f..0fc36d85 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,5 @@ # StyleTTS 2 API -> [!CAUTION] -> The Streaming API is not fully implemented yet. - [Original Repo](https://github.com/yl4579/StyleTTS2) - [CLI Tool](https://github.com/fakerybakery/styletTS2-cli) - **Streaming API** (GPL licensed due to Phonemizer. Should I switch to OpenPhonemizer and make it MIT-licensed?) @@ -27,9 +24,9 @@ Online demo: [Hugging Face](https://huggingface.co/spaces/styletts2/styletts2) ( - [x] Add a finetuning script for new speakers with base pre-trained multispeaker models - [x] REST API - [x] Importable inference script (PR #78) +- [x] Streaming API and WebSocket support - [ ] Fix DDP (accelerator) for `train_second.py` **(I have tried everything I could to fix this but had no success, so if you are willing to help, please see [#7](https://github.com/yl4579/StyleTTS2/issues/7))** - [ ] Pip package -- [ ] Demo of audio streaming ## Pre-requisites 1. Python >= 3.7 @@ -56,16 +53,54 @@ For LibriTTS, you will need to combine train-clean-360 with train-clean-100 and ## Streaming API -You can use StyleTTS 2 in your projects by launching the HTTP API with streaming support. Synthesize text from your frontend apps, etc by making HTTP calls to the API server. The server uses Flask. It has not been extensively tested and should not be used for production purposes. +You can use StyleTTS 2 in your projects by launching the HTTP API with streaming support. Synthesize text from your frontend apps, etc by making HTTP calls to the API server. The server uses Flask. API documentation may be found in the [`API_DOCS.md`](API_DOCS.md) file. Launch server: -``` +```bash python api.py ``` +## WebSocket API + +For real-time TTS streaming with chunked text input and low-latency audio output, use the WebSocket API powered by FastAPI. + +**Features:** +- Real-time bidirectional communication +- Chunked text input (send text incrementally) +- Base64-encoded MP3 audio output +- GPU queue management for concurrent requests +- Idle timeout and connection management + +**Quick Start:** + +```bash +# Start WebSocket server (default port 8765) +python ws_server.py + +# Or with custom port +python ws_server.py 9000 +``` + +**Endpoints:** +- WebSocket: `ws://localhost:8765/ws/tts` +- Health Check: `http://localhost:8765/health` +- Voice List: `http://localhost:8765/voices` + +**Test the WebSocket API:** + +```bash +# Simple test +python test_ws_client.py --text "Hello world" --voice f-us-1 --output output.mp3 + +# Chunked streaming test +python test_ws_client.py --text "This is a longer text" --voice m-us-2 --chunked +``` + +Full WebSocket documentation: [`WEBSOCKET_DOCS.md`](WEBSOCKET_DOCS.md) + ## Python API You can now use StyleTTS 2 directly in your programs! A `pip`-compatible package is coming soon. diff --git a/WEBSOCKET_DOCS.md b/WEBSOCKET_DOCS.md new file mode 100644 index 00000000..304a5aff --- /dev/null +++ b/WEBSOCKET_DOCS.md @@ -0,0 +1,235 @@ +# StyleTTS2 WebSocket API Documentation + +## Overview + +The WebSocket API provides real-time text-to-speech streaming with bidirectional communication. It supports chunked text input and returns base64-encoded MP3 audio. + +## Quick Start + +```bash +# Start WebSocket server +python ws_server.py + +# Test with client +python test_ws_client.py --text "Hello world" --voice f-us-1 +``` + +## Endpoints + +### WebSocket: `/ws/tts` + +``` +ws://localhost:8765/ws/tts +``` + +### REST: `/health` + +Health check endpoint. + +```bash +curl http://localhost:8765/health +``` + +Response: +```json +{ + "status": "healthy", + "ready": true, + "stats": { + "queue_size": 0, + "total_requests": 10, + "failed_requests": 0, + "success_rate": 1.0 + } +} +``` + +### REST: `/voices` + +List available voices. + +```bash +curl http://localhost:8765/voices +``` + +Response: +```json +{ + "voices": ["f-us-1", "f-us-2", "f-us-3", "f-us-4", "m-us-1", "m-us-2", "m-us-3", "m-us-4"] +} +``` + +## WebSocket Message Format + +### Input (Client → Server) + +```json +{ + "text": "Text to synthesize", + "voice": "f-us-1", + "flush": true +} +``` + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `text` | string | Yes | Text chunk to synthesize | +| `voice` | string | No | Voice ID (default: f-us-1) | +| `flush` | boolean | No | Set `true` to generate audio from buffered text | + +### Output (Server → Client) + +**Audio response:** +```json +{ + "audio": "base64_encoded_mp3_data", + "isFinal": false +} +``` + +**Welcome message (on connect):** +```json +{ + "status": "connected", + "available_voices": ["f-us-1", ...], + "message": "Send text chunks with 'flush: true' to generate audio" +} +``` + +**Error response:** +```json +{ + "error": "Error message", + "isFinal": true +} +``` + +## Available Voices + +| Voice ID | Description | +|----------|-------------| +| `f-us-1` to `f-us-4` | Female US English | +| `m-us-1` to `m-us-4` | Male US English | + +## Usage Patterns + +### Single Text (Simple) + +Send all text at once with `flush: true`: + +```python +await websocket.send(json.dumps({ + "text": "Hello, this is a complete sentence.", + "voice": "f-us-1", + "flush": True +})) +``` + +### Chunked Streaming (Real-time) + +Buffer text chunks, then flush to generate audio: + +```python +# Send chunks without flushing +await websocket.send(json.dumps({"text": "Hello, ", "voice": "f-us-1", "flush": False})) +await websocket.send(json.dumps({"text": "this is ", "flush": False})) +await websocket.send(json.dumps({"text": "streaming.", "flush": True})) # Flush to generate +``` + +## Code Examples + +### Python + +```python +import asyncio +import websockets +import json +import base64 + +async def synthesize(text, voice="f-us-1"): + uri = "ws://localhost:8765/ws/tts" + async with websockets.connect(uri) as ws: + # Receive welcome + await ws.recv() + + # Send text + await ws.send(json.dumps({ + "text": text, + "voice": voice, + "flush": True + })) + + # Receive audio + audio_chunks = [] + while True: + response = json.loads(await ws.recv()) + if "audio" in response and response["audio"]: + audio_chunks.append(base64.b64decode(response["audio"])) + if response.get("isFinal"): + break + + # Save audio + with open("output.mp3", "wb") as f: + f.write(b"".join(audio_chunks)) + +asyncio.run(synthesize("Hello world")) +``` + +### JavaScript + +```javascript +const ws = new WebSocket('ws://localhost:8765/ws/tts'); + +ws.onopen = () => { + ws.send(JSON.stringify({ + text: 'Hello world', + voice: 'f-us-1', + flush: true + })); +}; + +ws.onmessage = (event) => { + const data = JSON.parse(event.data); + if (data.audio) { + // Decode base64 and play audio + const audioBytes = atob(data.audio); + // ... play audio + } + if (data.isFinal) { + ws.close(); + } +}; +``` + +## Configuration + +Default settings in `ws_server.py`: + +| Setting | Default | Description | +|---------|---------|-------------| +| Port | 8765 | WebSocket server port | +| Idle timeout | 120s | Connection idle timeout | +| Max queue | 100 | Maximum pending requests | +| Ping interval | 20s | WebSocket keepalive | + +## Testing + +```bash +# Simple test +python test_ws_client.py --text "Hello" --voice f-us-1 --output test.mp3 + +# Chunked streaming test +python test_ws_client.py --text "Long text here" --chunked + +# Custom server +python test_ws_client.py --uri ws://192.168.1.100:8765/ws/tts --text "Hello" +``` + +## Error Handling + +| Error | Cause | Solution | +|-------|-------|----------| +| Invalid voice | Voice ID not recognized | Use voice from `/voices` endpoint | +| Queue full | Too many pending requests | Retry after delay | +| Connection timeout | Idle for 2+ minutes | Reconnect | +| Invalid JSON | Malformed message | Check JSON syntax | diff --git a/api.py b/api.py index d954972a..160a0531 100644 --- a/api.py +++ b/api.py @@ -4,21 +4,25 @@ # * Support voice cloning # * Implement authentication, user "credits" system w/ SQLite3 import io -import os -import hashlib -import threading import markdown -import re -import json from tortoise.utils.text import split_and_recombine_text from flask import Flask, Response, request, jsonify from scipy.io.wavfile import write +import phonemizer import numpy as np import ljinference import msinference import torch from flask_cors import CORS +# Download required NLTK data +import nltk + +try: + nltk.data.find("tokenizers/punkt_tab") +except LookupError: + nltk.download("punkt_tab", quiet=True) + def genHeader(sampleRate, bitsPerSample, channels): datasize = 2000 * 10**6 @@ -37,85 +41,131 @@ def genHeader(sampleRate, bitsPerSample, channels): o += (datasize).to_bytes(4, "little") return o -voicelist = ['f-us-1', 'f-us-2', 'f-us-3', 'f-us-4', 'm-us-1', 'm-us-2', 'm-us-3', 'm-us-4'] + +voicelist = [ + "f-us-1", + "f-us-2", + "f-us-3", + "f-us-4", + "m-us-1", + "m-us-2", + "m-us-3", + "m-us-4", +] voices = {} -import phonemizer -global_phonemizer = phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True) + +global_phonemizer = phonemizer.backend.EspeakBackend( + language="en-us", preserve_punctuation=True, with_stress=True +) print("Computing voices") for v in voicelist: - voices[v] = msinference.compute_style(f'voices/{v}.wav') + voices[v] = msinference.compute_style(f"voices/{v}.wav") print("Starting Flask app") app = Flask(__name__) cors = CORS(app) + @app.route("/") def index(): - with open('API_DOCS.md', 'r') as f: + with open("API_DOCS.md", "r") as f: return markdown.markdown(f.read()) + def synthesize(text, voice, steps): v = voice.lower() - return msinference.inference(t, voices[v], alpha=0.3, beta=0.7, diffusion_steps=lngsteps, embedding_scale=1) + return msinference.inference( + text, voices[v], alpha=0.3, beta=0.7, diffusion_steps=steps, embedding_scale=1 + ) + + def ljsynthesize(text, steps): - return ljinference.inference(text, torch.randn(1,1,256).to('cuda' if torch.cuda.is_available() else 'cpu'), diffusion_steps=7, embedding_scale=1) -# def ljsynthesize(text): -# texts = split_and_recombine_text(text) -# v = voice.lower() -# audios = [] -# noise = torch.randn(1,1,256).to('cuda' if torch.cuda.is_available() else 'cpu') -# for t in texts: -# audios.append(ljinference.inference(text, noise, diffusion_steps=7, embedding_scale=1)) -# return np.concatenate(audios) - -@app.route("/api/v1/stream", methods=['POST']) + return ljinference.inference( + text, + torch.randn(1, 1, 256).to("cuda" if torch.cuda.is_available() else "cpu"), + diffusion_steps=steps, + embedding_scale=1, + ) + + +@app.route("/api/v1/stream", methods=["POST"]) def serve_wav_stream(): - if 'text' not in request.form or 'voice' not in request.form: - error_response = {'error': 'Missing required fields. Please include "text" and "voice" in your request.'} + if "text" not in request.form or "voice" not in request.form: + error_response = { + "error": 'Missing required fields. Please include "text" and "voice" in your request.' + } return jsonify(error_response), 400 - text = request.form['text'].strip() - voice = request.form['voice'].strip().lower() - if not voice in voices: - error_response = {'error': 'Invalid voice selected'} + text = request.form["text"].strip() + voice = request.form["voice"].strip().lower() + + # Get diffusion steps from request or use default + steps = int(request.form.get("steps", 7)) + + if voice not in voices: + error_response = { + "error": "Invalid voice selected. Available voices: " + ", ".join(voicelist) + } return jsonify(error_response), 400 + v = voices[voice] texts = split_and_recombine_text(text) + def generate(): - wav_header = genHeader(24000, 16, 1) is_first_chunk = True for t in texts: - wav = msinference.inference(t, voice, alpha=0.3, beta=0.7, diffusion_steps=7, embedding_scale=1) + # Generate audio using the pre-computed voice style + wav = msinference.inference( + t, v, alpha=0.3, beta=0.7, diffusion_steps=steps, embedding_scale=1 + ) output_buffer = io.BytesIO() write(output_buffer, 24000, wav) - output_buffer.read(44) + + # Seek to start and skip WAV header for chunks + output_buffer.seek(0) if is_first_chunk: - data = wav_header + wav_file.read() + # For first chunk, include WAV header + data = output_buffer.read() is_first_chunk = False else: - data = wav_file.read() + # For subsequent chunks, skip the 44-byte WAV header + output_buffer.seek(44) + data = output_buffer.read() yield data + return Response(generate(), mimetype="audio/x-wav") -@app.route("/api/v1/static", methods=['POST']) +@app.route("/api/v1/static", methods=["POST"]) def serve_wav(): - if 'text' not in request.form or 'voice' not in request.form: - error_response = {'error': 'Missing required fields. Please include "text" and "voice" in your request.'} + if "text" not in request.form or "voice" not in request.form: + error_response = { + "error": 'Missing required fields. Please include "text" and "voice" in your request.' + } return jsonify(error_response), 400 - text = request.form['text'].strip() - voice = request.form['voice'].strip().lower() - if not voice in voices: - error_response = {'error': 'Invalid voice selected'} + text = request.form["text"].strip() + voice = request.form["voice"].strip().lower() + if voice not in voices: + error_response = {"error": "Invalid voice selected"} return jsonify(error_response), 400 - v = voices[voice] texts = split_and_recombine_text(text) audios = [] for t in texts: - audios.append(msinference.inference(t, voice, alpha=0.3, beta=0.7, diffusion_steps=7, embedding_scale=1)) + audios.append( + msinference.inference( + t, + voices[voice], + alpha=0.3, + beta=0.7, + diffusion_steps=7, + embedding_scale=1, + ) + ) output_buffer = io.BytesIO() write(output_buffer, 24000, np.concatenate(audios)) response = Response(output_buffer.getvalue()) response.headers["Content-Type"] = "audio/wav" return response + + if __name__ == "__main__": app.run("0.0.0.0") \ No newline at end of file diff --git a/audio_streamer.py b/audio_streamer.py new file mode 100644 index 00000000..5e7482e5 --- /dev/null +++ b/audio_streamer.py @@ -0,0 +1,111 @@ +""" +Audio streaming utilities for WebSocket TTS. +Handles MP3 encoding and base64 chunking for incremental audio delivery. +""" + +import io +import base64 +import numpy as np +from pydub import AudioSegment +import logging + +logger = logging.getLogger(__name__) + + +class AudioStreamer: + """Streams audio as base64-encoded MP3 chunks.""" + + def __init__(self, sample_rate: int = 24000): + """ + Initialize audio streamer. + + Args: + sample_rate: Audio sample rate in Hz (default 24000) + """ + self.sample_rate = sample_rate + + def create_mp3_bytes(self, audio_data: np.ndarray) -> bytes: + """ + Convert numpy audio array to MP3 bytes. + + Args: + audio_data: Audio waveform as numpy array + + Returns: + MP3 file bytes + """ + # Normalize audio data to 16-bit range + if audio_data.dtype != np.int16: + audio_data = (audio_data * 32767).astype(np.int16) + + # Create AudioSegment from numpy array + audio_segment = AudioSegment( + audio_data.tobytes(), + frame_rate=self.sample_rate, + sample_width=2, # 16-bit + channels=1, # Mono + ) + + # Export to MP3 + buffer = io.BytesIO() + audio_segment.export(buffer, format="mp3", bitrate="128k") + buffer.seek(0) + return buffer.read() + + def encode_audio_chunk(self, audio_data: np.ndarray) -> str: + """ + Encode audio data to base64 MP3 string. + + Args: + audio_data: Audio waveform as numpy array + + Returns: + Base64-encoded MP3 audio string + """ + mp3_bytes = self.create_mp3_bytes(audio_data) + return base64.b64encode(mp3_bytes).decode("utf-8") + + def stream_audio_frames(self, audio_data: np.ndarray, chunk_duration_ms: int = 300): + """ + Generator that yields audio in fixed-duration base64 MP3 chunks. + + Args: + audio_data: Complete audio waveform as numpy array + chunk_duration_ms: Duration of each chunk in milliseconds + + Yields: + Tuples of (base64_audio, is_first_chunk, is_final_chunk) + """ + chunk_samples = int(self.sample_rate * chunk_duration_ms / 1000) + total_samples = len(audio_data) + + if total_samples == 0: + logger.warning("Empty audio data received") + return + + num_chunks = (total_samples + chunk_samples - 1) // chunk_samples + + for i in range(num_chunks): + start_idx = i * chunk_samples + end_idx = min(start_idx + chunk_samples, total_samples) + + chunk = audio_data[start_idx:end_idx] + is_first = i == 0 + is_final = i == num_chunks - 1 + + # Encode chunk as MP3 + base64_audio = self.encode_audio_chunk(chunk) + + yield base64_audio, is_first, is_final + + def encode_full_audio(self, audio_data: np.ndarray) -> str: + """ + Encode complete audio as MP3 to base64. + + Args: + audio_data: Audio waveform as numpy array + + Returns: + Base64-encoded complete MP3 file + """ + return self.encode_audio_chunk(audio_data) diff --git a/inference_manager.py b/inference_manager.py new file mode 100644 index 00000000..b2295a6e --- /dev/null +++ b/inference_manager.py @@ -0,0 +1,160 @@ +""" +GPU-safe inference manager with request queuing and semaphore control. +Handles concurrent TTS requests with low latency and prevents GPU contention. +""" + +import asyncio +import time +import logging +from typing import Optional, List +import numpy as np +import msinference + +logger = logging.getLogger(__name__) + + +class InferenceManager: + """Manages GPU inference with concurrency control and queuing.""" + + def __init__( + self, max_queue_size: int = 100, voice_list: Optional[List[str]] = None + ): + """ + Initialize inference manager. + + Args: + max_queue_size: Maximum number of pending inference requests + voice_list: List of voice IDs to precompute styles for + """ + self.gpu_semaphore = asyncio.Semaphore(1) # Single GPU access at a time + self.max_queue_size = max_queue_size + self.queue_size = 0 + self.total_requests = 0 + self.failed_requests = 0 + self.voices = {} + + # Precompute voice styles + if voice_list: + logger.info("Precomputing %d voice styles...", len(voice_list)) + for voice_id in voice_list: + voice_path = f"voices/{voice_id}.wav" + try: + self.voices[voice_id] = msinference.compute_style(voice_path) + logger.info(" ✓ Loaded voice: %s", voice_id) + except Exception as e: + logger.error(" ✗ Failed to load voice %s: %s", voice_id, str(e)) + + logger.info( + "InferenceManager initialized with max_queue_size=%d, %d voices loaded", + max_queue_size, + len(self.voices), + ) + + async def generate_audio( + self, + text: str, + voice: str, + alpha: float = 0.3, + beta: float = 0.7, + diffusion_steps: int = 7, + embedding_scale: float = 1.0, + ) -> Optional[np.ndarray]: + """ + Generate audio from text using specified voice. + + Args: + text: Input text to synthesize + voice: Voice ID (e.g., 'f-us-1', 'm-us-2') + alpha: Style weight (default 0.3) + beta: Prosody weight (default 0.7) + diffusion_steps: Number of diffusion steps (default 7) + embedding_scale: Style embedding scale (default 1.0) + + Returns: + Audio waveform as numpy array (24kHz sample rate) or None on failure + """ + # Check queue capacity + if self.queue_size >= self.max_queue_size: + logger.warning( + "Queue full, rejecting request (queue_size=%d)", self.queue_size + ) + self.failed_requests += 1 + return None + + self.queue_size += 1 + self.total_requests += 1 + + try: + # Acquire GPU semaphore + async with self.gpu_semaphore: + start_time = time.time() + + # Run inference in thread pool to avoid blocking event loop + loop = asyncio.get_event_loop() + wav = await loop.run_in_executor( + None, + self._inference_sync, + text, + voice, + alpha, + beta, + diffusion_steps, + embedding_scale, + ) + + elapsed = time.time() - start_time + logger.info( + "Generated audio for text='%s...' voice=%s in %.2fs", + text[:30], + voice, + elapsed, + ) + + return wav + + except Exception as e: + logger.error("Inference failed: %s", str(e), exc_info=True) + self.failed_requests += 1 + return None + finally: + self.queue_size -= 1 + + def _inference_sync( + self, + text: str, + voice: str, + alpha: float, + beta: float, + diffusion_steps: int, + embedding_scale: float, + ) -> np.ndarray: + """Synchronous inference call wrapped by async executor.""" + # Get precomputed voice style + if voice not in self.voices: + raise ValueError(f"Voice '{voice}' not found in precomputed voices") + + voice_style = self.voices[voice] + + # Use msinference with precomputed style tensor + wav = msinference.inference( + text, + voice_style, + alpha=alpha, + beta=beta, + diffusion_steps=diffusion_steps, + embedding_scale=embedding_scale, + ) + return wav + + def get_stats(self) -> dict: + """Get current statistics.""" + return { + "queue_size": self.queue_size, + "total_requests": self.total_requests, + "failed_requests": self.failed_requests, + "success_rate": ( + (self.total_requests - self.failed_requests) / self.total_requests + if self.total_requests > 0 + else 1.0 + ), + } diff --git a/models.py b/models.py index 84bbb03d..36a5c6ec 100644 --- a/models.py +++ b/models.py @@ -585,7 +585,7 @@ def load_F0_models(path): # load F0 model F0_model = JDCNet(num_class=1, seq_len=192) - params = torch.load(path, map_location='cpu')['net'] + params = torch.load(path, map_location='cpu', weights_only=False)['net'] F0_model.load_state_dict(params) _ = F0_model.train() @@ -601,7 +601,7 @@ def _load_config(path): def _load_model(model_config, model_path): model = ASRCNN(**model_config) - params = torch.load(model_path, map_location='cpu')['model'] + params = torch.load(model_path, map_location='cpu', weights_only=False)['model'] model.load_state_dict(params) return model @@ -694,7 +694,7 @@ def build_model(args, text_aligner, pitch_extractor, bert): return nets def load_checkpoint(model, optimizer, path, load_only_params=True, ignore_modules=[]): - state = torch.load(path, map_location='cpu') + state = torch.load(path, map_location='cpu', weights_only=False) params = state['net'] for key in model: if key in params and key not in ignore_modules: diff --git a/requirements.txt b/requirements.txt index 58cf1fbf..30bb8d26 100644 --- a/requirements.txt +++ b/requirements.txt @@ -21,4 +21,7 @@ cached-path tortoise-tts # for the Gradio demo, splitting text flask # for api markdown # for api -flask-cors \ No newline at end of file +flask-cors +fastapi # for WebSocket API +uvicorn[standard] # ASGI server for WebSocket +websockets # WebSocket support \ No newline at end of file diff --git a/test_api_client.py b/test_api_client.py new file mode 100644 index 00000000..b2bf7b0f --- /dev/null +++ b/test_api_client.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +""" +StyleTTS2 Streaming API Client +This script demonstrates how to use the StyleTTS2 streaming API endpoint. +""" + +import requests +import sys +from pathlib import Path +import argparse + + +class StyleTTS2Client: + """Client for interacting with StyleTTS2 Streaming API""" + + def __init__(self, base_url="http://localhost:5000"): + """ + Initialize the client + + Args: + base_url (str): Base URL of the API server + """ + self.base_url = base_url.rstrip("/") + self.stream_endpoint = f"{self.base_url}/api/v1/stream" + + # Available voices + self.available_voices = [ + "f-us-1", + "f-us-2", + "f-us-3", + "f-us-4", + "m-us-1", + "m-us-2", + "m-us-3", + "m-us-4", + ] + + def check_server(self): + """Check if the API server is running""" + try: + response = requests.get(self.base_url, timeout=5) + if response.status_code == 200: + print(f"✓ API server is running at {self.base_url}") + return True + else: + print(f"✗ API server returned status code: {response.status_code}") + return False + except requests.exceptions.ConnectionError: + print(f"✗ Cannot connect to API server at {self.base_url}") + print(" Make sure the server is running with: python api.py") + return False + except Exception as e: + print(f"✗ Error checking server: {e}") + return False + + def synthesize_stream(self, text, voice, output_file, steps=7): + """ + Synthesize speech using the streaming endpoint + + Args: + text (str): Text to synthesize + voice (str): Voice ID to use + output_file (str): Path to save the output WAV file + steps (int): Number of diffusion steps (default: 7, higher=better quality but slower) + + Returns: + bool: True if successful, False otherwise + """ + if voice not in self.available_voices: + print(f"✗ Invalid voice '{voice}'") + print(f" Available voices: {', '.join(self.available_voices)}") + return False + + print(f"\n{'=' * 60}") + print("Synthesizing with streaming API") + print(f"{'=' * 60}") + print(f"Text: {text[:100]}{'...' if len(text) > 100 else ''}") + print(f"Voice: {voice}") + print(f"Diffusion steps: {steps}") + print(f"Output: {output_file}") + print(f"{'=' * 60}\n") + + # Prepare the request + data = {"text": text, "voice": voice, "steps": str(steps)} + + try: + # Make streaming request + print("Sending request to API...") + response = requests.post( + self.stream_endpoint, + data=data, + stream=True, + timeout=300, # 5 minutes timeout + ) + + if response.status_code != 200: + print(f"✗ API returned error status: {response.status_code}") + try: + error_data = response.json() + print(f" Error: {error_data.get('error', 'Unknown error')}") + except Exception: + print(f" Response: {response.text[:200]}") + return False + + # Create output directory if it doesn't exist + output_path = Path(output_file) + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Stream the audio data to file + print("Receiving audio stream...") + chunk_count = 0 + total_bytes = 0 + + with open(output_file, "wb") as f: + for chunk in response.iter_content(chunk_size=8192): + if chunk: + f.write(chunk) + chunk_count += 1 + total_bytes += len(chunk) + + # Print progress every 10 chunks + if chunk_count % 10 == 0: + print( + f" Received {chunk_count} chunks ({total_bytes:,} bytes)...", + end="\r", + ) + + print("\n\n✓ Audio saved successfully!") + print(f" File: {output_file}") + print(f" Size: {total_bytes:,} bytes ({total_bytes / 1024:.2f} KB)") + print(f" Chunks received: {chunk_count}") + + return True + + except requests.exceptions.Timeout: + print( + "✗ Request timed out. The text might be too long or the server is slow." + ) + return False + except requests.exceptions.ConnectionError: + print("✗ Connection error. Make sure the API server is running.") + return False + except Exception as e: + print(f"✗ Error during synthesis: {e}") + import traceback + + traceback.print_exc() + return False + + def list_voices(self): + """List all available voices""" + print("\nAvailable Voices:") + print("=" * 40) + for i, voice in enumerate(self.available_voices, 1): + voice_type = "Female" if voice.startswith("f-") else "Male" + print(f"{i}. {voice:10s} - {voice_type} US English") + print("=" * 40) + + +def main(): + parser = argparse.ArgumentParser( + description="StyleTTS2 Streaming API Client", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Simple synthesis + python test_api_client.py -t "Hello world" -v f-us-1 -o output.wav + + # With custom diffusion steps for better quality + python test_api_client.py -t "Hello world" -v m-us-2 -o output.wav -s 10 + + # Long text synthesis + python test_api_client.py -t "This is a longer text..." -v f-us-3 -o long.wav + + # List available voices + python test_api_client.py --list-voices + + # Custom server URL + python test_api_client.py -t "Hello" -v f-us-1 -o out.wav --url http://192.168.1.100:5000 + """, + ) + + parser.add_argument("-t", "--text", type=str, help="Text to synthesize") + parser.add_argument( + "-v", "--voice", type=str, help="Voice ID (e.g., f-us-1, m-us-2)" + ) + parser.add_argument("-o", "--output", type=str, help="Output WAV file path") + parser.add_argument( + "-s", + "--steps", + type=int, + default=7, + help="Diffusion steps (default: 7, higher=better quality)", + ) + parser.add_argument( + "--url", + type=str, + default="http://localhost:5000", + help="API server URL (default: http://localhost:5000)", + ) + parser.add_argument( + "--list-voices", action="store_true", help="List available voices and exit" + ) + parser.add_argument( + "--check-server", + action="store_true", + help="Check if server is running and exit", + ) + + args = parser.parse_args() + + # Initialize client + client = StyleTTS2Client(base_url=args.url) + + # Handle list voices + if args.list_voices: + client.list_voices() + return 0 + + # Handle check server + if args.check_server: + if client.check_server(): + return 0 + else: + return 1 + + # Validate required arguments + if not args.text or not args.voice or not args.output: + parser.print_help() + print("\n✗ Error: --text, --voice, and --output are required for synthesis") + print("\nQuick start:") + print(' python test_api_client.py -t "Hello world" -v f-us-1 -o output.wav') + return 1 + + # Check server before synthesis + if not client.check_server(): + return 1 + + # Perform synthesis + success = client.synthesize_stream( + text=args.text, voice=args.voice, output_file=args.output, steps=args.steps + ) + + if success: + print("\n✓ Synthesis completed successfully!") + print("\nYou can play the audio with:") + print(f" ffplay {args.output}") + print(" or") + print(f" aplay {args.output}") + return 0 + else: + print("\n✗ Synthesis failed") + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test_ws_client.py b/test_ws_client.py new file mode 100644 index 00000000..d54326ad --- /dev/null +++ b/test_ws_client.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +""" +WebSocket TTS client for testing StyleTTS2 WebSocket API. +""" + +import asyncio +import json +import base64 +import sys +import argparse +import websockets +from pathlib import Path + + +async def test_websocket_tts( + uri: str, text: str, voice: str = "m-us-1", output_file: str = "output.mp3" +): + """ + Test WebSocket TTS endpoint. + + Args: + uri: WebSocket URI (e.g., ws://localhost:8765/ws/tts) + text: Text to synthesize + voice: Voice ID + output_file: Output MP3 file path + """ + print(f"Connecting to {uri}...") + + audio_chunks = [] + + async with websockets.connect(uri) as websocket: + # Receive welcome message + welcome = await websocket.recv() + print(f"Server: {welcome}") + + # Send text with flush + message = {"text": text, "voice": voice, "flush": True} + + print(f"\nSending: {text[:50]}...") + print(f"Voice: {voice}") + + await websocket.send(json.dumps(message)) + + # Receive audio chunks + chunk_count = 0 + while True: + response = await websocket.recv() + data = json.loads(response) + + if "error" in data: + print(f"Error: {data['error']}") + break + + if "audio" in data and data["audio"]: + audio_chunks.append(data["audio"]) + chunk_count += 1 + print( + f"Received chunk {chunk_count} (isFinal: {data.get('isFinal', False)})" + ) + + if data.get("isFinal"): + print(f"\nReceived {chunk_count} audio chunks") + break + + # Combine and save audio + if audio_chunks: + print(f"Saving audio to {output_file}...") + + # Decode all chunks + audio_bytes = b"".join(base64.b64decode(chunk) for chunk in audio_chunks) + + # Write to file + with open(output_file, "wb") as f: + f.write(audio_bytes) + + print(f"✓ Saved {len(audio_bytes)} bytes to {output_file}") + else: + print("No audio received") + + +async def test_chunked_streaming( + uri: str, text_chunks: list, voice: str = "m-us-1", output_file: str = "output.mp3" +): + """ + Test chunked text streaming (simulates real-time text input). + + Args: + uri: WebSocket URI + text_chunks: List of text chunks to send + voice: Voice ID + output_file: Output MP3 file path + """ + print(f"Connecting to {uri}...") + + audio_chunks = [] + + async with websockets.connect(uri) as websocket: + # Receive welcome message + welcome = await websocket.recv() + print(f"Server: {welcome}") + + # Send text chunks incrementally + for i, chunk in enumerate(text_chunks): + is_last = i == len(text_chunks) - 1 + + message = { + "text": chunk, + "voice": voice, + "flush": is_last, # Only flush on last chunk + } + + print(f"\nSending chunk {i + 1}/{len(text_chunks)}: {chunk[:30]}...") + await websocket.send(json.dumps(message)) + + # Small delay to simulate real-time input + if not is_last: + await asyncio.sleep(0.1) + + # Receive audio + chunk_count = 0 + while True: + response = await websocket.recv() + data = json.loads(response) + + if "error" in data: + print(f"Error: {data['error']}") + break + + if "audio" in data and data["audio"]: + audio_chunks.append(data["audio"]) + chunk_count += 1 + print(f"Received audio chunk {chunk_count}") + + if data.get("isFinal"): + print(f"\nReceived {chunk_count} total audio chunks") + break + + # Save audio + if audio_chunks: + audio_bytes = b"".join(base64.b64decode(chunk) for chunk in audio_chunks) + with open(output_file, "wb") as f: + f.write(audio_bytes) + print(f"✓ Saved to {output_file}") + + +def main(): + parser = argparse.ArgumentParser(description="WebSocket TTS Client") + parser.add_argument( + "--uri", + default="ws://localhost:8765/ws/tts", + help="WebSocket URI (default: ws://localhost:8765/ws/tts)", + ) + parser.add_argument( + "--text", + default="Hello, this is a test of the WebSocket TTS streaming service.", + help="Text to synthesize", + ) + parser.add_argument( + "--voice", + default="m-us-1", + choices=[ + "f-us-1", + "f-us-2", + "f-us-3", + "f-us-4", + "m-us-1", + "m-us-2", + "m-us-3", + "m-us-4", + ], + help="Voice ID", + ) + parser.add_argument("--output", default="output.mp3", help="Output MP3 file") + parser.add_argument( + "--chunked", action="store_true", help="Test chunked streaming mode" + ) + + args = parser.parse_args() + + try: + if args.chunked: + # Split text into chunks for testing + words = args.text.split() + chunks = [" ".join(words[i : i + 3]) for i in range(0, len(words), 3)] + print(f"Testing chunked mode with {len(chunks)} chunks") + asyncio.run( + test_chunked_streaming(args.uri, chunks, args.voice, args.output) + ) + else: + asyncio.run( + test_websocket_tts(args.uri, args.text, args.voice, args.output) + ) + except KeyboardInterrupt: + print("\nInterrupted") + except Exception as e: + print(f"Error: {e}") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/ws_server.py b/ws_server.py new file mode 100644 index 00000000..34f0e188 --- /dev/null +++ b/ws_server.py @@ -0,0 +1,344 @@ +""" +Production-grade WebSocket TTS server with FastAPI. +Handles chunked text input and streams base64 audio output. +""" + +import asyncio +import json +import logging +import time +from contextlib import asynccontextmanager +from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from tortoise.utils.text import split_and_recombine_text +import uvicorn + +from inference_manager import InferenceManager +from audio_streamer import AudioStreamer + +# Configure logging +logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" +) +logger = logging.getLogger(__name__) + +# Global instances +inference_manager = None +audio_streamer = AudioStreamer(sample_rate=24000) + +# Available voices +AVAILABLE_VOICES = [ + "f-us-1", + "f-us-2", + "f-us-3", + "f-us-4", + "m-us-1", + "m-us-2", + "m-us-3", + "m-us-4", +] + +# Server state +server_ready = False + + +@asynccontextmanager +async def lifespan(app: FastAPI): + """Lifespan event handler for startup and shutdown.""" + global server_ready, inference_manager + logger.info("Starting StyleTTS2 WebSocket server...") + + # Download NLTK data if needed + import nltk + + try: + nltk.data.find("tokenizers/punkt_tab") + except LookupError: + logger.info("Downloading NLTK punkt_tab...") + nltk.download("punkt_tab", quiet=True) + + # Initialize inference manager with precomputed voices + logger.info("Precomputing voice styles...") + inference_manager = InferenceManager( + max_queue_size=100, voice_list=AVAILABLE_VOICES + ) + logger.info("Models loaded and voices precomputed") + + server_ready = True + logger.info("Server ready to accept WebSocket connections") + + yield + + # Cleanup on shutdown + logger.info("Shutting down server...") + + +# Initialize FastAPI app with lifespan +app = FastAPI( + title="StyleTTS2 WebSocket API", + description="Production TTS streaming service with WebSocket support", + version="1.0.0", + lifespan=lifespan, +) + +# CORS middleware +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + +@app.get("/health") +async def health_check(): + """Health check endpoint.""" + if not server_ready: + raise HTTPException(status_code=503, detail="Server initializing") + + stats = inference_manager.get_stats() + return {"status": "healthy", "ready": server_ready, "stats": stats} + + +@app.get("/voices") +async def list_voices(): + """List available voices.""" + return {"voices": AVAILABLE_VOICES} + + +class ConnectionManager: + """Manages WebSocket connection state and text buffering.""" + + def __init__(self, websocket: WebSocket, connection_id: str): + self.websocket = websocket + self.connection_id = connection_id + self.text_buffer = [] + self.voice = "f-us-1" # Default voice + self.last_activity = time.time() + self.active = True + + async def send_json(self, data: dict): + """Send JSON message to client.""" + if not self.active: + return + try: + await self.websocket.send_json(data) + self.last_activity = time.time() + except Exception as e: + logger.debug(f"Failed to send message (connection likely closed): {e}") + self.active = False + + async def send_error(self, error_message: str): + """Send error message to client.""" + if self.active: + await self.send_json({"error": error_message, "isFinal": True}) + + def add_text(self, text: str): + """Add text chunk to buffer.""" + if text: + self.text_buffer.append(text) + self.last_activity = time.time() + + def get_buffered_text(self) -> str: + """Get and clear text buffer.""" + text = " ".join(self.text_buffer) + self.text_buffer = [] + return text + + def is_idle(self, timeout_seconds: int = 120) -> bool: + """Check if connection has been idle for too long.""" + return (time.time() - self.last_activity) > timeout_seconds + + +@app.websocket("/ws/tts") +async def websocket_tts_endpoint(websocket: WebSocket): + """ + WebSocket endpoint for TTS streaming. + + Expected input JSON: + { + "text": "chunk of text", + "voice": "f-us-1", # optional, defaults to f-us-1 + "flush": true/false # if true, generate audio from buffered text + } + + Output JSON: + { + "audio": "base64_encoded_audio_bytes", + "isFinal": true/false + } + """ + await websocket.accept() + + connection_id = f"{websocket.client.host}:{websocket.client.port}" + conn_manager = ConnectionManager(websocket, connection_id) + + logger.info(f"WebSocket connected: {connection_id}") + + # Send welcome message + await conn_manager.send_json( + { + "status": "connected", + "available_voices": AVAILABLE_VOICES, + "message": "Send text chunks with 'flush: true' to generate audio", + } + ) + + try: + # Start idle timeout monitor + timeout_task = asyncio.create_task(monitor_idle_timeout(conn_manager)) + + while conn_manager.active: + try: + # Receive message with timeout + data = await asyncio.wait_for(websocket.receive_json(), timeout=5.0) + + # Parse message + text = data.get("text", "").strip() + voice = data.get("voice", conn_manager.voice).lower() + flush = data.get("flush", False) + + # Validate voice + if voice not in AVAILABLE_VOICES: + await conn_manager.send_error( + f"Invalid voice '{voice}'. Available: {AVAILABLE_VOICES}" + ) + continue + + conn_manager.voice = voice + + # Add text to buffer + if text: + conn_manager.add_text(text) + + # Generate audio if flush is requested + if flush: + buffered_text = conn_manager.get_buffered_text() + + if not buffered_text: + await conn_manager.send_json({"audio": "", "isFinal": True}) + continue + + # Split long text into manageable chunks + text_chunks = split_and_recombine_text(buffered_text) + + logger.info( + f"Processing {len(text_chunks)} text chunks for {connection_id}, " + f"voice={voice}" + ) + + # Process each text chunk + for chunk_idx, text_chunk in enumerate(text_chunks): + is_last_text_chunk = chunk_idx == len(text_chunks) - 1 + + # Generate audio + audio_wav = await inference_manager.generate_audio( + text=text_chunk, + voice=voice, + alpha=0.3, + beta=0.7, + diffusion_steps=7, + embedding_scale=1.0, + ) + + if audio_wav is None: + await conn_manager.send_error( + "Audio generation failed or queue full" + ) + break + + # Send complete audio as single base64-encoded WAV + base64_audio = audio_streamer.encode_full_audio(audio_wav) + await conn_manager.send_json( + { + "audio": base64_audio, + "isFinal": is_last_text_chunk, + } + ) + + logger.info( + f"Sent complete audio for chunk {chunk_idx + 1}/{len(text_chunks)}" + ) + + except asyncio.TimeoutError: + # No message received, continue loop + continue + + except WebSocketDisconnect as e: + # Client disconnected gracefully + logger.info(f"Client disconnected: {connection_id} (code: {e.code})") + break + + except json.JSONDecodeError: + await conn_manager.send_error("Invalid JSON format") + + except Exception as e: + logger.error(f"Error processing message: {e}", exc_info=True) + await conn_manager.send_error(f"Processing error: {str(e)}") + + # Cancel timeout monitor + timeout_task.cancel() + + except WebSocketDisconnect as e: + logger.info(f"WebSocket disconnected: {connection_id} (code: {e.code})") + except Exception as e: + logger.error(f"WebSocket error: {e}", exc_info=True) + finally: + if conn_manager.active: + conn_manager.active = False + logger.info(f"Connection closed: {connection_id}") + + +async def monitor_idle_timeout( + conn_manager: ConnectionManager, timeout_seconds: int = 120 +): + """Monitor connection for idle timeout (default 2 minutes).""" + try: + while conn_manager.active: + await asyncio.sleep(30) # Check every 30 seconds + + if conn_manager.is_idle(timeout_seconds): + logger.warning( + f"Connection {conn_manager.connection_id} idle for {timeout_seconds}s, closing" + ) + await conn_manager.send_json( + { + "status": "timeout", + "message": f"Connection idle for {timeout_seconds} seconds", + "isFinal": True, + } + ) + conn_manager.active = False + await conn_manager.websocket.close() + break + except asyncio.CancelledError: + pass + + +def main(): + """Run the WebSocket server.""" + import sys + + # Parse arguments + host = "0.0.0.0" + port = 8765 + + if len(sys.argv) > 1: + port = int(sys.argv[1]) + + logger.info(f"Starting server on {host}:{port}") + + uvicorn.run( + app, + host=host, + port=port, + log_level="info", + access_log=True, + ws_ping_interval=20, + ws_ping_timeout=20, + ) + + +if __name__ == "__main__": + main()