TTS-V8 / stream_client.py
cloudyu's picture
Release TTS-V8: Chinese call-center TTS model with online WAV demos and serving code
29439fe verified
Raw History Blame Contribute Delete
5.02 kB
#!/usr/bin/env python3
"""Streaming client / latency benchmark for stream_server.py.
Simulates an LLM emitting text at --cps characters per second (0 = all at once)
and measures first-audio latency from the first text message, real-time factor,
and playback stalls (buffer underruns) assuming playback starts at first audio.
python stream_client.py --voice bank_collection_female --text-file demos/text.txt --cps 15 --output out.wav
python stream_client.py --concurrency 4 --cps 15 ...
"""
import argparse
import asyncio
import json
import statistics
import time
from pathlib import Path
import numpy as np
import soundfile as sf
import websockets
DEFAULT_TEXT = '您好,很抱歉让您久等了。我已经为您查询到,您的订单编号是20261113004567,商品金额为128.50元,实际支付108.50元。请您打开APP查看处理进度。'
async def one(url, voice, text, cps, sample_rate, seed, output=None, chunk_chars=1, mode='icl', segment=None, speed=1.0):
async with websockets.connect(url, max_size=None) as ws:
await ws.send(json.dumps(dict(type='start', voice=voice, sample_rate=sample_rate, seed=seed, mode=mode, speed=speed, **({'segment': segment} if segment else {}))))
started = json.loads(await ws.recv())
if started.get('type') != 'started':
raise RuntimeError(started)
t0 = time.perf_counter()
arrivals, chunks, done = [], [], None
async def feed():
for i in range(0, len(text), chunk_chars):
await ws.send(json.dumps(dict(type='text', text=text[i:i + chunk_chars])))
if cps:
await asyncio.sleep(chunk_chars / cps)
await ws.send(json.dumps(dict(type='end')))
feeder = asyncio.create_task(feed())
async for message in ws:
if isinstance(message, bytes):
arrivals.append((time.perf_counter() - t0, len(message) // 2 / sample_rate))
chunks.append(np.frombuffer(message, '<i2'))
else:
msg = json.loads(message)
if msg['type'] == 'done':
done = msg['stats']
break
if msg['type'] == 'error':
raise RuntimeError(msg['message'])
await feeder
audio = np.concatenate(chunks) if chunks else np.zeros(0, np.int16)
if output:
sf.write(output, audio, sample_rate, subtype='PCM_16')
first = arrivals[0][0] if arrivals else None
received, stall = 0.0, 0.0
for t, dur in arrivals:
playback = (t - first) - stall
if received < playback:
stall += playback - received
received += dur
total = arrivals[-1][0] if arrivals else None
return dict(first_audio_ms=None if first is None else round(first * 1000, 1), total_s=total,
audio_s=len(audio) / sample_rate, stall_s=round(stall, 3), server=done)
async def main_async(args):
text = Path(args.text_file).read_text().strip() if args.text_file else args.text
jobs = [one(args.url, args.voice, text, args.cps, args.sample_rate, args.seed + i,
(args.output if args.concurrency == 1 else f'{Path(args.output).stem}_{i}.wav') if args.output else None,
mode=args.mode, segment=args.segment, speed=args.speed)
for i in range(args.concurrency)]
results = await asyncio.gather(*jobs)
for r in results:
print(json.dumps(r, ensure_ascii=False))
firsts = [r['first_audio_ms'] for r in results]
summary = dict(mode=args.mode, segment=args.segment or 'server default', concurrency=args.concurrency, cps=args.cps, first_audio_ms_median=statistics.median(firsts),
first_audio_ms_max=max(firsts), stall_s_max=max(r['stall_s'] for r in results),
server_rtf_median=statistics.median(r['server']['rtf'] for r in results))
print('SUMMARY', json.dumps(summary, ensure_ascii=False))
return summary
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--url', default='ws://127.0.0.1:8765/v1/tts/stream')
ap.add_argument('--voice', default='bank_collection_female')
ap.add_argument('--text', default=DEFAULT_TEXT)
ap.add_argument('--text-file')
ap.add_argument('--cps', type=float, default=15, help='simulated LLM characters/second; 0 = whole text at once')
ap.add_argument('--sample-rate', type=int, default=24000)
ap.add_argument('--concurrency', type=int, default=1)
ap.add_argument('--seed', type=int, default=0)
ap.add_argument('--output')
ap.add_argument('--mode', choices=['icl', 'xvec'], default='icl')
ap.add_argument('--speed', type=float, default=1.0, help='speaking-rate factor (pitch preserved), 0.5-2.0')
ap.add_argument('--segment', choices=['sentence', 'token'],
help='server default: sentence for icl, token for xvec')
args = ap.parse_args()
asyncio.run(main_async(args))
if __name__ == '__main__':
main()