classpulse-edge / modules /behavior_branch /consumption_detector.py
thegoatcc's picture
Upload ClassPulse Edge codebase, Dockerfile, and model weights
af70f62 verified
Raw History Blame Contribute Delete
8.67 kB
from __future__ import annotations
import logging, math
from collections import deque
from pathlib import Path
from typing import Any
import cv2, numpy as np
from core.base_module import BaseModelWrapper, PipelineModule
from core.config_manager import ConfigManager, ModuleState
import time
from core.clip_writer import save_bounded_clip
from core.state import FrameContext
logger = logging.getLogger("classpulse.consumption_detector")
DRINK_LABELS = {"bottle", "cup", "wine glass", "drinking"}
SMOKE_LABELS = {"smoke"}
class RealConsumptionDetectionWrapper(BaseModelWrapper):
def __init__(self, coco_weights: Any = "models/yolov8n.pt", smoking_weights: str = "models/smoking_yolov8.pt", **kwargs: Any) -> None:
if not isinstance(coco_weights, (str, Path)):
coco_weights = "models/yolov8n.pt"
self.coco_weights = str(coco_weights)
self.smoking_weights = str(smoking_weights)
self._coco = None
self._smoke = None
def load(self) -> None:
from ultralytics import YOLO
self._coco = YOLO(self.coco_weights if Path(self.coco_weights).exists() else "yolov8n.pt")
sp = Path(self.smoking_weights)
if sp.exists() and sp.stat().st_size > 500_000:
self._smoke = YOLO(str(sp))
logger.info("Loaded COCO (%s) + Smoking (%s, classes=%s).", self.coco_weights, sp, self._smoke.names)
else:
logger.warning("Loaded COCO (%s) only; smoking weights missing at %s.", self.coco_weights, sp)
def _attach(self, context: FrameContext, label: str, conf: float, bbox: tuple[int, int, int, int]) -> None:
cx, cy = (bbox[0] + bbox[2]) / 2.0, (bbox[1] + bbox[3]) / 2.0
best_p, best_s = None, -1.0
for p in context.people:
if getattr(p, 'state', None) is None:
continue
px1, py1, px2, py2 = p.bbox
pad_x, pad_y = 0.05 * max(1.0, px2 - px1), 0.05 * max(1.0, py2 - py1)
if (px1 - pad_x) <= cx <= (px2 + pad_x) and (py1 - pad_y) <= cy <= (py2 + pad_y):
s = 1.0 / (1.0 + math.hypot(cx - (px1 + px2) / 2.0, cy - (py1 + 0.30 * (py2 - py1))))
if s > best_s:
best_p, best_s = p, s
if best_p is not None:
best_p.detected_objects.append({"label": label, "confidence": conf, "bbox": bbox})
def process(self, context: FrameContext) -> FrameContext:
if not context.people:
return context
if self._coco is not None:
for r in self._coco.predict(context.frame, conf=0.30, verbose=False):
for b in r.boxes:
lbl = str(r.names.get(int(b.cls[0]), "")).lower()
if lbl in DRINK_LABELS:
self._attach(context, lbl, float(b.conf[0]), tuple(map(int, b.xyxy[0].tolist())))
if self._smoke is not None:
for r in self._smoke.predict(context.frame, conf=0.18, imgsz=640, verbose=False):
for b in r.boxes:
lbl = str(r.names.get(int(b.cls[0]), "")).lower()
if lbl in SMOKE_LABELS:
self._attach(context, lbl, float(b.conf[0]), tuple(map(int, b.xyxy[0].tolist())))
return context
class ConsumptionDetector(PipelineModule):
def __init__(self, config: ConfigManager, wrapper: BaseModelWrapper | None = None, sampler: Any = None, **kwargs: Any) -> None:
self.sampler = sampler
backend = str(config.get_system("backend", "pc")).lower()
smoke_pt = str(getattr(config, "_data", {}).get("models", {}).get("smoking_pt", "models/smoking_yolov8.pt"))
if wrapper is None and backend != "mock":
wrapper = RealConsumptionDetectionWrapper("models/yolov8n.pt", smoke_pt)
super().__init__(name="consumption_detector", config=config, branch="behavior_branch", wrapper=wrapper)
sample_sec = max(0.05, float(config.get_system("sampling_interval_sec", 3.0)))
buf_sec = float(config.get_system("buffer_seconds", 15.0))
self._ring: deque[np.ndarray] = deque(maxlen=min(150, max(10, int(round(buf_sec / sample_sec)))))
self._last_clip: dict[tuple[int, str], int] = {}
def _rule_on(self, name: str) -> bool:
if hasattr(self.config, "get_sub_rule_state"):
return self.config.get_sub_rule_state(name) == ModuleState.ENABLED
return str(getattr(self.config, "_data", {}).get("sub_rules", {}).get(name, "ENABLED")).upper() == "ENABLED"
def _save_clip(self, context: FrameContext, tid: int, flag: str) -> str:
cdir = Path(self.config.get_path("clips_dir"))
cdir.mkdir(parents=True, exist_ok=True)
base = cdir / f"s{context.session_id}_{flag.lower()}_t{tid}_f{context.frame_index}"
max_sec = float(self.config.get_threshold("review_clip_max_sec", 7.0))
sample_sec = max(0.05, float(self.config.get_system("sampling_interval_sec", 1.0)))
fallback_fps = max(4.0, min(15.0, 1.0 / sample_sec))
buf = list(self._ring) if self._ring else list(context.ring_buffer_frames)
return save_bounded_clip(buf, base, max_duration_sec=max_sec, fallback_fps=fallback_fps)
@staticmethod
def _near_mouth_or_hand(person, bbox: tuple[int, int, int, int]) -> bool:
ocx, ocy = (bbox[0] + bbox[2]) / 2.0, (bbox[1] + bbox[3]) / 2.0
px1, py1, px2, py2 = person.bbox
diag = max(1.0, math.hypot(px2 - px1, py2 - py1))
if person.keypoints is not None and len(person.keypoints) > 0:
if person.keypoints[0][2] > 0.30 and math.hypot(ocx - float(person.keypoints[0][0]), ocy - float(person.keypoints[0][1])) <= 0.38 * diag:
return True
for wi in (9, 10):
if len(person.keypoints) > wi and person.keypoints[wi][2] > 0.30 and math.hypot(ocx - float(person.keypoints[wi][0]), ocy - float(person.keypoints[wi][1])) <= 0.32 * diag:
return True
if person.face_bbox is not None:
fx1, fy1, fx2, fy2 = person.face_bbox
fw, fh = max(1.0, fx2 - fx1), max(1.0, fy2 - fy1)
if (fx1 - 0.5 * fw) <= ocx <= (fx2 + 0.5 * fw) and (fy1 - 0.6 * fh) <= ocy <= (fy2 + 0.4 * fh):
return True
if math.hypot(ocx - (fx1 + fx2) / 2.0, ocy - (fy1 + 0.75 * fh)) <= 1.3 * math.hypot(fw, fh):
return True
return ocy <= (py1 + 0.75 * (py2 - py1))
def run(self, context: FrameContext) -> FrameContext:
if self.wrapper is not None:
context = self.wrapper.process(context)
self._ring.append((time.monotonic(), context.frame.copy()))
drink_on, smoke_on = self._rule_on("drink_detection"), self._rule_on("smoke_detection")
if not drink_on and not smoke_on:
return context
win_sz = int(self.config.get_threshold("sliding_window_size", 5))
min_hits = int(self.config.get_threshold("persistence_hits", 3))
for p in context.people:
d_hit = any(drink_on and str(o.get("label", "")).lower() in DRINK_LABELS and self._near_mouth_or_hand(p, o["bbox"]) for o in p.detected_objects)
s_hit = any(smoke_on and str(o.get("label", "")).lower() in SMOKE_LABELS and self._near_mouth_or_hand(p, o["bbox"]) for o in p.detected_objects)
for flag, hit, attr in ([("Drinking", d_hit, "_drink_hist")] if drink_on else []) + ([("Smoking", s_hit, "_smoke_hist")] if smoke_on else []):
win = getattr(p.state, attr, None)
if win is None or not hasattr(win, "append"):
win = deque(maxlen=win_sz)
setattr(p.state, attr, win)
win.append(hit)
if sum(1 for v in win if v) >= min_hits and (context.frame_index - self._last_clip.get((p.track_id, flag), -999)) >= 15:
self._last_clip[(p.track_id, flag)] = context.frame_index
clip = self._save_clip(context, p.track_id, flag)
logger.warning("Raised %s Flag for track=%s student=%s -> saved clip %s", flag, p.track_id, p.state.student_id, clip)
context.events.append({"type": "incident_flag", "track_id": p.track_id, "student_id": (None if p.state.student_id in (None, "", "None", "Unknown") else p.state.student_id), "flag_type": f"{flag} Flag", "timestamp": context.timestamp, "clip_path": clip})
return context
RealConsumptionWrapper = RealConsumptionDetectionWrapper
ConsumptionDetectorModule = ConsumptionDetector