File size: 8,616 Bytes
af70f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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()