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: 5 additions & 0 deletions .github/workflows/test-example-collection.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
Expand Down Expand Up @@ -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
Expand Down
103 changes: 84 additions & 19 deletions examples/industrial_data_pretraining/fun_asr_nano/client_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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", "")
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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]
Expand All @@ -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__":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

> 完整文档请参见:[FunASR vLLM 推理引擎指南](../../../../docs/vllm_guide.md)

## 30 秒启动
## 启动服务端

```bash
cd examples/industrial_data_pretraining/fun_asr_nano
Expand Down Expand Up @@ -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
Expand All @@ -103,7 +117,7 @@ ssh -L 10095:localhost:10095 <server>

## 功能

- **vLLM 推理引擎**:RTF < 0.08,支持 tensor parallel 多卡加速
- **vLLM 推理引擎**:支持 tensor parallel 多卡推理;实际速度取决于模型、设备和输入。
- **流式 VAD 分句**:动态静音阈值,自然断句
- **说话人分离 (Beta)**:流式 ID 分配 + 最终重聚类
- **热词定制化**:加载人名、地名等实体词文件
Expand Down
Loading
Loading