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 main.py from thegoatcc/classpulse-edge: direct link, hf CLI and curl.
- Browser
- Download file 8.62 kB
-
https://huggingface.co/thegoatcc/classpulse-edge/resolve/main/main.py
- Command line
-
hf download hf://thegoatcc/classpulse-edge/main.py
-
curl -L -o main.py https://huggingface.co/thegoatcc/classpulse-edge/resolve/main/main.py
8.62 kB
| from __future__ import annotations | |
| import sqlite3 | |
| from datetime import datetime | |
| import signal | |
| import os | |
| import logging | |
| import threading | |
| import uvicorn | |
| from core.config_manager import ConfigManager | |
| from core.enrollment_service import EnrollmentService, RealFaceBiometricEngine | |
| from core.orchestrator import PipelineOrchestrator | |
| from dashboard.web_dashboard import create_app, publish_live_frame | |
| from modules.behavior_branch.consumption_detector import ConsumptionDetectorModule, RealConsumptionWrapper | |
| from modules.behavior_branch.phone_detector import PhoneDetectorModule, RealPhoneDetectionWrapper | |
| from modules.face_branch.attendance_recognizer import AttendanceRecognizerModule, CosineAttendanceMatcher | |
| from modules.face_branch.attention_analyzer import AttentionAnalyzer, ONNXMediaPipeAttentionWrapper | |
| from modules.face_branch.face_detector import FaceDetectorModule, MockFaceDetectorWrapper, PCFaceDetectorWrapper | |
| from modules.ingestion.frame_sampler import FrameSampler | |
| from modules.tracking.person_tracker import MockPersonTrackerWrapper, PCPersonTrackerWrapper, PersonTrackerModule | |
| from storage.database import DatabaseRepository | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s") | |
| logger = logging.getLogger("classpulse.main") | |
| def _cp_ignore_10054(): | |
| try: | |
| from asyncio.proactor_events import _ProactorBasePipeTransport | |
| _orig = _ProactorBasePipeTransport._call_connection_lost | |
| def _quiet(self, exc): | |
| try: | |
| _orig(self, exc) | |
| except ConnectionResetError: | |
| pass | |
| _ProactorBasePipeTransport._call_connection_lost = _quiet | |
| except Exception: | |
| pass | |
| _cp_ignore_10054() | |
| def _cp_check_session_end(db_path, sid) -> bool: | |
| if not sid: | |
| return False | |
| try: | |
| with sqlite3.connect(db_path) as conn: | |
| row = conn.execute( | |
| "SELECT end_time, is_active FROM class_sessions WHERE session_id = ?", | |
| (str(sid),), | |
| ).fetchone() | |
| if row is None: | |
| return False | |
| end_raw, is_active = row | |
| if not bool(is_active): | |
| return True | |
| if end_raw: | |
| en_dt = datetime.fromisoformat(str(end_raw).replace(" ", "T")).replace(tzinfo=None) | |
| if datetime.now() >= en_dt: | |
| with sqlite3.connect(db_path) as conn: | |
| conn.execute( | |
| "UPDATE class_sessions SET is_active = 0 WHERE session_id = ?", | |
| (str(sid),), | |
| ) | |
| return True | |
| except Exception: | |
| return False | |
| return False | |
| def main() -> None: | |
| config = ConfigManager("config.yaml") | |
| backend = str(config.get_system("backend", "pc")).lower() | |
| db = DatabaseRepository(config.get_path("database")) | |
| biometric_engine = RealFaceBiometricEngine( | |
| det_model_path=config.get_model_path("pc_face_det"), | |
| rec_model_path=config.get_model_path("pc_face_rec"), | |
| ) | |
| enrollment_svc = EnrollmentService( | |
| db=db, | |
| enrollment_dir=config.get_path("enrollment_dir"), | |
| backend=backend, | |
| engine=biometric_engine, | |
| ) | |
| sync_stats = enrollment_svc.enroll_from_directory() | |
| logger.info("Dataset sync on startup: %s", sync_stats) | |
| course_code = str(config.get_system("course_code", "CS499")) | |
| course_name = str(config.get_system("course_name", "Graduation Project II")) | |
| lecturer_id = str(config.get_system("lecturer_id", "LEC001")) | |
| room_number = str(config.get_system("room_number", "Room 101")) | |
| sample_interval = float(config.get_system("sampling_interval_sec", 2.0)) | |
| min_present = int(config.get_threshold("min_sightings_present", 3)) | |
| session_id = db.create_session( | |
| course_code=course_code, | |
| course_name=course_name, | |
| lecturer_id=lecturer_id, | |
| room_number=room_number, | |
| sampling_interval_sec=sample_interval, | |
| ) | |
| active_session_box = {"id": session_id} | |
| if backend == "pc": | |
| tracker_wrapper = PCPersonTrackerWrapper( | |
| detect_weights=config.get_model_path("pc_yolo_detect"), | |
| pose_weights=config.get_model_path("pc_yolo_pose"), | |
| ) | |
| face_wrapper = PCFaceDetectorWrapper(engine=biometric_engine) | |
| else: | |
| tracker_wrapper = MockPersonTrackerWrapper() | |
| face_wrapper = MockFaceDetectorWrapper() | |
| matcher = CosineAttendanceMatcher( | |
| db=db, | |
| similarity_threshold=float(config.get_threshold("face_match_similarity", 0.38)), | |
| ) | |
| recognizer = AttendanceRecognizerModule( | |
| config=config, | |
| wrapper=matcher, | |
| unknown_dir=config.get_path("unknown_dir"), | |
| max_retry_frames=int(config.get_threshold("max_unknown_retry_frames", 15)), | |
| ) | |
| def reload_profiles() -> None: | |
| count = recognizer.reload_profiles() | |
| logger.info("Hot-reloaded %d enrolled face profile(s) into live pipeline.", count) | |
| attention_wrapper = ONNXMediaPipeAttentionWrapper( | |
| head_pose_path=config.get_model_path("head_pose"), | |
| landmarker_path=config.get_model_path("face_landmarker"), | |
| ) | |
| sampler = FrameSampler(config) | |
| orchestrator = PipelineOrchestrator( | |
| config=config, | |
| modules=[ | |
| sampler, | |
| PersonTrackerModule(config, tracker_wrapper), | |
| FaceDetectorModule(config, face_wrapper), | |
| recognizer, | |
| AttentionAnalyzer(config, attention_wrapper), | |
| PhoneDetectorModule( | |
| config, | |
| RealPhoneDetectionWrapper(), | |
| min_samples=int(config.get_threshold("min_phone_samples", 3)), | |
| ), | |
| ConsumptionDetectorModule( | |
| config, | |
| RealConsumptionWrapper(), | |
| sampler=sampler, | |
| persistence_hits=int(config.get_threshold("persistence_hits", 3)), | |
| ), | |
| ], | |
| ) | |
| orchestrator.startup() | |
| stop_event = threading.Event() | |
| def pipeline_loop() -> None: | |
| logger.info("Pipeline worker started in [%s] mode for session %s.", backend.upper(), active_session_box["id"]) | |
| try: | |
| for ctx in sampler.stream_contexts( | |
| session_id=active_session_box["id"], | |
| stop_check=stop_event.is_set, | |
| ): | |
| current_sid = active_session_box["id"] | |
| ctx.session_id = current_sid | |
| try: | |
| ctx = orchestrator.process_frame(ctx) | |
| except Exception as exc: | |
| logger.warning(str(exc)) | |
| continue | |
| publish_live_frame(ctx, db) | |
| db.persist_events(current_sid, ctx.events, min_sightings_present=min_present) | |
| if _cp_check_session_end(config.get_path('database'), ctx.session_id): | |
| logger.info('Scheduled end_time reached for session %s; stopping recognition.', ctx.session_id) | |
| break | |
| sampler.update_ai_overlays(ctx) | |
| finally: | |
| db.finalize_attendance(active_session_box["id"], min_sightings=min_present) | |
| orchestrator.shutdown() | |
| os._exit(0) # _cp_fast_exit | |
| logger.info("Session %s finalized and pipeline shut down cleanly.", active_session_box["id"]) | |
| worker = threading.Thread(target=pipeline_loop, daemon=True) | |
| worker.start() | |
| app = create_app( | |
| config=config, | |
| db=db, | |
| active_session_box=active_session_box, | |
| on_profiles_updated=reload_profiles, | |
| frame_sampler=sampler, | |
| biometric_engine=biometric_engine, | |
| ) | |
| try: | |
| logger.info("Dashboard live at http://127.0.0.1:8000 (corner live AI window enabled)") | |
| _cp_stopping = [False] | |
| def _cp_sig_handler(signum, frame): | |
| if _cp_stopping[0]: | |
| os._exit(0) | |
| _cp_stopping[0] = True | |
| try: | |
| stop_event.set() | |
| except Exception: | |
| pass | |
| threading.Timer(1.5, os._exit, args=(0,)).start() | |
| raise KeyboardInterrupt() | |
| signal.signal(signal.SIGINT, _cp_sig_handler) | |
| signal.signal(signal.SIGTERM, _cp_sig_handler) | |
| uvicorn.run(app, host="0.0.0.0", port=8000, log_level="warning") | |
| finally: | |
| stop_event.set() | |
| worker.join(timeout=5.0) | |
| if __name__ == "__main__": | |
| main() | |