Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions client_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,16 @@ async def run_file(args):
sys.exit(1)

audio, sr = sf.read(args.file)
# soundfile returns (frames, channels), librosa resamples the last axis
if audio.ndim > 1:
audio = audio[:, 0]
if sr != SAMPLE_RATE:
try:
import librosa
audio = librosa.resample(audio, orig_sr=sr, target_sr=SAMPLE_RATE)
except ImportError:
print(f"Audio is {sr}Hz, need 16kHz. Install librosa: pip install librosa")
sys.exit(1)
if audio.ndim > 1:
audio = audio[:, 0]
audio = audio.astype(np.float32)

duration = len(audio) / SAMPLE_RATE
Expand Down
5 changes: 3 additions & 2 deletions client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,16 @@

def load_audio(file_path):
audio, sr = sf.read(file_path)
# soundfile returns (frames, channels), librosa resamples the last axis
if audio.ndim > 1:
audio = audio[:, 0]
if sr != SAMPLE_RATE:
try:
import librosa
audio = librosa.resample(audio, orig_sr=sr, target_sr=SAMPLE_RATE)
except ImportError:
print(f"ERROR: Audio is {sr}Hz. Install librosa for resampling.")
sys.exit(1)
if audio.ndim > 1:
audio = audio[:, 0]
return audio.astype(np.float32)


Expand Down
55 changes: 55 additions & 0 deletions tests/test_streaming_client_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@
import sys
import wave

import numpy as np
import pytest
from websockets.legacy.server import serve


ROOT = Path(__file__).resolve().parents[1]
CLIENT = ROOT / "client_test.py"
PYTHON_CLIENT = ROOT / "client_python.py"


@pytest.mark.parametrize("import_mode", ["prepend", "append", "importlib"])
Expand Down Expand Up @@ -104,3 +106,56 @@ async def handler(ws, path=None):
assert ("RESULTS: 0 passed, 3 failed" if missing_final else "RESULTS: 3 passed, 0 failed") in output
assert sessions == ([pcm, b"\0" * 1600, pcm] if missing_final else [pcm, b"\0" * 1600, pcm, pcm])
assert received_hotwords == ([hotwords] if hotwords else [])


@pytest.mark.parametrize("client", [CLIENT, PYTHON_CLIENT], ids=lambda path: path.name)
@pytest.mark.parametrize("sample_rate", [8000, 16000, 44100])
def test_clients_send_one_channel_of_stereo_audio_at_16khz(tmp_path, client, sample_rate):
pytest.importorskip("librosa")
audio_path = tmp_path / "stereo.wav"
tone = np.sin(2 * np.pi * 440 * np.arange(sample_rate) / sample_rate) * 12000
with wave.open(str(audio_path), "wb") as audio:
audio.setnchannels(2)
audio.setsampwidth(2)
audio.setframerate(sample_rate)
audio.writeframes(np.column_stack([tone, np.zeros_like(tone)]).astype("<i2").tobytes())

async def run():
sessions = []

async def handler(ws, path=None):
chunks = []
async for message in ws:
if message == "START":
chunks = []
await ws.send(json.dumps({"event": "started"}))
elif isinstance(message, bytes):
chunks.append(message)
elif message == "STOP":
sessions.append(b"".join(chunks))
await ws.send(json.dumps({"is_final": True, "sentences": [
{"text": "local protocol", "start": 0, "end": 1000},
]}))
await ws.send(json.dumps({"event": "stopped"}))

async with serve(handler, "127.0.0.1", 0) as server:
port = server.sockets[0].getsockname()[1]
process = await asyncio.create_subprocess_exec(
sys.executable, str(client), "--server", f"ws://127.0.0.1:{port}",
"--file", str(audio_path), cwd=ROOT,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
)
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=60)
finally:
if process.returncode is None:
process.kill()
await process.wait()
return process.returncode, stdout.decode(), stderr.decode(), sessions

code, output, errors, sessions = asyncio.run(run())
assert code == 0, output + errors
sent = np.frombuffer(sessions[0], dtype="<i2")
assert len(sent) == 16000
assert np.abs(np.fft.rfft(sent)).argmax() == 440
assert abs(int(np.abs(sent[4000:12000]).max()) - 12000) < 200
Loading