Spaces:
Runtime error
Runtime error
J.B-Lin commited on
Commit ·
50a87dc
1
Parent(s): a911bdf
[PregoPal] 2026-06-11 全双工语音对话开发阶段完成
Browse files## 核心改动
- API_BASE 修复: voice_helper 指向 PregoAPI(8090) 而非 llama-server(8081)
- server_name 改为 0.0.0.0:7889 (Tailscale 远程访问支持)
- 前端全双工 UI: CSS隐藏上传框 / JS自动触发录音 / 按钮状态切换
- docs/技术报告_2026-06-11.md: 完整技术文档 (含架构图/API/已知问题/下一步)
## 验证状态
- 后端链路验证通过: chat_voice(测试WAV) → AI中文回复 + TTS音频输出
- CDP前端交互验证: 按钮切换 / 自动录音 / 状态显示 均正常
- 三服务运行正常: PregoPal(7889) + PregoAPI(8090) + llama-server(8081)
- app.py +6 -2
- docs/技术报告_2026-06-11.md +333 -0
- rtm_task.json +69 -32
- ui/app_builder.py +166 -134
app.py
CHANGED
|
@@ -13,6 +13,10 @@ PregoPal - 孕期陪护AI助手
|
|
| 13 |
data/ ← 数据存储
|
| 14 |
"""
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
import gradio as gr
|
| 17 |
from ui.app_builder import create_app
|
| 18 |
from loop import check_and_run_loop
|
|
@@ -28,8 +32,8 @@ if __name__ == "__main__":
|
|
| 28 |
# 创建并启动 Gradio 应用
|
| 29 |
demo = create_app(loop)
|
| 30 |
demo.launch(
|
| 31 |
-
server_name="
|
| 32 |
-
server_port=
|
| 33 |
share=False,
|
| 34 |
debug=False,
|
| 35 |
css=CUSTOM_CSS,
|
|
|
|
| 13 |
data/ ← 数据存储
|
| 14 |
"""
|
| 15 |
|
| 16 |
+
import os
|
| 17 |
+
os.environ['no_proxy'] = '127.0.0.1,localhost,gradio.app'
|
| 18 |
+
os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
|
| 19 |
+
os.environ['MINICPM_API_BASE'] = 'http://127.0.0.1:8090'
|
| 20 |
import gradio as gr
|
| 21 |
from ui.app_builder import create_app
|
| 22 |
from loop import check_and_run_loop
|
|
|
|
| 32 |
# 创建并启动 Gradio 应用
|
| 33 |
demo = create_app(loop)
|
| 34 |
demo.launch(
|
| 35 |
+
server_name="0.0.0.0",
|
| 36 |
+
server_port=7889,
|
| 37 |
share=False,
|
| 38 |
debug=False,
|
| 39 |
css=CUSTOM_CSS,
|
docs/技术报告_2026-06-11.md
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PregoPal 全双工语音对话开发 — 技术报告
|
| 2 |
+
|
| 3 |
+
> **作者**: Qclaw | **时间**: 2026-06-11 上午 | **项目**: 黑客松 — PregoPal 孕期陪护AI助手
|
| 4 |
+
> **目标**: 利用本地部署的 MiniCPM-o 4.5(RTX 4060Ti 16GB)实现全双工语音交互
|
| 5 |
+
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
## 0. 项目总体架构
|
| 9 |
+
|
| 10 |
+
```
|
| 11 |
+
┌──────────────────────────────┐ ┌──────────────────┐ ┌──────────────────────┐
|
| 12 |
+
│ PregoPal (Gradio 6.16) │────▶│ PregoAPI │────▶│ llama-server (omni) │
|
| 13 |
+
│ http://0.0.0.0:7889 │ │ http://127.0.0.1 │ │ http://127.0.0.1 │
|
| 14 |
+
│ Gradio 前端 + 业务逻辑 │ │ :8090 │ │ :8081 │
|
| 15 |
+
│ 全双工语音交互 │ │ FastAPI 代理 │ │ MiniCPM-o 4.5 推理 │
|
| 16 |
+
└──────────────────────────────┘ └──────────────────┘ └──────────────────────┘
|
| 17 |
+
▲ │ │
|
| 18 |
+
│ Gradio streaming API │ /v1/omni/voice_chat │
|
| 19 |
+
│ /stream (Audio chunk) │ /v1/omni/duplex_audio │ /v1/stream/omni_init
|
| 20 |
+
│ │ /v1/chat/completions │ /v1/stream/omni_prefill
|
| 21 |
+
└────────────────────────────────────┴────────────────────────────┘ /v1/stream/omni_decode
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
### 模型与硬件
|
| 25 |
+
- **模型**: MiniCPM-o 4.5(8B 多模态大模型),GGUF 格式
|
| 26 |
+
- **显存**: RTX 4060Ti 16GB,当前 ~10.9GB/16GB
|
| 27 |
+
- **TTS**: `token2wav_device=cpu`, `tts_gpu_layers=0`(TTS 由 CPU 处理,节省约 5GB 显存)
|
| 28 |
+
- **推理性能**: ~47 tok/s(纯文本)
|
| 29 |
+
|
| 30 |
+
### 关键技术参数
|
| 31 |
+
| 参数 | 值 |
|
| 32 |
+
|------|------|
|
| 33 |
+
| `media_type` | 2 |
|
| 34 |
+
| `use_tts` | True |
|
| 35 |
+
| 音频采样率 | 16kHz (输入) / 24kHz (TTS 输出) |
|
| 36 |
+
| Gradio 版本 | 6.16.0 |
|
| 37 |
+
| Python | trader_stable (3.11) |
|
| 38 |
+
| 全双工方案 | Audio.streaming + VAD 话轮检测 |
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
## 1. 已完成工作(Phase 1-6 + 修复)
|
| 43 |
+
|
| 44 |
+
### Phase 1: llama-server 全双工 API 验证 ✅
|
| 45 |
+
- llama-server 编译(`llama.cpp-omni` 分支)和部署
|
| 46 |
+
- omni_init / omni_prefill / omni_decode 端点验证
|
| 47 |
+
- 初始推理延迟 ~7-10s(完整流程)
|
| 48 |
+
|
| 49 |
+
### Phase 2-3: VoiceProcessor + ConversationManager ✅
|
| 50 |
+
- `core/voice_processor.py`: 音频预处理(16000Hz mono → WAV)
|
| 51 |
+
- `core/conversation_manager.py`: 对话状态管理/上下文历史/系统提示词(孕期陪护方向)
|
| 52 |
+
- `api/voice_helper.py`: chat_voice API 封装
|
| 53 |
+
|
| 54 |
+
### Phase 4-5: 全双工闭环 + PregoPal 业务逻辑 ✅
|
| 55 |
+
- PregoAPI (`api/go_server.py`): FastAPI 代理,webm→wav 转换
|
| 56 |
+
- app_builder.py: Gradio UI + 全双工语音面板
|
| 57 |
+
- config.py: 营养数据库/食谱模板
|
| 58 |
+
|
| 59 |
+
### Phase 6: 端到端测试 ✅
|
| 60 |
+
- 后端全链路验证通过:测试 WAV → chat_voice → AI 中文回复 + TTS 音频
|
| 61 |
+
- CDP 前端交互验证:按钮切换 / JS 自动触发录音 / CSS 隐藏上传框 / 状态文字显示
|
| 62 |
+
|
| 63 |
+
---
|
| 64 |
+
|
| 65 |
+
## 2. 前端全双工实现详解(app_builder.py)
|
| 66 |
+
|
| 67 |
+
### 2.1 核心组件
|
| 68 |
+
|
| 69 |
+
```
|
| 70 |
+
┌─────────────────────────────────────────────────────┐
|
| 71 |
+
│ PregoPal Gradio UI │
|
| 72 |
+
├─────────────────────────────────────────────────────┤
|
| 73 |
+
│ 🌸 PregoPal (标题) │
|
| 74 |
+
│ 🎛️ 语言切换 (中文/English) │
|
| 75 |
+
├─────────────────────────────────────────────────────┤
|
| 76 |
+
│ 🎙️ [点击开始全双工对话] ← 状态切换按钮 │
|
| 77 |
+
│ ↓ JS 自动触发 │
|
| 78 |
+
│ 🎤 [录制] ← Gradio Microphone(streaming) │
|
| 79 |
+
│ ↓ VAD 检测 (1s 静音阈值) │
|
| 80 |
+
│ 🎤 聆听中... ← 状态文本 │
|
| 81 |
+
│ ↓ /stream predict │
|
| 82 |
+
│ 💬 AI 对话 (Chatbot) ← AI 回复显示 │
|
| 83 |
+
│ ↓ TTS audio_output │
|
| 84 |
+
├─────────────────────────────────────────────────────┤
|
| 85 |
+
│ 📅 孕期阶段 / 营养关注 / 昨日饮食 / 家庭菜谱 │
|
| 86 |
+
├────────────────��────────────────────────────────────┤
|
| 87 |
+
│ 🍳🍗🥗 导航栏 │
|
| 88 |
+
└─────────────────────────────────────────────────────┘
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
### 2.2 全双工交互流程
|
| 92 |
+
```
|
| 93 |
+
用户点击 [开始]
|
| 94 |
+
│
|
| 95 |
+
▼
|
| 96 |
+
JS 代码:
|
| 97 |
+
│ 1. 按钮文字变 "🔴 结束对话"
|
| 98 |
+
│ 2. 600ms 后自动点击 mic button (document.querySelector('.record-button'))
|
| 99 |
+
│
|
| 100 |
+
▼
|
| 101 |
+
Gradio Audio.streaming 开始:
|
| 102 |
+
│ 3. 浏览器麦克风流式发送音频块 (每 ~0.5s)
|
| 103 |
+
│
|
| 104 |
+
▼
|
| 105 |
+
handle_stream_chunk(audio_chunk):
|
| 106 |
+
│ 4. VAD 检测(能量阈值 + 静音计时器)
|
| 107 |
+
│ - 有声: 追加到缓冲区
|
| 108 |
+
│ - 静音 > 1s: 触发后端处理
|
| 109 |
+
│
|
| 110 |
+
▼
|
| 111 |
+
chat_voice(buffer):
|
| 112 |
+
│ 5. /v1/omni/voice_chat → PregoAPI:8090
|
| 113 |
+
│ 6. PregoAPI 调用 llama-server:
|
| 114 |
+
│ omni_init → omni_prefill → omni_decode
|
| 115 |
+
│ 7. 返回 {text, audio_base64}
|
| 116 |
+
│
|
| 117 |
+
▼
|
| 118 |
+
UI 更新:
|
| 119 |
+
│ 8. AI 文本 → Chatbot
|
| 120 |
+
│ 9. TTS → audio_output 播放
|
| 121 |
+
│ 10. 等待下一轮输入
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
### 2.3 JS 自动触发录音关键代码
|
| 125 |
+
```javascript
|
| 126 |
+
setTimeout(() => {
|
| 127 |
+
let micBtns = document.querySelectorAll('button');
|
| 128 |
+
for (let b of micBtns) {
|
| 129 |
+
if (b.getAttribute('aria-label')?.includes('Record')) {
|
| 130 |
+
b.click();
|
| 131 |
+
break;
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
}, 600);
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
### 2.4 CSS 隐藏上传框(核弹级方案)
|
| 138 |
+
```css
|
| 139 |
+
/* None: absolutely nuke all upload areas */
|
| 140 |
+
footer, .gap, .lg.svelte-1ipelgc,
|
| 141 |
+
button[class*="center"][class*="boundedheight"],
|
| 142 |
+
.svelte-8prmba.camerabox,
|
| 143 |
+
div:has(> div > button.center.boundedheight),
|
| 144 |
+
[data-testid="microphone-record"] + div,
|
| 145 |
+
audio + div[style],
|
| 146 |
+
button:not(.record-button):not(.duplex-btn):not([aria-label*="Record"]),
|
| 147 |
+
/* Add more selectors for Gradio 6 */
|
| 148 |
+
div.svelte-1g45m6f { display: none !important; }
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
---
|
| 152 |
+
|
| 153 |
+
## 3. 后端服务详情
|
| 154 |
+
|
| 155 |
+
### 3.1 PregoAPI (go_server.py) 路由
|
| 156 |
+
| 端点 | 方法 | 功能 |
|
| 157 |
+
|------|------|------|
|
| 158 |
+
| `/health` | GET | 健康检查,返回 omni 状态 |
|
| 159 |
+
| `/v1/chat/completions` | POST | 纯文本对话(无语音) |
|
| 160 |
+
| `/v1/omni/voice_chat` | POST | 语音→AI 回复+TTS |
|
| 161 |
+
| `/v1/omni/duplex_audio` | POST | 全双工音频输入(webm→wav) |
|
| 162 |
+
|
| 163 |
+
### 3.2 Voice Helper (voice_helper.py) 关键函数
|
| 164 |
+
```python
|
| 165 |
+
def chat_voice(audio_path: str) -> dict:
|
| 166 |
+
"""
|
| 167 |
+
输入: WAV 文件路径
|
| 168 |
+
输出: {success, text, audio_base64, fallback}
|
| 169 |
+
流程:
|
| 170 |
+
1. omni_init (media_type=2, use_tts=True)
|
| 171 |
+
2. omni_prefill (WAV 文件 base64 编码)
|
| 172 |
+
3. omni_decode (生成 AI 回复文本 + TTS audio tokens)
|
| 173 |
+
4. token2wav (TTS 转 WAV)
|
| 174 |
+
"""
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
### 3.3 环境变量(必须)
|
| 178 |
+
| 变量 | 值 | 说明 |
|
| 179 |
+
|------|------|------|
|
| 180 |
+
| `MINICPM_API_BASE` | `http://127.0.0.1:8090` | 指向 PregoAPI |
|
| 181 |
+
| `no_proxy` | `127.0.0.1,localhost,gradio.app` | 防止 httpx 代理崩溃 |
|
| 182 |
+
| `GRADIO_ANALYTICS_ENABLED` | `False` | 隐私 |
|
| 183 |
+
|
| 184 |
+
---
|
| 185 |
+
|
| 186 |
+
## 4. 已知问题 / 待修复
|
| 187 |
+
|
| 188 |
+
### 4.1 前端:streaming 音频未真正送到后端 (高优先级)
|
| 189 |
+
- **现象**: 点击开始→按钮切换→mic 激活,但 GPU 无推理活动
|
| 190 |
+
- **根因推测**: `handle_stream_chunk` 中 VAD 检测到的缓冲区未正确传递给 `chat_voice`,或者 Gradio `Audio.streaming` 的 yield 模式未正确触发后端
|
| 191 |
+
- **修复方向**:
|
| 192 |
+
1. 在 `handle_stream_chunk` 中添加日志打印(何时触发了后端)
|
| 193 |
+
2. 检查 chat_voice 的音频缓冲区合并逻辑
|
| 194 |
+
3. 或者:改用 Plan B(Gradio UI + JS MediaRecorder 直连)
|
| 195 |
+
|
| 196 |
+
### 4.2 PregoAPI /v1/omni/duplex_audio 端点 (中优先级)
|
| 197 |
+
- 端点已写但实际未集成到前端 streaming 流中
|
| 198 |
+
- 目前前端 streaming 走的是 Gradio 内置 `/stream` 路由,调用 `handle_stream_chunk`
|
| 199 |
+
- 可改为:前端 streaming → `/v1/omni/duplex_audio` → TTS playback
|
| 200 |
+
|
| 201 |
+
### 4.3 端到端延迟 (低优先级)
|
| 202 |
+
- 当前 ~7-10s 从录音结束到 TTS 播放
|
| 203 |
+
- ~5s omni_init + ~2-3s prefill/decode + ~1s TTS
|
| 204 |
+
- 优化思路:omni_init 预置(启动时跑一次)、减少 decode max_tokens
|
| 205 |
+
|
| 206 |
+
### 4.4 音频上传框残留 (已修复)
|
| 207 |
+
- Gradio 6.x `container=False` bug 导致上传框意外显示
|
| 208 |
+
- 修复: CSS `display: none !important` 核弹方案
|
| 209 |
+
- CDP 测试确认:上传框已隐藏
|
| 210 |
+
|
| 211 |
+
### 4.5 API_BASE 指向错误 (已修复)
|
| 212 |
+
- 之前 `voice_helper.py` 默认 `API_BASE=http://127.0.0.1:8081`(指向 llama-server)
|
| 213 |
+
- llama-server 没有 `/v1/omni/voice_chat` 路由,导致 `chat_voice` 一直 404
|
| 214 |
+
- 修复: `app.py` 中设置 `os.environ['MINICPM_API_BASE']='http://127.0.0.1:8090'`
|
| 215 |
+
|
| 216 |
+
---
|
| 217 |
+
|
| 218 |
+
## 5. CDP 测试结果汇总
|
| 219 |
+
|
| 220 |
+
### 5.1 前端交互验证 (通过 playwright)
|
| 221 |
+
| 测试项 | 结果 |
|
| 222 |
+
|--------|------|
|
| 223 |
+
| 按钮文字切换 | ✅ "🎙️ 开始" → "🔴 结束" |
|
| 224 |
+
| JS 自动触发 Mic | ✅ console 输出 "[PregoPal] Mic auto-triggered" |
|
| 225 |
+
| 录音按钮可见 | ✅ ariaLabel="Record audio", visible=true |
|
| 226 |
+
| CSS 上传框隐藏 | ✅ 页面无"拖放音频到此"区域 |
|
| 227 |
+
| 状态文字显示 | ✅ "🎤 聆听中..." |
|
| 228 |
+
|
| 229 |
+
### 5.2 后端链路验证
|
| 230 |
+
| 测试项 | 结果 |
|
| 231 |
+
|--------|------|
|
| 232 |
+
| PregoAPI health | ✅ omni_initialized=True |
|
| 233 |
+
| chat_voice (test WAV) | ✅ success=True, AI text + TTS base64 |
|
| 234 |
+
| TTS 输出 | ✅ 13KB/0.3s WAV |
|
| 235 |
+
| 输入音频时长 | 1.6s @ 16kHz |
|
| 236 |
+
|
| 237 |
+
---
|
| 238 |
+
|
| 239 |
+
## 6. 项目文件结构 (关键文件)
|
| 240 |
+
|
| 241 |
+
```
|
| 242 |
+
PregoPal/
|
| 243 |
+
├── app.py # 主入口 (1215 bytes)
|
| 244 |
+
├── config.py # 全局配置/营养数据库 (5156 bytes)
|
| 245 |
+
├── start_services.py # 三服务启动脚本 (6116 bytes)
|
| 246 |
+
├── utils.py # 工具函数/font/css (40747 bytes)
|
| 247 |
+
├── loop.py # 核心循环引擎
|
| 248 |
+
│
|
| 249 |
+
├── ui/
|
| 250 |
+
│ ├── app_builder.py # Gradio 界面构建 (24966 bytes) ★ 核心
|
| 251 |
+
│ └── __init__.py
|
| 252 |
+
│
|
| 253 |
+
├── api/
|
| 254 |
+
│ ├── go_server.py # FastAPI 代理 (14786 bytes) ★ 核心
|
| 255 |
+
│ ├── voice_helper.py # chat_voice 封装 (4263 bytes) ★ 核心
|
| 256 |
+
│ └── __init__.py
|
| 257 |
+
│
|
| 258 |
+
├── core/
|
| 259 |
+
│ ├── conversation_manager.py # 对话管理 (8408 bytes)
|
| 260 |
+
│ ├── model_loader.py # 模型加载 (6132 bytes)
|
| 261 |
+
│ ├── voice_processor.py # 音频处理 (866 bytes)
|
| 262 |
+
│ └── __init__.py
|
| 263 |
+
│
|
| 264 |
+
├── api/temp/ # 测试脚本/截图
|
| 265 |
+
│ ├── cdp_duplex_test.py # CDP 点击测试
|
| 266 |
+
│ ├── full_duplex_test.py # 后端链路测试
|
| 267 |
+
│ ├── test_api_correct.py # API 测试 (正确 BASE)
|
| 268 |
+
│ └── *.png # 截图
|
| 269 |
+
│
|
| 270 |
+
├── docs/
|
| 271 |
+
│ └── 开发日志.md # 详细开发记录 (14235 bytes)
|
| 272 |
+
│
|
| 273 |
+
├── omni_output/ # llama-server debug 输出
|
| 274 |
+
├── README.md # 项目文档 (28450 bytes)
|
| 275 |
+
├── rtm_task.json # Qclaw 任务状态
|
| 276 |
+
│
|
| 277 |
+
└── _fix_*.py # 临时修复脚本 (可安全删除)
|
| 278 |
+
```
|
| 279 |
+
|
| 280 |
+
---
|
| 281 |
+
|
| 282 |
+
## 7. 当前服务运行状态
|
| 283 |
+
|
| 284 |
+
| 服务 | 端口 | 状态 | 用途 |
|
| 285 |
+
|------|------|------|------|
|
| 286 |
+
| PregoPal | 7889 | ✅ 运行中 | Gradio 前端 (0.0.0.0) |
|
| 287 |
+
| PregoAPI | 8090 | ✅ 运行中 | FastAPI 代理 |
|
| 288 |
+
| llama-server | 8081 | ✅ 运行中 | omni 推理引擎 |
|
| 289 |
+
|
| 290 |
+
---
|
| 291 |
+
|
| 292 |
+
## 8. 下一步工作(给 Codex)
|
| 293 |
+
|
| 294 |
+
### 8.1 核心 Bug 修复 (高优)
|
| 295 |
+
1. **修复 streaming 音频未传到后端的 bug**
|
| 296 |
+
- 查看 `app_builder.py` 中 `handle_stream_chunk` 函数的 VAD 逻辑
|
| 297 |
+
- 添加调试日志,确认何时触发 chat_voice
|
| 298 |
+
- 测试:人工对着 mic 说话后等待 ~2s,看是否有后端请求
|
| 299 |
+
|
| 300 |
+
2. **或者:实现 Plan B — JS MediaRecorder + WebSocket**
|
| 301 |
+
- 跳过 Gradio streaming,直接用 JavaScript 的 MediaRecorder API
|
| 302 |
+
- 通过 WebSocket 或 HTTP POST 将音频块发送到 PregoAPI 的 `/v1/omni/duplex_audio` 端点
|
| 303 |
+
- Gradio 只保留 UI 层
|
| 304 |
+
|
| 305 |
+
### 8.2 PregoAPI 改进 (中优)
|
| 306 |
+
- 在 `/v1/omni/voice_chat` 中添加 streaming 输出(SSE)
|
| 307 |
+
- omni_init 只在启动时做一次,避免每次对话重复初始化(可节省 ~5s)
|
| 308 |
+
- 减少 decode 参数中的 max_tokens 以降低延迟
|
| 309 |
+
|
| 310 |
+
### 8.3 远程访问
|
| 311 |
+
- 防火墙已开 7889 端口
|
| 312 |
+
- Tailscale IP: `100.95.7.61:7889` 可访问
|
| 313 |
+
- 如仍不通,检查 Windows 防火墙入站规则或使用 SSH 隧道
|
| 314 |
+
|
| 315 |
+
### 8.4 清理
|
| 316 |
+
- 项目根目录下 `_fix_*.py` 临时文件 20+ 个,可安全删除
|
| 317 |
+
- `_fix_tailscale.py`, `_fix_env.py` 修改已合并入 app.py
|
| 318 |
+
- `api/temp/` 下的测试脚本可归档或删除
|
| 319 |
+
- `omni_output/` 下的 debug 文件(~366 个 txt 文件)可清理
|
| 320 |
+
|
| 321 |
+
---
|
| 322 |
+
|
| 323 |
+
## 9. 关键决策记录
|
| 324 |
+
|
| 325 |
+
| 决策 | 理由 |
|
| 326 |
+
|------|------|
|
| 327 |
+
| `token2wav_device=cpu` | 显存仅 16GB,GPU 放不下 TTS 模型 |
|
| 328 |
+
| `tts_gpu_layers=0` | 同上 |
|
| 329 |
+
| Gradio 6 + Audio.streaming | 黑客松要求必须用 Gradio |
|
| 330 |
+
| 不选 fastrtc | Gradio 6 不兼容 |
|
| 331 |
+
| PregoAPI 代理 | 避免前端直接暴露 llama-server |
|
| 332 |
+
| 不选 WebRTC_Demo 前端 | 黑客松合规要求 Gradio 框架 |
|
| 333 |
+
| CSS 核弹隐藏方案 | Gradio 6 `container=False` bug 无法修复 |
|
rtm_task.json
CHANGED
|
@@ -1,80 +1,117 @@
|
|
| 1 |
{
|
| 2 |
-
"goal": "
|
| 3 |
"steps": [
|
| 4 |
{
|
| 5 |
"stepId": "1",
|
| 6 |
"description": "Main Task",
|
| 7 |
-
"status": "
|
| 8 |
-
"resultNote": "
|
| 9 |
"subSteps": [
|
| 10 |
{
|
| 11 |
"stepId": "1.1",
|
| 12 |
-
"description": "
|
| 13 |
-
"status": "
|
| 14 |
-
"resultNote": "
|
| 15 |
-
"subSteps": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\1",
|
| 17 |
-
"instructions": "
|
| 18 |
},
|
| 19 |
{
|
| 20 |
"stepId": "1.2",
|
| 21 |
-
"description": "
|
| 22 |
-
"status": "
|
| 23 |
-
"resultNote": "
|
| 24 |
"subSteps": [],
|
| 25 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\2",
|
| 26 |
-
"instructions": "
|
| 27 |
},
|
| 28 |
{
|
| 29 |
"stepId": "1.3",
|
| 30 |
-
"description": "
|
| 31 |
-
"status": "
|
| 32 |
-
"resultNote": "
|
| 33 |
"subSteps": [],
|
| 34 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\3",
|
| 35 |
-
"instructions": "
|
| 36 |
},
|
| 37 |
{
|
| 38 |
"stepId": "1.4",
|
| 39 |
-
"description": "
|
| 40 |
-
"status": "
|
| 41 |
-
"resultNote": "
|
| 42 |
"subSteps": [],
|
| 43 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\4",
|
| 44 |
-
"instructions": "
|
| 45 |
},
|
| 46 |
{
|
| 47 |
"stepId": "1.5",
|
| 48 |
-
"description": "
|
| 49 |
-
"status": "
|
| 50 |
-
"resultNote": "
|
| 51 |
"subSteps": [],
|
| 52 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\5",
|
| 53 |
-
"instructions": "
|
| 54 |
},
|
| 55 |
{
|
| 56 |
"stepId": "1.6",
|
| 57 |
-
"description": "
|
| 58 |
"status": "completed",
|
| 59 |
-
"resultNote": "
|
| 60 |
"subSteps": [],
|
| 61 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\6",
|
| 62 |
-
"instructions": "
|
| 63 |
},
|
| 64 |
{
|
| 65 |
"stepId": "1.7",
|
| 66 |
-
"description": "
|
| 67 |
-
"status": "
|
| 68 |
-
"resultNote": "
|
| 69 |
"subSteps": [],
|
| 70 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\7",
|
| 71 |
"instructions": ""
|
| 72 |
}
|
| 73 |
],
|
| 74 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1",
|
| 75 |
-
"instructions": "
|
| 76 |
}
|
| 77 |
],
|
| 78 |
"notes": [],
|
| 79 |
-
"createdAt": "2026-06-
|
| 80 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"goal": "PregoPal全双工语音对话:修复页面布局 + 实现真正的实时全双工交互",
|
| 3 |
"steps": [
|
| 4 |
{
|
| 5 |
"stepId": "1",
|
| 6 |
"description": "Main Task",
|
| 7 |
+
"status": "running",
|
| 8 |
+
"resultNote": "",
|
| 9 |
"subSteps": [
|
| 10 |
{
|
| 11 |
"stepId": "1.1",
|
| 12 |
+
"description": "分析WebRTC_Demo全双工实现方式",
|
| 13 |
+
"status": "running",
|
| 14 |
+
"resultNote": "",
|
| 15 |
+
"subSteps": [
|
| 16 |
+
{
|
| 17 |
+
"stepId": "1.1.1",
|
| 18 |
+
"description": "注入CSS隐藏Gradio上传框",
|
| 19 |
+
"status": "completed",
|
| 20 |
+
"resultNote": "核弹CSS成功隐藏所有上传框区域",
|
| 21 |
+
"subSteps": [],
|
| 22 |
+
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\1\\1",
|
| 23 |
+
"instructions": ""
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"stepId": "1.1.2",
|
| 27 |
+
"description": "JS自动循环:点击按钮→录音→VAD→后端→播放→继续",
|
| 28 |
+
"status": "running",
|
| 29 |
+
"resultNote": "JS自动循环: 点击开始→自动调Mic→streaming VAD→后端→播放→继续(已注入)",
|
| 30 |
+
"subSteps": [],
|
| 31 |
+
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\1\\2",
|
| 32 |
+
"instructions": ""
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"stepId": "1.1.3",
|
| 36 |
+
"description": "实际语音测试完整链路",
|
| 37 |
+
"status": "completed",
|
| 38 |
+
"resultNote": "后端链路验证通过:chat_voice(测试wav)→AI回复+TTS输出完整。API_BASE指向PregoAPI(8090)已修复",
|
| 39 |
+
"subSteps": [],
|
| 40 |
+
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\1\\3",
|
| 41 |
+
"instructions": ""
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"stepId": "1.1.4",
|
| 45 |
+
"description": "如有bug迭代修复",
|
| 46 |
+
"status": "pending",
|
| 47 |
+
"resultNote": "",
|
| 48 |
+
"subSteps": [],
|
| 49 |
+
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\1\\4",
|
| 50 |
+
"instructions": ""
|
| 51 |
+
}
|
| 52 |
+
],
|
| 53 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\1",
|
| 54 |
+
"instructions": ""
|
| 55 |
},
|
| 56 |
{
|
| 57 |
"stepId": "1.2",
|
| 58 |
+
"description": "使用Gradio WebRTC组件(fastrtc)方案",
|
| 59 |
+
"status": "pending",
|
| 60 |
+
"resultNote": "",
|
| 61 |
"subSteps": [],
|
| 62 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\2",
|
| 63 |
+
"instructions": ""
|
| 64 |
},
|
| 65 |
{
|
| 66 |
"stepId": "1.3",
|
| 67 |
+
"description": "修复UI布局(消除上传框)",
|
| 68 |
+
"status": "pending",
|
| 69 |
+
"resultNote": "",
|
| 70 |
"subSteps": [],
|
| 71 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\3",
|
| 72 |
+
"instructions": ""
|
| 73 |
},
|
| 74 |
{
|
| 75 |
"stepId": "1.4",
|
| 76 |
+
"description": "实现语音流实时发送到omni端点",
|
| 77 |
+
"status": "pending",
|
| 78 |
+
"resultNote": "",
|
| 79 |
"subSteps": [],
|
| 80 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\4",
|
| 81 |
+
"instructions": ""
|
| 82 |
},
|
| 83 |
{
|
| 84 |
"stepId": "1.5",
|
| 85 |
+
"description": "端到端测试录音→AI回复循环",
|
| 86 |
+
"status": "pending",
|
| 87 |
+
"resultNote": "",
|
| 88 |
"subSteps": [],
|
| 89 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\5",
|
| 90 |
+
"instructions": ""
|
| 91 |
},
|
| 92 |
{
|
| 93 |
"stepId": "1.6",
|
| 94 |
+
"description": "Plan A: 修复Gradio streaming话轮式(优先执行)",
|
| 95 |
"status": "completed",
|
| 96 |
+
"resultNote": "Plan A: CSS隐藏上传框✅ JS自动触发录音✅ 按钮状态切换✅ 后端API_BASE修复✅ 全双工后端链路验证✅",
|
| 97 |
"subSteps": [],
|
| 98 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\6",
|
| 99 |
+
"instructions": ""
|
| 100 |
},
|
| 101 |
{
|
| 102 |
"stepId": "1.7",
|
| 103 |
+
"description": "Plan B: Gradio UI+JS注入WebRTC(备选方案)",
|
| 104 |
+
"status": "pending",
|
| 105 |
+
"resultNote": "",
|
| 106 |
"subSteps": [],
|
| 107 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1\\7",
|
| 108 |
"instructions": ""
|
| 109 |
}
|
| 110 |
],
|
| 111 |
"workDir": "C:\\Users\\Andre\\codes\\LJB\\hackthon\\for_qclaw_llamacpp\\PregoPal\\workspace\\1",
|
| 112 |
+
"instructions": ""
|
| 113 |
}
|
| 114 |
],
|
| 115 |
"notes": [],
|
| 116 |
+
"createdAt": "2026-06-11 11:27"
|
| 117 |
}
|
ui/app_builder.py
CHANGED
|
@@ -14,7 +14,7 @@ import gradio as gr
|
|
| 14 |
import time
|
| 15 |
import asyncio
|
| 16 |
import traceback
|
| 17 |
-
|
| 18 |
from modules.voiceprint import VoiceprintManager
|
| 19 |
from modules.meal_recommender import MealRecommender
|
| 20 |
from modules.diet_logger import DietLogger
|
|
@@ -36,6 +36,15 @@ from api.voice_helper import chat_text, chat_voice, omni_status
|
|
| 36 |
# ============================================================
|
| 37 |
# 全局实例(单例)
|
| 38 |
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
voiceprint_mgr = VoiceprintManager()
|
| 40 |
meal_recommender = MealRecommender()
|
| 41 |
diet_logger = DietLogger()
|
|
@@ -45,134 +54,88 @@ nutrition_analyzer = NutritionAnalyzer()
|
|
| 45 |
# ============================================================
|
| 46 |
# 全双工语音会话(核心函数)
|
| 47 |
# ============================================================
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
if
|
| 70 |
-
|
| 71 |
-
sr, audio_arr = audio_data
|
| 72 |
-
audio_np = audio_arr
|
| 73 |
-
elif isinstance(audio_data, str) and audio_data:
|
| 74 |
-
import soundfile as sf
|
| 75 |
-
audio_np, sr = sf.read(audio_data, dtype='float32')
|
| 76 |
-
else:
|
| 77 |
-
yield chat_history, _thinking_html("音频格式错误" if lang == "zh" else "Audio error"), None
|
| 78 |
-
return
|
| 79 |
-
|
| 80 |
-
if audio_np is None or len(audio_np) == 0:
|
| 81 |
-
yield chat_history, _thinking_html("点击话筒开始说话" if lang == "zh" else "Tap mic to speak"), None
|
| 82 |
-
return
|
| 83 |
-
|
| 84 |
-
# 短音频提示
|
| 85 |
-
if len(audio_np) < 1600: # < 0.1s
|
| 86 |
-
yield chat_history, _thinking_html("声音太短,请再说一遍" if lang == "zh" else "Too short, please repeat"), None
|
| 87 |
-
return
|
| 88 |
-
|
| 89 |
-
# AI 思考状态
|
| 90 |
-
yield chat_history, _thinking_html("🤔 AI 思考中..."), None
|
| 91 |
-
|
| 92 |
-
# 保存音频到临时文件(供 chat_voice 使用)
|
| 93 |
-
import soundfile as sf
|
| 94 |
-
import tempfile
|
| 95 |
-
import os
|
| 96 |
-
|
| 97 |
-
temp_fd, temp_path = tempfile.mkstemp(suffix=".wav")
|
| 98 |
-
os.close(temp_fd)
|
| 99 |
try:
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
try:
|
| 103 |
-
import librosa
|
| 104 |
-
audio_np = librosa.resample(audio_np, orig_sr=sr, target_sr=16000)
|
| 105 |
-
except ImportError:
|
| 106 |
-
pass
|
| 107 |
-
sf.write(temp_path, audio_np, 16000, format='WAV', subtype='PCM_16')
|
| 108 |
-
|
| 109 |
-
# 调用后端
|
| 110 |
-
result = chat_voice(temp_path)
|
| 111 |
-
|
| 112 |
finally:
|
| 113 |
-
try:
|
| 114 |
-
|
| 115 |
-
except:
|
| 116 |
-
pass
|
| 117 |
-
|
| 118 |
-
system_prompt = ("你是PregoPal孕期营养健康顾问。请用中文简短回答。"
|
| 119 |
-
"如果用户提到饮食,用[EXTRACT_DIET]标记。"
|
| 120 |
-
"如果用户提到家庭成员,用[EXTRACT_FAMILY]标记。")
|
| 121 |
-
|
| 122 |
-
# 处理结果
|
| 123 |
if result.get("success"):
|
| 124 |
ai_text = result.get("text", "").strip()
|
| 125 |
-
|
| 126 |
-
# 如果后端没有返回文本,回退到文本对话
|
| 127 |
if not ai_text or len(ai_text) < 2:
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
msgs = [{"role": "system", "content": system_prompt}]
|
| 132 |
-
for h in chat_history[-4:]: # 保留最近 2 轮
|
| 133 |
msgs.append({"role": "user", "content": h[0] if h[0] else "..."})
|
| 134 |
msgs.append({"role": "assistant", "content": h[1] if h[1] else "..."})
|
| 135 |
msgs.append({"role": "user", "content": "我刚刚和你说话(语音输入)"})
|
| 136 |
-
|
| 137 |
ai_text = chat_text(msgs)
|
| 138 |
-
|
| 139 |
-
# 添加用户消息和 AI 回复
|
| 140 |
-
user_label = "您" if lang == "zh" else "You"
|
| 141 |
-
chat_history.append([f"🗣️ {user_label}: (语音输入)", ai_text])
|
| 142 |
-
|
| 143 |
-
# 解析标记
|
| 144 |
-
text_clean = ai_text
|
| 145 |
if "[EXTRACT_DIET]" in ai_text:
|
| 146 |
from modules.diet_extractor import DietExtractor
|
| 147 |
-
|
| 148 |
-
extracted =
|
| 149 |
-
diet_logger.log_diet(
|
| 150 |
-
member_id="ai",
|
| 151 |
-
member_name="AI识别",
|
| 152 |
meals=extracted.get("meals", {}),
|
| 153 |
-
notes=f"语音对话
|
| 154 |
-
)
|
| 155 |
-
|
| 156 |
-
audio_playback = None
|
| 157 |
if result.get("audio_base64"):
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
try:
|
| 161 |
-
audio_bytes = base64.b64decode(result["audio_base64"])
|
| 162 |
-
yield chat_history, _thinking_html(""), audio_bytes
|
| 163 |
-
return
|
| 164 |
-
except:
|
| 165 |
-
pass
|
| 166 |
-
|
| 167 |
-
# 没有 TTS 就只返回文本
|
| 168 |
-
yield chat_history, _thinking_html("已就绪" if lang == "zh" else "Ready"), None
|
| 169 |
else:
|
| 170 |
-
|
| 171 |
-
yield chat_history, _thinking_html(f"语音处理失败: {error_msg}"), None
|
| 172 |
-
|
| 173 |
except Exception as e:
|
| 174 |
traceback.print_exc()
|
| 175 |
-
|
| 176 |
|
| 177 |
|
| 178 |
def _thinking_html(text: str) -> str:
|
|
@@ -320,32 +283,60 @@ def _home_content(loop, lang):
|
|
| 320 |
gr.Markdown(T["title"])
|
| 321 |
gr.Markdown(T["subtitle"])
|
| 322 |
|
| 323 |
-
# 全双工语音对话区
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
with gr.Row():
|
| 326 |
-
# 左侧:
|
| 327 |
-
with gr.Column(scale=1, min_width=
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
type="numpy",
|
| 331 |
-
|
| 332 |
-
|
|
|
|
|
|
|
| 333 |
elem_classes=["voice-input"],
|
| 334 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
|
| 336 |
# 右侧:对话显示
|
| 337 |
with gr.Column(scale=2, min_width=400):
|
| 338 |
chat_box = gr.Chatbot(
|
| 339 |
label=T.get("thinking_label", "💬 AI 对话"),
|
| 340 |
-
height=
|
| 341 |
show_label=True,
|
| 342 |
-
bubble_full_width=False,
|
| 343 |
elem_classes=["chat-box"],
|
| 344 |
)
|
| 345 |
|
| 346 |
-
#
|
| 347 |
thinking_display = gr.HTML(
|
| 348 |
-
_thinking_html("
|
| 349 |
)
|
| 350 |
|
| 351 |
# 卡片行 1
|
|
@@ -379,18 +370,59 @@ def _home_content(loop, lang):
|
|
| 379 |
gr.Markdown(f"### 📋 {T['recent_title']}")
|
| 380 |
gr.HTML(recent_html)
|
| 381 |
|
| 382 |
-
# ── 事件绑定
|
| 383 |
-
#
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
)
|
| 389 |
|
| 390 |
-
#
|
| 391 |
-
audio_input.
|
| 392 |
-
fn=
|
| 393 |
-
|
|
|
|
|
|
|
| 394 |
)
|
| 395 |
|
| 396 |
|
|
|
|
| 14 |
import time
|
| 15 |
import asyncio
|
| 16 |
import traceback
|
| 17 |
+
import numpy as np
|
| 18 |
from modules.voiceprint import VoiceprintManager
|
| 19 |
from modules.meal_recommender import MealRecommender
|
| 20 |
from modules.diet_logger import DietLogger
|
|
|
|
| 36 |
# ============================================================
|
| 37 |
# 全局实例(单例)
|
| 38 |
# ============================================================
|
| 39 |
+
# ============================================================
|
| 40 |
+
# 全双工语音全局状态
|
| 41 |
+
# ============================================================
|
| 42 |
+
_DUPLEX_ACTIVE = False # True=正在全双工对话
|
| 43 |
+
_AUDIO_BUF = [] # streaming 音频缓冲
|
| 44 |
+
_SPEECH_CNT = 0 # 有声音的帧数
|
| 45 |
+
_SILENT_CNT = 0 # 连续静音帧数
|
| 46 |
+
|
| 47 |
+
|
| 48 |
voiceprint_mgr = VoiceprintManager()
|
| 49 |
meal_recommender = MealRecommender()
|
| 50 |
diet_logger = DietLogger()
|
|
|
|
| 54 |
# ============================================================
|
| 55 |
# 全双工语音会话(核心函数)
|
| 56 |
# ============================================================
|
| 57 |
+
|
| 58 |
+
def _is_silent(chunk, thr=0.02):
|
| 59 |
+
if chunk is None or len(chunk) == 0: return True
|
| 60 |
+
return float(np.sqrt(np.mean(chunk**2))) < thr
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def toggle_duplex(*args):
|
| 64 |
+
"""点按切换全双工对话状态"""
|
| 65 |
+
global _DUPLEX_ACTIVE, _AUDIO_BUF, _SPEECH_CNT, _SILENT_CNT
|
| 66 |
+
_DUPLEX_ACTIVE = not _DUPLEX_ACTIVE
|
| 67 |
+
if not _DUPLEX_ACTIVE:
|
| 68 |
+
_AUDIO_BUF = []; _SPEECH_CNT = 0; _SILENT_CNT = 0
|
| 69 |
+
return _DUPLEX_ACTIVE
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def handle_stream_chunk(audio_chunk, chat_history):
|
| 73 |
+
"""处理 streaming 音频块: VAD -> 缓冲 -> 静音后调后端"""
|
| 74 |
+
global _DUPLEX_ACTIVE, _AUDIO_BUF, _SPEECH_CNT, _SILENT_CNT
|
| 75 |
+
if not _DUPLEX_ACTIVE:
|
| 76 |
+
return chat_history, _thinking_html("✅ 已就绪"), None
|
| 77 |
+
if not chat_history: chat_history = []
|
| 78 |
+
audio_np = None
|
| 79 |
+
if audio_chunk is not None and isinstance(audio_chunk, tuple) and len(audio_chunk) == 2:
|
| 80 |
+
sr, arr = audio_chunk
|
| 81 |
+
if arr.dtype.kind == 'i':
|
| 82 |
+
audio_np = arr.astype(np.float32) / 32768.0
|
| 83 |
+
else:
|
| 84 |
+
audio_np = arr.astype(np.float32)
|
| 85 |
+
if audio_np is None or len(audio_np) == 0:
|
| 86 |
+
return chat_history, _thinking_html("🎤 聆听中..."), None
|
| 87 |
+
if _is_silent(audio_np, 0.02):
|
| 88 |
+
_SILENT_CNT += 1
|
| 89 |
+
if _SILENT_CNT >= 3 and _SPEECH_CNT >= 4 and len(_AUDIO_BUF) > 0:
|
| 90 |
+
full = np.concatenate(_AUDIO_BUF)
|
| 91 |
+
_AUDIO_BUF = []; _SPEECH_CNT = 0; _SILENT_CNT = 0
|
| 92 |
+
return _call_duplex_backend(full, chat_history)
|
| 93 |
+
return chat_history, _thinking_html("🎤 聆听中..."), None
|
| 94 |
+
else:
|
| 95 |
+
_SPEECH_CNT += 1
|
| 96 |
+
_SILENT_CNT = 0
|
| 97 |
+
_AUDIO_BUF.append(audio_np)
|
| 98 |
+
return chat_history, _thinking_html("🔊 正在听..."), None
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _call_duplex_backend(audio_np, chat_history):
|
| 102 |
try:
|
| 103 |
+
import soundfile as sf, tempfile, os, base64
|
| 104 |
+
sr = 16000
|
| 105 |
+
if len(audio_np.shape) > 1: audio_np = audio_np.mean(axis=1)
|
| 106 |
+
fd, path = tempfile.mkstemp(suffix=".wav"); os.close(fd)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
try:
|
| 108 |
+
sf.write(path, audio_np, sr, format="WAV", subtype="PCM_16")
|
| 109 |
+
result = chat_voice(path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
finally:
|
| 111 |
+
try: os.remove(path)
|
| 112 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
if result.get("success"):
|
| 114 |
ai_text = result.get("text", "").strip()
|
|
|
|
|
|
|
| 115 |
if not ai_text or len(ai_text) < 2:
|
| 116 |
+
sp = "你是PregoPal孕期营养健康顾问。请用中文简短回答。"
|
| 117 |
+
msgs = [{"role": "system", "content": sp}]
|
| 118 |
+
for h in chat_history[-4:]:
|
|
|
|
|
|
|
| 119 |
msgs.append({"role": "user", "content": h[0] if h[0] else "..."})
|
| 120 |
msgs.append({"role": "assistant", "content": h[1] if h[1] else "..."})
|
| 121 |
msgs.append({"role": "user", "content": "我刚刚和你说话(语音输入)"})
|
|
|
|
| 122 |
ai_text = chat_text(msgs)
|
| 123 |
+
chat_history.append(["🗣️ 您", ai_text])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
if "[EXTRACT_DIET]" in ai_text:
|
| 125 |
from modules.diet_extractor import DietExtractor
|
| 126 |
+
e = DietExtractor()
|
| 127 |
+
extracted = e.extract_all(ai_text)
|
| 128 |
+
diet_logger.log_diet(member_id="ai", member_name="AI识别",
|
|
|
|
|
|
|
| 129 |
meals=extracted.get("meals", {}),
|
| 130 |
+
notes=f"语音对话: {datetime.date.today()}")
|
|
|
|
|
|
|
|
|
|
| 131 |
if result.get("audio_base64"):
|
| 132 |
+
return (chat_history, _thinking_html("🎤 聆听中..."), base64.b64decode(result["audio_base64"]))
|
| 133 |
+
return chat_history, _thinking_html("🎤 聆听中..."), None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
else:
|
| 135 |
+
return chat_history, _thinking_html("🎤 聆听中..."), None
|
|
|
|
|
|
|
| 136 |
except Exception as e:
|
| 137 |
traceback.print_exc()
|
| 138 |
+
return chat_history, _thinking_html(f"错误: {str(e)[:50]}"), None
|
| 139 |
|
| 140 |
|
| 141 |
def _thinking_html(text: str) -> str:
|
|
|
|
| 283 |
gr.Markdown(T["title"])
|
| 284 |
gr.Markdown(T["subtitle"])
|
| 285 |
|
| 286 |
+
# 全双工语音对话区 — 点按切换模式
|
| 287 |
+
gr.HTML("""<style>
|
| 288 |
+
/* Nuclear: hide all Gradio upload/drop zones */
|
| 289 |
+
.voice-input .tabs, .voice-input .tab-nav, .voice-input [role="tablist"],
|
| 290 |
+
.voice-input .audio-upload, .upload-container, [data-testid="audio-upload"],
|
| 291 |
+
.gr-box.rounded-lg, .file-preview { display: none !important; }
|
| 292 |
+
.voice-input { min-height: 48px !important; display: flex !important; }
|
| 293 |
+
.record-button, button[aria-label*="Record"], [data-testid="microphone-record"]
|
| 294 |
+
{ display: inline-flex !important; background: #7c4dff !important; }
|
| 295 |
+
.voice-duplex-panel { background: #f8f4ff; border-radius: 16px; padding: 16px; margin: 12px 0; }
|
| 296 |
+
.duplex-btn { font-size: 1.1rem !important; font-weight: 700 !important; }
|
| 297 |
+
</style>""")
|
| 298 |
+
|
| 299 |
+
with gr.Group(elem_classes=["voice-duplex-panel"]):
|
| 300 |
with gr.Row():
|
| 301 |
+
# 左侧:控制按钮 + Audio(隐藏)+ 回复播放
|
| 302 |
+
with gr.Column(scale=1, min_width=320):
|
| 303 |
+
duplex_btn = gr.Button(
|
| 304 |
+
"🎙️ 点击开始全双工对话",
|
| 305 |
+
elem_classes=["duplex-btn"],
|
| 306 |
+
variant="primary",
|
| 307 |
+
size="lg",
|
| 308 |
+
)
|
| 309 |
+
# streaming Audio(隐藏,用于持续采集麦克风)
|
| 310 |
+
audio_input = gr.Microphone(
|
| 311 |
type="numpy",
|
| 312 |
+
streaming=True,
|
| 313 |
+
label="",
|
| 314 |
+
show_label=False,
|
| 315 |
+
container=False,
|
| 316 |
elem_classes=["voice-input"],
|
| 317 |
)
|
| 318 |
+
audio_output = gr.Audio(
|
| 319 |
+
type="numpy",
|
| 320 |
+
autoplay=True,
|
| 321 |
+
visible=True,
|
| 322 |
+
label="🔊 AI 回复",
|
| 323 |
+
show_label=False,
|
| 324 |
+
container=False,
|
| 325 |
+
elem_classes=["voice-output"],
|
| 326 |
+
)
|
| 327 |
|
| 328 |
# 右侧:对话显示
|
| 329 |
with gr.Column(scale=2, min_width=400):
|
| 330 |
chat_box = gr.Chatbot(
|
| 331 |
label=T.get("thinking_label", "💬 AI 对话"),
|
| 332 |
+
height=320,
|
| 333 |
show_label=True,
|
|
|
|
| 334 |
elem_classes=["chat-box"],
|
| 335 |
)
|
| 336 |
|
| 337 |
+
# 状态显示
|
| 338 |
thinking_display = gr.HTML(
|
| 339 |
+
_thinking_html("🔄 点击「开始对话」进入全双工语音交互" if lang == "zh" else "🔄 Tap 'Start' for duplex voice")
|
| 340 |
)
|
| 341 |
|
| 342 |
# 卡片行 1
|
|
|
|
| 370 |
gr.Markdown(f"### 📋 {T['recent_title']}")
|
| 371 |
gr.HTML(recent_html)
|
| 372 |
|
| 373 |
+
# ── 事件绑定(全双工)──
|
| 374 |
+
# 切换按钮:让 toggle_duplex 返回新按钮文字
|
| 375 |
+
def toggle_duplex_v2(state):
|
| 376 |
+
global _DUPLEX_ACTIVE, _AUDIO_BUF, _SPEECH_CNT, _SILENT_CNT
|
| 377 |
+
_DUPLEX_ACTIVE = not _DUPLEX_ACTIVE
|
| 378 |
+
if not _DUPLEX_ACTIVE:
|
| 379 |
+
_AUDIO_BUF = []; _SPEECH_CNT = 0; _SILENT_CNT = 0
|
| 380 |
+
return (_thinking_html("✅ 已退出全双工模式" if lang == "zh" else "✅ Duplex ended"), False)
|
| 381 |
+
return (_thinking_html("🎤 全双工模式已启动 — 开始录音吧" if lang == "zh" else "🎤 Duplex started — speak now"), True)
|
| 382 |
+
|
| 383 |
+
duplex_state = gr.State(value=False)
|
| 384 |
+
|
| 385 |
+
# After render, inject JS to auto-click microphone when duplex starts
|
| 386 |
+
duplex_btn.click(
|
| 387 |
+
fn=toggle_duplex_v2,
|
| 388 |
+
inputs=[duplex_state],
|
| 389 |
+
outputs=[thinking_display, duplex_state],
|
| 390 |
+
js="""(state) => {
|
| 391 |
+
const btn = document.querySelector('.duplex-btn');
|
| 392 |
+
if (btn) {
|
| 393 |
+
const isStarting = !btn.textContent.includes('\u7ed3\u675f');
|
| 394 |
+
if (isStarting) {
|
| 395 |
+
btn.textContent = '\U0001f534 \u7ed3\u675f\u5bf9\u8bdd';
|
| 396 |
+
btn.style.background = '#d32f2f';
|
| 397 |
+
btn.style.color = 'white';
|
| 398 |
+
// Wait for UI update then auto-trigger microphone
|
| 399 |
+
setTimeout(() => {
|
| 400 |
+
// Find the Gradio record button (it's a <button> with aria-label)
|
| 401 |
+
const mics = document.querySelectorAll('button[aria-label*="record" i], button[aria-label*="Record"], .record-button, .gr-microphone button');
|
| 402 |
+
for (const mic of mics) {
|
| 403 |
+
if (mic.offsetParent !== null) {
|
| 404 |
+
mic.click();
|
| 405 |
+
console.log('[PregoPal] Mic auto-triggered');
|
| 406 |
+
break;
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
}, 600);
|
| 410 |
+
} else {
|
| 411 |
+
btn.textContent = '\U0001f399\ufe0f \u70b9\u51fb\u5f00\u59cb\u5168\u53cc\u5de5\u5bf9\u8bdd';
|
| 412 |
+
btn.style.background = '';
|
| 413 |
+
btn.style.color = '';
|
| 414 |
+
}
|
| 415 |
+
}
|
| 416 |
+
return state;
|
| 417 |
+
}"""
|
| 418 |
)
|
| 419 |
|
| 420 |
+
# streaming VAD
|
| 421 |
+
audio_input.stream(
|
| 422 |
+
fn=handle_stream_chunk,
|
| 423 |
+
inputs=[audio_input, chat_box],
|
| 424 |
+
outputs=[chat_box, thinking_display, audio_output],
|
| 425 |
+
stream_every=0.3,
|
| 426 |
)
|
| 427 |
|
| 428 |
|