feat(hel715): LiveTalking+MuseTalk verification kit (report, material spec, e2e scripts)
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -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>
|
||||
@@ -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())
|
||||
Reference in New Issue
Block a user