Merge pull request #3111 from xinnan-tech/py-test-wake

test测试页面唤醒功能
This commit is contained in:
wengzh
2026-05-12 11:00:58 +08:00
committed by GitHub
118 changed files with 2723 additions and 78 deletions
+5 -1
View File
@@ -187,4 +187,8 @@ uploadfile
!main/manager-mobile/**/env/
!main/manager-mobile/**/.env*
!main/manager-mobile/**/*.json
!main/xiaozhi-server/**/*.json
!main/xiaozhi-server/**/*.json
!main/digital-human/**/*.json
main/digital-human/wakeword_runtime/models
main/digital-human/wakeword_runtime/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01
sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2
+1 -1
View File
@@ -226,7 +226,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 工具名称 | 位置 | 使用方法 | 功能说明 |
|:---:|:---|:---:|:---:|
| 音频交互测试工具 | main》xiaozhi-server》test》test_page.html | 使用谷歌浏览器直接打开 | 测试音频播放和接收功能,验证Python端音频处理是否正常 |
| 音频交互测试工具 | main》digital-human》index.html | 在 `main/digital-human` 执行 `python start.py` 后访问 `http://127.0.0.1:8006/index.html` | 测试音频播放和接收功能,验证Python端音频处理是否正常 |
| 模型响应测试工具 | main》xiaozhi-server》performance_tester.py | 执行 `python performance_tester.py` | 测试ASR(语音识别)、LLM(大模型)、VLLM(视觉模型)、TTS(语音合成)三个核心模块的响应速度 |
> 💡 提示:测试模型速度时,只会测试配置了密钥的模型。
+1 -1
View File
@@ -224,7 +224,7 @@ Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfun
| Werkzeugname | Standort | Verwendungsmethode | Funktionsbeschreibung |
|:---:|:---|:---:|:---:|
| Audio-Interaktionstesttool | main》xiaozhi-server》test》test_page.html | Direkt mit Google Chrome öffnen | Testet Audio-Wiedergabe- und Empfangsfunktionen, überprüft, ob die Python-seitige Audioverarbeitung normal ist |
| Audio-Interaktionstesttool | main》digital-human》index.html | In `main/digital-human` `python start.py` ausführen und dann `http://127.0.0.1:8006/index.html` öffnen | Testet Audio-Wiedergabe- und Empfangsfunktionen, überprüft, ob die Python-seitige Audioverarbeitung normal ist |
| Modell-Reaktionstesttool | main》xiaozhi-server》performance_tester.py | Ausführen `python performance_tester.py` | Testet die Reaktionsgeschwindigkeit von ASR (Spracherkennung), LLM (großes Modell), VLLM (Vision-Modell), TTS (Sprachsynthese) drei Kernmodulen |
> 💡 Hinweis: Beim Testen der Modellgeschwindigkeit werden nur Modelle mit konfigurierten Schlüsseln getestet.
+1 -1
View File
@@ -224,7 +224,7 @@ This project provides the following testing tools to help you verify the system
| Tool Name | Location | Usage Method | Function Description |
|:---:|:---|:---:|:---:|
| Audio Interaction Test Tool | main》xiaozhi-server》test》test_page.html | Open directly with Google Chrome | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
| Audio Interaction Test Tool | main》digital-human》index.html | Run `python start.py` in `main/digital-human`, then open `http://127.0.0.1:8006/index.html` | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
| Model Response Test Tool | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Tests response speed of three core modules: ASR(speech recognition), LLM(large model), VLLM(vision model), TTS(speech synthesis) |
> 💡 Note: When testing model speed, only models with configured keys will be tested.
+1 -1
View File
@@ -224,7 +224,7 @@ Este projeto fornece as seguintes ferramentas de teste para ajudá-lo a verifica
| Nome da Ferramenta | Localização | Método de Uso | Descrição da Função |
|:---:|:---|:---:|:---:|
| Ferramenta de Teste de Interação por Áudio | main》xiaozhi-server》test》test_page.html | Abrir diretamente com Google Chrome | Testa as funções de reprodução e recepção de áudio, verifica se o processamento de áudio no lado Python está normal |
| Ferramenta de Teste de Interação por Áudio | main》digital-human》index.html | Execute `python start.py` em `main/digital-human` e depois abra `http://127.0.0.1:8006/index.html` | Testa as funções de reprodução e recepção de áudio, verifica se o processamento de áudio no lado Python está normal |
| Ferramenta de Teste de Resposta de Modelo | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Testa a velocidade de resposta dos três módulos principais: ASR(reconhecimento de fala), LLM(modelo de linguagem), VLLM(modelo de visão), TTS(síntese de voz) |
> 💡 Nota: Ao testar a velocidade dos modelos, apenas os modelos com chaves configuradas serão testados.
+1 -1
View File
@@ -225,7 +225,7 @@ Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác m
| Tên công cụ | Vị trí | Phương pháp sử dụng | Mô tả chức năng |
|:---:|:---|:---:|:---:|
| Công cụ kiểm tra tương tác âm thanh | main》xiaozhi-server》test》test_page.html | Mở trực tiếp bằng trình duyệt Google Chrome | Kiểm tra chức năng phát và nhận âm thanh, xác minh xử lý âm thanh phía Python có bình thường không |
| Công cụ kiểm tra tương tác âm thanh | main》digital-human》index.html | Chạy `python start.py` trong `main/digital-human`, sau đó mở `http://127.0.0.1:8006/index.html` | Kiểm tra chức năng phát và nhận âm thanh, xác minh xử lý âm thanh phía Python có bình thường không |
| Công cụ kiểm tra phản hồi mô hình | main》xiaozhi-server》performance_tester.py | Thực hiện `python performance_tester.py` | Kiểm tra tốc độ phản hồi của ba module cốt lõi ASR(Nhận dạng giọng nói), LLM(Mô hình lớn), VLLM(Mô hình thị giác), TTS(Tổng hợp giọng nói) |
> 💡 Gợi ý: Khi kiểm tra tốc độ mô hình, chỉ kiểm tra các mô hình đã cấu hình khóa.
+1 -1
View File
@@ -241,7 +241,7 @@ LLM:
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-OTA接口是 http://192.168.4.123:8003/xiaozhi/ota/
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-Websocket地址是 ws://192.168.4.123:8000/xiaozhi/v1/
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-=======上面的地址是websocket协议地址,请勿用浏览器访问=======
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-如想测试websocket请用谷歌浏览器打开test目录下的test_page.html
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-如想测试websocket请启动digital-human模块,打开浏览器交互测试
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-=======================================================
```
+2 -2
View File
@@ -198,7 +198,7 @@ docker logs -f xiaozhi-esp32-server
```
25-02-23 12:01:09[core.websocket_server] - INFO - Websocket地址是 ws://xxx.xx.xx.xx:8000/xiaozhi/v1/
25-02-23 12:01:09[core.websocket_server] - INFO - =======上面的地址是websocket协议地址,请勿用浏览器访问=======
25-02-23 12:01:09[core.websocket_server] - INFO - 如想测试websocket请用谷歌浏览器打开test目录下的test_page.html
25-02-23 12:01:09[core.websocket_server] - INFO - 如想测试websocket请启动digital-human模块,打开浏览器交互测试
25-02-23 12:01:09[core.websocket_server] - INFO - =======================================================
```
@@ -431,7 +431,7 @@ python app.py
```
25-02-23 12:01:09[core.websocket_server] - INFO - Server is running at ws://xxx.xx.xx.xx:8000/xiaozhi/v1/
25-02-23 12:01:09[core.websocket_server] - INFO - =======上面的地址是websocket协议地址,请勿用浏览器访问=======
25-02-23 12:01:09[core.websocket_server] - INFO - 如想测试websocket请用谷歌浏览器打开test目录下的test_page.html
25-02-23 12:01:09[core.websocket_server] - INFO - 如想测试websocket请启动digital-human模块,打开浏览器交互测试
25-02-23 12:01:09[core.websocket_server] - INFO - =======================================================
```
+442
View File
@@ -0,0 +1,442 @@
# 一体机数字人配置指南
本项目用于在 x86 架构设备(如迷你主机、工控机、普通电脑等)上部署一套完整的数字人展示系统,实现以下功能:
- 开机自动进入 Kiosk 全屏浏览器,展示指定网页
- 后台运行唤醒词检测服务,支持语音交互
> **说明**:本文档以 **Intel N100 迷你主机(天虹 QN10-100B4)** 为例进行部署演示,其他 x86 设备可参考调整(注意网络配置和声卡设备差异)。
## 适用环境
| 项目 | 说明 |
|------|------|
| 示例硬件 | 天虹 QN10-100B4Intel N100 |
| 操作系统 | Ubuntu 24.04 LTS (Noble Numbat) |
| 示例用户 | xz(请根据实际情况替换) |
| 网络 | Wi-Fi 连接,固定 IP(可按需改为有线) |
## 部署流程
1. 系统初始化(换源、连网)
2. 安装图形组件与 Kiosk 浏览器
3. 配置自动登录与图形界面
4. 部署唤醒词服务(Python 环境 + 麦克风)
5. 优化开机速度与隐藏启动信息
---
### 系统初始化(换源、连网)
```
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sudo tee /etc/apt/sources.list > /dev/null <<EOF
deb http://mirrors.aliyun.com/ubuntu/ noble main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ noble main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ noble-security main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ noble-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ noble-updates main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ noble-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ noble-proposed main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ noble-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ noble-backports main restricted universe multiverse
# deb-src http://mirrors.aliyun.com/ubuntu/ noble-backports main restricted universe multiverse
EOF
echo 'Acquire::ForceIPv4 "true";' | sudo tee /etc/apt/apt.conf.d/99force-ipv4
```
安装网络管理工具(若已存在可忽略)
Bash
```
sudo apt update
sudo apt install network-manager -y
sudo systemctl start NetworkManager
sudo systemctl enable NetworkManager
```
设置wifi密码,固定ip
> **提醒**:以下命令中的 Wi-Fi 名称、密码、IP 地址均为示例,请务必替换为你自己的实际信息。
Bash
```
sudo nmcli device wifi connect "MERCURY_1812" password "12345678"
sudo nmcli connection modify "MERCURY_1812" ipv4.addresses "192.168.0.86/24" ipv4.gateway "192.168.0.1" ipv4.dns "8.8.8.8,114.114.114.114" ipv4.method "manual"
sudo nmcli connection up "MERCURY_1812"
```
### 第一步:安装核心图形组件与浏览器
这里我们坚持“极简主义”,坚决不装多余的桌面环境(如 GNOME/KDE),只装底层驱动、最轻量的窗口管理器(Openbox)、隐藏鼠标工具以及 Chromium 浏览器。
Bash
```
sudo timedatectl set-timezone Asia/Shanghai
sudo apt install net-tools vim fonts-wqy-microhei fonts-wqy-zenhei alsa-utils pulseaudio -y
sudo apt install --no-install-recommends xserver-xorg x11-xserver-utils xinit openbox unclutter -y
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo apt install ./google-chrome-stable_current_amd64.deb -y
rm google-chrome-stable_current_amd64.deb
sudo apt purge snapd -y
```
### 第二步:配置 TTY1 开机免密自动登录
为了避免手动输入账号密码的尴尬,我们通过修改 systemd 服务,让系统一开机就自动以 `xz` 的身份登录。这里使用一键写入命令,彻底避开由于 `nano``vi` 操作不当导致的保存失败问题。
**1. 创建配置目录:**
Bash
```
sudo mkdir -p /etc/systemd/system/getty@tty1.service.d/
```
**2. 写入自动登录规则:**
Bash
```
echo -e "[Service]\nExecStart=\nExecStart=-/sbin/agetty --autologin xz --noclear %I \$TERM" | sudo tee /etc/systemd/system/getty@tty1.service.d/override.conf
```
**3. 重载服务并设置默认启动目标:**
Bash
```
sudo systemctl daemon-reload
sudo systemctl set-default multi-user.target
```
### 第三步:配置登录后自动启动图形界面
系统自动登录后默认停留在黑底白字的命令行,我们需要配置脚本,让它一旦登录立马启动 X11 图形环境。
**1. 触发 `startx` 的启动逻辑:**
直接将触发代码追加写入你的个人环境配置文件中:
Bash
```
cat << 'EOF' >> ~/.bash_profile
if [ -z "$DISPLAY" ] && [ "$(fgconsole)" -eq 1 ]; then
exec startx
fi
EOF
```
**2. 告诉 `startx` 去启动 Openbox**
Bash
```
echo "exec openbox-session" > ~/.xinitrc
```
### 第四步:配置“铜墙铁壁”的 Openbox 与浏览器
这是最核心的一步:关闭屏幕休眠、隐藏鼠标、全屏锁定浏览器,并写一个“死循环”保证浏览器被意外关闭后也能瞬间复活。
**1. 创建 Openbox 配置目录:**
Bash
```
mkdir -p ~/.config/openbox
```
**2. 写入自启动脚本 (`autostart`)**
复制以下整段代码并回车(这会自动把所有保护规则写进文件里):
Bash
```
cat << 'EOF' > ~/.config/openbox/autostart
# 关闭屏幕保护
xset -dpms
xset s noblank
xset s off
# 隐藏鼠标
unclutter -idle 0.1 -root &
# 死循环启动 Chromium(崩溃或被关也能秒重启)
while true; do
google-chrome \
--kiosk \
--no-first-run \
--no-default-browser-check \
--disable-infobars \
--disable-session-crashed-bubble \
--disable-translate \
--disable-external-intent-requests \
--autoplay-policy=no-user-gesture-required \
--use-fake-ui-for-media-stream \
"https://www.douyin.com"
sleep 2
done &
EOF
```
**3. 屏蔽 `Alt+F4` 退出快捷键:**
为了防止别人插上键盘强行关掉窗口,我们把 Openbox 默认的系统快捷键干掉。
Bash
```
cp /etc/xdg/openbox/rc.xml ~/.config/openbox/
sed -i '/<keybind key="A-F4">/,/<\/keybind>/d' ~/.config/openbox/rc.xml
```
### 第五步:重启验收成果
如果拔掉网线或不需要等待所有网络上线,可禁用网络等待服务,避免开机卡顿
Bash
```
sudo systemctl mask systemd-networkd-wait-online.service
sudo systemctl mask NetworkManager-wait-online.service
```
隐藏开机信息(GRUB
Bash
```
sudo sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT=.*/GRUB_CMDLINE_LINUX_DEFAULT="quiet loglevel=3 systemd.show_status=false vt.global_cursor_default=0"/g' /etc/default/grub
echo 'GRUB_TIMEOUT_STYLE="hidden"' | sudo tee -a /etc/default/grub
echo 'GRUB_RECORDFAIL_TIMEOUT=0' | sudo tee -a /etc/default/grub
sudo update-grub
```
声音设置成100%,然后 重启:
Bash
```
amixer -q sset Master 100% unmute
sudo reboot
```
### 部署唤醒词服务
在一体机上部署唤醒词检测服务,需要安装 Python 环境、上传项目文件、配置 Camera 麦克风和开机自启。
#### 1. 安装 Miniconda
```bash
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh -b -p $HOME/miniconda3
~/miniconda3/bin/conda init bash
source ~/.bashrc
rm Miniconda3-latest-Linux-x86_64.sh
```
确保登录时自动进入conda环境
```bash
if ! grep -q '.bashrc' ~/.bash_profile; then
cat << 'EOF' >> ~/.bash_profile
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
EOF
fi
```
#### 2. 创建 Python 虚拟环境
```bash
conda create -n test python=3.10 -y
conda activate test
```
若出现 Terms of Service have not been accepted 错误,执行:
```bash
conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main
conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r
```
#### 3. 上传项目文件
将开发机上的 `main/digital-human/` 整个目录上传到一体机的 `~/digital-human/` 目录:
```bash
# 在开发机上执行(将 <一体机IP> 替换为实际 IP
scp -r main/digital-human/ xz@<一体机IP>:~/digital-human/
```
#### 4. 安装系统依赖
唤醒词服务需要音频采集库和 ALSA PulseAudio 插件:
```bash
sudo apt install libportaudio2 portaudio19-dev libasound2-plugins -y
```
#### 5. 安装 Python 依赖
```bash
cd ~/digital-human/wakeword_runtime
pip install numpy
pip install -r requirements.txt
```
#### 6. 下载唤醒词模型
模型文件不包含在项目中,需要单独下载配置,详见 [docs/digital-human-wakeword.md](digital-human-wakeword.md) 中的“模型下载”章节。
#### 7. 修改 Openbox 自启动脚本
需要在 autostart 中加上 PulseAudio 和 Camera 麦克风配置,并将 Chrome 地址改为测试页面。
先确认 Camera 麦克风在 PulseAudio 中的设备名:
```bash
pulseaudio --start
pactl list sources short
```
找到包含 `USB_Camera` 的那一行,记下完整名称,例如:
```
alsa_input.usb-SN0002_2K_USB_Camera_46435000_P030D00_SN0002-02.mono-fallback
```
然后用完整内容覆盖 autostart(将 `TARGET_MIC` 替换为你的实际设备名):
```bash
cat << 'EOF' > ~/.config/openbox/autostart
# 1. 启动声音服务并稍作等待
pulseaudio --start
sleep 1
# 2. 锁定 Camera 的麦克风(请替换为你的实际设备名)
TARGET_MIC="alsa_input.usb-SN0002_2K_USB_Camera_46435000_P030D00_SN0002-02.mono-fallback"
# 3. 设为系统默认麦克风
pactl set-default-source "$TARGET_MIC"
# 4. 解除静音
pactl set-source-mute "$TARGET_MIC" 0
# 5. 音量拉到 100%
pactl set-source-volume "$TARGET_MIC" 100%
# --- 极简桌面与浏览器环境配置 ---
# 关闭屏幕保护
xset -dpms
xset s noblank
xset s off
# 隐藏鼠标
unclutter -idle 0.1 -root &
# 死循环启动浏览器(崩溃或被关也能秒重启)
while true; do
google-chrome \
--kiosk \
--no-first-run \
--no-default-browser-check \
--disable-infobars \
--disable-session-crashed-bubble \
--disable-translate \
--disable-external-intent-requests \
--autoplay-policy=no-user-gesture-required \
--use-fake-ui-for-media-stream \
"http://127.0.0.1:8006/index.html"
sleep 2
done &
EOF
```
#### 8. 配置唤醒词服务开机自启
创建 systemd 服务文件,让唤醒词服务开机自动运行。
先确认当前用户的 UID
```bash
id -u $(whoami)
```
然后用查到的 UID 替换下面 `1000`(通常第一个用户就是 1000):
```bash
sudo tee /etc/systemd/system/digital-human.service << 'EOF'
[Unit]
Description=Digital Human Runtime
After=network.target sound.target
[Service]
Type=simple
User=xz
Environment=XDG_RUNTIME_DIR=/run/user/1000
Environment=PULSE_SERVER=unix:/run/user/1000/pulse/native
WorkingDirectory=/home/xz/digital-human
ExecStartPre=/bin/sleep 10
ExecStart=/home/xz/miniconda3/envs/test/bin/python start.py
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
EOF
```
> **重要说明**
> - `User=xz` — 替换为你的实际用户名
> - `/run/user/1000` — 替换为你实际的 UID
> - `WorkingDirectory` 和 `ExecStart` 中的路径 — 替换为你的实际部署路径
> - `Environment` 中的 PulseAudio 环境变量**必须保留**,否则唤醒词服务和浏览器无法同时使用 Camera 麦克风
启用并启动服务:
```bash
sudo systemctl daemon-reload
sudo systemctl enable digital-human
sudo systemctl start digital-human
```
#### 9. 常用服务管理命令
```bash
sudo systemctl start digital-human # 立即启动
sudo systemctl stop digital-human # 停止
sudo systemctl restart digital-human # 重启
sudo systemctl status digital-human # 查看状态
journalctl -u digital-human -f # 查看实时日志
```
+220
View File
@@ -0,0 +1,220 @@
# 数字人唤醒词教程
## 概述
测试页面集成了基于 **Sherpa-ONNX** 的高精度语音唤醒功能,支持自定义唤醒词和实时检测。使用轻量级关键词检测模型,提供毫秒级响应速度。
## 唤醒词模型
### 模型下载(必需)
**重要说明**: 项目不包含模型文件,需要提前下载配置。
### 官方模型下载地址
- **官方模型列表**: <https://csukuangfj.github.io/sherpa/onnx/kws/pretrained_models/index.html>
- **推荐模型**: `sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01`
### 下载和配置步骤
#### 1. 下载模型包
```bash
# 方法1:直接下载(推荐)
cd main/digital-human/wakeword_runtime/
wget https://github.com/k2-fsa/sherpa-onnx/releases/download/kws-models/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2
# 解压
tar xvf sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2
# 方法2:使用ModelScope
pip install modelscope
python -c "
from modelscope import snapshot_download
snapshot_download('pkufool/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01', cache_dir='./models')
"
```
#### 2. 配置模型文件
模型包下载后包含以下文件:
```
sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01/
├── encoder-epoch-12-avg-2-chunk-16-left-64.int8.onnx # 速度优先
├── encoder-epoch-12-avg-2-chunk-16-left-64.onnx
├── encoder-epoch-99-avg-1-chunk-16-left-64.int8.onnx # 速度优先
├── encoder-epoch-99-avg-1-chunk-16-left-64.onnx # 精度优先
├── decoder-epoch-12-avg-2-chunk-16-left-64.onnx
├── decoder-epoch-99-avg-1-chunk-16-left-64.onnx # 精度优先
├── joiner-epoch-12-avg-2-chunk-16-left-64.int8.onnx # 速度优先
├── joiner-epoch-12-avg-2-chunk-16-left-64.onnx
├── joiner-epoch-99-avg-1-chunk-16-left-64.int8.onnx # 速度优先
├── joiner-epoch-99-avg-1-chunk-16-left-64.onnx # 精度优先
├── tokens.txt # Token映射表(必需)
├── keywords_raw.txt # 模型包里可能附带(可选,runtime 不依赖)
├── keywords.txt # 现成的
├── test_wavs/ # 测试音频(可选)
├── configuration.json # 模型元信息(可选)
└── README.md # 说明文档(可选)
```
#### 3. 选择配置方案
**方案一:精度优先(推荐)**
```bash
cd sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01
# 创建模型目录
mkdir -p ../models
# 复制精度优先的epoch-99 fp32三件套
cp encoder-epoch-99-avg-1-chunk-16-left-64.onnx ../models/encoder.onnx
cp decoder-epoch-99-avg-1-chunk-16-left-64.onnx ../models/decoder.onnx
cp joiner-epoch-99-avg-1-chunk-16-left-64.onnx ../models/joiner.onnx
# 复制配套文件
cp tokens.txt ../models/tokens.txt
# keywords_raw.txt 如果模型包里附带,可自行保留;runtime 不依赖它
```
**方案二:速度优先**
```bash
cd sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01
# 创建模型目录
mkdir -p ../models
# 复制速度优先的epoch-99 int8三件套
cp encoder-epoch-99-avg-1-chunk-16-left-64.int8.onnx ../models/encoder.onnx
cp decoder-epoch-99-avg-1-chunk-16-left-64.onnx ../models/decoder.onnx
cp joiner-epoch-99-avg-1-chunk-16-left-64.int8.onnx ../models/joiner.onnx
# 复制配套文件
cp tokens.txt ../models/tokens.txt
```
**注意事项**:
- **不要混用 fp32 与 int8**:三个模型文件必须保持一致的精度
- **优先选择 epoch-99**:比 epoch-12 训练更充分,精度更高
- **必需文件**`encoder.onnx` + `decoder.onnx` + `joiner.onnx` + `tokens.txt` + `keywords.txt`
### 最终模型文件结构
配置完成后,模型文件应放在 `wakeword_runtime/models/` 目录下,完整路径为 `main/digital-human/wakeword_runtime/models/`
```
wakeword_runtime/models/
├── encoder.onnx # 编码器模型(重命名后)
├── decoder.onnx # 解码器模型(重命名后)
├── joiner.onnx # 连接器模型(重命名后)
├── tokens.txt # 拼音 Token 映射表(228行版本)
├── keywords.txt # 关键词配置文件(首次启动自动生成)
└── keywords_raw.txt # 可选,runtime 不依赖
```
## 启动方式
`main/digital-human` 目录执行:
```bash
pip install -r wakeword_runtime/requirements.txt
python start.py
```
启动后默认地址:
- 页面地址:`http://127.0.0.1:8006/index.html`
- 事件桥地址:`ws://127.0.0.1:8006/wakeword-ws`
- 健康检查:`http://127.0.0.1:8006/health`
停止方式:
- 在运行终端按 `Ctrl+C`
- 会同时停止静态页面服务、事件桥和唤醒词检测流程
## 配置文件说明
配置文件位于 [main/digital-human/wakeword_runtime/config.json](../main/digital-human/wakeword_runtime/config.json)。
当前主要配置项:
```json
{
"wakeword": {
"enabled": true
},
"model_dir": "models",
"audio": {
"input_device": null,
"sample_rate": 16000,
"channels": 1
},
"detector": {
"num_threads": 4,
"provider": "cpu",
"max_active_paths": 2,
"keywords_score": 1.8,
"keywords_threshold": 0.1,
"num_trailing_blanks": 1,
"cooldown_seconds": 1.5
},
"logging": {
"level": "INFO",
"dir": "logs",
"file": "wakeword-runtime.log"
}
}
```
各字段含义:
| 参数 | 说明 |
| --- | --- |
| `wakeword.enabled` | 是否启用本地唤醒词检测 |
| `model_dir` | 模型和词表所在目录 |
| `audio.input_device` | 麦克风输入设备,默认使用系统默认设备 |
| `audio.sample_rate` | 采样率,默认 `16000` |
| `audio.channels` | 声道数,默认 `1` |
| `detector.num_threads` | 检测器线程数 |
| `detector.provider` | 推理 provider,当前通常为 `cpu` |
| `detector.max_active_paths` | 搜索路径数 |
| `detector.keywords_score` | 关键词增强分数 |
| `detector.keywords_threshold` | 检测阈值 |
| `detector.num_trailing_blanks` | 尾随空白数量 |
| `detector.cooldown_seconds` | 连续触发冷却时间 |
| `logging.level` | 日志等级 |
| `logging.dir` | 日志目录 |
| `logging.file` | 日志文件名 |
## 推荐使用流程
### 首次使用
1. 准备 `models/` 目录下的模型文件和 `tokens.txt`
2. 确认 `models/keywords.txt` 存在
3.`digital-human` 目录运行 `python start.py`
4. 浏览器打开 `http://127.0.0.1:8006/index.html`
5. 进入设置页检查“唤醒词”配置
### 修改唤醒词
1. 打开数字人页面设置
2. 切到“唤醒词”页签
3. 修改启用状态或唤醒词列表
4. 点击“应用唤醒词”
5. 根据提示决定是否立即重启
### 禁用唤醒词
1. 将“启用本地唤醒词”改成禁用
2. 点击“应用唤醒词”
3. 建议立即重启一次
禁用后:
- 页面与事件桥仍然可用
- 唤醒词检测不会继续运行
+2 -2
View File
@@ -13,9 +13,9 @@ http://192.168.1.25:8003/xiaozhi/ota/
```
如果显示“OTA接口运行正常,向设备发送的websocket地址是:ws://xxx:8000/xiaozhi/v1/
你可以使用项目自带的`test_page.html`测试一下,是否能连上ota页面输出的websocket地址。
你可以启动`digital-human`模块后打开`index.html`测试一下,是否能连上ota页面输出的websocket地址。
如果访问不到,你需要到配置文件`.config.yaml`里修改`server.websocket`的地址,重启后再重新测试,直到`test_page.html`能正常访问。
如果访问不到,你需要到配置文件`.config.yaml`里修改`server.websocket`的地址,重启后再重新测试,直到`index.html`能正常访问。
成功后,请往下进行第2步
+1 -1
View File
@@ -118,7 +118,7 @@ mcp_endpoint: ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=def
250705[__main__]-INFO-mcp接入点是 ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=abc
250705[__main__]-INFO-Websocket地址是 ws://192.168.1.25:8000/xiaozhi/v1/
250705[__main__]-INFO-=======上面的地址是websocket协议地址,请勿用浏览器访问=======
250705[__main__]-INFO-如想测试websocket请用谷歌浏览器打开test目录下的test_page.html
250705[__main__]-INFO-如想测试websocket请启动digital-human模块,打开浏览器交互测试
250705[__main__]-INFO-=============================================================
```
+1 -1
View File
@@ -23,7 +23,7 @@
250705[__main__]-INFO-mcp接入点是 ws://192.168.1.25:8004/mcp_endpoint/mcp/?token=abc
250705[__main__]-INFO-Websocket地址是 ws://192.168.1.25:8000/xiaozhi/v1/
250705[__main__]-INFO-=======上面的地址是websocket协议地址,请勿用浏览器访问=======
250705[__main__]-INFO-如想测试websocket请用谷歌浏览器打开test目录下的test_page.html
250705[__main__]-INFO-如想测试websocket请启动digital-human模块,打开浏览器交互测试
250705[__main__]-INFO-=============================================================
```
+2 -2
View File
@@ -58,7 +58,7 @@ docker restart xiaozhi-esp32-server
2025-06-01 **** - 视觉分析接口是 http://192.168.4.7:8003/mcp/vision/explain
2025-06-01 **** - Websocket地址是 ws://192.168.4.7:8000/xiaozhi/v1/
2025-06-01 **** - =======上面的地址是websocket协议地址,请勿用浏览器访问=======
2025-06-01 **** - 如想测试websocket请用谷歌浏览器打开test目录下的test_page.html
2025-06-01 **** - 如想测试websocket请启动digital-human模块,打开浏览器交互测试
2025-06-01 **** - =============================================================
```
@@ -133,7 +133,7 @@ docker restart xiaozhi-esp32-server
2025-06-01 **** - 视觉分析接口是 http://192.168.4.7:8003/mcp/vision/explain
2025-06-01 **** - Websocket地址是 ws://192.168.4.7:8000/xiaozhi/v1/
2025-06-01 **** - =======上面的地址是websocket协议地址,请勿用浏览器访问=======
2025-06-01 **** - 如想测试websocket请用谷歌浏览器打开test目录下的test_page.html
2025-06-01 **** - 如想测试websocket请启动digital-human模块,打开浏览器交互测试
2025-06-01 **** - =============================================================
```
+1 -1
View File
@@ -91,7 +91,7 @@ TTS:
```py
python app.py
```
打开test目录下的test_page.html,测试连接和发送消息时paddlespeech端是否有输出日志
启动`main/digital-human`下的`python start.py`后,打开`http://127.0.0.1:8006/index.html`,测试连接和发送消息时paddlespeech端是否有输出日志
输出日志参考:
```
+52 -1
View File
@@ -9,6 +9,7 @@
* [3.2. `manager-api` (管理后端 - Java Spring Boot实现)](#32-manager-api-管理后端---java-spring-boot实现)
* [3.3. `manager-web` (Web管理前端 - Vue.js实现)](#33-manager-web-web管理前端---vuejs实现)
* [3.4. `manager-mobile` (移动管理端 - uni-app+Vue3实现)](#34-manager-mobile-移动管理端---uni-appvue3实现)
* [3.5. `digital-human` (数字人测试模块 - Python+Web实现)](#35-digital-human-数字人测试模块---pythonweb实现)
4. [数据流与交互机制](#4-数据流与交互机制)
5. [核心功能概要](#5-核心功能概要)
6. [部署与配置概述](#6-部署与配置概述)
@@ -67,6 +68,13 @@
* 基于alova + @alova/adapter-uniapp实现网络请求,与manager-api无缝集成。
* 使用pinia进行状态管理,确保数据一致性。
6. **`digital-human` (数字人测试模块 - Python+Web实现):**
这是一个独立的数字人测试模块,提供本地测试页面、前端交互资源、唤醒词运行时与事件桥能力,用于联调整个数字人交互链路。其主要能力包括:
* 提供浏览器端的数字人测试页面,用于验证音频播放、接收和交互流程。
* 集成本地唤醒词运行时,支持基于Sherpa-ONNX的关键词检测。
* 通过事件桥将页面状态与本地运行时打通,便于调试唤醒词触发与交互效果。
* 作为独立模块与`xiaozhi-server``manager-web``manager-api`并列,便于单独开发和部署。
**高层交互流程概述:**
* **语音交互主线:** **ESP32设备**捕捉到用户语音后,通过**WebSocket**将音频数据实时传输给**`xiaozhi-server`**。`xiaozhi-server`完成一系列AI处理(VAD、ASR、LLM交互、TTS)后,再通过WebSocket将合成的语音回复发送回ESP32设备进行播放。所有与语音直接相关的实时交互均在此链路完成。
@@ -80,7 +88,8 @@ xiaozhi-esp32-server
├─ xiaozhi-server 8000 端口 Python语言开发 负责与esp32通信
├─ manager-web 8001 端口 Node.js+Vue开发 负责提供控制台的web界面
├─ manager-api 8002 端口 Java语言开发 负责提供控制台的api
─ manager-mobile 跨平台移动应用 uni-app+Vue3开发 负责提供移动版智控台管理
─ manager-mobile 跨平台移动应用 uni-app+Vue3开发 负责提供移动版智控台管理
└─ digital-human 数字人测试模块 Python+Web实现 负责本地测试页面、唤醒词运行时与事件桥
```
---
@@ -366,6 +375,48 @@ xiaozhi-esp32-server
---
### 3.5. `digital-human` (数字人测试模块 - Python+Web实现)
`digital-human` 组件是一个独立的数字人测试模块,负责提供本地测试页面、页面资源、唤醒词运行时和事件桥能力。它主要用于联调整个数字人交互链路,帮助开发者验证页面交互、音频能力和本地唤醒词流程。
* **核心目标:**
* 提供独立的本地测试页面,用于验证数字人交互效果。
* 提供本地唤醒词运行时,支持关键词检测与事件上报。
* 为前端页面和本地运行时提供事件桥,打通测试链路。
* 以独立模块形式存在,便于单独开发、调试和部署。
* **核心技术栈:**
* **Python 3:** 作为测试运行时的主要语言,负责启动本地服务、管理唤醒词运行时和事件桥。
* **原生HTML/CSS/JavaScript:** 用于构建数字人测试页面与交互逻辑。
* **Sherpa-ONNX:** 用于本地唤醒词检测。
* **ThreadingHTTPServer / WebSocket桥接:** 用于承载测试页面、健康检查和本地事件通信。
* **关键实现细节:**
1. **模块入口与页面资源:**
* `start.py` 是模块启动入口,负责初始化测试运行时。
* `index.html` 是数字人测试页面入口。
* `js/``css/``images/``resources/` 目录提供页面脚本、样式和资源文件。
2. **本地测试运行时:**
* `wakeword_runtime/` 目录承载本地唤醒词运行时实现。
* 运行时负责配置加载、日志初始化、音频采集、关键词检测和服务生命周期管理。
* 模块默认通过本地HTTP服务暴露页面地址、事件桥地址和健康检查接口。
3. **唤醒词检测链路:**
* 基于Sherpa-ONNX关键词检测模型,支持本地唤醒词触发。
* 模型文件和关键词配置位于 `wakeword_runtime/models/` 及相应配置文件中。
* 页面侧可结合事件桥观察唤醒词服务状态和触发结果。
4. **调试与联调定位:**
* 启动后可通过浏览器访问本地页面,验证音频播放、接收和交互逻辑。
* 通过事件桥可以将唤醒词状态同步到页面,便于排查本地链路问题。
* 详细的模型下载、运行时配置和使用说明已整理在 `docs/digital-human-wakeword.md` 中。
`digital-human` 的存在使得数字人相关能力可以脱离主服务独立验证,降低了页面调试、唤醒词联调和本地环境搭建的复杂度。
---
## 4. 数据流与交互机制
`xiaozhi-esp32-server` 系统通过各组件间定义清晰的数据流和交互协议来协同工作。主要的通信方式依赖于针对实时交互优化的WebSocket协议和适用于客户端-服务器请求的RESTful API。
+58 -1
View File
@@ -9,6 +9,7 @@
* [3.2. `manager-api` (Management Backend - Java Spring Boot Implementation)](#32-manager-api-management-backend---java-spring-boot-implementation)
* [3.3. `manager-web` (Web Management Frontend - Vue.js Implementation)](#33-manager-web-web-management-frontend---vuejs-implementation)
* [3.4. `manager-mobile` (Mobile Management Console - uni-app Implementation)](#34-manager-mobile-mobile-management-console---uniapp-implementation)
* [3.5. `digital-human` (Digital Human Test Module - Python+Web Implementation)](#35-digital-human-digital-human-test-module---pythonweb-implementation)
4. [Data Flow and Interaction Mechanisms](#4-data-flow-and-interaction-mechanisms)
5. [Key Features Summary](#5-key-features-summary)
6. [Deployment and Configuration Overview](#6-deployment-and-configuration-overview)
@@ -60,6 +61,21 @@ The `xiaozhi-esp32-server` system adopts a **distributed, multi-component collab
* (Potential functionality) Monitoring system operation status, viewing logs, troubleshooting, etc.
* Comprehensive interaction with all backend management functions provided by `manager-api`.
5. **`manager-mobile` (Mobile Management Console - uni-app Implementation):**
This is a cross-platform mobile management application based on uni-app v3 + Vue 3 + Vite, supporting App (Android & iOS) and WeChat Mini Program. Its main capabilities include:
* Providing a convenient management interface on mobile devices, similar in functionality to manager-web but optimized for mobile platforms.
* Supporting core functions such as user login, device management, and AI service configuration.
* Cross-platform adaptation, allowing a single codebase to run on iOS, Android, and WeChat Mini Programs.
* Integrating with `manager-api` through alova + `@alova/adapter-uniapp`.
* Using pinia for state management to ensure data consistency.
6. **`digital-human` (Digital Human Test Module - Python+Web Implementation):**
This is an independent digital human test module that provides a local test page, frontend interaction resources, a wake word runtime, and an event bridge for end-to-end debugging of the digital human interaction flow. Its main capabilities include:
* Providing a browser-based digital human test page for validating audio playback, audio reception, and interaction flow.
* Integrating a local wake word runtime with keyword detection based on Sherpa-ONNX.
* Bridging page state and the local runtime through an event bridge to simplify wake word debugging.
* Existing as a standalone module alongside `xiaozhi-server`, `manager-web`, and `manager-api`, making independent development and deployment easier.
**High-Level Interaction Flow Overview:**
* **Voice Interaction Main Line:** After the **ESP32 device** captures user voice, it transmits audio data in real-time to **`xiaozhi-server`** through **WebSocket**. After `xiaozhi-server` completes a series of AI processing (VAD, ASR, LLM interaction, TTS), it sends the synthesized voice response back to the ESP32 device for playback through WebSocket. All real-time interactions directly related to voice are completed in this link.
@@ -73,7 +89,8 @@ xiaozhi-esp32-server
├─ xiaozhi-server Port 8000 Python development Responsible for ESP32 communication
├─ manager-web Port 8001 Node.js+Vue development Responsible for providing web interface for console
├─ manager-api Port 8002 Java development Responsible for providing console API
─ manager-mobile Cross-platform mobile application uni-app+Vue3 development Responsible for providing mobile console management
─ manager-mobile Cross-platform mobile application uni-app+Vue3 development Responsible for providing mobile console management
└─ digital-human Digital human test module Python+Web implementation Responsible for local test page, wake word runtime, and event bridge
```
---
@@ -257,6 +274,46 @@ The `manager-mobile` component is a cross-platform mobile management application
`manager-mobile` provides users with a fully functional, smooth mobile management tool through the application of these technologies, allowing administrators to perform system management and configuration anytime, anywhere.
### 3.5. `digital-human` (Digital Human Test Module - Python+Web Implementation)
The `digital-human` component is an independent digital human test module responsible for providing a local test page, page resources, a wake word runtime, and an event bridge. It is primarily used to debug the complete digital human interaction flow and to validate frontend interaction, audio capability, and local wake word behavior.
* **Core Objectives:**
* Provide an independent local test page for validating digital human interaction effects.
* Provide a local wake word runtime for keyword detection and event reporting.
* Provide an event bridge between the frontend page and the local runtime to connect the test flow.
* Exist as a standalone module for easier independent development, debugging, and deployment.
* **Core Technologies:**
* **Python 3:** Used for the local test runtime, service startup, wake word lifecycle management, and event bridge coordination.
* **Native HTML/CSS/JavaScript:** Used to build the digital human test page and interaction logic.
* **Sherpa-ONNX:** Used for local wake word keyword detection.
* **ThreadingHTTPServer / WebSocket bridge:** Used to serve the local page, health check endpoint, and event communication.
* **Key Implementation Aspects:**
1. **Module Entry and Page Resources:**
* `start.py` is the module entry point responsible for starting the local test runtime.
* `index.html` is the entry page for digital human testing.
* The `js/`, `css/`, `images/`, and `resources/` directories provide frontend scripts, styles, and static resources.
2. **Local Test Runtime:**
* The `wakeword_runtime/` directory contains the local wake word runtime implementation.
* The runtime is responsible for configuration loading, logging initialization, audio capture, keyword detection, and lifecycle management.
* The module exposes a local page URL, event bridge URL, and health check endpoint through a local HTTP service.
3. **Wake Word Detection Flow:**
* Uses Sherpa-ONNX keyword detection models to support local wake word triggering.
* Model files and keyword configurations are stored in `wakeword_runtime/models/` and related configuration files.
* The page can observe runtime state and trigger results through the event bridge.
4. **Debugging and Integration Positioning:**
* After startup, developers can open the local page in a browser to validate playback, reception, and interaction logic.
* The event bridge synchronizes wake word state to the page, which helps with local debugging.
* Detailed model download, runtime configuration, and usage instructions are documented in `docs/digital-human-wakeword.md`.
The `digital-human` module allows digital human related capabilities to be validated independently from the main service, reducing the complexity of page debugging, wake word integration, and local environment setup.
---
## 4. Data Flow and Interaction Mechanisms
+46
View File
@@ -0,0 +1,46 @@
本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3)
如需查看一体机数字人落地部署、Kiosk 全屏启动和系统环境配置,[点击这里查看一体机部署指南](../../docs/all-in-one-digital-human-setup.md)
如需查看唤醒词模型下载、运行时配置和详细使用说明,[点击这里查看唤醒词专题文档](../../docs/digital-human-wakeword.md)
# 项目介绍
digital-human 是独立的数字人测试模块,负责提供本地测试页面、前端交互资源、唤醒词运行时和事件桥能力,用于联调整个数字人交互链路。
# 快速启动
安装依赖:
```bash
pip install -r wakeword_runtime/requirements.txt
```
启动模块:
```bash
python start.py
```
# 访问地址
启动后可访问:
- 页面地址:http://127.0.0.1:8006/index.html
- 事件桥地址:ws://127.0.0.1:8006/wakeword-ws
- 健康检查:http://127.0.0.1:8006/health
# 目录说明
- `start.py`:模块启动入口
- `index.html`:数字人测试页面入口
- `wakeword_runtime`:本地唤醒词运行时与配置目录
- `js``css`:页面前端脚本与样式
- `images``resources`:页面资源文件
# 相关文档
- 一体机部署指南:适用于 x86 设备整机落地部署、Kiosk 展示和开机自启动配置
[../../docs/all-in-one-digital-human-setup.md](../../docs/all-in-one-digital-human-setup.md)
- 唤醒词专题文档:适用于唤醒词模型下载、运行时配置和本地调试说明
[../../docs/digital-human-wakeword.md](../../docs/digital-human-wakeword.md)

Before

Width:  |  Height:  |  Size: 185 B

After

Width:  |  Height:  |  Size: 185 B

@@ -812,6 +812,20 @@ body {
font-size: 14px;
}
.config-item textarea {
width: 100%;
padding: 12px;
border: 1px solid #40444b;
border-radius: 6px;
background: #40444b;
color: white;
min-height: 100px;
resize: vertical;
box-sizing: border-box;
font-family: inherit;
font-size: 14px;
}
.model-select {
width: 100%;
padding: 10px 40px 10px 14px;

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Before

Width:  |  Height:  |  Size: 136 KiB

After

Width:  |  Height:  |  Size: 136 KiB

Before

Width:  |  Height:  |  Size: 321 KiB

After

Width:  |  Height:  |  Size: 321 KiB

Before

Width:  |  Height:  |  Size: 290 KiB

After

Width:  |  Height:  |  Size: 290 KiB

@@ -4,8 +4,8 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>小智服务器测试页面</title>
<link rel="stylesheet" href="css/test_page.css?v=0205">
<title>小智数字人页面</title>
<link rel="stylesheet" href="css/index.css?v=0206">
<script>
// 检测是否使用file://协议打开
if (window.location.protocol === 'file:') {
@@ -21,14 +21,14 @@
warningDiv.innerHTML = `
<h2>⚠️ 警告:请使用HTTP服务器打开此页面</h2>
<p>您当前使用的是本地文件方式打开页面(file://协议),这可能导致页面功能异常。</p>
<p>您可以使用nginx映射启动测试页面,也可以请按照以下步骤使用python启动测试http服务</p>
<p>您可以使用nginx映射启动小智数字人页面,也可以请按照以下步骤启动测试运行时</p>
<ol>
<li>打开命令行终端</li>
<li>命令行进入到 xiaozhi-server/test 目录</li>
<li>执行以下命令启动HTTP服务器</li>
<li>命令行进入到 digital-human 目录</li>
<li>执行以下命令启动小智数字人页面运行时</li>
</ol>
<pre>python -m http.server 8006</pre>
<p>然后在浏览器中访问:<strong>http://localhost:8006/test_page.html</strong></p>
<pre>python start.py</pre>
<p>然后在浏览器中访问:<strong>http://localhost:8006/index.html</strong></p>
`;
document.body.appendChild(warningDiv);
});
@@ -137,6 +137,7 @@
<div class="modal-body">
<div class="settings-tabs">
<button class="tab-btn active" data-tab="device">设备配置</button>
<button class="tab-btn" data-tab="wakeword">唤醒词</button>
<button class="tab-btn" data-tab="mcp">MCP工具</button>
<button class="tab-btn" data-tab="other">数字人皮肤</button>
</div>
@@ -162,6 +163,15 @@
placeholder="deviceName">
</div>
</div>
<div class="config-row">
<div class="config-item">
<label for="emojiEnabled">情绪表情:</label>
<select id="emojiEnabled" class="model-select">
<option value="true">启用</option>
<option value="false">禁用</option>
</select>
</div>
</div>
</div>
</div>
@@ -184,6 +194,37 @@
</div>
</div>
<div class="tab-content" id="wakewordTab">
<div class="config-panel">
<div class="control-panel">
<div class="config-row">
<div class="config-item">
<label for="wakewordEnabled">启用本地唤醒词:</label>
<select id="wakewordEnabled" class="model-select">
<option value="true">启用</option>
<option value="false">禁用</option>
</select>
</div>
</div>
<div class="config-row">
<div class="config-item">
<label for="wakewordWsUrl">唤醒词服务地址:</label>
<input type="text" id="wakewordWsUrl" placeholder="ws://127.0.0.1:8006/wakeword-ws">
</div>
</div>
<div class="config-row">
<div class="config-item">
<label for="wakewordList">唤醒词配置 (一行一个):</label>
<textarea id="wakewordList" placeholder="例如:&#10;小智小智&#10;你好小智"></textarea>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn-primary" id="applyWakewordBtn">应用唤醒词</button>
</div>
</div>
</div>
</div>
<div class="tab-content" id="mcpTab">
<!-- MCP 工具管理区域 -->
<div class="mcp-tools-container">
@@ -3,6 +3,7 @@ import { checkOpusLoaded, initOpusEncoder } from './core/audio/opus-codec.js?v=0
import { getAudioPlayer } from './core/audio/player.js?v=0205';
import { checkMicrophoneAvailability, isHttpNonLocalhost } from './core/audio/recorder.js?v=0205';
import { initMcpTools } from './core/mcp/tools.js?v=0205';
import { startWakewordBridgeListener } from './core/network/wakeword-bridge.js?v=0205';
import { uiController } from './ui/controller.js?v=0205';
import { log } from './utils/logger.js?v=0205';
@@ -43,6 +44,8 @@ class App {
await this.audioPlayer.start();
// 初始化MCP工具
initMcpTools();
// 初始化本地唤醒事件监听
startWakewordBridgeListener();
// 检查麦克风可用性
await this.checkMicrophoneAvailability();
// 检查摄像头可用性
@@ -1,5 +1,8 @@
// 配置管理模块
// 默认唤醒词列表
export const DEFAULT_WAKE_WORDS = '你好小智\n你好小志\n小爱同学\n你好小鑫\n你好小新\n小美同学\n小龙小龙\n喵喵同学\n小滨小滨\n小冰小冰\n嘿你好呀';
// 生成随机MAC地址
function generateRandomMac() {
const hexDigits = '0123456789ABCDEF';
@@ -19,6 +22,9 @@ export function loadConfig() {
const deviceNameInput = document.getElementById('deviceName');
const clientIdInput = document.getElementById('clientId');
const otaUrlInput = document.getElementById('otaUrl');
const wakewordWsUrlInput = document.getElementById('wakewordWsUrl');
const wakewordEnabledInput = document.getElementById('wakewordEnabled');
const wakewordListInput = document.getElementById('wakewordList');
// 从localStorage加载MAC地址,如果没有则生成新的
let savedMac = localStorage.getItem('xz_tester_deviceMac');
@@ -43,6 +49,29 @@ export function loadConfig() {
if (savedOtaUrl) {
otaUrlInput.value = savedOtaUrl;
}
const savedWakewordWsUrl = localStorage.getItem('xz_tester_wakewordWsUrl');
if (savedWakewordWsUrl !== null && wakewordWsUrlInput) {
wakewordWsUrlInput.value = savedWakewordWsUrl;
}
const savedWakewordEnabled = localStorage.getItem('xz_tester_wakewordEnabled');
if (savedWakewordEnabled !== null && wakewordEnabledInput) {
wakewordEnabledInput.value = savedWakewordEnabled;
}
const savedWakewordList = localStorage.getItem('xz_tester_wakewordList');
if (savedWakewordList !== null && wakewordListInput) {
wakewordListInput.value = savedWakewordList;
} else if (wakewordListInput) {
wakewordListInput.value = DEFAULT_WAKE_WORDS;
}
const emojiEnabledInput = document.getElementById('emojiEnabled');
const savedEmojiEnabled = localStorage.getItem('xz_tester_emojiEnabled');
if (savedEmojiEnabled !== null && emojiEnabledInput) {
emojiEnabledInput.value = savedEmojiEnabled;
}
}
// 保存配置
@@ -50,10 +79,26 @@ export function saveConfig() {
const deviceMacInput = document.getElementById('deviceMac');
const deviceNameInput = document.getElementById('deviceName');
const clientIdInput = document.getElementById('clientId');
const wakewordWsUrlInput = document.getElementById('wakewordWsUrl');
const wakewordEnabledInput = document.getElementById('wakewordEnabled');
const wakewordListInput = document.getElementById('wakewordList');
localStorage.setItem('xz_tester_deviceMac', deviceMacInput.value);
localStorage.setItem('xz_tester_deviceName', deviceNameInput.value);
localStorage.setItem('xz_tester_clientId', clientIdInput.value);
const emojiEnabledInput = document.getElementById('emojiEnabled');
if (emojiEnabledInput) {
localStorage.setItem('xz_tester_emojiEnabled', emojiEnabledInput.value);
}
if (wakewordEnabledInput) {
localStorage.setItem('xz_tester_wakewordEnabled', wakewordEnabledInput.value);
}
if (wakewordListInput) {
localStorage.setItem('xz_tester_wakewordList', wakewordListInput.value);
}
if (wakewordWsUrlInput && wakewordWsUrlInput.value.trim()) {
localStorage.setItem('xz_tester_wakewordWsUrl', wakewordWsUrlInput.value.trim());
}
}
// 获取配置值
@@ -62,12 +107,14 @@ export function getConfig() {
const deviceMac = document.getElementById('deviceMac')?.value.trim() || '';
const deviceName = document.getElementById('deviceName')?.value.trim() || '';
const clientId = document.getElementById('clientId')?.value.trim() || '';
const emojiEnabled = document.getElementById('emojiEnabled')?.value !== 'false';
return {
deviceId: deviceMac, // 使用MAC地址作为deviceId
deviceName,
deviceMac,
clientId
clientId,
emojiEnabled
};
}
@@ -203,17 +203,6 @@ export class AudioRecorder {
async start() {
if (this.isRecording) return false;
try {
// Check if WebSocketHandler instance exists
const { getWebSocketHandler } = await import('../network/websocket.js?v=0205');
const wsHandler = getWebSocketHandler();
// If machine is speaking, send abort message
if (wsHandler && wsHandler.isRemoteSpeaking && wsHandler.currentSessionId) {
const abortMessage = { session_id: wsHandler.currentSessionId, type: 'abort', reason: 'wake_word_detected' };
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
this.websocket.send(JSON.stringify(abortMessage));
log('已发送中止消息', 'info');
}
}
if (!this.initEncoder()) {
log('无法开始录音: Opus编码器初始化失败', 'error');
return false;
@@ -0,0 +1,225 @@
import { uiController } from '../../ui/controller.js?v=0205';
import { log } from '../../utils/logger.js?v=0205';
let wakewordSocket = null;
let reconnectTimer = null;
let reconnectAttempts = 0;
let shouldReconnect = true;
let wakewordRequestSeq = 0;
let onNextBridgeConnectedCallback = null;
const pendingWakewordRequests = new Map();
export function startWakewordBridgeListener() {
if (wakewordSocket) {
return wakewordSocket;
}
shouldReconnect = true;
log('正在连接本地唤醒事件桥...', 'info');
tryConnect();
return wakewordSocket;
}
function tryConnect() {
const bridgeUrl = buildWakewordBridgeUrl();
try {
wakewordSocket = new WebSocket(bridgeUrl);
wakewordSocket.onopen = () => {
reconnectAttempts = 0;
log(`本地唤醒事件桥已连接: ${bridgeUrl}`, 'success');
// 连接成功后自动保存地址,刷新后仍能记住
localStorage.setItem('xz_tester_wakewordWsUrl', bridgeUrl);
const urlInput = document.getElementById('wakewordWsUrl');
if (urlInput) urlInput.value = bridgeUrl;
};
wakewordSocket.onerror = () => {
log(`本地唤醒事件桥连接失败: ${bridgeUrl}`, 'error');
};
wakewordSocket.onmessage = async (event) => {
try {
const message = parseWakewordBridgeMessage(event.data);
if (message.requestId && pendingWakewordRequests.has(message.requestId)) {
settleWakewordRequest(message);
return;
}
if (message.success === false) {
log(`本地唤醒事件桥返回错误: ${message.error || '未知错误'}`, 'error');
return;
}
if (message.type === 'bridge_connected') {
log('本地唤醒监听已就绪', 'info');
if (onNextBridgeConnectedCallback) {
const cb = onNextBridgeConnectedCallback;
onNextBridgeConnectedCallback = null;
cb(message);
}
return;
}
if (message.type === 'service_ready') {
log('本地唤醒服务已启动', 'info');
return;
}
if (message.type === 'wakeword_config') {
uiController.applyWakewordConfig(message.payload || {});
log('已同步本地唤醒词配置', 'info');
return;
}
if (message.type === 'service_stopping') {
log('本地唤醒服务正在停止', 'warning');
return;
}
if (message.type === 'wake_word_detected') {
const wakeWord = message.payload?.wake_word || '唤醒词';
log(`检测到本地唤醒事件: ${wakeWord}`, 'info');
await uiController.triggerWakewordDial(wakeWord);
}
} catch (error) {
log(`解析本地唤醒事件失败: ${error.message}`, 'error');
}
};
wakewordSocket.onclose = () => {
if (wakewordSocket) {
wakewordSocket = null;
}
rejectAllWakewordRequests('本地唤醒事件桥已断开');
if (!shouldReconnect) {
return;
}
if (reconnectTimer) {
return;
}
reconnectAttempts += 1;
const delay = Math.min(1000 * reconnectAttempts, 5000);
log(`本地唤醒事件桥将在 ${delay}ms 后重连: ${bridgeUrl}`, 'warning');
reconnectTimer = window.setTimeout(() => {
reconnectTimer = null;
tryConnect();
}, delay);
};
return wakewordSocket;
} catch (error) {
log(`启动本地唤醒监听失败: ${error.message}`, 'error');
return null;
}
}
export function stopWakewordBridgeListener() {
shouldReconnect = false;
if (reconnectTimer) {
window.clearTimeout(reconnectTimer);
reconnectTimer = null;
}
if (!wakewordSocket) {
return;
}
wakewordSocket.onclose = null;
wakewordSocket.close();
wakewordSocket = null;
}
export function sendWakewordBridgeMessage(type, payload = {}, requestId = null) {
if (!wakewordSocket || wakewordSocket.readyState !== WebSocket.OPEN) {
log('本地唤醒事件桥未连接,无法发送消息', 'warning');
return false;
}
wakewordSocket.send(JSON.stringify({
type,
requestId,
payload,
}));
return true;
}
export function requestWakewordBridge(type, payload = {}, timeout = 5000) {
const requestId = `wakeword-${Date.now()}-${++wakewordRequestSeq}`;
return new Promise((resolve, reject) => {
const timer = window.setTimeout(() => {
pendingWakewordRequests.delete(requestId);
reject(new Error('本地唤醒服务响应超时'));
}, timeout);
pendingWakewordRequests.set(requestId, { resolve, reject, timer });
if (!sendWakewordBridgeMessage(type, payload, requestId)) {
window.clearTimeout(timer);
pendingWakewordRequests.delete(requestId);
reject(new Error('本地唤醒事件桥未连接'));
}
});
}
export function getWakewordBridgeUrl() {
if (wakewordSocket && wakewordSocket.url) {
return wakewordSocket.url;
}
return buildWakewordBridgeUrl();
}
export function onNextBridgeConnected(callback) {
onNextBridgeConnectedCallback = callback;
}
function buildWakewordBridgeUrl() {
const configured = localStorage.getItem('xz_tester_wakewordWsUrl');
if (configured && configured.trim()) {
return configured.trim();
}
return 'ws://127.0.0.1:8006/wakeword-ws';
}
function parseWakewordBridgeMessage(rawData) {
const message = JSON.parse(rawData);
return {
type: message.type || '',
requestId: message.requestId || null,
success: message.success !== false,
payload: message.payload || {},
error: message.error || null,
};
}
function settleWakewordRequest(message) {
const pendingRequest = pendingWakewordRequests.get(message.requestId);
if (!pendingRequest) {
return;
}
window.clearTimeout(pendingRequest.timer);
pendingWakewordRequests.delete(message.requestId);
if (message.success === false) {
pendingRequest.reject(new Error(message.error || '本地唤醒服务返回失败'));
return;
}
pendingRequest.resolve(message);
}
function rejectAllWakewordRequests(errorMessage) {
pendingWakewordRequests.forEach((pendingRequest) => {
window.clearTimeout(pendingRequest.timer);
pendingRequest.reject(new Error(errorMessage));
});
pendingWakewordRequests.clear();
}
@@ -34,7 +34,8 @@ export class WebSocketHandler {
device_mac: config.deviceMac,
token: config.token,
features: {
mcp: true
mcp: true,
emoji: config.emojiEnabled
}
};
@@ -70,6 +71,28 @@ export class WebSocketHandler {
}
}
_sendWakeupMessages(sessionId) {
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) return;
// listen detect
this.websocket.send(JSON.stringify({
session_id: sessionId,
type: 'listen',
state: 'detect',
text: '嘿,你好呀'
}));
log('发送listen detect消息,唤醒词: 嘿,你好呀', 'info');
// listen start:开始监听
this.websocket.send(JSON.stringify({
session_id: sessionId,
type: 'listen',
state: 'start',
mode: 'auto'
}));
log('发送listen start消息', 'info');
}
// 处理文本消息
handleTextMessage(message) {
if (message.type === 'hello') {
@@ -77,6 +100,9 @@ export class WebSocketHandler {
window.cameraAvailable = true;
log('连接成功,摄像头已可用', 'success');
uiController.updateDialButton(true);
this._sendWakeupMessages(message.session_id);
uiController.startAIChatSession();
} else if (message.type === 'tts') {
this.handleTTSMessage(message);
@@ -2,7 +2,9 @@
import { loadConfig, saveConfig } from '../config/manager.js?v=0205';
import { getAudioPlayer } from '../core/audio/player.js?v=0205';
import { getAudioRecorder } from '../core/audio/recorder.js?v=0205';
import { requestWakewordBridge, stopWakewordBridgeListener, startWakewordBridgeListener, getWakewordBridgeUrl, onNextBridgeConnected } from '../core/network/wakeword-bridge.js?v=0205';
import { getWebSocketHandler } from '../core/network/websocket.js?v=0205';
import { log } from '../utils/logger.js?v=0205';
// UI controller class
class UIController {
@@ -14,6 +16,8 @@ class UIController {
this.currentBackgroundIndex = localStorage.getItem('backgroundIndex') ? parseInt(localStorage.getItem('backgroundIndex')) : 0;
this.backgroundImages = ['1.png', '2.png', '3.png'];
this.dialBtnDisabled = false;
this.isConnecting = false;
this.lastWakewordDialTime = 0;
// Bind methods
this.init = this.init.bind(this);
@@ -25,6 +29,9 @@ class UIController {
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
this.switchTab = this.switchTab.bind(this);
this.applyWakewordConfig = this.applyWakewordConfig.bind(this);
this.handleApplyWakeword = this.handleApplyWakeword.bind(this);
this.triggerWakewordDial = this.triggerWakewordDial.bind(this);
}
// Initialize
@@ -262,6 +269,11 @@ class UIController {
});
});
const applyWakewordBtn = document.getElementById('applyWakewordBtn');
if (applyWakewordBtn) {
applyWakewordBtn.addEventListener('click', this.handleApplyWakeword);
}
// 点击模态框背景关闭(仅对特定模态框禁用此功能)
const modals = document.querySelectorAll('.modal');
modals.forEach(modal => {
@@ -512,6 +524,121 @@ class UIController {
}
}
applyWakewordConfig(config = {}) {
const wakewordEnabledInput = document.getElementById('wakewordEnabled');
const wakewordListInput = document.getElementById('wakewordList');
if (!wakewordEnabledInput || !wakewordListInput) {
return;
}
const wakeWords = Array.isArray(config.wakeWords)
? config.wakeWords.filter(item => typeof item === 'string' && item.trim())
: [];
wakewordEnabledInput.value = config.enabled === false ? 'false' : 'true';
wakewordListInput.value = wakeWords.join('\n');
saveConfig();
}
async handleApplyWakeword() {
const wakewordEnabledInput = document.getElementById('wakewordEnabled');
const wakewordListInput = document.getElementById('wakewordList');
const wakewordWsUrlInput = document.getElementById('wakewordWsUrl');
if (!wakewordEnabledInput || !wakewordListInput) {
return;
}
const wakeWords = wakewordListInput.value
.split(/\r?\n/u)
.map(item => item.trim())
.filter(Boolean)
.filter((item, index, items) => items.indexOf(item) === index);
const payload = {
enabled: wakewordEnabledInput.value !== 'false',
wakeWords,
};
if (payload.enabled && payload.wakeWords.length === 0) {
this.addChatMessage('启用唤醒词时,至少需要填写一个唤醒词。', false);
return;
}
const applyWakewordBtn = document.getElementById('applyWakewordBtn');
if (applyWakewordBtn) {
applyWakewordBtn.disabled = true;
applyWakewordBtn.textContent = '应用中...';
}
try {
// 保存地址到 localStorage
if (wakewordWsUrlInput && wakewordWsUrlInput.value.trim()) {
localStorage.setItem('xz_tester_wakewordWsUrl', wakewordWsUrlInput.value.trim());
}
// 比较新地址和当前连接地址
const newWsUrl = localStorage.getItem('xz_tester_wakewordWsUrl');
const currentWsUrl = getWakewordBridgeUrl();
const urlChanged = newWsUrl !== currentWsUrl;
if (urlChanged) {
// 地址变了,先确认
const shouldRestart = window.confirm('地址已变更,是否继续?(将断开旧连接并重新连接)');
if (!shouldRestart) {
// 恢复 localStorage 里的旧地址
localStorage.setItem('xz_tester_wakewordWsUrl', currentWsUrl);
this.addChatMessage('已取消地址变更。', false);
return;
}
// 断开旧连接
stopWakewordBridgeListener();
// 启动新连接(自动用新地址)
startWakewordBridgeListener();
// 等 bridge_connected
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('连接新服务器超时'));
}, 5000);
onNextBridgeConnected(() => {
clearTimeout(timeout);
resolve();
});
});
// 发配置和重启
await requestWakewordBridge('set_wakeword_config', payload);
this.applyWakewordConfig(payload);
await requestWakewordBridge('restart_wakeword_service');
this.addChatMessage('唤醒词配置已保存,唤醒词服务正在重启。', false);
} else {
// 地址没变:直接在当前连接操作
const response = await requestWakewordBridge('set_wakeword_config', payload);
this.applyWakewordConfig(response.payload || payload);
const shouldRestart = window.confirm('唤醒词已保存。是否现在重启唤醒词服务以立即生效?');
if (!shouldRestart) {
this.addChatMessage('唤醒词配置已保存,可稍后手动重启服务后生效。', false);
return;
}
await requestWakewordBridge('restart_wakeword_service');
this.addChatMessage('唤醒词配置已保存,唤醒词服务正在重启。', false);
}
} catch (error) {
this.addChatMessage(`应用唤醒词失败: ${error.message}`, false);
} finally {
if (applyWakewordBtn) {
applyWakewordBtn.disabled = false;
applyWakewordBtn.textContent = '应用唤醒词';
}
}
}
// Start AI chat session after connection
startAIChatSession() {
this.addChatMessage('连接成功,开始聊天吧~😊', false);
@@ -550,47 +677,51 @@ class UIController {
// Handle connect button click
async handleConnect() {
console.log('handleConnect called');
// Switch to device settings tab
this.switchTab('device');
// Wait for DOM update
await new Promise(resolve => setTimeout(resolve, 50));
const otaUrlInput = document.getElementById('otaUrl');
console.log('otaUrl element:', otaUrlInput);
if (!otaUrlInput || !otaUrlInput.value) {
this.addChatMessage('请输入OTA服务器地址', false);
const wsHandler = getWebSocketHandler();
if (this.isConnecting || (wsHandler && wsHandler.isConnected())) {
log('连接已存在或正在进行,忽略本次拨号请求', 'info');
return;
}
const otaUrl = otaUrlInput.value;
console.log('otaUrl value:', otaUrl);
// Update dial button state to connecting
const dialBtn = document.getElementById('dialBtn');
if (dialBtn) {
dialBtn.classList.add('dial-active');
dialBtn.querySelector('.btn-text').textContent = '连接中...';
dialBtn.disabled = true;
}
// Show connecting message
this.addChatMessage('正在连接服务器...', false);
const chatIpt = document.getElementById('chatIpt');
if (chatIpt) {
chatIpt.style.display = 'flex';
}
this.isConnecting = true;
console.log('handleConnect called');
try {
// Switch to device settings tab
this.switchTab('device');
// Wait for DOM update
await new Promise(resolve => setTimeout(resolve, 50));
const otaUrlInput = document.getElementById('otaUrl');
console.log('otaUrl element:', otaUrlInput);
if (!otaUrlInput || !otaUrlInput.value) {
this.addChatMessage('请输入OTA服务器地址', false);
return;
}
const otaUrl = otaUrlInput.value;
console.log('otaUrl value:', otaUrl);
// Update dial button state to connecting
const dialBtn = document.getElementById('dialBtn');
if (dialBtn) {
dialBtn.classList.add('dial-active');
dialBtn.querySelector('.btn-text').textContent = '连接中...';
dialBtn.disabled = true;
}
// Show connecting message
this.addChatMessage('正在连接服务器...', false);
const chatIpt = document.getElementById('chatIpt');
if (chatIpt) {
chatIpt.style.display = 'flex';
}
// Get WebSocket handler instance
const wsHandler = getWebSocketHandler();
// Register connection state callback BEFORE connecting
wsHandler.onConnectionStateChange = (isConnected) => {
this.updateConnectionUI(isConnected);
@@ -670,9 +801,36 @@ class UIController {
dialBtn.classList.remove('dial-active');
console.log('Dial button state restored successfully');
}
} finally {
this.isConnecting = false;
}
}
async triggerWakewordDial(wakeWord = '唤醒词') {
const wsHandler = getWebSocketHandler();
const now = Date.now();
if (wsHandler && wsHandler.isConnected()) {
log('页面已连接,忽略自动拨号', 'info');
return false;
}
if (this.isConnecting || this.dialBtnDisabled) {
log('页面正在连接中,忽略重复唤醒', 'info');
return false;
}
if (now - this.lastWakewordDialTime < 3000) {
log('唤醒触发过于频繁,忽略本次自动拨号', 'warning');
return false;
}
this.lastWakewordDialTime = now;
this.addChatMessage(`检测到唤醒词“${wakeWord}”,准备连接服务器...`, false);
await this.handleConnect();
return true;
}
// Add MCP tool
addMCPTool() {
const mcpToolsList = document.getElementById('mcpToolsList');
+55
View File
@@ -0,0 +1,55 @@
import threading
from pathlib import Path
from wakeword_runtime.config import load_config, setup_logging
from wakeword_runtime.runtime import TestRuntimeApplication, TestRuntimeHttpServer
def main() -> int:
test_root = Path(__file__).resolve().parent
runtime_root = test_root / "wakeword_runtime"
config = load_config(runtime_root)
setup_logging(config.log_file, config.log_level)
http_server = TestRuntimeHttpServer(test_root)
app_lock = threading.RLock()
app = TestRuntimeApplication(config, http_server.event_bridge)
def restart_runtime() -> None:
nonlocal app
with app_lock:
app.shutdown()
next_config = load_config(runtime_root)
setup_logging(next_config.log_file, next_config.log_level)
next_app = TestRuntimeApplication(next_config, http_server.event_bridge)
next_app.setup()
next_app.start()
app = next_app
http_server.set_restart_handler(restart_runtime)
print(f"test runtime started: {http_server.page_url}")
print(f"wakeword bridge websocket: {http_server.bridge_url}")
print(f"wakeword enabled: {config.wakeword_enabled}")
print("press Ctrl+C to stop")
try:
with app_lock:
try:
app.setup()
app.start()
except Exception as e:
print(f"警告: 唤醒词服务启动失败({e}),测试页面仍可正常使用")
http_server.serve_forever()
except KeyboardInterrupt:
print("test runtime stopped")
finally:
with app_lock:
app.shutdown()
http_server.shutdown()
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1 @@
"""Test-side wakeword runtime package."""
@@ -0,0 +1 @@
from .event_bridge import WakewordEventBridge
@@ -0,0 +1,106 @@
import json
import logging
import queue
import threading
import time
from typing import Any
logger = logging.getLogger(__name__)
class WakewordEventBridge:
def __init__(self) -> None:
self._clients: list[queue.Queue[str]] = []
self._clients_lock = threading.Lock()
self._running = True
@property
def is_running(self) -> bool:
return self._running
def build_ready_message(self) -> str:
return self.build_message(
"bridge_connected",
{"status": "ready"},
)
def publish_detected(self, wake_word: str) -> None:
self.publish(
"wake_word_detected",
{
"wake_word": wake_word,
"timestamp": time.time(),
},
)
def publish(self, event_type: str, payload: dict[str, Any] | None = None) -> None:
if not self._running:
return
message = self.build_message(event_type, payload or {})
with self._clients_lock:
clients = list(self._clients)
stale_clients: list[queue.Queue[str]] = []
for client_queue in clients:
try:
client_queue.put_nowait(message)
except queue.Full:
stale_clients.append(client_queue)
if stale_clients:
with self._clients_lock:
for client_queue in stale_clients:
if client_queue in self._clients:
self._clients.remove(client_queue)
def add_client(self) -> queue.Queue[str]:
client_queue: queue.Queue[str] = queue.Queue(maxsize=16)
with self._clients_lock:
self._clients.append(client_queue)
return client_queue
def build_message(
self,
event_type: str,
payload: dict[str, Any] | None = None,
request_id: str | None = None,
success: bool = True,
error: str | None = None,
) -> str:
message: dict[str, Any] = {
"type": event_type,
"requestId": request_id,
"success": success,
"payload": payload or {},
}
if error:
message["error"] = error
return json.dumps(message, ensure_ascii=False)
def remove_client(self, client_queue: queue.Queue[str]) -> None:
with self._clients_lock:
if client_queue in self._clients:
self._clients.remove(client_queue)
def publish_service_ready(self) -> None:
self.publish("service_ready", {"status": "ready"})
def publish_service_stopping(self) -> None:
self.publish("service_stopping", {"status": "stopping"})
def close(self) -> None:
if not self._running:
return
self.publish_service_stopping()
self._running = False
with self._clients_lock:
clients = list(self._clients)
self._clients.clear()
for client_queue in clients:
try:
client_queue.put_nowait("__bridge_closed__")
except queue.Full:
pass
@@ -0,0 +1,25 @@
{
"wakeword": {
"enabled": true
},
"model_dir": "models",
"audio": {
"input_device": null,
"sample_rate": 16000,
"channels": 1
},
"detector": {
"num_threads": 4,
"provider": "cpu",
"max_active_paths": 2,
"keywords_score": 1.8,
"keywords_threshold": 0.1,
"num_trailing_blanks": 1,
"cooldown_seconds": 1.5
},
"logging": {
"level": "INFO",
"dir": "logs",
"file": "wakeword-runtime.log"
}
}
@@ -0,0 +1,2 @@
from .config_loader import RuntimeConfig, load_config
from .logging_setup import setup_logging

Some files were not shown because too many files have changed in this diff Show More