frame_check.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #!/usr/bin/env python3
  2. """参考帧预加载回归:上传视频后画布应立刻显示一帧现场画面,便于标定区域。
  3. 断言:
  4. 1. 上传后自动铺上参考帧(画布有实际画面内容,而不是黑屏)
  5. 2. 画布尺寸 == 视频原始分辨率(保证区域坐标不走样)
  6. 3. 底图 + 区域叠加可以同时出现
  7. 4. 「抓取」按钮能跳到指定时间点并更新画面
  8. 5. 关闭再打开「显示区域」,底图不会丢失
  9. """
  10. import asyncio
  11. import json
  12. import subprocess
  13. import sys
  14. import time
  15. import urllib.request
  16. from pathlib import Path
  17. import websockets
  18. CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
  19. BASE = "http://127.0.0.1:8811"
  20. VIDEO = "/Users/wenhongquan/Documents/trae_projects/yolo/output_video.mp4"
  21. # 画布内容统计:非空像素 / 平均亮度 / 尺寸
  22. CANVAS = """(() => {
  23. const c = document.getElementById('stage');
  24. const d = c.getContext('2d').getImageData(0,0,c.width,c.height).data;
  25. let opaque=0, lum=0;
  26. for (let i=0;i<d.length;i+=4){
  27. if (d[i+3] <= 8) continue;
  28. opaque++; lum += (d[i]+d[i+1]+d[i+2])/3;
  29. }
  30. return JSON.stringify({w:c.width, h:c.height, opaque, lum:Math.round(lum/Math.max(1,opaque))});
  31. })()"""
  32. # 画布内容哈希:用于判定「叠加层是否残留」——与画面颜色无关,避免与视频内容撞色误判
  33. HASH = """(() => {
  34. const c = document.getElementById('stage');
  35. const d = c.getContext('2d').getImageData(0,0,c.width,c.height).data;
  36. let h = 2166136261;
  37. for (let i = 0; i < d.length; i += 97) { h ^= d[i]; h = Math.imul(h, 16777619); }
  38. return (h >>> 0).toString(16);
  39. })()"""
  40. def upload(path: Path):
  41. b = "----frameCheck"
  42. buf = bytearray()
  43. buf += f"--{b}\r\n".encode()
  44. buf += f'Content-Disposition: form-data; name="file"; filename="{path.name}"\r\n'.encode()
  45. buf += b"Content-Type: video/mp4\r\n\r\n" + path.read_bytes()
  46. buf += f"\r\n--{b}--\r\n".encode()
  47. r = urllib.request.Request(BASE + "/api/upload", data=bytes(buf), method="POST")
  48. r.add_header("Content-Type", f"multipart/form-data; boundary={b}")
  49. with urllib.request.urlopen(r, timeout=300) as x:
  50. return json.loads(x.read())
  51. async def main():
  52. meta = upload(Path(VIDEO))
  53. print(f"上传完成:{meta['filename']} {meta['width']}x{meta['height']} {meta['duration']}s (会话 {meta['id']})\n")
  54. proc = subprocess.Popen(
  55. [CHROME, "--headless=new", "--disable-gpu", "--no-sandbox",
  56. "--remote-debugging-port=9360", "--window-size=1500,1000",
  57. "--user-data-dir=/tmp/dccai-frame", "about:blank"],
  58. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  59. for _ in range(80):
  60. try:
  61. urllib.request.urlopen("http://127.0.0.1:9360/json/version", timeout=1)
  62. break
  63. except Exception:
  64. time.sleep(0.4)
  65. passed = 0
  66. total = 0
  67. try:
  68. tabs = json.loads(urllib.request.urlopen("http://127.0.0.1:9360/json").read())
  69. page = next(t for t in tabs if t["type"] == "page")
  70. async with websockets.connect(page["webSocketDebuggerUrl"], max_size=64 << 20) as ws:
  71. n = [0]
  72. async def send(m, **pr):
  73. n[0] += 1
  74. mid = n[0]
  75. await ws.send(json.dumps({"id": mid, "method": m, "params": pr}))
  76. while True:
  77. r = json.loads(await ws.recv())
  78. if r.get("id") == mid:
  79. return r.get("result", {})
  80. async def js(e, ap=False):
  81. r = await send("Runtime.evaluate", expression=e, returnByValue=True,
  82. awaitPromise=ap, userGesture=True)
  83. if r.get("exceptionDetails"):
  84. return None
  85. return r.get("result", {}).get("value")
  86. def chk(label, cond, extra=""):
  87. nonlocal passed, total
  88. total += 1
  89. print((" ✅ " if cond else " ❌ ") + label + (f" {extra}" if extra else ""))
  90. if cond:
  91. passed += 1
  92. await send("Page.enable")
  93. await send("Runtime.enable")
  94. await send("Page.navigate", url=BASE + "/")
  95. await asyncio.sleep(5)
  96. # 等参考帧铺上
  97. for _ in range(40):
  98. await asyncio.sleep(0.5)
  99. if (await js("(JSON.parse(%s)).opaque" % json.dumps(CANVAS)) or 0) > 0:
  100. break
  101. print("1) 上传后自动预加载参考帧")
  102. a = json.loads(await js(CANVAS))
  103. chk("画布非空(有画面)", a["opaque"] > 0, str(a))
  104. chk("画面不是纯黑(亮度 > 20)", a["lum"] > 20, f"亮度={a['lum']}")
  105. chk("画布尺寸=视频原始分辨率", a["w"] == meta["width"] and a["h"] == meta["height"],
  106. f"{a['w']}x{a['h']} vs {meta['width']}x{meta['height']}")
  107. # 用哈希判定叠加层有无/残留(与画面内容无关)
  108. h_default = await js(HASH) # 页面默认状态(未做持久化,必为关闭)
  109. await js("(()=>{const c=document.getElementById('chkShowRegions'); if(c.checked) c.click();})()")
  110. await asyncio.sleep(1)
  111. h_off = await js(HASH)
  112. chk("默认状态就是「不显示区域」", h_default == h_off, f"{h_default} vs {h_off}")
  113. print("\n2) 打开「显示区域」→ 底图与叠加层共存")
  114. await js("document.getElementById('chkShowRegions').click()")
  115. await asyncio.sleep(1)
  116. h_on = await js(HASH)
  117. b = json.loads(await js(CANVAS))
  118. chk("叠加层生效(画面发生变化)", h_on != h_off, f"{h_off} → {h_on}")
  119. chk("底图仍在(亮度接近)", abs(b["lum"] - a["lum"]) < 30, f"{a['lum']}→{b['lum']}")
  120. print("\n3) 「抓取」跳到指定时间点")
  121. t0 = await js("document.getElementById('frameTime').value")
  122. await js("(()=>{const i=document.getElementById('frameTime'); i.value='40';})()")
  123. await js("document.getElementById('btnGrabFrame').click()")
  124. await asyncio.sleep(3)
  125. t1 = await js("document.getElementById('frameTime').value")
  126. c1 = json.loads(await js(CANVAS))
  127. chk("时间回填为 40s 附近", t1 and abs(float(t1) - 40) < 2, f"{t0} → {t1}")
  128. chk("画面已更新且非空", c1["opaque"] > 0, str(c1))
  129. print("\n4) 同一帧上反复开关「显示区域」:无残留、可完全复原")
  130. # 确保当前为「显示」状态,取基准
  131. await js("(()=>{const c=document.getElementById('chkShowRegions'); if(!c.checked) c.click();})()")
  132. await asyncio.sleep(1)
  133. h_on_ref = await js(HASH)
  134. await js("document.getElementById('chkShowRegions').click()") # → 关
  135. await asyncio.sleep(1)
  136. h_off_ref = await js(HASH)
  137. await js("document.getElementById('chkShowRegions').click()") # → 开
  138. await asyncio.sleep(1)
  139. h_on2 = await js(HASH)
  140. await js("document.getElementById('chkShowRegions').click()") # → 关
  141. await asyncio.sleep(1)
  142. h_off2 = await js(HASH)
  143. chk("开关确实改变画面", h_on_ref != h_off_ref, f"{h_off_ref} vs {h_on_ref}")
  144. chk("再开启与首次开启逐像素一致(无累积残影)", h_on2 == h_on_ref,
  145. f"{h_on2} vs {h_on_ref}")
  146. chk("再关闭与首次关闭逐像素一致(无残留叠加)", h_off2 == h_off_ref,
  147. f"{h_off2} vs {h_off_ref}")
  148. finally:
  149. proc.terminate()
  150. print(f"\n结果:{passed}/{total} 通过")
  151. return 0 if passed == total else 1
  152. sys.exit(asyncio.run(main()))