#!/usr/bin/env python3 """规则引擎单元测试:不依赖视频,直接构造轨迹与检测结果。""" import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import numpy as np from backend import config from backend.engines.rules import MATERIAL, PERSON, VEHICLE, RuleEngine from backend.engines.tracking import Track W, H = 854, 480 FRAME = np.zeros((H, W, 3), np.uint8) REGIONS = config.default_regions(W, H) def T(tid, name, box, raw="", n=12, dx=0.0): trk = Track(track_id=tid, box=list(box), cls=0, name=name, conf=0.9, raw=raw or name) cx = (box[0] + box[2]) / 2 cy = (box[1] + box[3]) / 2 for i in range(n): trk.history.append((cx - dx * (n - 1 - i), cy)) return trk def run(cats, tracks, det=None, ts=None, engine=None): e = engine or RuleEngine(set(cats), REGIONS, {}) return e, e.evaluate(FRAME, tracks, det or {}, ts if ts is not None else time.time()) ok = fail = 0 def check(label, cond, extra=""): global ok, fail print((" ✅ " if cond else " ❌ ") + label + (f" {extra}" if extra else "")) ok, fail = ok + bool(cond), fail + (not cond) print("1) 跌倒:直立 → 横躺 持续帧数") eng = RuleEngine({"fall"}, REGIONS, {}) per_frame = [] for i in range(10): box = [300, 200, 360, 420] if i < 3 else [250, 400, 560, 460] # 先竖直后人形横躺 eng, tr = run(["fall"], [T(1, PERSON, box, n=1)], engine=eng) per_frame.append(tr) check("直立阶段(前 3 帧)不触发", not any(per_frame[i] for i in range(3))) check("横躺持续后触发跌倒", any(t.category == "fall" for tr in per_frame for t in tr)) print("2) 跌倒反向:一直横躺(静态侧影)不应触发") eng2 = RuleEngine({"fall"}, REGIONS, {}) fired2 = [] for i in range(20): eng2, tr = run(["fall"], [T(1, PERSON, [250, 400, 560, 460], n=1)], engine=eng2) fired2 += tr check("一直横躺不触发(避免静止误报)", not fired2) print("3) 未佩戴安全帽:nohat 关联人框且无 hat") p = T(1, PERSON, [100, 100, 200, 300]) _, tr = run(["no_helmet"], [p], {"nohat": [{"xyxy": [120, 110, 160, 150]}]}) check("检出未戴安全帽", any(t.category == "no_helmet" for t in tr)) _, tr = run(["no_helmet"], [p], {"nohat": [{"xyxy": [120, 110, 160, 150]}], "hat": [{"xyxy": [130, 115, 155, 145]}]}) check("同时有 hat 时不触发", not any(t.category == "no_helmet" for t in tr)) print("4) 未穿反光背心") _, tr = run(["no_vest"], [p], {"novest": [{"xyxy": [110, 150, 190, 260]}]}) check("检出未穿反光背心", any(t.category == "no_vest" for t in tr)) print("5) 非法闯入禁区:人员质心落入禁区多边形") cx = sum(x for x, _ in REGIONS["restricted"]) / 4 cy = sum(y for _, y in REGIONS["restricted"]) / 4 inside = T(1, PERSON, [cx - 30, cy - 60, cx + 30, cy + 60]) _, tr = run(["intrusion"], [inside]) check("禁区内触发闯入", any(t.category == "intrusion" for t in tr)) outside = T(1, PERSON, [20, 40, 80, 200]) _, tr = run(["intrusion"], [outside]) check("禁区外不触发", not any(t.category == "intrusion" for t in tr)) print("6) 异常人群聚集:禁区内人数≥N 且持续 T 秒") eng3 = RuleEngine({"crowd"}, REGIONS, {}) t0 = time.time() persons = [T(i, PERSON, [cx - 20 + i * 8, cy - 40, cx + 20 + i * 8, cy + 40]) for i in range(5)] tr = [] eng3, tr = run(["crowd"], persons, ts=t0, engine=eng3) check("人数达标但未达持续时间 → 不触发", not tr) eng3, tr = run(["crowd"], persons, ts=t0 + 4.0, engine=eng3) check("持续 4s 后触发聚集", any(t.category == "crowd" for t in tr)) print("7) 车辆越线计数(进/出,含滞回与冷却)") e4 = RuleEngine({"vehicle_count"}, REGIONS, {}) lx = REGIONS["count_line"][0][0] def veh(tid, cx, raw="car"): return T(tid, VEHICLE, [cx - 40, 200, cx + 40, 300], raw=raw, n=1) # 抖动:在计数线附近来回 ±10px(处于 margin 死区内),不应计数 for i, off in enumerate([10, -10, 12, -8, 15]): e4, _ = run(["vehicle_count"], [veh(1, lx + off)], ts=1.0 + i * 0.05, engine=e4) check("线附近抖动不计数", e4.vehicle_in == 0 and e4.vehicle_out == 0, f"in={e4.vehicle_in} out={e4.vehicle_out}") e4, _ = run(["vehicle_count"], [veh(1, lx - 120)], ts=2.0, engine=e4) # 明确到左侧 e4, _ = run(["vehicle_count"], [veh(1, lx + 120)], ts=2.2, engine=e4) # 左→右 check("左→右 记为「进」", e4.vehicle_in == 1 and e4.vehicle_out == 0, f"in={e4.vehicle_in} out={e4.vehicle_out}") check("车型归类为小型车", e4.by_class.get("小型车") == 1, str(e4.by_class)) e4, _ = run(["vehicle_count"], [veh(1, lx - 120)], ts=9.0, engine=e4) # 冷却后再出 check("同一目标冷却后右→左 记为「出」", e4.vehicle_in == 1 and e4.vehicle_out == 1, f"in={e4.vehicle_in} out={e4.vehicle_out}") check("累计 2 条越线记录", len(e4.crossing_records) == 2) e4, _ = run(["vehicle_count"], [veh(2, lx - 120, raw="truck")], ts=20.0, engine=e4) e4, _ = run(["vehicle_count"], [veh(2, lx + 120, raw="truck")], ts=20.2, engine=e4) check("货车归类为货车", e4.by_class.get("货车") == 1, str(e4.by_class)) check("货车标记 is_truck", e4.crossing_records[-1]["is_truck"] is True) print("8) 工程机械区域未配备防护设备") mx = sum(x for x, _ in REGIONS["machinery"]) / 4 my = sum(y for _, y in REGIONS["machinery"]) / 4 mp = T(1, PERSON, [mx - 30, my - 60, mx + 30, my + 60]) _, tr = run(["machinery_no_guard"], [mp], {"nohat": [{"xyxy": [mx - 20, my - 55, mx + 10, my - 25]}]}) check("机械区内未戴帽触发", any(t.category == "machinery_no_guard" for t in tr)) fp = T(2, PERSON, [20, 40, 80, 200]) _, tr = run(["machinery_no_guard"], [fp], {"nohat": [{"xyxy": [30, 50, 60, 80]}]}) check("机械区外不触发", not any(t.category == "machinery_no_guard" for t in tr)) print("9) 物资/设备异常移动") mv = T(1, MATERIAL, [300, 300, 380, 380], raw="suitcase", n=12, dx=12.0) _, tr = run(["object_move"], [mv]) check("位移超阈值触发", any(t.category == "object_move" for t in tr)) st = T(2, MATERIAL, [300, 300, 380, 380], raw="backpack", n=12, dx=0.0) _, tr = run(["object_move"], [st]) check("静止不触发", not any(t.category == "object_move" for t in tr)) print("10) 区域人数统计") e5 = RuleEngine({"people_count"}, REGIONS, {}) cons = REGIONS["construction"] wh = REGIONS["warehouse"] ps = [ T(1, PERSON, [cons[0][0] + 50, 100, cons[0][0] + 110, 300]), T(2, PERSON, [cons[0][0] + 150, 100, cons[0][0] + 210, 300]), T(3, PERSON, [wh[0][0] + 60, 100, wh[0][0] + 120, 300]), ] counts = e5.region_people_count(ps) check("施工区 2 人 / 仓储区 1 人", counts.get("construction") == 2 and counts.get("warehouse") == 1, str(counts)) print(f"\n结果:{ok} 通过 / {fail} 失败") sys.exit(1 if fail else 0)