#!/usr/bin/env python3 """参考帧预加载回归:上传视频后画布应立刻显示一帧现场画面,便于标定区域。 断言: 1. 上传后自动铺上参考帧(画布有实际画面内容,而不是黑屏) 2. 画布尺寸 == 视频原始分辨率(保证区域坐标不走样) 3. 底图 + 区域叠加可以同时出现 4. 「抓取」按钮能跳到指定时间点并更新画面 5. 关闭再打开「显示区域」,底图不会丢失 """ import asyncio import json import subprocess import sys import time import urllib.request from pathlib import Path import websockets CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" BASE = "http://127.0.0.1:8811" VIDEO = "/Users/wenhongquan/Documents/trae_projects/yolo/output_video.mp4" # 画布内容统计:非空像素 / 平均亮度 / 尺寸 CANVAS = """(() => { const c = document.getElementById('stage'); const d = c.getContext('2d').getImageData(0,0,c.width,c.height).data; let opaque=0, lum=0; for (let i=0;i { const c = document.getElementById('stage'); const d = c.getContext('2d').getImageData(0,0,c.width,c.height).data; let h = 2166136261; for (let i = 0; i < d.length; i += 97) { h ^= d[i]; h = Math.imul(h, 16777619); } return (h >>> 0).toString(16); })()""" def upload(path: Path): b = "----frameCheck" buf = bytearray() buf += f"--{b}\r\n".encode() buf += f'Content-Disposition: form-data; name="file"; filename="{path.name}"\r\n'.encode() buf += b"Content-Type: video/mp4\r\n\r\n" + path.read_bytes() buf += f"\r\n--{b}--\r\n".encode() r = urllib.request.Request(BASE + "/api/upload", data=bytes(buf), method="POST") r.add_header("Content-Type", f"multipart/form-data; boundary={b}") with urllib.request.urlopen(r, timeout=300) as x: return json.loads(x.read()) async def main(): meta = upload(Path(VIDEO)) print(f"上传完成:{meta['filename']} {meta['width']}x{meta['height']} {meta['duration']}s (会话 {meta['id']})\n") proc = subprocess.Popen( [CHROME, "--headless=new", "--disable-gpu", "--no-sandbox", "--remote-debugging-port=9360", "--window-size=1500,1000", "--user-data-dir=/tmp/dccai-frame", "about:blank"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(80): try: urllib.request.urlopen("http://127.0.0.1:9360/json/version", timeout=1) break except Exception: time.sleep(0.4) passed = 0 total = 0 try: tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9360/json").read()) page = next(t for t in tabs if t["type"] == "page") async with websockets.connect(page["webSocketDebuggerUrl"], max_size=64 << 20) as ws: n = [0] async def send(m, **pr): n[0] += 1 mid = n[0] await ws.send(json.dumps({"id": mid, "method": m, "params": pr})) while True: r = json.loads(await ws.recv()) if r.get("id") == mid: return r.get("result", {}) async def js(e, ap=False): r = await send("Runtime.evaluate", expression=e, returnByValue=True, awaitPromise=ap, userGesture=True) if r.get("exceptionDetails"): return None return r.get("result", {}).get("value") def chk(label, cond, extra=""): nonlocal passed, total total += 1 print((" ✅ " if cond else " ❌ ") + label + (f" {extra}" if extra else "")) if cond: passed += 1 await send("Page.enable") await send("Runtime.enable") await send("Page.navigate", url=BASE + "/") await asyncio.sleep(5) # 等参考帧铺上 for _ in range(40): await asyncio.sleep(0.5) if (await js("(JSON.parse(%s)).opaque" % json.dumps(CANVAS)) or 0) > 0: break print("1) 上传后自动预加载参考帧") a = json.loads(await js(CANVAS)) chk("画布非空(有画面)", a["opaque"] > 0, str(a)) chk("画面不是纯黑(亮度 > 20)", a["lum"] > 20, f"亮度={a['lum']}") chk("画布尺寸=视频原始分辨率", a["w"] == meta["width"] and a["h"] == meta["height"], f"{a['w']}x{a['h']} vs {meta['width']}x{meta['height']}") # 用哈希判定叠加层有无/残留(与画面内容无关) h_default = await js(HASH) # 页面默认状态(未做持久化,必为关闭) await js("(()=>{const c=document.getElementById('chkShowRegions'); if(c.checked) c.click();})()") await asyncio.sleep(1) h_off = await js(HASH) chk("默认状态就是「不显示区域」", h_default == h_off, f"{h_default} vs {h_off}") print("\n2) 打开「显示区域」→ 底图与叠加层共存") await js("document.getElementById('chkShowRegions').click()") await asyncio.sleep(1) h_on = await js(HASH) b = json.loads(await js(CANVAS)) chk("叠加层生效(画面发生变化)", h_on != h_off, f"{h_off} → {h_on}") chk("底图仍在(亮度接近)", abs(b["lum"] - a["lum"]) < 30, f"{a['lum']}→{b['lum']}") print("\n3) 「抓取」跳到指定时间点") t0 = await js("document.getElementById('frameTime').value") await js("(()=>{const i=document.getElementById('frameTime'); i.value='40';})()") await js("document.getElementById('btnGrabFrame').click()") await asyncio.sleep(3) t1 = await js("document.getElementById('frameTime').value") c1 = json.loads(await js(CANVAS)) chk("时间回填为 40s 附近", t1 and abs(float(t1) - 40) < 2, f"{t0} → {t1}") chk("画面已更新且非空", c1["opaque"] > 0, str(c1)) print("\n4) 同一帧上反复开关「显示区域」:无残留、可完全复原") # 确保当前为「显示」状态,取基准 await js("(()=>{const c=document.getElementById('chkShowRegions'); if(!c.checked) c.click();})()") await asyncio.sleep(1) h_on_ref = await js(HASH) await js("document.getElementById('chkShowRegions').click()") # → 关 await asyncio.sleep(1) h_off_ref = await js(HASH) await js("document.getElementById('chkShowRegions').click()") # → 开 await asyncio.sleep(1) h_on2 = await js(HASH) await js("document.getElementById('chkShowRegions').click()") # → 关 await asyncio.sleep(1) h_off2 = await js(HASH) chk("开关确实改变画面", h_on_ref != h_off_ref, f"{h_off_ref} vs {h_on_ref}") chk("再开启与首次开启逐像素一致(无累积残影)", h_on2 == h_on_ref, f"{h_on2} vs {h_on_ref}") chk("再关闭与首次关闭逐像素一致(无残留叠加)", h_off2 == h_off_ref, f"{h_off2} vs {h_off_ref}") finally: proc.terminate() print(f"\n结果:{passed}/{total} 通过") return 0 if passed == total else 1 sys.exit(asyncio.run(main()))