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
4 changes: 3 additions & 1 deletion .github/workflows/test-example-collection.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ on:
- "tests/test_jev_example_output.py"
- "examples/mcp_server/**"
- "examples/openai_api/**"
- "examples/industrial_data_pretraining/fun_asr_nano/client_python.py"
- "examples/industrial_data_pretraining/fun_asr_nano/client_test.py"
- "tests/test_streaming_client_collection.py"
- "tests/test_example_smoke_collection.py"
Expand All @@ -24,6 +25,7 @@ on:
- "tests/test_jev_example_output.py"
- "examples/mcp_server/**"
- "examples/openai_api/**"
- "examples/industrial_data_pretraining/fun_asr_nano/client_python.py"
- "examples/industrial_data_pretraining/fun_asr_nano/client_test.py"
- "tests/test_streaming_client_collection.py"
- "tests/test_example_smoke_collection.py"
Expand All @@ -50,7 +52,7 @@ jobs:
with:
python-version: ${{ matrix.python }}
- name: Install test runner and client dependencies
run: python -m pip install pytest numpy soundfile 'websockets>=10,<16'
run: python -m pip install pytest numpy soundfile librosa 'websockets>=10,<16'
- name: Check collection and standalone CLI compatibility
run: |
git rev-parse HEAD > source-commit.txt
Expand Down
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
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
56 changes: 56 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 / "examples/industrial_data_pretraining/fun_asr_nano/client_test.py"
PYTHON_CLIENT = CLIENT.with_name("client_python.py")


@pytest.mark.parametrize("import_mode", ["prepend", "append", "importlib"])
Expand Down Expand Up @@ -104,3 +106,57 @@ 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, 48000])
def test_clients_send_one_channel_of_stereo_audio_at_16khz(tmp_path, client, sample_rate):
audio_path = tmp_path / "stereo.wav"
time = np.arange(sample_rate) / sample_rate
left = np.sin(2 * np.pi * 440 * time) * 12000
right = np.sin(2 * np.pi * 880 * time) * 24000
with wave.open(str(audio_path), "wb") as audio:
audio.setnchannels(2)
audio.setsampwidth(2)
audio.setframerate(sample_rate)
audio.writeframes(np.column_stack([left, right]).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=client.parent,
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