Instructions to use thegoatcc/classpulse-edge with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- ultralytics
How to use thegoatcc/classpulse-edge with ultralytics:
from huggingface_hub import hf_hub_download from ultralytics import YOLO # pick the weights file from this repo's "Files and versions" tab weights = hf_hub_download("thegoatcc/classpulse-edge", "<weights>.pt") model = YOLO(weights) source = 'http://images.cocodataset.org/val2017/000000039769.jpg' model.predict(source=source, save=True) - Notebooks
- Google Colab
- Kaggle
Download modules/tracking/person_tracker.py from thegoatcc/classpulse-edge: direct link, hf CLI and curl.
- Browser
- Download file 7.48 kB
-
https://huggingface.co/thegoatcc/classpulse-edge/resolve/main/modules/tracking/person_tracker.py
- Command line
-
hf download hf://thegoatcc/classpulse-edge/modules/tracking/person_tracker.py
-
curl -L -o person_tracker.py https://huggingface.co/thegoatcc/classpulse-edge/resolve/main/modules/tracking/person_tracker.py
7.48 kB
| from __future__ import annotations | |
| import logging | |
| from pathlib import Path | |
| from typing import Any, Optional | |
| import numpy as np | |
| from core.base_module import BaseModelWrapper, PipelineModule | |
| from core.config_manager import ConfigManager | |
| from core.state import FrameContext, TrackedPerson | |
| logger = logging.getLogger("classpulse.tracking") | |
| class PCPersonTrackerWrapper(BaseModelWrapper): | |
| """Real YOLOv8 + ByteTrack + YOLOv8-pose runner for Windows laptop & USB webcams.""" | |
| def __init__(self, detect_weights: str, pose_weights: str) -> None: | |
| self.detect_weights = detect_weights | |
| self.pose_weights = pose_weights | |
| self.det_model: Any = None | |
| self.pose_model: Any = None | |
| def load(self) -> None: | |
| from ultralytics import YOLO | |
| det_path = self.detect_weights if Path(self.detect_weights).exists() else "yolov8n.pt" | |
| pose_path = self.pose_weights if Path(self.pose_weights).exists() else "yolov8n-pose.pt" | |
| self.det_model = YOLO(det_path) | |
| self.pose_model = YOLO(pose_path) | |
| logger.info("Loaded real PC YOLOv8 detection (%s) & pose (%s) models.", det_path, pose_path) | |
| def process(self, context: FrameContext) -> FrameContext: | |
| if self.det_model is None or self.pose_model is None: | |
| self.load() | |
| frame = context.frame | |
| if frame is None: | |
| return context | |
| # 1. Track people & detect classroom objects (person=0, bottle=39, cup=41, cell phone=67) | |
| track_res = self.det_model.track( | |
| frame, persist=True, tracker="bytetrack.yaml", classes=[0, 39, 41, 67], conf=0.35, verbose=False | |
| )[0] | |
| # 2. Extract (17, 3) COCO keypoints per person | |
| pose_res = self.pose_model(frame, conf=0.35, verbose=False)[0] | |
| pose_candidates: list[tuple[tuple[int, int, int, int], np.ndarray]] = [] | |
| if pose_res.boxes is not None and pose_res.keypoints is not None: | |
| p_boxes = pose_res.boxes.xyxy.cpu().numpy() | |
| p_kpts = pose_res.keypoints.data.cpu().numpy() | |
| for box, kpts in zip(p_boxes, p_kpts): | |
| pose_candidates.append( | |
| ((int(box[0]), int(box[1]), int(box[2]), int(box[3])), np.asarray(kpts, dtype=np.float32)) | |
| ) | |
| people: list[TrackedPerson] = [] | |
| detected_objects: list[dict[str, Any]] = [] | |
| if track_res.boxes is not None: | |
| boxes = track_res.boxes.xyxy.cpu().numpy() | |
| clss = track_res.boxes.cls.cpu().numpy().astype(int) | |
| confs = track_res.boxes.conf.cpu().numpy() | |
| ids = ( | |
| track_res.boxes.id.cpu().numpy().astype(int) | |
| if track_res.boxes.id is not None | |
| else np.arange(1, len(boxes) + 1) | |
| ) | |
| names = track_res.names | |
| for box, cls_id, conf, tid in zip(boxes, clss, confs, ids): | |
| x1, y1, x2, y2 = int(box[0]), int(box[1]), int(box[2]), int(box[3]) | |
| label = str(names.get(int(cls_id), cls_id)) | |
| if int(cls_id) == 0: | |
| matched_kps = self._match_best_pose((x1, y1, x2, y2), pose_candidates) | |
| people.append( | |
| TrackedPerson( | |
| track_id=int(tid), | |
| bbox=(x1, y1, x2, y2), | |
| confidence=float(conf), | |
| keypoints=matched_kps, | |
| ) | |
| ) | |
| else: | |
| detected_objects.append( | |
| {"label": label, "bbox": (x1, y1, x2, y2), "confidence": float(conf)} | |
| ) | |
| # Attach objects overlapping each student's bounding box | |
| for person in people: | |
| px1, py1, px2, py2 = person.bbox | |
| person.detected_objects = [ | |
| obj | |
| for obj in detected_objects | |
| if px1 <= (obj["bbox"][0] + obj["bbox"][2]) / 2.0 <= px2 | |
| and py1 <= (obj["bbox"][1] + obj["bbox"][3]) / 2.0 <= py2 | |
| ] | |
| context.people = people | |
| context.metadata["detected_objects"] = detected_objects | |
| return context | |
| def _match_best_pose( | |
| person_bbox: tuple[int, int, int, int], | |
| candidates: list[tuple[tuple[int, int, int, int], np.ndarray]], | |
| ) -> Optional[np.ndarray]: | |
| best_iou = 0.25 | |
| best_kps: Optional[np.ndarray] = None | |
| px1, py1, px2, py2 = person_bbox | |
| p_area = max(1, (px2 - px1) * (py2 - py1)) | |
| for (cx1, cy1, cx2, cy2), kps in candidates: | |
| ix1, iy1 = max(px1, cx1), max(py1, cy1) | |
| ix2, iy2 = min(px2, cx2), min(py2, cy2) | |
| inter = max(0, ix2 - ix1) * max(0, iy2 - iy1) | |
| c_area = max(1, (cx2 - cx1) * (cy2 - cy1)) | |
| iou = inter / float(p_area + c_area - inter) | |
| if iou > best_iou: | |
| best_iou = iou | |
| best_kps = kps | |
| return best_kps | |
| class MockPersonTrackerWrapper(BaseModelWrapper): | |
| def load(self) -> None: | |
| logger.info("Loaded MockPersonTrackerWrapper.") | |
| def process(self, context: FrameContext) -> FrameContext: | |
| if context.frame is None: | |
| return context | |
| h, w = context.frame.shape[:2] | |
| kps = np.zeros((17, 3), dtype=np.float32) | |
| kps[0] = [w * 0.5, h * 0.30, 0.9] | |
| kps[9] = [w * 0.4, h * 0.65, 0.9] | |
| kps[10] = [w * 0.6, h * 0.65, 0.9] | |
| context.people = [ | |
| TrackedPerson( | |
| track_id=1, | |
| bbox=(int(w * 0.25), int(h * 0.15), int(w * 0.75), int(h * 0.95)), | |
| confidence=0.95, | |
| keypoints=kps, | |
| ) | |
| ] | |
| context.metadata["detected_objects"] = [] | |
| return context | |
| class PersonTrackerModule(PipelineModule): | |
| def __init__(self, config: ConfigManager, wrapper: BaseModelWrapper) -> None: | |
| super().__init__(name="person_tracker", config=config, branch=None, wrapper=wrapper) | |
| def run(self, context: FrameContext) -> FrameContext: | |
| if self.wrapper is not None: | |
| context = self.wrapper.process(context) | |
| for person in context.people: | |
| state = context.get_or_create_track_state(person.track_id) | |
| person.state = state | |
| state.sighting_count += 1 | |
| context.events.append( | |
| { | |
| "type": "raw_sighting", | |
| "track_id": person.track_id, | |
| "timestamp": context.timestamp, | |
| } | |
| ) | |
| # _cp_safe_gap_reset: unlink student_id if track had a frame gap | |
| for _p in context.people: | |
| _st = getattr(_p, 'state', None) | |
| if _st is None: | |
| continue | |
| _last = getattr(_st, '_last_seen_frame', context.frame_index) | |
| if (context.frame_index - _last) > 5: | |
| _st.student_id = None | |
| _st.student_name = None | |
| _st.recognition_attempts = 0 | |
| _st.unknown_flagged = False | |
| if hasattr(_st, 'paused_modules'): | |
| _st.paused_modules.discard('attendance_recognizer') | |
| _st._last_seen_frame = context.frame_index | |
| return context | |
| PersonTracker = PersonTrackerModule | |