Fix bedroom loop return and stabilize hand mattes

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
Multica 施工员
2026-10-20 16:14:20 +08:00
co-authored by multica-agent
parent 444ee56c6a
commit dab536987a
8 changed files with 513 additions and 53 deletions
+16
View File
@@ -37,3 +37,19 @@ python matte_video.py
## 当前实测与未通过项
当前结果见 `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仍未测。
+37 -37
View File
@@ -1,52 +1,52 @@
2026-10-20 HEL-711 审核记录
HEL-712:原阅读动作循环与书本/手部蒙版返工候选,交总工复审,不部署。
## 实际结果
## 实现
已完成原始像素透明人物层、无人环境层、前景毯子/蒙版、暂定接触阴影、静态合成和独立开关。坐标系为 1672×941,固定右侧 552×552 区域(1120,200),人物未平移/缩放伪装动作。原参考和透明层在素材包中,可检查 alpha。
沿用原人物、米色开衫、深灰长裤、卧室、机位与552px人物落点。现有 Wan2.2 原生首尾帧条件节点,使用原片 f48→f0,seed 712,实际生成一条49帧抬头回程。原49帧向前播放,随后49帧真实回程,98帧/16fps/6.125秒,内部接点48→49,跨周期97→0。没有倒放、冻结、静态摆动、遮脸淡化或短窗口裁切。
仅生成一段 Wan2.2 真实阅读动作:512×512 原始生成、49 帧、16fps、3.0625s;逐帧分割后恢复为 552×552 裁切区域,VP9 WebM alpha。人物从微歪头看向镜头变为低头读书,衣服和坐姿保持;这次没有实现再次抬头。四张连续取样帧与原始视频均交付,不用 RGB 差分独自证明人物动作。
原49帧 alpha 不重新分割;新增49帧补书本/衣袖正点,保留连通人物,去掉分离的沙发碎点。两段仅在原512px坐标 y175:330(输出552px坐标189:356)稳定蒙版:TV-L1对齐前后各2帧,有符号距离去掉最高/最低值,再取均值,限制到当前轮廓6px不确定区域,首尾8行回接原蒙版。只处理alpha,RGB不做时间平均;原发丝区域保持原alpha。原始源片与透明片逐帧映射见manifest/stabilization.json。
实测推理日志 `Prompt executed in 57.18 seconds`,不包含环境启动、分层和浏览器录屏耗时。首尾 RGB 平均差约 11.998/255,仅是诊断数据。首尾姿态有明显差异,硬循环会跳变;没有反向播放伪造完整动作。
第一次新增回程直接套原分割提示时,会漏掉书本/衣袖;该版已拒绝,`before-crops.png` 保留实证。补充分割提示后才进入最终蒙版稳定。共生成一条视频,没有批量换装或动作试片。第一次稳定使用中值共识,接头alpha变化仍偏集中;最终使用去极值均值,缓和了两个分段蒙版的多数票切换。
## .12 工具核查
## 同口径差异与边缘统计
- GPU RTX 5090 D,nvidia-smi 总显存 32607MiB;生成/抠像前后既有占用均为 5633MiB,未记录精确峰值,不能声称峰值或共存 SLA。磁盘可用约 754GiB。
- Desktop 安装 `/home/lucian/ComfyUI-Installs/ComfyUI` 和 `/home/lucian/ComfyUI-Shared` 确实存在,但 8188 未监听。
- 实际可运行安装为 `/media/lucian/Downloads/ComfyUI`,venv PyTorch `2.14.1+cu130`、torchvision `0.29.1+cu130`、PyAV `19.0.1`;缺 cv2/rembg/timm,系统 ffmpeg 不在 PATH。未安装任何依赖。
- 原有 models 内已存在 Wan2.2 I2V 高/低噪声 fp8 各约 14.29GB、UMT5 fp8 约 6.74GB、Wan VAE 约 254MB、对应 LightX2V LoRA 各约 1.23GB,以及 SAM vit-b 约 375MB。并非只见到文件就宣称可用:本次已实际跑通原生节点和单片段生成。
- 临时 ComfyUI PID 596473,日志在素材包 `evidence/server.log`,已由启动脚本 finally 停止;18189 已无监听。旧 18080 及 ASR/TTS 监听保持。没有驻留生成工作,没有部署。
- SSH 使用已确认的主机密钥及既有凭据;没有输出凭据。没有下载大模型、购买接口、修改开机启动或运行 GUI。
本报告独立固定口径: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 |
- `npm run build`:通过,包含 TypeScript 严格检查;生产构建约 3.2KB CSS / 3.6KB JS(未 gzip)。
- `python3 -m pytest -q`:原有 78 项全部通过。
- `python3 -m ruff check src tests samples/bedroom/tools`:通过。
- 真实 Chromium 解码 alpha:背景像素 alpha=0、人物内部 alpha=255。
- 环境开关前后同一视频 source、同一 currentTime;实测样例 0.915222s→0.915222s。录屏包含人物播放、环境开关、无人画面、蒙版、阴影/前景开关和静态近景进入/退出。
- 1600×900、1280×800、390×844:无横向溢出、脸部在画面内,控制区不遮脸。手机以全画面包含方式展示,人物较小,未宣称手机沉浸效果验收通过。
- 暂停/恢复、减少动效切静态、动态素材加载失败回退静态:通过。浏览器 pageerror=0。
- 隐藏暂停/恢复处理经合成 visibilitychange 事件验证;headless 环境不能代表真实切后台/系统锁屏,仍需设备手测。未测 Safari/iOS 的 VP9 alpha 支持,解码失败会显式回退。
原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 |
1. 循环首尾头部跳变,未建立可接受切点。需后续在获准后做闭环片段或经美术确认的自然选片衔接,本轮不批量重试。
2. SAM 是分割加羽化,不是精细发丝抠像;细发、针织边缘、书本遮挡可能闪烁/缺损,需逐帧美术复核。49 帧蒙版面积范围 49312~50563 像素,不能据此宣称边缘无抖动。
3. 原无人/有人参考沙发与抱枕几何略有差异。人物固定落位与独立遮挡已实现,残余靠背、接触边缘和前景拼接仍需美术校正。接触阴影是暂定独立工程层。
4. 小尺寸手部/书页可辨但不保证解剖正确;没有完成逐帧身份评分,脸部细节与跨镜头一致性待审。
5. 环境减光只验证人物/房间独立,人物本身未做对应重打光;按钮标注手动演示,未接真实城市天气。
6. 近景为 v2 静态切换,进退是即时校对切镜,衔接未润色;不能算真实交谈、语音或口型通过。
动作补偿使用同一源RGB光流对齐前后蒙版;可见减少的是分割开关,不靠抹掉真实运动。人物内部透明片与源RGB编码误差逐帧中位1.89、最大2.10/255;无RGB时间混合。带外alpha逐数组一致为true。重点帧可见书本/指尖与袖口保持,未见新增吞手或RGB拖影;仍需总工以连续视频独立确认。没有把数值降低当作人体解剖或身份认证。
按 Emil review-animations 复核界面控制:
## 验证
| Before | After | Why |
| --- | --- | --- |
| 自动循环可能让减少动效用户持续看到人物运动 | 默认手动播放,减少动效时暂停并显示静态层 | 用户控制和无运动回退已验证 |
| 近景或环境切换可能重新装载视频 | 保留唯一 video,仅切独立层的可见性/环境亮度 | 切换可打断,保持实际播放位置 |
| 片段首尾头姿不同 | 仍标注待修,不添加平移/缩放掩盖跳变 | 真实视频循环没有通过观感验收 |
- 来源包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未测;近景仅静态,未增加口型、语音或后台生活功能。手机构图、沙发几何、重打光与近景润色保持原记录。
界面播放控制 Approve;循环衔接与自然近景体验 Block,交总管/美术继续验收。本卡交付可审核的最小真实片段,不表示整体动态体验通过。
## 文件与运行边界
## 仓库
修改 `tools/extract_layers.py`(可选补充提示)、新增 `tools/generate_return.py`、`stabilize_loop.py`、`measure_loop.py`,扩展 `tools/browser_check.py` 的连续三周期验证,更新manifest/README/本报告。没有改CSS、主题、核心服务或部署配置。
Multica checkout 返回仓库未配置,因此使用既有 SSH 权限直接 clone 指定仓库,建立独立 `hel-711-layered-bedroom`,基于明确指定 main `1e9b08a`。旧 `hel-700-rain-room` 未改动。`git ls-remote refs/pull/*/head` 无结果;SSH refs 不能证明私有 Gitea 没有 PR,未通过未知 API 凭据枚举 PR。此次不合并、不部署,提交号见本卡最终结果评论。
分支继续 `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 -14
View File
@@ -1,5 +1,5 @@
{
"schema": "hel711-review-1",
"schema": "hel712-review-1",
"status": "review_candidate",
"reference_sha256": {
"reference.png": "226d7922e042e22e4b8a8241a7cf6f7aea50c301029978e4ca26cad9b3d56359",
@@ -48,11 +48,11 @@
}
],
"motion": {
"status": "真实生成;循环与抠像待修",
"status": "真实回程与书本手部蒙版返工候选,待复审",
"file": "reading-alpha.webm",
"alpha": true,
"maskFile": null,
"original": "reading_00001_.webm",
"original": "loop-source.webm",
"generator": "installed ComfyUI native Wan2.2 high/low 14B fp8 + installed LightX2V 4-step LoRAs",
"seed": 711,
"dimensions": [
@@ -63,15 +63,40 @@
512,
512
],
"frames": 49,
"frames": 98,
"fps": 16,
"duration_seconds": 3.0625,
"duration_seconds": 6.125,
"codec": "VP9 yuva420p / WebM",
"matting": "existing SAM vit-b, per frame, filled enclosed holes, 0.65px feather",
"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": "same seat and clothes, head down at book",
"loop": "hard loop at 49 frames; visible head jump, not seamless",
"cut_point": "none accepted"
"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",
@@ -82,12 +107,11 @@
},
"known_issues": [
"Original empty/occupied sofa and pillow geometry differs; residual contact geometry needs art review.",
"SAM hard segmentation + feather is not hair matting; edge texture loss/flicker possible.",
"Book and fingers are small; hand anatomy/identity not certified.",
"Start/end head poses differ; hard loop jumps visibly.",
"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."
"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": {
@@ -95,8 +119,8 @@
"sha256": "0ae9b1a1cb9c590ab89a81ce4efd25de843a600ff227c184663db23e9e9c16b3"
},
"reading-alpha.webm": {
"bytes": 472707,
"sha256": "d28ef9a062744a8b362abfc6a4bc4d374a74128eea7c59d8441a4b77f7c14d98"
"bytes": 1971817,
"sha256": "9b9b95fff6c047c68ea66d14eba1ca896a80107b7c5b531c326bfac8bdc90b76"
},
"person.png": {
"bytes": 2522355,
+15 -1
View File
@@ -37,6 +37,20 @@ def main():
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
@@ -74,7 +88,7 @@ def main():
page.screenshot(path=str(EVIDENCE / 'static-near.png'))
page.click('#closeup')
assert page.locator('#talk').is_hidden()
page.wait_for_timeout(3400) # Includes a real hard loop.
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')
+6 -1
View File
@@ -22,7 +22,7 @@ def load_sam(source: Path, checkpoint: Path):
return builder.build_sam_vit_b(str(checkpoint)).eval()
def segment(model, image):
def segment(model, image, extra_positive=()):
width, height = image.size
scale = 1024 / max(width, height)
size = (round(width * scale), round(height * scale))
@@ -30,8 +30,13 @@ def segment(model, image):
# 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),
+149
View File
@@ -0,0 +1,149 @@
"""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()
+106
View File
@@ -0,0 +1,106 @@
"""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
@@ -0,0 +1,146 @@
"""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()