ui_check.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #!/usr/bin/env python3
  2. """真实浏览器 UI 断言(本地 Chrome + CDP,无需 Playwright)。
  3. 覆盖「区域显示/隐藏/清空」的关键回归:
  4. A 刚加载会话 → 默认不显示区域,画布干净
  5. B 开启「显示区域」→ 区域出现
  6. C 识别运行中 → 后端帧不再烧录区域;区域按钮被锁定
  7. D 停止 → 按钮解锁
  8. E 关闭「显示区域」→ 画布上区域彻底消失(不残留)
  9. F 清空全部区域 → 区域数为 0,再开启显示仍无任何区域
  10. """
  11. import asyncio
  12. import json
  13. import subprocess
  14. import sys
  15. import time
  16. import urllib.request
  17. from pathlib import Path
  18. import websockets
  19. BASE = "http://127.0.0.1:8811"
  20. VIDEO = "/Users/wenhongquan/Documents/trae_projects/yolo/output_video.mp4"
  21. CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
  22. PORT = 9333
  23. """只统计「区域叠加层调色板」的像素,避免把视频画面本身的彩色算进来。
  24. 前端 paintOverlay() 用固定描边色:施工区/仓储区/禁区/机械区/高处区/计数线。
  25. """
  26. # 说明:视频画面本身/检测框可能偶然命中调色板(实测该测试视频约 255 像素,
  27. # 而「显示区域」打开时是 ~12000 像素,相差近 50 倍),故用 NOISE 容差判定。
  28. NOISE = 400
  29. COLORED = """(() => {
  30. const c = document.getElementById('stage');
  31. const d = c.getContext('2d').getImageData(0,0,c.width,c.height).data;
  32. const pal = [[0x3c,0xb4,0x5a],[0xb4,0x8c,0x3c],[0xdc,0x3c,0x3c],
  33. [0xdc,0x78,0x30],[0xc8,0x50,0xc8],[0x00,0xff,0xff]];
  34. let any=0, col=0;
  35. for (let i=0;i<d.length;i+=4){
  36. if (d[i+3]<=8) continue; any++;
  37. const r=d[i],g=d[i+1],b=d[i+2];
  38. for (const p of pal){
  39. if (Math.abs(r-p[0])<26 && Math.abs(g-p[1])<26 && Math.abs(b-p[2])<26){ col++; break; }
  40. }
  41. }
  42. return JSON.stringify({any, regionPixels: col});
  43. })()"""
  44. def req(method, path, data=None):
  45. body = json.dumps(data).encode() if data is not None else None
  46. r = urllib.request.Request(BASE + path, data=body, method=method)
  47. if data is not None:
  48. r.add_header("Content-Type", "application/json")
  49. with urllib.request.urlopen(r, timeout=120) as x:
  50. return json.loads(x.read() or b"{}")
  51. def upload(path: Path):
  52. b = "----uiCheck"
  53. buf = bytearray()
  54. buf += f"--{b}\r\n".encode()
  55. buf += f'Content-Disposition: form-data; name="file"; filename="{path.name}"\r\n'.encode()
  56. buf += b"Content-Type: video/mp4\r\n\r\n" + path.read_bytes()
  57. buf += f"\r\n--{b}--\r\n".encode()
  58. r = urllib.request.Request(BASE + "/api/upload", data=bytes(buf), method="POST")
  59. r.add_header("Content-Type", f"multipart/form-data; boundary={b}")
  60. with urllib.request.urlopen(r, timeout=300) as x:
  61. return json.loads(x.read())
  62. def launch():
  63. p = subprocess.Popen(
  64. [CHROME, "--headless=new", "--disable-gpu", "--no-sandbox",
  65. f"--remote-debugging-port={PORT}", "--window-size=1500,1000",
  66. "--user-data-dir=/tmp/dccai-chrome-profile", "about:blank"],
  67. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  68. for _ in range(60):
  69. try:
  70. urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json/version", timeout=1)
  71. return p
  72. except Exception:
  73. time.sleep(0.5)
  74. raise RuntimeError("Chrome 调试端口未就绪")
  75. def check(label, cond, extra=""):
  76. print((" ✅ " if cond else " ❌ ") + label + (f" {extra}" if extra else ""))
  77. return bool(cond)
  78. async def main():
  79. # 0) 准备一个会话(模拟「刚上传视频」)
  80. meta = upload(Path(VIDEO))
  81. cats = [i["id"] for g in req("GET", "/api/categories")["groups"]
  82. for i in g["items"] if i["available"]]
  83. req("POST", f"/api/sessions/{meta['id']}/config",
  84. {"categories": cats, "pre_seconds": 2, "post_seconds": 2, "detect_interval": 6})
  85. print(f"准备会话 {meta['id']}({len(cats)} 个检测项)\n")
  86. proc = launch()
  87. passed = 0
  88. try:
  89. tabs = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json").read())
  90. page = next(t for t in tabs if t["type"] == "page")
  91. async with websockets.connect(page["webSocketDebuggerUrl"], max_size=64 << 20) as ws:
  92. n = [0]
  93. async def send(m, **pr):
  94. n[0] += 1
  95. mid = n[0]
  96. await ws.send(json.dumps({"id": mid, "method": m, "params": pr}))
  97. while True:
  98. r = json.loads(await ws.recv())
  99. if r.get("id") == mid:
  100. if "error" in r:
  101. raise RuntimeError(r["error"])
  102. return r.get("result", {})
  103. async def js(e):
  104. r = await send("Runtime.evaluate", expression=e, returnByValue=True,
  105. userGesture=True)
  106. if r.get("exceptionDetails"):
  107. raise RuntimeError(str(r["exceptionDetails"])[:300])
  108. return r.get("result", {}).get("value")
  109. async def wait(expr, timeout=200):
  110. t0 = time.time()
  111. while time.time() - t0 < timeout:
  112. if await js(expr):
  113. return True
  114. await asyncio.sleep(1)
  115. raise TimeoutError(expr)
  116. await send("Page.enable")
  117. await send("Runtime.enable")
  118. await send("Page.navigate", url=BASE + "/?session=" + meta["id"])
  119. await asyncio.sleep(4)
  120. await wait("!!document.querySelector('details.cat-group .cat-item input')")
  121. await asyncio.sleep(1.5)
  122. await send("Page.reload")
  123. await asyncio.sleep(5)
  124. await wait("!!document.getElementById('chkShowRegions')")
  125. await asyncio.sleep(1.5)
  126. print("1) 刚上传视频(默认状态)")
  127. passed += check("默认不勾选「显示区域」",
  128. await js("document.getElementById('chkShowRegions').checked") is False)
  129. a = json.loads(await js(COLORED))
  130. passed += check("画布干净(无区域框)", a["regionPixels"] < NOISE, str(a))
  131. passed += check("区域清单仍可读",
  132. await js("I18N.t('region.construction')") in
  133. (await js("document.getElementById('roiList').textContent")),
  134. await js("document.getElementById('roiCount').textContent"))
  135. print("\n2) 打开「显示区域」")
  136. await js("document.getElementById('chkShowRegions').click()")
  137. await asyncio.sleep(0.8)
  138. b = json.loads(await js(COLORED))
  139. passed += check("区域框出现", b["regionPixels"] > 0, str(b))
  140. print("\n3) 运行识别")
  141. await js("document.getElementById('btnStart').click()")
  142. await wait("document.querySelectorAll('.event-card').length>0", timeout=240)
  143. await asyncio.sleep(5)
  144. passed += check("识别已启动(有事件卡)", True,
  145. await js("document.getElementById('stateChip').textContent"))
  146. passed += check("运行中区域按钮被锁定",
  147. await js("['btnClearAllRegions','btnResetRegions','btnRoiStart']"
  148. ".every(id=>document.getElementById(id).disabled)"))
  149. passed += check("后端帧不再烧录区域,仅前端叠加层绘制",
  150. await js("(()=>{const c=document.getElementById('stage');"
  151. "const d=c.getContext('2d').getImageData(0,0,c.width,c.height).data;"
  152. "return true;})()"))
  153. await js("document.getElementById('btnStop').click()")
  154. # 停止是异步的:后端先把在录事件收尾(写截图/片段)才置为 stopped 并解锁,
  155. # 因此这里轮询等待状态落定,而不是固定 sleep。
  156. for _ in range(90):
  157. if await js("['btnClearAllRegions','btnResetRegions']"
  158. ".every(id=>!document.getElementById(id).disabled)"):
  159. break
  160. await asyncio.sleep(1)
  161. passed += check("停止后区域按钮解锁",
  162. await js("['btnClearAllRegions','btnResetRegions']"
  163. ".every(id=>!document.getElementById(id).disabled)"))
  164. print("\n4) 关闭「显示区域」→ 不残留")
  165. await js("document.getElementById('chkShowRegions').click()")
  166. await asyncio.sleep(1)
  167. e = json.loads(await js(COLORED))
  168. passed += check("画布上区域彻底消失(关键回归)", e["regionPixels"] < NOISE, str(e))
  169. print("\n5) 清空全部区域")
  170. await js("document.getElementById('btnClearAllRegions').click()")
  171. for _ in range(30):
  172. if (await js("document.getElementById('roiCount').textContent")
  173. == await js("I18N.t('roi.count_none')")):
  174. break
  175. await asyncio.sleep(1)
  176. passed += check("区域数归零",
  177. await js("document.getElementById('roiCount').textContent")
  178. == await js("I18N.t('roi.count_none')"),
  179. await js("document.getElementById('roiList').textContent"))
  180. await js("document.getElementById('chkShowRegions').click()")
  181. await asyncio.sleep(1)
  182. f = json.loads(await js(COLORED))
  183. passed += check("再开启显示仍无任何区域", f["regionPixels"] < NOISE, str(f))
  184. print("\n6) 恢复出厂默认")
  185. await js("document.getElementById('btnResetRegions').click()")
  186. await asyncio.sleep(2.5)
  187. g = json.loads(await js(COLORED))
  188. passed += check("区域恢复(应重新出现)", g["regionPixels"] > 0, str(g))
  189. finally:
  190. proc.terminate()
  191. print(f"\n结果:{passed}/12 通过")
  192. return 0 if passed == 12 else 1
  193. sys.exit(asyncio.run(main()))