Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db571ba204 | ||
|
|
f6614d4bf9 | ||
|
|
4984293998 | ||
|
|
6c3b09e693 |
@@ -1,11 +1,8 @@
|
||||
# 复制成 .env 后填写。不填也能跑(会回退到离线 provider)。
|
||||
|
||||
# ---- LLM ----
|
||||
DEEPSEEK_API_KEY=
|
||||
|
||||
# ---- Embedding(可选,留空则用本地或跳过向量检索)----
|
||||
EMBEDDING_API_KEY=
|
||||
|
||||
# ---- 运行时 ----
|
||||
CYBERGRIL_DB=companion.db
|
||||
CYBERGRIL_LOG_LEVEL=INFO
|
||||
# R1 uses the approved no-key gateway from config/models.yaml.
|
||||
# These variables are read from the process environment; this file is not auto-loaded.
|
||||
# Keep data outside release directories. Use an independent directory for local testing.
|
||||
CYBERGRIL_DB=/opt/cybergril-data/cybergril.db
|
||||
CYBERGRIL_MODELS=config/models.yaml
|
||||
CYBERGRIL_WEB=web/dist
|
||||
CYBERGRIL_HOST=127.0.0.1
|
||||
CYBERGRIL_PORT=8310
|
||||
|
||||
@@ -48,3 +48,5 @@ models/
|
||||
*.swp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
.venv311/
|
||||
|
||||
@@ -306,3 +306,7 @@ pytest -k degradation -v # 降级机制
|
||||
## 许可
|
||||
|
||||
私有项目,未授权。
|
||||
|
||||
## S1 前端演示
|
||||
|
||||
独立的 React / TypeScript 前端位于 `web/`,运行 `cd web && npm ci && npm run dev` 后从普通入口进入明确标识的本机演示。真实后台、语音、视觉和备份尚未接通;不自动连接模型或现有服务。安装、构建和测试命令见 [web/README.md](web/README.md),实现与后续接线见 [docs/frontend/IMPLEMENTATION.md](docs/frontend/IMPLEMENTATION.md)。
|
||||
|
||||
@@ -18,9 +18,9 @@ tiers:
|
||||
# ---- 旗舰:人设浓度最高的时刻 ----
|
||||
high:
|
||||
provider: openai_compat
|
||||
model: deepseek-v4.1-flash
|
||||
base_url: https://api.deepseek.com/v1
|
||||
api_key_env: DEEPSEEK_API_KEY
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 60.0
|
||||
temperature: 0.85
|
||||
|
||||
@@ -28,9 +28,9 @@ tiers:
|
||||
# 省钱的杠杆通常不是换更小的模型,而是少喂上下文。
|
||||
standard:
|
||||
provider: openai_compat
|
||||
model: deepseek-v4.1-flash
|
||||
base_url: https://api.deepseek.com/v1
|
||||
api_key_env: DEEPSEEK_API_KEY
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 40.0
|
||||
temperature: 0.7
|
||||
|
||||
@@ -38,8 +38,8 @@ tiers:
|
||||
# 没有本地服务时,把它指向 openai_compat 的远端小模型即可。
|
||||
low:
|
||||
provider: openai_compat
|
||||
model: qwen3.5-4b-instruct
|
||||
base_url: http://127.0.0.1:8000/v1
|
||||
model: halogen-qwen3.8-flash-next
|
||||
base_url: http://192.168.200.11:8731/v1
|
||||
api_key_env: null
|
||||
timeout: 20.0
|
||||
temperature: 0.4
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Review/install by 总工 only. Single worker; never share DB with demo or tests.
|
||||
[Unit]
|
||||
Description=CyberGril R1 persistent text API
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=cybergril
|
||||
WorkingDirectory=/opt/cybergril-api/current
|
||||
Environment=CYBERGRIL_DB=/opt/cybergril-data/cybergril.db
|
||||
Environment=CYBERGRIL_MODELS=/opt/cybergril-api/current/config/models.yaml
|
||||
Environment=CYBERGRIL_WEB=/opt/cybergril-api/current/web/dist
|
||||
Environment=CYBERGRIL_HOST=0.0.0.0
|
||||
Environment=CYBERGRIL_PORT=8310
|
||||
ExecStart=/opt/cybergril-api/current/.venv/bin/python -m cybergril.api
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
TimeoutStopSec=15
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/opt/cybergril-data
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1 @@
|
||||
screenshots/
|
||||
@@ -0,0 +1,48 @@
|
||||
HEL-748 · S1 实现与接线说明
|
||||
|
||||
本轮范围是可构建的完整前端及离线演示,不部署,不实现 B1–B3。基于正式仓库 main 的 `1e9b08aed81b4ebf163721232a8d65707b1c3183` 新建任务分支;检出时工作区干净,无仓库内额外 AGENTS,无平台关联 PR。未改 Python 核心、既有测试、服务配置、SSH 信任、端口、GPU 或模型。
|
||||
|
||||
依据为本卡《整套设计验收与施工裁定-v1》、HEL-746 R2、HEL-738 结构与接口边界和需求 v1.6。名字、关系不预选、未分享即隐藏三项裁定覆盖旧原型。首建底色明确为示例,真实排盘待接已有 Python 编译器,不在浏览器重写八字规则。
|
||||
|
||||
主要目录与职责:
|
||||
|
||||
- `web/src/app/`:入口、首建守卫、导航、全局 UI 偏好、返回/主动/断线演示。
|
||||
- `web/src/manage/`:四步首建;只读身份;关系/城市/服务/显示草稿;保存取消失败;外观标识;演示导出与同身份恢复。
|
||||
- `web/src/chat/`:文字草稿、IME 与快捷键、字幕/记录、取消重试、模拟语音/观察授权及结束。
|
||||
- `web/src/life/`:生活与四类回忆、双向关联、原位保留、手机详情推入、分页和深链守卫。
|
||||
- `web/src/domain/`:模型、首建校验、公开视图。所有可见事件、回忆、消息、摘要统一经过 `publicView`,未知关联默认拒绝;详情也从公开视图查找。
|
||||
- `web/src/adapters/`:独立可替换聊天适配器、turn_id/epoch 门槛、AbortController、本地持久化、严格 JSON 重建校验。
|
||||
- `web/src/demo/`:固定场景数据,与页面和传输分离。
|
||||
- `web/src/stage/`:背景空间与 `FallbackPresenter`。Presenter 只消费 SceneDesc,不写生活;参考图片失效也有文字降级,不黑屏。
|
||||
- `web/src/shared/`:复用按钮、图标、字段、状态和带焦点边界的确认弹层。
|
||||
- `web/src/styles/`:R2 单一 Token 和组件样式来源;没有第三方 UI 皮肤或叠加覆盖样式表。
|
||||
|
||||
两主题使用相同 DOM 和布局;人物拱窗、交谈展开、阅读面板与手机断点沿用获批样式。静帧仅呈现参考人物/房间,不渲染整页图片。语音/观察不访问 `getUserMedia`、不调用 ASR/TTS、不发外部请求。演示天气固定并标注模拟;当前视觉标签来自演示记录公开视图。
|
||||
|
||||
F1–F9 走法:
|
||||
|
||||
| 流程 | 入口与边界 |
|
||||
|---|---|
|
||||
| F1 | 无本机档案 → 四步创建 → 名字/成年生日/关系/勾选校验 → 本机持久化 → 首晚空生活 |
|
||||
| F2 | 普通入口说明未接服务 → 明确演示入口;重开直接回到同一位她 |
|
||||
| F3 | 演示场景 → 模拟两天后返回;只从已分享数据生成摘要,不生成后台生活 |
|
||||
| F4 | 演示场景 → 主动消息;来源是已分享事件,回她定位聊天并保留来源区域 |
|
||||
| F5 | 交流麦克风 → 模拟授权 → 倾听界面;文字发送推进思考/说话,可打断/结束;无真实收音 |
|
||||
| F6 | 演示断线 → 暂停发送,保留草稿,结束模拟语音、取消旧轮;恢复失败可重试,不自动重发 |
|
||||
| F7 | 设置城市 → 搜索/选择 → 保存成功/失败/重试;不调用天气 API |
|
||||
| F8 | 本地演示素材 JSON → 结构检查/模拟对比/确认;只更新外观标识,真实媒体导入待后续 |
|
||||
| F9 | 本地演示 JSON 下载/同身份校验/输入确认/先导出再恢复;服务器备份明确未接通 |
|
||||
|
||||
取消与错误:新轮、手动取消、切离交流会 abort 当前模拟回复;事件还需同时匹配 turn_id 与 epoch,非协作适配器的迟到消息同样被门槛拒绝。断线 resync 提升 epoch;恢复不自动续接旧轮。管理保存切区/关区会 abort;草稿保留,取消恢复上次提交值;存储损坏不进入新的首建覆盖。导入只执行 JSON.parse 后按固定 schema 重建;不执行脚本、不作为 HTML、不加载媒体/服务 URL。
|
||||
|
||||
后续接线清单(当前均未提供):
|
||||
|
||||
1. B1 同源 API 与 WS:hello/sync、游标和持久 epoch、能力声明、HTTP AbortSignal。真实模式不得直接替换成未经审定的 LLM URL。
|
||||
2. 服务端授权与隐私:必须在响应前裁剪未分享记录、未知引用、回忆和消息及摘要;本轮前端过滤不构成服务器权限控制。
|
||||
3. 接已有 Python 生辰预览/只读档案、真实关系更新;身份 ID、底色指纹由服务端负责。
|
||||
4. B2/B3 后台生活、主动性、记忆与增长层;前端只订阅 LifeScene/事件,不从素材反编生活。
|
||||
5. S2 流式文字;S3 ASR/TTS 二进制协议、session_id/seq 隔离、权限与实际中断;当前没有真实音频流,因此不声称达到延迟指标。
|
||||
6. S4 生活/回忆服务分页;S5 城市/天气、素材包校验和完整服务器备份/自动备份;演示 JSON 的 MIME 和结构不是媒体真伪校验。
|
||||
7. S6 视觉摘要时效与 HTTPS、真实权限;Presenter 的视频/音频/口型驱动器可注入,当前只交静帧降级。
|
||||
|
||||
测试部署由总工审核后执行。建议在独立目录安装构建,将 `web/dist/` 作为静态站点挂到总工选定的未占用测试端口;正常路径 `/`,演示 `/?demo=1`。本轮未占用固定服务端口,也未更改 8010/18080/18081 或现网。部署若换 origin,浏览器本地演示资料不会自动迁移,可通过同身份演示 JSON 手动恢复。
|
||||
@@ -0,0 +1,11 @@
|
||||
HEL-748: S1 完整前端与本机演示(不含后端或部署)
|
||||
|
||||
原仓库只有 Python 核心,没有产品前端。新增独立 `web/` React/TypeScript/Vite 工程,将获批 HEL-746 R2 的两主题、相处/交流/日子/管理和 F1–F9 演示落地为可构建组件。
|
||||
|
||||
创建必须输入名字并亲自选关系,刷新保留同一位档案;未分享生活及未知引用统一隐藏,包括详情、回忆、聊天和离开摘要。普通入口说明服务未接通,只有显式 `?demo=1` 进入本机演示;导入只解析校验 JSON,不执行 HTML/脚本、不请求外部媒体或服务。轮次/epoch/AbortSignal 隔离旧回复,管理草稿按分区保存或取消,恢复需同身份、输入确认并先导出。
|
||||
|
||||
验证:TypeScript、ESLint、Vite 生产构建、11 项领域测试、原有 Python 78 项测试;实际 Chromium 在 1440×900、1280×800、390×844 走查两主题及关键失败/恢复路径。浏览器记录与接线清单见 `docs/frontend/`。真实手机/Safari、真实服务和性能指标未测。
|
||||
|
||||
本轮仅 S1。没有更改 Python 核心、现网配置或服务端口,没有部署/合并,没有接入 LLM/ASR/TTS/视觉/后台循环/真实备份。Presenter 使用标识清楚的参考静帧。审查通过后由总工负责独立测试部署。
|
||||
|
||||
目标 base: main (`1e9b08aed81b4ebf163721232a8d65707b1c3183`)
|
||||
@@ -0,0 +1,33 @@
|
||||
HEL-748 S1 · 实际验证记录 · 2026-10-22(北京时间)
|
||||
|
||||
环境:Ubuntu 22.04;Node 24.16.0 / npm 11.13.0;Chromium 151.0.7922.34(Python Playwright、无头真实浏览器);Python 3.11.16 独立 `.venv`。浏览器直接加载 Vite 生产产物,测试脚本启动随机 loopback HTTP 端口并在结束时关闭。
|
||||
|
||||
| 检查 | 实际结果 |
|
||||
|---|---|
|
||||
| `npm run typecheck` | 通过 |
|
||||
| `npm run lint` | 通过,无调试输出残留 |
|
||||
| `npm test` | 11 项通过:隐私公开视图/未知引用、首建拦截、持久化失败与损坏、恢复身份/结构/脚本边界、turn/epoch/Abort 隔离、HTTP 标识兼容 |
|
||||
| `npm run build` | 通过,41 个模块;JS 197.50KB / gzip 64.67KB,CSS 61.20KB / gzip 13.05KB |
|
||||
| Python 既有测试 | `.venv/bin/python -m pytest -q`:78 项通过(Python 3.11.16);默认 Python 3.10.12 亦通过 78 项 |
|
||||
| 运行时依赖检查 | `npm audit --omit=dev --registry=https://registry.npmjs.org` 返回 0 漏洞;只检查生产依赖 |
|
||||
| 三尺寸主走查 | 1440×900、1280×800、390×844,两套主题;16 组结果通过,88 次本机请求,无未捕获浏览器错误、无外部服务请求 |
|
||||
| 末次手机复测 | 390×844 两主题重跑,包含保存错误说明进入可见区域的断言;结果另存 `browser-results-390.json` |
|
||||
| 导入与草稿专项 | 7 组通过,见 `import-results.json` |
|
||||
|
||||
主走查是本轮新增的真实操作脚本,未引用原型自检数字:
|
||||
|
||||
- 普通入口有未接服务说明,不能直接进入伪在线状态;正常入口没有演示控制台。
|
||||
- 首建空名字、未成年生日、未选关系、未勾选均拦截;关系无预选;创建模拟失败资料保留,可重试;创建后刷新不再首建,名字统一使用。
|
||||
- 两套主题下首页、交流、生活详情、回忆关联返回、管理表单、保存取消与关系二次确认;主题刷新仍保留。
|
||||
- 未分享列表项、详情深链、回忆、聊天引用、离开摘要不可见;未知引用默认隐藏。原始本机演示数据仍含专门的隐私测试条目,展示使用过滤后的公开视图,不能把这一点当作服务端授权。
|
||||
- 手动取消回复、退出交流后的旧回复不复活;发送失败重试;中文输入法 Enter 不误发,Shift+Enter 换行,Enter 发送;用户/导入的 HTML 字符串只显示文本。
|
||||
- 模拟语音的结束控件在手机视口内,文字输入常驻;观察为无采集模拟;断线暂停发送、草稿保留、失败重试;城市保存失败保留修改、重试同步顶栏。
|
||||
- 离开摘要经过隐私过滤;主动消息有已分享事件来源,回她定位记录。
|
||||
|
||||
专项覆盖:同一位档案恢复、异人阻断、输入“恢复”与恢复前下载;非法素材清单拒绝;素材 URL/服务测试不发网络请求;换外观标识不改身份;切换分区取消尚未完成的保存;保存城市不提交服务草稿;长列表 18+12 分页、聊天返回精确保留滚动位置;坏存储不自动覆盖;模拟 `randomUUID` 缺失时创建与聊天仍能完成。
|
||||
|
||||
本轮实际发现并修正:表单下拉框可访问标签混入选项文字;SVG 图标视口/命名空间;手机固定操作区域与内容关系;管理分区误带其他草稿提交的风险;保存反馈在手机滚动区内不够可见;局域网 HTTP 的标识生成兼容性。手机列表/详情推入需要先按返回才能操作列表,这是获批的布局行为,测试脚本已按实际用户路径操作。
|
||||
|
||||
截图为本轮 DOM 实际捕获,共 45 张 PNG;`screenshots/` 不进入前端构建或 Git,随任务评论附件打包交付。包含三尺寸的两主题首页/交流记录/生活详情/管理,以及首建、创建失败、发送失败、语音、断线失败、保存失败、离开返回。截图不代表动效性能实测。
|
||||
|
||||
未测:真实手机硬件、Safari、触屏键盘/安全区、真实麦克风/摄像头/ASR/TTS/天气/服务器记忆与备份、真实媒体/口型、后台常驻生活、FPS/延迟/长时稳定性。上述能力当前均未接线,不声称完成。
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"checks": [
|
||||
"1440: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"1440: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"1440: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"1440: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"1440: privacy-filtered away summary and proactive message",
|
||||
"No uncaught browser errors, API/external requests, microphone or camera requests"
|
||||
],
|
||||
"errors": [],
|
||||
"requests": 31
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"checks": [
|
||||
"390: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"390: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"390: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"390: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"390: privacy-filtered away summary and proactive message",
|
||||
"No uncaught browser errors, API/external requests, microphone or camera requests"
|
||||
],
|
||||
"errors": [],
|
||||
"requests": 23
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"checks": [
|
||||
"1440: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"1440: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"1440: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"1440: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"1440: privacy-filtered away summary and proactive message",
|
||||
"1280: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"1280: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"1280: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"1280: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"1280: privacy-filtered away summary and proactive message",
|
||||
"390: ordinary entry, creation validation/failure/retry and reopen",
|
||||
"390: both themes, home/talk/days/memory return, relation confirm/cancel/save",
|
||||
"390: private deep-link guard, cancel/exit isolation, IME/Shift+Enter and XSS text",
|
||||
"390: failed send/retry, voice end reachable, no-camera simulation, reconnect failure/retry, save failure/retry",
|
||||
"390: privacy-filtered away summary and proactive message",
|
||||
"No uncaught browser errors, external requests, microphone or camera requests"
|
||||
],
|
||||
"errors": [],
|
||||
"requests": 88
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[
|
||||
"Reject foreign identity; same-identity restore requires typed confirmation and pre-restore export",
|
||||
"Invalid manifests rejected; external media never loaded; appearance confirm/cancel preserves identity; service test has no network",
|
||||
"Changing section aborts outstanding save; saving city does not commit an unsaved service draft",
|
||||
"Imported model text rendered as text, never as HTML",
|
||||
"Long timeline paginates 18 then 12 and retains exact scroll position after chat return",
|
||||
"Corrupt persistence never falls back to overwriting first creation",
|
||||
"Creation and chat work when secure-context randomUUID is unavailable"
|
||||
]
|
||||
@@ -0,0 +1,15 @@
|
||||
HEL-780 · 8310独立部署/回滚材料(总工执行,尚未部署)
|
||||
|
||||
1. 审核确切任务分支和提交,复核8310空闲;保持8300和其他既有服务不动。建立 `/opt/cybergril-api/releases/<release>/`,构建生产前端和独立Python≥3.11虚拟环境,按 IMPLEMENTATION 安装。服务账号示例为 cybergril,由总工按主机现有规范准备,不默认root。
|
||||
2. 准备代码目录外的 `/opt/cybergril-data/`,仅服务账号可写。首次上线保持数据库没有真实档案,不运行创建POST、不替用户创建。已有数据升级前,停止该API,用 SQLite backup API 做一致快照至独立回滚目录;禁止只复制正在写入中的主DB文件而漏WAL。
|
||||
3. 将 `current` 指向已审核release,审查 `deploy/cybergril-api.service.example` 后再安装服务。模板限制单进程,端口8310,持久数据目录独立;模板不改防火墙、证书或反向代理。按现场systemd版本核对保护项和目录权限。uvicorn直连SSE无代理缓冲;若后续接代理,需另行配置关闭SSE缓冲。
|
||||
4. 启动前确认 `web/dist/index.html`、models配置、虚拟环境可读和数据目录可写。启动时自动执行幂等增量建表、epoch加一和pending取消。使用 `GET /api/health`、`GET /api/companion`(首装预期404)与普通页面做无副作用检查;模型健康异常先记录,不改共享网关、不循环调参。不要以调用preview之外的写接口作为上线健康检查。
|
||||
5. 审核通过后由总工记录服务URL、release、SHA、`journalctl -u cybergril-api` 日志位置,再交用户创建。普通入口 `/`,演示 `/?demo=1`。本轮不切换8300入口,不合并、不部署。
|
||||
|
||||
回滚:
|
||||
|
||||
- 停止 `cybergril-api`,记录当时release与数据快照;把 current 切回上一已审核release,重新启动。数据目录保持原样,不随release回退或删除。R1迁移仅增表,保留旧表;每次重新启动epoch递增。回滚到纯前端版本时真实API将不可用,应明确告知,服务器数据仍保留。
|
||||
- 数据恢复与代码回滚分别处理。需恢复快照时先再次备份当前数据,由总管确认可接受的数据时间点,再由总工停服恢复;禁止把本地测试库覆盖用户库。
|
||||
- 取消部署的清理只针对新建8310服务及明确release;不删除 `/opt/cybergril-data/`,不停止8300或其他项目服务。
|
||||
|
||||
限制:单用户内网、无新增鉴权体系;应沿既有内网访问边界使用。尚无产品级备份功能,本文的升级快照属于部署运维操作;真实页面不会声称已自动备份。SQLite单worker是当前约束,后续扩展需独立设计。
|
||||
@@ -0,0 +1,64 @@
|
||||
HEL-780 · R1 实现与安装运行说明
|
||||
|
||||
基准为 main `498429399812a0776dadd4b56662d31b455a9ea5`,保留原前端两主题与统一样式,未增加 CSS 或运行中的服务。代码审核后由总工决定部署;施工阶段未登录部署服务器、未占用8310,也未修改8300、模型服务或用户档案。
|
||||
|
||||
- `src/cybergril/api/app.py`:单进程 FastAPI 工厂;字段中文复验、无副作用真实排盘预览、唯一档案、只允许关系/称呼/边界修改、历史游标分页和 SSE。复用 `Store`、八字编译器、`ModelRouter` 与 `OpenAICompatLLM`。
|
||||
- `memory/schema.sql`:只增 `companion`、`api_meta`、`chat_message` 及索引;既有八字/生活/记忆/关系表保留。WAL;启动自动加 epoch,并把上次意外退出遗留的 pending 标记 cancelled。
|
||||
- `web/src/adapters/real.ts`、`app/RealApp.tsx`:普通入口只读服务器数据,404首建;复用创建、聊天、管理和人物静帧组件。真实入口不读/写 `cybergril.demo.v1`,草稿使用独立 `cg.real.draft`。`?demo=1` 仍由原 App 与 DemoAdapter 处理,零 API 请求。
|
||||
- 创建第二步通过 `POST /api/companion/preview` 排盘,不写档案;仅最终确认 POST 才在一个事务内写唯一档案和八字。SQLite 单行主键与事务保证并发只成功一次。生辰按 Asia/Shanghai、公历、1900年起、满18岁复验;时辰映射为对应双小时内偶数点,不引入出生地点/真太阳时规则。
|
||||
- SSE 使用同一 `turn_id` 和持久 `epoch`。前端每次发送先同步 epoch,并可处理发送前恰逢重启的409。轮次门槛继续拒绝旧事件;取消/退出直接 abort;服务端取消并等待上游结束后才开始新轮。响应缺少完成标志、空回答、异常或60秒超时均作为失败。部分回答丢弃,用户消息标 failed/cancelled,失败与取消的轮次不进下一轮上下文。成功回答可按同一 turn_id 回放,重试不会重复用户记录或重新生成已完成回答;并发相同轮次也只生成一次。
|
||||
- 模型三档均使用批准网关与模型,保留原 temperature、provider timeout 与预算。dialogue_main 路由限制最近20轮,再按档位上下文预算保留完整近轮;不截断当前用户消息。每轮最多默认1024输出 token,usage 缺失时按字符数保守估算计账,沿用原预算降档策略。原 BudgetGuard 的预算是进程内运维量,重启重置;不是持久化费用账本。
|
||||
|
||||
API 契约:
|
||||
|
||||
| API | 成功/错误 |
|
||||
|---|---|
|
||||
| GET `/api/health` | 200;epoch、是否已创建、模型探测与能力声明。模型 `/models` 2xx且包含配置模型才为真;5秒上限、30秒缓存、并发探测合并;不返回地址或凭据 |
|
||||
| GET `/api/companion` | 200档案(含只读四柱/白话),404未创建 |
|
||||
| POST `/api/companion/preview` | `{name,birth,hour}`→只读底色,422中文字段错误 |
|
||||
| POST `/api/companion` | `{name,birth,hour,relation,nickname?}`→201,409已有档案,422字段错误;拒绝额外字段 |
|
||||
| PATCH `/api/relation` | `{relation,nickname?,boundary?}`→更新后档案;404/422;无任何生辰/底色修改入口 |
|
||||
| GET `/api/messages?limit=200&before=<id>` | 升序 messages、next_before、epoch;每页1–200条;按id稳定排序;前端逐页恢复 |
|
||||
| POST `/api/chat` | `{text,turn_id,epoch}`;UUID turn_id;1–4000字;SSE chat.delta/final/error;404/409/422。chat.error带中文phi和retryable |
|
||||
|
||||
已接通:真实唯一档案、排盘、文字流式对话、服务器聊天历史、关系修改。尚未接通:生活循环、长期记忆检索/整合、主动消息、语音、视觉、天气、素材包与服务器备份。真实页面明确不可用,不填示例经历或伪造执行结果。当前只有近轮对话上下文,不把它说成长期记忆。
|
||||
|
||||
安装(Python ≥3.11;隔离环境,Node/npm用于构建):
|
||||
|
||||
```bash
|
||||
python3.11 -m venv .venv
|
||||
.venv/bin/pip install -r requirements.lock
|
||||
.venv/bin/pip install --no-deps .
|
||||
npm ci --prefix web
|
||||
npm run build --prefix web
|
||||
```
|
||||
|
||||
`requirements.lock` 固定本轮已解析的运行时依赖;开发检查另装 `pip install -e '.[dev]'`。默认 Python 3.10 不满足项目要求。服务不自动读取 `.env`,变量需由启动环境或 systemd 提供:
|
||||
|
||||
```bash
|
||||
export CYBERGRIL_DB=/absolute/separate/test-data/companion.db
|
||||
export CYBERGRIL_HOST=127.0.0.1
|
||||
export CYBERGRIL_PORT=18310
|
||||
.venv/bin/python -m cybergril.api
|
||||
```
|
||||
|
||||
从仓库根目录启动;默认模型配置 `config/models.yaml`、静态产物 `web/dist`,可分别通过 `CYBERGRIL_MODELS` / `CYBERGRIL_WEB` 指定绝对路径。本地默认数据库在用户 `.local/share/cybergril/`,生产必须显式指定独立数据目录。**单进程单worker,不启用reload或多worker。** 8310由总工部署时使用,本地测试脚本使用随机loopback端口、临时数据库并在结束时关闭服务。
|
||||
|
||||
自测:
|
||||
|
||||
```bash
|
||||
.venv/bin/pytest -q
|
||||
.venv/bin/ruff check src/cybergril/api src/cybergril/providers/llm/openai_compat.py tests/test_api.py
|
||||
npm run typecheck --prefix web
|
||||
npm run lint --prefix web
|
||||
npm test --prefix web
|
||||
npm run build --prefix web
|
||||
# 下列为可选浏览器工具,只装在测试虚拟环境:
|
||||
.venv/bin/pip install playwright
|
||||
.venv/bin/python -m playwright install chromium
|
||||
.venv/bin/python web/tests/real_browser_check.py
|
||||
.venv/bin/python web/tests/browser_check.py 1440
|
||||
.venv/bin/python web/tests/browser_check.py 390
|
||||
```
|
||||
|
||||
浏览器脚本启动/关闭自己的HTTP服务。真实脚本只向批准网关发两轮完整对话和一轮中途取消;随后切同源隔离桩验证失败、重启和立即新轮,结果区分真实模型与桩。环境若需额外浏览器运行库,应使用现有用户级库,不改系统/GPU环境。本轮复用 `/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu` 设置 LD_LIBRARY_PATH;它不是部署依赖。
|
||||
@@ -0,0 +1,7 @@
|
||||
普通入口此前只有未接服务说明,无法创建真实档案或与模型聊天。本次接通唯一服务器档案、无副作用排盘预览、真实SSE文字对话、历史恢复与关系修改;演示入口继续独立使用本机资料,零API请求,保持原两主题和统一组件。
|
||||
|
||||
服务端复用Store/八字编译/模型路由与OpenAI兼容provider,增量建表,持久epoch随启动递增。取消会关闭上游且不把残句存成完整回答;失败、取消轮不进入后续上下文;同轮重试/并发回放去重。未接生活、长期记忆、语音、视觉、天气、素材和备份均明确不可用。
|
||||
|
||||
验证:Python92项通过(原78+新增14),前端14项通过;typecheck/lint/build及新增Pythonruff通过。真实网关两轮上下文与一次中途取消有浏览器证据;电脑与390×844独立上下文、重启epoch、隔离错误/超时/断流、演示双主题零API请求通过。手机为浏览器模拟,无真机。验证细节及版本边界见docs/r1/TEST-RECORD.md。
|
||||
|
||||
运行安装/数据语义见docs/r1/IMPLEMENTATION.md;8310部署回滚材料及单进程systemd示例已备。数据必须独立于代码release,回滚不删;首次上线留待用户自行创建。本次未部署、未合并、未触碰8300和共享模型服务,交总工独立审核。
|
||||
@@ -0,0 +1,20 @@
|
||||
HEL-780 · R1 自测记录 · 2026-10-22(北京时间)
|
||||
|
||||
环境:Python3.11.16独立虚拟环境、Node24/npm11、Playwright1.64无头Chromium;生产前端构建;服务均为本机随机loopback端口、临时SQLite。未部署8310、未连接部署服务器、未访问4080或改动8300。真实模型仅连接批准的 .11:8731/v1,不安装或修改模型。
|
||||
|
||||
| 批准方案2.3 / 本卡补充验收 | 实测 |
|
||||
|---|---|
|
||||
| 1. 全新首建、真实排盘、必选关系 | 电脑四步浏览器通过;第二步四柱为庚辰/丙戌/己酉/乙亥;preview后companion与bazi_core均零记录;最终确认才写。API绕过校验:非法名/日期/未成年/早于1900/时辰/关系/未知字段均422中文错误;5个并发创建仅1个201,其余409;底色字段不可PATCH |
|
||||
| 2. 真实流式、取消和新轮隔离 | 网关两轮完成:设置“蓝色风铃”暗号,次轮直接答“蓝色风铃”。第三轮长故事在首个delta后取消;用户记录cancelled、无完整回答入库、上游请求已结束。隔离慢provider紧接新轮通过;另以真实OpenAICompatLLM连接隔离HTTP网关,验证浏览器侧断流后上游HTTP响应在1秒内关闭 |
|
||||
| 3. 重开/另一设备恢复 | 实际reload及另一独立Chromium上下文(390×844)恢复同一“星河”和两轮历史。**没有物理手机或另一台物理设备,独立上下文与手机视口模拟不称真机** |
|
||||
| 4. 重启epoch | 同origin停/启本地API,复用同一临时DB;epoch1→2,原页面直接续发通过。API测试同时验证档案/关系/历史保留,旧epoch409携当前epoch;前端单测覆盖过期epoch、其他turn拒绝 |
|
||||
| 5. 模型异常、失败草稿与去重 | 隔离错误provider抛异常→中文chat.error,隐藏内部详情、草稿恢复;同轮重试只增加1条回答,无重复用户记录。后端覆盖超时和上游提前结束;SSE单测覆盖UTF-8逐字节/CRLF/多帧/坏JSON/无final;并发相同turn只调用模型一次。另验证较早失败轮在较新轮完成后重试,上下文仍按完成轮次正确成对 |
|
||||
| 6. 演示隔离 | 演示电脑1440与手机390双主题全流程通过;每尺寸23个本机静态请求,**零API/外部请求**;无麦克风/摄像头申请。真实入口用存储读取陷阱断言cybergril.demo.v1零读取。正常页面无演示控制台;日子/长期记忆/语音/视觉/天气/素材/备份明确未接通 |
|
||||
| 7. health与history | health模型要求/models成功且含配置模型;401/404/503及其他模型均false。5秒超时、30秒缓存测试通过;不含地址/敏感配置。历史limit1–200、确定id顺序与before分页;非法页大小422 |
|
||||
| 8. 构建与测试 | Python **92 passed**(原78+新增14个参数化实例);前端 **14 passed**(原11+SSE3);typecheck/lint/build通过;新增Python与provider的ruff通过。CSS仍为原61.20KB,JS约207.70KB/gzip67.45KB;未加覆盖样式 |
|
||||
|
||||
浏览器截图在本目录:desktop-preview-moon、desktop-real-chat-moon、desktop-history-moon、desktop-model-error(该张为隔离故障)、mobile-history-moon、mobile-chat-fog、mobile-relation-fog。原始真实网关对话及逐项记录见 `browser-results.json`;末版隔离复测见 `controlled/browser-results.json`,来源明确区分,未拿桩回复冒充真实模型。
|
||||
|
||||
最终运行时锁定为requirements.lock(FastAPI0.159.1、Starlette1.7.0、uvicorn0.54.0、lunar-python1.4.8等)。初次真实网关浏览器证据采集时Starlette为1.9.0;锁定后在1.7.0完整重跑92项Python(含真实OpenAI兼容HTTP断流)、前端检查与相同浏览器关键路径隔离复测,均通过,避免为凑线重复调用共享模型。pytest有1条上游TestClient/httpx弃用提示,不影响结果,未另装不需要的httpx2。
|
||||
|
||||
没有覆盖:真机浏览器、正式8310/系统服务重启、生产数据迁移/权限与真实部署回滚、长期并发/长时间运行。上述部署验证由总工在审核后执行;模板与数据保留步骤见DEPLOY-ROLLBACK。当前单用户内网、单进程;近轮上下文与进程内预算不是长期记忆或持久费用账本。
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"checks": [
|
||||
"desktop: four-step real creation, side-effect-free lunar preview, mandatory relationship",
|
||||
"real gateway: complete streamed reply and second turn recalls 蓝色风铃 from server context",
|
||||
"real gateway: cancel after first delta, upstream request closed, no complete assistant row",
|
||||
"independent Chromium context 390×844: same companion/history; both themes; IME and Shift+Enter",
|
||||
"server restart on same origin: epoch 1→2, existing page sends automatically, data retained",
|
||||
"controlled SSE model error: Chinese notice, draft retained, same-turn retry without duplicate user row",
|
||||
"controlled blocked upstream: immediate cancellation/new question isolation",
|
||||
"mobile: relation cancel/confirm/save restores from server; unfinished life has no demo records/console"
|
||||
],
|
||||
"real_dialogue": [
|
||||
{
|
||||
"input": "请记住我们这次聊天的暗号是蓝色风铃。简短回应一句就好。",
|
||||
"reply": "星河暗号记住了,蓝色风铃。",
|
||||
"source": "real gateway"
|
||||
},
|
||||
{
|
||||
"input": "刚才我们的暗号是什么?请直接回答。",
|
||||
"reply": "星河蓝色风铃。",
|
||||
"source": "real gateway"
|
||||
},
|
||||
{
|
||||
"input": "重启后继续",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "新轮不会串台",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
}
|
||||
],
|
||||
"console_errors": []
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"checks": [
|
||||
"desktop: four-step real creation, side-effect-free lunar preview, mandatory relationship",
|
||||
"controlled provider: two complete streamed turns",
|
||||
"controlled provider: cancel after first delta, upstream request closed, no complete assistant row",
|
||||
"independent Chromium context 390×844: same companion/history; both themes; IME and Shift+Enter",
|
||||
"server restart on same origin: epoch 1→2, existing page sends automatically, data retained",
|
||||
"controlled SSE model error: Chinese notice, draft retained, same-turn retry without duplicate user row",
|
||||
"controlled blocked upstream: immediate cancellation/new question isolation",
|
||||
"mobile: relation cancel/confirm/save restores from server; unfinished life has no demo records/console"
|
||||
],
|
||||
"real_dialogue": [
|
||||
{
|
||||
"input": "请记住我们这次聊天的暗号是蓝色风铃。简短回应一句就好。",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "刚才我们的暗号是什么?请直接回答。",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "重启后继续",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "新轮不会串台",
|
||||
"reply": "星河答复",
|
||||
"source": "controlled provider"
|
||||
}
|
||||
],
|
||||
"console_errors": []
|
||||
}
|
||||
|
After Width: | Height: | Size: 713 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 535 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 346 KiB |
|
After Width: | Height: | Size: 213 KiB |
|
After Width: | Height: | Size: 90 KiB |
@@ -0,0 +1,77 @@
|
||||
HEL-783 六项返工交付与复审说明 · 2026-10-22
|
||||
|
||||
本轮由总管在可用的 Codex 环境亲自完成。沿用获批 HEL-746 R2 两主题和现有 R1 API,在原 PR#4 的 `agent/agent/de8874a3803b` 上追加修复,目标仍为 `main`。没有更换业务模型、修改现网或读写用户真实数据库,没有合并。最终提交号以 PR#4 最新 head 为准。
|
||||
|
||||
## 六项反馈闭环
|
||||
|
||||
| 用户反馈 / Before | 本轮 After | 实际验证 / Why |
|
||||
| --- | --- | --- |
|
||||
| 手机对话被输入栏挡住;台词和输入分别固定定位,没有长文高度预算 | `ChatPanel` 统一布局,人物占位、可滚动台词、状态/取消、语音条、输入分别占位;`Viewport` 跟随 visualViewport 的高度、顶部和底部偏移,含安全区。视口变化时人物窗立即调整,不等待装饰过渡 | 1440×900、360×640、390×700、390×844、390×420、844×390,两主题共12组;长中文前后文均在 DOM,可滚到末尾、完整记录能读全文。420高是键盘缩小等效场景,未冒称真机键盘实测 |
|
||||
| 流式全文在结束时被 `slice(-90)` 截成尾部;用户也被 `slice(-48)` 截断 | 当前双方消息保留全文;滚动阅读,跟随阅读位置;完整记录继续提供历史入口。流式和最终使用同一 turn 身份 | 长用户句首尾与五段长回复逐字相等;流式完成前后为同一个 DOM,取消立即中断,未完成文本标明未保存 |
|
||||
| 只写 opacity transition,没有真实改变透明度 | `SoftText` 按轮次用 WAAPI 淡入200ms、旧句保留160ms淡出;流式增量只更新文字,不重播。使用现有 `--ease-out`;减少动效120ms轻淡化 | 实际动画0/80/200ms逐帧截图及 computed opacity/transform;旧句0/80/159ms仍挂载、透明度递减。全轮只有一次入场,完成不重播,取消不等动画 |
|
||||
| 滚动条脱离主题 | 两套主题各有轨道/滑块/悬停 token;全局标准属性与 Chromium 兼容样式,强制色使用系统色;触摸区仍原生滚动 | 实际消息、记录、首建、设置长内容滚动及两主题截图;强制色有 CSS 回退。没有做真实辅助设备和各系统滚动条外观全覆盖测试 |
|
||||
| 底色只有公历和几个内部短标签 | 新增只读日历展示与六维解释映射:表达社交、亲密边界、冲突修复、行动节律、压力恢复、成长张力。显示真实农历/闰月、钟点、四柱和术语提示;每段可展开解释依据。预览/确认/已有档案共用组件 | 48组日期×时辰检查,含1900边界、春节、立春附近、真实闰四月;预览不写库。旧档案使用已存四柱、十神、Derived,禁止重新编译;GET前后原始JSON、底色行一致,关系修改不改底色和历史;聊天系统提示逐段复用同一解释 |
|
||||
| 分不清谁在说话 | 当前对话中“你”右对齐,真实伴侣名字左对齐,独立角色行;阅读状态行持续标明伴侣名字,滚动后也能确认正在读谁的回复。流式、最终、失败、取消与记录都使用同一身份 | 两主题截图,失败/重试、取消新轮、历史恢复都检查;不单靠颜色辨别 |
|
||||
| 真实入口把完整页面缩成“未接通”卡片 | 恢复日子/回忆双栏与分组;城市、外观、备份、四类服务的完整结构和真实空态;服务页可读健康检查,未接通写入控件明确禁用;加入未保存离开确认 | 实际手机逐页进入、返回、搜索空态、服务检查、未保存取消/放弃、演示事件→聊天→返回。真实入口无演示记录,演示模式全流程零API请求 |
|
||||
|
||||
## R2 功能覆盖差异表
|
||||
|
||||
“已接真”表示已有 API 持续可用;“本批补齐”表示前端结构/交互已恢复;“后台待接”表示本轮没有增加该后台能力,不能据此验收为已接通。
|
||||
|
||||
| R2 落点 | 演示模式 | 真实入口 | 本批结论 |
|
||||
| --- | --- | --- | --- |
|
||||
| 四类区域、两主题、底部导航 | 原有此刻/交谈/日子/设置 | 同样四区与主题切换 | 保留;手机短高度首页内容可滚动 |
|
||||
| 首页留言与日子入口 | 固定演示留言、已分享日子入口 | 服务器最近回复可打开完整记录;日子入口明确后台待接 | 本批补齐真实入口,历史已接真;不伪称主动留言 |
|
||||
| 日子列表、按日分组、三类事件、分页 | 原有已分享事件与18+12分页 | 完整列表区、三类图例和空态 | 本批补齐结构;真实生活后台待接,无示例填充 |
|
||||
| 事件详情、回忆互链、聊天与返回 | 可走详情→关联→聊天→回到原日子 | 详情阅读区域保留,无数据时不造条目/链接 | 演示路径实测;真实数据后台待接 |
|
||||
| 我们一起的/小习惯/她知道的你/成长 | 四组演示回忆、来源、关联日子 | 四组独立空态和阅读区 | 本批补齐真实分组;长期记忆后台待接 |
|
||||
| 隐私:她说过才显示 | 继续使用 publicView 过滤 | 当前没有生活/回忆数据 | 不放宽隐私,不展示未讲述事件 |
|
||||
| 首建四步、关系无预选、同意确认 | 本机独立创建;排盘不以固定假值冒充 | 服务端唯一档案、只读预览、实际创建 | 已接真;补公农历/闰月/四柱帮助和六维说明 |
|
||||
| 首建失败、返回修改、重试 | 原有模拟失败且保留输入 | API 中文错误、输入保留、409恢复唯一档案 | 保留;未增建档入口或清空入口 |
|
||||
| 她的档案与底色锁定 | 演示底色明确未计算 | 旧档案只读补展示,原参数和历史不动 | 本批补齐;无数据库迁移 |
|
||||
| 最初与后来成长分层 | 两栏及成长回忆 | 出生说明与后续记忆区分,当前长期记忆未接 | 不把出生说明当作已经发生的经历 |
|
||||
| 关系、称呼、边界;改变关系确认 | 原有模拟保存/取消/失败 | PATCH真实保存、二次确认、重开恢复 | 已接真,回归通过 |
|
||||
| 未保存提示、取消和离开 | 原有暖色点、取消、beforeunload | 同样提示;关闭/导航离开新增确认 | 本批补齐;取消继续编辑,放弃不写服务器 |
|
||||
| 城市搜索与列表/无结果 | 原有候选城市本机保存与失败演示 | 可搜索候选目录,有空态;明确未设置真实城市,保存禁用 | 本批补齐;真实城市/天气后台待接 |
|
||||
| 外观选择、五项检查、对比、确认 | JSON结构检查、对比与模拟标识确认 | 当前参考、文件入口、五项待检查、新旧对比、应用入口 | 本批补齐;真实导入与媒体检查禁用,后台待接 |
|
||||
| 自动备份列表、完整导出 | 已标真实备份未接通;本机演示JSON可导出 | 自动备份空列表、完整导出说明和禁用按钮 | 本批补齐;不制造成功备份 |
|
||||
| 恢复检查、同一档案、双重确认、先导出 | 原有本机恢复检查和输入“恢复” | 明示四步恢复过程;文件和执行入口禁用 | 本批补齐结构;真实恢复后台待接,不能实际覆盖 |
|
||||
| 四类外接服务与测试反馈 | 只保存演示地址,不发请求 | 文字、语音识别、语音合成、视觉四项;文字可重新检查健康,配置只读 | 本批补齐;不暴露凭据,不模拟其他连接成功 |
|
||||
| 显示、减少动效 | 原有本机设置 | 主题与减少动效保存于本浏览器,和服务器资料分开 | 减少动效刷新恢复;系统设置也生效 |
|
||||
| 长文字、完整记录、滚动、角色 | 模拟流式继续可用 | SSE、完整记录、失败与取消状态 | 本批修复全文、占位和角色;已接真 |
|
||||
| 重试、轮次/epoch、重启、多设备恢复 | 原有 TurnGate | 原有传输机制保留 | 确定性API测试和浏览器回归通过 |
|
||||
| 连续语音、打断、结束、拒绝/失败状态 | 保留无收音模拟和权限说明;新布局语音条不挡输入 | 控件明确尚未接通,文字仍可用 | 真实语音后台待接,未申请设备权限 |
|
||||
| 视觉说明、时效、失败、总服务区 | 原有30秒模拟过期与失败 | 明确未接通、不采集;服务项保留 | 真实视觉后台待接 |
|
||||
| 断线/模型不可达/草稿 | 原有断线重连演示 | 实际请求错误、草稿保留、重试、服务状态;已有档案历史可读 | 保留已接真能力;自动重连推送属后续,不假造补消息 |
|
||||
| 离开欢迎摘要、主动消息与未读 | 原有明确标注的固定演示,来源为已分享事件 | 生活/主动消息未接通,不伪造欢迎摘要或来信 | 后台待接;真实最近回复入口已保留 |
|
||||
| 手机列表/详情与设置返回、Esc | 保留推入和返回、原日子位置 | 同样区域/分区返回;Esc关闭记录再退出交流 | 本批补齐真实Esc与未保存确认 |
|
||||
| 新设计建议 | 无 | 无 | 未把新增后台能力夹进本批 |
|
||||
|
||||
## 验证记录
|
||||
|
||||
- Python 3.11:`pytest -q` **142通过**,含原92项和新增50项。唯一提示为既有 Starlette TestClient 依赖弃用提示。
|
||||
- TypeScript类型检查、ESLint、前端 **14项** Vitest、Vite生产构建通过。后端变更文件 Ruff通过。没有新增运行时依赖。
|
||||
- `web/tests/rework_browser_check.py`:8组通过,12组尺寸/主题组合;记录 `browser-results.json`。使用隔离SQLite和可控模型验证长中文、错误、取消与完整页面,不把可控模型说成在线模型。
|
||||
- `web/tests/real_browser_check.py --controlled`:8组回归通过,记录 `r1-regression/browser-results.json`。包括真实HTTP SSE、浏览器关闭流、立即新轮、同源重启epoch变化、多设备恢复、关系取消/确认保存。
|
||||
- `web/tests/real_browser_check.py`:真实批准网关完成两轮对话,第二轮正确回答上一轮暗号“蓝色风铃”;第三轮收到增量后取消,上游请求结束且没有完整回复落库。随后同源重启和故障段使用可控provider,结果逐项区分,记录 `live-gateway/browser-results.json`。所有建档、聊天和关系写入仍只在临时库。
|
||||
- 动效证据:`motion-enter-0/80/200.png` 和结果JSON中的 `motion.entry_frames/exit_frames`。截图暂停实际 WAAPI 后逐帧采样,随后恢复;没有为截图修改生产动画时长。
|
||||
- 代表图:`long-start-360-640-*.png`、`long-start/long-end-390-420-*.png`、`full-history-*.png`、`birth-*.png`、`existing-*.png`、城市/外观/备份/服务/生活回忆各图。图中“星河/小满”和聊天全部是本轮隔离测试资料。
|
||||
- 已实际看过代表性手机长文、短视口、语音模拟、出生预览、已有档案说明、服务页、回忆分组截图;复审仍需独立看图、播放实际界面,不能只用坐标和测试数认定视觉通过。
|
||||
- 未测:实体手机键盘、Safari、真实强制色设备、屏幕阅读器、长时运行和帧率。420/390高只证明等效可见高度布局,不等于真机键盘实测。
|
||||
|
||||
## 说明层的兼容性与回滚
|
||||
|
||||
`core/birth_view.py` 是可维护的确定性解释映射,不调用模型润色。分档值只选择解释段落,不产生新的底色参数。敏感度的展示分档与普通0–1参数分别归一到解释选择范围。四柱与十神取旧库已存值,五行侧重和性格取旧Derived;日历只从不可变生日、时辰换算展示。没有重新调用旧档案的四柱编译器,也没有把新说明写回旧档案。新增档案会在原有JSON中携带可选展示字段;旧字段仍保留,旧前端不依赖新增字段。
|
||||
|
||||
聊天提示与UI共用六段解释,仍明确本体、现实边界、未接通能力和不能编造生活。取消、历史、epoch、路由和业务模型配置未改。服务端关系修改只保存关系字段及原档案JSON,不把本次只读展示偷偷写回旧档案。
|
||||
|
||||
本批无schema改动、不需要重建库。回滚只切回上一个程序版本;旧版忽略JSON新增字段。服务器切换前按HEL-784要求备份,不能删除、替换或重算用户档案。浏览器新加 `cg.real.display` 仅保存减少动效偏好;不存真实聊天或底色。
|
||||
|
||||
## 给HEL-784的部署交接
|
||||
|
||||
1. 重新读取PR#4最新head,与本轮交付SHA一致后审核;base仍main。远端若另有推进,先协调,不覆盖。
|
||||
2. 独立运行检查,实际看截图及流式/取消/渐入渐出,特别检查用户原截图对应的手机短视口和长回复。
|
||||
3. 安装方式沿用 `docs/r1/IMPLEMENTATION.md`:Python≥3.11、`requirements.lock`、安装当前包,`npm ci --prefix web` 和 `npm run build --prefix web`。浏览器测试可选Playwright,不是部署依赖。
|
||||
4. 审核通过才部署8310的新release,保留现有用户库,切换前备份;不要把本轮临时测试库、测试人物或演示存储带上服务器。8300和其他服务不动。
|
||||
5. 回读现有档案/历史与health,检查新静态资源和旧档案补充说明;附件不要泄露真实聊天全文。记录部署SHA、备份位置和回滚指令。
|
||||
6. 本批用户尚未验收,不合并、不归档、不推进到收尾。
|
||||
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 557 KiB |
|
After Width: | Height: | Size: 516 KiB |
@@ -0,0 +1,391 @@
|
||||
{
|
||||
"checks": [
|
||||
"Real creation: lunar leap month, all six explanations, same final confirmation; preview writes no rows",
|
||||
"Long Chinese stream: entire user/reply retained; final keeps same DOM; one entrance across all chunks and final",
|
||||
"Old sentence stays mounted during a visible 160ms fade-out, then leaves",
|
||||
"12 viewport/theme combinations: long text scrolls, stage/dialog/composer/navigation never overlap; full history reachable",
|
||||
"Cancel then immediate new turn, model error and same-turn retry preserve roles and avoid duplicate user messages",
|
||||
"Restored real pages: city search/empty, appearance/check/compare, backup/recovery, four services/live health, life/memory groups; unsaved close guard",
|
||||
"Escape navigation; browser display preference survives reload; settings/system reduced motion uses gentle opacity",
|
||||
"Demo has its own profile, voice simulation, life/detail/chat/return path and zero API requests"
|
||||
],
|
||||
"viewports": [
|
||||
{
|
||||
"width": 1440,
|
||||
"height": 900,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 564,
|
||||
"bottom": 734,
|
||||
"height": 170
|
||||
},
|
||||
"composer": {
|
||||
"top": 746,
|
||||
"bottom": 806,
|
||||
"height": 60
|
||||
},
|
||||
"nav": {
|
||||
"top": 818,
|
||||
"bottom": 878,
|
||||
"height": 60
|
||||
},
|
||||
"stage": {
|
||||
"top": 72,
|
||||
"bottom": 552,
|
||||
"height": 480
|
||||
},
|
||||
"scrollHeight": 1848,
|
||||
"clientHeight": 142,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 1440,
|
||||
"height": 900,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 564,
|
||||
"bottom": 734,
|
||||
"height": 170
|
||||
},
|
||||
"composer": {
|
||||
"top": 746,
|
||||
"bottom": 806,
|
||||
"height": 60
|
||||
},
|
||||
"nav": {
|
||||
"top": 818,
|
||||
"bottom": 878,
|
||||
"height": 60
|
||||
},
|
||||
"stage": {
|
||||
"top": 72,
|
||||
"bottom": 552,
|
||||
"height": 480
|
||||
},
|
||||
"scrollHeight": 1848,
|
||||
"clientHeight": 142,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 360,
|
||||
"height": 640,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 220,
|
||||
"bottom": 492,
|
||||
"height": 272
|
||||
},
|
||||
"composer": {
|
||||
"top": 500,
|
||||
"bottom": 556,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 566,
|
||||
"bottom": 624,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 212,
|
||||
"height": 154
|
||||
},
|
||||
"scrollHeight": 2876,
|
||||
"clientHeight": 244,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 360,
|
||||
"height": 640,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 220,
|
||||
"bottom": 492,
|
||||
"height": 272
|
||||
},
|
||||
"composer": {
|
||||
"top": 500,
|
||||
"bottom": 556,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 566,
|
||||
"bottom": 624,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 212,
|
||||
"height": 154
|
||||
},
|
||||
"scrollHeight": 2876,
|
||||
"clientHeight": 244,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 700,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 253,
|
||||
"bottom": 552,
|
||||
"height": 299
|
||||
},
|
||||
"composer": {
|
||||
"top": 560,
|
||||
"bottom": 616,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 626,
|
||||
"bottom": 684,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 245,
|
||||
"height": 187
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 271,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 700,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 253,
|
||||
"bottom": 552,
|
||||
"height": 299
|
||||
},
|
||||
"composer": {
|
||||
"top": 560,
|
||||
"bottom": 616,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 626,
|
||||
"bottom": 684,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 245,
|
||||
"height": 187
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 271,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 844,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 332.1875,
|
||||
"bottom": 696,
|
||||
"height": 363.8125
|
||||
},
|
||||
"composer": {
|
||||
"top": 704,
|
||||
"bottom": 760,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 770,
|
||||
"bottom": 828,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 324.1875,
|
||||
"height": 266.1875
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 335,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 844,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 332.1875,
|
||||
"bottom": 696,
|
||||
"height": 363.8125
|
||||
},
|
||||
"composer": {
|
||||
"top": 704,
|
||||
"bottom": 760,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 770,
|
||||
"bottom": 828,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 324.1875,
|
||||
"height": 266.1875
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 335,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 420,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 106,
|
||||
"bottom": 272,
|
||||
"height": 166
|
||||
},
|
||||
"composer": {
|
||||
"top": 280,
|
||||
"bottom": 336,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 346,
|
||||
"bottom": 404,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 98,
|
||||
"height": 40
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 138,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 420,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 106,
|
||||
"bottom": 272,
|
||||
"height": 166
|
||||
},
|
||||
"composer": {
|
||||
"top": 280,
|
||||
"bottom": 336,
|
||||
"height": 56
|
||||
},
|
||||
"nav": {
|
||||
"top": 346,
|
||||
"bottom": 404,
|
||||
"height": 58
|
||||
},
|
||||
"stage": {
|
||||
"top": 58,
|
||||
"bottom": 98,
|
||||
"height": 40
|
||||
},
|
||||
"scrollHeight": 2735,
|
||||
"clientHeight": 138,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 844,
|
||||
"height": 390,
|
||||
"theme": "moon",
|
||||
"dialog": {
|
||||
"top": 124,
|
||||
"bottom": 224,
|
||||
"height": 100
|
||||
},
|
||||
"composer": {
|
||||
"top": 236,
|
||||
"bottom": 296,
|
||||
"height": 60
|
||||
},
|
||||
"nav": {
|
||||
"top": 308,
|
||||
"bottom": 368,
|
||||
"height": 60
|
||||
},
|
||||
"stage": {
|
||||
"top": 72,
|
||||
"bottom": 112,
|
||||
"height": 40
|
||||
},
|
||||
"scrollHeight": 2178,
|
||||
"clientHeight": 72,
|
||||
"overflow": false
|
||||
},
|
||||
{
|
||||
"width": 844,
|
||||
"height": 390,
|
||||
"theme": "fog",
|
||||
"dialog": {
|
||||
"top": 124,
|
||||
"bottom": 224,
|
||||
"height": 100
|
||||
},
|
||||
"composer": {
|
||||
"top": 236,
|
||||
"bottom": 296,
|
||||
"height": 60
|
||||
},
|
||||
"nav": {
|
||||
"top": 308,
|
||||
"bottom": 368,
|
||||
"height": 60
|
||||
},
|
||||
"stage": {
|
||||
"top": 72,
|
||||
"bottom": 112,
|
||||
"height": 40
|
||||
},
|
||||
"scrollHeight": 2178,
|
||||
"clientHeight": 72,
|
||||
"overflow": false
|
||||
}
|
||||
],
|
||||
"motion": {
|
||||
"entry_frames": [
|
||||
{
|
||||
"time": 0,
|
||||
"opacity": "0",
|
||||
"transform": "matrix(1, 0, 0, 1, 0, 3)"
|
||||
},
|
||||
{
|
||||
"time": 80,
|
||||
"opacity": "0.917147",
|
||||
"transform": "matrix(1, 0, 0, 1, 0, 0.248559)"
|
||||
},
|
||||
{
|
||||
"time": 200,
|
||||
"opacity": "1",
|
||||
"transform": "none"
|
||||
}
|
||||
],
|
||||
"exit_frames": [
|
||||
{
|
||||
"time": 0,
|
||||
"opacity": "1",
|
||||
"retained": true
|
||||
},
|
||||
{
|
||||
"time": 80,
|
||||
"opacity": "0.0386175",
|
||||
"retained": true
|
||||
},
|
||||
{
|
||||
"time": 159,
|
||||
"opacity": "3.47566e-08",
|
||||
"retained": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"console_errors": [],
|
||||
"limits": [
|
||||
"Chromium only; physical phone keyboard, Safari and screen reader not tested.",
|
||||
"LLM is controlled for deterministic long-stream/error/cancel checks, not a live gateway."
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 259 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 366 KiB |
|
After Width: | Height: | Size: 350 KiB |
|
After Width: | Height: | Size: 124 KiB |
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"checks": [
|
||||
"desktop: four-step real creation, side-effect-free lunar preview, mandatory relationship",
|
||||
"real gateway: complete streamed reply and second turn recalls 蓝色风铃 from server context",
|
||||
"real gateway: cancel after first delta, upstream request closed, no complete assistant row",
|
||||
"independent Chromium context 390×844: same companion/history; both themes; IME and Shift+Enter",
|
||||
"server restart on same origin: epoch 1→2, existing page sends automatically, data retained",
|
||||
"controlled SSE model error: Chinese notice, draft retained, same-turn retry without duplicate user row",
|
||||
"controlled blocked upstream: immediate cancellation/new question isolation",
|
||||
"mobile: relation cancel/confirm/save restores from server; unfinished life has no demo records/console"
|
||||
],
|
||||
"real_dialogue": [
|
||||
{
|
||||
"input": "请记住我们这次聊天的暗号是蓝色风铃。简短回应一句就好。",
|
||||
"reply": "好的,暗号是蓝色风铃。",
|
||||
"source": "real gateway"
|
||||
},
|
||||
{
|
||||
"input": "刚才我们的暗号是什么?请直接回答。",
|
||||
"reply": "蓝色风铃。",
|
||||
"source": "real gateway"
|
||||
},
|
||||
{
|
||||
"input": "重启后继续",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "新轮不会串台",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
}
|
||||
],
|
||||
"console_errors": []
|
||||
}
|
||||
|
After Width: | Height: | Size: 251 KiB |
|
After Width: | Height: | Size: 221 KiB |
|
After Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 145 KiB |
|
After Width: | Height: | Size: 374 KiB |
|
After Width: | Height: | Size: 363 KiB |
|
After Width: | Height: | Size: 240 KiB |
|
After Width: | Height: | Size: 213 KiB |
|
After Width: | Height: | Size: 142 KiB |
|
After Width: | Height: | Size: 137 KiB |
|
After Width: | Height: | Size: 363 KiB |
|
After Width: | Height: | Size: 354 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 974 KiB |
|
After Width: | Height: | Size: 1016 KiB |
|
After Width: | Height: | Size: 1017 KiB |
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"checks": [
|
||||
"desktop: four-step real creation, side-effect-free lunar preview, mandatory relationship",
|
||||
"controlled provider: two complete streamed turns",
|
||||
"controlled provider: cancel after first delta, upstream request closed, no complete assistant row",
|
||||
"independent Chromium context 390×844: same companion/history; both themes; IME and Shift+Enter",
|
||||
"server restart on same origin: epoch 1→2, existing page sends automatically, data retained",
|
||||
"controlled SSE model error: Chinese notice, draft retained, same-turn retry without duplicate user row",
|
||||
"controlled blocked upstream: immediate cancellation/new question isolation",
|
||||
"mobile: relation cancel/confirm/save restores from server; unfinished life has no demo records/console"
|
||||
],
|
||||
"real_dialogue": [
|
||||
{
|
||||
"input": "请记住我们这次聊天的暗号是蓝色风铃。简短回应一句就好。",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "刚才我们的暗号是什么?请直接回答。",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "重启后继续",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
},
|
||||
{
|
||||
"input": "新轮不会串台",
|
||||
"reply": "答复",
|
||||
"source": "controlled provider"
|
||||
}
|
||||
],
|
||||
"console_errors": []
|
||||
}
|
||||
|
After Width: | Height: | Size: 97 KiB |
@@ -1,72 +0,0 @@
|
||||
# HEL-715 素材包规范与施工方案(可交施工员)
|
||||
|
||||
依据 CG-029(日常用成品视频、交谈用同一人物实时口型)、CG-005/006(换外观保留人格/记忆/关系)、CG-030(首批素材小队制作)。原则:单图不自动生成整套;每份素材可独立替换、可校验、可回滚。
|
||||
|
||||
## 1. 素材包目录规范
|
||||
|
||||
```
|
||||
assets/personas/<persona>/ # persona=外观方案,如 wanwan-v2;换外观=新目录
|
||||
manifest.json # 见下
|
||||
daily/ # 日常成品视频(CG-029 主路线)
|
||||
<scene-id>.mp4 # H.264 25fps ≥6s 可无缝循环;按时段/天气/活动命名
|
||||
talk/ # 交谈底板(近景,同房间同脸同服装)
|
||||
<talk-id>.mp4 # H.264 25fps 5~15s,人物目视镜头、口部微闭或自然微动
|
||||
voice/ # CosyVoice 音色登记名(.12 voices.json 中的 voice 名)
|
||||
ref/ # 定妆照/场景照 PNG(身份对照用)
|
||||
```
|
||||
|
||||
`manifest.json` 必填字段:`persona_id`、`identity_ref`(ref/ 内主定妆图)、`daily_clips[{id, timeofday, weather, activity, loop_points}]`、`talk_clips[{id, avatar_id, framing}]`、`created_by`、`created_at`、`pipeline_version`(如 hel715-v1)。
|
||||
|
||||
## 2. 身份/服装/光线一致性标记(导入校验项)
|
||||
|
||||
- 同一 persona 内所有 daily/talk 片段必须与 `identity_ref` 同人物、同发型、同套服装;换服装=新 persona 目录。
|
||||
- 每段导入时人工对照 ref 图打勾(首版人工,不做自动人脸embedding校验——留待后续)。
|
||||
- 光线:同一 persona 的交谈底板光线需与常用日常场景一致(近景底板从日常成品裁切放大可天然保证,如本轮 talk-close = loop 1.75× 裁切)。
|
||||
|
||||
## 3. 可切节点与缺素材回退
|
||||
|
||||
- 日常片循环点:`loop_points` 记录首尾衔接帧(硬循环跳变处需美术确认或选首尾近同帧的段)。
|
||||
- 交谈进入点:任意时刻可切(预连接流,实测切换 0~3ms);退出点同。
|
||||
- 缺素材回退顺序:请求场景无 daily 片 → 用同 persona 默认 daily 片;无 talk 底板 → 禁用交谈入口并提示,不得用其他人物素材顶替;TTS 失败 → 显示重试按钮,不静默。
|
||||
|
||||
## 4. 导入与回滚流程(本轮实测命令)
|
||||
|
||||
```
|
||||
# 1) 预处理:任意源 → H.264 25fps(示例见 scripts/,PyAV,秒级)
|
||||
# 2) 生成交谈 avatar(47~60s GPU/份,独立目录,无硬编码):
|
||||
cd /opt/hel715-verify/LiveTalking
|
||||
venv/bin/python -m avatars.musetalk.genavatar --file <talk-clip.mp4> --avatar_id <persona>-<talk-id>
|
||||
# 3) 校验:data/avatars/<id>/ 含 avator_info.json/coords.pkl/latents.pt/mask;avator_info.json 的 video_path 指向素材包内文件
|
||||
# 4) 服务挂载:app.py --avatar_id <id>(或 custom_config 多 avatar 预载)
|
||||
```
|
||||
|
||||
回滚:素材包按目录整体保留旧版本(`<persona>.bak-<date>`),avatar 目录同理;manifest 记录版本,恢复=改回引用。模型权重不入 Git,assets 二进制走附件/对象存储,仓库只放 manifest 与脚本。
|
||||
|
||||
## 5. 换一套外观的实测成本(CG-005/006 输入)
|
||||
|
||||
| 项 | 实测耗时 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 交谈底板由既有成品裁切 | <1min(PyAV 转码)+ 47~60s genavatar | 本轮 talk-close 路线,推荐 |
|
||||
| 交谈底板由 Wan2.2 全新生成 | ~57s/3s 片段 + 挑选重试(3~5 倍余量) | HEL-712 实测单次推理 |
|
||||
| 日常成品视频生成 | 同上量级/段 | 小队批量制作 |
|
||||
| 照片需求 | 定妆/场景各 ≥1 张 | 用于身份对照与 i2v 起点 |
|
||||
| 预处理 | 自动,无人工参数 | bbox_shift=0 默认可用 |
|
||||
|
||||
## 6. 首版最小验收矩阵(交谈链路)
|
||||
|
||||
| 项 | 通过标准 |
|
||||
| --- | --- |
|
||||
| 日常循环播放 | ≥3 周期无肉眼跳变(或美术确认衔接) |
|
||||
| 进交谈 | 切换 ≤200ms,同人物同服装目视确认 |
|
||||
| 口型 | 说话段口部动作肉眼可辨,静息段无明显异常 |
|
||||
| 打断 | interrupt 后 ≤1s 静音,不等播完 |
|
||||
| 再开口 | 打断后可立即再次发话 |
|
||||
| 回日常 | 切回 ≤200ms,日常从暂停点续播 |
|
||||
| 持续 | 单次会话 ≥10 分钟不崩、显存不涨 |
|
||||
| 失败路径 | TTS 断连时有可见错误提示,可恢复 |
|
||||
|
||||
## 7. 职责划分(衔接 HEL-714 施工)
|
||||
|
||||
- 客户端(web):日常选片/循环、交谈视图挂载(预连接 WebRTC)、打断信号(先按钮/快捷键,VAD 后置)、失败回退 UI。
|
||||
- 服务端:LiveTalking(交谈渲染 + TTS 适配,本分支 patch);日常视频静态文件由现有 web 服务出。
|
||||
- 素材:美术/施工按第 1 节规范产出,总工验收导入。
|
||||
@@ -1,42 +0,0 @@
|
||||
# HEL-715 实验复现说明
|
||||
|
||||
实验环境(.12,全部隔离在 `/opt/hel715-verify/`,未改系统 Python/CUDA/ASR/TTS):
|
||||
|
||||
- LiveTalking c726943(官方 GitHub)+ MuseTalk v1.5 权重 3.8GB(`LiveTalking/models/`)
|
||||
- venv:`/opt/hel715-verify/venv`(torch 2.8.0+cu128、aiortc 1.15.0、PyAV 17.1.0)
|
||||
- 既有服务复用:CosyVoice TTS `http://127.0.0.1:9880`(音色 xiaoyun)、LLM `http://192.168.200.11:8731`(halogen-qwen3.8-flash-next)
|
||||
- 对上游的两处改动:`livetalking-patch/cosyvoice.py`(新增,对接 .12 CosyVoice)、`livetalking-patch/enable-cosyvoice-registration.diff`(base_avatar.py 启用注册)
|
||||
|
||||
## 启动
|
||||
|
||||
```bash
|
||||
cd /opt/hel715-verify/LiveTalking
|
||||
nohup /opt/hel715-verify/venv/bin/python app.py --model musetalk \
|
||||
--avatar_id hel715-talk-close --transport webrtc \
|
||||
--tts cosyvoice --REF_FILE xiaoyun \
|
||||
--TTS_SERVER http://127.0.0.1:9880 --listenport 8010 \
|
||||
> /opt/hel715-verify/livetalking.log 2>&1 &
|
||||
```
|
||||
|
||||
注意:仓库内 `config.yaml` 的 `TTS_SERVER: ''` 会覆盖 argparse 默认值,必须显式传 `--TTS_SERVER`(本轮曾因此空跑过一次)。
|
||||
|
||||
已生成 avatar(`LiveTalking/data/avatars/`):`hel715-loop-wide`(loop-25fps.mp4,196 帧全景)、`hel715-talk-close`(talk-close.mp4,196 帧近景=loop 1.75× 裁切)、`hel715-return`(return-25fps.mp4,77 帧独立源)。
|
||||
|
||||
## 测试脚本
|
||||
|
||||
- `scripts/e2e_client.py`:aiortc 收流客户端,四句时间线(含打断),产出 mp4+stats.json+events.json+contact-sheet.png。在 .12 上运行:`E2E_OUT=... venv/bin/python e2e_client.py`。
|
||||
- `scripts/llm_chain2.py`:LLM→TTS→数字人单链路采样。
|
||||
- `scripts/hel715-chain.html`:日常→交谈→打断→回日常→再交谈演示页(部署于 LiveTalking `web/`,`?auto=1` 自动演示;依赖 `web/hel715-daily.webm`)。
|
||||
- `scripts/record_chain.py`:本机(192.168.200.13)Playwright+Chromium 录制上述页面,需 LD_LIBRARY_PATH 指向解包的运行库(脚本内已写死 /tmp 路径,迁移时改)。
|
||||
|
||||
## 清理
|
||||
|
||||
```bash
|
||||
# 停实验服务(先对 PID:pgrep -af 'app.py --model musetalk')
|
||||
pkill -f 'app.py --model musetalk'
|
||||
# 删除整个实验目录(含 venv/权重/素材,约 12GB)
|
||||
rm -rf /opt/hel715-verify
|
||||
# 演示页随目录一起消失;18080/18081 旧演示与 ASR/TTS 未动
|
||||
```
|
||||
|
||||
本轮收尾状态:LiveTalking 已停止;目录与权重保留供 HEL-714 复用。
|
||||
@@ -1,73 +0,0 @@
|
||||
# HEL-715 技术验证报告:本地真人交谈与日常视频衔接
|
||||
|
||||
日期:2026-10-20 | 环境:192.168.200.12(RTX 5090D 32GB,torch 2.8.0+cu128)
|
||||
候选:LiveTalking @ c726943(官方 GitHub)+ MuseTalk v1.5 + .12 既有 CosyVoice(9880) + .11 LLM(halogen-qwen3.8-flash-next)
|
||||
|
||||
## 一句话结论
|
||||
|
||||
**有条件可用。** 日常↔交谈切换、打断、25fps 连续口型视频、素材流水线复用均实测通过;条件是接受 ①发话到出声约 4.5~5.5s 的起步延迟,②TTS 流式按标点分句带来的句内 0.4~1.1s 停顿,③交谈驱动只改口型(表情/目光来自底板视频)。三项都需要在首版验收时向用户如实展示,其中 ①② 可在施工阶段继续压。
|
||||
|
||||
## 四个问题的实测回答
|
||||
|
||||
### 1. 主候选 LiveTalking+MuseTalk 实际跑通了吗?——跑通
|
||||
|
||||
- 安装:官方仓库 clone 至 `/opt/hel715-verify/LiveTalking`,独立 venv(不改系统 Python/CUDA/ASR/TTS);权重 musetalkV15/face-parse/sd-vae/whisper 共约 3.8GB,已就位。
|
||||
- 适配:仅两处改动(见 `livetalking-patch/`):`tts/cosyvoice.py` 新增(对接 .12 既有 CosyVoice 的 POST /tts 24kHz PCM 流)+ `avatars/base_avatar.py` 启用该 TTS 注册。其余代码未动。
|
||||
- 能力边界(CG-028 相关,明确来源):
|
||||
- **口型**:实时音频驱动(whisper 特征→unet 逐帧生成下半脸)——实测(口部区差分:静息中位 0.74 vs 说话峰值 13~14)。
|
||||
- **表情/目光/头姿/身体**:全部来自底板视频循环(预处理时逐帧 landmark+face-parse 固化),**不是**实时生成——来源:代码结构+录像复核。交谈底板选片时必须挑"目视镜头、微动作"段。
|
||||
- 不要求也不提供逐句新肩部手势;与 CG-027/028 的预期一致,未发现必须换 Ditto 等替代的实证。
|
||||
|
||||
### 2. 同一人物实时交谈可否成立?——可以,起步延迟与句内停顿需接受
|
||||
|
||||
实测(aiortc 客户端走真实 WebRTC 通道,含网络传输;e2e-session.mp4 / stats.json):
|
||||
|
||||
| 指标 | 实测值 |
|
||||
| --- | --- |
|
||||
| 连接→首帧视频 | 3.6s(含 ICE 协商 1.7s) |
|
||||
| 文本→首次出声 | 4.6~5.5s(CosyVoice 首包 3.4s + LiveTalking 音频缓冲约 1.2s) |
|
||||
| 连续帧率 | 25.05fps 恒定(27s 全程,说话与静息一致) |
|
||||
| 音画同步 | 容器内音视频齐备;口型动作较出声晚约 0.5~1.3s(MuseTalk 音频前瞻缓冲所致)。自动互相关度量噪声大,最终以录像人工复核为准 |
|
||||
| 句内停顿 | TTS 按标点分句合成,句内间隙 0.45~1.05s("抱歉"与"你刚想说什么"之间 0.66s)——CosyVoice 流式模式固有,非口型管线问题 |
|
||||
| 打断→静音 | **0.35s**(interrupt_talk 后队列即清) |
|
||||
| 打断后再开口 | 正常(S3/S4 均正常播出) |
|
||||
| 峰值资源 | 总显存 18.9GB(基线 5.8GB + CosyVoice 4.2GB + LiveTalking 空载 11.2GB/说话峰值约 13.1GB);GPU 利用率瞬时 100% 但帧率不跌 |
|
||||
| 失败行为 | 本轮未触发服务崩溃;语音名不存在时 TTS 适配层回退 default 音色 |
|
||||
|
||||
LLM 链路(llm-chain.mp4):.11 真实模型 halogen-qwen3.8-flash-next 回复 1.33s → 递给数字人出声共 4.63s,全程录音正常。
|
||||
|
||||
### 3. 日常→交谈→打断→回日常衔接?——信号级链路实测通过
|
||||
|
||||
两份证据:
|
||||
|
||||
- **浏览器真实链路**(chain/page@*.webm,Playwright+Chromium 走 LAN WebRTC):日常成品视频循环 → 切交谈视图(预连接流,切换 0~3ms)→ 发文本 → 语音进行中注入 interrupt_talk(HTTP 2~5ms)→ 立即切回日常(不等她说完、不等日常片尾)→ 再次进入交谈并发第二句 → 回日常。全程 33.5s,页面零 JS 错误。注:Playwright 录屏不含音轨,音频证据见下条。
|
||||
- **媒体级连续音画**(e2e-session.mp4):同一 WebRTC 通道收到的连续音视频原样落盘,覆盖 静息→说话→打断→静默→再说话 全程,有声有画。
|
||||
|
||||
边界说明:麦克风/VAD 未接入,打断由信号注入触发,**只是信号级验证**,不冒充自然语音抢话已通过。转场为视图级切换(同人物同房间同服装的近景底板 vs 日常全景),自然转场(如淡入淡出)属施工项,不计入本轮结论。
|
||||
|
||||
### 4. 素材能否持续制作/替换/维护?——流水线已验证可复用
|
||||
|
||||
- 同一流水线已跑通 **3 份素材、3 个 avatar**:loop 全景(196 帧)、面部近景(196 帧,经核实为 loop 素材 1.75× 放大裁切,同人物同房间同服装)、回程片段(77 帧,独立源文件)。
|
||||
- 新素材仅需:转码 25fps mp4 → `python -m avatars.musetalk.genavatar --file X --avatar_id Y`,47~60s/份(GPU),零代码改动、目录隔离、无硬编码人脸。
|
||||
- 成本实测:交谈底板若由 Wan2.2 生成约 57s/3s 片段(HEL-712 实测);由既有成品裁切仅需秒级(PyAV)。详见 MATERIAL-SPEC.md。
|
||||
- 限制:本轮三份素材同属一个人物;跨人物泛化未实测(离线环境无第二真人素材可用),算法层面为通用 landmark/face-parse 管线,无按脸硬编码逻辑。
|
||||
|
||||
## CG-029/028 能力矩阵(来源/实测/未测)
|
||||
|
||||
| 能力 | 状态 | 依据 |
|
||||
| --- | --- | --- |
|
||||
| 成品日常视频按时段/活动选片播放 | 实测(浏览器循环播放) | chain webm |
|
||||
| 同人物近景实时口型交谈 | 实测 | e2e-session.mp4 / llm-chain.mp4 |
|
||||
| 口型由音频实时驱动 | 实测 | 口部差分 15~19 倍 |
|
||||
| 表情/目光实时生成 | 未测(来源=底板视频) | 代码结构 |
|
||||
| 语音打断(信号级) | 实测 0.35s 停止 | events.json |
|
||||
| 自然语音抢话(VAD) | 未测 | 麦克风未接 |
|
||||
| 日常↔交谈视图切换 | 实测 0~3ms | chain webm + 日志 |
|
||||
| LLM→TTS→口型全链 | 实测 | llm-chain.mp4 |
|
||||
| 素材替换保留人格记忆 | 设计已验证路径(素材目录隔离) | genavatar 复用 |
|
||||
|
||||
## 风险与建议(给总管的决策输入)
|
||||
|
||||
1. **起步延迟 4.5~5.5s** 是当前体验最大短板:可在施工时用"思考中"微动作/状态提示掩盖,或后续换更低首包延迟的 TTS 配置(CosyVoice 首包 3.4s 占大头)。无已确认延迟门槛,不编造 SLA;建议向用户展示实测录像后再定验收线。
|
||||
2. **句内停顿**可通过 TTS 侧整句缓冲或标点预处理缓解,代价是首包更慢——二者权衡留施工阶段。
|
||||
3. LiveTalking 空载即占 11.2GB 显存,与 ComfyUI 重生成任务并存时需调度(先交谈后生成的队列约定)。
|
||||
@@ -1,82 +0,0 @@
|
||||
import time
|
||||
import numpy as np
|
||||
import resampy
|
||||
import requests
|
||||
from io import BytesIO
|
||||
from typing import Iterator
|
||||
|
||||
from utils.logger import logger
|
||||
from .base_tts import BaseTTS, State
|
||||
from registry import register
|
||||
|
||||
|
||||
@register("tts", "cosyvoice")
|
||||
class CosyVoiceTTS(BaseTTS):
|
||||
"""适配本机既有 CosyVoice3 流式 TTS (POST /tts -> 24kHz int16 PCM 流)."""
|
||||
|
||||
def txt_to_audio(self, msg: tuple[str, dict]):
|
||||
text, textevent = msg
|
||||
voice = textevent.get('tts', {}).get('voice', self.opt.REF_FILE or 'default')
|
||||
self.stream_tts(self.cosyvoice(text, voice), msg)
|
||||
|
||||
def cosyvoice(self, text: str, voice: str) -> Iterator[bytes]:
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
res = requests.post(
|
||||
f"{self.opt.TTS_SERVER}/tts",
|
||||
json={"text": text, "voice": voice},
|
||||
stream=True,
|
||||
timeout=(5, 300),
|
||||
)
|
||||
if res.status_code != 200:
|
||||
logger.error("cosyvoice http %s: %s", res.status_code, res.text[:200])
|
||||
return
|
||||
first = True
|
||||
for chunk in res.iter_content(chunk_size=4800): # 100ms @24k int16
|
||||
if first:
|
||||
logger.info("cosyvoice time to first chunk: %.3fs", time.perf_counter() - start)
|
||||
first = False
|
||||
if chunk and self.state == State.RUNNING:
|
||||
yield chunk
|
||||
elif self.state != State.RUNNING:
|
||||
logger.info("cosyvoice interrupted, stop consuming")
|
||||
res.close()
|
||||
return
|
||||
except Exception:
|
||||
logger.exception('cosyvoice tts error')
|
||||
|
||||
def stream_tts(self, audio_stream: Iterator[bytes], msg: tuple[str, dict]):
|
||||
text, textevent = msg
|
||||
first = True
|
||||
for chunk in audio_stream:
|
||||
if not chunk:
|
||||
continue
|
||||
pcm24 = np.frombuffer(chunk, dtype=np.int16).astype(np.float32) / 32767.0
|
||||
stream = resampy.resample(pcm24, sr_orig=24000, sr_new=self.sample_rate)
|
||||
streamlen = stream.shape[0]
|
||||
idx = 0
|
||||
while streamlen >= self.chunk:
|
||||
eventpoint = {}
|
||||
if first:
|
||||
eventpoint = {'status': 'start', 'text': text}
|
||||
first = False
|
||||
eventpoint.update(**textevent)
|
||||
self.parent.put_audio_frame(stream[idx:idx + self.chunk], eventpoint)
|
||||
streamlen -= self.chunk
|
||||
idx += self.chunk
|
||||
eventpoint = {'status': 'end', 'text': text}
|
||||
eventpoint.update(**textevent)
|
||||
self.parent.put_audio_frame(np.zeros(self.chunk, np.float32), eventpoint)
|
||||
diff --git a/avatars/base_avatar.py b/avatars/base_avatar.py
|
||||
index 28c826a..a9744e6 100644
|
||||
--- a/avatars/base_avatar.py
|
||||
+++ b/avatars/base_avatar.py
|
||||
@@ -90,7 +90,7 @@ class BaseAvatar:
|
||||
'edgetts': 'tts.edge',
|
||||
'gpt-sovits': 'tts.sovits',
|
||||
'xtts': 'tts.xtts',
|
||||
- # 'cosyvoice': 'tts.cosyvoice',
|
||||
+ 'cosyvoice': 'tts.cosyvoice',
|
||||
# 'fishtts': 'tts.fish',
|
||||
'tencent': 'tts.tencent',
|
||||
'doubao': 'tts.doubao',
|
||||
@@ -1,69 +0,0 @@
|
||||
import time
|
||||
import numpy as np
|
||||
import resampy
|
||||
import requests
|
||||
from io import BytesIO
|
||||
from typing import Iterator
|
||||
|
||||
from utils.logger import logger
|
||||
from .base_tts import BaseTTS, State
|
||||
from registry import register
|
||||
|
||||
|
||||
@register("tts", "cosyvoice")
|
||||
class CosyVoiceTTS(BaseTTS):
|
||||
"""适配本机既有 CosyVoice3 流式 TTS (POST /tts -> 24kHz int16 PCM 流)."""
|
||||
|
||||
def txt_to_audio(self, msg: tuple[str, dict]):
|
||||
text, textevent = msg
|
||||
voice = textevent.get('tts', {}).get('voice', self.opt.REF_FILE or 'default')
|
||||
self.stream_tts(self.cosyvoice(text, voice), msg)
|
||||
|
||||
def cosyvoice(self, text: str, voice: str) -> Iterator[bytes]:
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
res = requests.post(
|
||||
f"{self.opt.TTS_SERVER}/tts",
|
||||
json={"text": text, "voice": voice},
|
||||
stream=True,
|
||||
timeout=(5, 300),
|
||||
)
|
||||
if res.status_code != 200:
|
||||
logger.error("cosyvoice http %s: %s", res.status_code, res.text[:200])
|
||||
return
|
||||
first = True
|
||||
for chunk in res.iter_content(chunk_size=4800): # 100ms @24k int16
|
||||
if first:
|
||||
logger.info("cosyvoice time to first chunk: %.3fs", time.perf_counter() - start)
|
||||
first = False
|
||||
if chunk and self.state == State.RUNNING:
|
||||
yield chunk
|
||||
elif self.state != State.RUNNING:
|
||||
logger.info("cosyvoice interrupted, stop consuming")
|
||||
res.close()
|
||||
return
|
||||
except Exception:
|
||||
logger.exception('cosyvoice tts error')
|
||||
|
||||
def stream_tts(self, audio_stream: Iterator[bytes], msg: tuple[str, dict]):
|
||||
text, textevent = msg
|
||||
first = True
|
||||
for chunk in audio_stream:
|
||||
if not chunk:
|
||||
continue
|
||||
pcm24 = np.frombuffer(chunk, dtype=np.int16).astype(np.float32) / 32767.0
|
||||
stream = resampy.resample(pcm24, sr_orig=24000, sr_new=self.sample_rate)
|
||||
streamlen = stream.shape[0]
|
||||
idx = 0
|
||||
while streamlen >= self.chunk:
|
||||
eventpoint = {}
|
||||
if first:
|
||||
eventpoint = {'status': 'start', 'text': text}
|
||||
first = False
|
||||
eventpoint.update(**textevent)
|
||||
self.parent.put_audio_frame(stream[idx:idx + self.chunk], eventpoint)
|
||||
streamlen -= self.chunk
|
||||
idx += self.chunk
|
||||
eventpoint = {'status': 'end', 'text': text}
|
||||
eventpoint.update(**textevent)
|
||||
self.parent.put_audio_frame(np.zeros(self.chunk, np.float32), eventpoint)
|
||||
@@ -1,13 +0,0 @@
|
||||
diff --git a/avatars/base_avatar.py b/avatars/base_avatar.py
|
||||
index 28c826a..a9744e6 100644
|
||||
--- a/avatars/base_avatar.py
|
||||
+++ b/avatars/base_avatar.py
|
||||
@@ -90,7 +90,7 @@ class BaseAvatar:
|
||||
'edgetts': 'tts.edge',
|
||||
'gpt-sovits': 'tts.sovits',
|
||||
'xtts': 'tts.xtts',
|
||||
- # 'cosyvoice': 'tts.cosyvoice',
|
||||
+ 'cosyvoice': 'tts.cosyvoice',
|
||||
# 'fishtts': 'tts.fish',
|
||||
'tencent': 'tts.tencent',
|
||||
'doubao': 'tts.doubao',
|
||||
@@ -1,375 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""HEL-715 end-to-end verification client for LiveTalking(MuseTalk) @ 127.0.0.1:8010.
|
||||
|
||||
Connects as a WebRTC receiver (same path a browser takes), drives the avatar via
|
||||
/human + /interrupt_talk, records the received A/V to mp4 and logs timing stats.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import aiohttp
|
||||
import av
|
||||
import numpy as np
|
||||
from aiortc import RTCPeerConnection, RTCSessionDescription
|
||||
|
||||
BASE = os.environ.get("LT_BASE", "http://127.0.0.1:8010")
|
||||
OUT = os.environ.get("E2E_OUT", "/opt/hel715-verify/e2e")
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
S1 = "在呢。你回来啦,今天在外面累不累?"
|
||||
S2 = "还有,我跟你说,今天下午我在窗边看了好久的天空,云跑得特别快,有一朵特别像小兔子,我还给它拍了张照片,等下拿给你看。"
|
||||
S3 = "抱歉,你刚想说什么?我在听。"
|
||||
S4 = "嗯,我在。"
|
||||
|
||||
# approx mouth region (lower third of face bbox 218,203,324,333 from avatar prep)
|
||||
MOUTH = (222, 268, 320, 331)
|
||||
|
||||
log_lines = []
|
||||
|
||||
|
||||
def log(msg):
|
||||
line = f"[{time.strftime('%H:%M:%S')}] {msg}"
|
||||
print(line, flush=True)
|
||||
log_lines.append(line)
|
||||
|
||||
|
||||
class Recorder:
|
||||
def __init__(self, path, w, h):
|
||||
self.container = av.open(path, "w")
|
||||
self.vstream = self.container.add_stream("libx264", rate=25)
|
||||
self.vstream.width = w
|
||||
self.vstream.height = h
|
||||
self.vstream.pix_fmt = "yuv420p"
|
||||
self.vstream.options = {"crf": "20", "preset": "veryfast"}
|
||||
self.astream = self.container.add_stream("aac", rate=48000)
|
||||
self.astream.layout = "stereo"
|
||||
|
||||
def write_video(self, img_bgr):
|
||||
frame = av.VideoFrame.from_ndarray(img_bgr, format="bgr24")
|
||||
for p in self.vstream.encode(frame):
|
||||
self.container.mux(p)
|
||||
|
||||
def write_audio(self, pcm_i16, sr, ch):
|
||||
arr = pcm_i16.astype(np.int16)
|
||||
if ch == 1:
|
||||
arr = np.repeat(arr[:, None], 2, axis=1).reshape(-1)
|
||||
elif ch == 2:
|
||||
arr = arr.reshape(-1)
|
||||
else:
|
||||
arr = arr[: len(arr) // ch * ch].reshape(-1, ch)[:, :2].reshape(-1)
|
||||
if sr != 48000:
|
||||
n = len(arr) // 2
|
||||
idx = (np.arange(n) * (sr / 48000.0)).astype(int)
|
||||
idx = idx[idx < len(arr) // 2]
|
||||
arr = arr.reshape(-1, 2)[idx].reshape(-1)
|
||||
frame = av.AudioFrame.from_ndarray(
|
||||
np.ascontiguousarray(arr.reshape(1, -1)), format="s16", layout="stereo"
|
||||
)
|
||||
frame.sample_rate = 48000
|
||||
for p in self.astream.encode(frame):
|
||||
self.container.mux(p)
|
||||
|
||||
def close(self):
|
||||
for p in self.vstream.encode():
|
||||
self.container.mux(p)
|
||||
for p in self.astream.encode():
|
||||
self.container.mux(p)
|
||||
self.container.close()
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self):
|
||||
self.events = {"video": [], "audio": [], "speak": [], "actions": []}
|
||||
self.imgs_sample = []
|
||||
self.sid = None
|
||||
self.http = None
|
||||
|
||||
async def post(self, path, payload):
|
||||
t0 = time.perf_counter()
|
||||
async with self.http.post(BASE + path, json=payload) as r:
|
||||
body = await r.json()
|
||||
return time.perf_counter() - t0, body
|
||||
|
||||
async def poll_speaking(self, stop_evt):
|
||||
while not stop_evt.is_set():
|
||||
try:
|
||||
dt, body = await self.post("/is_speaking", {"sessionid": self.sid})
|
||||
self.events["speak"].append(
|
||||
[round(time.perf_counter(), 3), body.get("data", False)]
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
await asyncio.sleep(0.25)
|
||||
|
||||
|
||||
def mouth_motion(prev, cur):
|
||||
if prev is None or cur is None:
|
||||
return 0.0
|
||||
x0, y0, x1, y1 = MOUTH
|
||||
d = np.abs(
|
||||
cur[y0:y1, x0:x1].astype(np.int16) - prev[y0:y1, x0:x1].astype(np.int16)
|
||||
).mean()
|
||||
return float(d)
|
||||
|
||||
|
||||
async def main():
|
||||
stats = {"sentences": {}, "meta": {}}
|
||||
rec = None
|
||||
pc = RTCPeerConnection()
|
||||
sess = Session()
|
||||
t_start = time.perf_counter()
|
||||
|
||||
done = asyncio.Event()
|
||||
|
||||
@pc.on("track")
|
||||
def on_track(track):
|
||||
log(f"track: {track.kind}")
|
||||
if track.kind == "video":
|
||||
asyncio.ensure_future(video_loop(track))
|
||||
else:
|
||||
asyncio.ensure_future(audio_loop(track))
|
||||
|
||||
async def video_loop(track):
|
||||
nonlocal rec
|
||||
prev = None
|
||||
while True:
|
||||
try:
|
||||
frame = await track.recv()
|
||||
except Exception:
|
||||
break
|
||||
img = frame.to_ndarray(format="bgr24")
|
||||
if rec is None:
|
||||
rec = Recorder(os.path.join(OUT, "e2e-session.mp4"), img.shape[1], img.shape[0])
|
||||
log(f"recorder ready {img.shape[1]}x{img.shape[0]}")
|
||||
t = time.perf_counter()
|
||||
m = mouth_motion(prev, img)
|
||||
sess.events["video"].append([round(t, 3), round(m, 2)])
|
||||
prev = img
|
||||
rec.write_video(img)
|
||||
if len(sess.imgs_sample) < 400:
|
||||
sess.imgs_sample.append((round(t - t_start, 2), img))
|
||||
|
||||
async def audio_loop(track):
|
||||
while True:
|
||||
try:
|
||||
frame = await track.recv()
|
||||
except Exception:
|
||||
break
|
||||
t = time.perf_counter()
|
||||
arr = frame.to_ndarray()
|
||||
if arr.dtype != np.int16:
|
||||
if arr.dtype in (np.float32, np.float64):
|
||||
arr = (np.clip(arr, -1, 1) * 32767).astype(np.int16)
|
||||
else:
|
||||
arr = arr.astype(np.int16)
|
||||
ch = len(frame.layout.channels)
|
||||
if arr.ndim == 2 and arr.shape[0] == 1:
|
||||
pcm = arr.reshape(-1) # packed s16
|
||||
elif arr.ndim == 2 and arr.shape[0] == ch:
|
||||
pcm = arr.T.reshape(-1) # planar
|
||||
else:
|
||||
pcm = arr.reshape(-1)
|
||||
ch = 1
|
||||
rms = float(np.sqrt((pcm.astype(np.float64) ** 2).mean()) / 32767.0)
|
||||
sess.events["audio"].append([round(t, 3), round(rms, 5)])
|
||||
if rec is not None:
|
||||
rec.write_audio(pcm, frame.sample_rate, ch)
|
||||
|
||||
async with aiohttp.ClientSession() as http:
|
||||
sess.http = http
|
||||
pc.addTransceiver("video", direction="recvonly")
|
||||
pc.addTransceiver("audio", direction="recvonly")
|
||||
offer = await pc.createOffer()
|
||||
await pc.setLocalDescription(offer)
|
||||
while pc.iceGatheringState != "complete":
|
||||
await asyncio.sleep(0.1)
|
||||
t0 = time.perf_counter()
|
||||
async with http.post(
|
||||
BASE + "/offer", json={"sdp": pc.localDescription.sdp, "type": "offer"}
|
||||
) as r:
|
||||
answer = await r.json()
|
||||
log(f"offer round-trip {time.perf_counter()-t0:.3f}s sessionid={answer.get('sessionid')}")
|
||||
sess.sid = answer["sessionid"]
|
||||
await pc.setRemoteDescription(
|
||||
RTCSessionDescription(sdp=answer["sdp"], type=answer["type"])
|
||||
)
|
||||
stats["meta"]["sessionid"] = sess.sid
|
||||
|
||||
stop_evt = asyncio.Event()
|
||||
poller = asyncio.ensure_future(sess.poll_speaking(stop_evt))
|
||||
|
||||
def mark(name):
|
||||
t = time.perf_counter()
|
||||
sess.events["actions"].append([round(t, 3), name])
|
||||
log(f"ACTION {name}")
|
||||
return t
|
||||
|
||||
# wait for first video frame / idle
|
||||
for _ in range(200):
|
||||
if sess.events["video"]:
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
first_v = sess.events["video"][0][0] if sess.events["video"] else -1
|
||||
first_a = sess.events["audio"][0][0] if sess.events["audio"] else -1
|
||||
stats["meta"]["first_video_s"] = round(first_v - t_start, 3)
|
||||
stats["meta"]["first_audio_s"] = round(first_a - t_start, 3)
|
||||
log(f"first video {stats['meta']['first_video_s']}s audio {stats['meta']['first_audio_s']}s")
|
||||
await asyncio.sleep(3.0) # idle baseline
|
||||
|
||||
async def speak(name, text, wait_end=True, interrupt_after=None, next_line=None):
|
||||
t_send = mark(f"send:{name}")
|
||||
dt, body = await sess.post(
|
||||
"/human", {"sessionid": sess.sid, "type": "echo", "text": text}
|
||||
)
|
||||
log(f"/human {name} ack {dt:.3f}s {body}")
|
||||
t_interrupt = None
|
||||
if interrupt_after is not None:
|
||||
await asyncio.sleep(interrupt_after)
|
||||
t_interrupt = mark(f"interrupt:{name}")
|
||||
dt2, b2 = await sess.post("/interrupt_talk", {"sessionid": sess.sid})
|
||||
log(f"/interrupt_talk ack {dt2:.3f}s {b2}")
|
||||
if wait_end:
|
||||
# wait until speaking False and audio silent
|
||||
silent = 0.0
|
||||
last_speak_true = time.perf_counter()
|
||||
while True:
|
||||
await asyncio.sleep(0.1)
|
||||
now = time.perf_counter()
|
||||
sp = sess.events["speak"][-1][1] if sess.events["speak"] else None
|
||||
if sp:
|
||||
last_speak_true = now
|
||||
recent = [a for a in sess.events["audio"] if a[0] > now - 0.6]
|
||||
loud = any(a[1] > 0.02 for a in recent)
|
||||
if not sp and not loud:
|
||||
silent = now - last_speak_true
|
||||
if silent > 1.2:
|
||||
break
|
||||
else:
|
||||
last_speak_true = max(last_speak_true, now)
|
||||
return t_send, t_interrupt
|
||||
|
||||
# S1 short
|
||||
s, _ = await speak("S1", S1)
|
||||
stats["sentences"]["S1"] = {"text": S1, "sent_at": round(s - t_start, 2)}
|
||||
await asyncio.sleep(1.5)
|
||||
# S2 long with interrupt 3s after send
|
||||
s2, ti = await speak("S2", S2, wait_end=True, interrupt_after=3.0)
|
||||
stats["sentences"]["S2"] = {
|
||||
"text": S2, "sent_at": round(s2 - t_start, 2),
|
||||
"interrupt_at": round(ti - t_start, 2),
|
||||
}
|
||||
await asyncio.sleep(2.0)
|
||||
# S3 re-open after interrupt
|
||||
s3, _ = await speak("S3", S3)
|
||||
stats["sentences"]["S3"] = {"text": S3, "sent_at": round(s3 - t_start, 2)}
|
||||
await asyncio.sleep(3.0) # pause test
|
||||
s4, _ = await speak("S4", S4)
|
||||
stats["sentences"]["S4"] = {"text": S4, "sent_at": round(s4 - t_start, 2)}
|
||||
mark("end")
|
||||
await asyncio.sleep(2.0)
|
||||
stop_evt.set()
|
||||
poller.cancel()
|
||||
await pc.close()
|
||||
|
||||
if rec:
|
||||
rec.close()
|
||||
log("recording closed")
|
||||
|
||||
# analysis
|
||||
def rel(ts):
|
||||
return round(ts - t_start, 3)
|
||||
|
||||
ev_a = sess.events["audio"]
|
||||
ev_v = sess.events["video"]
|
||||
for name, info in stats["sentences"].items():
|
||||
sent = info.get("sent_at", 0) + t_start
|
||||
aud = [a for a in ev_a if a[0] >= sent and a[1] > 0.02]
|
||||
info["first_audible_rel_s"] = rel(aud[0][0]) if aud else None
|
||||
if aud:
|
||||
last = sent
|
||||
for a in aud:
|
||||
if a[0] - last < 1.5:
|
||||
last = a[0]
|
||||
info["last_audible_rel_s"] = rel(last)
|
||||
if "interrupt_at" in info:
|
||||
it = info["interrupt_at"] + t_start
|
||||
after = [a for a in ev_a if a[0] >= it and a[1] > 0.02]
|
||||
info["audible_after_interrupt_s"] = rel(after[0][0]) if after else None
|
||||
tail = [a for a in ev_a if a[0] >= it]
|
||||
tl = [a for a in tail if a[1] > 0.02]
|
||||
info["last_audible_after_interrupt_rel_s"] = rel(tl[-1][0]) if tl else None
|
||||
|
||||
# video motion around each sentence
|
||||
for name, info in stats["sentences"].items():
|
||||
sent = info.get("sent_at", 0) + t_start
|
||||
window = [v for v in ev_v if sent - 1.0 <= v[0] <= sent + 12]
|
||||
base = [v for v in ev_v if v[0] < sent - 1.0][-60:]
|
||||
if window and base:
|
||||
b = np.median([v[1] for v in base])
|
||||
info["mouth_motion_idle"] = round(float(b), 2)
|
||||
peak = max(v[1] for v in window)
|
||||
info["mouth_motion_peak"] = round(float(peak), 2)
|
||||
|
||||
# fps over speech windows
|
||||
if ev_v:
|
||||
dur = ev_v[-1][0] - ev_v[0][0]
|
||||
stats["meta"]["video_frames"] = len(ev_v)
|
||||
stats["meta"]["video_span_s"] = round(dur, 2)
|
||||
stats["meta"]["avg_recv_fps"] = round(len(ev_v) / dur, 2) if dur > 0 else None
|
||||
if ev_a:
|
||||
dur = ev_a[-1][0] - ev_a[0][0]
|
||||
stats["meta"]["audio_frames"] = len(ev_a)
|
||||
stats["meta"]["audio_span_s"] = round(dur, 2)
|
||||
|
||||
stats["meta"]["wall_total_s"] = round(time.perf_counter() - t_start, 2)
|
||||
|
||||
with open(os.path.join(OUT, "stats.json"), "w") as f:
|
||||
json.dump(stats, f, ensure_ascii=False, indent=1)
|
||||
with open(os.path.join(OUT, "events.json"), "w") as f:
|
||||
json.dump(
|
||||
{
|
||||
"t_start": t_start,
|
||||
"video": sess.events["video"],
|
||||
"audio": sess.events["audio"],
|
||||
"speak": sess.events["speak"],
|
||||
"actions": sess.events["actions"],
|
||||
},
|
||||
f,
|
||||
)
|
||||
with open(os.path.join(OUT, "run.log"), "w") as f:
|
||||
f.write("\n".join(log_lines))
|
||||
|
||||
# contact sheet: pick frames around S1 onset, S2 mid, interrupt, S3
|
||||
try:
|
||||
from PIL import Image
|
||||
|
||||
picks = []
|
||||
s1 = stats["sentences"]["S1"].get("first_audible_rel_s") or 5
|
||||
s2i = stats["sentences"]["S2"].get("interrupt_at")
|
||||
picks += [max(0, s1 - 1.5), s1 + 0.5, s1 + 2.5]
|
||||
if s2i:
|
||||
picks += [s2i - 1.0, s2i + 0.3, s2i + 1.5]
|
||||
picks += [stats["sentences"]["S3"]["sent_at"] + 2.0]
|
||||
tiles = []
|
||||
for p in picks:
|
||||
cand = min(sess.imgs_sample, key=lambda x: abs(x[0] - p))
|
||||
im = Image.fromarray(cand[1][:, :, ::-1]).resize((276, 276))
|
||||
tiles.append((cand[0], im))
|
||||
sheet = Image.new("RGB", (276 * len(tiles), 276 + 18), "black")
|
||||
from PIL import ImageDraw
|
||||
|
||||
d = ImageDraw.Draw(sheet)
|
||||
for i, (ts, im) in enumerate(tiles):
|
||||
sheet.paste(im, (i * 276, 18))
|
||||
d.text((i * 276 + 4, 2), f"t={ts:.1f}s", fill="white")
|
||||
sheet.save(os.path.join(OUT, "contact-sheet.png"))
|
||||
except Exception as e:
|
||||
log(f"contact sheet failed: {e}")
|
||||
|
||||
log("DONE")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,129 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<title>HEL-715 日常→交谈→打断→日常 链路演示</title>
|
||||
<style>
|
||||
html,body{margin:0;height:100%;background:#000;color:#eee;font-family:"Noto Sans CJK SC",sans-serif;overflow:hidden}
|
||||
#stage{position:relative;height:100%;display:flex;align-items:center;justify-content:center}
|
||||
video{position:absolute;height:92%;top:2%;left:50%;transform:translateX(-50%);background:#000}
|
||||
#daily{display:block}
|
||||
#talk{display:none}
|
||||
#hud{position:absolute;left:0;right:0;bottom:0;padding:10px 14px;background:rgba(0,0,0,.72);font-size:15px;line-height:1.5}
|
||||
#phase{font-size:19px;font-weight:700;color:#ffd166}
|
||||
#timer{position:absolute;top:8px;right:14px;font-family:monospace;font-size:18px;background:rgba(0,0,0,.6);padding:2px 8px;border-radius:4px}
|
||||
#log{position:absolute;top:8px;left:14px;font-family:monospace;font-size:12px;background:rgba(0,0,0,.6);padding:6px 10px;border-radius:4px;max-height:46%;overflow:hidden;white-space:pre}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="stage">
|
||||
<video id="daily" autoplay loop muted playsinline>
|
||||
<source src="/hel715-daily.webm" type="video/webm"/>
|
||||
<source src="/hel715-daily.mp4" type="video/mp4"/>
|
||||
</video>
|
||||
<video id="talk" autoplay playsinline></video>
|
||||
<div id="timer">0.0s</div>
|
||||
<div id="log"></div>
|
||||
<div id="hud"><div id="phase">初始化…</div><div id="note">成品日常视频循环播放 · 交谈流后台预连接</div></div>
|
||||
</div>
|
||||
<script>
|
||||
const BASE = location.origin;
|
||||
const $ = id => document.getElementById(id);
|
||||
const t0 = performance.now();
|
||||
const logs = [];
|
||||
function now(){ return (performance.now()-t0)/1000; }
|
||||
function log(msg){
|
||||
const line = `${now().toFixed(2)}s ${msg}`;
|
||||
logs.push(line);
|
||||
$('log').textContent = logs.slice(-14).join('\n');
|
||||
console.log('[chain]', line);
|
||||
}
|
||||
function phase(p, note){ $('phase').textContent = p; $('note').textContent = note||''; }
|
||||
setInterval(()=>{ $('timer').textContent = now().toFixed(1)+'s'; }, 100);
|
||||
|
||||
/* ---------- WebRTC pre-connect (same path as LiveTalking client.js) ---------- */
|
||||
let pc = null, sessionid = null, connected = false, firstTalkFrameAt = null;
|
||||
async function connectTalk(){
|
||||
pc = new RTCPeerConnection({sdpSemantics:'unified-plan'});
|
||||
pc.addTransceiver('video',{direction:'recvonly'});
|
||||
pc.addTransceiver('audio',{direction:'recvonly'});
|
||||
pc.addEventListener('track', ev=>{
|
||||
if(ev.track.kind==='video'){
|
||||
firstTalkFrameAt = firstTalkFrameAt || now();
|
||||
$('talk').srcObject = ev.streams[0];
|
||||
log('交谈视频轨到达');
|
||||
} else {
|
||||
$('talk').srcObject = $('talk').srcObject || ev.streams[0];
|
||||
}
|
||||
});
|
||||
const offer = await pc.createOffer();
|
||||
await pc.setLocalDescription(offer);
|
||||
while(pc.iceGatheringState!=='complete') await new Promise(r=>setTimeout(r,50));
|
||||
const res = await fetch(BASE+'/offer',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({sdp:pc.localDescription.sdp,type:pc.localDescription.type})});
|
||||
const answer = await res.json();
|
||||
sessionid = answer.sessionid;
|
||||
await pc.setRemoteDescription(answer);
|
||||
log(`交谈流已连接 session=${sessionid.slice(0,8)}(预连接,用户尚未进入)`);
|
||||
connected = true;
|
||||
}
|
||||
async function say(text){
|
||||
const t=now();
|
||||
const r = await fetch(BASE+'/human',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({sessionid, type:'echo', text})});
|
||||
log(`发送对话文本(${text.slice(0,10)}…)HTTP ${(now()-t)*1000|0}ms`);
|
||||
}
|
||||
async function interrupt(){
|
||||
const t=now();
|
||||
await fetch(BASE+'/interrupt_talk',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({sessionid})});
|
||||
log(`打断信号 interrupt_talk HTTP ${(now()-t)*1000|0}ms`);
|
||||
}
|
||||
/* ---------- view switching ---------- */
|
||||
function showDaily(){ $('daily').style.display='block'; $('talk').style.display='none'; }
|
||||
function showTalk(){ $('daily').style.display='none'; $('talk').style.display='block'; }
|
||||
window.__chainLog = logs;
|
||||
|
||||
/* ---------- auto timeline ---------- */
|
||||
const auto = new URLSearchParams(location.search).has('auto');
|
||||
if(auto){
|
||||
(async ()=>{
|
||||
await connectTalk().catch(e=>log('连接失败: '+e));
|
||||
phase('① 日常播放','成品日常原片(HEL-712 同人物素材)循环播放');
|
||||
await sleep(7000);
|
||||
const sw = now(); showTalk();
|
||||
phase('② 进入交谈','同一人物·同一房间·同一套衣服 · 实时口型(MuseTalk)');
|
||||
log(`切换到交谈视图(预连接流,切换耗时 ${(now()-sw)*1000|0}ms)`);
|
||||
await say('你回来啦!我在窗边等你呢,快过来坐,我跟你说今天下午的云。');
|
||||
await sleep(6500); // speech ongoing (~1s in voice)
|
||||
phase('③ 用户开口→打断','interrupt_talk 信号注入 · 不等她说完、不等日常片尾');
|
||||
const ti = now();
|
||||
await interrupt();
|
||||
showDaily(); // 回日常/倾听,不等待
|
||||
log(`打断后立即切回日常视图(+${((now()-ti)*1000)|0}ms)`);
|
||||
await sleep(4000);
|
||||
showTalk();
|
||||
phase('④ 再次交谈','打断后可立即重新开口(清空待播队列后)');
|
||||
log('再次切换到交谈视图');
|
||||
await say('嗯,你说,我在听。');
|
||||
await sleep(8000);
|
||||
showDaily();
|
||||
phase('⑤ 回到日常','交谈结束 → 成品日常继续');
|
||||
log('回到日常播放');
|
||||
await sleep(4000);
|
||||
phase('演示结束','HEL-715 链路取样:日常→交谈→打断→回日常→再交谈');
|
||||
log('AUTO-DEMO-END');
|
||||
})();
|
||||
} else {
|
||||
phase('手动模式','D=日常 T=进入交谈并发送 I=打断并回日常');
|
||||
addEventListener('keydown', async ev=>{
|
||||
if(ev.key==='d'){ showDaily(); log('手动: 日常'); }
|
||||
if(ev.key==='t'){ showTalk(); log('手动: 交谈'); if(connected) await say('你回来啦!我在窗边等你呢。'); }
|
||||
if(ev.key==='i'){ await interrupt(); showDaily(); log('手动: 打断→日常'); }
|
||||
});
|
||||
connectTalk().catch(e=>log('连接失败: '+e));
|
||||
}
|
||||
function sleep(ms){ return new Promise(r=>setTimeout(r,ms)); }
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,124 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""LLM-chained conversation sample: .11 LLM -> .12 CosyVoice -> MuseTalk avatar.
|
||||
Same receiver architecture as e2e_client.py (proven to capture A/V)."""
|
||||
import asyncio, json, os, time
|
||||
import aiohttp, av, numpy as np
|
||||
from aiortc import RTCPeerConnection, RTCSessionDescription
|
||||
|
||||
BASE = "http://127.0.0.1:8010"
|
||||
LLM = "http://192.168.200.11:8731/v1/chat/completions"
|
||||
OUT = "/opt/hel715-verify/e2e"
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
|
||||
class Recorder:
|
||||
def __init__(self, path, w, h):
|
||||
self.container = av.open(path, "w")
|
||||
self.v = self.container.add_stream("libx264", rate=25)
|
||||
self.v.width, self.v.height, self.v.pix_fmt = w, h, "yuv420p"
|
||||
self.v.options = {"crf": "20", "preset": "veryfast"}
|
||||
self.a = self.container.add_stream("aac", rate=48000)
|
||||
self.a.layout = "stereo"
|
||||
|
||||
def video(self, img):
|
||||
for p in self.v.encode(av.VideoFrame.from_ndarray(img, format="bgr24")):
|
||||
self.container.mux(p)
|
||||
|
||||
def audio(self, frame):
|
||||
arr = frame.to_ndarray()
|
||||
if arr.dtype != np.int16:
|
||||
arr = (np.clip(arr, -1, 1) * 32767).astype(np.int16)
|
||||
ch = len(frame.layout.channels)
|
||||
if arr.ndim == 2 and arr.shape[0] == 1:
|
||||
pcm = arr.reshape(-1)
|
||||
elif arr.ndim == 2 and arr.shape[0] == ch:
|
||||
pcm = arr.T.reshape(-1)
|
||||
else:
|
||||
pcm = arr.reshape(-1)
|
||||
fr = av.AudioFrame.from_ndarray(np.ascontiguousarray(pcm.reshape(1, -1)), format="s16", layout="stereo")
|
||||
fr.sample_rate = 48000
|
||||
for p in self.a.encode(fr):
|
||||
self.container.mux(p)
|
||||
|
||||
def close(self):
|
||||
for p in self.v.encode(): self.container.mux(p)
|
||||
for p in self.a.encode(): self.container.mux(p)
|
||||
self.container.close()
|
||||
|
||||
|
||||
async def main():
|
||||
t0 = time.perf_counter()
|
||||
result = {}
|
||||
async with aiohttp.ClientSession() as http:
|
||||
async with http.post(LLM, json={
|
||||
"model": "halogen-qwen3.8-flash-next",
|
||||
"messages": [{"role": "user", "content": "你是住在高层公寓卧室里的伴侣晚晚,用一两句自然中文回应:我回来了,今天好累啊。"}],
|
||||
"max_tokens": 80,
|
||||
}) as r:
|
||||
body = await r.json()
|
||||
reply = body["choices"][0]["message"]["content"]
|
||||
result["llm_model"] = body["model"]
|
||||
result["llm_reply"] = reply
|
||||
result["llm_latency_s"] = round(time.perf_counter() - t0, 2)
|
||||
print(f"[{result['llm_latency_s']}s] LLM: {reply}", flush=True)
|
||||
|
||||
pc = RTCPeerConnection()
|
||||
rec = {"r": None}
|
||||
audio_marks = []
|
||||
|
||||
@pc.on("track")
|
||||
def on_track(track):
|
||||
async def drain():
|
||||
while True:
|
||||
try:
|
||||
f = await track.recv()
|
||||
except Exception:
|
||||
break
|
||||
t = time.perf_counter()
|
||||
if track.kind == "video":
|
||||
img = f.to_ndarray(format="bgr24")
|
||||
if rec["r"] is None:
|
||||
rec["r"] = Recorder(f"{OUT}/llm-chain.mp4", img.shape[1], img.shape[0])
|
||||
rec["r"].video(img)
|
||||
else:
|
||||
arr = f.to_ndarray()
|
||||
if arr.dtype != np.int16:
|
||||
arr = (np.clip(arr, -1, 1) * 32767).astype(np.int16)
|
||||
rms = float(np.sqrt((arr.astype(np.float64) ** 2).mean()) / 32767)
|
||||
audio_marks.append([round(t - t0, 3), round(rms, 5)])
|
||||
if rec["r"] is not None:
|
||||
rec["r"].audio(f)
|
||||
asyncio.ensure_future(drain())
|
||||
|
||||
pc.addTransceiver("video", direction="recvonly")
|
||||
pc.addTransceiver("audio", direction="recvonly")
|
||||
offer = await pc.createOffer()
|
||||
await pc.setLocalDescription(offer)
|
||||
while pc.iceGatheringState != "complete":
|
||||
await asyncio.sleep(0.1)
|
||||
async with http.post(BASE + "/offer", json={"sdp": pc.localDescription.sdp, "type": "offer"}) as r:
|
||||
answer = await r.json()
|
||||
await pc.setRemoteDescription(RTCSessionDescription(sdp=answer["sdp"], type=answer["type"]))
|
||||
sid = answer["sessionid"]
|
||||
await asyncio.sleep(3)
|
||||
t_send = time.perf_counter() - t0
|
||||
async with http.post(BASE + "/human", json={"sessionid": sid, "type": "echo", "text": reply}) as r:
|
||||
await r.json()
|
||||
print(f"[{t_send:.2f}s] sent to avatar", flush=True)
|
||||
await asyncio.sleep(15)
|
||||
await pc.close()
|
||||
|
||||
if rec["r"]:
|
||||
rec["r"].close()
|
||||
loud = [m for _, m in audio_marks if _ and m > 0.02]
|
||||
first_loud = next((t for t, m in audio_marks if m > 0.02), None)
|
||||
result["sent_at_s"] = round(t_send, 2)
|
||||
result["first_audible_s"] = round(first_loud, 2) if first_loud else None
|
||||
result["send_to_audible_s"] = round(first_loud - t_send, 2) if first_loud else None
|
||||
with open(f"{OUT}/llm-chain-stats.json", "w") as f:
|
||||
json.dump(result, f, ensure_ascii=False, indent=1)
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
print("DONE", flush=True)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,59 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
os.environ["LD_LIBRARY_PATH"] = (
|
||||
"/tmp/multica-task-4070005680/debs/root/usr/lib/x86_64-linux-gnu"
|
||||
+ (":" + os.environ["LD_LIBRARY_PATH"] if os.environ.get("LD_LIBRARY_PATH") else "")
|
||||
)
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
OUT = pathlib.Path("/tmp/multica-task-4070005680/opencode/chain")
|
||||
OUT.mkdir(exist_ok=True)
|
||||
URL = "http://192.168.200.12:8010/hel715-chain.html?auto=1"
|
||||
|
||||
|
||||
async def main():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(
|
||||
args=["--autoplay-policy=no-user-gesture-required", "--no-sandbox"]
|
||||
)
|
||||
ctx = await browser.new_context(
|
||||
viewport={"width": 1280, "height": 800},
|
||||
record_video_dir=str(OUT),
|
||||
record_video_size={"width": 1280, "height": 800},
|
||||
)
|
||||
page = await ctx.new_page()
|
||||
errors = []
|
||||
page.on("pageerror", lambda e: errors.append(str(e)))
|
||||
await page.goto(URL, wait_until="domcontentloaded")
|
||||
# wait for demo end marker (auto demo ~37s)
|
||||
try:
|
||||
await page.wait_for_function(
|
||||
"() => window.__chainLog && window.__chainLog.some(l => l.includes('AUTO-DEMO-END'))",
|
||||
timeout=60000,
|
||||
)
|
||||
except Exception as e:
|
||||
errors.append(f"wait_for_function: {e}")
|
||||
await asyncio.sleep(1.5)
|
||||
logs = await page.evaluate("() => window.__chainLog")
|
||||
metrics = {
|
||||
"url": URL,
|
||||
"chain_log": logs,
|
||||
"pageerrors": errors,
|
||||
}
|
||||
(OUT / "chain-browser-log.json").write_text(
|
||||
json.dumps(metrics, ensure_ascii=False, indent=1)
|
||||
)
|
||||
video = page.video
|
||||
await ctx.close()
|
||||
path = await video.path()
|
||||
await browser.close()
|
||||
print("video:", path)
|
||||
print("errors:", errors)
|
||||
print(json.dumps(logs, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -16,6 +16,10 @@ dependencies = [
|
||||
"httpx>=0.27",
|
||||
"pyyaml>=6.0",
|
||||
"pydantic>=2.7",
|
||||
"fastapi>=0.115,<1",
|
||||
"anyio>=4,<5",
|
||||
"uvicorn>=0.30,<1",
|
||||
"lunar-python>=1.4,<2",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# This file was autogenerated by uv via the following command:
|
||||
# uv pip compile --python .venv311/bin/python pyproject.toml -o requirements.lock
|
||||
annotated-doc==0.0.5
|
||||
# via fastapi
|
||||
annotated-types==0.8.0
|
||||
# via pydantic
|
||||
anyio==4.15.1
|
||||
# via
|
||||
# cybergril (pyproject.toml)
|
||||
# httpx
|
||||
# starlette
|
||||
certifi==2026.10.19
|
||||
# via
|
||||
# httpcore
|
||||
# httpx
|
||||
click==8.5.0
|
||||
# via uvicorn
|
||||
fastapi==0.159.1
|
||||
# via cybergril (pyproject.toml)
|
||||
h11==0.16.0
|
||||
# via
|
||||
# httpcore
|
||||
# uvicorn
|
||||
httpcore==1.0.9
|
||||
# via httpx
|
||||
httpx==0.28.1
|
||||
# via cybergril (pyproject.toml)
|
||||
idna==3.20
|
||||
# via
|
||||
# anyio
|
||||
# httpx
|
||||
lunar-python==1.4.8
|
||||
# via cybergril (pyproject.toml)
|
||||
opentelemetry-api==1.45.1
|
||||
# via fastapi
|
||||
pydantic==2.14.1
|
||||
# via
|
||||
# cybergril (pyproject.toml)
|
||||
# fastapi
|
||||
pydantic-core==2.50.1
|
||||
# via pydantic
|
||||
pyyaml==6.0.3
|
||||
# via cybergril (pyproject.toml)
|
||||
starlette==1.7.0
|
||||
# via fastapi
|
||||
typing-extensions==4.16.0
|
||||
# via
|
||||
# anyio
|
||||
# fastapi
|
||||
# opentelemetry-api
|
||||
# pydantic
|
||||
# pydantic-core
|
||||
# starlette
|
||||
# typing-inspection
|
||||
typing-inspection==0.4.4
|
||||
# via
|
||||
# fastapi
|
||||
# pydantic
|
||||
uvicorn==0.54.0
|
||||
# via cybergril (pyproject.toml)
|
||||
@@ -1,12 +0,0 @@
|
||||
node_modules/
|
||||
dist/
|
||||
runtime/*.log
|
||||
runtime/*.pid
|
||||
__pycache__/
|
||||
evidence/
|
||||
|
||||
packs/
|
||||
|
||||
public/assets/
|
||||
assets/personas/**/*.mp4
|
||||
assets/personas/**/*.png
|
||||
@@ -1,185 +0,0 @@
|
||||
HEL-714 日常成片+本地半身交谈样机,基于远端 main `1e9b08a` 和 P10 `6a5e155`。独立交付,不合并、不部署。PR #1 仍是旧分层小样,目标 main;本目录不依赖其尚未合并代码。
|
||||
|
||||
## 模块边界
|
||||
|
||||
- `src/main.ts`:日常选片、可切点、真实进退素材、WebRTC、麦克风/能量 VAD、原生 PCM AudioWorklet、取消、恢复和浏览器音画录制。
|
||||
- `runtime/server.py`:aiohttp 同源网关;既有 FunASR WebSocket、LLM HTTP、CosyVoice HTTP、LiveTalking WebRTC 信令与音频上传。只读素材 manifest。不写人格、八字、记忆、关系或生活数据。
|
||||
- `src/tokens.css` 原样复用 HEL-711 的唯一 token 表;`controls.css` 从已确认雨夜界面的基础控件抽取,未另造主题。页面布局在 `style.css`,无追加覆盖旧样式。没有引入动画库;Emil animate 模块的目的为避免场景跳变,主体过渡依赖真实正向素材,减少动态偏好下 UI 无按压位移。
|
||||
- `tools/patch_driver.py` 仅修改独立 LiveTalking 代码副本,给 peer 记录 session id,并增加精确关闭该 peer 的端点。模型权重复用,不改 P10 安装、18080/18081、ASR/TTS 或系统环境。
|
||||
|
||||
## 运行候选
|
||||
|
||||
先解压本卡复核包,恢复 `assets/personas/wanwan-v2-cream-night`(整个外观包)。素材二进制不入 Git。依赖锁来自既有小样,没有新增 npm 依赖。
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
python3 tools/pack_assets.py
|
||||
npm run build
|
||||
```
|
||||
|
||||
在 .12 复用 `/opt/hel715-verify/venv`(aiohttp 3.14.5、aiortc 1.15.0、PyAV 17.1.0、torch 2.8.0+cu128、numpy 2.5.4、resampy 0.4.3),不安装或升级系统依赖。先检查 8010、8014 没有其他监听者。
|
||||
|
||||
```bash
|
||||
python3 tools/prepare_driver.py --destination /opt/hel714-review/LiveTalking
|
||||
python3 tools/patch_driver.py /opt/hel714-review/LiveTalking
|
||||
```
|
||||
|
||||
把构建结果、runtime 和素材放在独立样机目录后,在独立 LiveTalking 目录生成本包 avatar(仓库中没有权重或预处理张量):
|
||||
|
||||
```bash
|
||||
cd /opt/hel714-review/LiveTalking
|
||||
/opt/hel715-verify/venv/bin/python -m avatars.musetalk.genavatar \
|
||||
--file /path/to/sample/dist/assets/talk/gaze.mp4 --avatar_id hel714-gaze-v1
|
||||
/opt/hel715-verify/venv/bin/python app.py --model musetalk \
|
||||
--avatar_id hel714-gaze-v1 --batch_size 8 --transport webrtc --tts cosyvoice \
|
||||
--REF_FILE xiaoyun --TTS_SERVER http://127.0.0.1:9880 \
|
||||
--listenport 8010 --stun ''
|
||||
```
|
||||
|
||||
另一个前台终端在本目录启动网关;Ctrl-C 后确认两个自测进程都退出。禁止 pkill、fuser -k 或停止共享服务。`runtime/config.json` 是本样机唯一模型/端点配置。
|
||||
|
||||
```bash
|
||||
/opt/hel715-verify/venv/bin/python runtime/server.py --port 8014
|
||||
```
|
||||
|
||||
浏览器在 .12 本机可打开 `http://localhost:8014`。远程麦克风需要 HTTPS;本次自测只读复用已有 `/opt/voice-agent/web/certs/cert.pem`、`key.pem`,给网关传 `--host 0.0.0.0 --cert ... --key ...`。未改系统证书信任、防火墙或开机启动。自动化使用 Chromium 的忽略证书检查,仅作用于该测试浏览器;普通浏览器是否能授权须实际确认。
|
||||
|
||||
## 行为和取消契约
|
||||
|
||||
日常片目前只有一份雨夜阅读。活动、手动天气、时段全部匹配才选中;无匹配时明确回退默认片。没有接真实天气,没有批量换装或跨人物验证。
|
||||
|
||||
进入时等阅读第 96 帧,播真实正向进场,再交谈;返回用独立正向生成回程,续播原日常切点。v2 新底板来自已确认的 `04-交谈近景-v2.png`,有微动作和目视镜头候选;表情/身体/目光来自底板,只有口型实时驱动。全部仍待总工人工观感审核,不能据“可播放”判断自然。
|
||||
|
||||
每轮回复拥有独立 peer。取消首先断开浏览器音频图、静音/暂停旧视频、关闭 peer、递增轮次;后端取消 LLM/TTS HTTP 任务,关闭上游响应,再精确销毁该 driver session(含其推理/输出队列)。旧 peer 的 RTP 和旧轮异步错误不进入新轮。这个选择增加建连成本,换来不复用难以完整清理的上游队列。共享 CosyVoice 服务不由本样机管理:客户端断开不等于已证明共享模型内部 GPU 生成即时停止。
|
||||
|
||||
LLM 和整句 TTS 生成与 ICE/转场并行。网关等浏览器 `/api/ready` 才把音频送入驱动器,防止转场期间提前说话。整句缓冲减少标点分句空隙,代价是长回复要等整句生成;未声称首包 SLA 或流式生成性能通过。前端的“等待首声”是真实等待。
|
||||
|
||||
麦克风请求 AEC/降噪,原生 Worklet 输出 16k PCM;150ms 连续能量启动会立即停止旧回复,650ms 静音发送 ASR 端点。FunASR `2pass-online` 仅展示,`2pass-offline` 收集终稿后提交。失败不伪造文字。长停顿、轻声、扬声器回声仍需真人校准;请用耳机。按钮和合成 WAV 结果均不冒充真人自然抢话通过。
|
||||
|
||||
## 素材版本和回滚
|
||||
|
||||
`assets/personas/wanwan-v2-cream-night/manifest.json`:稳定 `companion_id=wanwan`、外观 `persona_id`、服装/光线/天气标签、avatar id、帧级切点、v2 版本、v1 前版和逐文件 SHA256。换包不创建伴侣或写入身份状态。
|
||||
|
||||
先把候选完整包解压到新目录,用 `tools/pack_assets.py --assets <目录>` 校验,再整体替换 `assets/personas/<persona_id>`,在 `assets/active.json` 选择它,再构建、重启独立测试服务。禁止把不同版本的单文件混放。avatar 按 manifest 的 id 重新生成或复用对应缓存;网关从 manifest 指定 avatar,不使用别的脸兜底。构建先校验再把所选整包挂载到生成目录 `public/assets`,该目录可由构建重建,勿作为用户素材唯一副本。回滚对旧完整包执行同样步骤。复核包另附 `packs/hel714-v1`,仓库只保留它的 manifest 元数据;当前包为 hel714-v2。
|
||||
|
||||
## 检查
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
python3 -m ruff check samples/companion/runtime samples/companion/tools # 仓库根目录
|
||||
python3 -m pytest -q # 仓库根目录,原78项
|
||||
/opt/hel715-verify/venv/bin/python tools/check_gateway.py # .12,5项取消/音色/模型故障检查
|
||||
LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu python3 tools/check_browser.py
|
||||
LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu python3 tools/check_races.py
|
||||
LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu python3 tools/check_microphone.py
|
||||
LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu python3 tools/soak.py
|
||||
```
|
||||
|
||||
浏览器脚本依赖运行机已安装 Playwright/Chromium;麦克风脚本需复核包内的 `evidence/synthetic-microphone.wav`。它是 CosyVoice 合成的测试句,经 Chromium 假麦克风送入实际 Worklet→ASR→LLM→TTS→口型链路,绝不是人现场说话。录制用页面实际绘制画面和实际播放的 WebAudio 输出、同一个 MediaRecorder 时钟,不按帧数重建时间戳;静音时钟从开头持续输出零样本,保留进入前的日常画面。连续音画是浏览器播放图的合成采集,不是物理屏幕/扬声器校准。
|
||||
|
||||
实测结果和未通过项见 `REPORT.md`。生成工作流、history、原始候选片、浏览器证据和资源采样放复核附件,不在主仓库存大文件。
|
||||
|
||||
## HEL-718 驱动器补丁(候选,尚未通过同步门槛)
|
||||
|
||||
`tools/patch_driver.py` 追加类型透传:`AudioFrameData.type` 经
|
||||
`BaseAvatar.process_frames → WebRTCOutput → HumanPlayer` 到未赋 PTS 的
|
||||
`PendingAudio`。仅合成空闲 `type=1` 且无事件的块限至3块(60ms);
|
||||
真实语音(包括零值 PCM)、自定义音频和事件保留,100块队列提供背压。
|
||||
首次音频随真实首帧建立时间原点,此后轨道每20ms从队列取最新待播块,
|
||||
饥饿时补320样本静音;所有已输出包保持320步长,不在 RTP 队列跳时间戳。
|
||||
时钟改用 monotonic,`warm_up` 排空左右全部上下文,不移动 Whisper 特征窗。
|
||||
取消仍销毁本轮 peer,补丁不改变前后端取消协议。
|
||||
|
||||
先用 `prepare_driver.py` 新建私有副本,再运行补丁;源为已选 c726943。
|
||||
已验证从 P10 干净副本首次及重复应用,拒绝直接修改 P10 复用目录。
|
||||
`driver_audio.py` 必须与 `patch_driver.py` 一起携带。回滚时停止自己的候选
|
||||
服务,重建全新 c726943 副本,使用 `git show ae4fd5c:samples/companion/tools/patch_driver.py`
|
||||
导出的旧版补丁恢复 HEL-714 endpoint,再指向原 avatar/权重;不要原地混用新旧文件。
|
||||
|
||||
新增有效检查(使用原有 P10 venv,无新增依赖):
|
||||
|
||||
```bash
|
||||
/opt/hel715-verify/venv/bin/python tools/check_driver_audio.py /path/to/private/LiveTalking
|
||||
# 按真实 RTP PTS 录制刚进入、空闲15秒、连续多轮、打断后再次送入相同音频
|
||||
/opt/hel715-verify/venv/bin/python tools/record_driver.py \
|
||||
--wav fixed.wav --out server-rounds.mp4 --rounds 0,15,1,1 --post 9
|
||||
```
|
||||
|
||||
`trace_driver.py` 仅用于隔离测试,以 `PYTHONPATH=私有驱动器目录` 从该目录运行,
|
||||
首参为 JSONL 路径,其余为原 `app.py` 参数。记录逐块生产/接收 RMS、类型、深度、
|
||||
丢弃合成静音计数、PTS 和 monotonic 墙钟,不随产品默认开启。
|
||||
`record_graph.html/graph_server.py/record_graph.py` 复现浏览器产品音频图;
|
||||
`record_product.py` 记录三轮日常→进场→交谈→说话中取消→正向回程→续读。
|
||||
`measure_sync.py` 固定 ROI 和阈值并保存检测器 SHA256、完整命令、offset、窗口、
|
||||
idle-until、输入/底板哈希、检测误差及逐 lag 相关性。相关性很低时不能把最佳 lag 当作可靠对齐。
|
||||
|
||||
本轮仍未达到服务端绝对偏差≤0.15秒/浏览器≤0.25秒,详见 `REPORT-HEL718.md`。
|
||||
本补丁解决的是可确认的空闲队列/时钟问题,不能据此宣称音画同步已修好。
|
||||
|
||||
## HEL-720 头部闭唇候选(阈值待真人确认,仍未达同步门槛)
|
||||
|
||||
`patch_driver.py` 携带 `driver_head.py`,安装到私有驱动的
|
||||
`avatars/hel720_head.py`。在 `BaseASR.put_audio_frame` 的原始16k PCM入口逐块
|
||||
标记头部闭唇;20ms块不修改、不改类型或事件,仍进入原特征及RTP路径。
|
||||
首个RMS超过候选值的块结束本话语的门控,其后弱音保留口型。
|
||||
`start`/`end`事件和`flush_talk`重置状态,新peer各有独立状态;合成空闲不重新
|
||||
开启头部规则。标记随原`AudioFrameData`传递,旧帧的决定不会因新话语重置改变。
|
||||
|
||||
每个视频帧关联两块PCM;仅当对应两块均不需口型时走既有闭唇底板。
|
||||
混合批次仍推理全部8帧,再逐帧选择底板/预测结果,不以首块决定整批画面。
|
||||
自定义音频的类型与底板选择、真实语音的`is_speaking`及事件语义保留。
|
||||
Whisper的`[2,3]`特征窗、队列、时钟、转场及前后端取消协议不变。
|
||||
|
||||
候选进程启动环境变量 `HEL720_HEAD_RMS=0.001` 为默认试验值;`0`关闭规则。
|
||||
负值或非有限值拒绝启动会话。不要把该值写入共享服务环境。
|
||||
固定音频0.16秒处RMS约0.01333,规则已在这里结束,不能继续压制其后弱段。
|
||||
阈值未经真人听看批准,本轮未继续调参。详见 `REPORT-HEL720.md`。
|
||||
|
||||
```bash
|
||||
# 原有P10 venv;不装新依赖,PRIVATE_DRIVER必须为新建私有副本
|
||||
python3 tools/prepare_driver.py --source /path/to/clean-c726943 --destination "$PRIVATE_DRIVER"
|
||||
python3 tools/patch_driver.py "$PRIVATE_DRIVER"
|
||||
python3 tools/patch_driver.py "$PRIVATE_DRIVER" # 幂等重复应用
|
||||
/opt/hel715-verify/venv/bin/python tools/check_driver_head.py "$PRIVATE_DRIVER"
|
||||
/opt/hel715-verify/venv/bin/python tools/check_driver_audio.py "$PRIVATE_DRIVER"
|
||||
```
|
||||
|
||||
`trace_head.py`仅在隔离诊断时显式调用,参数与`trace_driver.py`一致;记录原始
|
||||
PCM哈希/RMS/门控、两块对应的渲染帧及RTP输出哈希/PTS,不由产品默认加载。
|
||||
`check_races.py [证据目录]`在失败时也保留页面状态、事件和截图,仍不把一次通过
|
||||
视为已定位历史超时。
|
||||
|
||||
回滚:停止自己的候选进程,新建同一c726943私有副本,使用
|
||||
`git show 415f837:samples/companion/tools/patch_driver.py`和同提交的
|
||||
`driver_audio.py`重装HEL-718补丁,复用原avatar/权重。也可在候选启动前设
|
||||
`HEL720_HEAD_RMS=0`关闭策略;该开关回滚保留代码但不闭唇。不要原地覆盖共享安装。
|
||||
|
||||
## HEL-722 启动准备(局部通过,整体同步仍未通过)
|
||||
|
||||
`driver_ready.py` 与补丁一起携带。MuseTalk 在监听 HTTP 前依次执行真实文件
|
||||
解码/24k→16k 重采样、Whisper 特征提取/既有切窗、真实 avatar latent 的
|
||||
`inference_batch`。替换原固定张量的 `warm_up` 调用,不重复加载模型。
|
||||
探针仅引用已加载模型与 avatar,不构造 session/ASR/HeadGate/输出队列,不调用
|
||||
`put_audio_file`、TTS 或网络。预测结果丢弃,不生成真实话语的 start/end。
|
||||
|
||||
日志明确报告 preparing/ready/failed、各阶段和总耗时;失败抛异常并退出,HTTP
|
||||
不会开始监听。成功后 `GET /hel722/ready` 返回本次准备状态与时间。这个状态只
|
||||
表示启动路径已准备,不表示音画同步验收通过。首次工作线程仍有约0.18秒模型
|
||||
调用,暖轮约0.08秒;已有批处理/排队/补静音的残差未在本轮修改。
|
||||
|
||||
```bash
|
||||
python3 tools/prepare_driver.py --source /path/to/clean-c726943 --destination "$PRIVATE_DRIVER"
|
||||
python3 tools/patch_driver.py "$PRIVATE_DRIVER"
|
||||
/opt/hel715-verify/venv/bin/python tools/check_driver_ready.py "$PRIVATE_DRIVER"
|
||||
/opt/hel715-verify/venv/bin/python tools/check_driver_head.py "$PRIVATE_DRIVER"
|
||||
/opt/hel715-verify/venv/bin/python tools/check_driver_audio.py "$PRIVATE_DRIVER"
|
||||
```
|
||||
|
||||
`trace_head.py` 诊断额外把原 PCM key/type/event 放在编码前 AVFrame 的 opaque
|
||||
元数据中,区分真实全零 PCM 与合成静音;不改 PCM、事件、类型、队列策略或 RTP。
|
||||
仅显式诊断时加载,元数据不会进入网络编码。阶段计时包装和本轮完整命令随证据包。
|
||||
|
||||
回滚:停止自己的候选进程,在新建的 c726943 私有副本应用
|
||||
`77b7608` 的 `patch_driver.py`、`driver_audio.py`、`driver_head.py`,复用同 avatar
|
||||
及权重,即恢复 HEL-720。不要原地去掉 readiness 而留其他混合版本。
|
||||
详见 `REPORT-HEL722.md`,不部署、不发布、不合并。
|
||||
@@ -1,64 +0,0 @@
|
||||
HEL-718 返工记录,2026-10-21。候选沿草稿 PR #2 / `hel-714-daily-talk`,base `main@1e9b08a`,施工基线 `ae4fd5c`。结论:**blocked,同步未修好,不发布、不合并、不转正式 PR。**
|
||||
|
||||
## 实现与实测结论
|
||||
|
||||
- `tools/patch_driver.py`、`tools/driver_audio.py`:在私有 c726943 驱动器透传 `AudioFrameData.type`,未赋 PTS 的合成空闲块最多3块;真实语音(包括零 PCM)、自定义音频和事件不丢,100块总队列背压。音频饥饿补零保持320样本/20ms时钟;时钟使用 monotonic;warm_up 排空左右全部上下文。
|
||||
- 追加4项有效回归:2000次空闲/语音混入顺序与事件保留、真实音频满队列背压、warm_up 后首块关联、饥饿期间 PTS/节奏与首块 PCM 字节哈希。P10 干净副本首次及重复应用通过,旧取消 endpoint 保留。
|
||||
- 不改前端播放延迟、不移动 Whisper 特征窗、不改转场、素材、接口或结束检测。其他输出 transport 保持原来的 `push_audio_frame`,新增类型入口仅作用于 WebRTC。
|
||||
- 自测与分析工具纳入 `tools/`;复现和回滚步骤见 README 的 HEL-718 节。
|
||||
|
||||
静音积压与时钟问题已得到有效限制,**残余起点仍超门槛**。独立单会话约66秒:最大音频队列27块(含语音),删除合成静音1206块;四个完整轮次各338块真实音频均按顺序匹配到输出 RMS,首块排队19/37/9/75ms。RMS顺序匹配不是全 PCM 哈希证明,单元检查另核对首块原始字节;没有靠裁掉弱音/首音节改善数值。
|
||||
|
||||
## 固定口径与原始指标
|
||||
|
||||
固定音频“八百标兵奔北坡,炮兵并排北边跑。宝宝抱抱爸爸,妈妈慢慢说。”,xiaoyun,24kHz,6.76秒,SHA256 `8c0c1ec943882d4aafbb4f8cda488f138a19231dabe2a58335777c0c42fff3dc`。本轮直接复制审核留存文件,未重新合成。强度门槛0.015下,第一个20ms RMS达标块在源音频0.56秒,首次样本幅度达标0.169秒;审核所述11ms并非同一强度检测口径,不应直接与当前起点混用。真实语音开头的低强度部分仍全部保留。
|
||||
|
||||
所有主比较使用 `measure_sync.py` 的 `hel718-v2-mask-fix`,修正旧 source mask 的 x1 索引错误,并用新版对修前录像重新计算。ROI固定为512尺度的 `(271,341,180,220)`;服务端不裁切,浏览器/产品canvas裁切 `offset=(160,0), render-size=640` 后缩放512。服务端运动/残差门槛固定 `3.1718642664 / 7.693739183`;浏览器与产品固定 `4.294028549194336 / 10.492400400638578`。音频RMS门槛0.015。每个窗口 JSON 持久化完整命令、输入/底板哈希、检测器脚本哈希、ROI/offset/idle-until/start/stop、门槛、逐lag相关性;每个窗口各自保留CSV,避免被下一轮覆盖。
|
||||
|
||||
数值为口部起点减声音起点,**负号表示嘴提前**。合格意图为绝对值≤0.15秒(服务端)、≤0.25秒(浏览器)。视频帧量化约40ms,音频包约22ms,起点阈值/弱音/口型残差另有未定标误差,数值不替代真人听看。
|
||||
|
||||
| 实验 | 运动起点差(s) | 残差起点差(s) | 稳态最佳有符号lag(s) / 相关系数 |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 修前真 PTS | -0.576 | -0.576 | -0.06 / 0.209 |
|
||||
| 修前浏览器图 | -0.699 | -0.665 | +0.52 / 0.231 |
|
||||
| 修后真 PTS 第1轮 | -0.433 | -0.433 | -0.58 / 0.191 |
|
||||
| 修后真 PTS 第2轮 | -0.320 | -0.320 | -0.44 / 0.189 |
|
||||
| 修后真 PTS 第3轮 | -0.273 | -0.273 | -0.40 / 0.192 |
|
||||
| 修后真 PTS 第4轮 | -0.313 | -0.313 | +0.34 / 0.173 |
|
||||
| 修后真 PTS 第5轮 | -0.343 | -0.343 | +0.80 / 0.897 |
|
||||
| 修后真 PTS 第6轮 | -0.296 | -0.296 | -0.44 / 0.339 |
|
||||
| 修后浏览器图 第1轮 | -0.442 | -0.442 | -0.56 / 0.183 |
|
||||
| 修后浏览器图 第2轮 | -0.360 | -0.360 | +0.32 / 0.171 |
|
||||
| 修后浏览器图 第3轮 | -0.448 | -0.448 | -0.52 / 0.184 |
|
||||
| 修后浏览器图 第4轮 | -0.324 | -0.324 | -0.40 / 0.206 |
|
||||
| 修前产品端到端(不同短句) | -0.382 | -0.382 | -0.46 / 0.391 |
|
||||
| 修后产品端到端首轮 | -0.507 | -0.507 | -0.26 / 0.203 |
|
||||
| 修后产品端到端被打断轮 | -0.241 | -0.218 | -0.34 / 0.593 |
|
||||
|
||||
服务端第1轮刚进入;第2轮前空闲15秒;第3/4轮连续播放后空闲1秒;第5轮在2秒处发 `/interrupt_talk`;第6轮同peer再次送固定音频(仅驱动诊断,不能替代产品取消隔离)。浏览器图覆盖前四个完整场景,产品回归另覆盖打断后新peer重入。修前固定音频只复用审核单轮原始录像,**未重建修前完整多轮矩阵**;此限制不能写成完整A/B验收已过。
|
||||
|
||||
产品端到端使用实际LLM/TTS,不以固定音频替换上游;首轮虽同文本,实际TTS为9.52秒,第二轮7.96秒,修前为1.96秒短句,**不能将这些行当成同音频因果对照**。受控同音频的因果比较以真PTS/浏览器图为准。
|
||||
|
||||
稳态lag使用运动能量与声音包络相关:定义 `lip_minus_audio = -shift`,修正旧xcorr脚本打印标签与相关计算方向相反的问题。四个完整受控轮次相关系数只有约0.17~0.21,最佳lag不稳定,**无法证明稳态音素同步或排除感知漂移**;第5轮只有截断短窗,其高相关与边界lag也不具验收意义。不能拿“某个最佳lag接近零”冒充通过。
|
||||
|
||||
音频PTS逐包20ms、视频40ms,无跳步;独立单会话末端墙钟减PTS分别约+1.07ms/+0.22ms;瞬时墙钟停顿最大约110/129ms,累计偏移峰值约90ms后回落。没有观察到持续时钟漂移,未机械重跑620秒。并行诊断曾有约1秒停顿(关闭其他peer同步join时),相应原始trace保留;主表使用独立单会话重测,不能把并发记录的卡顿抹掉。
|
||||
|
||||
## 回归、完整录像及未测项
|
||||
|
||||
- 前端构建通过;ruff通过;原78项pytest通过;5项网关检查通过;新增4项队列/时钟检查通过。日志见复核包 `checks/` 与 `remote/evidence/*checks.log`。
|
||||
- Chromium真实WebRTC回归通过:说话中取消、准备中取消、回日常、offer故障、缺素材、断网重连、快速取消再重入。快速重入首次与多轮采集并行时等待首声45秒超时,独立复跑通过,无pageerror或迟到旧轮错误;首轮未自动保存页面状态,不能追认已定位该偶发问题。
|
||||
- `product-continuous.webm` 约66.7秒:日常片7.84秒,录制后等待24.52秒(至少三轮)→f96切点→正向进场→两轮实际LLM/TTS→说话中按钮取消→独立正向回程→阅读续播。无pageerror;末态“已回到阅读原位置”。两轮首声8.49/7.91秒(本次样本,不是SLA)。取消后200~1000ms窗口最大RMS约0.0000041,低于0.015,无旧声复播证据。
|
||||
- 真人走查仍逐项待确认:日常循环接缝、两个切点、近景暖色、书本/手部/坐垫形变、微动作自然性、物理扬声器听感。没有用像素统计代替真人通过。
|
||||
- 真人自然抢话、手机真机/iOS/Safari、真实系统后台/锁屏、共享TTS内部GPU即停、多用户并发仍未测;桌面390px与synthetic visibility仅是处理器回归。
|
||||
|
||||
## 阻塞与最小后续路径
|
||||
|
||||
目前证据只能确认空闲积压受限、真实音频未被队列裁切、PTS连续;不能确认“积压修复足以消除同步故障”。残余服务端约−0.27~−0.43秒、浏览器约−0.32~−0.45秒,产品首轮约−0.51秒,均不足以放行。
|
||||
|
||||
建议下一步在同一固定音频的弱起音/闭唇音附近,保存每个推理批次的输入采样区间、Whisper特征区间和实际paste-back视频帧对应关系,以原始PCM对齐/人工音素标注核实残余来自特征关联还是起点检测;再由总工审定最小修法。不要盲加固定视频延迟、删除真实静音段或移动特征窗来压低指标。
|
||||
|
||||
## 隔离与交接
|
||||
|
||||
复用 c726943、MuseTalk v1.5 及原P10 venv/权重/avatar,无新依赖。工作仅在 `/opt/hel718-fix` 私有目录;18080/18081/9880/10095、系统Python/CUDA/驱动、证书信任、防火墙与开机配置未改。精确PID 1018154(驱动)、1018618(网关)、1098378(浏览器图代理)已核对cmd/cwd并在比较Multica daemon PID 44286后停止;8010/8014/8933已释放;共享服务PID 538167/608898/445461/220889保持。详见 `cleanup.json`。没有部署长期站点。
|
||||
|
||||
草稿 PR #2 沿原分支更新head,不另建PR。候选交付不等于样机通过;本卡保持blocked,由总管组织后续归因与真人检查。
|
||||
@@ -1,84 +0,0 @@
|
||||
HEL-720 最小返工记录,2026-10-21。施工基线 `hel-714-daily-talk@415f837`,原草稿 PR #2,base `main@1e9b08a`。**结论:blocked;已完成一轮限定修复和验证,指标仍未全过,不发布、不合并。0.001候选阈值待真人听看确认。**
|
||||
|
||||
## 实现、粒度与边界
|
||||
|
||||
- `tools/patch_driver.py`、`driver_head.py`:在ASR入口对原始16k/320样本/20ms块计算RMS并携带独立渲染标记。`type=0`、PCM内容、事件原样保留;未用合成静音类型绕过HEL-718队列保护。
|
||||
- 每个视频帧对应`audio_frames[i*2:i*2+2]`,每个批次8帧/16块。混合批次照常推理,仅把应闭唇的单帧预测替换为既有底板,不整批闭嘴。全闭唇批次复用既有跳过推理分支。画面选择仍沿原三元组队列,不按墙钟门控。
|
||||
- 状态在输入端顺序计算,`start`重启头部、首个超过门槛的块锁定开口、`end`/`flush_talk`重置;新peer有独立实例。合成空闲不重启话语,避免流式饥饿后吞掉弱音。标记写在帧对象上,重置不追改旧帧。产品取消仍销毁peer,本卡未另造轮次隔离。
|
||||
- 保留自定义音频类型和静态视频选择;画面闭唇期间真实音频的speaking/通知语义保持。可配置环境变量`HEL720_HEAD_RMS`,默认0.001,0关闭,非有限值/负值拒绝。
|
||||
- `check_driver_head.py`检查边界、禁用、混合先弱后强、话语中弱音、事件、取消/新peer及实际推理→输出循环的PCM字节/类型/事件保留。`trace_head.py`是显式调用的诊断工具。`check_races.py`新增无论成功失败都保存页面状态/事件/截图。
|
||||
- 未改窗口、队列、时钟、视频裁剪、固定延迟、transition、检测器或UI/素材。没有新依赖。
|
||||
|
||||
Whisper源码粒度核对:`run_step`每次追加16块,保留`l+r=20`块上下文;`_feature2chunks`的`start=l/2=5`、`feature_idx_multiplier=2`、`audio_feat_win=[2,3]`,特征索引窗口为`[2*i+6, 2*i+16)`。本轮仅在同一批次的每帧对应PCM对上选择画面,未改变这些参数。**没有逐特征张量转储,特征窗口说明来自固定驱动源码;实录trace直接覆盖PCM→渲染对→RTP,不能据此声称完整音素关联已验证。**
|
||||
|
||||
## 同固定音频的逐轮结果
|
||||
|
||||
沿用原fixed.wav,24kHz、6.76秒,SHA256 `8c0c1ec943882d4aafbb4f8cda488f138a19231dabe2a58335777c0c42fff3dc`。没有重新合成或裁掉头部。与HEL-718同`hel718-v2-mask-fix`检测器,脚本SHA256 `081e40486793d9c57dbd9d682aacbefe58670eb07a9b22675953cd6b883f0ec6`,ROI `(271,341,180,220)`;服务端不裁切,浏览器/产品`offset=(160,0), render-size=640`后缩放512。服务端motion/residual门槛 `3.1718642664/7.693739183`,浏览器 `4.294028549194336/10.492400400638578`,音频RMS门槛0.015,均未放宽。
|
||||
|
||||
所有差值为“口部起点-相应声音起点”,秒,负号为嘴提前。主验收是响亮RMS起点绝对差服务端≤0.15、浏览器≤0.25;另列弱瞬态的采样幅度起点和原始PCM首块口径,不能互换。样本幅度检测是独立辅助报告,非主检测器变更。原音频首次样本幅度绝对值>0.015在0.169208秒,首次20ms RMS>0.015在0.56秒;原PCM首块包含此前全部弱头。
|
||||
|
||||
| 路径/轮 | HEL-718响亮差 | 本轮响亮差 | 本轮残差差 | 样本幅度起点差 | 原PCM首块差 |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| server/1 | -0.433 | -0.640 | -0.640 | -0.288 | -0.080 |
|
||||
| server/2 | -0.320 | -0.159 | -0.159 | +0.212 | +0.420 |
|
||||
| server/3 | -0.273 | -0.199 | -0.199 | +0.252 | +0.440 |
|
||||
| server/4 | -0.313 | -0.068 | -0.068 | +0.312 | +0.500 |
|
||||
| server/5 | -0.343 | -0.183 | -0.183 | +0.172 | +0.580 |
|
||||
| server/6 | -0.296 | -0.103 | -0.103 | +0.252 | +0.720 |
|
||||
| graph/1 | -0.442 | -0.350 | -0.350 | +0.024 | 未标定 |
|
||||
| graph/2 | -0.360 | -0.307 | -0.307 | +0.068 | 未标定 |
|
||||
| graph/3 | -0.448 | -0.220 | -0.220 | +0.153 | 未标定 |
|
||||
| graph/4 | -0.324 | -0.208 | -0.208 | +0.166 | 未标定 |
|
||||
| product/1 | 未标定 | -0.314 | -0.314 | +0.019 | 未标定 |
|
||||
| product/2 | 未标定 | -0.322 | -0.288 | -0.318 | 未标定 |
|
||||
0 3
|
||||
|
||||
server 1刚进入、2空闲15秒后、3/4连续轮次、5在2秒处打断(非完整轮)、6同peer重新送音频诊断。graph覆盖前四场景。product为实际LLM/TTS的另两轮,9.56/9.16秒,不是固定音频对照,不与HEL-718产品数值作因果比较。
|
||||
|
||||
浏览器“原PCM首块”未单独标定;表中的样本幅度起点直接从其录音解码采样测得,另受有损编码和图时钟误差影响。服务端原PCM首块用实际RTP PTS锚定。视频量化约40ms、主音频检测约22ms,阈值/弱瞬态的感知误差未标定。弱瞬态口径中服务端出现+0.21~+0.31秒反向滞后,不能只报告嘴提前缩小。稳态包络相关在完整受控轮中约0.139~0.368,仍不足以证明音素同步或感知漂移已通过;被截断短窗不用于稳态验收。
|
||||
|
||||
本轮所有JSON/CSV保留各自完整命令、窗口、idle-until、阈值、源/录像/检测器哈希。分析窗口在各轮开始前保留空闲段;第6轮排除上一被打断轮的尾音。首轮若把idle-until放在原PCM首块之前仅40ms,会把更早的真实口部变化藏掉;最终保留口部1.12秒、响亮1.76秒的−0.640秒结果,没有用后移检测窗口美化首轮。
|
||||
|
||||
## 直接证据与最小剩余问题
|
||||
|
||||
固定音频输入的每一轮都仅前8块闭唇,第8号块(0.16秒)RMS `0.0133345156` 超过0.001,结束头部规则;后面的弱块继续有口型。`head-policy-summary.json`显示所有渲染帧选择与对应两块标记一致(0个冲突),实录有3个一弱一强的混合帧,均正确保留预测帧。
|
||||
|
||||
服务端四个完整轮及打断后第6轮各338块,浏览器四轮各338块,均逐块SHA256按顺序匹配到编码前RTP输出;5号打断轮已输出104块后主动取消,其余未输出是取消,不冒充338块完整播放。音频320样本/20ms、视频3600tick/40ms PTS连续,无跳步。`trace-summary.json`含各peer原始计数;原始`trace.jsonl`记录门控、原PCM float/int16哈希、渲染对、RTP音频哈希/PTS和视频PTS。
|
||||
|
||||
首轮还有独立的时序疑点:`head-frame-map.json`中第0/1块的闭唇画面在视频0.96秒,RTP第0块音频在1.20秒;第8/9块的首次预测画面在1.12秒,对应音频第8块在1.36秒。该轮画面与对应音频PTS相差−0.24秒,不能把剩余偏差全部归因弱音;其余轮并非同一偏移。该图的video_pts按render输出顺序与无丢帧的video recv顺序配对,trace可复核。需要总工复核首轮供给停顿/两路PTS推进与输出关联;本卡未扩展到视频修剪或新时钟方案。
|
||||
|
||||
因此0.001方案只覆盖最前0.16秒,**未满足总体目标**。下一步先由总管安排真人听原音频0.00~0.60秒,确认0.169秒瞬态应否触发口型,并由总工审视上述首轮PTS证据。不要将“近无声均不可闻”“阈值应调到更高”写为已证事实,本轮不循环盲调。
|
||||
|
||||
## 构建、自测、录像和未验项
|
||||
|
||||
- 前端`npm run build`通过;完整样机runtime/tools的ruff通过;新增4项门控检查、受影响的原4项队列/时钟检查通过。原78项核心测试/5项网关检查与本次未改动模块无关,沿用HEL-718已通过记录,未机械重跑。
|
||||
- 私有clean-driver首次/重复应用通过,最终再次应用所有Python文件哈希完全相同(`reapply.json`)。保留c726943/MuseTalk v1.5、原P10 venv、avatar和素材。
|
||||
- 本轮Chromium实际WebRTC检查:说话中取消、准备中取消、回阅读、offer故障、断网/恢复通过;快速重入独立首测通过,页面无pageerror。已保存本次完整页面状态/事件/截图。HEL-718快速重入并行首测超时仍未定位,本次通过不能关闭历史疑点。网关故障注入期间有SSL断连回调日志,浏览器恢复通过;未据此扩展修改网关。
|
||||
- 新`product-continuous.webm`约68秒,日常三轮→f96切点→正向进场→两轮交谈→说话中取消→独立正向回程→续读。取消后200~1000ms最大录音RMS `0.00000605`,无旧声复播证据。页面最终“已回到阅读原位置”,无pageerror。录制是浏览器实际画面/音频图的共同MediaRecorder,非物理扬声器校准。
|
||||
- 供真人:fixed.wav的0.00~0.60秒(重点0.16~0.18瞬态、0.54~0.58响亮起点);新完整录像约26.3~30.5秒进场、38.2~39.6秒首轮弱头/开口/响亮起点、55.0~56.3秒第二轮开头、57.51秒取消、58.76~61.89秒正向回程、61.89~67.97秒续读。事件时间已减record-start,实际容器有一帧左右误差,以音画原件为准。
|
||||
- 真人循环接缝/切点/暖色/书本/手部/坐垫/微动作、真人自然抢话、手机真机、真实后台/锁屏、共享TTS内部GPU即停逐项待验。390px桌面视口和synthetic visibility不等同真机/系统测试。0.001阈值、弱瞬态听感和稳态音素同步待验。任何脚本通过都不构成发布许可。
|
||||
|
||||
## 可复现命令与回滚
|
||||
|
||||
代码运行见README的HEL-720节。附件包含本轮实际`remote_supervisor.py`、`analyze_rounds.py`、`analyze_graph.py`、`weak_onsets.py`和`summarize.py`,各分析JSON含完整展开命令,`services.json`含实际启动参数/cwd/日志。诊断使用独立`/opt/hel720-fix`,复用材料不原地改写。
|
||||
|
||||
```bash
|
||||
# 先确认8010/8014/8933空闲;PRIVATE_DRIVER为全新c726943副本
|
||||
python3 tools/prepare_driver.py --source /path/to/clean-c726943 --destination "$PRIVATE_DRIVER"
|
||||
python3 tools/patch_driver.py "$PRIVATE_DRIVER"
|
||||
/opt/hel715-verify/venv/bin/python tools/check_driver_head.py "$PRIVATE_DRIVER"
|
||||
/opt/hel715-verify/venv/bin/python tools/check_driver_audio.py "$PRIVATE_DRIVER"
|
||||
# 在私有驱动cwd启动trace_head.py,后跟原app.py参数;原始命令见services.json
|
||||
# 以下驱动录制是单会话顺序执行;浏览器各脚本也逐项运行,不并发制造peer关闭卡顿
|
||||
/opt/hel715-verify/venv/bin/python tools/record_driver.py --wav fixed.wav --out server.mp4 --rounds 0,15,1,1 --post 9
|
||||
LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu python3 tools/record_graph.py evidence
|
||||
LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu python3 tools/record_product.py evidence
|
||||
LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu python3 tools/check_races.py evidence/race
|
||||
LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu python3 tools/check_browser.py
|
||||
python3 -m ruff check samples/companion/runtime samples/companion/tools
|
||||
# 样机目录:npm ci --ignore-scripts --no-audit --no-fund;npm run build
|
||||
```
|
||||
|
||||
回滚可在候选启动前`HEL720_HEAD_RMS=0`关闭策略;完全回滚则在新私有c726943副本应用415f837版本的`patch_driver.py`和`driver_audio.py`。不覆盖共享安装,不修改现网配置。
|
||||
|
||||
本轮对照Multica daemon PID 44286后停止自己的1425456/1425457/1425458,实际cmd/cwd/退出码见`cleanup.json`。8010/8014/8933已释放,18080/18081/9880/10095共享PID保持。没有运行中诊断遗留。提交/推送沿原分支和草稿PR,最终提交号见本卡结果评论。
|
||||
@@ -1,80 +0,0 @@
|
||||
HEL-722 一轮最小施工与验证,2026-10-21。基线 `hel-714-daily-talk@77b76083d05536893744d50ccf2a01c4a3c85a27`,原草稿 PR #2,base `main@1e9b08a`。
|
||||
|
||||
**结论:启动局部目标通过,交 in_review 复审;整体音画同步仍未通过,继续禁止部署、发布、合并。** 未调整门槛、PCM、特征窗、空闲视频队列或任何固定延迟。
|
||||
|
||||
## 已有预热缺口与最小修复
|
||||
|
||||
独立重现旧候选后,修正 HEL-721 的一项因果归因:约0.55秒并非全部是 MuseTalk 推理。首次 `/humanaudio` 在 aiohttp 主事件循环同步执行文件解码/重采样;`resampy.resample` 首次调用实测0.557秒,期间 WebRTC recv 停顿。首批真实模型推理另为0.201秒。旧启动 `warm_up` 只用固定 ones 特征和 latent 跑 pe/UNet/VAE,未跑上传重采样及 Whisper;会话的 `BaseASR.warm_up` 只填左右上下文,完全不提特征、不推理。固定张量与真实张量尺寸实际上均为 `(8,50,384)` / `(8,8,32,32)`,不是尺寸失配,不再沿用猜测。
|
||||
|
||||
旧候选本次实测:视频 recv 空洞0.574秒、render间隔0.632秒、视频时钟落后0.257秒,随后3个连续小于5ms的追赶间隔;视频深度39、音频深度93。首口部帧相对原第8块音频墙钟 vlag=-0.142秒,文件口径=-0.260秒。独立录端归零确实夸大偏差,但不能解释真实停顿。
|
||||
|
||||
`tools/patch_driver.py` 仅在 MuseTalk 的 HTTP 监听之前,改调用新 `driver_ready.prepare`:
|
||||
|
||||
1. 用内部短 WAV 走原私有解码函数,覆盖相同24k→16k首次重采样路径。
|
||||
2. 使用同一已加载 Whisper、相同上下文长度及 `_feature2chunks([2,3],l/2,2)`。
|
||||
3. 用真实 avatar latent 调用原 `MuseReal.inference_batch`,丢弃预测。
|
||||
|
||||
没有重复加载模型。没有会话/ASR构造器、HeadGate、音频输入/输出队列、TTS、网络或 start/end,内部样本不进入真实话语。`preparing/ready/failed`、阶段和总耗时写日志;异常明确抛出,未监听 HTTP。成功后 `/hel722/ready` 返回状态。两次冷进程准备耗时0.968/0.973秒(重采样0.461/0.455、特征0.198/0.201、推理0.309/0.316);第二进程从创建到 ready 标志约13.0秒,包含导入、模型和avatar加载,监听观测另有1秒轮询量化,没有把准备耗时冒充完整启动耗时。
|
||||
|
||||
## 测量口径与关联可信度
|
||||
|
||||
固定音频原件24kHz/6.76秒、SHA256 `8c0c1ec943882d4aafbb4f8cda488f138a19231dabe2a58335777c0c42fff3dc`,未重合成、未裁头。检测脚本 SHA256 `081e40486793d9c57dbd9d682aacbefe58670eb07a9b22675953cd6b883f0ec6`,ROI `(271,341,180,220)`、服务端 motion/residual `3.1718642664/7.693739183`、浏览器 `4.294028549194336/10.492400400638578`,浏览器裁切 offset160、size640→512,全保留。
|
||||
|
||||
原PCM key→render两块配对→视频recv序号,使用同一主机 `time.monotonic/perf_counter`,原PCM SHA顺序匹配到编码前音频recv;接收端独立记录实际 recv 的同一单调时钟与两轨PTS。文件指标另列,不混作墙钟。服务端视频步进3600、音频320,序号配对无中途负延迟;未入RTP的尾部render分别17/18帧,均为关闭时未拉取的队尾;这些帧可在关闭前已入队,不能写成“全在teardown后才render”,详见原trace。冷2进一步在AVFrame opaque携带原key/type/event,338块/338唯一key全部哈希、类型、事件一致,含最后5块原始全零PCM,预热期间输入PCM数=0。
|
||||
|
||||
冷1与旧基线用顺序哈希;原块0/8/28均非零、可直接追踪。尾部333~337号全零块与合成静音字节相同,旧格式不能独立证明这5块身份,因此没有用零/低相关性的 placement 结果证明定位。新opaque证据补足冷2该风险;冷1的关键起点不依赖全零尾部。录端视频关联是顺序及连续性核验,不是逐帧像素指纹。没有宣称完整音素对应已验证。
|
||||
|
||||
## 六轮服务端原门槛
|
||||
|
||||
秒;差值=口部-响亮声音,负=嘴提前,绝对值≤0.15达标。S4为2秒打断的局部轮,不能当完整稳态样本。弱瞬态栏是原第8块内幅度>0.015的采样起点,按16k重采样后0.16925秒定位;原24k为0.169208秒,量化/录制误差约40ms视频、22ms主RMS。主RMS仍为0.015,不替换验收口径。
|
||||
|
||||
|轮/场景|文件口部-响亮|发送墙钟口部-响亮|弱瞬态差|原PCM首块差|墙钟/文件达标|
|
||||
|---|---:|---:|---:|---:|---|
|
||||
|S1 冷进程A首轮|-0.251|-0.240|+0.151|+0.319|否/否|
|
||||
|S2 同peer空闲15秒|-0.148|-0.140|+0.270|+0.440|是/是|
|
||||
|S3 暖连续轮|-0.091|-0.079|+0.312|+0.482|是/是|
|
||||
|S4 说话中取消(104块)|-0.160|-0.159|+0.232|+0.560|否/否|
|
||||
|S5 同peer取消后再送(诊断)|-0.091|-0.079|+0.311|+0.481|是/是|
|
||||
|S6 冷进程B首轮|-0.193|-0.178|+0.272|+0.441|否/否|
|
||||
|
||||
发送墙钟、文件均3/6;两次冷首轮仍未达整体同步门槛。接收端实际收帧墙钟口部-响亮依次为 -0.317/-0.198/-0.148/-0.212/-0.149/-0.259,记录的是 aiortc 解码接收时刻,不是浏览器扬声器时间,也不与发送端验收行偷换。
|
||||
|
||||
|轮|首口部帧vlag(相对所配原块)|首次推理|上传重采样|视频recv最大间隔*|render最大间隔*|音频补位块/内容跨度拉伸|
|
||||
|---|---:|---:|---:|---:|---:|---|
|
||||
|旧基线冷首轮|-0.142|0.201|0.557|0.574|0.632|0 / 0.00|
|
||||
|S1|+0.160|0.178|0.083|0.134|0.342|0 / 0.00|
|
||||
|S2|+0.280|0.080|0.085|0.128|0.426|2 / 0.04|
|
||||
|S3|+0.322|0.082|0.086|0.116|0.339|6 / 0.12|
|
||||
|S4|+0.241|0.084|0.092|0.148|0.385|8 / 0.16|
|
||||
|S5|+0.320|0.079|0.084|0.133|0.342|8 / 0.16|
|
||||
|S6|+0.281|0.178|0.090|0.111|0.343|3 / 0.06|
|
||||
|
||||
*窗口为上传前0.2秒至后2秒,包含跨窗口起点的间隔,避免漏掉上传时的停顿。原批处理按8帧突发生产仍存在;没有宣称逐帧生产间距40ms。两次冷首轮时钟最大落后0.093/0.071秒,连续<5ms追赶间隔最多1个,已与暖轮0~1个同构,原0.24秒异常及连续追赶消失。冷首轮视频深度峰值16/14(暖轮约14~16),音频深度25/21,不是通过新增一秒排队取得结果。
|
||||
|
||||
冷工作线程首推仍约0.178秒,暖轮约0.08秒;预热没有声称覆盖所有线程局部初始化。原预渲染队列相位、每批边界和合成音频补位仍使冷暖/轮间差异浮动:例如S1第一口部render→recv为0.321秒,S6为0.506秒,S6弱到响亮之间另插入0.06秒音频补位。已有逐块墙钟表可以分解这些差异,不能将全部差异继续归咎弱头,也没有调阈值或补固定延迟抵消它们。
|
||||
|
||||
## 暖驱动新peer浏览器对照(单列)
|
||||
|
||||
同驱动A已暖,新建peer、相同固定音频四轮。共同MediaRecorder文件的口部-响亮为 -0.234/-0.211/-0.220/-0.221秒,4/4过浏览器0.25门槛。驱动侧首口部对应原PCM对vlag为 +0.320/+0.301/+0.242/+0.321;第2/4轮是第7/8块混合对,保留预测画面符合既有规则。它们不证明冷驱动已热,故不冒充独立冷启动。浏览器文件弱瞬态口径另为 +0.144/+0.133/+0.114/+0.215秒(有损解码采样幅度>0.015,不代替主RMS门槛);原PCM首块在浏览器播放端未独立定位,不能用低相关性推算。浏览器音频通路额外延迟仍未独立标定,不批准固定补偿;文件采集也不冒充物理扬声器/屏幕或真人听感。
|
||||
|
||||
## HEL-721 统计纠错与残余风险
|
||||
|
||||
按原列值独立取绝对值,服务端S4/S6达标(2/6),浏览器第3/4轮达标(2/4);实时修正列同样是S4/S6,不是“仅S4”或“浏览器全超线”。附件 `HEL721-corrected-gates.json`逐轮列出,原复审zip原封保留,不沿用其错误gate文字。原结论整体未通过仍成立。
|
||||
|
||||
全部固定音频完整轮仅前8块闭唇、首个超门槛块后弱音保持;本轮全trace渲染标记0冲突。S4已输入338块,取消前实际输出104块,其余234块取消;S5新话语从新start重置,产品路径仍用销毁peer隔离。首轮嘴不再早于配对块,但相对响亮/弱瞬态仍有正负残差;稳态包络只是运动能量启发式,音素与真人感知未验。本卡只交局部修复复审,不盲调残差。
|
||||
|
||||
## 检查、隔离、重现与回滚
|
||||
|
||||
新增2项检查:禁止探针构造真实会话/写PCM/通知/触门控,准备成功只返回状态;注入解码/推理失败必须抛异常。另实跑进程级重采样故障,启动exit=1、明确failed日志,8010未监听。原4项HeadGate和4项队列/时钟检查全过。干净c726943副本应用及重复应用116个Python文件哈希一致,和私有运行候选一致。
|
||||
|
||||
`npm run build`、runtime/tools的ruff、diff检查通过。实际Chromium准备中/说话中取消、快速重入、断网/恢复/offer故障通过,pageerror为空,有页面状态、事件、截图和连续录像。历史快速重入并行首测超时仍未定位;本轮通过不关闭历史疑点。网关故障注入中仍有既有SSL断连回调异常,页面恢复成功,未扩范围修共享服务。核心人格/记忆模块未改,沿用既有核心检查,未机械重跑。
|
||||
|
||||
私有工作目录 `/opt/hel722-fix`,源代码、模型/权重/avatar只读复用材料,新建代码副本;不修改共享安装/配置/端口/数据。仓库CLI因未配置该项目资源拒绝checkout,改用明确仓库URL普通git clone,确认工作树干净、head/base与无并行运行;不新建PR。
|
||||
|
||||
实际完整命令在证据包 `diagnostic/supervisor.py`、services.json、逐轮analysis JSON及脚本中。baseline在打HEL-722补丁之前跑;cold1为 `record_driver.py --rounds 0,15,1 --post 9`;cold2为相同录制器移除打断段的 `record_once.py --rounds 0 --post 9`。先查8010/8014/8933空闲,再前台运行supervisor,发送record命令,收齐结果后stop,禁止留下运行中诊断。浏览器脚本按原README命令运行,需已有Playwright/Chromium库路径;全部文件随附件,无新依赖。`diagnostic/summarize.py`在证据包根运行产生逐轮JSON。`analyze.py`在私有远端执行检测,统一窗口和参数,固定检测器未改。
|
||||
|
||||
前台监督进程均已收回;对照Multica daemon PID44286后,只停止记录的自有精确PID;cleanup.json记录实际cmd/cwd/exit。8010/8014/8933释放,18080/18081/9880/10095等共享服务PID保持。无诊断留运行。
|
||||
|
||||
完整回滚:停止自己的候选,另建c726943私有副本,取 `77b7608:samples/companion/tools/{patch_driver.py,driver_audio.py,driver_head.py}` 应用,复用同avatar/权重;不要编辑共享安装。仓库本次提交可用 `git revert <本次提交>`撤回,提交号见本卡结果评论。只推原候选分支,不合并。
|
||||
|
||||
真人弱音听感、画面循环/切点/暖色/书本手部坐垫、自然抢话、手机真机、后台锁屏、共享TTS内部GPU即停仍逐项待验。本轮不访问4080、不新增依赖、不部署、不发布。
|
||||
@@ -1,73 +0,0 @@
|
||||
HEL-714 候选交付记录,2026-10-20~21(上海时间)。基线 main `1e9b08a`,引入已选 P10 实验提交 `6a5e155`,独立样机位于 `samples/companion`。
|
||||
|
||||
## 结论
|
||||
|
||||
代码、构建、基础自测和连续音画已交候选;**同步与自然观感、真人自然抢话、手机真机仍未通过体验验收,禁止据此发布或宣称首版完成**。后续由总管组织总工审查。当前需要继续处理的首要问题是口部起点提前的来源;没有用“思考中”掩盖,也未盲加固定延迟。
|
||||
|
||||
已实现:单组日常片按活动/手动天气/时段匹配及明确回退;已确认 v2 近景图生成目视微动作候选;真实正向进场/回程和第 96 帧可切点;文字与麦克风入口;FunASR→LLM→TTS→MuseTalk;停止、倾听、回日常、再进入;旧轮隔离;缺片、网络、模型与音色错误提示;素材版本/校验/回滚。
|
||||
|
||||
## 同步:实际播放证据、修正和未通过项
|
||||
|
||||
P10 附件 REPORT、MATERIAL-SPEC、e2e-session、chain-demo-browser、llm-chain 均经鉴权 CLI 下载,文档与远端实验分支一致。先读了原始适配器、音频特征/输出队列和录制脚本。
|
||||
|
||||
旧采样脚本按音频样本/视频帧数重建容器时间轴,首个视频 recorder 建立前的音频也会丢弃;因此不把原报告的“口型晚 0.5–1.3 秒”当作已标定真实浏览器偏差。本轮改为同一 Chromium 绘制的画面+同一 WebAudio 实际播放图输出,交给一个 MediaRecorder;不重新按帧数生成时间戳。
|
||||
|
||||
还修正了两项采集问题:Chromium 从 WebRTC video 元素建立 MediaElementSource 时分析输出全零,改用同一接收流的 MediaStreamSource,播放和录音共用输出;无 peer 时音频图缺少活动源会裁掉录像开头,增加恒为零的音频时钟后,最终录像视频从 0 秒开始、首个静音音频包 0.03 秒,完整保留日常和进场。无物理扬声器/屏幕的硬件时钟校准。
|
||||
|
||||
| 样本 | 口部变化起点−声音起点 | 含义 |
|
||||
| --- | ---: | --- |
|
||||
| P10 同驱动、原裁切底板,重新在浏览器采集 | −0.081s | 只比较起点,不能证明逐音节通过;没有复现报告的明显起步滞后 |
|
||||
| 新目视底板,batch 16,第二轮完整静息段校准 | −0.635s | 口部先变化,体验验收仍有缺口 |
|
||||
| 新目视底板,batch 8,单份对照 | −0.622s | 减半批量未稳定消除差异 |
|
||||
| 最终包 batch 8,复测第二轮 | −0.424s | 仍有提前;不能据单个数值说同步已修好 |
|
||||
|
||||
这些数值来自源片相对口部残差与音频 RMS>0.015,使用录制文件本身的 PTS。新底板先按整段无语音静息片校准,再查口部残差越阈;坐标与窗口保存在脚本/CSV/JSON 中。头部微动、生成器改动嘴周和噪声会影响检测;它不是音素对齐或人工听看结论。各段不是相同台词、相同负载的受控基准,不能将上表差值解释为修复幅度。连续音画、口部帧条和原始数值一并提供。
|
||||
|
||||
下一条最小路径:固定同一段含清晰闭唇/开口音节的音频,在同一浏览器做原生 video 音频播放与 WebAudio 输出的 A/B,采集轨道/播放时钟并逐音节听看,区分浏览器播放图与 Whisper 前瞻/音频帧关联;确认稳定偏移来源后再改时间基准或特征对齐。当前没有证明消除了明显错位,列为体验验收阻塞。
|
||||
|
||||
## 素材和自然往返
|
||||
|
||||
复用已有 Wan2.2 生成工具,独立前台任务生成并停止自己的 ComfyUI PID 687113。无新模型、无新增依赖,未访问 4080。新 avatar 预处理只用原 MuseTalk 权重,新缓存独立保存在样机副本。三个任务 history 均 success,实际生成耗时约 65.5s、37.6s、34.4s。
|
||||
|
||||
| 素材 | 来源和长度 | 审核状态 |
|
||||
| --- | --- | --- |
|
||||
| 日常 | P10 loop,196帧/25fps | 单份雨夜阅读;其他天气/活动缺片,明确回退 |
|
||||
| 倾听/交谈底板 | 确认过的04近景v2中裁,81个新生成帧→127帧/25fps,5.08s | 目视、眨眼、呼吸候选;身体/目光来自片段 |
|
||||
| 进场 | 日常f96→近景v2,49帧→77帧/25fps,3.08s | 真正正向生成,非淡化/倒放;仍待人工检查形变和镜头连续性 |
|
||||
| 回程 | 近景v2→日常f96,独立49帧→77帧/25fps,3.08s | 与进场分开生成,取消声音不等回程 |
|
||||
|
||||
页面等到日常 f96 再进场;回来续该位置。连续录屏覆盖完整往返、说话中取消、再次说话和准备期取消。联系表已核对同人物/发型/服装/房间的方向一致性,不代表动态自然性通过。镜头变焦、书本/手部、坐垫形变、循环衔接必须由总工看连续片人工裁定。
|
||||
|
||||
canonical 素材放 `assets/personas/wanwan-v2-cream-night`,含 daily/talk/ref/voice/transitions 和 manifest。版本 hel714-v2,前版 hel714-v1;6 个文件逐一 SHA256。构建只在全部校验后挂载选中整包至生成目录 public/assets。v1/v2 均校验通过,篡改 talk 文件会拒绝;复核包提供 v1 完整回滚包。固定 companion_id=wanwan 与 persona/服装/版本分离;代码不写人格、八字、记忆或关系。没有跨人物、跨服装或真实天气验证。
|
||||
|
||||
## 真实链路、取消与恢复
|
||||
|
||||
既有 ASR 协议经只读检查:FunASR 2pass WebSocket,16k PCM,online 展示、offline 终稿,端点发送 is_speaking=false;没有通过端口猜协议。既有 LLM halogen-qwen3.8-flash-next(.11:8731)、CosyVoice xiaoyun(.12:9880)保持原服务。
|
||||
|
||||
每轮独立 peer。前端立即断开播放音频图、暂停/静音并丢弃视频、递增轮次;后端取消请求、关闭上游响应并精确关闭 driver peer/session,不复用旧媒体队列。最终连续录像中,两次按钮取消100ms后的1.1秒窗口内,无RMS>0.015的残留声音帧(最大0.000145/0);这只是数字播放图的观测上界。旧 ICE/offer 迟到和超时异常按轮次拒绝;取消连接时也立即唤醒等待,避免旧超时误停新轮。LLM/TTS 生成与 ICE/进场并行,ready 门控防止画面到位前发声。TTS 整句缓冲减少分句空隙,长句首声较慢;共享 TTS 内部 GPU 生成是否随客户端断开即时停止未获证明,未改共享服务。
|
||||
|
||||
- 原78项 Python测试通过;TypeScript严格检查+Vite构建通过;新增Python代码ruff通过。
|
||||
- 5项网关检查通过:取消LLM、取消TTS、等待画面ready时取消、错误音色不回退、模型不可达。
|
||||
- Chromium真实WebRTC回归通过:文字回复、说话轮取消、准备期取消、再次说话、回阅读续播、暂停、无匹配场景回退、offer失败、断网/恢复重连、缺片提示。未停止共享模型模拟故障。
|
||||
- ICE/offer建立中快速取消再发送的真实浏览器回归通过,旧超时没有停止新轮。
|
||||
- 合成WAV经Chromium假麦克风→Worklet/VAD→真实ASR终稿→LLM/TTS/口型通过;旧回复已出声,检测到开口后停止,新终稿“你好,请听我说一个问题。”正常产生新回复。附有声连续录像。**输入不是人现场说话,不计真人自然抢话通过**;长停顿可拆轮、轻声阈值和扬声器回声仍待耳机/真麦克风校准。
|
||||
- 1280×800 和390×844视口可操作,无横向溢出、无pageerror。390px只是桌面Chromium视口,手机真机/iOS/Safari未测。
|
||||
- 页面隐藏处理器停止音视频/麦克风并要求主动恢复;测试用合成visibilitychange,真实系统切后台/锁屏未测。
|
||||
|
||||
## 设备、延迟和长时观察
|
||||
|
||||
推理 .12:RTX5090D 32GB,Linux7.0.0,复用 torch2.8.0+cu128、LiveTalking c726943、MuseTalk v1.5、aiortc1.15.0、PyAV17.1.0、aiohttp3.14.5。浏览器在 .13 用已安装 Playwright/Chromium,headless;没有真实耳机/麦克风或手机接入。
|
||||
|
||||
测量口径:同一轮用户提交完成(或ASR终稿提交)→播放图RMS首次>0.015,包含该轮建连、等待可切点、进场和模型处理。不是模型首包、不是物理耳朵校准,也不拿不同样本相加。LLM/queued字段只是同轮分段记录。视频“首次可见”只有媒体ready标记,逐音节首个可见口型仍需同步复核,不与声音口径混用。
|
||||
|
||||
最终连续浏览器音画的两轮:首次从日常进入7.43s,已在近景的下一轮5.74s;本轮记录期间有长测客户端并行,不是单用户SLA。此前batch16连续618.41秒、15次真实模型回复、15次首声全部返回、无pageerror/错误状态;P50 5.62s,范围4.93~7.57s,10秒采样总显存最大20248MiB,末尾18277MiB。前段曾并行功能/麦克风自测,不能说这是纯单会话显存峰值。
|
||||
|
||||
batch8最终代码与新素材目录的长测 619.89 秒,15轮提交均返回实际声音,P50 5.19s、范围4.49~7.79s;无pageerror或错误状态。10秒采样总显存最大16168MiB、末尾15110MiB。前段并行了功能、麦克风和取消竞态测试。与batch16样本非严格受控对照,不能把差值当作SLA改善保证。总显存采样包含既有TTS等进程,10秒采样可能漏过瞬时峰值;不声称已测得绝对峰值或无泄漏的长期保证。
|
||||
|
||||
## 隔离与交接
|
||||
|
||||
代码/模型不合并、不部署、不改开机启动。现有18080/18081、8090、9880、10095等共享服务保持。临时服务使用8010/8014,仅本轮自测;启动前确认空闲,按精确PID记录和停止,不使用pkill/fuser清理。权重和用户素材保留。
|
||||
|
||||
分支 `hel-714-daily-talk`,实际[草稿PR #2](http://192.168.200.36:3200/leefer/CyberGril/pulls/2),目标main。通过Gitea现有SSH的AGit创建,无需Token;PR和远端分支head均已核对。交付时Multica的PR链接表仍为空,CLI只有查询功能,没有盲改标题或调用平台私有API。最终提交号随卡片评论交接。
|
||||
|
||||
本轮最后的网关PID706044、driver PID737284已按精确PID/命令/cwd核对后停止,先核对其不等于Multica daemon PID44286。8010/8014均无监听;18080/18081仍为原PID538167/608898,9880仍为445461,10095仍为原docker代理。停止后总显存约5701MiB。权重、生成素材和新avatar保留,未部署长期站点。故障注入的HTTPS客户端断开曾产生Python/aiohttp sendfile清理traceback,页面随后恢复且不影响长测;原始网关日志保留,没有升级共享依赖掩盖它。当前同步/自然观感与真人、真机缺口均显式列出,不能据构建和基础测试通过自审上线。
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"persona_id": "wanwan-v2-cream-night"
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
{
|
||||
"companion_id": "wanwan",
|
||||
"persona_id": "wanwan-v2-cream-night",
|
||||
"version": "hel714-v2",
|
||||
"previous_version": "hel714-v1",
|
||||
"identity_ref": "ref/identity.png",
|
||||
"created_by": "HEL-714 / P10 reused assets",
|
||||
"created_at": "2026-10-20",
|
||||
"pipeline_version": "hel714-wan-first-last-v1",
|
||||
"outfit": "cream",
|
||||
"light": "warm-bedroom-night",
|
||||
"weather_source": "manual-test",
|
||||
"default_daily": "reading-rain-night",
|
||||
"daily_clips": [
|
||||
{
|
||||
"id": "reading-rain-night",
|
||||
"file": "daily/reading-rain-night.mp4",
|
||||
"timeofday": "night",
|
||||
"weather": "rain",
|
||||
"activity": "reading",
|
||||
"loop_points": [
|
||||
0,
|
||||
195
|
||||
],
|
||||
"loop_review": "pending-human-review"
|
||||
}
|
||||
],
|
||||
"talk_clips": [
|
||||
{
|
||||
"id": "gaze",
|
||||
"file": "talk/gaze.mp4",
|
||||
"avatar_id": "hel714-gaze-v1",
|
||||
"framing": "approved v2 near reference, center square crop",
|
||||
"approved": false,
|
||||
"gaze_review": "new 81-frame subtle-motion candidate; pending human review",
|
||||
"source_sha256": "d8028b938096ed02d03f727c3723cf423d8dd2ab794d84b532c778a2cde118d5",
|
||||
"driver_revision": "c726943"
|
||||
}
|
||||
],
|
||||
"transition": {
|
||||
"enter": "transitions/enter.mp4",
|
||||
"return": "transitions/return.mp4",
|
||||
"cut_frame": 96,
|
||||
"available": true,
|
||||
"approved": false,
|
||||
"cut_points": [
|
||||
96
|
||||
],
|
||||
"reason": "forward-generated first/last conditioned motion, not reversed or crossfaded"
|
||||
},
|
||||
"manual_consistency_review": "candidate contact sheet checked; final human motion review pending",
|
||||
"sha256": {
|
||||
"ref/identity.png": "e40b72c44611cc6f0a9651ad24cc4b0985e2bb8efa19cba963d515a7a6cf4c8f",
|
||||
"daily/reading-rain-night.mp4": "776801d38db4a4c3c0afa7488b380987fd9541c699dcfa6e8b26aa492d8255cf",
|
||||
"talk/gaze.mp4": "d8028b938096ed02d03f727c3723cf423d8dd2ab794d84b532c778a2cde118d5",
|
||||
"transitions/enter.mp4": "d014fc07f0f1c4ba6686f51380cc99f472119c70527a65b8f37c7992dded8828",
|
||||
"transitions/return.mp4": "ca5cdfd8a3dd1267a5e95b587fb1d5fc921421993742707e9fe931bedeee9c7c",
|
||||
"voice/voice.json": "dc235f2eccba209fdb63873b9f74ee99a899fe9e8883e497704d6ebd75b3ee2f"
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"registered_voice": "xiaoyun",
|
||||
"silent_fallback": false
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>晚晚 · 交谈样机</title></head>
|
||||
<body><main>
|
||||
<header><h1>晚晚</h1><small>本地交谈样机 · 人物 v2</small></header>
|
||||
<section class="glass stage" aria-label="晚晚的房间">
|
||||
<video id="daily" playsinline muted loop preload="auto"></video>
|
||||
<video id="talk" playsinline autoplay hidden></video>
|
||||
<video id="listening" playsinline muted loop hidden></video>
|
||||
<video id="bridge" playsinline muted hidden></video>
|
||||
<p id="scene-label">日常成片 · 阅读</p>
|
||||
</section>
|
||||
<section class="glass controls">
|
||||
<p id="status" role="status" aria-live="polite">正在检查素材…</p>
|
||||
<p id="warning" role="alert">近景仍是阅读片裁切;抬头、目视交谈与自然回程尚未通过观感验收。</p>
|
||||
<div class="row"><button id="enter">进入交谈</button><button id="cancel">停下,听我说</button><button id="back">回到阅读</button><button id="pause">暂停日常</button></div>
|
||||
<form id="form"><label for="text">对晚晚说</label><div class="row"><input id="text" maxlength="500" autocomplete="off" placeholder="说说今天的事"><button type="submit">发送</button></div></form>
|
||||
<div class="row"><button id="mic" aria-pressed="false">开启麦克风</button><button id="retry">重连</button><button id="record">录制音画证据</button></div>
|
||||
<p id="transcript" aria-live="polite"></p><p id="reply"></p>
|
||||
<details><summary>场景测试</summary><div class="row">
|
||||
<label>活动 <select id="activity"><option value="reading">阅读</option><option value="rest">休息</option></select></label>
|
||||
<label>天气(手动测试) <select id="weather"><option value="rain">雨天</option><option value="clear">晴天</option></select></label>
|
||||
<label>时段 <select id="timeofday"><option value="night">夜晚</option><option value="day">白天</option></select></label>
|
||||
</div><p id="selection"></p><small>真实天气未接入。素材替换不修改身份、八字、记忆或关系;本页未接入这些模块。</small></details>
|
||||
<a id="download" hidden>下载连续音画</a>
|
||||
</section>
|
||||
</main><script type="module" src="/src/main.ts"></script></body></html>
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"name": "cybergril-companion-sample",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "python3 tools/stage_assets.py && tsc --noEmit && vite build",
|
||||
"preview": "vite preview --host 127.0.0.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"pixi.js": "^8.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^5.4.0"
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
/* Native AudioWorklet: 100ms PCM packets. AudioContext requests 16kHz. */
|
||||
class PCM extends AudioWorkletProcessor {
|
||||
constructor() { super(); this.buffer = []; }
|
||||
process(inputs) {
|
||||
const channel = inputs[0]?.[0];
|
||||
if (!channel) return true;
|
||||
this.buffer.push(...channel);
|
||||
const count = Math.round(sampleRate / 10);
|
||||
while (this.buffer.length >= count) {
|
||||
const input = this.buffer.splice(0, count);
|
||||
const output = new Int16Array(1600);
|
||||
let sum = 0;
|
||||
for (let i = 0; i < 1600; i++) {
|
||||
const value = input[Math.min(count - 1, Math.floor(i * count / 1600))];
|
||||
output[i] = Math.round(Math.max(-1, Math.min(1, value)) * 32767);
|
||||
sum += value * value;
|
||||
}
|
||||
this.port.postMessage({pcm:output.buffer, rms:Math.sqrt(sum/1600), ms:100}, [output.buffer]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
registerProcessor('pcm', PCM);
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"driver": "http://127.0.0.1:8010",
|
||||
"llm": "http://192.168.200.11:8731/v1/chat/completions",
|
||||
"model": "halogen-qwen3.8-flash-next",
|
||||
"tts": "http://127.0.0.1:9880",
|
||||
"voice": "xiaoyun",
|
||||
"asr": "ws://127.0.0.1:10095"
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
"""Isolated sample gateway. Reuses existing aiohttp; never mutates companion state.
|
||||
|
||||
Each speaking turn owns a WebRTC peer. Cancellation retires that peer, cancels
|
||||
upstream HTTP work, and closes the driver session. A late packet cannot be played
|
||||
by the next peer. TTS is buffered as one utterance to avoid punctuation gaps.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import secrets
|
||||
import ssl
|
||||
import time
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class Gateway:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
self.sessions = {}
|
||||
self.http = None
|
||||
|
||||
async def start(self, app):
|
||||
self.http = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=90))
|
||||
|
||||
async def stop(self, app):
|
||||
for token in list(self.sessions):
|
||||
await self.retire(token)
|
||||
await self.http.close()
|
||||
|
||||
async def driver(self, path, data):
|
||||
async with self.http.post(self.config["driver"] + path, json=data) as response:
|
||||
response.raise_for_status()
|
||||
result = await response.json()
|
||||
if result.get("code", 0) != 0:
|
||||
raise RuntimeError(result.get("msg", "driver failed"))
|
||||
return result
|
||||
|
||||
async def retire(self, token):
|
||||
session = self.sessions.pop(token, None)
|
||||
if not session:
|
||||
return
|
||||
task = session.get("task")
|
||||
if task and not task.done():
|
||||
task.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await task
|
||||
# Flush and destroy the peer, including inference/output queues. The
|
||||
# isolated driver extension closes only this peer, never other services.
|
||||
await self.driver("/hel714/close", {"sessionid": session["sid"]})
|
||||
|
||||
async def offer(self, request):
|
||||
params = await request.json()
|
||||
manifest = json.loads((ROOT / "dist/assets/manifest.json").read_text())
|
||||
clips = manifest.get("talk_clips", [])
|
||||
if not clips:
|
||||
raise RuntimeError("当前外观包没有交谈底板,未改用其他人物")
|
||||
answer = await self.driver(
|
||||
"/offer", {"sdp": params["sdp"], "type": "offer", "avatar": clips[0]["avatar_id"]}
|
||||
)
|
||||
token = secrets.token_urlsafe(24)
|
||||
self.sessions[token] = {"sid": answer["sessionid"], "task": None, "ready": asyncio.Event()}
|
||||
return web.json_response({**answer, "token": token})
|
||||
|
||||
async def ready(self, request):
|
||||
session = self.sessions.get((await request.json())["token"])
|
||||
if not session:
|
||||
raise web.HTTPConflict(text="会话已取消")
|
||||
session["ready"].set()
|
||||
return web.json_response({"ready": True})
|
||||
|
||||
async def cancel(self, request):
|
||||
await self.retire((await request.json())["token"])
|
||||
return web.json_response({"cancelled": True})
|
||||
|
||||
async def reply(self, session, text):
|
||||
started = time.monotonic()
|
||||
cfg = self.config
|
||||
async with self.http.get(cfg["tts"] + "/health") as response:
|
||||
response.raise_for_status()
|
||||
health = await response.json()
|
||||
if not health.get("ok") or cfg["voice"] not in health.get("voices", []):
|
||||
raise RuntimeError("指定音色不可用;已停止,未回退其他音色")
|
||||
async with self.http.post(
|
||||
cfg["llm"],
|
||||
json={
|
||||
"model": cfg["model"],
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": "你是晚晚。当前画面是你在卧室阅读,书名未知。用一两句简短自然的中文回应。不编造书名,不声称有未接入的记忆、天气或感知。",
|
||||
},
|
||||
{"role": "user", "content": text},
|
||||
],
|
||||
"max_tokens": 100,
|
||||
},
|
||||
) as response:
|
||||
response.raise_for_status()
|
||||
body = await response.json()
|
||||
reply = body["choices"][0]["message"]["content"]
|
||||
llm_ms = round((time.monotonic() - started) * 1000)
|
||||
pcm = bytearray()
|
||||
async with self.http.post(
|
||||
cfg["tts"] + "/tts",
|
||||
json={
|
||||
"voice": cfg["voice"],
|
||||
"text": reply,
|
||||
},
|
||||
) as response:
|
||||
response.raise_for_status()
|
||||
async for chunk in response.content.iter_chunked(4800):
|
||||
pcm.extend(chunk)
|
||||
if len(pcm) > 24000 * 2 * 45:
|
||||
raise RuntimeError("语音超过样机上限,已停止")
|
||||
if not pcm:
|
||||
raise RuntimeError("语音服务未返回音频")
|
||||
# Generate while the camera transition/ICE handshake runs, but never
|
||||
# enqueue speech until the browser confirms the media view is ready.
|
||||
if session.get("ready"):
|
||||
await asyncio.wait_for(session["ready"].wait(), timeout=20)
|
||||
wav = io.BytesIO()
|
||||
with wave.open(wav, "wb") as output:
|
||||
output.setnchannels(1)
|
||||
output.setsampwidth(2)
|
||||
output.setframerate(24000)
|
||||
output.writeframes(pcm)
|
||||
form = aiohttp.FormData()
|
||||
form.add_field("sessionid", session["sid"])
|
||||
form.add_field("file", wav.getvalue(), filename="utterance.wav", content_type="audio/wav")
|
||||
async with self.http.post(cfg["driver"] + "/humanaudio", data=form) as response:
|
||||
response.raise_for_status()
|
||||
result = await response.json()
|
||||
if result.get("code") != 0:
|
||||
raise RuntimeError(result.get("msg", "audio enqueue failed"))
|
||||
return {
|
||||
"text": reply,
|
||||
"llm_ms": llm_ms,
|
||||
"queued_ms": round((time.monotonic() - started) * 1000),
|
||||
"audio_seconds": len(pcm) / 48000,
|
||||
}
|
||||
|
||||
async def turn(self, request):
|
||||
params = await request.json()
|
||||
session = self.sessions.get(params["token"])
|
||||
if not session:
|
||||
raise web.HTTPConflict(text="会话已取消,请重新进入")
|
||||
if session["task"]:
|
||||
raise web.HTTPConflict(text="本轮已提交,请先取消")
|
||||
text = str(params.get("text", "")).strip()
|
||||
if not text or len(text) > 500:
|
||||
raise web.HTTPBadRequest(text="请输入1至500字")
|
||||
task = session["task"] = asyncio.create_task(self.reply(session, text))
|
||||
try:
|
||||
result = await task
|
||||
except asyncio.CancelledError:
|
||||
raise web.HTTPConflict(text="本轮已取消") from None
|
||||
return web.json_response(result)
|
||||
|
||||
async def asr(self, request):
|
||||
browser = web.WebSocketResponse(max_msg_size=1024 * 1024)
|
||||
await browser.prepare(request)
|
||||
try:
|
||||
async with self.http.ws_connect(self.config["asr"]) as upstream:
|
||||
await upstream.send_json(
|
||||
{
|
||||
"mode": "2pass",
|
||||
"wav_name": "hel714",
|
||||
"is_speaking": True,
|
||||
"wav_format": "pcm",
|
||||
"chunk_size": [5, 10, 5],
|
||||
"audio_fs": 16000,
|
||||
"itn": True,
|
||||
}
|
||||
)
|
||||
|
||||
async def receive():
|
||||
async for message in upstream:
|
||||
if message.type == aiohttp.WSMsgType.TEXT:
|
||||
data = json.loads(message.data)
|
||||
await browser.send_json(data)
|
||||
await browser.close()
|
||||
|
||||
reader = asyncio.create_task(receive())
|
||||
try:
|
||||
async for message in browser:
|
||||
if message.type == aiohttp.WSMsgType.BINARY:
|
||||
await upstream.send_bytes(message.data)
|
||||
elif message.type == aiohttp.WSMsgType.TEXT:
|
||||
# Only endpoint signals are accepted from the client.
|
||||
await upstream.send_json({"is_speaking": False})
|
||||
finally:
|
||||
reader.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await reader
|
||||
except (aiohttp.ClientError, TimeoutError) as error:
|
||||
if not browser.closed:
|
||||
await browser.send_json({"error": f"ASR不可达: {type(error).__name__}"})
|
||||
finally:
|
||||
await browser.close()
|
||||
return browser
|
||||
|
||||
|
||||
@web.middleware
|
||||
async def guard(request, handler):
|
||||
origin = request.headers.get("Origin")
|
||||
if origin and origin != f"{request.scheme}://{request.host}":
|
||||
raise web.HTTPForbidden(text="仅接受同源请求")
|
||||
try:
|
||||
return await handler(request)
|
||||
except (aiohttp.ClientError, TimeoutError, RuntimeError, KeyError) as error:
|
||||
return web.json_response({"error": str(error)}, status=502)
|
||||
|
||||
|
||||
def make_app(config):
|
||||
gateway = Gateway(config)
|
||||
app = web.Application(middlewares=[guard], client_max_size=1024 * 1024)
|
||||
app.on_startup.append(gateway.start)
|
||||
app.on_cleanup.append(gateway.stop)
|
||||
app.router.add_post("/api/offer", gateway.offer)
|
||||
app.router.add_post("/api/cancel", gateway.cancel)
|
||||
app.router.add_post("/api/turn", gateway.turn)
|
||||
app.router.add_post("/api/ready", gateway.ready)
|
||||
app.router.add_get("/api/asr", gateway.asr)
|
||||
app.router.add_get("/", lambda _: web.FileResponse(ROOT / "dist/index.html"))
|
||||
app.router.add_static("/", ROOT / "dist", show_index=False)
|
||||
return app
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=8014)
|
||||
parser.add_argument("--cert")
|
||||
parser.add_argument("--key")
|
||||
args = parser.parse_args()
|
||||
tls = None
|
||||
if args.cert:
|
||||
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
tls.load_cert_chain(args.cert, args.key)
|
||||
web.run_app(
|
||||
make_app(json.loads((ROOT / "runtime/config.json").read_text())),
|
||||
host=args.host,
|
||||
port=args.port,
|
||||
ssl_context=tls,
|
||||
)
|
||||
@@ -1,70 +0,0 @@
|
||||
/* Existing rain-room base controls, extracted without overrides. */
|
||||
* {
|
||||
box-sizing:border-box
|
||||
}
|
||||
[hidden] {
|
||||
display:none!important
|
||||
}
|
||||
html,body {
|
||||
margin:0;
|
||||
min-height:100%;
|
||||
background:var(--scene-night-deep);
|
||||
color:var(--ink-primary);
|
||||
font-family:var(--font-sans);
|
||||
font-size:var(--fs-body);
|
||||
letter-spacing:.02em
|
||||
}
|
||||
body {
|
||||
height:100dvh;
|
||||
overflow:hidden
|
||||
}
|
||||
button,input,textarea,select {
|
||||
font:inherit;
|
||||
color:inherit
|
||||
}
|
||||
button {
|
||||
cursor:pointer;
|
||||
border:1px solid transparent;
|
||||
background:transparent;
|
||||
border-radius:var(--r-control);
|
||||
padding:var(--space-2) var(--space-3);
|
||||
transition:transform 160ms var(--ease-out),opacity 160ms var(--ease-out)
|
||||
}
|
||||
button:active {
|
||||
transform:scale(.94);
|
||||
opacity:.7
|
||||
}
|
||||
button:disabled {
|
||||
color:var(--ink-disabled);
|
||||
cursor:default
|
||||
}
|
||||
button[aria-disabled=true] {
|
||||
color:var(--ink-disabled)
|
||||
}
|
||||
button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible {
|
||||
outline:2px solid var(--accent);
|
||||
outline-offset:3px
|
||||
}
|
||||
p,h1,h2 {
|
||||
margin:0
|
||||
}
|
||||
small {
|
||||
font-size:var(--fs-caption);
|
||||
color:var(--ink-secondary)
|
||||
}
|
||||
h1 {
|
||||
font-size:var(--fs-title);
|
||||
font-weight:500
|
||||
}
|
||||
h2 {
|
||||
font-size:var(--fs-title);
|
||||
font-weight:500
|
||||
}
|
||||
.glass {
|
||||
background:var(--glass-bg);
|
||||
border:1px solid var(--glass-border);
|
||||
border-radius:var(--r-panel);
|
||||
backdrop-filter:var(--glass-blur);
|
||||
-webkit-backdrop-filter:var(--glass-blur);
|
||||
box-shadow:inset 0 1px 0 var(--glass-highlight),var(--shadow-panel)
|
||||
}
|
||||
@@ -1,323 +0,0 @@
|
||||
import './style.css';
|
||||
|
||||
type Clip = { id:string; file:string; activity:string; weather:string; timeofday:string };
|
||||
type Manifest = { companion_id:string; version:string; default_daily:string; daily_clips:Clip[]; talk_clips:{file:string;avatar_id:string; approved:boolean}[]; transition?:{enter:string;return:string;cut_frame:number;available:boolean} };
|
||||
const el = <T extends HTMLElement>(id:string) => document.getElementById(id) as T;
|
||||
const daily=el<HTMLVideoElement>('daily'), talk=el<HTMLVideoElement>('talk');
|
||||
const listening=el<HTMLVideoElement>('listening'), bridge=el<HTMLVideoElement>('bridge');
|
||||
let view:'daily'|'talk'|'listening'|'bridge'='daily';
|
||||
const status=el('status');
|
||||
let manifest:Manifest, clipId='', inTalk=false, paused=false, generation=0;
|
||||
let dailyMissing=false;
|
||||
let pc:RTCPeerConnection|null=null, token='', abort:AbortController|null=null;
|
||||
let serial:Promise<unknown>=Promise.resolve();
|
||||
let mic:MediaStream|null=null, micContext:AudioContext|null=null, asr:WebSocket|null=null;
|
||||
let utterance=false, loud=0, quiet=0, submitted=false, micEpoch=0, finalTimer=0;
|
||||
let asrTimeout=0, endpointSent=false;
|
||||
let partials:string[]=[];
|
||||
let mediaSource:MediaStreamAudioSourceNode|null=null, audioContext:AudioContext|null=null;
|
||||
let destination:MediaStreamAudioDestinationNode|null=null, analyser:AnalyserNode|null=null;
|
||||
let recording:MediaRecorder|null=null, recordingRaf=0, downloadUrl='';
|
||||
const events:{at:number; event:string; detail:unknown}[]=[];
|
||||
function mark(event:string, detail:unknown={}) { events.push({at:performance.now(),event,detail}); }
|
||||
Object.assign(window,{sampleEvents:events});
|
||||
function message(text:string) { status.textContent=text; mark('status',text); }
|
||||
function setView(next:typeof view) {
|
||||
view=next;
|
||||
for(const [name,video] of [['daily',daily],['talk',talk],['listening',listening],['bridge',bridge]] as const) {
|
||||
video.hidden=name!==next;
|
||||
if(name!==next)video.pause();
|
||||
}
|
||||
if(next==='listening')void listening.play().catch(()=>message('倾听底板不可用,请回到日常或重试。'));
|
||||
}
|
||||
async function playBridge(file:string, epoch:number) {
|
||||
bridge.src=`/assets/${file}`;setView('bridge');await bridge.play();
|
||||
const deadline=performance.now()+15000;
|
||||
while(!bridge.ended&&epoch===generation) {
|
||||
if(bridge.error||performance.now()>deadline)throw new Error('转场素材无法播放');
|
||||
await new Promise(r=>setTimeout(r,40));
|
||||
}
|
||||
}
|
||||
async function enterBridge(epoch:number) {
|
||||
const transition=manifest.transition;
|
||||
if(view!=='daily'||!transition?.available)return;
|
||||
const cut=transition.cut_frame/25;
|
||||
message('等待阅读可切点,再抬头交谈…');
|
||||
if(paused){paused=false;el('pause').textContent='暂停日常';}
|
||||
await daily.play();
|
||||
const deadline=performance.now()+12000;
|
||||
let previous=daily.currentTime;
|
||||
while(epoch===generation) {
|
||||
const now=daily.currentTime;
|
||||
if(previous<=cut&&now>=cut)break;
|
||||
if(performance.now()>deadline)throw new Error('日常视频未到达可切点');
|
||||
previous=now;await new Promise(r=>setTimeout(r,16));
|
||||
}
|
||||
if(epoch!==generation)return;
|
||||
daily.pause();daily.currentTime=cut;mark('enter-cut',{frame:transition.cut_frame});
|
||||
await playBridge(transition.enter,epoch);
|
||||
}
|
||||
|
||||
async function api(path:string, data:unknown, signal?:AbortSignal) {
|
||||
const response=await fetch(`/api/${path}`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data),signal});
|
||||
if(!response.ok) throw new Error((await response.text()).slice(0,200));
|
||||
return response.json();
|
||||
}
|
||||
function enqueue<T>(fn:()=>Promise<T>):Promise<T> {
|
||||
const next=serial.then(fn,fn); serial=next.catch(()=>{}); return next;
|
||||
}
|
||||
function stopMic() {
|
||||
micEpoch++; clearTimeout(finalTimer); clearTimeout(asrTimeout); asr?.close(); asr=null;
|
||||
mic?.getTracks().forEach(t=>t.stop());mic=null;
|
||||
void micContext?.close();micContext=null;
|
||||
utterance=false;partials=[]; loud=quiet=0;
|
||||
el('mic').setAttribute('aria-pressed','false');el('mic').textContent='开启麦克风';
|
||||
}
|
||||
// Immediate local silence is independent of network/transition progress.
|
||||
function silence(reason:string, keepMic=false) {
|
||||
generation++; abort?.abort();abort=null;
|
||||
mediaSource?.disconnect();mediaSource=null;
|
||||
talk.muted=true;talk.pause();talk.srcObject=null;
|
||||
pc?.close();pc=null;setView(inTalk?'listening':'daily');
|
||||
const oldToken=token;token='';
|
||||
if(!keepMic)stopMic();
|
||||
if(oldToken)void enqueue(()=>api('cancel',{token:oldToken})).catch(e=>message(`已本地停止;服务端取消失败:${e.message}`));
|
||||
mark('cancel',{reason,generation});
|
||||
}
|
||||
function fail(error:unknown) {
|
||||
inTalk=false;silence('error');
|
||||
message(dailyMissing?'日常素材丢失或无法解码,交谈入口已禁用。请恢复素材包后刷新。':`已停止交谈,保留日常。${error instanceof Error?error.message:String(error)};可点击重连。`);
|
||||
}
|
||||
async function audioGraph() {
|
||||
if(!audioContext) {
|
||||
audioContext=new AudioContext();destination=audioContext.createMediaStreamDestination();
|
||||
analyser=audioContext.createAnalyser();
|
||||
// Keep the recording clock producing actual silence before the first peer
|
||||
// arrives. Otherwise Chromium may omit the opening daily/transition frames
|
||||
// while waiting for the first audio packet.
|
||||
const clock=audioContext.createConstantSource();clock.offset.value=0;
|
||||
clock.connect(destination);clock.connect(audioContext.destination);clock.start();
|
||||
}
|
||||
await audioContext.resume();
|
||||
}
|
||||
async function connect(epoch:number, onOffer?:(token:string)=>void) {
|
||||
if(pc&&token) return;
|
||||
const peer=new RTCPeerConnection({iceServers:[]});pc=peer;
|
||||
const stream=new MediaStream();talk.srcObject=stream;talk.muted=true;
|
||||
peer.ontrack=event=>{if(epoch===generation)stream.addTrack(event.track)};
|
||||
peer.onconnectionstatechange=()=>{
|
||||
if(peer!==pc)return;
|
||||
if(['failed','disconnected'].includes(peer.connectionState))fail(new Error('媒体连接中断'));
|
||||
};
|
||||
peer.addTransceiver('audio',{direction:'recvonly'});peer.addTransceiver('video',{direction:'recvonly'});
|
||||
await peer.setLocalDescription(await peer.createOffer());
|
||||
await new Promise<void>((resolve,reject)=>{
|
||||
const timeout=setTimeout(()=>reject(new Error('媒体协商超时')),8000);
|
||||
const check=()=>{if(peer.iceGatheringState==='complete'){clearTimeout(timeout);resolve()}};
|
||||
peer.addEventListener('icegatheringstatechange',check);check();
|
||||
peer.addEventListener('connectionstatechange',()=>{
|
||||
if(peer.connectionState==='closed'){clearTimeout(timeout);reject(new Error('本轮媒体已取消'));}
|
||||
});
|
||||
});
|
||||
const answer=await api('offer',peer.localDescription);
|
||||
if(epoch!==generation) { peer.close();await api('cancel',{token:answer.token});return; }
|
||||
token=answer.token;
|
||||
onOffer?.(token);
|
||||
await peer.setRemoteDescription(answer);
|
||||
await talk.play();
|
||||
await new Promise<void>((resolve,reject)=>{
|
||||
const timeout=setTimeout(()=>reject(new Error('媒体未到达,HTTP成功不代表媒体已通')),10000);
|
||||
const check=()=>{if(talk.readyState>=2){clearTimeout(timeout);resolve()}};
|
||||
talk.addEventListener('loadeddata',check,{once:true});check();
|
||||
});
|
||||
if(epoch!==generation)return;
|
||||
await enterBridge(epoch);
|
||||
if(epoch!==generation)return;
|
||||
setView('talk');await talk.play();
|
||||
// New peer contains only this turn's media, so unmuting cannot reveal an old queue.
|
||||
mediaSource=audioContext!.createMediaStreamSource(stream);
|
||||
mediaSource.connect(audioContext!.destination);mediaSource.connect(destination!);mediaSource.connect(analyser!);
|
||||
talk.muted=true;el('scene-label').textContent='本地实时口型 · 目光与身体来自底板';
|
||||
await api('ready',{token});
|
||||
mark('media-ready');
|
||||
}
|
||||
async function enter() {
|
||||
if(!manifest?.talk_clips.length)throw new Error('交谈素材缺失,入口已禁用');
|
||||
inTalk=true;message('正在连接本地交谈…');await audioGraph();
|
||||
const epoch=generation;
|
||||
try { await enqueue(()=>connect(epoch)); }
|
||||
catch(error) { if(epoch===generation)throw error;return; }
|
||||
if(epoch===generation)message('正在听。可以输入文字,或开启麦克风。');
|
||||
}
|
||||
async function send(text:string) {
|
||||
if(!text.trim())return;
|
||||
const finishedAt=performance.now();
|
||||
silence('new-turn',true);inTalk=true;
|
||||
const epoch=generation;
|
||||
message('正在连接本轮媒体…');await audioGraph();
|
||||
abort=new AbortController();
|
||||
const signal=abort.signal;
|
||||
let pending:Promise<{result:any;error:unknown}>|undefined;
|
||||
mark('input-finished',{text,finishedAt});
|
||||
try {
|
||||
await enqueue(()=>connect(epoch,currentToken=>{
|
||||
pending=api('turn',{token:currentToken,text},signal).then(result=>({result,error:null}),error=>({result:null,error}));
|
||||
}));
|
||||
} catch(error) { if(epoch===generation)throw error;return; }
|
||||
if(epoch!==generation)return;
|
||||
message('正在准备回复与语音,等待首声…');
|
||||
const analysis=analyser!, values=new Float32Array(analysis.fftSize);
|
||||
let firstAudio=false, monitor=0;
|
||||
function measure() {
|
||||
if(epoch!==generation)return;
|
||||
analysis.getFloatTimeDomainData(values);
|
||||
const rms=Math.sqrt(values.reduce((s,v)=>s+v*v,0)/values.length);
|
||||
if(!firstAudio&&rms>0.015){firstAudio=true;mark('first-audible',{latencyMs:performance.now()-finishedAt});message('正在回应…');}
|
||||
monitor=requestAnimationFrame(measure);
|
||||
} measure();
|
||||
try {
|
||||
if(!pending)throw new Error('本轮请求未创建');
|
||||
const response=await pending;
|
||||
if(response.error)throw response.error;
|
||||
const result=response.result;
|
||||
if(epoch!==generation)return;
|
||||
el('reply').textContent=result.text;mark('audio-queued',result);
|
||||
// Duration covers utterance playback plus driver lookahead; cancellation
|
||||
// still independently retires the peer at any point during this wait.
|
||||
const deadline=performance.now()+(result.audio_seconds+8)*1000;
|
||||
while(epoch===generation&&performance.now()<deadline)await new Promise(r=>setTimeout(r,100));
|
||||
if(epoch===generation){silence('completed',true);message('正在听。');}
|
||||
} catch(error) { if(epoch===generation)throw error; }
|
||||
finally {cancelAnimationFrame(monitor);}
|
||||
}
|
||||
async function selectClip() {
|
||||
const activity=el<HTMLSelectElement>('activity').value, weather=el<HTMLSelectElement>('weather').value, timeofday=el<HTMLSelectElement>('timeofday').value;
|
||||
const exact=manifest.daily_clips.find(c=>c.activity===activity&&c.weather===weather&&c.timeofday===timeofday);
|
||||
const clip=exact??manifest.daily_clips.find(c=>c.id===manifest.default_daily);
|
||||
if(!clip)throw new Error('默认日常素材缺失');
|
||||
el('selection').textContent=exact?'已匹配活动/手动天气/时段。':`缺少所选场景,回退默认阅读片(${clip.weather}/${clip.timeofday})。`;
|
||||
if(clip.id!==clipId){daily.src=`/assets/${clip.file}`;clipId=clip.id;}
|
||||
if(!paused&&!inTalk&&!document.hidden)await daily.play();
|
||||
}
|
||||
|
||||
async function startMic() {
|
||||
if(mic){stopMic();return;}
|
||||
if(!isSecureContext||!navigator.mediaDevices)throw new Error('麦克风需要HTTPS或localhost安全上下文;文字仍可用');
|
||||
mic=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:true,noiseSuppression:true,autoGainControl:true},video:false});
|
||||
micContext=new AudioContext({sampleRate:16000});
|
||||
await micContext.audioWorklet.addModule('/pcm-worklet.js');
|
||||
const source=micContext.createMediaStreamSource(mic), processor=new AudioWorkletNode(micContext,'pcm');
|
||||
const gain=micContext.createGain();gain.gain.value=0;
|
||||
source.connect(processor);processor.connect(gain);gain.connect(micContext.destination);
|
||||
const epoch=++micEpoch;
|
||||
const preRoll:ArrayBuffer[]=[];
|
||||
const commit=(socket:WebSocket)=>{
|
||||
if(!endpointSent||!partials.length)return;
|
||||
clearTimeout(finalTimer);
|
||||
finalTimer=window.setTimeout(()=>{
|
||||
if(epoch!==micEpoch||socket!==asr||submitted)return;
|
||||
clearTimeout(asrTimeout);submitted=true;const text=partials.join('');socket.close();asr=null;
|
||||
utterance=false;loud=quiet=0;preRoll.length=0;
|
||||
void send(text).catch(fail);
|
||||
},600);
|
||||
};
|
||||
processor.port.onmessage=({data}:{data:{pcm:ArrayBuffer;rms:number;ms:number}})=>{
|
||||
if(epoch!==micEpoch)return;
|
||||
preRoll.push(data.pcm);if(preRoll.length>3)preRoll.shift();
|
||||
if(data.rms>0.025){loud+=data.ms;quiet=0;}else{quiet+=data.ms;if(!utterance)loud=0;}
|
||||
if(!utterance&&loud>=150){
|
||||
silence('microphone-onset',true);inTalk=true;message('检测到开口,已停止旧回复,正在识别…');
|
||||
utterance=true;submitted=false;partials=[];endpointSent=false;
|
||||
asr=new WebSocket(`${location.protocol==='https:'?'wss':'ws'}://${location.host}/api/asr`);
|
||||
const socket=asr;
|
||||
socket.onopen=()=>{if(socket===asr)preRoll.forEach(packet=>socket.send(packet))};
|
||||
socket.onmessage=event=>{
|
||||
if(epoch!==micEpoch||socket!==asr||submitted)return;
|
||||
const response=JSON.parse(event.data);
|
||||
mark('asr-result',response);
|
||||
if(response.error){fail(new Error(response.error));return;}
|
||||
if(response.text)el('transcript').textContent=`识别:${response.text}`;
|
||||
if(String(response.mode).endsWith('offline')&&response.text){
|
||||
partials.push(response.text);commit(socket);
|
||||
}
|
||||
};
|
||||
socket.onerror=()=>fail(new Error('ASR连接失败'));
|
||||
socket.onclose=()=>{if(socket===asr&&!submitted){asr=null;utterance=false;message('识别连接结束,请重新开口或用文字。');}};
|
||||
}
|
||||
if(utterance&&!endpointSent&&asr?.readyState===WebSocket.OPEN)asr.send(data.pcm);
|
||||
if(utterance&&!endpointSent&&quiet>=650&&asr?.readyState===WebSocket.OPEN){
|
||||
endpointSent=true;asr.send(JSON.stringify({is_speaking:false}));commit(asr);
|
||||
mark('microphone-endpoint');
|
||||
asrTimeout=window.setTimeout(()=>fail(new Error('ASR未返回终稿,请重新开麦或输入文字')),6000);
|
||||
// ASR must return an actual final; never fabricate one from silence.
|
||||
}
|
||||
};
|
||||
await micContext.resume();el('mic').setAttribute('aria-pressed','true');el('mic').textContent='关闭麦克风';
|
||||
message('麦克风已开启。开口会停止旧回复;建议佩戴耳机。');
|
||||
}
|
||||
|
||||
// Record the rendered canvas and the same media element's audible output on a
|
||||
// shared browser MediaRecorder clock, instead of rebuilding timestamps by count.
|
||||
async function record() {
|
||||
if(recording?.state==='recording'){recording.stop();return;}
|
||||
await audioGraph();
|
||||
const canvas=document.createElement('canvas');canvas.width=960;canvas.height=720;
|
||||
const context=canvas.getContext('2d')!;
|
||||
const theme=getComputedStyle(document.documentElement);
|
||||
const background=theme.getPropertyValue('--scene-night-deep').trim();
|
||||
const ink=theme.getPropertyValue('--ink-primary').trim();
|
||||
const draw=()=>{
|
||||
context.fillStyle=background;context.fillRect(0,0,960,720);
|
||||
const video=view==='bridge'?bridge:view==='listening'?listening:view==='talk'?talk:daily;
|
||||
if(video.readyState>=2){const scale=Math.min(960/video.videoWidth,640/video.videoHeight);context.drawImage(video,(960-video.videoWidth*scale)/2,0,video.videoWidth*scale,video.videoHeight*scale);}
|
||||
context.fillStyle=ink;context.font='18px sans-serif';context.fillText(status.textContent??'',12,675);context.fillText(`${(performance.now()/1000).toFixed(3)}s · 浏览器播放音画`,12,705);
|
||||
recordingRaf=requestAnimationFrame(draw);
|
||||
};draw();
|
||||
const stream=canvas.captureStream(25);destination!.stream.getAudioTracks().forEach(t=>stream.addTrack(t));
|
||||
const chunks:Blob[]=[];
|
||||
recording=new MediaRecorder(stream,{mimeType:'video/webm;codecs=vp8,opus'});
|
||||
recording.ondataavailable=e=>chunks.push(e.data);
|
||||
recording.onstop=()=>{
|
||||
cancelAnimationFrame(recordingRaf);stream.getVideoTracks().forEach(t=>t.stop());
|
||||
if(downloadUrl)URL.revokeObjectURL(downloadUrl);
|
||||
downloadUrl=URL.createObjectURL(new Blob(chunks,{type:'video/webm'}));
|
||||
const link=el<HTMLAnchorElement>('download');link.href=downloadUrl;link.download='wanwan-browser-av.webm';link.hidden=false;
|
||||
el('record').textContent='录制音画证据';mark('record-stop');
|
||||
};
|
||||
recording.start(1000);el('record').textContent='停止录制';mark('record-start');
|
||||
}
|
||||
|
||||
el('enter').onclick=()=>void enter().catch(fail);
|
||||
el('retry').onclick=()=>{silence('reconnect');void enter().catch(fail)};
|
||||
el('cancel').onclick=()=>{silence('button',true);message('已停下,正在听。')};
|
||||
el('back').onclick=()=>{
|
||||
const needsReturn=view!=='daily';inTalk=false;silence('daily');const epoch=generation;
|
||||
void (async()=>{
|
||||
if(needsReturn&&manifest.transition?.available) {
|
||||
message('已停止声音,正在回到阅读…');
|
||||
await playBridge(manifest.transition.return,epoch);
|
||||
}
|
||||
if(epoch!==generation)return;
|
||||
setView('daily');el('scene-label').textContent='日常成片 · 阅读';await selectClip();message('已回到阅读原位置。');
|
||||
})().catch(fail);
|
||||
};
|
||||
el('pause').onclick=()=>{paused=!paused;daily.pause();if(!paused)void selectClip().catch(fail);el('pause').textContent=paused?'继续日常':'暂停日常'};
|
||||
el('mic').onclick=()=>void startMic().catch(fail);
|
||||
el('record').onclick=()=>void record().catch(fail);
|
||||
el('form').onsubmit=event=>{event.preventDefault();const input=el<HTMLInputElement>('text');const text=input.value;input.value='';void send(text).catch(error=>{if(error?.name!=='AbortError')fail(error)})};
|
||||
for(const id of ['activity','weather','timeofday'])el(id).onchange=()=>void selectClip().catch(fail);
|
||||
document.addEventListener('visibilitychange',()=>{
|
||||
if(document.hidden){inTalk=false;silence('hidden');daily.pause();message('页面已隐藏,音视频与麦克风均已停止;恢复后需主动进入。');}
|
||||
});
|
||||
window.addEventListener('pagehide',()=>{const old=token;silence('pagehide');if(old)void fetch('/api/cancel',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:old}),keepalive:true})});
|
||||
window.addEventListener('offline',()=>fail(new Error('网络已断开')));
|
||||
daily.onerror=()=>{dailyMissing=true;el<HTMLButtonElement>('enter').disabled=true;fail(new Error('日常素材丢失或无法解码'))};
|
||||
talk.onerror=()=>fail(new Error('实时视频无法解码'));
|
||||
void (async()=>{
|
||||
const response=await fetch('/assets/manifest.json');if(!response.ok)throw new Error('素材manifest不可达');
|
||||
manifest=await response.json();await selectClip();
|
||||
if(manifest.talk_clips.length)listening.src=`/assets/${manifest.talk_clips[0].file}`;
|
||||
if(manifest.transition?.available)el('warning').textContent='已补目视底板与真实往返候选;自然衔接、同脸和同步仍待人工观感验收。';
|
||||
el<HTMLButtonElement>('enter').disabled=!manifest.talk_clips.length;
|
||||
message('日常视频已就绪。交谈入口会连接本地实时口型。');
|
||||
})().catch(fail);
|
||||
@@ -1,20 +0,0 @@
|
||||
@import './tokens.css';
|
||||
@import './controls.css';
|
||||
main { height:100dvh; overflow:auto; padding:var(--space-6); display:grid; grid-template-columns:minmax(0,1fr) minmax(320px,420px); grid-template-rows:auto 1fr; gap:var(--space-4); }
|
||||
header { grid-column:1/-1; display:flex; align-items:baseline; gap:var(--space-4); }
|
||||
.stage { position:relative; overflow:hidden; min-height:280px; }
|
||||
.stage video { width:100%; height:100%; object-fit:contain; position:absolute; inset:0; }
|
||||
#scene-label { position:absolute; bottom:var(--space-4); left:var(--space-4); padding:var(--space-2); background:var(--glass-bg-strong); border-radius:var(--r-control); }
|
||||
.controls { padding:var(--space-5); display:flex; flex-direction:column; gap:var(--space-4); overflow:auto; }
|
||||
.row { display:flex; gap:var(--space-2); flex-wrap:wrap; align-items:center; }
|
||||
.controls button { border-color:var(--glass-border); background:var(--bubble-her); min-height:44px; }
|
||||
#enter,button[type=submit] { background:var(--accent); color:var(--accent-ink); }
|
||||
label { display:block; color:var(--ink-secondary); font-size:var(--fs-small); }
|
||||
input,select { border:1px solid var(--glass-border); border-radius:var(--r-control); background:var(--glass-bg-strong); padding:var(--space-3); min-width:0; }
|
||||
input { flex:1; width:100%; }
|
||||
#warning { color:var(--state-danger); font-size:var(--fs-small); }
|
||||
#selection, #transcript { color:var(--ink-secondary); }
|
||||
summary { cursor:pointer; padding-block:var(--space-2); }
|
||||
a { color:var(--accent); }
|
||||
@media(max-width:760px) { main { grid-template-columns:1fr; grid-template-rows:auto minmax(260px,45dvh) auto; padding:var(--space-3); } .controls { overflow:visible; } }
|
||||
@media(prefers-reduced-motion:reduce) { button { transition:none; } button:active { transform:none; } }
|
||||
@@ -1,73 +0,0 @@
|
||||
/* Reused verbatim from hel-700-rain-room; no alternative product theme. */
|
||||
:root {
|
||||
--scene-night-deep:#16233c;
|
||||
--scene-city-blue:#305481;
|
||||
--scene-city-mid:#5a76a2;
|
||||
--scene-tower:#2b456b;
|
||||
--scene-glass-blue:#718fc2;
|
||||
--scene-amber:#e8a45c;
|
||||
--scene-amber-soft:#f2c894;
|
||||
--scene-wood:#59361d;
|
||||
--scene-cream:#e8d9c8;
|
||||
--scene-blanket:#362928;
|
||||
--ink-primary:#f2efe9;
|
||||
--ink-secondary:rgba(242,239,233,.64);
|
||||
--ink-tertiary:rgba(242,239,233,.4);
|
||||
--ink-disabled:rgba(242,239,233,.28);
|
||||
--accent:#e8a45c;
|
||||
--accent-hover:#f2b879;
|
||||
--accent-pressed:#c9853f;
|
||||
--accent-ink:#1a1208;
|
||||
--glass-bg:rgba(14,18,30,.55);
|
||||
--glass-bg-strong:rgba(14,18,30,.72);
|
||||
--glass-border:rgba(255,255,255,.08);
|
||||
--glass-highlight:rgba(255,255,255,.14);
|
||||
--bubble-user:rgba(120,144,180,.2);
|
||||
--bubble-user-border:rgba(255,255,255,.07);
|
||||
--bubble-her:rgba(255,255,255,.06);
|
||||
--bubble-failed:rgba(200,90,80,.14);
|
||||
--state-danger:#e07a6a;
|
||||
--font-sans:"PingFang SC","HarmonyOS Sans SC","MiSans","Source Han Sans SC",system-ui,-apple-system,sans-serif;
|
||||
--fs-caption:12px;
|
||||
--fs-small:13px;
|
||||
--fs-body:14px;
|
||||
--fs-chat:15px;
|
||||
--fs-nav:15px;
|
||||
--fs-title:20px;
|
||||
--fs-brand:16px;
|
||||
--fs-time:13px;
|
||||
--space-1:4px;
|
||||
--space-2:8px;
|
||||
--space-3:12px;
|
||||
--space-4:16px;
|
||||
--space-5:20px;
|
||||
--space-6:24px;
|
||||
--space-8:32px;
|
||||
--space-10:40px;
|
||||
--r-panel:24px;
|
||||
--r-bubble:16px;
|
||||
--r-card:16px;
|
||||
--r-control:12px;
|
||||
--r-pill:999px;
|
||||
--shadow-panel:0 24px 80px rgba(0,0,0,.45);
|
||||
--shadow-pop:0 8px 24px rgba(0,0,0,.35);
|
||||
--glow-accent:0 0 12px rgba(232,164,92,.45);
|
||||
--glass-blur:blur(28px) saturate(1.2);
|
||||
--z-scene-far:0;
|
||||
--z-scene-rain:1;
|
||||
--z-scene-near:2;
|
||||
--z-caption:10;
|
||||
--z-nav:10;
|
||||
--z-topbar:20;
|
||||
--z-panel:30;
|
||||
--z-toast:40;
|
||||
--ease-out:cubic-bezier(.23,1,.32,1);
|
||||
--ease-in-out:cubic-bezier(.77,0,.175,1);
|
||||
--ease-drawer:cubic-bezier(.32,.72,0,1);
|
||||
--lamp-opacity:.12;
|
||||
--panel-width:clamp(360px,30vw,460px);
|
||||
--panel-top:64px;
|
||||
--panel-inset:24px;
|
||||
--scene-height:330px;
|
||||
--drawer-height:30dvh;
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
"""Source-relative lip residual + audio RMS using browser MediaRecorder PTS.
|
||||
Heuristic evidence only: no automatic perceptual-sync acceptance.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import av
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("video", type=Path)
|
||||
p.add_argument("--source", type=Path, default=Path("/opt/hel715-verify/talk-close.mp4"))
|
||||
p.add_argument("--size", type=int, default=768)
|
||||
p.add_argument("--offset-x", type=int, default=0)
|
||||
p.add_argument("--offset-y", type=int, default=0)
|
||||
p.add_argument("--render-size", type=int, default=768)
|
||||
p.add_argument("--start", type=float, default=0)
|
||||
p.add_argument("--stop", type=float, default=100000)
|
||||
p.add_argument("--roi", default="0.4492,0.6185,0.4753,0.6315")
|
||||
p.add_argument("--idle-until", type=float)
|
||||
a = p.parse_args()
|
||||
source = [f.to_ndarray(format="bgr24") for f in av.open(str(a.source)).decode(video=0)]
|
||||
size = a.size
|
||||
source = [cv2.resize(f, (size, size)) for f in source]
|
||||
# Broad lower-face region; source matching uses pixels outside it and outside
|
||||
# caption/watermark so normal head movement is not mistaken for synthesized lips.
|
||||
x0, x1, y0, y1 = [round(v * size) for v in map(float, a.roi.split(","))]
|
||||
mask = np.ones((48, 48), dtype=bool)
|
||||
mask[0:3] = False
|
||||
mask[43:] = False
|
||||
mask[
|
||||
round(y0 * 48 / size) : round(y1 * 48 / size), round(x0 * 48 / size) : round(x1 * 48 / size)
|
||||
] = False
|
||||
features = np.asarray([cv2.resize(f, (48, 48))[mask].astype(np.float32) for f in source])
|
||||
rows = []
|
||||
for f in av.open(str(a.video)).decode(video=0):
|
||||
if not a.start <= float(f.time) <= a.stop:
|
||||
continue
|
||||
image = f.to_ndarray(format="bgr24")
|
||||
image = image[a.offset_y : a.offset_y + a.render_size, a.offset_x : a.offset_x + a.render_size]
|
||||
image = cv2.resize(image, (size, size))
|
||||
feature = cv2.resize(image, (48, 48))[mask].astype(np.float32)
|
||||
index = np.argmin(((features - feature) ** 2).mean(axis=(1, 2)))
|
||||
residual = np.abs(image.astype(np.float32) - source[index]).mean(axis=2)
|
||||
rows.append([float(f.time), float(residual[y0:y1, x0:x1].mean()), int(index)])
|
||||
audio = []
|
||||
for f in av.open(str(a.video)).decode(audio=0):
|
||||
if not a.start <= float(f.time) <= a.stop:
|
||||
continue
|
||||
data = f.to_ndarray().astype(np.float64)
|
||||
if f.format.is_planar and f.format.name.startswith("fl"):
|
||||
pass
|
||||
elif data.max() > 1:
|
||||
data /= 32768
|
||||
audio.append([float(f.time), float(np.sqrt((data**2).mean()))])
|
||||
with a.video.with_suffix(".sync.csv").open("w") as out:
|
||||
w = csv.writer(out)
|
||||
w.writerow(["time_seconds", "lip_residual", "source_index", "audio_rms"])
|
||||
for t, residual, idx in rows:
|
||||
nearest = min(audio, key=lambda x: abs(x[0] - t))
|
||||
w.writerow([t, residual, idx, nearest[1]])
|
||||
first_audio = next((t for t, rms in audio if rms > 0.015), None)
|
||||
baseline = [
|
||||
r
|
||||
for t, r, _ in rows
|
||||
if first_audio and t < (a.idle_until if a.idle_until is not None else first_audio - 0.5)
|
||||
]
|
||||
threshold = max(4, float(np.quantile(baseline, 0.99)) * 1.5) if baseline else 4
|
||||
first_lip = next(
|
||||
(
|
||||
t
|
||||
for t, r, _ in rows
|
||||
if r > threshold
|
||||
and first_audio
|
||||
and t >= (a.idle_until if a.idle_until is not None else first_audio - 1)
|
||||
),
|
||||
None,
|
||||
)
|
||||
result = dict(
|
||||
first_audio=first_audio,
|
||||
first_lip=first_lip,
|
||||
residual_threshold=threshold,
|
||||
onset_difference_seconds=first_lip - first_audio if first_lip and first_audio else None,
|
||||
caveat="Source-relative residual heuristic, not phoneme alignment or perceptual acceptance",
|
||||
)
|
||||
a.video.with_suffix(".sync.json").write_text(json.dumps(result, indent=2))
|
||||
print(result)
|
||||
@@ -1,50 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
OUT = pathlib.Path(__file__).resolve().parents[1] / "evidence"
|
||||
OUT.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
async def main():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(
|
||||
args=["--no-sandbox", "--autoplay-policy=no-user-gesture-required"]
|
||||
)
|
||||
page = await browser.new_page()
|
||||
await page.goto("http://192.168.200.12:8010")
|
||||
await page.evaluate("""async () => {
|
||||
document.body.innerHTML='<video id="v" autoplay playsinline></video><canvas id="c" width="768" height="768"></canvas>';
|
||||
const v=document.querySelector('video'), c=document.querySelector('canvas'), ctx=c.getContext('2d');
|
||||
const ac=new AudioContext(), dest=ac.createMediaStreamDestination();
|
||||
const pc=window.pc=new RTCPeerConnection({iceServers:[]});
|
||||
const stream=new MediaStream(); v.srcObject=stream;
|
||||
pc.ontrack=e=>stream.addTrack(e.track);
|
||||
pc.addTransceiver('audio',{direction:'recvonly'}); pc.addTransceiver('video',{direction:'recvonly'});
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(r=>{if(pc.iceGatheringState==='complete')r();else pc.onicegatheringstatechange=()=>{if(pc.iceGatheringState==='complete')r()}});
|
||||
const a=await (await fetch('/offer',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(pc.localDescription)})).json();
|
||||
window.sid=a.sessionid; await pc.setRemoteDescription(a);
|
||||
await new Promise(r=>v.onloadeddata=r); await v.play();
|
||||
v.muted=true; const source=ac.createMediaStreamSource(stream); source.connect(ac.destination); source.connect(dest);
|
||||
await ac.resume(); const recorded=c.captureStream(25); dest.stream.getAudioTracks().forEach(t=>recorded.addTrack(t));
|
||||
window.metrics=[]; const analyser=ac.createAnalyser();source.connect(analyser);let buffer=new Float32Array(analyser.fftSize);
|
||||
function draw(){ctx.drawImage(v,0,0,768,768);ctx.fillStyle='white';ctx.font='20px sans-serif';ctx.fillText((performance.now()/1000).toFixed(3),20,750);analyser.getFloatTimeDomainData(buffer);metrics.push([performance.now(),Math.sqrt(buffer.reduce((s,x)=>s+x*x,0)/buffer.length)]);window.raf=requestAnimationFrame(draw)}draw();
|
||||
window.chunks=[];window.rec=new MediaRecorder(recorded,{mimeType:'video/webm;codecs=vp8,opus'});rec.ondataavailable=e=>chunks.push(e.data);rec.start(1000);
|
||||
}""")
|
||||
await page.wait_for_timeout(1500)
|
||||
await page.evaluate(
|
||||
"""async()=>{window.sent=performance.now();await fetch('/human',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({sessionid:sid,type:'echo',text:'你好。八百标兵奔北坡,炮兵并排北边跑。现在我停下来听你说话。'})})}"""
|
||||
)
|
||||
await page.wait_for_timeout(18000)
|
||||
data = await page.evaluate(
|
||||
"""async()=>{await new Promise(r=>{rec.onstop=r;rec.stop()});const b=new Blob(chunks);return Array.from(new Uint8Array(await b.arrayBuffer()))}"""
|
||||
)
|
||||
(OUT / "baseline-browser-av.webm").write_bytes(bytes(data))
|
||||
(OUT / "baseline.json").write_text(json.dumps(await page.evaluate("({sent,metrics})")))
|
||||
await browser.close()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,136 +0,0 @@
|
||||
"""Real Chromium/WebRTC check; fake devices are explicitly synthetic fixtures."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
import time
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence"
|
||||
OUT.mkdir(exist_ok=True)
|
||||
URL = "https://192.168.200.12:8014"
|
||||
|
||||
|
||||
async def download(page, path):
|
||||
await page.click("#record")
|
||||
await page.wait_for_selector("#download:not([hidden])")
|
||||
async with page.expect_download() as pending:
|
||||
await page.click("#download")
|
||||
await (await pending.value).save_as(path)
|
||||
|
||||
|
||||
async def main():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(
|
||||
args=["--no-sandbox", "--autoplay-policy=no-user-gesture-required"]
|
||||
)
|
||||
context = await browser.new_context(
|
||||
ignore_https_errors=True, viewport={"width": 1280, "height": 800}
|
||||
)
|
||||
page = await context.new_page()
|
||||
errors = []
|
||||
page.on("pageerror", lambda e: errors.append(str(e)))
|
||||
await page.goto(URL)
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('就绪')"
|
||||
)
|
||||
await page.click("#record")
|
||||
await page.wait_for_timeout(1000)
|
||||
await page.fill("#text", "我今天下班了,有点累。请只用一句简短的话回应。")
|
||||
await page.click("button[type=submit]")
|
||||
await page.wait_for_function(
|
||||
"window.sampleEvents.some(e=>e.event==='first-audible')", timeout=60000
|
||||
)
|
||||
await page.wait_for_timeout(1500)
|
||||
await page.click("#cancel")
|
||||
await page.wait_for_timeout(1500)
|
||||
assert await page.evaluate("document.querySelector('#talk').srcObject===null")
|
||||
await page.fill("#text", "你在看什么书?只说一句话。")
|
||||
await page.click("button[type=submit]")
|
||||
await page.wait_for_function(
|
||||
"window.sampleEvents.filter(e=>e.event==='first-audible').length>=2", timeout=60000
|
||||
)
|
||||
await page.wait_for_timeout(6000)
|
||||
await page.click("#back")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('已回到阅读')", timeout=15000
|
||||
)
|
||||
assert not await page.locator("#daily").evaluate("(v)=>v.paused")
|
||||
await page.click("#pause")
|
||||
assert await page.locator("#daily").evaluate("(v)=>v.paused")
|
||||
await page.click("#pause")
|
||||
await page.locator("summary").click()
|
||||
await page.select_option("#weather", "clear")
|
||||
assert "回退" in await page.locator("#selection").inner_text()
|
||||
await page.click("#enter")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('正在听')", timeout=30000
|
||||
)
|
||||
await page.fill("#text", "这是取消准备阶段的测试,请简短回复。")
|
||||
await page.click("button[type=submit]")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('准备回复')", timeout=30000
|
||||
)
|
||||
await page.wait_for_timeout(1000)
|
||||
await page.click("#cancel")
|
||||
await page.wait_for_timeout(6000)
|
||||
assert await page.locator("#talk").evaluate("(v)=>v.srcObject===null")
|
||||
await page.click("#back")
|
||||
(OUT / "sample-events.json").write_text(
|
||||
json.dumps(await page.evaluate("window.sampleEvents"), ensure_ascii=False, indent=2)
|
||||
)
|
||||
await download(page, OUT / "sample-browser-av.webm")
|
||||
await page.screenshot(path=str(OUT / "desktop.png"))
|
||||
await page.set_viewport_size({"width": 390, "height": 844})
|
||||
await page.screenshot(path=str(OUT / "mobile.png"), full_page=True)
|
||||
mobile_overflow = await page.evaluate("document.documentElement.scrollWidth > innerWidth")
|
||||
# Failure tests use browser request routing, never stop shared models.
|
||||
await page.route("**/api/offer", lambda route: route.abort())
|
||||
await page.click("#retry")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('已停止交谈')", timeout=30000
|
||||
)
|
||||
await page.unroute("**/api/offer")
|
||||
await page.click("#retry")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('正在听')", timeout=30000
|
||||
)
|
||||
await context.set_offline(True)
|
||||
await page.wait_for_timeout(500)
|
||||
assert await page.locator("#talk").evaluate("(v)=>v.srcObject===null")
|
||||
await context.set_offline(False)
|
||||
await page.reload()
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('就绪')"
|
||||
)
|
||||
# This is a handler test, not a claim of real OS background testing.
|
||||
await page.evaluate(
|
||||
"Object.defineProperty(document,'hidden',{configurable:true,value:true});document.dispatchEvent(new Event('visibilitychange'))"
|
||||
)
|
||||
assert await page.locator("#daily").evaluate("(v)=>v.paused")
|
||||
await page.evaluate(
|
||||
"Object.defineProperty(document,'hidden',{configurable:true,value:false})"
|
||||
)
|
||||
await page.route("**/reading-rain-night.mp4", lambda route: route.abort())
|
||||
await page.reload()
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('素材丢失')", timeout=30000
|
||||
)
|
||||
result = {
|
||||
"pageerrors": errors,
|
||||
"mobile_overflow": mobile_overflow,
|
||||
"visibility_test": "synthetic event only; real OS background not tested",
|
||||
"cancel": "speaking and preparing",
|
||||
"network": "offer abort, offline, recovery",
|
||||
"missing_asset": "daily video request abort",
|
||||
"time": time.time(),
|
||||
}
|
||||
# Events from the main continuous recording were captured before reload.
|
||||
(OUT / "browser-check.json").write_text(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
await browser.close()
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,92 +0,0 @@
|
||||
"""Run with the pinned driver venv: python check_driver_audio.py PRIVATE_DRIVER."""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
ROOT = pathlib.Path(sys.argv.pop(1)).resolve()
|
||||
sys.path.insert(0, str(ROOT))
|
||||
spec = importlib.util.spec_from_file_location('driver_webrtc', ROOT / 'server/webrtc.py')
|
||||
driver = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(driver)
|
||||
PendingAudio = driver.PendingAudio
|
||||
|
||||
|
||||
class QueueChecks(unittest.TestCase):
|
||||
def test_idle_is_bounded_speech_and_events_are_lossless(self):
|
||||
pending = PendingAudio()
|
||||
expected = []
|
||||
for i in range(2000):
|
||||
if i % 100 == 0:
|
||||
# Real zero PCM and custom audio are not synthetic silence.
|
||||
item = (i, {'event': i} if i % 200 else {}, 0 if i % 200 else 2)
|
||||
expected.append(item)
|
||||
else:
|
||||
item = (i, None, 1)
|
||||
pending.put(item)
|
||||
actual = list(pending.queue)
|
||||
self.assertEqual([x for x in actual if x[2] != 1], expected)
|
||||
self.assertEqual(sum(x[2] == 1 for x in actual), 3)
|
||||
self.assertLessEqual(pending.high_water, len(expected) + 3)
|
||||
self.assertGreater(pending.dropped_silence, 1900)
|
||||
marker = ('event', {'end': True}, 1)
|
||||
pending.put(marker)
|
||||
for i in range(50):
|
||||
pending.put((i, None, 1))
|
||||
self.assertIn(marker, list(pending.queue))
|
||||
|
||||
def test_real_audio_has_bounded_backpressure(self):
|
||||
pending = PendingAudio()
|
||||
for i in range(100):
|
||||
pending.put((i, None, 0))
|
||||
import queue
|
||||
with self.assertRaises(queue.Full):
|
||||
pending.put((101, None, 0), block=False)
|
||||
self.assertEqual([x[0] for x in pending.queue], list(range(100)))
|
||||
|
||||
def test_warmup_drains_all_context(self):
|
||||
from avatars.audio_features.base_asr import BaseASR
|
||||
asr = BaseASR(SimpleNamespace(fps=25, batch_size=8, l=10, r=10))
|
||||
asr.warm_up()
|
||||
self.assertEqual(len(asr.frames), 20)
|
||||
self.assertTrue(asr.output_queue.empty())
|
||||
first = np.arange(320, dtype=np.float32)
|
||||
asr.put_audio_frame(first, {'first': True})
|
||||
frame = asr.get_audio_frame()
|
||||
np.testing.assert_array_equal(frame.data, first)
|
||||
self.assertEqual(frame.type, 0)
|
||||
self.assertEqual(frame.userdata, {'first': True})
|
||||
|
||||
|
||||
class ClockChecks(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_starvation_preserves_cadence_and_first_pcm(self):
|
||||
player = SimpleNamespace(_start=lambda _: None, _stop=lambda _: None, notify=lambda _: None)
|
||||
track = driver.PlayerStreamTrack(player, 'audio')
|
||||
frame = driver.AudioFrame.from_ndarray(np.ones((1, 320), np.int16), format='s16', layout='mono')
|
||||
frame.sample_rate = 16000
|
||||
track._queue.put((frame, None, 0))
|
||||
start = time.monotonic()
|
||||
frames = [await track.recv() for _ in range(15)]
|
||||
self.assertEqual([f.pts for f in frames], list(range(0, 15 * 320, 320)))
|
||||
self.assertGreater(time.monotonic() - start, 0.25)
|
||||
self.assertLess(time.monotonic() - start, 0.5)
|
||||
self.assertTrue(all(not f.to_ndarray().any() for f in frames[1:]))
|
||||
# Resume with exact first speech PCM, without trimming any syllable.
|
||||
pcm = np.arange(320, dtype=np.int16).reshape(1, -1)
|
||||
voice = driver.AudioFrame.from_ndarray(pcm, format='s16', layout='mono')
|
||||
voice.sample_rate = 16000
|
||||
track._queue.put((voice, {'start': True}, 0))
|
||||
out = await track.recv()
|
||||
self.assertEqual(out.pts, 15 * 320)
|
||||
self.assertEqual(hashlib.sha256(out.to_ndarray().tobytes()).digest(), hashlib.sha256(pcm.tobytes()).digest())
|
||||
track.stop()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -1,103 +0,0 @@
|
||||
"""Exercise the patched ingress, mixed inference batch and real output loop."""
|
||||
|
||||
import hashlib
|
||||
import pathlib
|
||||
import queue
|
||||
import sys
|
||||
import unittest
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
ROOT = pathlib.Path(sys.argv.pop(1)).resolve()
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from avatars.audio_features.base_asr import BaseASR # noqa: E402
|
||||
from avatars.base_avatar import AudioFrameData, BaseAvatar # noqa: E402
|
||||
from avatars.hel720_head import HeadGate # noqa: E402
|
||||
|
||||
|
||||
def frame(value, status=None, kind=0):
|
||||
return AudioFrameData(np.full(320, value, dtype=np.float64), kind,
|
||||
{'status': status} if status else {})
|
||||
|
||||
|
||||
class HeadChecks(unittest.TestCase):
|
||||
def test_boundary_disabled_and_invalid(self):
|
||||
gate = HeadGate(.001)
|
||||
self.assertTrue(gate.classify(frame(.001, 'start')))
|
||||
self.assertFalse(gate.classify(frame(.0010001)))
|
||||
self.assertFalse(gate.classify(frame(0)))
|
||||
self.assertFalse(HeadGate(0).classify(frame(0, 'start')))
|
||||
for value in [-1, float('nan'), float('inf')]:
|
||||
with self.assertRaises(ValueError):
|
||||
HeadGate(value)
|
||||
|
||||
def test_lifecycle_starvation_custom_and_end(self):
|
||||
gate = HeadGate(.001)
|
||||
self.assertTrue(gate.classify(frame(0, 'start')))
|
||||
self.assertFalse(gate.classify(frame(.1)))
|
||||
self.assertFalse(gate.classify(frame(0, kind=1)))
|
||||
self.assertFalse(gate.classify(frame(0, kind=2)))
|
||||
self.assertFalse(gate.classify(frame(0))) # weak mid-utterance remains speech
|
||||
self.assertFalse(gate.classify(frame(0, 'end')))
|
||||
self.assertTrue(gate.classify(frame(0)))
|
||||
self.assertFalse(gate.classify(frame(.1)))
|
||||
self.assertTrue(gate.classify(frame(0, 'start')))
|
||||
|
||||
def test_cancel_and_new_peer_keep_old_decisions_isolated(self):
|
||||
opt = SimpleNamespace(fps=25, batch_size=8, l=10, r=10)
|
||||
asr = BaseASR(opt)
|
||||
asr.put_audio_frame(np.ones(320), {'status': 'start'})
|
||||
old = asr.queue.get()
|
||||
asr.flush_talk()
|
||||
asr.put_audio_frame(np.zeros(320), {})
|
||||
self.assertTrue(asr.queue.get().hel720_head_closed)
|
||||
self.assertFalse(old.hel720_head_closed)
|
||||
fresh = BaseASR(opt)
|
||||
fresh.put_audio_frame(np.zeros(320), {})
|
||||
self.assertTrue(fresh.queue.get().hel720_head_closed)
|
||||
|
||||
def test_mixed_batch_render_and_exact_audio_events_types(self):
|
||||
asr = BaseASR(SimpleNamespace(fps=25, batch_size=8, l=10, r=10))
|
||||
values = [0] * 5 + [.02] + [0] * 10
|
||||
expected = []
|
||||
for i, value in enumerate(values):
|
||||
data = np.full(320, value, np.float32)
|
||||
event = {'status': 'start'} if i == 0 else {'status': 'end'} if i == 15 else {}
|
||||
asr.put_audio_frame(data, event)
|
||||
expected.append((hashlib.sha256((data * 32767).astype(np.int16).tobytes()).hexdigest(), event, 0))
|
||||
frames = [asr.queue.get() for _ in values]
|
||||
self.assertEqual([f.hel720_head_closed for f in frames], [True]*5 + [False]*11)
|
||||
for f in frames:
|
||||
asr.output_queue.put(f)
|
||||
asr.feat_queue.put(['feature']*8)
|
||||
avatar = BaseAvatar.__new__(BaseAvatar)
|
||||
avatar.asr, avatar.batch_size = asr, 8
|
||||
avatar.frame_list_cycle = [np.zeros((32, 32, 3), np.uint8) for _ in range(20)]
|
||||
avatar.custom_index = {}
|
||||
avatar.res_frame_queue = queue.Queue()
|
||||
avatar.inference_batch = lambda index, features: [np.ones((32, 32, 3), np.uint8)*100 for _ in features]
|
||||
avatar.inference(SimpleNamespace(is_set=lambda: avatar.res_frame_queue.qsize() == 8))
|
||||
results = list(avatar.res_frame_queue.queue)
|
||||
self.assertEqual([x[0] is None for x in results], [True, True] + [False]*6)
|
||||
quit_event = Event()
|
||||
videos, audios = [], []
|
||||
def video(image):
|
||||
videos.append(image.copy())
|
||||
if len(videos) == 8:
|
||||
quit_event.set()
|
||||
avatar.output = SimpleNamespace(start=lambda: None, stop=lambda: None,
|
||||
push_video_frame=video,
|
||||
push_audio_data=lambda pcm, event, kind: audios.append(
|
||||
(hashlib.sha256(pcm.tobytes()).hexdigest(), event, kind)))
|
||||
avatar.record_video_data = lambda image: None
|
||||
avatar.record_audio_data = lambda pcm: None
|
||||
avatar.paste_back_frame = lambda image, index: image
|
||||
avatar.process_frames(quit_event)
|
||||
self.assertEqual([int(v[-1, -1, 0]) for v in videos], [0, 0] + [100]*6)
|
||||
self.assertEqual(audios, expected)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -1,47 +0,0 @@
|
||||
"""Startup failure must propagate; preparation must never touch live I/O or gates."""
|
||||
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
root = pathlib.Path(sys.argv.pop(1)).resolve()
|
||||
sys.path.insert(0, str(root))
|
||||
from avatars.base_avatar import BaseAvatar # noqa: E402
|
||||
from avatars.hel720_head import HeadGate # noqa: E402
|
||||
from avatars.hel722_ready import prepare # noqa: E402
|
||||
from avatars.musetalk_avatar import MuseReal # noqa: E402
|
||||
|
||||
|
||||
class ReadyChecks(unittest.TestCase):
|
||||
def test_decoder_failure_is_fatal_without_constructing_session(self):
|
||||
with patch.object(MuseReal, '__init__', side_effect=AssertionError('live session')), \
|
||||
patch('resampy.resample', side_effect=ValueError('injected resampler failure')), \
|
||||
self.assertRaisesRegex(RuntimeError, 'decode_resample'):
|
||||
prepare(SimpleNamespace(), None, None)
|
||||
|
||||
def test_discard_predictions_and_no_pcm_events_or_gate_mutation(self):
|
||||
opt = SimpleNamespace(fps=25, batch_size=8, l=10, r=10)
|
||||
processor = SimpleNamespace(audio2feat=lambda x: np.zeros((1500, 5, 384), np.float16))
|
||||
avatar = [None, None, None, None, [np.zeros((1, 8, 32, 32))]]
|
||||
model = [None, None, None, None, processor]
|
||||
# Real decode/resample and feature slicing; deny all live-session entrypoints.
|
||||
with patch.object(MuseReal, '__init__', side_effect=AssertionError('live session')), \
|
||||
patch.object(HeadGate, 'classify', side_effect=AssertionError('gate')), \
|
||||
patch.object(BaseAvatar, 'put_audio_file', side_effect=AssertionError('input')), \
|
||||
patch.object(BaseAvatar, 'notify', side_effect=AssertionError('event')), \
|
||||
patch.object(MuseReal, 'inference_batch', return_value=np.zeros((8, 4, 4, 3))) as infer:
|
||||
status = prepare(opt, model, avatar)
|
||||
self.assertEqual(status['state'], 'ready')
|
||||
self.assertEqual(status['feature_shape'], [8, 50, 384])
|
||||
self.assertEqual(infer.call_count, 1)
|
||||
self.assertNotIn('prediction', status)
|
||||
with patch.object(MuseReal, 'inference_batch', side_effect=RuntimeError('GPU failed')), \
|
||||
self.assertRaisesRegex(RuntimeError, 'inference'):
|
||||
prepare(opt, model, avatar)
|
||||
|
||||
|
||||
unittest.main()
|
||||
@@ -1,127 +0,0 @@
|
||||
"""Cancellation/voice checks against local fake HTTP services, no paid APIs."""
|
||||
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import unittest
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestServer
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"sample_server", pathlib.Path(__file__).resolve().parents[1] / "runtime/server.py"
|
||||
)
|
||||
server = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(server)
|
||||
|
||||
|
||||
class GatewayChecks(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.started = asyncio.Event()
|
||||
self.release = asyncio.Event()
|
||||
self.mode = "llm"
|
||||
self.voice = "xiaoyun"
|
||||
self.queued = 0
|
||||
self.closed = []
|
||||
app = web.Application()
|
||||
|
||||
async def health(request):
|
||||
return web.json_response({"ok": True, "voices": [self.voice]})
|
||||
|
||||
async def llm(request):
|
||||
if self.mode == "llm":
|
||||
self.started.set()
|
||||
await self.release.wait()
|
||||
return web.json_response({"choices": [{"message": {"content": "你好。"}}]})
|
||||
|
||||
async def tts(request):
|
||||
self.started.set()
|
||||
await self.release.wait()
|
||||
return web.Response(body=b"\0\0" * 2400)
|
||||
|
||||
async def audio(request):
|
||||
self.queued += 1
|
||||
return web.json_response({"code": 0})
|
||||
|
||||
async def close(request):
|
||||
self.closed.append((await request.json())["sessionid"])
|
||||
return web.json_response({"closed": True})
|
||||
|
||||
app.router.add_get("/health", health)
|
||||
app.router.add_post("/llm", llm)
|
||||
app.router.add_post("/tts", tts)
|
||||
app.router.add_post("/humanaudio", audio)
|
||||
app.router.add_post("/hel714/close", close)
|
||||
self.upstream = TestServer(app)
|
||||
await self.upstream.start_server()
|
||||
base = str(self.upstream.make_url("")).rstrip("/")
|
||||
self.gateway = server.Gateway(
|
||||
{
|
||||
"driver": base,
|
||||
"llm": base + "/llm",
|
||||
"model": "fixture",
|
||||
"tts": base,
|
||||
"voice": "xiaoyun",
|
||||
}
|
||||
)
|
||||
await self.gateway.start(None)
|
||||
|
||||
async def asyncTearDown(self):
|
||||
self.release.set()
|
||||
await self.gateway.stop(None)
|
||||
await self.upstream.close()
|
||||
|
||||
async def cancel_at(self, mode):
|
||||
self.mode = mode
|
||||
session = {"sid": "old-session", "task": None}
|
||||
self.gateway.sessions["old-token"] = session
|
||||
task = session["task"] = asyncio.create_task(self.gateway.reply(session, "测试"))
|
||||
await asyncio.wait_for(self.started.wait(), 2)
|
||||
await self.gateway.retire("old-token")
|
||||
self.assertTrue(task.cancelled())
|
||||
self.release.set()
|
||||
await asyncio.sleep(0.05)
|
||||
self.assertEqual(self.queued, 0)
|
||||
self.assertEqual(self.closed, ["old-session"])
|
||||
self.assertNotIn("old-token", self.gateway.sessions)
|
||||
# Idempotence: a late duplicate cancel cannot close a new session.
|
||||
self.gateway.sessions["new-token"] = {"sid": "new-session", "task": None}
|
||||
await self.gateway.retire("old-token")
|
||||
self.assertIn("new-token", self.gateway.sessions)
|
||||
|
||||
async def test_cancel_during_llm(self):
|
||||
await self.cancel_at("llm")
|
||||
|
||||
async def test_cancel_during_tts(self):
|
||||
await self.cancel_at("tts")
|
||||
|
||||
async def test_missing_voice_is_explicit(self):
|
||||
self.voice = "default"
|
||||
with self.assertRaisesRegex(RuntimeError, "未回退"):
|
||||
await self.gateway.reply({"sid": "test"}, "测试")
|
||||
self.assertEqual(self.queued, 0)
|
||||
|
||||
async def test_cancel_while_waiting_for_media_ready(self):
|
||||
self.mode = "tts"
|
||||
session = {"sid": "old-session", "task": None, "ready": asyncio.Event()}
|
||||
self.gateway.sessions["old-token"] = session
|
||||
task = session["task"] = asyncio.create_task(self.gateway.reply(session, "测试"))
|
||||
await asyncio.wait_for(self.started.wait(), 2)
|
||||
self.release.set()
|
||||
await asyncio.sleep(0.05)
|
||||
self.assertEqual(self.queued, 0)
|
||||
await self.gateway.retire("old-token")
|
||||
session["ready"].set()
|
||||
await asyncio.sleep(0.05)
|
||||
self.assertTrue(task.cancelled())
|
||||
self.assertEqual(self.queued, 0)
|
||||
|
||||
async def test_model_unreachable(self):
|
||||
self.gateway.config["llm"] = "http://127.0.0.1:1/unavailable"
|
||||
with self.assertRaises(server.aiohttp.ClientError):
|
||||
await self.gateway.reply({"sid": "unreachable"}, "测试")
|
||||
self.assertEqual(self.queued, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -1,89 +0,0 @@
|
||||
"""Synthetic WAV through Chromium's microphone device, not a human VAD pass."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence"
|
||||
|
||||
|
||||
async def main():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(
|
||||
args=[
|
||||
"--no-sandbox",
|
||||
"--autoplay-policy=no-user-gesture-required",
|
||||
"--use-fake-device-for-media-stream",
|
||||
"--use-fake-ui-for-media-stream",
|
||||
f"--use-file-for-fake-audio-capture={OUT / 'synthetic-microphone.wav'}%noloop",
|
||||
]
|
||||
)
|
||||
context = await browser.new_context(ignore_https_errors=True, permissions=["microphone"])
|
||||
page = await context.new_page()
|
||||
errors = []
|
||||
page.on("pageerror", lambda error: errors.append(str(error)))
|
||||
await page.goto("https://192.168.200.12:8014")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('就绪')"
|
||||
)
|
||||
await page.click("#enter")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('正在听')", timeout=40000
|
||||
)
|
||||
await page.click("#record")
|
||||
await page.click("#mic")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#mic').getAttribute('aria-pressed')==='true'"
|
||||
)
|
||||
await page.fill("#text", "请用三句话描述你眼前卧室的温暖氛围,大约六十个字。")
|
||||
await page.click("button[type=submit]")
|
||||
await page.wait_for_function(
|
||||
"window.sampleEvents.some(e=>e.event==='cancel'&&e.detail.reason==='microphone-onset')",
|
||||
timeout=25000,
|
||||
)
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#transcript').textContent.includes('识别:')", timeout=15000
|
||||
)
|
||||
await page.wait_for_function(
|
||||
"window.sampleEvents.filter(e=>e.event==='input-finished').length>=2", timeout=15000
|
||||
)
|
||||
await page.wait_for_timeout(18000)
|
||||
await page.click("#record")
|
||||
await page.wait_for_selector("#download:not([hidden])")
|
||||
async with page.expect_download() as pending:
|
||||
await page.click("#download")
|
||||
await (await pending.value).save_as(OUT / "synthetic-microphone-av.webm")
|
||||
events = await page.evaluate("window.sampleEvents")
|
||||
onset = next(
|
||||
e["at"]
|
||||
for e in events
|
||||
if e["event"] == "cancel" and e["detail"]["reason"] == "microphone-onset"
|
||||
)
|
||||
audible_before = [e for e in events if e["event"] == "first-audible" and e["at"] < onset]
|
||||
audible_after = [e for e in events if e["event"] == "first-audible" and e["at"] > onset]
|
||||
result = dict(
|
||||
fixture="CosyVoice synthesized WAV through fake Chromium microphone; no human recording",
|
||||
secure_context=await page.evaluate("isSecureContext"),
|
||||
transcript=await page.locator("#transcript").inner_text(),
|
||||
speech_was_audible_before_onset=bool(audible_before),
|
||||
new_reply_after_asr=bool(audible_after),
|
||||
events=events,
|
||||
pageerrors=errors,
|
||||
)
|
||||
(OUT / "synthetic-microphone.json").write_text(
|
||||
json.dumps(result, ensure_ascii=False, indent=2)
|
||||
)
|
||||
await page.click("#mic")
|
||||
await page.click("#back")
|
||||
await page.wait_for_timeout(4000)
|
||||
await browser.close()
|
||||
print(
|
||||
json.dumps({k: v for k, v in result.items() if k != "events"}, ensure_ascii=False),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,65 +0,0 @@
|
||||
"""Cancel during ICE/offer, then verify a late old error cannot stop a new turn."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
OUT = pathlib.Path(sys.argv[1]) if len(sys.argv) > 1 else pathlib.Path(__file__).resolve().parents[1] / "evidence"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
async def main():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(
|
||||
args=["--no-sandbox", "--autoplay-policy=no-user-gesture-required"]
|
||||
)
|
||||
context = await browser.new_context(ignore_https_errors=True)
|
||||
page = await context.new_page()
|
||||
errors = []
|
||||
page.on("pageerror", lambda e: errors.append(str(e)))
|
||||
try:
|
||||
await page.goto("https://192.168.200.12:8014")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('就绪')"
|
||||
)
|
||||
await page.click("#enter")
|
||||
await page.wait_for_function(
|
||||
"document.querySelector('#status').textContent.includes('正在听')", timeout=40000
|
||||
)
|
||||
await page.fill("#text", "这一轮马上取消。")
|
||||
await page.click("button[type=submit]")
|
||||
await page.wait_for_timeout(100)
|
||||
await page.click("#cancel")
|
||||
await page.fill("#text", "新一轮只回复:你好。")
|
||||
await page.click("button[type=submit]")
|
||||
await page.wait_for_function(
|
||||
"window.sampleEvents.some(e=>e.event==='first-audible')", timeout=45000
|
||||
)
|
||||
await page.wait_for_timeout(10000)
|
||||
events = await page.evaluate("window.sampleEvents")
|
||||
failures = [
|
||||
e for e in events if e["event"] == "status" and "媒体协商超时" in str(e["detail"])
|
||||
]
|
||||
result = {"pageerrors": errors, "late_error_failures": failures, "events": events}
|
||||
(OUT / "race-check.json").write_text(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
assert not failures
|
||||
await page.click("#back")
|
||||
await page.wait_for_timeout(4000)
|
||||
finally:
|
||||
(OUT / "race-page-state.json").write_text(json.dumps({
|
||||
"url": page.url,
|
||||
"status": await page.locator('#status').inner_text(),
|
||||
"events": await page.evaluate('window.sampleEvents'),
|
||||
"pageerrors": errors,
|
||||
"media": await page.locator('video').evaluate_all(
|
||||
'(vs)=>vs.map(v=>({id:v.id, ready:v.readyState, paused:v.paused, time:v.currentTime}))'),
|
||||
}, ensure_ascii=False, indent=2))
|
||||
await page.screenshot(path=str(OUT / 'race-final.png'))
|
||||
await browser.close()
|
||||
print("ICE cancellation race passed", flush=True)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -1,35 +0,0 @@
|
||||
"""Pending audio before RTP timestamps: only type=1 synthetic idle is expendable."""
|
||||
|
||||
import queue
|
||||
|
||||
|
||||
class PendingAudio(queue.Queue):
|
||||
"""Keep at most three un-timestamped synthetic blocks; preserve speech/events.
|
||||
|
||||
One render producer, one RTP consumer. Real speech (including zero PCM and
|
||||
custom type>1 audio) uses bounded Queue backpressure, never a drop policy.
|
||||
"""
|
||||
|
||||
silence_limit = 3
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(maxsize=100)
|
||||
self.dropped_silence = 0
|
||||
self.high_water = 0
|
||||
|
||||
def put(self, item, block=True, timeout=None):
|
||||
with self.not_full:
|
||||
# Trim before assigning pts, never inside the RTP consumer. Event
|
||||
# markers remain observable even if a producer puts one on silence.
|
||||
idle = [i for i, (_, event, kind) in enumerate(self.queue) if kind == 1 and not event]
|
||||
incoming_idle = item[2] == 1 and not item[1]
|
||||
excess = len(idle) + int(incoming_idle) - self.silence_limit
|
||||
for i in reversed(idle[:max(0, excess)]):
|
||||
del self.queue[i]
|
||||
self.unfinished_tasks -= 1
|
||||
self.dropped_silence += 1
|
||||
if excess > 0:
|
||||
self.not_full.notify_all()
|
||||
super().put(item, block=block, timeout=timeout)
|
||||
with self.mutex:
|
||||
self.high_water = max(self.high_water, len(self.queue))
|
||||
@@ -1,42 +0,0 @@
|
||||
"""Candidate head-only render policy; audio bytes, types and events stay intact."""
|
||||
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
class HeadGate:
|
||||
def __init__(self, threshold=None):
|
||||
self.threshold = float(os.environ.get('HEL720_HEAD_RMS', '0.001')
|
||||
if threshold is None else threshold)
|
||||
if not math.isfinite(self.threshold) or self.threshold < 0:
|
||||
raise ValueError('HEL720_HEAD_RMS must be finite and >= 0 (0 disables)')
|
||||
self._lock = threading.Lock()
|
||||
self.leading = True
|
||||
|
||||
def reset(self):
|
||||
with self._lock:
|
||||
self.leading = True
|
||||
|
||||
def classify(self, frame):
|
||||
# Called on original 16k PCM at ASR ingress, BEFORE feature batching.
|
||||
# Synthetic idle never rearms a running utterance (stream starvation).
|
||||
with self._lock:
|
||||
if frame.type != 0:
|
||||
return False
|
||||
status = (frame.userdata or {}).get('status')
|
||||
if status == 'start':
|
||||
self.leading = True
|
||||
rms = float(np.sqrt(np.mean(np.square(frame.data, dtype=np.float64))))
|
||||
closed = self.threshold > 0 and self.leading and rms <= self.threshold
|
||||
if not closed:
|
||||
self.leading = False
|
||||
if status == 'end':
|
||||
self.leading = True
|
||||
return closed
|
||||
|
||||
|
||||
def render_speech(frames):
|
||||
return any(f.type == 0 and not getattr(f, 'hel720_head_closed', False) for f in frames)
|
||||