Compare commits

..
Author SHA1 Message Date
mobaiandmultica-agent 6a5e155258 feat(hel715): LiveTalking+MuseTalk verification kit (report, material spec, e2e scripts)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-20 23:24:31 +08:00
29 changed files with 1038 additions and 2626 deletions
+72
View File
@@ -0,0 +1,72 @@
# 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 节规范产出,总工验收导入。
+42
View File
@@ -0,0 +1,42 @@
# 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 复用。
+73
View File
@@ -0,0 +1,73 @@
# 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 重生成任务并存时需调度(先交谈后生成的队列约定)。
@@ -0,0 +1,82 @@
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',
@@ -0,0 +1,69 @@
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)
@@ -0,0 +1,13 @@
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',
+375
View File
@@ -0,0 +1,375 @@
#!/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())
@@ -0,0 +1,129 @@
<!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>
+124
View File
@@ -0,0 +1,124 @@
#!/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())
@@ -0,0 +1,59 @@
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())
-7
View File
@@ -1,7 +0,0 @@
node_modules/
dist/
public/assets/*
!public/assets/manifest.json
evidence/*
!evidence/.gitkeep
__pycache__/
-55
View File
@@ -1,55 +0,0 @@
HEL-711 最小动态校对小样,基于 main `1e9b08a`。仅在 `samples/bedroom` 内工作;不连接人格、记忆、天气或语音。采用 HEL-708 的环境/人物/交谈分层边界,以及 CG-001~026 的当前需求。旧演示不变。
## 本地复核
1. 将本卡附件 `HEL-711-review-bundle.zip` 中的 `public/assets` 解压到此目录对应位置。
2. `npm ci --ignore-scripts --no-audit --no-fund`,沿用旧前端分支的 package.json/package-lock.json/tsconfig.json,无新依赖。
3. `npm run build`(包含严格 TypeScript 检查)。
4. `npm run dev -- --port 5173`,本机浏览器打开终端输出的地址。
5. `python3 tools/browser_check.py` 使用已安装的 Playwright/Chromium,自动启停本机测试服务并保存证据。此运行机需要给该命令设置 `LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu`,复用了已有浏览器库,未安装系统依赖。
素材不进 Git,缺失时页面明确提示;manifest 在 Git 中保存来源、原图 SHA256、坐标、编码和问题。附件内含完整 assets、已构建 dist、浏览器连续录屏、原始试片、透明试片、分层校对图及生成工作流/日志。
## 代码与边界
- `src/main.ts`:一个持久 video 元素驱动透明 canvas;环境按钮只改环境亮度,不重建/seek 视频。人物、前景遮挡、接触阴影独立开关;静态近景不替代真实交谈。
- `src/tokens.css`:原样复用旧前端唯一 token 表。`style.css` 为独立工程校对台,无第二套同类组件。
- `tools/extract_layers.py`:读取现有 SAM vit-b 模型的原始 modeling API,避免可选 predictor 的 OpenCV 依赖;不伪造 cv2,不下载。原图 RGB 保留,只生成 alpha;封闭孔洞填充、0.65px 羽化。
- `tools/contact_layers.py`:从原入景图提取毯子前景,另建可关闭的暂定接触阴影;未宣称物理阴影校准完成。
- `tools/generate_once.py`:原 ComfyUI venv + 原生 Wan 节点,单片段、离线、自定义节点禁用。临时服务器仅监听回环 18189,finally 终止自己启动的精确 PID。不修改现有服务、系统 Python、驱动或模型路径配置。
- `tools/matte_video.py`:49 帧逐帧 SAM 分割,原有 PyAV 编码 VP9 alpha。原始视频未抠像的背景不用于浏览器人物合成。
- `tools/browser_check.py`:真实 Chromium 检查、三种视口截图和可下载连续录屏。页面隐藏的事件处理做了合成 visibilitychange 检查;真实系统切后台/锁屏仍待体验环境手测。
## 素材处理命令
处理目录:`.12:/media/lucian/Downloads/ComfyUI/output/hel711-task`,输入复制到其 `assets`,脚本放此目录;没有改变现有项目输入。原图由 Multica 鉴权 attachment download 获取。运行时使用原 `/media/lucian/Downloads/ComfyUI/venv/bin/python`。
```bash
python extract_layers.py assets \
--sam-source /media/lucian/Downloads/ComfyUI/custom_nodes/was-node-suite-comfyui/repos/SAM/segment_anything \
--checkpoint /media/lucian/Downloads/ComfyUI/models/sams/sam_vit_b_01ec64.pth
python generate_once.py
python matte_video.py
```
回传处理后的素材到本地 `public/assets`,运行 `python3 tools/contact_layers.py`。手工蒙版和坐标均保留在脚本中。`workflow.json` 是本次实际运行的请求,最终脚本仅补了目录创建/日志关闭等清理逻辑;日志和 history 可交叉核对。执行新试片前必须重新检查显存和端口;禁止停止已有服务腾资源。
## 当前实测与未通过项
当前结果见 `REPORT.md`,属于可审核候选,不代表 D1–D6 全部通过。图层是真实独立合成;没有用重生成整幅图代替分层。近景仍用已确认 v2 静态方向图;没有真人语音或口型。
## HEL-712 返工复现
本轮只补原动作的真实回程,并处理书本/手部蒙版;环境、机位、比例、UI token 与静态近景不变。完整返工包中的 `public/assets` 替换旧素材后执行同一构建/浏览器检查。
已有 ComfyUI 环境中,保留原片在 `output/hel711-task/reading_00001_.webm`、原透明片在同目录 `reading-alpha.webm`:
```bash
python generate_return.py
python stabilize_loop.py
python measure_loop.py
```
脚本放在 `output/hel712-task` 并附同目录 `extract_layers.py`。生成器只用已有原生 `WanFirstLastFrameToVideo` 节点与原有权重,以原片 f48、f0 为两端,seed 712,只生成一条49帧回程。服务器仍仅临时监听回环18189;主程序收齐结果后停止精确子进程。`stabilize_loop.py` 读取原49帧 alpha,新增49帧按书本/衣袖补充分割提示;只在原512坐标 y175–330 对动作对齐的5帧有符号距离去掉最大/最小值后取均值稳定,RGB不做时域融合,原发丝区域不重新分割。原始两段按顺序拼成98帧,接点48→49、97→0,无倒放/淡化/冻结/短窗口裁切。
`measure_loop.py` 输出固定坐标口径的逐对差异、蒙版统计、动作补偿残差、接头与手部证据图;数值不替代目验。`browser_check.py` 先在真实Chromium完整播放至少3周期,再做原交互与三视口复测。真实后台/锁屏及Safari/iOS仍未测。
-52
View File
@@ -1,52 +0,0 @@
HEL-712:原阅读动作循环与书本/手部蒙版返工候选,交总工复审,不部署。
## 实现
沿用原人物、米色开衫、深灰长裤、卧室、机位与552px人物落点。现有 Wan2.2 原生首尾帧条件节点,使用原片 f48→f0,seed 712,实际生成一条49帧抬头回程。原49帧向前播放,随后49帧真实回程,98帧/16fps/6.125秒,内部接点48→49,跨周期97→0。没有倒放、冻结、静态摆动、遮脸淡化或短窗口裁切。
原49帧 alpha 不重新分割;新增49帧补书本/衣袖正点,保留连通人物,去掉分离的沙发碎点。两段仅在原512px坐标 y175:330(输出552px坐标189:356)稳定蒙版:TV-L1对齐前后各2帧,有符号距离去掉最高/最低值,再取均值,限制到当前轮廓6px不确定区域,首尾8行回接原蒙版。只处理alpha,RGB不做时间平均;原发丝区域保持原alpha。原始源片与透明片逐帧映射见manifest/stabilization.json。
第一次新增回程直接套原分割提示时,会漏掉书本/衣袖;该版已拒绝,`before-crops.png` 保留实证。补充分割提示后才进入最终蒙版稳定。共生成一条视频,没有批量换装或动作试片。第一次稳定使用中值共识,接头alpha变化仍偏集中;最终使用去极值均值,缓和了两个分段蒙版的多数票切换。
## 同口径差异与边缘统计
本报告独立固定口径:RGB头部框为512px源坐标 x230:340、y50:180;蒙版缩到512px、alpha>127,边界用二值侵蚀差,书本/手部带为全部x、y175:330。与HEL-710采用的框/缩放细节不同,所以这里原接头22.30不直接与审核卡29.5混算;下列前后全部由同一脚本重算。完整逐对数据见 `evidence/metrics.json`,覆盖全部98个相邻对(包括末→首)。
| 头部RGB绝对差 /255 | 最小 | 中位 | P95 | 最大 |
|---|---:|---:|---:|---:|
| 原49帧普通相邻 | 0.36 | 1.73 | 4.97 | 5.75 |
| 新98帧普通相邻(排除两接头) | 0.24 | 1.65 | 5.47 | 8.30 |
原f48→f0:22.30;新内部f48→49:3.66;新跨周期f97→0:5.22。两个接头落在普通相邻变化范围内。接头前后整帧、头部放大与98帧序列均附;连续录屏为实际浏览器播放,未用离线合成冒充。
| 蒙版指标 | 稳定前 | 最终稳定后 |
|---|---:|---:|
| 原49帧带内边界像素范围 | 510–794 | 509–604 |
| 原49帧最差相邻边界变化 | 255 | 75 |
| 原49帧相邻alpha开关最大像素 | 771 | 300 |
| 全98帧边界像素范围 | 504–794 | 503–604 |
| 全98对最差边界变化(含循环) | 261 | 75 |
| 全98对alpha开关P95 / 最大像素 | 505.05 / 988 | 142.55 / 300 |
| 内部 / 跨周期接头alpha开关像素 | 988 / 528 | 195 / 193 |
| 动作补偿后alpha开关P95 / 最大 | 503.25 / 988 | 152.75 / 300 |
动作补偿使用同一源RGB光流对齐前后蒙版;可见减少的是分割开关,不靠抹掉真实运动。人物内部透明片与源RGB编码误差逐帧中位1.89、最大2.10/255;无RGB时间混合。带外alpha逐数组一致为true。重点帧可见书本/指尖与袖口保持,未见新增吞手或RGB拖影;仍需总工以连续视频独立确认。没有把数值降低当作人体解剖或身份认证。
## 验证
- 来源包SHA256:60/60核对一致。
- `npm ci --ignore-scripts --no-audit --no-fund`:沿用锁文件,无新依赖。
- `npm run build`:严格TypeScript检查和Vite构建通过;原JS/CSS逻辑保持,返工通过素材和工具落地。
- `ruff check src tests samples/bedroom/tools`:通过。
- `PYTHONPATH=src python3 -m pytest -q`:78通过。
- `LD_LIBRARY_PATH=/home/xiaomo/pwlibs/root/usr/lib/x86_64-linux-gnu python3 tools/browser_check.py`:真实Chromium通过。最终视频先完整播放3周期,记录循环时间约6.28、12.42、18.56秒;此段全部图层显示,之后再执行交互测试。
- VP9 alpha背景0/人物255;环境切换currentTime 0.905816→0.905816,source不变;图层开关、静态近景进退且播放继续、手动暂停、合成visibility暂停/恢复、减少动效切静态、缺片回退通过;1600×900、1280×800、390×844无横溢,人脸在画面内;pageerror=0。
- 真实后台/锁屏、Safari/iOS未测;近景仅静态,未增加口型、语音或后台生活功能。手机构图、沙发几何、重打光与近景润色保持原记录。
## 文件与运行边界
修改 `tools/extract_layers.py`(可选补充提示)、新增 `tools/generate_return.py`、`stabilize_loop.py`、`measure_loop.py`,扩展 `tools/browser_check.py` 的连续三周期验证,更新manifest/README/本报告。没有改CSS、主题、核心服务或部署配置。
分支继续 `hel-711-layered-bedroom`,基于原444ee56;最终提交与PR head核对写入附件 `DELIVERY.json` 及任务完成评论。素材不进Git。完整包包含源码、构建产物、manifest、SHA256SUMS、原始前程/回程、整周期源片、透明片、逐帧前后alpha、生成请求/节点/history/server日志、浏览器连续录屏、三视口及接头/手部证据、复现说明。
严格校验了.12已确认SSH指纹。临时ComfyUI仅回环18189、精确PID600329,生成请求成功后已停止。CPU蒙版任务均前台收齐,没有遗留生成任务、没有新增依赖/模型/付费接口;ASR/TTS及18080原演示保持运行。未推main、未合并、未部署。
-38
View File
@@ -1,38 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>卧室分层校对 · HEL-711</title></head>
<body>
<main>
<header><h1>卧室分层校对</h1><p>工程小样 · 手动光照演示 · 近景仅静态参考,未接语音或口型</p></header>
<div id="stage" role="img" aria-label="固定机位卧室人物合成">
<div id="frame">
<img id="environment" src="./assets/environment.png" alt="无人高层卧室">
<img id="shadow" src="./assets/contact-shadow.png" alt="" class="layer">
<img id="person" src="./assets/person.png" alt="阅读人物透明层" class="layer">
<canvas id="motion" width="552" height="552" hidden></canvas>
<img id="occlusion" src="./assets/occlusion.png" alt="" class="layer">
<img id="mask" src="./assets/person-mask.png" alt="人物蒙版" class="layer" hidden>
<img id="talk" src="./assets/talk-reference.png" alt="交谈静态近景参考" class="layer" hidden>
</div>
</div>
<video id="source" muted playsinline loop preload="metadata" hidden></video>
<section aria-label="校对控制">
<fieldset><legend>图层开关</legend>
<label><input id="show-person" type="checkbox" checked>人物</label>
<label><input id="show-shadow" type="checkbox" checked>接触阴影</label>
<label><input id="show-occlusion" type="checkbox" checked>前景毯子</label>
<label><input id="show-mask" type="checkbox">仅看人物蒙版</label>
</fieldset>
<div class="controls">
<button id="lighting" type="button" aria-pressed="false">光照演示:原始</button>
<button id="play" type="button" disabled>读取动作素材</button>
<button id="closeup" type="button" aria-pressed="false">进入静态近景</button>
</div>
<p id="status" role="status">读取素材清单…</p>
<output id="time">动作位置:未载入</output>
<p id="fallback" role="alert" hidden></p>
<p>人物、房间和近景来自已确认的 v2 参考。图层独立不等于几何、发丝与循环已经通过验收。</p>
</section>
</main>
<script type="module" src="./src/main.ts"></script>
</body></html>
-1166
View File
File diff suppressed because it is too large Load Diff
-19
View File
@@ -1,19 +0,0 @@
{
"name": "cybergril-rain-room",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1",
"typecheck": "tsc --noEmit",
"build": "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"
}
}
-162
View File
@@ -1,162 +0,0 @@
{
"schema": "hel712-review-1",
"status": "review_candidate",
"reference_sha256": {
"reference.png": "226d7922e042e22e4b8a8241a7cf6f7aea50c301029978e4ca26cad9b3d56359",
"environment.png": "b5d4771eb010dc1d0a41d1b698e45edaa45d2f90bb441378bc32cf5c812e76a2",
"talk-reference.png": "0ae9b1a1cb9c590ab89a81ce4efd25de843a600ff227c184663db23e9e9c16b3"
},
"camera": {
"canvas": [
1672,
941
],
"generation_crop": [
1120,
200,
552,
552
],
"person_anchor": [
1390,
530
],
"coordinate_units": "source pixels, top left origin",
"transform": "none; crop reinserted into original position",
"clothing": "v2 cream cardigan, charcoal trousers"
},
"layers": [
{
"file": "environment.png",
"source": "approved 02-v2 original",
"alpha": false
},
{
"file": "contact-shadow.png",
"source": "engineered ellipse 65/255, 12px blur, not physically calibrated",
"alpha": true
},
{
"file": "person.png",
"source": "original 03-v2 RGB + existing SAM vit-b alpha; enclosed mask holes filled",
"alpha": true
},
{
"file": "occlusion.png",
"source": "03-v2 blanket pixels, hand-authored polygon matte",
"alpha": true
}
],
"motion": {
"status": "真实回程与书本手部蒙版返工候选,待复审",
"file": "reading-alpha.webm",
"alpha": true,
"maskFile": null,
"original": "loop-source.webm",
"generator": "installed ComfyUI native Wan2.2 high/low 14B fp8 + installed LightX2V 4-step LoRAs",
"seed": 711,
"dimensions": [
552,
552
],
"generation_dimensions": [
512,
512
],
"frames": 98,
"fps": 16,
"duration_seconds": 6.125,
"codec": "VP9 yuva420p / WebM",
"matting": "original 49 alpha retained outside hand/book band; added return frames use book/sleeve foreground points + connected subject; y175:330 (512 source) uses TV-L1 aligned 5-frame trimmed signed-distance mean within 6px uncertainty band",
"start_pose": "seated holding open book, head slightly tilted toward camera",
"end_pose": "generated return to the original relaxed camera-facing pose",
"loop": "forward 0–48 + real generated return 49–97; joins 48→49 and 97→0, no reverse/fade/freeze",
"cut_point": "no subwindow trimming",
"return_seed": 712,
"source_map": [
{
"frames": [
0,
48
],
"file": "reading_00001_.webm",
"source_frames": [
0,
48
]
},
{
"frames": [
49,
97
],
"file": "return_00001_.webm",
"source_frames": [
0,
48
]
}
]
},
"closeup": {
"file": "talk-reference.png",
"type": "static_reference_only",
"identity_verified": false,
"lipsync": false,
"source": "approved v2 static direction reference"
},
"known_issues": [
"Original empty/occupied sofa and pillow geometry differs; residual contact geometry needs art review.",
"Book and fingers are small; hand anatomy/identity not certified.",
"Manual environment dimming changes background only; subject relighting not implemented.",
"Static near-shot is a generated reference; cross-shot face continuity not certified.",
"No real weather, speech, lipsync or life-state integration.",
"Loop joins and stabilized hand/book edges are a HEL-712 candidate pending independent re-review."
],
"files": {
"talk-reference.png": {
"bytes": 2246098,
"sha256": "0ae9b1a1cb9c590ab89a81ce4efd25de843a600ff227c184663db23e9e9c16b3"
},
"reading-alpha.webm": {
"bytes": 1971817,
"sha256": "9b9b95fff6c047c68ea66d14eba1ca896a80107b7c5b531c326bfac8bdc90b76"
},
"person.png": {
"bytes": 2522355,
"sha256": "a904f4081069ba97019d3c679d8dd59102118560471f8d6337f7b29d60380f24"
},
"composite.png": {
"bytes": 2576324,
"sha256": "4354716558858d0e9ac9a4c4a025d77f4042a0e106f10fc37e500c7157e77456"
},
"person-mask.png": {
"bytes": 7264,
"sha256": "7569160b3c87ebf1d5bb66792ed6d2db6b41fde006fad0473e7db5337d18b0f7"
},
"environment.png": {
"bytes": 2442707,
"sha256": "b5d4771eb010dc1d0a41d1b698e45edaa45d2f90bb441378bc32cf5c812e76a2"
},
"occlusion-mask.png": {
"bytes": 4838,
"sha256": "dc22d1823a02df4fa5f3bf484f157c49b270f100185c0a35b3c31f28880dd3f0"
},
"generation-input.png": {
"bytes": 508812,
"sha256": "f3922903fb28c5940a2e272b70be6e33dc094039b4e275724cf3ff1aa4af1584"
},
"occlusion.png": {
"bytes": 2522991,
"sha256": "5f0f4aa7ae90ad863f694365eaa93d7d7558841ecca08c95d415731450226c4f"
},
"reference.png": {
"bytes": 2384917,
"sha256": "226d7922e042e22e4b8a8241a7cf6f7aea50c301029978e4ca26cad9b3d56359"
},
"contact-shadow.png": {
"bytes": 16144,
"sha256": "948f88c1298638158f9a21ffe107bf403106dcf6e58c72a3d6e738fe0c7cc003"
}
}
}
-141
View File
@@ -1,141 +0,0 @@
import './style.css';
type Manifest = {
motion: { status: string; file: string | null; alpha: boolean; maskFile: string | null };
};
const get = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
const video = get<HTMLVideoElement>('source');
const canvas = get<HTMLCanvasElement>('motion');
const context = canvas.getContext('2d')!;
const play = get<HTMLButtonElement>('play');
const person = get<HTMLImageElement>('person');
const status = get('status');
const reduced = matchMedia('(prefers-reduced-motion: reduce)');
const missingImages = new Set<string>();
let ready = false;
let wantsPlay = false;
let near = false;
let failed = false;
let frameHandle = 0;
function fallback(message: string) {
const node = get('fallback');
node.hidden = false;
node.textContent = message;
}
for (const image of document.querySelectorAll<HTMLImageElement>('#frame img')) {
image.addEventListener('error', () => {
missingImages.add(image.id);
image.hidden = true;
fallback(`素材缺失:${image.id}。请解压任务素材包到 public/assets;当前内容不能作为验收结果。`);
});
}
function visibility() {
const visible = get<HTMLInputElement>('show-person').checked;
const maskOnly = get<HTMLInputElement>('show-mask').checked;
const activeMotion = ready && !failed && !reduced.matches;
person.hidden = !visible || maskOnly || near || activeMotion;
canvas.hidden = !visible || maskOnly || near || !activeMotion;
get('environment').hidden = maskOnly;
get('mask').hidden = !maskOnly || near;
get('shadow').hidden = !visible || maskOnly || near || !get<HTMLInputElement>('show-shadow').checked;
get('occlusion').hidden = !visible || maskOnly || near || !get<HTMLInputElement>('show-occlusion').checked;
get('talk').hidden = !near;
for (const id of missingImages) get(id).hidden = true;
}
function paint() {
if (video.readyState >= 2) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.globalCompositeOperation = 'source-over';
context.drawImage(video, 0, 0, canvas.width, canvas.height);
}
get('time').textContent = ready
? `动作位置:${video.currentTime.toFixed(2)} / ${Number.isFinite(video.duration) ? video.duration.toFixed(2) : '…'} 秒`
: '动作位置:未载入';
}
function draw() {
paint();
if (!video.paused && !document.hidden) frameHandle = requestAnimationFrame(draw);
}
async function syncPlayback() {
cancelAnimationFrame(frameHandle);
const run = wantsPlay && ready && !failed && !document.hidden && !reduced.matches;
if (run) {
try {
await video.play();
draw();
} catch {
wantsPlay = false;
video.pause();
fallback('浏览器未允许播放;请点击播放重试。');
}
} else { video.pause(); paint(); }
play.textContent = ready ? (video.paused ? '播放真实试片' : '暂停真实试片') : '真实动作尚不可用';
visibility();
}
function layout() {
const stage = get('frame');
const scale = Math.min(stage.clientWidth / 1672, stage.clientHeight / 941);
const left = (stage.clientWidth - 1672 * scale) / 2;
const top = (stage.clientHeight - 941 * scale) / 2;
Object.assign(canvas.style, { left: `${left + 1120 * scale}px`, top: `${top + 200 * scale}px`,
width: `${552 * scale}px`, height: `${552 * scale}px` });
}
new ResizeObserver(layout).observe(get('frame'));
for (const input of document.querySelectorAll('input')) input.addEventListener('change', visibility);
get('lighting').addEventListener('click', () => {
const button = get<HTMLButtonElement>('lighting');
const dim = button.getAttribute('aria-pressed') !== 'true';
button.setAttribute('aria-pressed', String(dim));
button.textContent = `光照演示:${dim ? '环境减光' : '原始'}`;
get('environment').style.setProperty('--demo-environment-brightness', dim ? '0.65' : '1');
// No source assignment, load(), currentTime mutation or player recreation here.
});
get('closeup').addEventListener('click', () => {
near = !near;
const button = get<HTMLButtonElement>('closeup');
button.setAttribute('aria-pressed', String(near));
button.textContent = near ? '退出静态近景' : '进入静态近景';
visibility();
});
play.addEventListener('click', () => { wantsPlay = !wantsPlay; void syncPlayback(); });
document.addEventListener('visibilitychange', () => { void syncPlayback(); });
reduced.addEventListener('change', () => {
if (reduced.matches) wantsPlay = false;
void syncPlayback();
});
video.addEventListener('error', () => {
failed = true; ready = false; wantsPlay = false; play.disabled = true;
fallback('动作素材缺失或解码失败,回退静态人物;未通过动态验证。');
void syncPlayback();
});
async function init() {
try {
const response = await fetch('./assets/manifest.json');
if (!response.ok) throw new Error('manifest');
const manifest: Manifest = await response.json();
const motion = manifest.motion;
if (!motion.file || !motion.alpha) {
status.textContent = '静态分层可校对;无合格的透明动作素材,动态验收未通过。';
play.disabled = true; play.textContent = '真实动作尚不可用'; return;
}
video.src = `./assets/${motion.file}`;
video.addEventListener('loadeddata', () => {
ready = true; play.disabled = false;
status.textContent = `真实生成试片 · ${motion.status} · 循环切点与身份一致性以检查报告为准`;
paint(); void syncPlayback();
}, { once: true });
} catch {
fallback('素材清单不可用;保留静态分层校对。');
play.textContent = '真实动作尚不可用';
}
}
visibility(); layout(); void init();
-22
View File
@@ -1,22 +0,0 @@
@import './tokens.css';
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { margin: 0; background: var(--scene-night-deep); color: var(--ink-primary); font: var(--fs-body) var(--font-sans); }
main { max-width: 1600px; margin: auto; }
header, section { padding: var(--space-4) var(--space-6); }
h1 { font-size: var(--fs-title); margin: 0; }
p { color: var(--ink-secondary); line-height: 1.5; }
#stage { position: relative; overflow: hidden; height: min(60vh, 640px); background: var(--glass-bg-strong); }
#frame { position: absolute; width: 100%; height: 100%; }
#environment, .layer { position: absolute; width: 100%; height: 100%; object-fit: contain; }
#environment { filter: brightness(var(--demo-environment-brightness, 1)); }
#motion { position: absolute; }
fieldset { border: 1px solid var(--glass-border); border-radius: var(--r-control); padding: var(--space-3); display: flex; flex-wrap: wrap; gap: var(--space-4); }
label, button { cursor: pointer; }
.controls { display: flex; flex-wrap: wrap; gap: var(--space-2); margin-top: var(--space-3); }
button { color: var(--ink-primary); background: var(--glass-bg-strong); border: 1px solid var(--glass-highlight); border-radius: var(--r-control); padding: var(--space-3) var(--space-4); font: inherit; }
button[aria-pressed=true] { border-color: var(--accent); }
button:disabled { color: var(--ink-disabled); cursor: default; }
button:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
output { font-variant-numeric: tabular-nums; color: var(--accent); }
@media (max-width: 600px) { header, section { padding: var(--space-3); } #stage { height: 38vh; } }
-73
View File
@@ -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;
}
-158
View File
@@ -1,158 +0,0 @@
"""Foreground Chromium interaction checks, screenshots and downloadable recording."""
import functools
import http.server
import json
import threading
from pathlib import Path
from playwright.sync_api import sync_playwright
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / 'evidence'
class Quiet(http.server.SimpleHTTPRequestHandler):
def log_message(self, *_args):
pass
def main():
EVIDENCE.mkdir(exist_ok=True)
handler = functools.partial(Quiet, directory=str(ROOT / 'dist'))
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), handler)
thread = threading.Thread(target=server.serve_forever)
thread.start()
results = {}
try:
with sync_playwright() as p:
browser = p.chromium.launch()
url = f'http://127.0.0.1:{server.server_port}'
context = browser.new_context(viewport={'width': 1280, 'height': 800},
record_video_dir=str(EVIDENCE),
record_video_size={'width': 1280, 'height': 800})
page = context.new_page()
errors = []
page.on('pageerror', lambda error: errors.append(str(error)))
page.goto(url)
page.wait_for_function('!document.querySelector("#play").disabled')
assert page.locator('#source').evaluate('(v) => v.paused')
page.click('#play')
# Keep every layer visible for three full cycles before interaction checks.
duration = page.locator('#source').evaluate('(v) => v.duration')
page.evaluate("""() => {
window.observedLoops = []; window.lastVideoTime = 0;
const v = document.querySelector('#source');
v.addEventListener('timeupdate', () => {
if (v.currentTime < window.lastVideoTime) window.observedLoops.push(performance.now());
window.lastVideoTime = v.currentTime;
});
}""")
page.wait_for_timeout((duration * 3 + 0.8) * 1000)
observed = page.evaluate('window.observedLoops')
assert len(observed) >= 3, observed
results['continuous_three_cycles'] = {'duration': duration, 'wraps_ms': observed}
page.wait_for_timeout(800)
alpha = page.locator('#motion').evaluate('(c) => {const x=c.getContext("2d"); return [x.getImageData(0,0,1,1).data[3], x.getImageData(300,220,1,1).data[3]]}')
assert alpha[0] == 0 and alpha[1] > 240, alpha
results['vp9_alpha_decoded_by_chromium'] = alpha
page.wait_for_function('document.querySelector("#source").currentTime > 0.9 && document.querySelector("#source").currentTime < 1.4')
positions = page.evaluate('''() => {
const video=document.querySelector('#source'); const before=video.currentTime;
const source=video.currentSrc; document.querySelector('#lighting').click();
return {before, after:video.currentTime, sourcePreserved: source===video.currentSrc};
}''')
assert positions['before'] == positions['after'] and positions['sourcePreserved']
results['environment_toggle_no_seek'] = positions
page.wait_for_timeout(650)
assert page.locator('#source').evaluate('(v) => !v.paused')
page.click('#show-person')
assert page.locator('#motion').is_hidden() and page.locator('#person').is_hidden()
page.wait_for_timeout(600)
page.screenshot(path=str(EVIDENCE / 'environment-only.png'))
page.click('#show-person')
page.click('#show-occlusion')
assert page.locator('#occlusion').is_hidden()
page.click('#show-occlusion')
page.click('#show-shadow')
assert page.locator('#shadow').is_hidden()
page.click('#show-shadow')
page.click('#show-mask')
assert page.locator('#mask').is_visible() and page.locator('#environment').is_hidden()
page.wait_for_timeout(500)
page.click('#show-mask')
results['independent_layers'] = True
page.click('#closeup')
assert page.locator('#talk').is_visible()
assert page.locator('#source').evaluate('(v) => !v.paused')
page.wait_for_timeout(700)
page.screenshot(path=str(EVIDENCE / 'static-near.png'))
page.click('#closeup')
assert page.locator('#talk').is_hidden()
page.wait_for_timeout(6400) # Includes the forward and generated return.
results['near_is_static_player_continues'] = True
page.click('#play')
t = page.locator('#source').evaluate('(v) => v.currentTime')
page.wait_for_timeout(250)
assert page.locator('#source').evaluate('(v) => v.currentTime') == t
results['manual_pause'] = True
# Chromium lifecycle API freezes the page after making it hidden.
session = context.new_cdp_session(page)
session.send('Page.setWebLifecycleState', {'state': 'active'})
# Visibility handler unit probe. Browser screenshot/recording checks above are real.
page.click('#play')
page.evaluate('''() => {
Object.defineProperty(document, 'hidden', {configurable:true, get:()=>true});
document.dispatchEvent(new Event('visibilitychange'));
}''')
assert page.locator('#source').evaluate('(v) => v.paused')
page.evaluate('''() => {
delete document.hidden; document.dispatchEvent(new Event('visibilitychange'));
}''')
page.wait_for_function('!document.querySelector("#source").paused')
results['visibility_pause_resume_handler_synthetic_event'] = True
for width, height in [(1600, 900), (1280, 800), (390, 844)]:
page.set_viewport_size({'width': width, 'height': height})
page.wait_for_timeout(180)
bounds = page.evaluate('''() => {
const r=document.querySelector('#motion').getBoundingClientRect();
const s=document.querySelector('#stage').getBoundingClientRect();
return {faceX:r.x+305/552*r.width, faceY:r.y+135/552*r.height,
stage:{left:s.left,right:s.right,top:s.top,bottom:s.bottom},
scroll:document.documentElement.scrollWidth, width:innerWidth};
}''')
assert bounds['scroll'] <= width
assert bounds['stage']['left'] <= bounds['faceX'] <= bounds['stage']['right']
assert bounds['stage']['top'] <= bounds['faceY'] <= bounds['stage']['bottom']
page.screenshot(path=str(EVIDENCE / f'viewport-{width}x{height}.png'))
results[f'viewport_{width}x{height}'] = bounds
page.emulate_media(reduced_motion='reduce')
page.wait_for_timeout(100)
assert page.locator('#source').evaluate('(v) => v.paused')
assert page.locator('#person').is_visible() and page.locator('#motion').is_hidden()
results['reduced_motion_static_fallback'] = True
page.emulate_media(reduced_motion='no-preference')
assert page.locator('#source').evaluate('(v) => v.paused')
video_path = Path(page.video.path())
context.close()
video_path.rename(EVIDENCE / 'browser-continuous.webm')
missing = browser.new_page()
missing.route('**/reading-alpha.webm', lambda route: route.abort())
missing.goto(url)
missing.wait_for_function('!document.querySelector("#fallback").hidden')
assert missing.locator('#person').is_visible()
assert missing.locator('#play').is_disabled()
results['missing_motion_static_fallback'] = True
missing.close()
assert not errors, errors
results['page_errors'] = errors
browser.close()
finally:
server.shutdown()
thread.join()
server.server_close()
(EVIDENCE / 'browser-results.json').write_text(json.dumps(results, ensure_ascii=False, indent=2))
print(json.dumps(results, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()
-33
View File
@@ -1,33 +0,0 @@
"""Reproduce the separately switchable foreground and provisional contact shadow."""
from pathlib import Path
from PIL import Image, ImageDraw, ImageFilter
def main():
assets = Path(__file__).resolve().parents[1] / 'public/assets'
source = Image.open(assets / 'reference.png').convert('RGBA')
mask = Image.new('L', source.size)
ImageDraw.Draw(mask).polygon([
(1240, 582), (1282, 566), (1316, 556), (1360, 552), (1403, 532),
(1438, 526), (1486, 514), (1517, 521), (1539, 544), (1559, 556),
(1565, 634), (1520, 707), (1407, 747), (1260, 703), (1227, 650),
], fill=255)
mask = mask.filter(ImageFilter.GaussianBlur(1))
source.putalpha(mask)
source.save(assets / 'occlusion.png')
mask.save(assets / 'occlusion-mask.png')
mask = Image.new('L', source.size)
ImageDraw.Draw(mask).ellipse((1230, 511, 1512, 595), fill=65)
mask = mask.filter(ImageFilter.GaussianBlur(12))
shadow = Image.new('RGBA', source.size, (44, 28, 20, 0))
shadow.putalpha(mask)
shadow.save(assets / 'contact-shadow.png')
composite = Image.open(assets / 'environment.png').convert('RGBA')
for name in ['contact-shadow.png', 'person.png', 'occlusion.png']:
composite = Image.alpha_composite(composite, Image.open(assets / name))
composite.save(assets / 'composite.png')
if __name__ == '__main__':
main()
-79
View File
@@ -1,79 +0,0 @@
"""Use installed SAM modeling modules directly; no predictor/OpenCV dependency.
Run in the existing ComfyUI venv. No downloads or dependency changes.
"""
import argparse
import importlib
import sys
import types
from pathlib import Path
import numpy as np
import torch
from PIL import Image, ImageChops, ImageDraw, ImageFilter
def load_sam(source: Path, checkpoint: Path):
# The optional predictor package imports cv2. We only use the original model API.
package = types.ModuleType("hel711_sam")
package.__path__ = [str(source)]
sys.modules[package.__name__] = package
builder = importlib.import_module("hel711_sam.build_sam")
return builder.build_sam_vit_b(str(checkpoint)).eval()
def segment(model, image, extra_positive=()):
width, height = image.size
scale = 1024 / max(width, height)
size = (round(width * scale), round(height * scale))
tensor = torch.from_numpy(np.array(image.resize(size))).permute(2, 0, 1).to(model.device)
# Crop coordinate system: fixed right-hand seat, 552 x 552.
points = torch.tensor([[[305, 140], [300, 245], [200, 300], [307, 301],
[80, 100], [450, 400], [330, 450]]], dtype=torch.float)
if extra_positive:
extra = torch.tensor([extra_positive], dtype=torch.float)
points = torch.cat((points, extra), dim=1)
points = (points * scale).to(model.device)
labels = torch.tensor([[1, 1, 1, 1, 0, 0, 0]], device=model.device)
if extra_positive:
labels = torch.cat((labels, torch.ones((1, len(extra_positive)), device=model.device)), dim=1)
box = torch.tensor([[100, 60, 420, 380]], dtype=torch.float, device=model.device) * scale
with torch.inference_mode():
result = model([dict(image=tensor, original_size=(height, width),
point_coords=points, point_labels=labels, boxes=box)],
multimask_output=False)[0]
mask = result['masks'][0, 0].cpu().numpy().astype(np.uint8) * 255
mask = Image.fromarray(mask)
# The book/knit texture produces enclosed SAM holes. Fill enclosed holes only.
exterior = mask.copy()
ImageDraw.floodfill(exterior, (0, 0), 255)
mask = ImageChops.lighter(mask, ImageChops.invert(exterior))
return mask.filter(ImageFilter.GaussianBlur(0.65))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('assets', type=Path)
parser.add_argument('--sam-source', type=Path, required=True)
parser.add_argument('--checkpoint', type=Path, required=True)
args = parser.parse_args()
torch.set_num_threads(8)
model = load_sam(args.sam_source, args.checkpoint)
source = Image.open(args.assets / 'reference.png').convert('RGB')
region = (1120, 200, 1672, 752)
crop = source.crop(region)
mask = segment(model, crop)
full_mask = Image.new('L', source.size)
full_mask.paste(mask, region[:2])
full_mask.save(args.assets / 'person-mask.png')
layer = source.convert('RGBA')
layer.putalpha(full_mask)
layer.save(args.assets / 'person.png')
crop.save(args.assets / 'generation-input.png')
environment = Image.open(args.assets / 'environment.png').convert('RGBA')
Image.alpha_composite(environment, layer).save(args.assets / 'composite.png')
print('Saved original-pixel person layer, SAM mask, crop and real composite.', flush=True)
if __name__ == '__main__':
main()
-141
View File
@@ -1,141 +0,0 @@
"""One foreground job using the installed ComfyUI native Wan nodes.
Owns and stops its exact server PID in finally. Does not modify the installation.
"""
import json
import os
import subprocess
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path('/media/lucian/Downloads/ComfyUI')
TASK = ROOT / 'output/hel711-task'
URL = 'http://127.0.0.1:18189'
def request(path, payload=None):
data = None if payload is None else json.dumps(payload).encode()
req = urllib.request.Request(URL + path, data=data,
headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(req, timeout=20) as response:
return json.load(response)
def graph():
nodes = {}
def add(key, kind, **inputs):
nodes[str(key)] = dict(class_type=kind, inputs=inputs)
for key, mode in [(1, 'high'), (2, 'low')]:
add(key, 'UNETLoader', unet_name=f'wan2.2_i2v_{mode}_noise_14B_fp8_scaled.safetensors',
weight_dtype='default')
add(key + 2, 'LoraLoaderModelOnly', model=[str(key), 0],
lora_name=f'wan2.2_i2v_lightx2v_4steps_lora_v1_{mode}_noise.safetensors',
strength_model=1.0)
add(key + 4, 'ModelSamplingSD3', model=[str(key + 2), 0], shift=5.0)
add(7, 'CLIPLoader', clip_name='umt5_xxl_fp8_e4m3fn_scaled.safetensors',
type='wan', device='cpu')
add(8, 'VAELoader', vae_name='wan_2.1_vae.safetensors')
add(9, 'LoadImage', image='generation-input.png')
add(10, 'CLIPTextEncode', clip=['7', 0], text=(
'Locked off camera, photorealistic young adult woman with short dark hair, '
'cream cardigan and dark trousers seated on the same sofa in the same bedroom. '
'She quietly reads the book in her hands, slowly lowers her gaze to the page '
'then gently raises her head a little. Small natural eye blink and breathing. '
'Her hands keep holding the book. Fixed seat position, stationary room and furniture.'))
add(11, 'CLIPTextEncode', clip=['7', 0],
text='camera movement, zoom, changing face, changing clothes, standing up, '
'extra fingers, distorted hands, deformed face, moving furniture, subtitles')
add(12, 'WanImageToVideo', positive=['10', 0], negative=['11', 0], vae=['8', 0],
width=512, height=512, length=49, batch_size=1, start_image=['9', 0])
add(13, 'KSamplerAdvanced', model=['5', 0], add_noise='enable', noise_seed=711,
steps=4, cfg=1.0, sampler_name='euler', scheduler='simple',
positive=['12', 0], negative=['12', 1], latent_image=['12', 2],
start_at_step=0, end_at_step=2, return_with_leftover_noise='enable')
add(14, 'KSamplerAdvanced', model=['6', 0], add_noise='disable', noise_seed=711,
steps=4, cfg=1.0, sampler_name='euler', scheduler='simple',
positive=['12', 0], negative=['12', 1], latent_image=['13', 0],
start_at_step=2, end_at_step=4, return_with_leftover_noise='disable')
add(15, 'VAEDecode', samples=['14', 0], vae=['8', 0])
add(16, 'SaveWEBM', images=['15', 0], codec='vp9', fps=16.0,
filename_prefix='reading', crf=20.0)
return nodes
def main():
for name in ['user', 'temp']:
(TASK / name).mkdir(exist_ok=True)
os.environ['HF_HUB_OFFLINE'] = '1'
os.environ['TRANSFORMERS_OFFLINE'] = '1'
command = [str(ROOT / 'venv/bin/python'), str(ROOT / 'main.py'),
'--listen', '127.0.0.1', '--port', '18189', '--disable-all-custom-nodes',
'--offline', '--disable-manager-ui', '--disable-assets',
'--reserve-vram', '8', '--disable-dynamic-vram',
'--input-directory', str(TASK / 'assets'),
'--output-directory', str(TASK), '--user-directory', str(TASK / 'user'),
'--temp-directory', str(TASK / 'temp'), '--database-url', 'sqlite:///:memory:']
# Refuse to attach to an unrelated listener.
import socket
with socket.socket() as sock:
if sock.connect_ex(('127.0.0.1', 18189)) == 0:
raise RuntimeError('Task port already occupied; no process started')
with open(TASK / 'server.log', 'w') as log:
server = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT)
(TASK / 'process.json').write_text(json.dumps(dict(pid=server.pid, command=command)))
try:
deadline = time.monotonic() + 90
while True:
if server.poll() is not None:
raise RuntimeError(f'ComfyUI exited: {server.returncode}; see server.log')
try:
info = request('/object_info')
break
except (OSError, urllib.error.URLError):
if time.monotonic() > deadline:
raise TimeoutError('Startup exceeded 90 seconds') from None
time.sleep(1)
workflow = graph()
(TASK / 'workflow.json').write_text(json.dumps(workflow, indent=2))
required = {n['class_type']: info.get(n['class_type']) for n in workflow.values()}
(TASK / 'nodes.json').write_text(json.dumps(required, indent=2))
if any(v is None for v in required.values()):
raise RuntimeError('Required native node unavailable; see nodes.json')
result = request('/prompt', {'prompt': workflow})
(TASK / 'submission.json').write_text(json.dumps(result))
prompt_id = result['prompt_id']
print(f'Generating one clip: {prompt_id}; owned server PID {server.pid}', flush=True)
deadline = time.monotonic() + 2400
last_report = 0
while time.monotonic() < deadline:
history = request('/history/' + prompt_id)
if prompt_id in history:
(TASK / 'history.json').write_text(json.dumps(history, indent=2))
print(json.dumps(history[prompt_id]['status']), flush=True)
if history[prompt_id]['status']['status_str'] != 'success':
raise RuntimeError('Generation failed; see history.json')
break
if time.monotonic() - last_report > 30:
print('Single generation still active; existing services untouched.', flush=True)
last_report = time.monotonic()
time.sleep(3)
else:
request('/interrupt', {})
raise TimeoutError('Single generation exceeded 40 minutes')
except urllib.error.HTTPError as error:
(TASK / 'api-error.json').write_bytes(error.read())
raise
finally:
server.terminate()
try:
server.wait(timeout=20)
except subprocess.TimeoutExpired:
server.kill()
server.wait()
print(f'Stopped owned server PID {server.pid}', flush=True)
if __name__ == '__main__':
main()
-149
View File
@@ -1,149 +0,0 @@
"""Generate one conditioned return, from original frame 48 back to frame 0.
Owns and stops its exact server PID in finally. Does not modify the installation.
"""
import json
import os
import subprocess
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path('/media/lucian/Downloads/ComfyUI')
TASK = ROOT / 'output/hel712-task'
URL = 'http://127.0.0.1:18189'
def request(path, payload=None):
data = None if payload is None else json.dumps(payload).encode()
req = urllib.request.Request(URL + path, data=data,
headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(req, timeout=20) as response:
return json.load(response)
def graph():
nodes = {}
def add(key, kind, **inputs):
nodes[str(key)] = dict(class_type=kind, inputs=inputs)
for key, mode in [(1, 'high'), (2, 'low')]:
add(key, 'UNETLoader', unet_name=f'wan2.2_i2v_{mode}_noise_14B_fp8_scaled.safetensors',
weight_dtype='default')
add(key + 2, 'LoraLoaderModelOnly', model=[str(key), 0],
lora_name=f'wan2.2_i2v_lightx2v_4steps_lora_v1_{mode}_noise.safetensors',
strength_model=1.0)
add(key + 4, 'ModelSamplingSD3', model=[str(key + 2), 0], shift=5.0)
add(7, 'CLIPLoader', clip_name='umt5_xxl_fp8_e4m3fn_scaled.safetensors',
type='wan', device='cpu')
add(8, 'VAELoader', vae_name='wan_2.1_vae.safetensors')
add(9, 'LoadImage', image='return-start.png')
add(17, 'LoadImage', image='return-end.png')
add(10, 'CLIPTextEncode', clip=['7', 0], text=(
'Locked off camera, photorealistic young adult woman with short dark hair, '
'cream cardigan and dark trousers seated on the same sofa in the same bedroom. '
'She slowly and smoothly raises her head from looking down at the book, '
'returning to the exact relaxed head pose and eye direction in the final reference. '
'Her hands keep holding the open book without moving it. Natural continuous breathing. '
'Fixed seat position, stationary room and furniture, identical face and outfit.'))
add(11, 'CLIPTextEncode', clip=['7', 0],
text='camera movement, zoom, changing face, changing clothes, standing up, '
'extra fingers, distorted hands, deformed face, moving furniture, subtitles')
add(12, 'WanFirstLastFrameToVideo', positive=['10', 0], negative=['11', 0], vae=['8', 0],
width=512, height=512, length=49, batch_size=1, start_image=['9', 0], end_image=['17', 0])
add(13, 'KSamplerAdvanced', model=['5', 0], add_noise='enable', noise_seed=712,
steps=4, cfg=1.0, sampler_name='euler', scheduler='simple',
positive=['12', 0], negative=['12', 1], latent_image=['12', 2],
start_at_step=0, end_at_step=2, return_with_leftover_noise='enable')
add(14, 'KSamplerAdvanced', model=['6', 0], add_noise='disable', noise_seed=712,
steps=4, cfg=1.0, sampler_name='euler', scheduler='simple',
positive=['12', 0], negative=['12', 1], latent_image=['13', 0],
start_at_step=2, end_at_step=4, return_with_leftover_noise='disable')
add(15, 'VAEDecode', samples=['14', 0], vae=['8', 0])
add(16, 'SaveWEBM', images=['15', 0], codec='vp9', fps=16.0,
filename_prefix='return', crf=20.0)
return nodes
def main():
import av
(TASK / 'assets').mkdir(parents=True, exist_ok=True)
with av.open(str(ROOT / 'output/hel711-task/reading_00001_.webm')) as source:
frames = [frame.to_image() for frame in source.decode(video=0)]
frames[-1].save(TASK / 'assets/return-start.png')
frames[0].save(TASK / 'assets/return-end.png')
for name in ['user', 'temp']:
(TASK / name).mkdir(exist_ok=True)
os.environ['HF_HUB_OFFLINE'] = '1'
os.environ['TRANSFORMERS_OFFLINE'] = '1'
command = [str(ROOT / 'venv/bin/python'), str(ROOT / 'main.py'),
'--listen', '127.0.0.1', '--port', '18189', '--disable-all-custom-nodes',
'--offline', '--disable-manager-ui', '--disable-assets',
'--reserve-vram', '8', '--disable-dynamic-vram',
'--input-directory', str(TASK / 'assets'),
'--output-directory', str(TASK), '--user-directory', str(TASK / 'user'),
'--temp-directory', str(TASK / 'temp'), '--database-url', 'sqlite:///:memory:']
# Refuse to attach to an unrelated listener.
import socket
with socket.socket() as sock:
if sock.connect_ex(('127.0.0.1', 18189)) == 0:
raise RuntimeError('Task port already occupied; no process started')
with open(TASK / 'server.log', 'w') as log:
server = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT)
(TASK / 'process.json').write_text(json.dumps(dict(pid=server.pid, command=command)))
try:
deadline = time.monotonic() + 90
while True:
if server.poll() is not None:
raise RuntimeError(f'ComfyUI exited: {server.returncode}; see server.log')
try:
info = request('/object_info')
break
except (OSError, urllib.error.URLError):
if time.monotonic() > deadline:
raise TimeoutError('Startup exceeded 90 seconds') from None
time.sleep(1)
workflow = graph()
(TASK / 'workflow.json').write_text(json.dumps(workflow, indent=2))
required = {n['class_type']: info.get(n['class_type']) for n in workflow.values()}
(TASK / 'nodes.json').write_text(json.dumps(required, indent=2))
if any(v is None for v in required.values()):
raise RuntimeError('Required native node unavailable; see nodes.json')
result = request('/prompt', {'prompt': workflow})
(TASK / 'submission.json').write_text(json.dumps(result))
prompt_id = result['prompt_id']
print(f'Generating one clip: {prompt_id}; owned server PID {server.pid}', flush=True)
deadline = time.monotonic() + 2400
last_report = 0
while time.monotonic() < deadline:
history = request('/history/' + prompt_id)
if prompt_id in history:
(TASK / 'history.json').write_text(json.dumps(history, indent=2))
print(json.dumps(history[prompt_id]['status']), flush=True)
if history[prompt_id]['status']['status_str'] != 'success':
raise RuntimeError('Generation failed; see history.json')
break
if time.monotonic() - last_report > 30:
print('Single generation still active; existing services untouched.', flush=True)
last_report = time.monotonic()
time.sleep(3)
else:
request('/interrupt', {})
raise TimeoutError('Single generation exceeded 40 minutes')
except urllib.error.HTTPError as error:
(TASK / 'api-error.json').write_bytes(error.read())
raise
finally:
server.terminate()
try:
server.wait(timeout=20)
except subprocess.TimeoutExpired:
server.kill()
server.wait()
print(f'Stopped owned server PID {server.pid}', flush=True)
if __name__ == '__main__':
main()
-59
View File
@@ -1,59 +0,0 @@
"""Per-frame real SAM segmentation, then VP9 alpha encoding with existing PyAV."""
import json
from pathlib import Path
import av
import numpy as np
import torch
from extract_layers import load_sam, segment
from PIL import Image
ROOT = Path('/media/lucian/Downloads/ComfyUI')
TASK = ROOT / 'output/hel711-task'
def main():
torch.set_num_threads(8)
model = load_sam(
ROOT / 'custom_nodes/was-node-suite-comfyui/repos/SAM/segment_anything',
ROOT / 'models/sams/sam_vit_b_01ec64.pth').to('cuda')
output = av.open(str(TASK / 'reading-alpha.webm'), 'w')
stream = output.add_stream('libvpx-vp9', rate=16)
stream.width = 552
stream.height = 552
stream.pix_fmt = 'yuva420p'
stream.options = {'crf': '20', 'b': '0', 'auto-alt-ref': '0'}
metrics = []
previews = []
source = av.open(str(TASK / 'reading_00001_.webm'))
previous = None
first = None
for index, decoded in enumerate(source.decode(video=0)):
image = decoded.to_image().resize((552, 552), Image.Resampling.LANCZOS)
mask = segment(model, image)
frame = image.convert('RGBA')
frame.putalpha(mask)
pixels = np.array(image).astype(float)
if first is None:
first = pixels
metrics.append(dict(frame=index, mask_pixels=int((np.array(mask) > 127).sum()),
mean_absolute_rgb_change=0 if previous is None else float(np.abs(pixels-previous).mean())))
previous = pixels
if index in [0, 16, 32, 48]:
previews.append(frame)
frame.save(TASK / f'matted-{index:02}.png')
for packet in stream.encode(av.VideoFrame.from_ndarray(np.array(frame), format='rgba')):
output.mux(packet)
if index % 16 == 0:
print(f'Matted frame {index}', flush=True)
for packet in stream.encode():
output.mux(packet)
output.close()
source.close()
(TASK / 'frame-metrics.json').write_text(json.dumps(dict(
frames=metrics, loop_rgb_difference=float(np.abs(previous-first).mean()),
interpretation='Real generated frames; RGB differences alone are not proof of valid anatomy or identity.'), indent=2))
if __name__ == '__main__':
main()
-106
View File
@@ -1,106 +0,0 @@
"""Measure all joins and before/after hand mattes; export reviewable frame evidence."""
import json
from pathlib import Path
import av
import numpy as np
from PIL import Image, ImageDraw
from scipy.ndimage import binary_erosion, map_coordinates
from skimage.color import rgb2gray
from skimage.registration import optical_flow_tvl1
TASK = Path('/media/lucian/Downloads/ComfyUI/output/hel712-task')
def summary(values):
a = np.array(values)
return dict(min=float(a.min()), median=float(np.median(a)),
p95=float(np.percentile(a, 95)), max=float(a.max()))
def panel(images, labels, path, size=(256, 256), columns=6):
width, height = size
board = Image.new('RGB', (columns*width, ((len(images)+columns-1)//columns)*(height+22)), '#202020')
draw = ImageDraw.Draw(board)
for i, (image, label) in enumerate(zip(images, labels, strict=True)):
x, y = i % columns*width, i // columns*(height+22)
board.paste(image.resize(size), (x, y))
draw.text((x+3, y+height+3), label, fill='white')
board.save(path)
def main():
data = np.load(TASK/'segmentation-v2.npz')
mattes = np.load(TASK/'mattes.npz')
rgb = data['images']
# All measurement uses 512px source coordinates. The head box is fixed for both clips.
images = [np.array(Image.fromarray(x).resize((512,512))) for x in rgb]
before, after = [[np.array(Image.fromarray(x).resize((512,512))) > 127
for x in mattes[key]] for key in ['before','after']]
head = [x[50:180,230:340].astype(float) for x in images]
pairs = [(i, i+1) for i in range(97)] + [(97,0)]
head_diff = [float(np.abs(head[a]-head[b]).mean()) for a,b in pairs]
ordinary = [d for i,d in enumerate(head_diff) if i not in [48,97]]
report = {'coordinates':'512x512, head x230:340 y50:180, book/hand all x y175:330',
'original_head_adjacent':summary(head_diff[:48]),
'original_head_seam':float(np.abs(head[48]-head[0]).mean()),
'loop_ordinary_head':summary(ordinary),
'joins':[{'pair':[48,49],'head_mae':head_diff[48]},
{'pair':[97,0],'head_mae':head_diff[97]}],
'head_mae_all_pairs':head_diff}
for name, masks in [('before',before),('after',after)]:
edge = [int((m & ~binary_erosion(m))[175:330].sum()) for m in masks]
switches = [int((masks[a]^masks[b])[175:330].sum()) for a,b in pairs]
report[name] = {'boundary_pixels': edge, 'switch_pixels':switches,
'original49_boundary':summary(edge[:49]),
'original49_boundary_jump':summary(np.abs(np.diff(edge[:49]))),
'original49_switch':summary(switches[:48]),
'all_boundary':summary(edge), 'all_boundary_jump':summary(np.abs(np.diff(edge + [edge[0]]))),
'all_switch':summary(switches),
'joins_switch':[switches[48],switches[97]]}
# Warp both alpha candidates with the same image motion. Residuals separate
# mask switching from unaligned silhouette motion (not an anatomy metric).
compensated = {'before':[], 'after':[]}
rows, cols = np.meshgrid(np.arange(155), np.arange(512), indexing='ij')
for a,b in pairs:
flow = optical_flow_tvl1(rgb2gray(images[a][175:330]).astype(np.float32),
rgb2gray(images[b][175:330]).astype(np.float32),
num_warp=3, num_iter=5)
for name,masks in [('before',before),('after',after)]:
warped = map_coordinates(masks[b][175:330].astype(float),
[rows+flow[0],cols+flow[1]], order=1, mode='nearest')>0.5
compensated[name].append(int((masks[a][175:330]^warped).sum()))
report['flow_compensated_switch']={k:{'all':summary(v), 'original49':summary(v[:48]),'per_pair':v}
for k,v in compensated.items()}
# Raw interior stays paired with alpha output; encoding error is reported separately.
with av.open(str(TASK/'reading-alpha.webm')) as src:
decoder=av.CodecContext.create('libvpx-vp9','r')
decoded=[f.to_ndarray(format='rgba') for p in src.demux(video=0) for f in decoder.decode(p)]
report['alpha_rgb_interior_mae']=summary([
float(np.abs(out[:,:,:3].astype(float)-im).mean(axis=2)[m>250].mean())
for out,im,m in zip(decoded,rgb,mattes['after'],strict=True)])
(TASK/'metrics.json').write_text(json.dumps(report,indent=2))
print(json.dumps({k:v for k,v in report.items() if k not in ['before','after','head_mae_all_pairs','flow_compensated_switch']},indent=2))
print(json.dumps({k:{x:y for x,y in v.items() if not isinstance(y,list)} for k,v in report.items() if k in ['before','after']},indent=2))
ids=[46,47,48,49,50,51,94,95,96,97,0,1]
panel([Image.fromarray(images[i]) for i in ids], [f'frame {i}' for i in ids],TASK/'join-frames.png')
panel([Image.fromarray(images[i][50:180,230:340]) for i in ids], [f'head {i}' for i in ids],TASK/'join-heads.png',size=(220,260))
ids=[0,8,16,24,32,40,47,48,49,56,64,72,80,88,96,97]
crops=[]
labels=[]
for i in ids:
for name,masks in [('before',mattes['before']),('after',mattes['after'])]:
rgba=np.dstack((rgb[i],masks[i]))
bg=Image.new('RGBA',(552,552),'#557788')
bg.alpha_composite(Image.fromarray(rgba))
crops.append(bg.convert('RGB').crop((90,189,430,356)))
labels.append(f'{name} {i}')
panel(crops,labels,TASK/'hand-before-after.png',size=(340,167),columns=4)
panel([Image.fromarray(mattes['after'][i]).convert('RGB').crop((90,189,430,356)) for i in ids],
[f'alpha {i}' for i in ids],TASK/'hand-mattes.png',size=(340,167),columns=4)
panel([Image.fromarray(images[i]) for i in range(98)], [str(i) for i in range(98)],
TASK/'all-frames.png',size=(170,170),columns=14)
if __name__=='__main__':
main()
-146
View File
@@ -1,146 +0,0 @@
"""Assemble the generated forward/return clips and stabilize only the hand/book matte.
Run with the existing ComfyUI environment; no models or dependencies are fetched.
Optical flow aligns neighbouring masks; only alpha changes, never source RGB.
"""
import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import av
import numpy as np
import torch
from extract_layers import load_sam, segment
from PIL import Image
from scipy.ndimage import distance_transform_edt, gaussian_filter, label, map_coordinates
from skimage.color import rgb2gray
from skimage.registration import optical_flow_tvl1
ROOT = Path('/media/lucian/Downloads/ComfyUI')
TASK = ROOT / 'output/hel712-task'
BASE = ROOT / 'output/hel711-task'
Y0, Y1 = round(175 * 552 / 512), round(330 * 552 / 512)
def decode_alpha(path):
with av.open(str(path)) as source:
decoder = av.CodecContext.create('libvpx-vp9', 'r')
return [f.to_ndarray(format='rgba') for p in source.demux(video=0)
for f in decoder.decode(p)]
def encode(path, frames, alpha):
with av.open(str(path), 'w') as output:
stream = output.add_stream('libvpx-vp9', rate=16)
stream.width = stream.height = frames[0].shape[0]
stream.pix_fmt = 'yuva420p' if alpha else 'yuv420p'
stream.options = {'crf': '10', 'b': '0', 'auto-alt-ref': '0'}
for frame in frames:
for packet in stream.encode(av.VideoFrame.from_ndarray(
frame, format='rgba' if alpha else 'rgb24')):
output.mux(packet)
for packet in stream.encode():
output.mux(packet)
def signed(mask):
binary = mask > 127
return distance_transform_edt(binary) - distance_transform_edt(~binary)
def stabilize(images, masks):
# Padding supplies flow context, but edits are restricted to the specified band.
top, bottom = Y0 - 24, Y1 + 24
gray = [rgb2gray(im[top:bottom]).astype(np.float32) for im in images]
distances = [signed(m[top:bottom]) for m in masks]
rows, cols = np.meshgrid(np.arange(bottom-top), np.arange(552), indexing='ij')
def one(i):
mask = masks[i]
aligned = [distances[i]]
for offset in [-2, -1, 1, 2]:
j = (i + offset) % len(masks)
flow = optical_flow_tvl1(gray[i], gray[j], attachment=15,
num_warp=5, num_iter=10)
aligned.append(map_coordinates(distances[j], [rows+flow[0], cols+flow[1]],
order=1, mode='nearest'))
# Trim the most extreme masks; averaging the remaining three signed
# distances also avoids a majority-vote jump at the two clip joins.
consensus = np.sort(aligned, axis=0)[1:-1].mean(axis=0)
# A narrow spatial regularization removes single-pixel segmentation teeth.
stable = gaussian_filter(consensus, 0.65)
current = distances[i]
stable = np.where(np.abs(current) <= 6, stable, current)
alpha = np.clip(127.5 + stable * 127.5, 0, 255)
# Blend the first/last 8 rows back to the unchanged matte.
weight = np.ones(Y1-Y0)
weight[:8] = np.linspace(0, 1, 8)
weight[-8:] = np.linspace(1, 0, 8)
new = mask.copy()
roi = alpha[Y0-top:Y1-top]
new[Y0:Y1] = np.rint(roi*weight[:, None] + mask[Y0:Y1]*(1-weight[:, None])).astype(np.uint8)
return new, int(np.count_nonzero((new>127) != (mask>127)))
output, changes = [], []
with ThreadPoolExecutor(max_workers=4) as executor:
for i, (mask, change) in enumerate(executor.map(one, range(len(masks)))):
output.append(mask)
changes.append(change)
if i % 8 == 0:
print(f'Flow-aligned matte {i}/{len(masks)}', flush=True)
return output, changes
def main():
torch.set_num_threads(8)
cache = TASK / 'segmentation-v2.npz'
if cache.exists():
data = np.load(cache)
images, masks = list(data['images']), list(data['masks'])
else:
# Preserve original matte outside the hand/book band without rerunning it.
original = decode_alpha(BASE / 'reading-alpha.webm')
with av.open(str(BASE / 'reading_00001_.webm')) as source:
images = [np.array(f.to_image().resize((552, 552), Image.Resampling.LANCZOS))
for f in source.decode(video=0)]
masks = [f[:, :, 3] for f in original]
model = load_sam(ROOT / 'custom_nodes/was-node-suite-comfyui/repos/SAM/segment_anything',
ROOT / 'models/sams/sam_vit_b_01ec64.pth').to('cuda')
with av.open(str(TASK / 'return_00001_.webm')) as source:
for i, frame in enumerate(source.decode(video=0)):
image = frame.to_image().resize((552, 552), Image.Resampling.LANCZOS)
images.append(np.array(image))
alpha = np.array(segment(model, image, extra_positive=(
(245, 258), (280, 275), (360, 245), (365, 295))))
components, count = label(alpha > 127)
sizes = np.bincount(components.ravel())
sizes[0] = 0
keep = components == sizes.argmax()
# Retain feather next to the connected subject; discard isolated sofa specks.
from scipy.ndimage import binary_dilation
alpha[~binary_dilation(keep, iterations=3)] = 0
masks.append(alpha)
if i % 8 == 0:
print(f'Segmented return frame {i}', flush=True)
np.savez_compressed(cache, images=np.array(images), masks=np.array(masks))
del model
torch.cuda.empty_cache()
stable, changes = stabilize(images, masks)
np.savez_compressed(TASK / 'mattes.npz', before=np.array(masks), after=np.array(stable))
encode(TASK / 'loop-source.webm', images, False)
frames = [np.dstack((rgb, a)) for rgb, a in zip(images, stable, strict=True)]
encode(TASK / 'reading-alpha.webm', frames, True)
(TASK / 'stabilization.json').write_text(json.dumps({
'frames': len(images), 'fps': 16, 'join_pairs': [[48,49],[97,0]],
'source_map': [{'frames':[0,48], 'source':'reading_00001_.webm'},
{'frames':[49,97], 'source':'return_00001_.webm'}],
'band_512': [175,330], 'band_552': [Y0,Y1],
'flow': 'TV-L1, four neighbours, cyclic trimmed signed-distance mean, 6px uncertainty band',
'changed_binary_pixels_per_frame': changes,
'rgb': 'Original RGB retained; no temporal RGB blending or frame replacement',
'outside_band_unchanged': all(np.array_equal(a[:Y0],b[:Y0]) and np.array_equal(a[Y1:],b[Y1:])
for a,b in zip(masks,stable,strict=True))}, indent=2))
print('Encoded 98-frame forward/return candidate, not yet accepted.', flush=True)
if __name__ == '__main__':
main()
-20
View File
@@ -1,20 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": [
"src"
]
}