feat(HEL-714): add isolated daily-video and local talking sample

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
mobai
2026-10-21 00:14:18 +08:00
co-authored by multica-agent
parent 6a5e155258
commit bcc0eb7036
31 changed files with 3340 additions and 0 deletions
+91
View File
@@ -0,0 +1,91 @@
"""Source-relative lip residual + audio RMS using browser MediaRecorder PTS.
Heuristic evidence only: no automatic perceptual-sync acceptance.
"""
import argparse
import csv
import json
from pathlib import Path
import av
import cv2
import numpy as np
p = argparse.ArgumentParser()
p.add_argument("video", type=Path)
p.add_argument("--source", type=Path, default=Path("/opt/hel715-verify/talk-close.mp4"))
p.add_argument("--size", type=int, default=768)
p.add_argument("--offset-x", type=int, default=0)
p.add_argument("--offset-y", type=int, default=0)
p.add_argument("--render-size", type=int, default=768)
p.add_argument("--start", type=float, default=0)
p.add_argument("--stop", type=float, default=100000)
p.add_argument("--roi", default="0.4492,0.6185,0.4753,0.6315")
p.add_argument("--idle-until", type=float)
a = p.parse_args()
source = [f.to_ndarray(format="bgr24") for f in av.open(str(a.source)).decode(video=0)]
size = a.size
source = [cv2.resize(f, (size, size)) for f in source]
# Broad lower-face region; source matching uses pixels outside it and outside
# caption/watermark so normal head movement is not mistaken for synthesized lips.
x0, x1, y0, y1 = [round(v * size) for v in map(float, a.roi.split(","))]
mask = np.ones((48, 48), dtype=bool)
mask[0:3] = False
mask[43:] = False
mask[
round(y0 * 48 / size) : round(y1 * 48 / size), round(x0 * 48 / size) : round(x1 * 48 / size)
] = False
features = np.asarray([cv2.resize(f, (48, 48))[mask].astype(np.float32) for f in source])
rows = []
for f in av.open(str(a.video)).decode(video=0):
if not a.start <= float(f.time) <= a.stop:
continue
image = f.to_ndarray(format="bgr24")
image = image[a.offset_y : a.offset_y + a.render_size, a.offset_x : a.offset_x + a.render_size]
image = cv2.resize(image, (size, size))
feature = cv2.resize(image, (48, 48))[mask].astype(np.float32)
index = np.argmin(((features - feature) ** 2).mean(axis=(1, 2)))
residual = np.abs(image.astype(np.float32) - source[index]).mean(axis=2)
rows.append([float(f.time), float(residual[y0:y1, x0:x1].mean()), int(index)])
audio = []
for f in av.open(str(a.video)).decode(audio=0):
if not a.start <= float(f.time) <= a.stop:
continue
data = f.to_ndarray().astype(np.float64)
if f.format.is_planar and f.format.name.startswith("fl"):
pass
elif data.max() > 1:
data /= 32768
audio.append([float(f.time), float(np.sqrt((data**2).mean()))])
with a.video.with_suffix(".sync.csv").open("w") as out:
w = csv.writer(out)
w.writerow(["time_seconds", "lip_residual", "source_index", "audio_rms"])
for t, residual, idx in rows:
nearest = min(audio, key=lambda x: abs(x[0] - t))
w.writerow([t, residual, idx, nearest[1]])
first_audio = next((t for t, rms in audio if rms > 0.015), None)
baseline = [
r
for t, r, _ in rows
if first_audio and t < (a.idle_until if a.idle_until is not None else first_audio - 0.5)
]
threshold = max(4, float(np.quantile(baseline, 0.99)) * 1.5) if baseline else 4
first_lip = next(
(
t
for t, r, _ in rows
if r > threshold
and first_audio
and t >= (a.idle_until if a.idle_until is not None else first_audio - 1)
),
None,
)
result = dict(
first_audio=first_audio,
first_lip=first_lip,
residual_threshold=threshold,
onset_difference_seconds=first_lip - first_audio if first_lip and first_audio else None,
caveat="Source-relative residual heuristic, not phoneme alignment or perceptual acceptance",
)
a.video.with_suffix(".sync.json").write_text(json.dumps(result, indent=2))
print(result)
+50
View File
@@ -0,0 +1,50 @@
import asyncio
import json
import pathlib
from playwright.async_api import async_playwright
OUT = pathlib.Path(__file__).resolve().parents[1] / "evidence"
OUT.mkdir(exist_ok=True)
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(
args=["--no-sandbox", "--autoplay-policy=no-user-gesture-required"]
)
page = await browser.new_page()
await page.goto("http://192.168.200.12:8010")
await page.evaluate("""async () => {
document.body.innerHTML='<video id="v" autoplay playsinline></video><canvas id="c" width="768" height="768"></canvas>';
const v=document.querySelector('video'), c=document.querySelector('canvas'), ctx=c.getContext('2d');
const ac=new AudioContext(), dest=ac.createMediaStreamDestination();
const pc=window.pc=new RTCPeerConnection({iceServers:[]});
const stream=new MediaStream(); v.srcObject=stream;
pc.ontrack=e=>stream.addTrack(e.track);
pc.addTransceiver('audio',{direction:'recvonly'}); pc.addTransceiver('video',{direction:'recvonly'});
await pc.setLocalDescription(await pc.createOffer());
await new Promise(r=>{if(pc.iceGatheringState==='complete')r();else pc.onicegatheringstatechange=()=>{if(pc.iceGatheringState==='complete')r()}});
const a=await (await fetch('/offer',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(pc.localDescription)})).json();
window.sid=a.sessionid; await pc.setRemoteDescription(a);
await new Promise(r=>v.onloadeddata=r); await v.play();
v.muted=true; const source=ac.createMediaStreamSource(stream); source.connect(ac.destination); source.connect(dest);
await ac.resume(); const recorded=c.captureStream(25); dest.stream.getAudioTracks().forEach(t=>recorded.addTrack(t));
window.metrics=[]; const analyser=ac.createAnalyser();source.connect(analyser);let buffer=new Float32Array(analyser.fftSize);
function draw(){ctx.drawImage(v,0,0,768,768);ctx.fillStyle='white';ctx.font='20px sans-serif';ctx.fillText((performance.now()/1000).toFixed(3),20,750);analyser.getFloatTimeDomainData(buffer);metrics.push([performance.now(),Math.sqrt(buffer.reduce((s,x)=>s+x*x,0)/buffer.length)]);window.raf=requestAnimationFrame(draw)}draw();
window.chunks=[];window.rec=new MediaRecorder(recorded,{mimeType:'video/webm;codecs=vp8,opus'});rec.ondataavailable=e=>chunks.push(e.data);rec.start(1000);
}""")
await page.wait_for_timeout(1500)
await page.evaluate(
"""async()=>{window.sent=performance.now();await fetch('/human',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({sessionid:sid,type:'echo',text:'你好。八百标兵奔北坡,炮兵并排北边跑。现在我停下来听你说话。'})})}"""
)
await page.wait_for_timeout(18000)
data = await page.evaluate(
"""async()=>{await new Promise(r=>{rec.onstop=r;rec.stop()});const b=new Blob(chunks);return Array.from(new Uint8Array(await b.arrayBuffer()))}"""
)
(OUT / "baseline-browser-av.webm").write_bytes(bytes(data))
(OUT / "baseline.json").write_text(json.dumps(await page.evaluate("({sent,metrics})")))
await browser.close()
asyncio.run(main())
+136
View File
@@ -0,0 +1,136 @@
"""Real Chromium/WebRTC check; fake devices are explicitly synthetic fixtures."""
import asyncio
import json
import pathlib
import time
from playwright.async_api import async_playwright
ROOT = pathlib.Path(__file__).resolve().parents[1]
OUT = ROOT / "evidence"
OUT.mkdir(exist_ok=True)
URL = "https://192.168.200.12:8014"
async def download(page, path):
await page.click("#record")
await page.wait_for_selector("#download:not([hidden])")
async with page.expect_download() as pending:
await page.click("#download")
await (await pending.value).save_as(path)
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(
args=["--no-sandbox", "--autoplay-policy=no-user-gesture-required"]
)
context = await browser.new_context(
ignore_https_errors=True, viewport={"width": 1280, "height": 800}
)
page = await context.new_page()
errors = []
page.on("pageerror", lambda e: errors.append(str(e)))
await page.goto(URL)
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('就绪')"
)
await page.click("#record")
await page.wait_for_timeout(1000)
await page.fill("#text", "我今天下班了,有点累。请只用一句简短的话回应。")
await page.click("button[type=submit]")
await page.wait_for_function(
"window.sampleEvents.some(e=>e.event==='first-audible')", timeout=60000
)
await page.wait_for_timeout(1500)
await page.click("#cancel")
await page.wait_for_timeout(1500)
assert await page.evaluate("document.querySelector('#talk').srcObject===null")
await page.fill("#text", "你在看什么书?只说一句话。")
await page.click("button[type=submit]")
await page.wait_for_function(
"window.sampleEvents.filter(e=>e.event==='first-audible').length>=2", timeout=60000
)
await page.wait_for_timeout(6000)
await page.click("#back")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('已回到阅读')", timeout=15000
)
assert not await page.locator("#daily").evaluate("(v)=>v.paused")
await page.click("#pause")
assert await page.locator("#daily").evaluate("(v)=>v.paused")
await page.click("#pause")
await page.locator("summary").click()
await page.select_option("#weather", "clear")
assert "回退" in await page.locator("#selection").inner_text()
await page.click("#enter")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('正在听')", timeout=30000
)
await page.fill("#text", "这是取消准备阶段的测试,请简短回复。")
await page.click("button[type=submit]")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('准备回复')", timeout=30000
)
await page.wait_for_timeout(1000)
await page.click("#cancel")
await page.wait_for_timeout(6000)
assert await page.locator("#talk").evaluate("(v)=>v.srcObject===null")
await page.click("#back")
(OUT / "sample-events.json").write_text(
json.dumps(await page.evaluate("window.sampleEvents"), ensure_ascii=False, indent=2)
)
await download(page, OUT / "sample-browser-av.webm")
await page.screenshot(path=str(OUT / "desktop.png"))
await page.set_viewport_size({"width": 390, "height": 844})
await page.screenshot(path=str(OUT / "mobile.png"), full_page=True)
mobile_overflow = await page.evaluate("document.documentElement.scrollWidth > innerWidth")
# Failure tests use browser request routing, never stop shared models.
await page.route("**/api/offer", lambda route: route.abort())
await page.click("#retry")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('已停止交谈')", timeout=30000
)
await page.unroute("**/api/offer")
await page.click("#retry")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('正在听')", timeout=30000
)
await context.set_offline(True)
await page.wait_for_timeout(500)
assert await page.locator("#talk").evaluate("(v)=>v.srcObject===null")
await context.set_offline(False)
await page.reload()
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('就绪')"
)
# This is a handler test, not a claim of real OS background testing.
await page.evaluate(
"Object.defineProperty(document,'hidden',{configurable:true,value:true});document.dispatchEvent(new Event('visibilitychange'))"
)
assert await page.locator("#daily").evaluate("(v)=>v.paused")
await page.evaluate(
"Object.defineProperty(document,'hidden',{configurable:true,value:false})"
)
await page.route("**/reading-rain-night.mp4", lambda route: route.abort())
await page.reload()
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('素材丢失')", timeout=30000
)
result = {
"pageerrors": errors,
"mobile_overflow": mobile_overflow,
"visibility_test": "synthetic event only; real OS background not tested",
"cancel": "speaking and preparing",
"network": "offer abort, offline, recovery",
"missing_asset": "daily video request abort",
"time": time.time(),
}
# Events from the main continuous recording were captured before reload.
(OUT / "browser-check.json").write_text(json.dumps(result, ensure_ascii=False, indent=2))
await browser.close()
print(json.dumps(result, ensure_ascii=False), flush=True)
asyncio.run(main())
+127
View File
@@ -0,0 +1,127 @@
"""Cancellation/voice checks against local fake HTTP services, no paid APIs."""
import asyncio
import importlib.util
import pathlib
import unittest
from aiohttp import web
from aiohttp.test_utils import TestServer
spec = importlib.util.spec_from_file_location(
"sample_server", pathlib.Path(__file__).resolve().parents[1] / "runtime/server.py"
)
server = importlib.util.module_from_spec(spec)
spec.loader.exec_module(server)
class GatewayChecks(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.started = asyncio.Event()
self.release = asyncio.Event()
self.mode = "llm"
self.voice = "xiaoyun"
self.queued = 0
self.closed = []
app = web.Application()
async def health(request):
return web.json_response({"ok": True, "voices": [self.voice]})
async def llm(request):
if self.mode == "llm":
self.started.set()
await self.release.wait()
return web.json_response({"choices": [{"message": {"content": "你好。"}}]})
async def tts(request):
self.started.set()
await self.release.wait()
return web.Response(body=b"\0\0" * 2400)
async def audio(request):
self.queued += 1
return web.json_response({"code": 0})
async def close(request):
self.closed.append((await request.json())["sessionid"])
return web.json_response({"closed": True})
app.router.add_get("/health", health)
app.router.add_post("/llm", llm)
app.router.add_post("/tts", tts)
app.router.add_post("/humanaudio", audio)
app.router.add_post("/hel714/close", close)
self.upstream = TestServer(app)
await self.upstream.start_server()
base = str(self.upstream.make_url("")).rstrip("/")
self.gateway = server.Gateway(
{
"driver": base,
"llm": base + "/llm",
"model": "fixture",
"tts": base,
"voice": "xiaoyun",
}
)
await self.gateway.start(None)
async def asyncTearDown(self):
self.release.set()
await self.gateway.stop(None)
await self.upstream.close()
async def cancel_at(self, mode):
self.mode = mode
session = {"sid": "old-session", "task": None}
self.gateway.sessions["old-token"] = session
task = session["task"] = asyncio.create_task(self.gateway.reply(session, "测试"))
await asyncio.wait_for(self.started.wait(), 2)
await self.gateway.retire("old-token")
self.assertTrue(task.cancelled())
self.release.set()
await asyncio.sleep(0.05)
self.assertEqual(self.queued, 0)
self.assertEqual(self.closed, ["old-session"])
self.assertNotIn("old-token", self.gateway.sessions)
# Idempotence: a late duplicate cancel cannot close a new session.
self.gateway.sessions["new-token"] = {"sid": "new-session", "task": None}
await self.gateway.retire("old-token")
self.assertIn("new-token", self.gateway.sessions)
async def test_cancel_during_llm(self):
await self.cancel_at("llm")
async def test_cancel_during_tts(self):
await self.cancel_at("tts")
async def test_missing_voice_is_explicit(self):
self.voice = "default"
with self.assertRaisesRegex(RuntimeError, "未回退"):
await self.gateway.reply({"sid": "test"}, "测试")
self.assertEqual(self.queued, 0)
async def test_cancel_while_waiting_for_media_ready(self):
self.mode = "tts"
session = {"sid": "old-session", "task": None, "ready": asyncio.Event()}
self.gateway.sessions["old-token"] = session
task = session["task"] = asyncio.create_task(self.gateway.reply(session, "测试"))
await asyncio.wait_for(self.started.wait(), 2)
self.release.set()
await asyncio.sleep(0.05)
self.assertEqual(self.queued, 0)
await self.gateway.retire("old-token")
session["ready"].set()
await asyncio.sleep(0.05)
self.assertTrue(task.cancelled())
self.assertEqual(self.queued, 0)
async def test_model_unreachable(self):
self.gateway.config["llm"] = "http://127.0.0.1:1/unavailable"
with self.assertRaises(server.aiohttp.ClientError):
await self.gateway.reply({"sid": "unreachable"}, "测试")
self.assertEqual(self.queued, 0)
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -0,0 +1,89 @@
"""Synthetic WAV through Chromium's microphone device, not a human VAD pass."""
import asyncio
import json
import pathlib
from playwright.async_api import async_playwright
ROOT = pathlib.Path(__file__).resolve().parents[1]
OUT = ROOT / "evidence"
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(
args=[
"--no-sandbox",
"--autoplay-policy=no-user-gesture-required",
"--use-fake-device-for-media-stream",
"--use-fake-ui-for-media-stream",
f"--use-file-for-fake-audio-capture={OUT / 'synthetic-microphone.wav'}%noloop",
]
)
context = await browser.new_context(ignore_https_errors=True, permissions=["microphone"])
page = await context.new_page()
errors = []
page.on("pageerror", lambda error: errors.append(str(error)))
await page.goto("https://192.168.200.12:8014")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('就绪')"
)
await page.click("#enter")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('正在听')", timeout=40000
)
await page.click("#record")
await page.click("#mic")
await page.wait_for_function(
"document.querySelector('#mic').getAttribute('aria-pressed')==='true'"
)
await page.fill("#text", "请用三句话描述你眼前卧室的温暖氛围,大约六十个字。")
await page.click("button[type=submit]")
await page.wait_for_function(
"window.sampleEvents.some(e=>e.event==='cancel'&&e.detail.reason==='microphone-onset')",
timeout=25000,
)
await page.wait_for_function(
"document.querySelector('#transcript').textContent.includes('识别:')", timeout=15000
)
await page.wait_for_function(
"window.sampleEvents.filter(e=>e.event==='input-finished').length>=2", timeout=15000
)
await page.wait_for_timeout(18000)
await page.click("#record")
await page.wait_for_selector("#download:not([hidden])")
async with page.expect_download() as pending:
await page.click("#download")
await (await pending.value).save_as(OUT / "synthetic-microphone-av.webm")
events = await page.evaluate("window.sampleEvents")
onset = next(
e["at"]
for e in events
if e["event"] == "cancel" and e["detail"]["reason"] == "microphone-onset"
)
audible_before = [e for e in events if e["event"] == "first-audible" and e["at"] < onset]
audible_after = [e for e in events if e["event"] == "first-audible" and e["at"] > onset]
result = dict(
fixture="CosyVoice synthesized WAV through fake Chromium microphone; no human recording",
secure_context=await page.evaluate("isSecureContext"),
transcript=await page.locator("#transcript").inner_text(),
speech_was_audible_before_onset=bool(audible_before),
new_reply_after_asr=bool(audible_after),
events=events,
pageerrors=errors,
)
(OUT / "synthetic-microphone.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2)
)
await page.click("#mic")
await page.click("#back")
await page.wait_for_timeout(4000)
await browser.close()
print(
json.dumps({k: v for k, v in result.items() if k != "events"}, ensure_ascii=False),
flush=True,
)
asyncio.run(main())
+52
View File
@@ -0,0 +1,52 @@
"""Cancel during ICE/offer, then verify a late old error cannot stop a new turn."""
import asyncio
import json
import pathlib
from playwright.async_api import async_playwright
OUT = pathlib.Path(__file__).resolve().parents[1] / "evidence"
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(
args=["--no-sandbox", "--autoplay-policy=no-user-gesture-required"]
)
context = await browser.new_context(ignore_https_errors=True)
page = await context.new_page()
errors = []
page.on("pageerror", lambda e: errors.append(str(e)))
await page.goto("https://192.168.200.12:8014")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('就绪')"
)
await page.click("#enter")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('正在听')", timeout=40000
)
await page.fill("#text", "这一轮马上取消。")
await page.click("button[type=submit]")
await page.wait_for_timeout(100)
await page.click("#cancel")
await page.fill("#text", "新一轮只回复:你好。")
await page.click("button[type=submit]")
await page.wait_for_function(
"window.sampleEvents.some(e=>e.event==='first-audible')", timeout=45000
)
await page.wait_for_timeout(10000)
events = await page.evaluate("window.sampleEvents")
failures = [
e for e in events if e["event"] == "status" and "媒体协商超时" in str(e["detail"])
]
result = {"pageerrors": errors, "late_error_failures": failures, "events": events}
(OUT / "race-check.json").write_text(json.dumps(result, ensure_ascii=False, indent=2))
assert not failures
await page.click("#back")
await page.wait_for_timeout(4000)
await browser.close()
print("ICE cancellation race passed", flush=True)
asyncio.run(main())
@@ -0,0 +1,251 @@
"""Generate one v2 gaze idle and two forward first/last-frame transitions.
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 = Path("/opt/hel714-material")
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(kind):
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="start.png")
add(17, "LoadImage", image="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 gently raises her gaze from the book to meet the viewer, then holds a calm listening gaze. "
"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=714,
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=714,
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="enter", crf=20.0)
nodes["9"]["inputs"]["image"] = "daily-cut.png" if kind == "enter" else "near.png"
nodes["17"]["inputs"]["image"] = "daily-cut.png" if kind == "return" else "near.png"
nodes["10"]["inputs"]["text"] = {
"enter": "Photorealistic adult woman, same short dark hair, cream cardigan, same bedroom. Starting from reading, she gently raises her head to meet the viewer. Smooth slow camera push toward her half body, ending at the exact reference framing. Hands keep holding the same book. Continuous physically plausible movement, stable face, stable clothing and light.",
"return": "Photorealistic adult woman, same short dark hair, cream cardigan, same bedroom. She gently lowers her gaze to the book and returns to reading, with a smooth slow camera pull back to the exact final reference. Same hands holding the same book, continuous physically plausible movement, stable face, stable clothing and light.",
"idle": "Locked camera, photorealistic adult woman in cream cardigan in the same bedroom. Calmly looks toward the viewer, lips gently closed, one subtle natural blink and breathing. Keeps holding the open book still. Stable face, clothing, seat, camera, light and room.",
}[kind]
nodes["11"]["inputs"]["text"] = (
"changing identity, changing clothes, extra fingers, distorted hands, deformed face, melting furniture, subtitles, speaking mouth"
)
nodes["12"]["inputs"]["length"] = 81 if kind == "idle" else 49
nodes["16"]["inputs"]["filename_prefix"] = kind
return nodes
def main():
(TASK / "assets").mkdir(parents=True, exist_ok=True)
# Explicit first/last frames are prepared from the approved v2 source.
assert (TASK / "assets/daily-cut.png").exists()
assert (TASK / "assets/near.png").exists()
if list(TASK.glob("*-history.json")):
raise RuntimeError("Use a new task directory; existing generation evidence is preserved")
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)
for kind in ["idle", "enter", "return"]:
workflow = graph(kind)
(TASK / f"{kind}-workflow.json").write_text(json.dumps(workflow, indent=2))
required = {n["class_type"]: info.get(n["class_type"]) for n in workflow.values()}
(TASK / f"{kind}-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 / f"{kind}-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 / f"{kind}-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__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--task", type=Path, default=TASK)
TASK = parser.parse_args().task
main()
+41
View File
@@ -0,0 +1,41 @@
"""Verify a whole versioned pack before building or rolling back.
Material versions and outfit labels are independent of the stable companion id.
This command never writes identity, bazi, memory or relationship state.
"""
import argparse
import hashlib
import json
from pathlib import Path
def verify(root):
root = root.resolve()
manifest = json.loads((root / "manifest.json").read_text())
assert manifest["version"] and manifest["persona_id"]
assert manifest["companion_id"] == "wanwan", "Companion identity cannot change with assets"
files = [manifest["identity_ref"]]
files += [c["file"] for c in manifest["daily_clips"] + manifest["talk_clips"]]
transition = manifest.get("transition", {})
if transition.get("available"):
files += [transition["enter"], transition["return"]]
for name in files:
assert name in manifest["sha256"], f"No checksum: {name}"
for name, checksum in manifest["sha256"].items():
path = (root / name).resolve()
assert path.is_relative_to(root), f"Unsafe asset path: {name}"
assert hashlib.sha256(path.read_bytes()).hexdigest() == checksum, name
return manifest
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--assets",
type=Path,
default=Path(__file__).resolve().parents[1] / "assets/personas/wanwan-v2-cream-night",
)
args = parser.parse_args()
manifest = verify(args.assets)
print("Verified asset pack:", manifest["version"], len(manifest["sha256"]), "files")
+47
View File
@@ -0,0 +1,47 @@
"""Apply only to a private c726943 code copy, never the reused installation.
The extra endpoint destroys one owned peer rather than reusing partially flushed
queues. The caller must retain the randomly generated session id.
"""
import argparse
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("copy", type=Path)
args = parser.parse_args()
root = args.copy.resolve()
if root == Path("/opt/hel715-verify/LiveTalking"):
raise SystemExit("Refusing to edit reused P10 installation")
p = root / "server/rtc_manager.py"
s = p.read_text()
needle = " self.pcs.add(pc)"
replacement = needle + "\n pc.hel714_sessionid = sessionid"
if replacement not in s:
assert s.count(needle) >= 1
p.write_text(s.replace(needle, replacement, 1))
p = root / "app.py"
s = p.read_text()
needle = " setup_routes(appasync)"
replacement = (
""" async def hel714_close(request):
params = await request.json()
sid = params['sessionid']
session = session_manager.get_session(sid)
if session:
session.flush_talk()
for peer in list(rtc_manager.pcs):
if getattr(peer, 'hel714_sessionid', None) == sid:
await peer.close()
rtc_manager.pcs.discard(peer)
session_manager.remove_session(sid)
return web.json_response({'closed': sid})
appasync.router.add_post('/hel714/close', hel714_close)
"""
+ needle
)
if replacement not in s:
assert s.count(needle) >= 1
p.write_text(s.replace(needle, replacement, 1))
print("Installed HEL-714 peer retirement endpoint in private copy:", root)
+26
View File
@@ -0,0 +1,26 @@
"""Create a private code copy; symlink only existing weights, never overwrite."""
import argparse
import shutil
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("--source", type=Path, default=Path("/opt/hel715-verify/LiveTalking"))
parser.add_argument("--destination", type=Path, required=True)
args = parser.parse_args()
source, destination = args.source.resolve(), args.destination.resolve()
assert source != destination and not destination.exists(), "Destination must be new"
def ignore(directory, names):
excluded = {n for n in names if n == "__pycache__" or n.endswith(".log")}
if Path(directory).resolve() == source:
excluded.update({"models", "data", ".git"})
return excluded
shutil.copytree(source, destination, ignore=ignore)
(destination / "models").symlink_to(source / "models", target_is_directory=True)
(destination / "data/avatars").mkdir(parents=True)
print("Private driver code:", destination)
print("Weights reused read-only by convention:", source / "models")
@@ -0,0 +1,37 @@
"""Convert the three generated candidates to 25fps; retain real forward motion."""
import json
from pathlib import Path
import av
import numpy as np
from PIL import Image, ImageDraw
root = Path("/opt/hel714-material")
assets = Path("/opt/hel714-sample/dist/assets")
metrics = {}
sheet = Image.new("RGB", (7 * 220, 3 * 245))
draw = ImageDraw.Draw(sheet)
for row, (kind, name) in enumerate([("idle", "talk"), ("enter", "enter"), ("return", "return")]):
source = next(root.glob(f"{kind}_*.webm"))
frames = [f.to_image() for f in av.open(str(source)).decode(video=0)]
out = av.open(str(assets / f"{name}.mp4"), "w")
stream = out.add_stream("libx264", rate=25)
stream.width = stream.height = 512
stream.pix_fmt = "yuv420p"
stream.options = {"crf": "18", "preset": "fast"}
count = round(len(frames) * 25 / 16)
for i in range(count):
frame = av.VideoFrame.from_image(frames[min(len(frames) - 1, int(i * 16 / 25))])
for packet in stream.encode(frame):
out.mux(packet)
for packet in stream.encode():
out.mux(packet)
out.close()
for column, index in enumerate(np.linspace(0, len(frames) - 1, 7).astype(int)):
sheet.paste(frames[index].resize((220, 220)), (column * 220, row * 245))
draw.text((column * 220, row * 245 + 222), f"{kind} f{index}", fill="white")
metrics[kind] = {"input_frames": len(frames), "output_frames": count, "seconds": count / 25}
sheet.save(root / "candidate-contact.png")
(root / "candidate-metrics.json").write_text(json.dumps(metrics, indent=2))
print(metrics)
+85
View File
@@ -0,0 +1,85 @@
"""Ten-minute real browser / local model session, sampled resource evidence."""
import asyncio
import json
import pathlib
import subprocess
import time
from playwright.async_api import async_playwright
OUT = pathlib.Path(__file__).resolve().parents[1] / "evidence"
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(
args=["--no-sandbox", "--autoplay-policy=no-user-gesture-required"]
)
context = await browser.new_context(ignore_https_errors=True)
page = await context.new_page()
errors = []
page.on("pageerror", lambda error: errors.append(str(error)))
await page.goto("https://192.168.200.12:8014")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('就绪')"
)
await page.click("#enter")
await page.wait_for_function(
"document.querySelector('#status').textContent.includes('正在听')", timeout=40000
)
start = time.monotonic()
samples = []
for index in range(15):
text = f"这是第{index + 1}次交谈。请只回复一句不超过十五个字的自然中文。"
await page.fill("#text", text)
await page.click("button[type=submit]")
for _tick in range(4):
await page.wait_for_timeout(10000)
state = await page.evaluate("""()=>({status:document.querySelector('#status').textContent,
videoTime:document.querySelector('#talk').currentTime,
frames:document.querySelector('#talk').getVideoPlaybackQuality().totalVideoFrames,
events:window.sampleEvents.slice(-3)})""")
gpu = subprocess.run(
[
"ssh",
"root@192.168.200.12",
"nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits",
],
capture_output=True,
text=True,
check=True,
).stdout.strip()
sample = dict(
elapsed=round(time.monotonic() - start, 2), turn=index + 1, state=state, gpu=gpu
)
samples.append(sample)
(OUT / "soak-progress.json").write_text(
json.dumps(samples, ensure_ascii=False, indent=2)
)
print(
"soak",
index + 1,
"elapsed",
round(time.monotonic() - start),
"status",
state["status"],
"gpu",
gpu,
flush=True,
)
result = dict(
duration_seconds=round(time.monotonic() - start, 2),
samples=samples,
events=await page.evaluate("window.sampleEvents"),
pageerrors=errors,
scope="One logical session, peer retired each turn by cancellation design; 15 real LLM/TTS/avatar turns",
)
(OUT / "soak.json").write_text(json.dumps(result, ensure_ascii=False, indent=2))
await page.click("#back")
await page.wait_for_timeout(4000)
await browser.close()
print("SOAK COMPLETE", result["duration_seconds"], len(errors), flush=True)
asyncio.run(main())
+24
View File
@@ -0,0 +1,24 @@
"""Mount the verified active persona pack at the sample's /assets URL.
public/assets is generated build output. Canonical user-replaceable packs live
under assets/personas; no identity or companion-state file is touched.
"""
import json
import shutil
from pathlib import Path
from pack_assets import verify
root = Path(__file__).resolve().parents[1]
active = json.loads((root / "assets/active.json").read_text())
source = (root / "assets/personas" / active["persona_id"]).resolve()
assert source.is_relative_to((root / "assets/personas").resolve())
manifest = verify(source)
assert manifest["persona_id"] == active["persona_id"]
destination = root / "public/assets"
assert not destination.is_symlink(), "Generated asset mount must not be a symlink"
if destination.exists():
shutil.rmtree(destination)
shutil.copytree(source, destination)
print("Staged complete asset pack:", manifest["persona_id"], manifest["version"])