diff --git a/.github/workflows/native-transformers-examples.yml b/.github/workflows/native-transformers-examples.yml index 6c0cef56..25019aa0 100644 --- a/.github/workflows/native-transformers-examples.yml +++ b/.github/workflows/native-transformers-examples.yml @@ -2,10 +2,10 @@ name: Native Transformers examples on: pull_request: - paths: ['README*.md', 'examples/**', 'tests/**', 'client_test.py', '.github/workflows/native-transformers-examples.yml'] + paths: ['README*.md', 'examples/**', 'tests/**', 'client_test.py', 'client_python.py', 'docs/realtime_demo.md', '.github/workflows/native-transformers-examples.yml'] push: branches: [main, 'codex/transformers-first-*'] - paths: ['README*.md', 'examples/**', 'tests/**', 'client_test.py', '.github/workflows/native-transformers-examples.yml'] + paths: ['README*.md', 'examples/**', 'tests/**', 'client_test.py', 'client_python.py', 'docs/realtime_demo.md', '.github/workflows/native-transformers-examples.yml'] permissions: contents: read @@ -27,3 +27,4 @@ jobs: tests/test_examples_smoke.py tests/test_funasr_requirement.py tests/test_timestamp_documentation.py tests/test_moss_ecosystem_docs.py tests/test_streaming_client_collection.py + tests/test_file_client_session.py diff --git a/client_python.py b/client_python.py index da762d57..f9426867 100644 --- a/client_python.py +++ b/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/docs/realtime_demo.md b/docs/realtime_demo.md index 77956ef3..a883ce83 100644 --- a/docs/realtime_demo.md +++ b/docs/realtime_demo.md @@ -1,71 +1,38 @@ -# Fun-ASR-Nano 实时 WebSocket 服务 — 快速上手 +# 把一段录音发给 Fun-ASR WebSocket 服务 -> 完整文档请参见:[FunASR vLLM 推理引擎指南](https://github.com/modelscope/FunASR/blob/main/docs/vllm_guide.md) +文件上传完,和拿到最终转写,是两件事。下面从文件发起一次转写,以客户端输出 `Done.` 并正常退出作为成功判据。这个客户端对接的是仓库里的 [WebSocket 服务](../serve_realtime_ws.py),不是 OpenAI HTTP 转写接口。 -> **注意**: `serve_realtime_ws.py` 等服务脚本位于 [FunASR 主仓库](https://github.com/modelscope/FunASR/tree/main/examples/industrial_data_pretraining/fun_asr_nano),需要先 clone FunASR。 +## 准备客户端 -## 30 秒启动 +需要一个已经运行、允许你发送样例音频的服务地址。下面假定它在本机 `ws://127.0.0.1:10095`。还没有服务时,先看 [vLLM 部署指南](vllm_guide_zh.md);安装客户端不会启动模型。远端服务涉及上传数据,只使用得到授权的地址和录音,不要把本地示例端口直接暴露到公网。 -```bash -# Clone FunASR main repo (contains the server scripts) -git clone https://github.com/modelscope/FunASR.git -cd FunASR/examples/industrial_data_pretraining/fun_asr_nano - -# 安装依赖 -pip install -r requirements.txt -pip install vllm>=0.12.0 - -# 启动服务 -CUDA_VISIBLE_DEVICES=0 python serve_realtime_ws.py \ - --port 10095 --language 中文 \ - --ws-ping-interval 30 --ws-ping-timeout 120 -``` - -长时间会议、访谈或经过 Nginx/负载均衡访问时,可按网络空闲回收时间调整 `--ws-ping-interval` 与 `--ws-ping-timeout`。如果外部网关已经负责心跳和重连,可将两者设为 `0` 关闭 WebSocket 协议层 ping。 - -## 客户端 +以下是 Linux、Bash、Python 3.12 的文件客户端环境。它可以只用 CPU;首次获取源码和安装依赖需要网络许可,不下载模型权重。模型及其运行环境在服务端单独准备。 ```bash -# 浏览器 -open client_mic.html - -# Python 麦克风 -python client_python.py --server ws://localhost:10095 --mic - -# Python 文件 -python client_python.py --server ws://localhost:10095 --file audio.wav - -# 自动化测试 -python client_test.py --server ws://localhost:10095 --file audio.wav +set -eu +git clone https://github.com/QwenAudio/Fun-ASR.git +cd Fun-ASR +python3.12 -m venv .venv-client +source .venv-client/bin/activate +python -m pip install 'numpy==1.26.4' 'soundfile==0.13.1' 'librosa==0.11.0' 'websockets==16.0' +python -m pip check ``` -## 远程访问 +## 发送一段文件 + +留在同一终端和仓库根目录。用仓库自带的 [六秒 WAV](../runtime/llama.cpp/tests/sample.wav) 先走通流程,再换成自己有权发送的本地文件。已备齐依赖和音频时,客户端不需要再去模型站下载,但仍须能连到指定服务。 ```bash -ssh -L 10095:localhost:10095 -# 然后本地打开 client_mic.html +SERVER='ws://127.0.0.1:10095' +AUDIO='runtime/llama.cpp/tests/sample.wav' +python client_python.py --server "$SERVER" --file "$AUDIO" --response-timeout 60 ``` -## 功能 - -- **vLLM 推理引擎**:RTF < 0.08,支持 tensor parallel 多卡加速 -- **流式 VAD 分句**:动态静音阈值,自然断句 -- **说话人分离 (Beta)**:流式 ID 分配 + 最终重聚类 -- **热词定制化**:加载人名、地名等实体词文件 -- **语种指定**:31 种语言 + 中文方言 -- **幻觉检测**:自动检测重复模式并截断 - -## 文件列表 - -| 文件 | 说明 | -|------|------| -| `serve_realtime_ws.py` | WebSocket 服务端 | -| `client_mic.html` | 浏览器客户端 | -| `client_python.py` | Python CLI 客户端 | -| `client_test.py` | 自动化测试脚本 | -| `热词列表` | 热词文件示例 | -| `demo_vllm.py` | 离线 vLLM 推理 demo | +运行时可能先显示临时文字。只有全部音频发送完毕、客户端请求停止后收到 `is_final: true` 且含 `sentences` 列表的结果,才显示 `Done.` 并以 0 退出。列表可以为空:服务完成了请求,不等于检测到了语音。不要把临时文字、仅有的 `stopped` 通知或正常断线当作完整转写。 -## 详细文档 +- `--response-timeout` 是正的有限秒数,默认 60。它分别限制等待启动确认、可选热词确认和发送 `STOP` 后等待最终结果的时间,不限制整段录音的发送时长。 +- 可选 `--hotwords '张三,北京'` 会在音频前发送热词。服务没有确认启动或热词时,客户端不会开始发送音频。 +- 出错或超时是非零退出。先核对协议、端口和服务日志;服务在 `STOP` 后可能仍在解码,不要无条件重发同一录音。手动中断文件模式也不算成功。 +- `--file` 和 `--mic` 只能选一个。文件模式不需要麦克风权限;只有在用户明确授权录音时才选麦克风模式。有浏览器交互需求时可另看 [浏览器客户端](../client_mic.html)。 -- [FunASR vLLM 推理引擎指南](https://github.com/modelscope/FunASR/blob/main/docs/vllm_guide.md) — 完整文档(离线/流式/WebSocket/API/FAQ) +客户端协议由生成的 WAV 和本地 WebSocket 回复测试覆盖;这些测试不测识别准确率或服务延迟。服务端的连接保活参数 `--ws-ping-interval` 和 `--ws-ping-timeout` 与上述文件结果超时是不同的设置,详见[服务端源码](../serve_realtime_ws.py)。 diff --git a/tests/test_file_client_session.py b/tests/test_file_client_session.py new file mode 100644 index 00000000..8d3fa50d --- /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] / "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