feat(voice_worker): M1 multi-speaker streaming STT and sentence TTS over a local WebSocket
- One shared faster-whisper model for every speaker, batched; finals go before partials and partial batches are capped at two so a final never waits behind a ten-speaker pass. - Per-speaker 48k stereo to 16k mono conversion, streaming Silero VAD, utterance ends on VAD silence, Discord speaking_end, missing audio, or the 28 s Whisper window. - MeloTTS in its own venv through a child process; sentences stream out one chunk each, with incremental text, cancel and failure reporting. - Loopback-only server with a token from the environment; logs carry no transcript text. - Spec in src/voice_worker/voice_worker.spec.md; unit tests with fake engines and an opt-in real-GPU test that streams ten speakers at once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
122
tests/test_voice_worker_audio.py
Normal file
122
tests/test_voice_worker_audio.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""Voice worker: binary frames, input conversion to 16 kHz mono, clip normalisation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from voice_worker.audio import InputConverter, peak_normalise
|
||||
from voice_worker.protocol import (KIND_AUDIO, KIND_TTS, ProtocolError, decode_audio_frame, encode_audio_frame,
|
||||
encode_tts_frame, decode_tts_frame)
|
||||
|
||||
|
||||
def _pcm16(x: np.ndarray) -> bytes:
|
||||
return (np.clip(x, -1, 1) * 32767).astype("<i2").tobytes()
|
||||
|
||||
|
||||
def _dominant_hz(x: np.ndarray, rate: int) -> float:
|
||||
spec = np.abs(np.fft.rfft(x * np.hanning(len(x))))
|
||||
return float(np.fft.rfftfreq(len(x), 1 / rate)[int(np.argmax(spec))])
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_audio_frame_round_trip_keeps_speaker_and_pcm():
|
||||
pcm = _pcm16(np.linspace(-0.5, 0.5, 960))
|
||||
frame = encode_audio_frame("123456789012345678", pcm)
|
||||
assert frame[0] == KIND_AUDIO
|
||||
speaker, payload = decode_audio_frame(frame)
|
||||
assert speaker == "123456789012345678"
|
||||
assert payload == pcm
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_tts_frame_round_trip_keeps_id_and_sequence():
|
||||
pcm = b"\x01\x00\x02\x00"
|
||||
frame = encode_tts_frame("reply-7", 3, pcm)
|
||||
assert frame[0] == KIND_TTS
|
||||
assert decode_tts_frame(frame) == ("reply-7", 3, pcm)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("frame", [b"", b"\x01", b"\x09\x01a\x00\x00", b"\x01\x05ab", b"\x01\x01a\x00",
|
||||
b"\x01\x02\xff\xfe\x00\x00"])
|
||||
def test_malformed_audio_frames_are_rejected(frame):
|
||||
with pytest.raises(ProtocolError):
|
||||
decode_audio_frame(frame)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_48k_stereo_becomes_16k_mono_and_keeps_the_tone():
|
||||
rate = 48000
|
||||
t = np.arange(rate) / rate
|
||||
tone = 0.5 * np.sin(2 * np.pi * 1000 * t)
|
||||
stereo = np.stack([tone, tone], axis=1).reshape(-1)
|
||||
out = InputConverter(rate, 2).push(_pcm16(stereo))
|
||||
assert out.dtype == np.float32
|
||||
assert abs(len(out) - rate // 3) <= 1
|
||||
assert abs(_dominant_hz(out, 16000) - 1000) < 5
|
||||
assert 0.4 < np.max(np.abs(out[500:])) < 0.6
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_tones_above_the_new_nyquist_are_filtered_out():
|
||||
rate = 48000
|
||||
t = np.arange(rate) / rate
|
||||
high = 0.5 * np.sin(2 * np.pi * 11000 * t)
|
||||
out = InputConverter(rate, 1).push(_pcm16(high))
|
||||
# At least 30 dB down instead of folding back to 5 kHz.
|
||||
assert np.sqrt(np.mean(out[500:] ** 2)) < 0.5 / np.sqrt(2) * 10 ** (-30 / 20)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_streaming_in_20ms_frames_matches_one_shot_conversion():
|
||||
rng = np.random.default_rng(1)
|
||||
sig = rng.uniform(-0.5, 0.5, 48000 * 2 // 2 * 2)
|
||||
one = InputConverter(48000, 2).push(_pcm16(sig))
|
||||
conv = InputConverter(48000, 2)
|
||||
raw = _pcm16(sig)
|
||||
step = 960 * 2 * 2 # 20 ms of 48 kHz stereo PCM16
|
||||
parts = [conv.push(raw[i:i + step]) for i in range(0, len(raw), step)]
|
||||
assert np.allclose(np.concatenate(parts), one, atol=1e-6)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_16k_mono_passes_through():
|
||||
sig = np.linspace(-0.25, 0.25, 1600)
|
||||
out = InputConverter(16000, 1).push(_pcm16(sig))
|
||||
assert np.allclose(out, sig, atol=1e-4)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_unsupported_input_formats_are_refused():
|
||||
with pytest.raises(ValueError):
|
||||
InputConverter(44100, 2)
|
||||
with pytest.raises(ValueError):
|
||||
InputConverter(48000, 6)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_odd_byte_counts_are_carried_to_the_next_frame():
|
||||
sig = _pcm16(np.full(10, 0.5))
|
||||
conv = InputConverter(16000, 1)
|
||||
a = conv.push(sig[:5])
|
||||
b = conv.push(sig[5:])
|
||||
assert len(a) + len(b) == 10
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_quiet_clip_is_raised_to_the_target_peak():
|
||||
x = np.full(100, 0.2, dtype=np.float32)
|
||||
assert np.isclose(np.max(np.abs(peak_normalise(x))), 0.9)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_near_silence_is_not_boosted_past_the_gain_cap():
|
||||
x = np.full(100, 0.001, dtype=np.float32)
|
||||
assert np.isclose(np.max(np.abs(peak_normalise(x))), 0.01)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_loud_clip_is_brought_down_to_the_target_peak():
|
||||
x = np.array([0.0, 1.0, -0.5], dtype=np.float32)
|
||||
assert np.isclose(np.max(np.abs(peak_normalise(x))), 0.9)
|
||||
209
tests/test_voice_worker_real.py
Normal file
209
tests/test_voice_worker_real.py
Normal file
@@ -0,0 +1,209 @@
|
||||
"""Voice worker with the real models: ten recorded clips streamed at once, and a TTS round trip.
|
||||
|
||||
Opt-in because it needs a CUDA GPU and the downloaded models:
|
||||
|
||||
JARVIS_VOICE_REAL_TESTS=1 [JARVIS_MELO_PYTHON=<MeloTTS venv python>] pytest tests/test_voice_worker_real.py -s
|
||||
|
||||
On Linux, put the pip CUDA libraries on LD_LIBRARY_PATH (nvidia/cublas/lib, nvidia/cudnn/lib).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.integration,
|
||||
pytest.mark.skipif(os.environ.get("JARVIS_VOICE_REAL_TESTS") != "1",
|
||||
reason="set JARVIS_VOICE_REAL_TESTS=1 to run on the GPU")]
|
||||
|
||||
SAMPLES = Path(__file__).resolve().parent.parent / "scripts" / "m0" / "assets" / "ko_samples"
|
||||
TOKEN = "real-test-token"
|
||||
FRAME_MS = 20
|
||||
|
||||
|
||||
def cer(ref: str, hyp: str) -> float:
|
||||
a, b = (re.sub(r"[\W_]+", "", s) for s in (ref, hyp))
|
||||
prev = list(range(len(b) + 1))
|
||||
for i, ca in enumerate(a, 1):
|
||||
cur = [i]
|
||||
for j, cb in enumerate(b, 1):
|
||||
cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
|
||||
prev = cur
|
||||
return prev[-1] / max(1, len(a))
|
||||
|
||||
|
||||
def load(name: str) -> np.ndarray:
|
||||
with wave.open(str(SAMPLES / name), "rb") as w:
|
||||
assert w.getframerate() == 16000 and w.getnchannels() == 1
|
||||
return np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(np.float32) / 32768.0
|
||||
|
||||
|
||||
def to_48k_stereo(x16: np.ndarray) -> np.ndarray:
|
||||
t48 = np.arange(len(x16) * 3) / 3
|
||||
x48 = np.interp(t48, np.arange(len(x16)), x16)
|
||||
return np.repeat(x48, 2)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def engines():
|
||||
from voice_worker.stt_whisper import WhisperTranscriber
|
||||
from voice_worker.vad import SileroVad
|
||||
stt = WhisperTranscriber()
|
||||
stt.warm_up()
|
||||
tts = None
|
||||
if os.environ.get("JARVIS_MELO_PYTHON"):
|
||||
from voice_worker.tts_melo import MeloEngine
|
||||
tts = MeloEngine(os.environ["JARVIS_MELO_PYTHON"])
|
||||
yield stt, SileroVad(), tts
|
||||
if tts:
|
||||
tts.close()
|
||||
|
||||
|
||||
async def with_worker(engines, body):
|
||||
from websockets.asyncio.client import connect
|
||||
from voice_worker.server import VoiceWorker
|
||||
stt, vad, tts = engines
|
||||
worker = VoiceWorker(TOKEN, stt, vad.stream, tts)
|
||||
server = await worker.serve("127.0.0.1", 0)
|
||||
url = f"ws://127.0.0.1:{server.sockets[0].getsockname()[1]}"
|
||||
try:
|
||||
async with connect(url, max_size=2 ** 24) as ws:
|
||||
await ws.send(json.dumps({"type": "hello", "token": TOKEN, "stt": {"hotwords": ["자비스"]}}))
|
||||
assert json.loads(await ws.recv())["type"] == "hello_ok"
|
||||
return await asyncio.wait_for(body(ws), 120)
|
||||
finally:
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await worker.stop()
|
||||
|
||||
|
||||
def test_ten_speakers_at_once(engines):
|
||||
"""Ten speakers talk over each other in real time (48 kHz stereo, 20 ms frames, staggered starts).
|
||||
Half end with Discord's speaking_end, half keep sending silence so only the VAD can end them."""
|
||||
from voice_worker.protocol import encode_audio_frame
|
||||
|
||||
refs = json.loads((SAMPLES / "refs.json").read_text(encoding="utf-8"))["samples"]
|
||||
files = [refs[i % len(refs)] for i in range(10)]
|
||||
speakers = [f"spk{i}" for i in range(10)]
|
||||
frame = 48000 * FRAME_MS // 1000 * 2 # stereo samples per frame
|
||||
|
||||
def track(i: int) -> list[bytes]:
|
||||
lead = np.zeros(int(0.15 * i * 16000), dtype=np.float32)
|
||||
tail = np.zeros(int(0.6 * 16000), dtype=np.float32) if i % 2 else np.zeros(0, dtype=np.float32)
|
||||
clip = load(files[i]["file"])
|
||||
if i % 2 == 0: # these end with speaking_end: Discord stops sending right after the last word
|
||||
loud = np.nonzero(np.abs(clip) > 0.02)[0]
|
||||
clip = clip[: loud[-1] + 800]
|
||||
x = to_48k_stereo(np.concatenate([lead, clip, tail]))
|
||||
pcm = (np.clip(x, -1, 1) * 32767).astype("<i2")
|
||||
return [pcm[k:k + frame].tobytes() for k in range(0, len(pcm), frame)]
|
||||
|
||||
tracks = [track(i) for i in range(10)]
|
||||
|
||||
async def body(ws):
|
||||
finals: dict[str, list[dict]] = {s: [] for s in speakers}
|
||||
partials = 0
|
||||
finished = asyncio.Event()
|
||||
|
||||
async def reader():
|
||||
nonlocal partials
|
||||
async for raw in ws:
|
||||
msg = json.loads(raw)
|
||||
if msg["type"] == "speech_start":
|
||||
open_utts[msg["speaker"]] = msg["utt"]
|
||||
elif msg["type"] == "partial":
|
||||
partials += 1
|
||||
elif msg["type"] == "final":
|
||||
finals[msg["speaker"]].append(msg)
|
||||
if sent_all.is_set() and all(finals.values()) and closed_all():
|
||||
finished.set()
|
||||
|
||||
open_utts: dict[str, int] = {}
|
||||
|
||||
def closed_all() -> bool:
|
||||
return all(len(finals[s]) >= open_utts.get(s, 0) for s in speakers)
|
||||
|
||||
sent_all = asyncio.Event()
|
||||
rd = asyncio.create_task(reader())
|
||||
t0 = time.monotonic()
|
||||
for k in range(max(len(t) for t in tracks)):
|
||||
for i, s in enumerate(speakers):
|
||||
if k < len(tracks[i]):
|
||||
await ws.send(encode_audio_frame(s, tracks[i][k]))
|
||||
elif k == len(tracks[i]) and i % 2 == 0:
|
||||
await ws.send(json.dumps({"type": "speaking_end", "speaker": s}))
|
||||
await asyncio.sleep(max(0.0, t0 + (k + 1) * FRAME_MS / 1000 - time.monotonic()))
|
||||
sent_all.set()
|
||||
try:
|
||||
await asyncio.wait_for(finished.wait(), 20)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
rd.cancel()
|
||||
return finals, partials
|
||||
|
||||
finals, partials = asyncio.run(with_worker(engines, body))
|
||||
rows = []
|
||||
for i, s in enumerate(speakers):
|
||||
text = " ".join(m["text"] for m in finals[s]).strip()
|
||||
rows.append((s, files[i]["file"], len(finals[s]), cer(files[i]["text"], text),
|
||||
[m["end_reason"] for m in finals[s]], [m["wait_ms"] for m in finals[s]], text))
|
||||
for r in rows:
|
||||
print(*r)
|
||||
waits = [w for r in rows for w in r[5]]
|
||||
print(f"partials={partials} wait_ms median={np.median(waits):.0f} max={max(waits)}")
|
||||
assert all(r[2] >= 1 for r in rows), "every speaker gets a final"
|
||||
assert np.mean([r[3] for r in rows]) <= 0.15
|
||||
assert max(r[3] for r in rows) <= 0.35
|
||||
assert {"speaking_end", "silence"} <= {reason for r in rows for reason in r[4]}
|
||||
assert partials > 0
|
||||
|
||||
|
||||
def test_tts_reply_comes_back_as_the_same_words(engines):
|
||||
"""Speech the worker synthesises, fed back in as a speaker, is transcribed to the same text."""
|
||||
if engines[2] is None:
|
||||
pytest.skip("set JARVIS_MELO_PYTHON to the MeloTTS venv python")
|
||||
from voice_worker.protocol import decode_tts_frame, encode_audio_frame
|
||||
text = "오늘 서울은 맑고 기온은 이십삼 도예요. 우산은 필요 없어요."
|
||||
|
||||
async def body(ws):
|
||||
await ws.send(json.dumps({"type": "config", "partials": False}))
|
||||
await ws.send(json.dumps({"type": "tts", "id": "t1", "text": text}))
|
||||
chunks = []
|
||||
t0 = time.monotonic()
|
||||
first = None
|
||||
while True:
|
||||
raw = await ws.recv()
|
||||
if isinstance(raw, bytes):
|
||||
chunks.append(decode_tts_frame(raw))
|
||||
first = first or time.monotonic() - t0
|
||||
elif json.loads(raw)["type"] == "tts_done":
|
||||
break
|
||||
pcm = b"".join(c[2] for c in chunks)
|
||||
step = 48000 * FRAME_MS // 1000 * 2 * 2
|
||||
for k in range(0, len(pcm), step):
|
||||
await ws.send(encode_audio_frame("echo", pcm[k:k + step]))
|
||||
await ws.send(json.dumps({"type": "speaking_end", "speaker": "echo"}))
|
||||
got = []
|
||||
# The pause between the sentences may split them, and the clip's own trailing silence may end
|
||||
# the last one before speaking_end does, so collect finals until the worker goes quiet.
|
||||
while True:
|
||||
try:
|
||||
msg = json.loads(await asyncio.wait_for(ws.recv(), 3))
|
||||
except asyncio.TimeoutError:
|
||||
break
|
||||
if msg["type"] == "final":
|
||||
got.append(msg["text"])
|
||||
return chunks, first, " ".join(got)
|
||||
|
||||
chunks, first, heard = asyncio.run(with_worker(engines, body))
|
||||
print(f"tts chunks={len(chunks)} first_chunk_s={first:.2f} heard={heard}")
|
||||
assert [c[1] for c in chunks] == [0, 1]
|
||||
assert cer(text, heard) <= 0.2
|
||||
253
tests/test_voice_worker_scheduler.py
Normal file
253
tests/test_voice_worker_scheduler.py
Normal file
@@ -0,0 +1,253 @@
|
||||
"""Voice worker: the shared-model STT scheduler (batching, finals first, partial coalescing)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from voice_worker.scheduler import DecodeOptions, SttScheduler
|
||||
|
||||
FINAL = DecodeOptions(beam=2, language="ko", hotwords=())
|
||||
PARTIAL = DecodeOptions(beam=1, language="ko", hotwords=())
|
||||
|
||||
|
||||
class FakeTranscriber:
|
||||
"""Names each clip by its length; the first call can be held to build up a queue."""
|
||||
|
||||
def __init__(self, hold_first: bool = False, fail_on_beam: int | None = None):
|
||||
self.calls: list[tuple[DecodeOptions, list[int]]] = []
|
||||
self.gate = threading.Event()
|
||||
self.entered = threading.Event()
|
||||
if not hold_first:
|
||||
self.gate.set()
|
||||
self.fail_on_beam = fail_on_beam
|
||||
|
||||
def transcribe(self, clips, opts):
|
||||
self.entered.set()
|
||||
self.gate.wait(5)
|
||||
self.calls.append((opts, [len(c) for c in clips]))
|
||||
if opts.beam == self.fail_on_beam:
|
||||
raise RuntimeError("boom")
|
||||
return [f"n{len(c)}" for c in clips]
|
||||
|
||||
|
||||
def clip(n: int) -> np.ndarray:
|
||||
return np.zeros(n, dtype=np.float32)
|
||||
|
||||
|
||||
async def _run(body):
|
||||
return await asyncio.wait_for(body(), 10)
|
||||
|
||||
|
||||
def run(body):
|
||||
return asyncio.run(_run(body))
|
||||
|
||||
|
||||
async def _wait_entered(t: FakeTranscriber):
|
||||
while not t.entered.is_set():
|
||||
await asyncio.sleep(0.005)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_finals_queued_while_busy_go_in_one_batch_before_partials():
|
||||
t = FakeTranscriber(hold_first=True)
|
||||
|
||||
async def body():
|
||||
s = SttScheduler(t, max_partial_batch=4)
|
||||
s.start()
|
||||
got = []
|
||||
done = asyncio.Event()
|
||||
|
||||
def cb(name):
|
||||
def _cb(res):
|
||||
got.append((name, res.text))
|
||||
if len(got) == 5:
|
||||
done.set()
|
||||
return _cb
|
||||
|
||||
s.submit_partial(("a", "1"), clip(10), PARTIAL, cb("p-first"))
|
||||
await _wait_entered(t)
|
||||
s.submit_partial(("a", "2"), clip(20), PARTIAL, cb("p2"))
|
||||
s.submit_final(("a", "3"), clip(30), FINAL, cb("f3"))
|
||||
s.submit_final(("a", "4"), clip(40), FINAL, cb("f4"))
|
||||
s.submit_partial(("a", "5"), clip(50), PARTIAL, cb("p5"))
|
||||
t.gate.set()
|
||||
await done.wait()
|
||||
await s.stop()
|
||||
return got
|
||||
|
||||
got = run(body)
|
||||
assert [c[1] for c in t.calls] == [[10], [30, 40], [20, 50]]
|
||||
assert [c[0].beam for c in t.calls] == [1, 2, 1]
|
||||
assert got == [("p-first", "n10"), ("f3", "n30"), ("f4", "n40"), ("p2", "n20"), ("p5", "n50")]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_newer_partial_replaces_the_waiting_one_for_the_same_speaker():
|
||||
t = FakeTranscriber(hold_first=True)
|
||||
|
||||
async def body():
|
||||
s = SttScheduler(t)
|
||||
s.start()
|
||||
got = []
|
||||
done = asyncio.Event()
|
||||
s.submit_final(("a", "x"), clip(5), FINAL, lambda r: None)
|
||||
await _wait_entered(t)
|
||||
s.submit_partial(("a", "1"), clip(10), PARTIAL, lambda r: got.append(r.text))
|
||||
s.submit_partial(("a", "1"), clip(20), PARTIAL, lambda r: (got.append(r.text), done.set()))
|
||||
t.gate.set()
|
||||
await done.wait()
|
||||
await asyncio.sleep(0.05)
|
||||
await s.stop()
|
||||
return got
|
||||
|
||||
assert run(body) == ["n20"]
|
||||
assert [c[1] for c in t.calls] == [[5], [20]]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_dropped_partials_are_never_transcribed():
|
||||
t = FakeTranscriber(hold_first=True)
|
||||
|
||||
async def body():
|
||||
s = SttScheduler(t)
|
||||
s.start()
|
||||
done = asyncio.Event()
|
||||
got = []
|
||||
s.submit_final(("a", "x"), clip(5), FINAL, lambda r: None)
|
||||
await _wait_entered(t)
|
||||
s.submit_partial(("a", "1"), clip(10), PARTIAL, lambda r: got.append(r.text))
|
||||
s.submit_partial(("b", "1"), clip(20), PARTIAL, lambda r: (got.append(r.text), done.set()))
|
||||
s.drop_partials(lambda key: key[0] == "a")
|
||||
t.gate.set()
|
||||
await done.wait()
|
||||
await s.stop()
|
||||
return got
|
||||
|
||||
assert run(body) == ["n20"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_different_decode_settings_are_not_mixed_in_one_batch():
|
||||
t = FakeTranscriber(hold_first=True)
|
||||
other = DecodeOptions(beam=2, language=None, hotwords=("자비스",))
|
||||
|
||||
async def body():
|
||||
s = SttScheduler(t)
|
||||
s.start()
|
||||
n = []
|
||||
done = asyncio.Event()
|
||||
|
||||
def cb(r):
|
||||
n.append(r)
|
||||
if len(n) == 4:
|
||||
done.set()
|
||||
|
||||
s.submit_final(("a", "x"), clip(1), FINAL, cb)
|
||||
await _wait_entered(t)
|
||||
s.submit_final(("a", "1"), clip(10), FINAL, cb)
|
||||
s.submit_final(("b", "1"), clip(20), other, cb)
|
||||
s.submit_final(("a", "2"), clip(30), FINAL, cb)
|
||||
t.gate.set()
|
||||
await done.wait()
|
||||
await s.stop()
|
||||
|
||||
run(body)
|
||||
assert sorted(c[1] for c in t.calls[1:]) == [[10, 30], [20]]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_batches_are_capped():
|
||||
t = FakeTranscriber(hold_first=True)
|
||||
|
||||
async def body():
|
||||
s = SttScheduler(t, max_batch=3)
|
||||
s.start()
|
||||
n = []
|
||||
done = asyncio.Event()
|
||||
|
||||
def cb(r):
|
||||
n.append(r)
|
||||
if len(n) == 8:
|
||||
done.set()
|
||||
|
||||
s.submit_final(("a", "x"), clip(1), FINAL, cb)
|
||||
await _wait_entered(t)
|
||||
for i in range(7):
|
||||
s.submit_final(("a", str(i)), clip(10 + i), FINAL, cb)
|
||||
t.gate.set()
|
||||
await done.wait()
|
||||
await s.stop()
|
||||
|
||||
run(body)
|
||||
assert [len(c[1]) for c in t.calls] == [1, 3, 3, 1]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_failing_batch_reports_the_error_and_the_scheduler_keeps_going():
|
||||
t = FakeTranscriber(fail_on_beam=2)
|
||||
|
||||
async def body():
|
||||
s = SttScheduler(t)
|
||||
s.start()
|
||||
out = []
|
||||
done = asyncio.Event()
|
||||
s.submit_final(("a", "1"), clip(10), FINAL, out.append)
|
||||
s.submit_partial(("a", "2"), clip(20), PARTIAL, lambda r: (out.append(r), done.set()))
|
||||
await done.wait()
|
||||
await s.stop()
|
||||
return out
|
||||
|
||||
out = run(body)
|
||||
assert out[0].text == "" and out[0].error
|
||||
assert out[1].text == "n20" and out[1].error is None
|
||||
assert out[0].stt_ms >= 0
|
||||
|
||||
|
||||
|
||||
class StepTranscriber:
|
||||
"""Every call waits for one ``step()``, so the test decides when each batch finishes."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls: list[list[int]] = []
|
||||
self._steps = threading.Semaphore(0)
|
||||
|
||||
def step(self):
|
||||
self._steps.release()
|
||||
|
||||
def transcribe(self, clips, opts):
|
||||
self.calls.append([len(c) for c in clips])
|
||||
self._steps.acquire(timeout=5)
|
||||
return ["" for _ in clips]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_partial_batches_are_kept_small_so_finals_can_cut_in():
|
||||
t = StepTranscriber()
|
||||
|
||||
async def until(n):
|
||||
while len(t.calls) < n:
|
||||
await asyncio.sleep(0.005)
|
||||
|
||||
async def body():
|
||||
s = SttScheduler(t, max_partial_batch=2)
|
||||
s.start()
|
||||
for i in range(5):
|
||||
s.submit_partial(("a", str(i)), clip(10 + i), PARTIAL, lambda r: None)
|
||||
await until(1) # first partial batch is running
|
||||
s.submit_final(("a", "late"), clip(99), FINAL, lambda r: None)
|
||||
t.step()
|
||||
await until(2)
|
||||
t.step()
|
||||
await until(3)
|
||||
t.step()
|
||||
await until(4)
|
||||
t.step()
|
||||
await asyncio.sleep(0.02)
|
||||
await s.stop()
|
||||
|
||||
run(body)
|
||||
assert t.calls == [[10, 11], [99], [12, 13], [14]]
|
||||
191
tests/test_voice_worker_segmenter.py
Normal file
191
tests/test_voice_worker_segmenter.py
Normal file
@@ -0,0 +1,191 @@
|
||||
"""Voice worker: per-speaker utterance segmentation (start, partial cadence, the four end reasons).
|
||||
|
||||
The fake VAD reads the speech probability straight off the audio: a window of constant amplitude
|
||||
0.9 is "speech at 0.9". That keeps the tests about the segmentation rules, not about Silero.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from voice_worker.segmenter import Final, Partial, Segmenter, SpeechStart
|
||||
from voice_worker.settings import SttSettings
|
||||
|
||||
SR = 16000
|
||||
FRAME_MS = 20
|
||||
|
||||
|
||||
class AmplitudeVad:
|
||||
def prob(self, window: np.ndarray) -> float:
|
||||
return float(np.max(np.abs(window)))
|
||||
|
||||
|
||||
class Feeder:
|
||||
def __init__(self, settings: SttSettings | None = None):
|
||||
self.settings = settings or SttSettings()
|
||||
self.seg = Segmenter(AmplitudeVad(), self.settings)
|
||||
self.now = 100.0
|
||||
self.events: list = []
|
||||
|
||||
def feed(self, level: float, ms: int) -> list:
|
||||
got = []
|
||||
for _ in range(ms // FRAME_MS):
|
||||
self.now += FRAME_MS / 1000
|
||||
got += self.seg.push(np.full(SR * FRAME_MS // 1000, level, dtype=np.float32), self.now)
|
||||
self.events += got
|
||||
return got
|
||||
|
||||
def of(self, cls) -> list:
|
||||
return [e for e in self.events if isinstance(e, cls)]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_silence_produces_nothing():
|
||||
f = Feeder()
|
||||
f.feed(0.0, 3000)
|
||||
assert f.events == []
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_speech_then_silence_ends_with_one_final():
|
||||
f = Feeder()
|
||||
f.feed(0.0, 500)
|
||||
f.feed(0.9, 1000)
|
||||
f.feed(0.0, 500)
|
||||
starts, finals = f.of(SpeechStart), f.of(Final)
|
||||
assert [s.utt for s in starts] == [1]
|
||||
assert len(finals) == 1
|
||||
fin = finals[0]
|
||||
assert fin.utt == 1 and fin.reason == "silence"
|
||||
# Pre-roll (<= 200 ms) + 1 s speech + trailing silence capped at 200 ms.
|
||||
assert 1.0 <= len(fin.audio) / SR <= 1.45
|
||||
assert fin.audio.dtype == np.float32
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_final_waits_for_the_configured_silence():
|
||||
f = Feeder(SttSettings(end_silence_ms=600))
|
||||
f.feed(0.9, 800)
|
||||
f.feed(0.0, 400)
|
||||
assert f.of(Final) == []
|
||||
f.feed(0.0, 300)
|
||||
assert len(f.of(Final)) == 1
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_changed_settings_apply_to_the_running_utterance():
|
||||
f = Feeder(SttSettings(end_silence_ms=1500))
|
||||
f.feed(0.9, 800)
|
||||
f.settings.update({"end_silence_ms": 200})
|
||||
f.feed(0.0, 300)
|
||||
assert [e.reason for e in f.of(Final)] == ["silence"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_short_blip_is_dropped_without_any_message():
|
||||
f = Feeder()
|
||||
f.feed(0.9, 120)
|
||||
f.feed(0.0, 1000)
|
||||
assert f.events == []
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_hysteresis_keeps_speech_going_but_never_starts_it():
|
||||
f = Feeder()
|
||||
f.feed(0.4, 1000)
|
||||
assert f.events == []
|
||||
f.feed(0.9, 400)
|
||||
f.feed(0.4, 1000) # below the start threshold but above the keep threshold
|
||||
assert f.of(Final) == []
|
||||
f.feed(0.0, 400)
|
||||
assert len(f.of(Final)) == 1
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_speaking_end_closes_the_utterance_at_once():
|
||||
f = Feeder()
|
||||
f.feed(0.9, 700)
|
||||
events = f.seg.speaking_end(f.now)
|
||||
assert [type(e) for e in events] == [Final]
|
||||
assert events[0].reason == "speaking_end"
|
||||
assert events[0].decided_at == f.now
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_speaking_end_after_a_blip_sends_nothing():
|
||||
f = Feeder()
|
||||
f.feed(0.9, 100)
|
||||
assert f.seg.speaking_end(f.now) == []
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_audio_that_stops_arriving_ends_as_idle():
|
||||
f = Feeder()
|
||||
f.feed(0.9, 700)
|
||||
assert f.seg.tick(f.now + 0.2) == []
|
||||
events = f.seg.tick(f.now + 0.31)
|
||||
assert [e.reason for e in events] == ["idle"]
|
||||
assert f.seg.tick(f.now + 1.0) == []
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_long_speech_is_cut_at_the_whisper_window_and_continues_as_a_new_utterance():
|
||||
f = Feeder()
|
||||
f.feed(0.9, 29_000)
|
||||
finals = f.of(Final)
|
||||
assert [e.reason for e in finals] == ["max_length"]
|
||||
assert len(finals[0].audio) / SR <= 28.0
|
||||
assert [s.utt for s in f.of(SpeechStart)] == [1, 2]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_partials_follow_the_interval_and_grow():
|
||||
f = Feeder(SttSettings(partial_interval_ms=400))
|
||||
f.feed(0.9, 2000)
|
||||
partials = f.of(Partial)
|
||||
assert 3 <= len(partials) <= 5
|
||||
lengths = [len(p.audio) for p in partials]
|
||||
assert lengths == sorted(lengths) and len(set(lengths)) == len(lengths)
|
||||
assert all(p.utt == 1 for p in partials)
|
||||
f.feed(0.0, 400)
|
||||
n = len(f.of(Partial))
|
||||
f.feed(0.0, 1000)
|
||||
assert len(f.of(Partial)) == n # nothing after the final
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_no_partials_before_speech_start():
|
||||
f = Feeder(SttSettings(partial_interval_ms=100))
|
||||
f.feed(0.9, 200)
|
||||
assert f.of(Partial) == []
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_utterance_numbers_count_up_per_speaker():
|
||||
f = Feeder()
|
||||
for _ in range(3):
|
||||
f.feed(0.9, 500)
|
||||
f.feed(0.0, 400)
|
||||
assert [e.utt for e in f.of(Final)] == [1, 2, 3]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("bad", [{"end_silence_ms": 50}, {"end_silence_ms": 5000}, {"final_beam": 0},
|
||||
{"final_beam": 9}, {"partials": "yes"}, {"hotwords": "자비스"},
|
||||
{"language": 3}, {"partial_interval_ms": 10}, {"nope": 1}])
|
||||
def test_bad_settings_are_refused_and_change_nothing(bad):
|
||||
s = SttSettings()
|
||||
before = s.as_dict()
|
||||
with pytest.raises(ValueError):
|
||||
s.update(bad)
|
||||
assert s.as_dict() == before
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_settings_accept_null_language_and_hotword_lists():
|
||||
s = SttSettings()
|
||||
s.update({"language": None, "hotwords": ["자비스", "Jarvis"], "partials": False})
|
||||
assert s.as_dict()["language"] is None
|
||||
assert s.hotwords == ("자비스", "Jarvis")
|
||||
assert s.partials is False
|
||||
50
tests/test_voice_worker_sentences.py
Normal file
50
tests/test_voice_worker_sentences.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""Voice worker: sentence splitting for streaming TTS, whole and incremental."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from voice_worker.sentences import StreamingSplitter, split_sentences
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_splits_on_terminal_punctuation_only():
|
||||
assert split_sentences("안녕하세요. 오늘은 맑아요! 우산은 필요 없어요?") == [
|
||||
"안녕하세요.", "오늘은 맑아요!", "우산은 필요 없어요?"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_decimals_versions_and_urls_stay_whole():
|
||||
assert split_sentences("기온은 17.5도예요. 자세한 건 example.com 에 있어요.") == [
|
||||
"기온은 17.5도예요.", "자세한 건 example.com 에 있어요."]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cjk_terminators_split_without_spaces():
|
||||
assert split_sentences("今日は晴れです。明日は雨です。") == ["今日は晴れです。", "明日は雨です。"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_short_fragments_merge_into_a_neighbour():
|
||||
assert split_sentences("네. 알람을 일곱 시에 맞췄어요.") == ["네. 알람을 일곱 시에 맞췄어요."]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_streaming_holds_the_unfinished_tail_until_more_text_arrives():
|
||||
s = StreamingSplitter()
|
||||
assert s.feed("오늘 서울은 맑") == []
|
||||
assert s.feed("아요. 기온은 17") == ["오늘 서울은 맑아요."]
|
||||
assert s.feed(".5도예요. 바람은") == ["기온은 17.5도예요."]
|
||||
assert s.finish() == ["바람은"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_streaming_output_equals_whole_text_split():
|
||||
text = "첫 문장입니다. 두 번째 문장이에요! 세 번째는 질문인가요? 마지막 문장이에요."
|
||||
s = StreamingSplitter()
|
||||
got = []
|
||||
for i in range(0, len(text), 3):
|
||||
got += s.feed(text[i:i + 3])
|
||||
got += s.finish()
|
||||
assert got == split_sentences(text)
|
||||
|
||||
327
tests/test_voice_worker_server.py
Normal file
327
tests/test_voice_worker_server.py
Normal file
@@ -0,0 +1,327 @@
|
||||
"""Voice worker end to end over a real local WebSocket, with fake STT/VAD/TTS engines.
|
||||
|
||||
The fake VAD reads speech probability off the amplitude and the fake transcriber names a clip by its
|
||||
peak level, so each speaker's text tells which speaker's audio reached the model.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from voice_worker.protocol import decode_tts_frame, encode_audio_frame
|
||||
from voice_worker.server import CLOSE_BAD_HELLO, CLOSE_BAD_TOKEN, VoiceWorker
|
||||
|
||||
websockets = pytest.importorskip("websockets")
|
||||
from websockets.asyncio.client import connect # noqa: E402
|
||||
|
||||
TOKEN = "test-token"
|
||||
|
||||
|
||||
class AmplitudeVad:
|
||||
def prob(self, window):
|
||||
return float(np.max(np.abs(window)))
|
||||
|
||||
|
||||
class LevelTranscriber:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def transcribe(self, clips, opts):
|
||||
self.calls.append((opts, len(clips)))
|
||||
return [f"level {np.median(np.abs(c)):.1f}" for c in clips]
|
||||
|
||||
|
||||
class FakeTts:
|
||||
"""10 samples per character; optional delay per sentence; can fail on a marker."""
|
||||
|
||||
def __init__(self, delay: float = 0.0):
|
||||
self.delay = delay
|
||||
self.texts = []
|
||||
|
||||
def synthesize(self, text, rate):
|
||||
if self.delay:
|
||||
time.sleep(self.delay)
|
||||
if "FAIL" in text:
|
||||
raise RuntimeError("engine broke")
|
||||
self.texts.append(text)
|
||||
return np.full(len(text) * 10, 1000, dtype=np.int16)
|
||||
|
||||
|
||||
def pcm(level: float, ms: int, rate=16000, channels=1) -> bytes:
|
||||
n = rate * ms // 1000
|
||||
return (np.full(n * channels, level) * 32767).astype("<i2").tobytes()
|
||||
|
||||
|
||||
async def with_worker(body, transcriber=None, tts=None, **kw):
|
||||
worker = VoiceWorker(TOKEN, transcriber if transcriber is not None else LevelTranscriber(), AmplitudeVad,
|
||||
tts, **kw)
|
||||
server = await worker.serve("127.0.0.1", 0)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
try:
|
||||
return await asyncio.wait_for(body(f"ws://127.0.0.1:{port}"), 15)
|
||||
finally:
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await worker.stop()
|
||||
|
||||
|
||||
async def hello(ws, **extra):
|
||||
await ws.send(json.dumps({"type": "hello", "token": TOKEN, "audio": {"rate": 16000, "channels": 1},
|
||||
"tts": {"rate": 24000, "channels": 2}, **extra}))
|
||||
return json.loads(await ws.recv())
|
||||
|
||||
|
||||
async def recv_until(ws, pred, limit=200):
|
||||
seen = []
|
||||
for _ in range(limit):
|
||||
raw = await ws.recv()
|
||||
msg = raw if isinstance(raw, bytes) else json.loads(raw)
|
||||
seen.append(msg)
|
||||
if pred(msg):
|
||||
return seen
|
||||
raise AssertionError("condition never met")
|
||||
|
||||
|
||||
async def stream(ws, speaker: str, level: float, ms: int, realtime: bool = False):
|
||||
for _ in range(ms // 20):
|
||||
await ws.send(encode_audio_frame(speaker, pcm(level, 20)))
|
||||
if realtime:
|
||||
await asyncio.sleep(0.02)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_wrong_token_is_refused():
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await ws.send(json.dumps({"type": "hello", "token": "nope"}))
|
||||
with pytest.raises(websockets.ConnectionClosed) as e:
|
||||
await ws.recv()
|
||||
return e.value.rcvd.code
|
||||
|
||||
assert asyncio.run(with_worker(body)) == CLOSE_BAD_TOKEN
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_silent_client_is_dropped_after_the_hello_timeout():
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
with pytest.raises(websockets.ConnectionClosed) as e:
|
||||
await ws.recv()
|
||||
return e.value.rcvd.code
|
||||
|
||||
assert asyncio.run(with_worker(body, hello_timeout_s=0.2)) == CLOSE_BAD_HELLO
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_non_loopback_addresses_are_refused():
|
||||
worker = VoiceWorker(TOKEN, LevelTranscriber(), AmplitudeVad)
|
||||
with pytest.raises(ValueError):
|
||||
asyncio.run(worker.serve("0.0.0.0", 0))
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_hello_ok_reports_readiness_and_effective_settings():
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
return await hello(ws, stt={"hotwords": ["자비스"], "end_silence_ms": 250})
|
||||
|
||||
ok = asyncio.run(with_worker(body))
|
||||
assert ok["type"] == "hello_ok"
|
||||
assert ok["stt_ready"] is True and ok["tts_ready"] is False
|
||||
assert ok["stt"]["hotwords"] == ["자비스"] and ok["stt"]["end_silence_ms"] == 250
|
||||
assert ok["tts"] == {"rate": 24000, "channels": 2}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_two_speakers_each_get_their_own_final():
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws, stt={"partials": False})
|
||||
await stream(ws, "alice", 0.9, 600)
|
||||
await stream(ws, "bob", 0.6, 600)
|
||||
await ws.send(json.dumps({"type": "speaking_end", "speaker": "alice"}))
|
||||
await ws.send(json.dumps({"type": "speaking_end", "speaker": "bob"}))
|
||||
seen = await recv_until(ws, lambda m: m.get("type") == "final" and m["speaker"] == "bob")
|
||||
if not any(m.get("type") == "final" and m["speaker"] == "alice" for m in seen):
|
||||
seen += await recv_until(ws, lambda m: m.get("type") == "final")
|
||||
return seen
|
||||
|
||||
seen = asyncio.run(with_worker(body))
|
||||
finals = {m["speaker"]: m for m in seen if m.get("type") == "final"}
|
||||
assert finals["alice"]["text"] == "level 0.9" and finals["bob"]["text"] == "level 0.6"
|
||||
assert {m["end_reason"] for m in finals.values()} == {"speaking_end"}
|
||||
assert all(m["utt"] == 1 and 500 <= m["audio_ms"] <= 900 for m in finals.values())
|
||||
starts = [m for m in seen if m.get("type") == "speech_start"]
|
||||
assert sorted(m["speaker"] for m in starts) == ["alice", "bob"]
|
||||
assert not any(m.get("type") == "partial" for m in seen)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_audio_that_stops_without_speaking_end_still_ends():
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws, stt={"partials": False, "end_silence_ms": 200})
|
||||
await stream(ws, "alice", 0.9, 500)
|
||||
return await recv_until(ws, lambda m: m.get("type") == "final")
|
||||
|
||||
final = asyncio.run(with_worker(body))[-1]
|
||||
assert final["end_reason"] == "idle" and final["text"] == "level 0.9"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_partials_flow_while_speaking_and_stop_when_turned_off():
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws, stt={"partial_interval_ms": 100})
|
||||
await stream(ws, "alice", 0.9, 800, realtime=True)
|
||||
first = await recv_until(ws, lambda m: m.get("type") == "partial")
|
||||
await ws.send(json.dumps({"type": "config", "partials": False}))
|
||||
# Drain whatever was already on its way before the setting changed.
|
||||
while True:
|
||||
try:
|
||||
await asyncio.wait_for(ws.recv(), 0.3)
|
||||
except asyncio.TimeoutError:
|
||||
break
|
||||
await stream(ws, "alice", 0.9, 600, realtime=True)
|
||||
await ws.send(json.dumps({"type": "speaking_end", "speaker": "alice"}))
|
||||
rest = await recv_until(ws, lambda m: m.get("type") == "final")
|
||||
return first, rest
|
||||
|
||||
first, rest = asyncio.run(with_worker(body))
|
||||
assert first[-1]["text"] == "level 0.9" and first[-1]["utt"] == 1
|
||||
assert not any(m.get("type") == "partial" for m in rest)
|
||||
assert rest[-1]["type"] == "final"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_tts_streams_one_chunk_per_sentence_in_the_session_format():
|
||||
tts = FakeTts()
|
||||
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws)
|
||||
await ws.send(json.dumps({"type": "tts", "id": "r1", "text": "오늘은 맑아요. 기온은 17.5도예요."}))
|
||||
return await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "tts_done")
|
||||
|
||||
seen = asyncio.run(with_worker(body, tts=tts))
|
||||
chunks = [decode_tts_frame(m) for m in seen if isinstance(m, bytes)]
|
||||
assert [(c[0], c[1]) for c in chunks] == [("r1", 0), ("r1", 1)]
|
||||
assert tts.texts == ["오늘은 맑아요.", "기온은 17.5도예요."]
|
||||
# Stereo: every mono sample twice, 16-bit.
|
||||
assert len(chunks[0][2]) == len("오늘은 맑아요.") * 10 * 2 * 2
|
||||
assert seen[-1] == {"type": "tts_done", "id": "r1", "chunks": 2, "cancelled": False, "failed": False}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_tts_text_can_arrive_in_pieces():
|
||||
tts = FakeTts()
|
||||
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws)
|
||||
for piece, more in [("첫 번째 문장", True), ("이에요. 두 번", True), ("째 문장이에요.", False)]:
|
||||
await ws.send(json.dumps({"type": "tts", "id": "s", "text": piece, "more": more}))
|
||||
return await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "tts_done")
|
||||
|
||||
seen = asyncio.run(with_worker(body, tts=tts))
|
||||
assert tts.texts == ["첫 번째 문장이에요.", "두 번째 문장이에요."]
|
||||
assert seen[-1]["chunks"] == 2
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cancel_stops_the_remaining_sentences():
|
||||
tts = FakeTts(delay=0.15)
|
||||
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws)
|
||||
text = " ".join(f"이것은 {i}번째 문장입니다." for i in range(6))
|
||||
await ws.send(json.dumps({"type": "tts", "id": "c", "text": text}))
|
||||
first = await recv_until(ws, lambda m: isinstance(m, bytes))
|
||||
await ws.send(json.dumps({"type": "tts_cancel", "id": "c"}))
|
||||
return first + await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "tts_done")
|
||||
|
||||
seen = asyncio.run(with_worker(body, tts=tts))
|
||||
done = seen[-1]
|
||||
assert done["cancelled"] is True and done["chunks"] < 6
|
||||
assert sum(isinstance(m, bytes) for m in seen) == done["chunks"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_failing_sentence_ends_the_request_as_failed():
|
||||
tts = FakeTts()
|
||||
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws)
|
||||
await ws.send(json.dumps({"type": "tts", "id": "f", "text": "첫 문장입니다. FAIL 문장입니다. 셋째 문장입니다."}))
|
||||
return await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "tts_done")
|
||||
|
||||
seen = asyncio.run(with_worker(body, tts=tts))
|
||||
errors = [m for m in seen if isinstance(m, dict) and m.get("type") == "error"]
|
||||
assert errors and errors[0]["code"] == "tts_failed" and errors[0]["id"] == "f"
|
||||
assert seen[-1]["failed"] is True and seen[-1]["chunks"] == 1
|
||||
assert tts.texts == ["첫 문장입니다."]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_tts_without_an_engine_reports_unavailable():
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws)
|
||||
await ws.send(json.dumps({"type": "tts", "id": "x", "text": "안녕하세요."}))
|
||||
return json.loads(await ws.recv())
|
||||
|
||||
msg = asyncio.run(with_worker(body))
|
||||
assert msg["type"] == "error" and msg["code"] == "tts_unavailable" and msg["id"] == "x"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_bad_messages_get_an_error_and_the_connection_stays_open():
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws)
|
||||
out = []
|
||||
for raw in ["{not json", json.dumps({"type": "dance"}), json.dumps({"type": "config", "final_beam": 99})]:
|
||||
await ws.send(raw)
|
||||
out.append(json.loads(await ws.recv()))
|
||||
await ws.send(b"\x01\x00")
|
||||
out.append(json.loads(await ws.recv()))
|
||||
await ws.send(json.dumps({"type": "config", "final_beam": 3}))
|
||||
await ws.send(json.dumps({"type": "dance"}))
|
||||
out.append(json.loads(await ws.recv()))
|
||||
return out
|
||||
|
||||
out = asyncio.run(with_worker(body))
|
||||
assert [m["code"] for m in out] == ["bad_message", "bad_message", "bad_message", "bad_frame", "bad_message"]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_48k_stereo_input_reaches_the_model_at_16k():
|
||||
t = LevelTranscriber()
|
||||
lengths = []
|
||||
orig = t.transcribe
|
||||
|
||||
def spy(clips, opts):
|
||||
lengths.extend(len(c) for c in clips)
|
||||
return orig(clips, opts)
|
||||
|
||||
t.transcribe = spy
|
||||
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await ws.send(json.dumps({"type": "hello", "token": TOKEN, "stt": {"partials": False}}))
|
||||
await ws.recv()
|
||||
for _ in range(30): # 600 ms
|
||||
await ws.send(encode_audio_frame("a", pcm(0.9, 20, rate=48000, channels=2)))
|
||||
await ws.send(json.dumps({"type": "speaking_end", "speaker": "a"}))
|
||||
return await recv_until(ws, lambda m: m.get("type") == "final")
|
||||
|
||||
final = asyncio.run(with_worker(body, transcriber=t))[-1]
|
||||
assert final["text"] == "level 0.9"
|
||||
assert 0.5 * 16000 <= lengths[0] <= 0.9 * 16000
|
||||
53
tests/test_voice_worker_vad.py
Normal file
53
tests/test_voice_worker_vad.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Voice worker: the streaming Silero VAD (real ONNX model bundled with faster-whisper, CPU only)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("onnxruntime")
|
||||
pytest.importorskip("faster_whisper")
|
||||
|
||||
from voice_worker.segmenter import WINDOW # noqa: E402
|
||||
from voice_worker.vad import SileroVad # noqa: E402
|
||||
|
||||
SAMPLE = Path(__file__).resolve().parent.parent / "scripts" / "m0" / "assets" / "ko_samples" / "ko_01.wav"
|
||||
|
||||
|
||||
def _speech() -> np.ndarray:
|
||||
with wave.open(str(SAMPLE), "rb") as w:
|
||||
return np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(np.float32) / 32768.0
|
||||
|
||||
|
||||
def _probs(stream, audio):
|
||||
n = len(audio) // WINDOW * WINDOW
|
||||
return np.array([stream.prob(audio[i:i + WINDOW]) for i in range(0, n, WINDOW)])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def vad():
|
||||
return SileroVad()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_speech_is_detected_and_silence_is_not(vad):
|
||||
speech = _probs(vad.stream(), _speech())
|
||||
silence = _probs(vad.stream(), np.zeros(16000, dtype=np.float32))
|
||||
assert (speech >= 0.5).mean() > 0.4
|
||||
assert silence.max() < 0.2
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_each_speaker_stream_keeps_its_own_state(vad):
|
||||
audio = _speech()
|
||||
alone = _probs(vad.stream(), audio)
|
||||
a, b = vad.stream(), vad.stream()
|
||||
n = len(audio) // WINDOW * WINDOW
|
||||
interleaved = []
|
||||
for i in range(0, n, WINDOW):
|
||||
interleaved.append(a.prob(audio[i:i + WINDOW]))
|
||||
b.prob(np.zeros(WINDOW, dtype=np.float32)) # another speaker in silence between every window
|
||||
assert np.allclose(alone, interleaved, atol=1e-5)
|
||||
Reference in New Issue
Block a user