Files

136 lines
6.4 KiB
Python

import asyncio
import io
import json
import struct
import sys
import time
import wave
from pathlib import Path
import httpx
import numpy as np
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
TEXT = '今天天气不错,我们去散步吧。'
def wav_header(data):
if len(data) < 12 or data[:4] != b'RIFF' or data[8:12] != b'WAVE':
return None
pos = 12
fmt = None
while pos + 8 <= len(data):
tag = data[pos:pos + 4]
size = struct.unpack_from('<I', data, pos + 4)[0]
if tag == b'data':
return (pos + 8, fmt) if fmt else None
if pos + 8 + size > len(data):
return None
if tag == b'fmt ':
fmt = struct.unpack_from('<HHIIHH', data, pos + 8)
pos += 8 + size + (size % 2)
return None
async def tts(client, index, cancel=False):
start = time.perf_counter()
body = bytearray()
first = None
audible = None
header = None
times = []
async with client.stream('POST', 'http://192.168.31.61:5002/v1/audio/speech', json={'model': 'openbmb/VoxCPM2', 'input': TEXT, 'stream': True}) as response:
response.raise_for_status()
async for block in response.aiter_bytes():
elapsed = time.perf_counter() - start
times.append(elapsed)
body.extend(block)
header = header or wav_header(body)
if header:
offset, fmt = header
usable = (len(body) - offset) // 2 * 2
if usable and first is None:
first = elapsed
if usable and audible is None:
pcm = np.frombuffer(body[offset:offset + usable], dtype='<i2')
if np.any(np.abs(pcm.astype(np.int32)) > 327):
audible = elapsed
if cancel and first is not None:
break
result = {'kind': 'tts', 'index': index, 'first_pcm_ms': round(first * 1000, 2) if first else None, 'first_above_minus40dbfs_ms': round(audible * 1000, 2) if audible else None, 'total_ms': round((time.perf_counter() - start) * 1000, 2), 'cancel_after_first_pcm': cancel, 'network_blocks': len(times)}
if header:
offset, fmt = header
result.update({'format_tag': fmt[0], 'channels': fmt[1], 'sample_rate': fmt[2], 'bits': fmt[5], 'audio_seconds': (len(body) - offset) / fmt[3]})
if not cancel:
with wave.open(str(ROOT / 'tmp/public_tts.wav'), 'wb') as wav:
wav.setnchannels(fmt[1]); wav.setsampwidth(fmt[5] // 8); wav.setframerate(fmt[2]); wav.writeframes(body[offset:])
x = np.frombuffer(body[offset:], dtype='<i2')
if fmt[2] != 48000 or fmt[1] != 1 or fmt[5] != 16:
raise ValueError('unexpected TTS format')
trim = len(x) // 3 * 3
reduced = np.rint(x[:trim].reshape(-1, 3).astype(np.float64).mean(axis=1)).astype('<i2')
with wave.open(str(ROOT / 'tmp/public_tts_16k.wav'), 'wb') as wav:
wav.setnchannels(1); wav.setsampwidth(2); wav.setframerate(16000); wav.writeframes(reduced.tobytes())
return result
async def qwen(client, index):
start = time.perf_counter()
first = None
text = ''
reasoning = ''
first_sentence = None
finish = None
usage = None
async with client.stream('POST', 'http://127.0.0.1:8888/v1/chat/completions', json={'model': 'qwen3.8-27b', 'messages': [{'role': 'user', 'content': '请用一句不超过十五个汉字回答:为什么要喝水?不要思考过程。'}], 'stream': True, 'max_tokens': 64, 'temperature': 0, 'chat_template_kwargs': {'enable_thinking': False}, 'stream_options': {'include_usage': True}}) as response:
response.raise_for_status()
async for line in response.aiter_lines():
if not line.startswith('data: ') or line == 'data: [DONE]':
continue
data = json.loads(line[6:])
usage = data.get('usage') or usage
for choice in data.get('choices', []):
delta = choice.get('delta', {})
reasoning += delta.get('reasoning_content') or ''
content = delta.get('content') or ''
if content:
if first is None: first = time.perf_counter() - start
text += content
if first_sentence is None and any(c in text for c in '。!?!?'):
first_sentence = time.perf_counter() - start
finish = choice.get('finish_reason') or finish
return {'kind': 'qwen', 'index': index, 'first_body_ms': round(first * 1000, 2) if first else None, 'first_sentence_ms': round(first_sentence * 1000, 2) if first_sentence else None, 'total_ms': round((time.perf_counter() - start) * 1000, 2), 'body': text, 'reasoning_chars': len(reasoning), 'finish_reason': finish, 'usage': usage, 'enable_thinking': False, 'max_tokens': 64}
async def stt(client, index):
data = (ROOT / 'tmp/public_tts_16k.wav').read_bytes()
start = time.perf_counter()
response = await client.post('http://192.168.31.61:5001/v1/audio/transcriptions', files={'file': ('public.wav', data, 'audio/wav')})
response.raise_for_status()
with wave.open(io.BytesIO(data)) as w: duration = w.getnframes() / w.getframerate()
total = time.perf_counter() - start
return {'kind': 'stt', 'index': index, 'total_ms': round(total * 1000, 2), 'audio_seconds': duration, 'rtf': round(total / duration, 4), 'text': response.json().get('text')}
async def main():
(ROOT / 'tmp').mkdir(exist_ok=True)
results = []
async with httpx.AsyncClient(timeout=30, trust_env=False) as client:
for kind, fn, count in [('tts', tts, 3), ('qwen', qwen, 3), ('stt', stt, 3)]:
for i in range(1, count + 1):
if kind == 'stt' and not (ROOT / 'tmp/public_tts_16k.wav').exists(): break
try:
async with asyncio.timeout(30):
result = await fn(client, i, cancel=i == 3) if kind == 'tts' else await fn(client, i)
except Exception as exc:
result = {'kind': kind, 'index': i, 'error_type': type(exc).__name__}
results.append(result)
print(json.dumps(result, ensure_ascii=False), flush=True)
(ROOT / 'tmp/measurements.json').write_text(json.dumps(results, ensure_ascii=False, indent=2) + '\n')
await asyncio.sleep(0.2)
if __name__ == '__main__':
asyncio.run(main())