Commit ·
7a8d16e
1
Parent(s): 1f92494
feat(api): server streaming chuẩn OpenAI (/v1/audio/speech) + profile docker api-gpu/api-cpu
Browse filesapps/openai_speech.py: pcm/wav, stream_format audio|sse, sample_rate 48k/24k/16k/8k
(soxr từng chunk), /v1/models, /v1/voices (+POST clone), /health; trần luồng theo
backend (GPU max_streams, CPU 1 fp32 / 2 int8) với hàng đợi nhỏ và 429 Retry-After;
warm-up lúc khởi động; lỗi đúng dạng OpenAI. Client mẫu examples/openai_speech_client.py
đo TTFA/RTF, --bench N, --sse, --sdk. Compose: api-gpu, api-cpu (dev) và api (prod).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- apps/openai_speech.py +373 -0
- docker/docker-compose.prod.yml +35 -0
- docker/docker-compose.yml +77 -0
- examples/openai_speech_client.py +163 -0
apps/openai_speech.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VieNeu-TTS — OpenAI-compatible speech API (streaming), CPU or GPU.
|
| 3 |
+
==================================================================
|
| 4 |
+
Drop-in for ``POST /v1/audio/speech``: any OpenAI SDK / Pipecat / LiveKit /
|
| 5 |
+
Vercel AI client works by changing ``base_url``. Audio streams as it is
|
| 6 |
+
generated — the first bytes leave ~115 ms after the request on an RTX 3060,
|
| 7 |
+
~600 ms on a 6-core CPU (see docs/streaming.vi.md for every number).
|
| 8 |
+
|
| 9 |
+
uv run python -m apps.openai_speech # http://127.0.0.1:8000
|
| 10 |
+
VIENEU_BACKEND=onnx uv run python -m apps.openai_speech # force CPU
|
| 11 |
+
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="x")
|
| 14 |
+
with client.audio.speech.with_streaming_response.create(
|
| 15 |
+
model="vieneu-v3-turbo", voice="Mai Anh", input="Xin chào!",
|
| 16 |
+
response_format="pcm", # 48 kHz s16le mono (see `sample_rate` below)
|
| 17 |
+
) as r:
|
| 18 |
+
for chunk in r.iter_bytes(4096):
|
| 19 |
+
play(chunk)
|
| 20 |
+
|
| 21 |
+
Request body (OpenAI fields + a few extras, all optional but ``input``):
|
| 22 |
+
model any string; reported back as-is
|
| 23 |
+
input text, chunked internally at ``max_chars`` (256)
|
| 24 |
+
voice preset name (GET /v1/voices) or one added with POST /v1/voices
|
| 25 |
+
response_format "pcm" (s16le, no header) | "wav" (header with unknown length,
|
| 26 |
+
plays as it streams). mp3/opus/aac/flac → 400.
|
| 27 |
+
stream_format "audio" (default: raw chunked body) | "sse" (Server-Sent
|
| 28 |
+
Events: {"type":"speech.audio.delta","audio":"<base64>"} ...
|
| 29 |
+
{"type":"speech.audio.done","usage":{...}})
|
| 30 |
+
speed accepted for compatibility, ignored (header X-VieNeu-Ignored)
|
| 31 |
+
sample_rate 48000 (native) | 24000 (OpenAI's pcm rate) | 16000 | 8000 —
|
| 32 |
+
resampled on the fly (soxr), per chunk, no extra latency
|
| 33 |
+
temperature, top_k, top_p, repetition_penalty, max_chars sampling extras
|
| 34 |
+
|
| 35 |
+
Concurrency: GPU serves ``VIENEU_MAX_STREAMS`` streams at once (continuous
|
| 36 |
+
batching, default 16); CPU serves one (fp32) or two (int8) — the ONNX engine
|
| 37 |
+
interleaves them frame by frame but they share the cores.
|
| 38 |
+
Extra requests wait up to ``VIENEU_QUEUE_TIMEOUT`` s in a queue of at most
|
| 39 |
+
``VIENEU_QUEUE`` entries, then get 429 with Retry-After.
|
| 40 |
+
|
| 41 |
+
Environment:
|
| 42 |
+
VIENEU_BACKEND=auto|onnx|pytorch VIENEU_DEVICE=auto|cuda|cpu
|
| 43 |
+
VIENEU_PRECISION=fp32|int8 (CPU) VIENEU_ONNX_DIR=... (local ONNX export)
|
| 44 |
+
VIENEU_MAX_STREAMS=16 (GPU) VIENEU_QUEUE=16 VIENEU_QUEUE_TIMEOUT=10
|
| 45 |
+
VIENEU_API_KEY=... (Bearer auth; unset = open)
|
| 46 |
+
VIENEU_WATERMARK=1 HOST=0.0.0.0 PORT=8000
|
| 47 |
+
"""
|
| 48 |
+
from __future__ import annotations
|
| 49 |
+
|
| 50 |
+
import base64
|
| 51 |
+
import io
|
| 52 |
+
import json
|
| 53 |
+
import logging
|
| 54 |
+
import os
|
| 55 |
+
import struct
|
| 56 |
+
import threading
|
| 57 |
+
import time
|
| 58 |
+
import uuid
|
| 59 |
+
import wave
|
| 60 |
+
from typing import Any, Iterator, Optional
|
| 61 |
+
|
| 62 |
+
import numpy as np
|
| 63 |
+
import uvicorn
|
| 64 |
+
from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, Request, UploadFile
|
| 65 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 66 |
+
from pydantic import BaseModel, Field
|
| 67 |
+
|
| 68 |
+
from vieneu import Vieneu
|
| 69 |
+
|
| 70 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
| 71 |
+
log = logging.getLogger("vieneu.api")
|
| 72 |
+
|
| 73 |
+
SAMPLE_RATE = 48_000
|
| 74 |
+
MODEL_ID = "vieneu-v3-turbo"
|
| 75 |
+
RATES = (48_000, 24_000, 16_000, 8_000)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _env_int(name: str, default: int) -> int:
|
| 79 |
+
try:
|
| 80 |
+
return int(os.environ.get(name, default))
|
| 81 |
+
except ValueError:
|
| 82 |
+
return default
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# ── engine + admission ───────────────────────────────────────────────────────
|
| 86 |
+
|
| 87 |
+
class Engine:
|
| 88 |
+
"""The model plus the admission gate (how many streams run at once)."""
|
| 89 |
+
|
| 90 |
+
def __init__(self):
|
| 91 |
+
backend = os.environ.get("VIENEU_BACKEND", "auto")
|
| 92 |
+
device = os.environ.get("VIENEU_DEVICE", "auto")
|
| 93 |
+
kw: dict = dict(backend=backend, device=device,
|
| 94 |
+
precision=os.environ.get("VIENEU_PRECISION", "fp32"),
|
| 95 |
+
onnx_dir=os.environ.get("VIENEU_ONNX_DIR") or None,
|
| 96 |
+
max_streams=_env_int("VIENEU_MAX_STREAMS", 16))
|
| 97 |
+
log.info("⏳ loading VieNeu-TTS v3 Turbo (backend=%s device=%s)", backend, device)
|
| 98 |
+
t = time.perf_counter()
|
| 99 |
+
self.tts = Vieneu(mode="v3turbo", **kw)
|
| 100 |
+
self.backend = self.tts.backend
|
| 101 |
+
self.watermark = os.environ.get("VIENEU_WATERMARK", "1") != "0"
|
| 102 |
+
# GPU: the scheduler batches every stream. CPU: the ONNX engine interleaves
|
| 103 |
+
# calls frame by frame, but they share the cores — measured on a 6-core
|
| 104 |
+
# desktop, fp32 keeps one stream real-time (RTF 0.58; two → 1.19), int8
|
| 105 |
+
# two (RTF 0.35; two → 0.67). VIENEU_MAX_STREAMS overrides either.
|
| 106 |
+
self.sched = self.tts._get_stream_scheduler() if self.backend == "pytorch" else None
|
| 107 |
+
if self.sched is not None:
|
| 108 |
+
self.max_streams = self.sched.B
|
| 109 |
+
else:
|
| 110 |
+
cpu_default = 2 if kw["precision"] == "int8" else 1
|
| 111 |
+
self.max_streams = _env_int("VIENEU_MAX_STREAMS", cpu_default) if "VIENEU_MAX_STREAMS" in os.environ else cpu_default
|
| 112 |
+
self.max_queue = _env_int("VIENEU_QUEUE", self.max_streams)
|
| 113 |
+
self.queue_timeout = float(os.environ.get("VIENEU_QUEUE_TIMEOUT", "10"))
|
| 114 |
+
self._gate = threading.BoundedSemaphore(self.max_streams)
|
| 115 |
+
self._lock = threading.Lock()
|
| 116 |
+
self.active = 0
|
| 117 |
+
self.waiting = 0
|
| 118 |
+
# Warm-up: capture the CUDA graphs / load the ONNX graphs before the
|
| 119 |
+
# first client pays for it.
|
| 120 |
+
for _ in self.tts.infer_stream("Xin chào.", apply_watermark=False):
|
| 121 |
+
pass
|
| 122 |
+
log.info("✅ ready in %.1fs: backend=%s max_streams=%d queue=%d", time.perf_counter() - t,
|
| 123 |
+
self.backend, self.max_streams, self.max_queue)
|
| 124 |
+
|
| 125 |
+
def acquire(self) -> None:
|
| 126 |
+
with self._lock:
|
| 127 |
+
if self.waiting >= self.max_queue:
|
| 128 |
+
raise HTTPException(429, "server busy: queue full", headers={"Retry-After": "1"})
|
| 129 |
+
self.waiting += 1
|
| 130 |
+
try:
|
| 131 |
+
if not self._gate.acquire(timeout=self.queue_timeout):
|
| 132 |
+
raise HTTPException(429, "server busy: timed out waiting for a stream slot",
|
| 133 |
+
headers={"Retry-After": "2"})
|
| 134 |
+
finally:
|
| 135 |
+
with self._lock:
|
| 136 |
+
self.waiting -= 1
|
| 137 |
+
with self._lock:
|
| 138 |
+
self.active += 1
|
| 139 |
+
|
| 140 |
+
def release(self) -> None:
|
| 141 |
+
with self._lock:
|
| 142 |
+
self.active -= 1
|
| 143 |
+
self._gate.release()
|
| 144 |
+
|
| 145 |
+
def voices(self) -> list:
|
| 146 |
+
out = []
|
| 147 |
+
for name, v in self.tts._preset_voices.items():
|
| 148 |
+
out.append({"id": name, "name": name, "description": v.get("description", ""),
|
| 149 |
+
"gender": v.get("gender", "")})
|
| 150 |
+
return out
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
ENGINE: Optional[Engine] = None
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def engine() -> Engine:
|
| 157 |
+
global ENGINE
|
| 158 |
+
if ENGINE is None:
|
| 159 |
+
ENGINE = Engine()
|
| 160 |
+
return ENGINE
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ── auth / errors in OpenAI's shape ───────────────────────────────────────────
|
| 164 |
+
|
| 165 |
+
def _auth(authorization: Optional[str] = Header(default=None)) -> None:
|
| 166 |
+
key = os.environ.get("VIENEU_API_KEY")
|
| 167 |
+
if key and authorization != f"Bearer {key}":
|
| 168 |
+
raise HTTPException(401, "invalid api key")
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _error(status: int, message: str, code: Optional[str] = None, headers=None) -> JSONResponse:
|
| 172 |
+
return JSONResponse({"error": {"message": message, "type": "invalid_request_error",
|
| 173 |
+
"code": code or status}}, status_code=status, headers=headers)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
app = FastAPI(title="VieNeu-TTS speech API", version="1.0")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@app.exception_handler(HTTPException)
|
| 180 |
+
async def _http_exc(_req: Request, exc: HTTPException):
|
| 181 |
+
return _error(exc.status_code, str(exc.detail), headers=exc.headers)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@app.on_event("startup")
|
| 185 |
+
def _startup() -> None:
|
| 186 |
+
engine()
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# ── audio helpers ────────────────────────────────────────────────────────────
|
| 190 |
+
|
| 191 |
+
def _pcm16(x: np.ndarray) -> bytes:
|
| 192 |
+
return (np.asarray(x, dtype=np.float32) * 32767).clip(-32768, 32767).astype("<i2").tobytes()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _wav_header(rate: int) -> bytes:
|
| 196 |
+
"""A WAV header claiming an unknown (huge) length, so players start at once."""
|
| 197 |
+
h = io.BytesIO()
|
| 198 |
+
with wave.open(h, "wb") as w:
|
| 199 |
+
w.setnchannels(1)
|
| 200 |
+
w.setsampwidth(2)
|
| 201 |
+
w.setframerate(rate)
|
| 202 |
+
w.setnframes(0)
|
| 203 |
+
b = bytearray(h.getvalue())
|
| 204 |
+
struct.pack_into("<I", b, 4, 0xFFFFFFFF) # RIFF size
|
| 205 |
+
struct.pack_into("<I", b, len(b) - 4, 0xFFFFFFFF) # data size
|
| 206 |
+
return bytes(b)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class _Resampler:
|
| 210 |
+
"""48 kHz → ``rate`` chunk by chunk with carried state (soxr), no added latency."""
|
| 211 |
+
|
| 212 |
+
def __init__(self, rate: int):
|
| 213 |
+
self.rate = rate
|
| 214 |
+
self._rs = None
|
| 215 |
+
if rate != SAMPLE_RATE:
|
| 216 |
+
import soxr
|
| 217 |
+
self._rs = soxr.ResampleStream(SAMPLE_RATE, rate, 1, dtype="float32", quality="HQ")
|
| 218 |
+
|
| 219 |
+
def __call__(self, x: np.ndarray, last: bool = False) -> np.ndarray:
|
| 220 |
+
if self._rs is None:
|
| 221 |
+
return x
|
| 222 |
+
return self._rs.resample_chunk(np.asarray(x, dtype=np.float32), last=last)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# ── /v1/audio/speech ─────────────────────────────────────────────────────────
|
| 226 |
+
|
| 227 |
+
class SpeechRequest(BaseModel):
|
| 228 |
+
model: str = MODEL_ID
|
| 229 |
+
input: str = Field(min_length=1, max_length=20_000)
|
| 230 |
+
voice: Optional[str] = None
|
| 231 |
+
response_format: str = "wav"
|
| 232 |
+
stream_format: str = "audio"
|
| 233 |
+
speed: Optional[float] = None
|
| 234 |
+
instructions: Optional[str] = None
|
| 235 |
+
sample_rate: int = SAMPLE_RATE
|
| 236 |
+
temperature: float = 0.8
|
| 237 |
+
top_k: int = 25
|
| 238 |
+
top_p: float = 0.95
|
| 239 |
+
repetition_penalty: float = 1.2
|
| 240 |
+
max_chars: int = 256
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _speech_chunks(eng: Engine, req: SpeechRequest, rid: str) -> Iterator[np.ndarray]:
|
| 244 |
+
"""float32 chunks at ``req.sample_rate``; logs TTFA / RTF; holds one stream slot."""
|
| 245 |
+
t0 = time.perf_counter()
|
| 246 |
+
first = None
|
| 247 |
+
emitted = 0
|
| 248 |
+
rs = _Resampler(req.sample_rate)
|
| 249 |
+
try:
|
| 250 |
+
for chunk in eng.tts.infer_stream(
|
| 251 |
+
req.input, voice=req.voice or None, apply_watermark=eng.watermark,
|
| 252 |
+
temperature=req.temperature, top_k=req.top_k, top_p=req.top_p,
|
| 253 |
+
repetition_penalty=req.repetition_penalty, max_chars=req.max_chars,
|
| 254 |
+
):
|
| 255 |
+
if chunk is None or len(chunk) == 0:
|
| 256 |
+
continue
|
| 257 |
+
if first is None:
|
| 258 |
+
first = time.perf_counter() - t0
|
| 259 |
+
emitted += len(chunk)
|
| 260 |
+
out = rs(chunk)
|
| 261 |
+
if len(out):
|
| 262 |
+
yield out
|
| 263 |
+
tail = rs(np.zeros(0, np.float32), last=True)
|
| 264 |
+
if len(tail):
|
| 265 |
+
yield tail
|
| 266 |
+
finally:
|
| 267 |
+
eng.release()
|
| 268 |
+
total = time.perf_counter() - t0
|
| 269 |
+
audio_s = emitted / SAMPLE_RATE
|
| 270 |
+
log.info("%s done: ttfa=%s total=%.2fs audio=%.2fs rtf=%s active=%d", rid,
|
| 271 |
+
f"{first*1000:.0f}ms" if first is not None else "-", total, audio_s,
|
| 272 |
+
f"{total/audio_s:.2f}" if audio_s else "-", eng.active)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def _audio_body(chunks: Iterator[np.ndarray], fmt: str, rate: int) -> Iterator[bytes]:
|
| 276 |
+
if fmt == "wav":
|
| 277 |
+
yield _wav_header(rate)
|
| 278 |
+
for c in chunks:
|
| 279 |
+
yield _pcm16(c)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _sse_body(chunks: Iterator[np.ndarray], fmt: str, rate: int) -> Iterator[bytes]:
|
| 283 |
+
def ev(obj: dict) -> bytes:
|
| 284 |
+
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n".encode("utf-8")
|
| 285 |
+
n = 0
|
| 286 |
+
if fmt == "wav":
|
| 287 |
+
yield ev({"type": "speech.audio.delta", "audio": base64.b64encode(_wav_header(rate)).decode()})
|
| 288 |
+
for c in chunks:
|
| 289 |
+
n += len(c)
|
| 290 |
+
yield ev({"type": "speech.audio.delta", "audio": base64.b64encode(_pcm16(c)).decode()})
|
| 291 |
+
yield ev({"type": "speech.audio.done",
|
| 292 |
+
"usage": {"output_samples": n, "sample_rate": rate, "seconds": round(n / rate, 3)}})
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
@app.post("/v1/audio/speech", dependencies=[Depends(_auth)])
|
| 296 |
+
def speech(req: SpeechRequest):
|
| 297 |
+
eng = engine()
|
| 298 |
+
fmt = req.response_format.lower()
|
| 299 |
+
if fmt not in ("pcm", "wav"):
|
| 300 |
+
raise HTTPException(400, f"response_format '{fmt}' not supported; use 'pcm' or 'wav'")
|
| 301 |
+
if req.stream_format not in ("audio", "sse"):
|
| 302 |
+
raise HTTPException(400, "stream_format must be 'audio' or 'sse'")
|
| 303 |
+
if req.sample_rate not in RATES:
|
| 304 |
+
raise HTTPException(400, f"sample_rate must be one of {RATES}")
|
| 305 |
+
if req.voice and req.voice not in eng.tts._preset_voices:
|
| 306 |
+
raise HTTPException(400, f"unknown voice '{req.voice}'; see GET /v1/voices")
|
| 307 |
+
rid = f"spk-{uuid.uuid4().hex[:8]}"
|
| 308 |
+
eng.acquire() # 429 if the server is full; released when the stream ends
|
| 309 |
+
chunks = _speech_chunks(eng, req, rid)
|
| 310 |
+
headers = {"X-Request-Id": rid, "X-Sample-Rate": str(req.sample_rate), "Cache-Control": "no-store"}
|
| 311 |
+
ignored = [k for k in ("speed", "instructions") if getattr(req, k) is not None]
|
| 312 |
+
if ignored:
|
| 313 |
+
headers["X-VieNeu-Ignored"] = ",".join(ignored)
|
| 314 |
+
if req.stream_format == "sse":
|
| 315 |
+
return StreamingResponse(_sse_body(chunks, fmt, req.sample_rate),
|
| 316 |
+
media_type="text/event-stream", headers=headers)
|
| 317 |
+
media = "audio/wav" if fmt == "wav" else "audio/pcm"
|
| 318 |
+
return StreamingResponse(_audio_body(chunks, fmt, req.sample_rate), media_type=media, headers=headers)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
# ── discovery ────────────────────────────────────────────────────────────────
|
| 322 |
+
|
| 323 |
+
@app.get("/v1/models", dependencies=[Depends(_auth)])
|
| 324 |
+
def models():
|
| 325 |
+
eng = engine()
|
| 326 |
+
return {"object": "list", "data": [{
|
| 327 |
+
"id": MODEL_ID, "object": "model", "created": 0, "owned_by": "vieneu",
|
| 328 |
+
"sample_rate": SAMPLE_RATE, "backend": eng.backend,
|
| 329 |
+
"max_streams": eng.max_streams, "response_formats": ["pcm", "wav"],
|
| 330 |
+
"stream_formats": ["audio", "sse"], "sample_rates": list(RATES),
|
| 331 |
+
}]}
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@app.get("/v1/voices", dependencies=[Depends(_auth)])
|
| 335 |
+
def voices():
|
| 336 |
+
return {"object": "list", "data": engine().voices()}
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@app.post("/v1/voices", dependencies=[Depends(_auth)])
|
| 340 |
+
async def add_voice(name: str = Form(...), file: UploadFile = File(...), denoise: bool = Form(True),
|
| 341 |
+
description: str = Form("")):
|
| 342 |
+
"""Enroll a 3-8 s reference clip as ``voice=name`` (in memory, for this process)."""
|
| 343 |
+
import tempfile
|
| 344 |
+
eng = engine()
|
| 345 |
+
suffix = os.path.splitext(file.filename or "")[1] or ".wav"
|
| 346 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as f:
|
| 347 |
+
f.write(await file.read())
|
| 348 |
+
path = f.name
|
| 349 |
+
try:
|
| 350 |
+
eng.tts.add_voice(name, path, denoise=denoise, description=description)
|
| 351 |
+
except Exception as e: # noqa: BLE001
|
| 352 |
+
raise HTTPException(400, f"could not enroll voice: {e}")
|
| 353 |
+
finally:
|
| 354 |
+
os.unlink(path)
|
| 355 |
+
return {"id": name, "name": name, "description": description}
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@app.get("/health")
|
| 359 |
+
def health():
|
| 360 |
+
eng = engine()
|
| 361 |
+
return {"status": "ok", "backend": eng.backend, "max_streams": eng.max_streams,
|
| 362 |
+
"active": eng.active, "waiting": eng.waiting, "sample_rate": SAMPLE_RATE}
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def main() -> None:
|
| 366 |
+
host = os.environ.get("HOST", "0.0.0.0")
|
| 367 |
+
port = _env_int("PORT", 8000)
|
| 368 |
+
# One worker: the model (and on GPU the scheduler) is process-local.
|
| 369 |
+
uvicorn.run(app, host=host, port=port, workers=1, log_level="info")
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
if __name__ == "__main__":
|
| 373 |
+
main()
|
docker/docker-compose.prod.yml
CHANGED
|
@@ -22,5 +22,40 @@ services:
|
|
| 22 |
env_file:
|
| 23 |
- .env
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
volumes:
|
| 26 |
huggingface_cache:
|
|
|
|
| 22 |
env_file:
|
| 23 |
- .env
|
| 24 |
|
| 25 |
+
# ========================================================
|
| 26 |
+
# GPU Production — OpenAI-compatible streaming API (same image, other command)
|
| 27 |
+
# docker compose -f docker/docker-compose.prod.yml --profile api up
|
| 28 |
+
# ========================================================
|
| 29 |
+
api:
|
| 30 |
+
restart: unless-stopped
|
| 31 |
+
profiles: ["api"]
|
| 32 |
+
image: ${IMAGE_NAME}:${IMAGE_TAG}
|
| 33 |
+
container_name: vieneu-tts-api
|
| 34 |
+
command: ["python", "-m", "apps.openai_speech"]
|
| 35 |
+
ports:
|
| 36 |
+
- "${API_PORT:-8000}:8000"
|
| 37 |
+
environment:
|
| 38 |
+
- PORT=8000
|
| 39 |
+
- VIENEU_MAX_STREAMS=${VIENEU_MAX_STREAMS:-16}
|
| 40 |
+
- VIENEU_QUEUE=${VIENEU_QUEUE:-16}
|
| 41 |
+
- VIENEU_API_KEY=${VIENEU_API_KEY:-}
|
| 42 |
+
healthcheck:
|
| 43 |
+
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3).status == 200 else 1)"]
|
| 44 |
+
interval: 15s
|
| 45 |
+
timeout: 5s
|
| 46 |
+
start_period: 120s
|
| 47 |
+
retries: 3
|
| 48 |
+
deploy:
|
| 49 |
+
resources:
|
| 50 |
+
reservations:
|
| 51 |
+
devices:
|
| 52 |
+
- driver: nvidia
|
| 53 |
+
count: all
|
| 54 |
+
capabilities: [gpu]
|
| 55 |
+
volumes:
|
| 56 |
+
- huggingface_cache:/root/.cache/huggingface
|
| 57 |
+
env_file:
|
| 58 |
+
- .env
|
| 59 |
+
|
| 60 |
volumes:
|
| 61 |
huggingface_cache:
|
docker/docker-compose.yml
CHANGED
|
@@ -53,6 +53,83 @@ services:
|
|
| 53 |
count: all
|
| 54 |
capabilities: [gpu]
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
# ========================================================
|
| 57 |
# Serve profile — LEGACY v1/v2 LMDeploy API server (not used by v3)
|
| 58 |
# ========================================================
|
|
|
|
| 53 |
count: all
|
| 54 |
capabilities: [gpu]
|
| 55 |
|
| 56 |
+
# ========================================================
|
| 57 |
+
# API profiles — OpenAI-compatible streaming speech API (apps/openai_speech.py)
|
| 58 |
+
# docker compose -f docker/docker-compose.yml --profile api-gpu up # RTX: 16 streams
|
| 59 |
+
# docker compose -f docker/docker-compose.yml --profile api-cpu up # no GPU: 1-2 streams
|
| 60 |
+
# -> POST http://localhost:8000/v1/audio/speech (docs/streaming.vi.md)
|
| 61 |
+
# ========================================================
|
| 62 |
+
api-gpu:
|
| 63 |
+
profiles: ["api-gpu"]
|
| 64 |
+
build:
|
| 65 |
+
context: ..
|
| 66 |
+
dockerfile: docker/Dockerfile.gpu
|
| 67 |
+
target: prod
|
| 68 |
+
container_name: vieneu-tts-api-gpu
|
| 69 |
+
command: ["python", "-m", "apps.openai_speech"]
|
| 70 |
+
ports:
|
| 71 |
+
- "${API_PORT:-8000}:8000"
|
| 72 |
+
environment:
|
| 73 |
+
- HF_HOME=${HF_HOME:-/home/app/.cache/huggingface}
|
| 74 |
+
- PYTHONUNBUFFERED=1
|
| 75 |
+
- PORT=8000
|
| 76 |
+
- VIENEU_MAX_STREAMS=${VIENEU_MAX_STREAMS:-16}
|
| 77 |
+
- VIENEU_QUEUE=${VIENEU_QUEUE:-16}
|
| 78 |
+
- VIENEU_QUEUE_TIMEOUT=${VIENEU_QUEUE_TIMEOUT:-10}
|
| 79 |
+
- VIENEU_API_KEY=${VIENEU_API_KEY:-}
|
| 80 |
+
- VIENEU_WATERMARK=${VIENEU_WATERMARK:-1}
|
| 81 |
+
env_file:
|
| 82 |
+
- path: .env
|
| 83 |
+
required: false
|
| 84 |
+
volumes:
|
| 85 |
+
- huggingface_cache:/home/app/.cache/huggingface
|
| 86 |
+
healthcheck:
|
| 87 |
+
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3).status == 200 else 1)"]
|
| 88 |
+
interval: 15s
|
| 89 |
+
timeout: 5s
|
| 90 |
+
start_period: 120s
|
| 91 |
+
retries: 3
|
| 92 |
+
deploy:
|
| 93 |
+
resources:
|
| 94 |
+
reservations:
|
| 95 |
+
devices:
|
| 96 |
+
- driver: nvidia
|
| 97 |
+
count: all
|
| 98 |
+
capabilities: [gpu]
|
| 99 |
+
restart: unless-stopped
|
| 100 |
+
|
| 101 |
+
api-cpu:
|
| 102 |
+
profiles: ["api-cpu"]
|
| 103 |
+
build:
|
| 104 |
+
context: ..
|
| 105 |
+
dockerfile: docker/Dockerfile.cpu
|
| 106 |
+
container_name: vieneu-tts-api-cpu
|
| 107 |
+
command: ["python", "-m", "apps.openai_speech"]
|
| 108 |
+
ports:
|
| 109 |
+
- "${API_PORT:-8000}:8000"
|
| 110 |
+
environment:
|
| 111 |
+
- HF_HOME=${HF_HOME:-/home/app/.cache/huggingface}
|
| 112 |
+
- PYTHONUNBUFFERED=1
|
| 113 |
+
- PORT=8000
|
| 114 |
+
- VIENEU_BACKEND=onnx
|
| 115 |
+
- VIENEU_PRECISION=${VIENEU_PRECISION:-fp32} # int8: nhanh ~2x, cần CPU có VNNI
|
| 116 |
+
- VIENEU_QUEUE=${VIENEU_QUEUE:-4}
|
| 117 |
+
- VIENEU_QUEUE_TIMEOUT=${VIENEU_QUEUE_TIMEOUT:-10}
|
| 118 |
+
- VIENEU_API_KEY=${VIENEU_API_KEY:-}
|
| 119 |
+
- VIENEU_WATERMARK=${VIENEU_WATERMARK:-1}
|
| 120 |
+
env_file:
|
| 121 |
+
- path: .env
|
| 122 |
+
required: false
|
| 123 |
+
volumes:
|
| 124 |
+
- huggingface_cache:/home/app/.cache/huggingface
|
| 125 |
+
healthcheck:
|
| 126 |
+
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3).status == 200 else 1)"]
|
| 127 |
+
interval: 15s
|
| 128 |
+
timeout: 5s
|
| 129 |
+
start_period: 180s
|
| 130 |
+
retries: 3
|
| 131 |
+
restart: unless-stopped
|
| 132 |
+
|
| 133 |
# ========================================================
|
| 134 |
# Serve profile — LEGACY v1/v2 LMDeploy API server (not used by v3)
|
| 135 |
# ========================================================
|
examples/openai_speech_client.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Client mẫu cho API streaming chuẩn OpenAI của VieNeu-TTS (apps/openai_speech.py).
|
| 3 |
+
|
| 4 |
+
uv run python -m apps.openai_speech # bật server (cổng 8000)
|
| 5 |
+
uv run python examples/openai_speech_client.py # 1 request, ghi out_stream.wav, in TTFA/RTF
|
| 6 |
+
uv run python examples/openai_speech_client.py --bench 8 # 8 client cùng lúc: TTFA/RTF từng luồng
|
| 7 |
+
uv run python examples/openai_speech_client.py --sse # nhận dạng Server-Sent Events
|
| 8 |
+
|
| 9 |
+
Chỉ cần `requests`; nếu có `openai` SDK thì `--sdk` dùng đúng client của OpenAI.
|
| 10 |
+
"""
|
| 11 |
+
import argparse
|
| 12 |
+
import base64
|
| 13 |
+
import json
|
| 14 |
+
import statistics
|
| 15 |
+
import threading
|
| 16 |
+
import time
|
| 17 |
+
import wave
|
| 18 |
+
|
| 19 |
+
import requests
|
| 20 |
+
|
| 21 |
+
SR = 48_000
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def check_server(base, api_key=None):
|
| 25 |
+
"""Fail fast with a readable message when the server is not up (or not ready)."""
|
| 26 |
+
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
|
| 27 |
+
try:
|
| 28 |
+
r = requests.get(f"{base}/health", headers=headers, timeout=5)
|
| 29 |
+
except requests.ConnectionError:
|
| 30 |
+
raise SystemExit(
|
| 31 |
+
f"Không kết nối được {base} — server chưa chạy?\n"
|
| 32 |
+
f" Bật ở cửa sổ khác: uv run python -m apps.openai_speech\n"
|
| 33 |
+
f" rồi đợi dòng '✅ ready ...' (cổng khác thì thêm --base http://127.0.0.1:<port>)."
|
| 34 |
+
)
|
| 35 |
+
if r.status_code == 401:
|
| 36 |
+
raise SystemExit("Server yêu cầu API key: thêm --api-key <VIENEU_API_KEY>")
|
| 37 |
+
r.raise_for_status()
|
| 38 |
+
h = r.json()
|
| 39 |
+
print(f"server: backend={h.get('backend')} max_streams={h.get('max_streams')} active={h.get('active')}")
|
| 40 |
+
return h
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def stream_pcm(base, text, voice=None, sample_rate=SR, api_key=None):
|
| 44 |
+
"""POST /v1/audio/speech (pcm) → (ttfa_s, total_s, pcm_bytes). RTF = total / audio."""
|
| 45 |
+
body = {"model": "vieneu-v3-turbo", "input": text, "voice": voice,
|
| 46 |
+
"response_format": "pcm", "sample_rate": sample_rate}
|
| 47 |
+
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
|
| 48 |
+
t0 = time.perf_counter()
|
| 49 |
+
first = None
|
| 50 |
+
buf = bytearray()
|
| 51 |
+
with requests.post(f"{base}/v1/audio/speech", json=body, headers=headers, stream=True, timeout=120) as r:
|
| 52 |
+
if r.status_code != 200:
|
| 53 |
+
raise RuntimeError(f"{r.status_code}: {r.text}")
|
| 54 |
+
for chunk in r.iter_content(chunk_size=None):
|
| 55 |
+
if not chunk:
|
| 56 |
+
continue
|
| 57 |
+
if first is None:
|
| 58 |
+
first = time.perf_counter() - t0
|
| 59 |
+
buf += chunk
|
| 60 |
+
return first, time.perf_counter() - t0, bytes(buf)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def stream_sse(base, text, voice=None, api_key=None):
|
| 64 |
+
body = {"model": "vieneu-v3-turbo", "input": text, "voice": voice,
|
| 65 |
+
"response_format": "pcm", "stream_format": "sse"}
|
| 66 |
+
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
|
| 67 |
+
t0 = time.perf_counter()
|
| 68 |
+
first = None
|
| 69 |
+
buf = bytearray()
|
| 70 |
+
with requests.post(f"{base}/v1/audio/speech", json=body, headers=headers, stream=True, timeout=120) as r:
|
| 71 |
+
for line in r.iter_lines():
|
| 72 |
+
if not line.startswith(b"data: "):
|
| 73 |
+
continue
|
| 74 |
+
ev = json.loads(line[6:])
|
| 75 |
+
if ev["type"] == "speech.audio.delta":
|
| 76 |
+
if first is None:
|
| 77 |
+
first = time.perf_counter() - t0
|
| 78 |
+
buf += base64.b64decode(ev["audio"])
|
| 79 |
+
elif ev["type"] == "speech.audio.done":
|
| 80 |
+
print("done:", ev.get("usage"))
|
| 81 |
+
return first, time.perf_counter() - t0, bytes(buf)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def stream_sdk(base, text, voice=None, api_key="x"):
|
| 85 |
+
from openai import OpenAI # pip install openai
|
| 86 |
+
client = OpenAI(base_url=f"{base}/v1", api_key=api_key or "x")
|
| 87 |
+
t0 = time.perf_counter()
|
| 88 |
+
first = None
|
| 89 |
+
buf = bytearray()
|
| 90 |
+
with client.audio.speech.with_streaming_response.create(
|
| 91 |
+
model="vieneu-v3-turbo", voice=voice or "Mai Anh", input=text, response_format="pcm",
|
| 92 |
+
) as r:
|
| 93 |
+
for chunk in r.iter_bytes(4096):
|
| 94 |
+
if first is None:
|
| 95 |
+
first = time.perf_counter() - t0
|
| 96 |
+
buf += chunk
|
| 97 |
+
return first, time.perf_counter() - t0, bytes(buf)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def save_wav(path, pcm, sample_rate=SR):
|
| 101 |
+
with wave.open(path, "wb") as w:
|
| 102 |
+
w.setnchannels(1)
|
| 103 |
+
w.setsampwidth(2)
|
| 104 |
+
w.setframerate(sample_rate)
|
| 105 |
+
w.writeframes(pcm)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def report(tag, first, total, pcm, sample_rate=SR):
|
| 109 |
+
audio_s = len(pcm) / 2 / sample_rate
|
| 110 |
+
print(f"{tag}: TTFA {first*1000:.0f} ms | tổng {total:.2f}s | audio {audio_s:.2f}s | RTF {total/audio_s:.2f}")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def main():
|
| 114 |
+
ap = argparse.ArgumentParser()
|
| 115 |
+
ap.add_argument("--base", default="http://127.0.0.1:8000")
|
| 116 |
+
ap.add_argument("--text", default="Xin chào, đây là giọng đọc VieNeu phát trực tiếp qua API chuẩn OpenAI.")
|
| 117 |
+
ap.add_argument("--voice", default=None, help="tên preset (GET /v1/voices); bỏ trống = giọng mặc định")
|
| 118 |
+
ap.add_argument("--api-key", default=None)
|
| 119 |
+
ap.add_argument("--sample-rate", type=int, default=SR, choices=[48000, 24000, 16000, 8000])
|
| 120 |
+
ap.add_argument("--bench", type=int, default=0, help="N client đồng thời")
|
| 121 |
+
ap.add_argument("--sse", action="store_true")
|
| 122 |
+
ap.add_argument("--sdk", action="store_true")
|
| 123 |
+
a = ap.parse_args()
|
| 124 |
+
check_server(a.base, a.api_key)
|
| 125 |
+
|
| 126 |
+
if a.bench:
|
| 127 |
+
res = [None] * a.bench
|
| 128 |
+
def one(i):
|
| 129 |
+
try:
|
| 130 |
+
res[i] = stream_pcm(a.base, a.text, a.voice, a.sample_rate, a.api_key)
|
| 131 |
+
except Exception as e: # noqa: BLE001 — một client lỗi không được làm hỏng cả bench
|
| 132 |
+
res[i] = e
|
| 133 |
+
ths = [threading.Thread(target=one, args=(i,)) for i in range(a.bench)]
|
| 134 |
+
t = time.perf_counter()
|
| 135 |
+
for th in ths:
|
| 136 |
+
th.start()
|
| 137 |
+
for th in ths:
|
| 138 |
+
th.join()
|
| 139 |
+
wall = time.perf_counter() - t
|
| 140 |
+
ok = [r for r in res if not isinstance(r, Exception)]
|
| 141 |
+
bad = [r for r in res if isinstance(r, Exception)]
|
| 142 |
+
for e in bad[:3]:
|
| 143 |
+
print(f" lỗi: {e}")
|
| 144 |
+
if not ok:
|
| 145 |
+
raise SystemExit(f"{len(bad)}/{a.bench} client lỗi, không có kết quả.")
|
| 146 |
+
ttfa = [r[0] for r in ok]
|
| 147 |
+
rtf = [r[1] / (len(r[2]) / 2 / a.sample_rate) for r in ok]
|
| 148 |
+
print(f"{a.bench} client ({len(ok)} ok, {len(bad)} lỗi/429): TTFA median {statistics.median(ttfa)*1000:.0f} ms, "
|
| 149 |
+
f"max {max(ttfa)*1000:.0f} ms | RTF max {max(rtf):.2f} (cần < 1) | {wall:.1f}s tổng")
|
| 150 |
+
return
|
| 151 |
+
if a.sse:
|
| 152 |
+
first, total, pcm = stream_sse(a.base, a.text, a.voice, a.api_key)
|
| 153 |
+
elif a.sdk:
|
| 154 |
+
first, total, pcm = stream_sdk(a.base, a.text, a.voice, a.api_key)
|
| 155 |
+
else:
|
| 156 |
+
first, total, pcm = stream_pcm(a.base, a.text, a.voice, a.sample_rate, a.api_key)
|
| 157 |
+
report("1 request", first, total, pcm, a.sample_rate)
|
| 158 |
+
save_wav("out_stream.wav", pcm, a.sample_rate)
|
| 159 |
+
print("→ out_stream.wav")
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if __name__ == "__main__":
|
| 163 |
+
main()
|