From 3f3329fb23fad32d61ac48e3a72565cb832d93da Mon Sep 17 00:00:00 2001 From: zhifu gao Date: Wed, 2 Dec 2026 10:21:59 +0800 Subject: [PATCH] Require a final transcript for the example WebSocket file client Validate acknowledgements and await a final result after all file audio and STOP. Keep per-utterance COMMIT behavior on the server unchanged. Signed-off-by: LauraGPT --- .github/workflows/test-example-collection.yml | 5 + .../fun_asr_nano/client_python.py | 103 +++++++++--- .../fun_asr_nano/docs/realtime_demo.md | 24 ++- tests/test_file_client_session.py | 154 ++++++++++++++++++ 4 files changed, 262 insertions(+), 24 deletions(-) create mode 100644 tests/test_file_client_session.py diff --git a/.github/workflows/test-example-collection.yml b/.github/workflows/test-example-collection.yml index 6e5d37e9bd..de9699a6f0 100644 --- a/.github/workflows/test-example-collection.yml +++ b/.github/workflows/test-example-collection.yml @@ -10,8 +10,10 @@ on: - "examples/mcp_server/**" - "examples/openai_api/**" - "examples/industrial_data_pretraining/fun_asr_nano/client_python.py" + - "examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md" - "examples/industrial_data_pretraining/fun_asr_nano/client_test.py" - "tests/test_streaming_client_collection.py" + - "tests/test_file_client_session.py" - "tests/test_example_smoke_collection.py" - "tests/test_mcp_server_example.py" - "tests/test_openai_api_docker_validation.py" @@ -26,8 +28,10 @@ on: - "examples/mcp_server/**" - "examples/openai_api/**" - "examples/industrial_data_pretraining/fun_asr_nano/client_python.py" + - "examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md" - "examples/industrial_data_pretraining/fun_asr_nano/client_test.py" - "tests/test_streaming_client_collection.py" + - "tests/test_file_client_session.py" - "tests/test_example_smoke_collection.py" - "tests/test_mcp_server_example.py" - "tests/test_openai_api_docker_validation.py" @@ -62,6 +66,7 @@ jobs: tests/test_jev_example_output.py \ tests/test_example_smoke_collection.py \ tests/test_streaming_client_collection.py \ + tests/test_file_client_session.py \ tests/test_mcp_server_example.py \ tests/test_openai_api_docker_validation.py \ --junitxml=example-results.xml diff --git a/examples/industrial_data_pretraining/fun_asr_nano/client_python.py b/examples/industrial_data_pretraining/fun_asr_nano/client_python.py index da762d5726..f94268676d 100644 --- a/examples/industrial_data_pretraining/fun_asr_nano/client_python.py +++ b/examples/industrial_data_pretraining/fun_asr_nano/client_python.py @@ -20,11 +20,13 @@ import asyncio import argparse import json +import math import sys import numpy as np try: import websockets + from websockets.exceptions import ConnectionClosed except ImportError: print("Please install websockets: pip install websockets") sys.exit(1) @@ -48,7 +50,7 @@ def format_time(ms): return f"{s:.1f}s" -def print_result(data, show_spk=True): +def print_result(data, show_spk=True, *, recording=True): """Print ASR result to terminal.""" sentences = data.get("sentences", []) partial = data.get("partial", "") @@ -81,7 +83,8 @@ def print_result(data, show_spk=True): print(f"\n{GRAY}{'─' * 60}{RESET}") print(f"{GREEN}Done.{RESET} {len(sentences)} sentences") else: - print(f"\n{GRAY}Recording... Press Ctrl+C to stop{RESET}") + status = "Recording... Press Ctrl+C to stop" if recording else "Processing file..." + print(f"\n{GRAY}{status}{RESET}") sys.stdout.flush() @@ -161,6 +164,8 @@ async def run_file(args): sys.exit(1) audio, sr = sf.read(args.file) + if len(audio) == 0: + raise FileSessionError("input contains no audio frames") # soundfile returns (frames, channels), librosa resamples the last axis if audio.ndim > 1: audio = audio[:, 0] @@ -178,56 +183,116 @@ async def run_file(args): print(f"Connecting to {args.server}...") async with websockets.connect(args.server, ping_interval=None) as ws: - await ws.send("START") - await ws.recv() - + async def expect_event(command, expected): + await ws.send(command) + try: + message = await asyncio.wait_for(ws.recv(), args.response_timeout) + except asyncio.TimeoutError as exc: + raise FileSessionError(f"timed out waiting for {expected}") from exc + if file_response(message).get("event") != expected: + raise FileSessionError(f"expected {expected} acknowledgement") + + await expect_event("START", "started") if args.hotwords: - await ws.send(f"HOTWORDS:{args.hotwords}") - await ws.recv() + await expect_event(f"HOTWORDS:{args.hotwords}", "hotwords_set") int16 = (audio * 32768).clip(-32768, 32767).astype(np.int16) chunk_size = CHUNK_SAMPLES - total_chunks = (len(int16) + chunk_size - 1) // chunk_size + stop_requested = False async def send_audio(): + nonlocal stop_requested for i in range(0, len(int16), chunk_size): chunk = int16[i:i+chunk_size] await ws.send(chunk.tobytes()) await asyncio.sleep(CHUNK_DURATION_MS / 1000 * 0.5) + stop_requested = True await ws.send("STOP") async def recv_results(): async for msg in ws: - data = json.loads(msg) - if "sentences" in data: - print_result(data, show_spk=args.spk) - if data.get("is_final") or data.get("event") == "stopped": + data = file_response(msg) + if data.get("is_final") is True: + if not stop_requested or not isinstance(data.get("sentences"), list): + raise FileSessionError("unexpected final result") + return data + if data.get("event") == "stopped": break + if "is_final" in data and data["is_final"] is not False: + raise FileSessionError("invalid is_final flag") + if "sentences" in data: + print_result(data, show_spk=args.spk, recording=False) + raise FileSessionError("connection ended without a final result") - await asyncio.gather(send_audio(), recv_results()) + sender = asyncio.create_task(send_audio()) + receiver = asyncio.create_task(recv_results()) + try: + # Detect an early termination while sending, but do not count file + # upload time against the server's final-response deadline. + await asyncio.wait((sender, receiver), return_when=asyncio.FIRST_COMPLETED) + if receiver.done(): + receiver.result() + await sender + try: + final = await asyncio.wait_for(receiver, args.response_timeout) + except asyncio.TimeoutError as exc: + raise FileSessionError("timed out waiting for a final result") from exc + print_result(final, show_spk=args.spk) + finally: + sender.cancel() + receiver.cancel() + await asyncio.gather(sender, receiver, return_exceptions=True) + + +class FileSessionError(Exception): + pass + + +def file_response(message): + try: + value = json.loads(message) + except ValueError as exc: + raise FileSessionError("invalid JSON response") from exc + if not isinstance(value, dict): + raise FileSessionError("expected a JSON object") + return value + + +def positive_seconds(value): + seconds = float(value) + if not math.isfinite(seconds) or seconds <= 0: + raise argparse.ArgumentTypeError("expected a finite positive number of seconds") + return seconds def main(): parser = argparse.ArgumentParser(description="Fun-ASR-Nano Python Client") parser.add_argument("--server", type=str, default="ws://localhost:10095") - parser.add_argument("--mic", action="store_true", help="Use microphone input") - parser.add_argument("--file", type=str, help="Audio file to transcribe") + source = parser.add_mutually_exclusive_group(required=True) + source.add_argument("--mic", action="store_true", help="Use microphone input") + source.add_argument("--file", type=str, help="Audio file to transcribe") + parser.add_argument("--response-timeout", type=positive_seconds, default=60.0, metavar="SECONDS", + help="File mode: wait per acknowledgement and after STOP (default: 60 seconds)") parser.add_argument("--hotwords", type=str, default="", help="Hotwords (comma-separated)") parser.add_argument("--spk", action="store_true", default=True, help="Show speaker IDs") parser.add_argument("--no-spk", dest="spk", action="store_false") args = parser.parse_args() - if not args.mic and not args.file: - parser.error("Specify --mic or --file") - try: if args.mic: asyncio.run(run_mic(args)) else: - asyncio.run(run_file(args)) + try: + asyncio.run(run_file(args)) + except ConnectionClosed: + sys.exit("File session failed: connection closed before completion") + except FileSessionError as exc: + sys.exit(f"File session failed: {exc}") except KeyboardInterrupt: print(f"\n{RESET}Interrupted.") + if args.file is not None: + sys.exit(130) if __name__ == "__main__": diff --git a/examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md b/examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md index 8af573fff7..49034aad3b 100644 --- a/examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md +++ b/examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md @@ -2,7 +2,7 @@ > 完整文档请参见:[FunASR vLLM 推理引擎指南](../../../../docs/vllm_guide.md) -## 30 秒启动 +## 启动服务端 ```bash cd examples/industrial_data_pretraining/fun_asr_nano @@ -80,20 +80,34 @@ POSTPROCESS_HOTWORDS:哈囉=>客製化,哈罗=>客製化 ## 客户端 +只想发送文件时,不需要在客户端安装服务端的 PyTorch、vLLM 或模型权重。在仓库根目录打开另一个终端,用 Linux、Python 3.11 和 CPU 即可运行下面的示例。首次安装需要允许下载 Python 包;已经装好依赖、示例录音位于本地且服务可达时,客户端不会主动下载模型。 + +```bash +python3.11 -m venv .venv-file-client +source .venv-file-client/bin/activate +python -m pip install 'numpy==1.26.4' 'soundfile==0.13.1' 'librosa==0.11.0' 'websockets==16.0' +cd examples/industrial_data_pretraining/fun_asr_nano +``` + ```bash # 浏览器 open client_mic.html -# Python 麦克风 +# Python 麦克风(需要明确授权;不要同时传 --file) python client_python.py --server ws://localhost:10095 --mic -# Python 文件 -python client_python.py --server ws://localhost:10095 --file audio.wav +# Python 文件:从本示例目录发送仓库自带的六秒录音 +python client_python.py --server ws://127.0.0.1:10095 \ + --file ../../../runtime/llama.cpp/tests/sample.wav --response-timeout 60 # 自动化测试 python client_test.py --server ws://localhost:10095 --file audio.wav ``` +文件客户端在 CPU 上运行。请先确认服务已经启动,且允许把这段音频和可选热词发给它;它不会为你启动服务或下载权重。成功判据是发送完整音频和 `STOP` 后收到 `is_final: true` 及 `sentences` 列表,显示 `Done.` 并以 0 退出。空列表是合法的最终结果,临时文字、单独的 `stopped` 通知或断线不是。这里说的是文件 CLI;上文支持连续 `COMMIT` 的客户端是另一种用法。 + +`--response-timeout` 的单位是秒,必须为有限正数;默认 60。它分别限制启动确认、可选的热词确认、以及发送 `STOP` 后的最终回复,不是整个文件上传的时间限制。确认失败时不开始发送音频;超时或不完整的会话以非零退出。先检查协议和服务端状态,不要自动重复上传录音。 + ## 远程访问 ```bash @@ -103,7 +117,7 @@ ssh -L 10095:localhost:10095 ## 功能 -- **vLLM 推理引擎**:RTF < 0.08,支持 tensor parallel 多卡加速 +- **vLLM 推理引擎**:支持 tensor parallel 多卡推理;实际速度取决于模型、设备和输入。 - **流式 VAD 分句**:动态静音阈值,自然断句 - **说话人分离 (Beta)**:流式 ID 分配 + 最终重聚类 - **热词定制化**:加载人名、地名等实体词文件 diff --git a/tests/test_file_client_session.py b/tests/test_file_client_session.py new file mode 100644 index 0000000000..683340c131 --- /dev/null +++ b/tests/test_file_client_session.py @@ -0,0 +1,154 @@ +"""File-mode CLI contracts over loopback, without a model or microphone.""" + +import asyncio +import importlib.util +import json +from pathlib import Path +import subprocess +import sys +import wave + +import pytest +from websockets.legacy.server import serve + + +CLIENT = Path(__file__).resolve().parents[1] / "examples/industrial_data_pretraining/fun_asr_nano/client_python.py" + + +@pytest.fixture +def client(): + spec = importlib.util.spec_from_file_location("local_client", CLIENT) + client = importlib.util.module_from_spec(spec) + spec.loader.exec_module(client) + return client + + +def test_file_and_microphone_are_mutually_exclusive(client, monkeypatch): + monkeypatch.setattr(sys, "argv", ["client_python.py", "--file", "chosen.wav", "--mic"]) + + def forbidden(coro): + coro.close() + pytest.fail("ambiguous input reached an input handler") + + monkeypatch.setattr(asyncio, "run", forbidden) + with pytest.raises(SystemExit) as exc: + client.main() + assert exc.value.code == 2 + + +def test_interrupted_file_is_not_success(client, monkeypatch): + def interrupt(coro): + coro.close() + raise KeyboardInterrupt + + monkeypatch.setattr(sys, "argv", ["client_python.py", "--file", "chosen.wav"]) + monkeypatch.setattr(asyncio, "run", interrupt) + with pytest.raises(SystemExit) as exc: + client.main() + assert exc.value.code == 130 + + +@pytest.mark.parametrize("case,expected", [ + ("started", 1), ("hotwords_set", 1), ("not_json", 1), + ("stopped", 1), ("closed", 1), ("early_final", 1), ("invalid_final", 1), + ("silent_start", 1), ("silent_final", 1), ("complete", 0), ("empty_transcript", 0), + ("closed_at_start", 1), ("string_flag", 1), ("partial_only", 1), ("silent_hotwords", 1), +]) +def test_file_session(tmp_path, case, expected): + pcm = b"\x01\x02" * 16000 + wav = tmp_path / "sample.wav" + with wave.open(str(wav), "wb") as f: + f.setparams((1, 2, 16000, 0, "NONE", "not compressed")) + f.writeframes(pcm) + events = [] + + async def run(): + async def handler(ws, path=None): + async for msg in ws: + events.append(msg) + if msg == "START": + if case == "closed_at_start": + await ws.close() + break + if case == "silent_start": + continue + if case == "not_json": + await ws.send("not an event") + else: + event = "stopped" if case == "started" else "started" + await ws.send(json.dumps({"event": event})) + elif msg == "HOTWORDS:test": + if case == "silent_hotwords": + continue + event = "stopped" if case == "hotwords_set" else "hotwords_set" + await ws.send(json.dumps({"event": event})) + elif isinstance(msg, bytes) and case == "early_final": + if sum(isinstance(e, bytes) for e in events) == 1: + await ws.send(json.dumps({"is_final": True, "sentences": []})) + elif msg == "STOP": + if case == "silent_final": + continue + if case in ("string_flag", "partial_only"): + await ws.send(json.dumps({"is_final": "false" if case == "string_flag" else False, + "sentences": [{"text": "a partial result"}]})) + if case in ("complete", "empty_transcript", "invalid_final"): + reply = {"is_final": True} + if case != "invalid_final": + reply["sentences"] = [] if case == "empty_transcript" else [{"text": "local fixture"}] + await ws.send(json.dumps(reply)) + if case != "closed": + await ws.send(json.dumps({"event": "stopped"})) + await ws.close() + + async with serve(handler, "127.0.0.1", 0) as server: + port = server.sockets[0].getsockname()[1] + args = [sys.executable, str(CLIENT), "--server", f"ws://127.0.0.1:{port}", + "--file", str(wav), "--hotwords", "test"] + if case.startswith("silent_") or case == "empty_transcript": + args.extend(["--response-timeout", "0.2"]) + proc = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE) + try: + stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=10) + finally: + if proc.returncode is None: + proc.kill() + await proc.wait() + return proc.returncode, stdout.decode(), stderr.decode() + + code, stdout, stderr = asyncio.run(run()) + assert code == expected, (stdout, stderr) + if case in ("started", "not_json", "silent_start", "closed_at_start"): + assert events == ["START"] + elif case in ("hotwords_set", "silent_hotwords"): + assert events == ["START", "HOTWORDS:test"] + elif case == "early_final": + assert "STOP" not in events + else: + assert events[0:2] == ["START", "HOTWORDS:test"] and events[-1] == "STOP" + assert b"".join(e for e in events if isinstance(e, bytes)) == pcm + if expected == 0: + assert "Done." in stdout + else: + assert "Done." not in stdout and "File session" in stderr + if case.startswith("silent_"): + assert "timed out" in stderr + if case == "partial_only": + assert "Processing file..." in stdout and "Recording..." not in stdout + + +@pytest.mark.parametrize("value", ["0", "-1", "nan", "inf"]) +def test_response_deadline_must_be_finite_and_positive(value): + result = subprocess.run([sys.executable, str(CLIENT), "--file", "not-opened.wav", + "--response-timeout", value], capture_output=True, timeout=10) + assert result.returncode == 2 and b"finite positive" in result.stderr + + +def test_empty_file_stops_before_connecting(tmp_path): + path = tmp_path / "empty.wav" + with wave.open(str(path), "wb") as f: + f.setparams((1, 2, 16000, 0, "NONE", "not compressed")) + result = subprocess.run([sys.executable, str(CLIENT), "--file", str(path)], + capture_output=True, timeout=10) + assert result.returncode == 1 and b"no audio frames" in result.stderr + assert b"Connecting" not in result.stdout