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 .github/workflows/native-transformers-examples.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
103 changes: 84 additions & 19 deletions 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
81 changes: 24 additions & 57 deletions docs/realtime_demo.md
Original file line number Diff line number Diff line change
@@ -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 <server>
# 然后本地打开 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)。
Loading
Loading