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 storage/database.py from thegoatcc/classpulse-edge: direct link, hf CLI and curl.
- Browser
- Download file 62.7 kB
-
https://huggingface.co/thegoatcc/classpulse-edge/resolve/main/storage/database.py
- Command line
-
hf download hf://thegoatcc/classpulse-edge/storage/database.py
-
curl -L -o database.py https://huggingface.co/thegoatcc/classpulse-edge/resolve/main/storage/database.py
62.7 kB
from __future__ import annotations
from core.clip_writer import format_duration
from datetime import datetime
import json
from pathlib import Path
import shutil
import sqlite3
from typing import Any, Optional
import uuid
import numpy as np
class DatabaseRepository:
"""3NF SQLite repository for ClassPulse Edge (13-table schema + dashboard management)."""
def __init__(self, db_path: str | Path = "data/classroom.db") -> None:
self.db_path = Path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._migrate_legacy_if_needed()
self.init_db()
def connect(self) -> sqlite3.Connection:
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON;")
return conn
def _migrate_legacy_if_needed(self) -> None:
"""Backs up an older pre-3NF classroom.db if detected so the 13-table schema initializes cleanly."""
if not self.db_path.exists():
return
try:
conn = sqlite3.connect(self.db_path)
cols = [r[1] for r in conn.execute("PRAGMA table_info(students)").fetchall()]
tables = {
r[0]
for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
}
conn.close()
if (cols and "student_name" not in cols) or ("sessions" in tables and "class_sessions" not in tables):
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup = self.db_path.with_name(f"classroom_legacy_{stamp}.db.bak")
shutil.move(str(self.db_path), str(backup))
except sqlite3.Error:
pass
def init_db(self) -> None:
with self.connect() as conn:
conn.executescript(
"""
PRAGMA foreign_keys = ON;
-- 1. CORE ACADEMIC & BIOMETRIC REGISTRY
CREATE TABLE IF NOT EXISTS courses (
course_code VARCHAR(20) PRIMARY KEY,
course_name VARCHAR(100) NOT NULL
);
CREATE TABLE IF NOT EXISTS lecturers (
lecturer_id VARCHAR(36) PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS students (
student_id VARCHAR(50) PRIMARY KEY,
student_name VARCHAR(100) NOT NULL
);
CREATE TABLE IF NOT EXISTS course_enrollments (
course_code VARCHAR(20) NOT NULL,
student_id VARCHAR(50) NOT NULL,
enrolled_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (course_code, student_id),
FOREIGN KEY (course_code) REFERENCES courses (course_code) ON DELETE CASCADE,
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS enrolled_face_profiles (
profile_id VARCHAR(36) PRIMARY KEY,
student_id VARCHAR(50) NOT NULL,
embedding_vector TEXT NOT NULL,
source_image VARCHAR(150) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (student_id, source_image),
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE
);
-- 2. SESSION EXECUTION & PRE-BRANCH TRACKING
CREATE TABLE IF NOT EXISTS class_sessions (
session_id VARCHAR(36) PRIMARY KEY,
course_code VARCHAR(20) NOT NULL,
lecturer_id VARCHAR(36) NOT NULL,
room_number VARCHAR(20) NOT NULL,
sampling_interval_sec FLOAT NOT NULL DEFAULT 3.0 CHECK (sampling_interval_sec > 0),
start_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
end_time TIMESTAMP,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
FOREIGN KEY (course_code) REFERENCES courses (course_code) ON DELETE CASCADE,
FOREIGN KEY (lecturer_id) REFERENCES lecturers (lecturer_id) ON DELETE RESTRICT
);
CREATE TABLE IF NOT EXISTS frame_sightings (
sighting_id VARCHAR(36) PRIMARY KEY,
session_id VARCHAR(36) NOT NULL,
tracking_id INT NOT NULL,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE
);
-- 3. FACE BRANCH, BEHAVIOR BRANCH & HUMAN-IN-THE-LOOP QUEUES
CREATE TABLE IF NOT EXISTS attendance_sightings (
match_id VARCHAR(36) PRIMARY KEY,
session_id VARCHAR(36) NOT NULL,
student_id VARCHAR(50) NOT NULL,
tracking_id INT NOT NULL,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
confidence_score FLOAT NOT NULL CHECK (confidence_score >= 0.0 AND confidence_score <= 1.0),
FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS attendance_logs (
attendance_id VARCHAR(36) PRIMARY KEY,
session_id VARCHAR(36) NOT NULL,
student_id VARCHAR(50) NOT NULL,
sighting_count INT NOT NULL DEFAULT 0 CHECK (sighting_count >= 0),
first_seen_timestamp TIMESTAMP,
status VARCHAR(20) NOT NULL DEFAULT 'Absent' CHECK (status IN ('Present', 'Absent')),
is_manual_override BOOLEAN NOT NULL DEFAULT FALSE,
confidence_score FLOAT,
UNIQUE (session_id, student_id),
CHECK (
is_manual_override = 1
OR (status = 'Present' AND sighting_count >= 3 AND first_seen_timestamp IS NOT NULL)
OR (status = 'Absent' AND sighting_count < 3)
),
FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS unknown_faces (
unknown_id VARCHAR(36) PRIMARY KEY,
session_id VARCHAR(36) NOT NULL,
tracking_id INT NOT NULL,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
crop_file_path VARCHAR(255) NOT NULL,
assigned_student_id VARCHAR(50),
status VARCHAR(20) NOT NULL DEFAULT 'Pending' CHECK (status IN ('Pending', 'Assigned', 'Dismissed')),
reviewed_at TIMESTAMP,
UNIQUE (session_id, tracking_id),
FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,
FOREIGN KEY (assigned_student_id) REFERENCES students (student_id) ON DELETE SET NULL
);
CREATE TABLE IF NOT EXISTS attention_logs (
attention_id VARCHAR(36) PRIMARY KEY,
session_id VARCHAR(36) NOT NULL,
student_id VARCHAR(50) NOT NULL,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
yaw_angle FLOAT NOT NULL,
pitch_angle FLOAT NOT NULL,
expression_state VARCHAR(20) NOT NULL DEFAULT 'Not Evaluated'
CHECK (expression_state IN ('Alert', 'Drowsy', 'Yawning', 'Not Evaluated')),
attention_state VARCHAR(20) NOT NULL
CHECK (attention_state IN ('Attentive', 'Low Engagement', 'Looking Away')),
FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS behavior_logs (
log_id VARCHAR(36) PRIMARY KEY,
session_id VARCHAR(36) NOT NULL,
student_id VARCHAR(50) NOT NULL,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
behavior_type VARCHAR(30) NOT NULL DEFAULT 'Phone Use'
CHECK (behavior_type IN ('Phone Use')),
sample_count INT NOT NULL DEFAULT 3 CHECK (sample_count >= 3),
UNIQUE (session_id, student_id, behavior_type),
FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS flagged_events (
event_id VARCHAR(36) PRIMARY KEY,
session_id VARCHAR(36) NOT NULL,
student_id VARCHAR(50),
tracking_id INT,
flag_type VARCHAR(30) NOT NULL
CHECK (flag_type IN ('Drinking Flag', 'Smoking Flag')),
clip_file_path VARCHAR(255),
confidence_score FLOAT,
status VARCHAR(20) NOT NULL DEFAULT 'Unconfirmed'
CHECK (status IN ('Unconfirmed', 'Confirmed', 'Dismissed')),
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
reviewed_at TIMESTAMP,
CHECK (status = 'Dismissed' OR clip_file_path IS NOT NULL),
FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE SET NULL
);
-- 4. PERFORMANCE INDEXES
CREATE INDEX IF NOT EXISTS idx_profiles_student ON enrolled_face_profiles (student_id);
CREATE INDEX IF NOT EXISTS idx_sessions_course ON class_sessions (course_code, start_time);
CREATE INDEX IF NOT EXISTS idx_frame_sightings_session ON frame_sightings (session_id, timestamp);
CREATE INDEX IF NOT EXISTS idx_att_sightings_session_student ON attendance_sightings (session_id, student_id);
CREATE INDEX IF NOT EXISTS idx_unknown_faces_session_status ON unknown_faces (session_id, status);
CREATE INDEX IF NOT EXISTS idx_attention_logs_session_student ON attention_logs (session_id, student_id);
CREATE INDEX IF NOT EXISTS idx_behavior_logs_session_student ON behavior_logs (session_id, student_id);
CREATE INDEX IF NOT EXISTS idx_flagged_events_session_status ON flagged_events (session_id, status);
"""
)
@staticmethod
def _normalize_timestamp(ts: Optional[str]) -> Optional[str]:
if not ts or not ts.strip():
return None
val = ts.strip().replace("T", " ")
if len(val) == 16: # YYYY-MM-DD HH:MM
val += ":00"
return val
# ------------------------------------------------------------------
# COURSES, LECTURERS & COURSE ENROLLMENTS
# ------------------------------------------------------------------
def upsert_course(self, course_code: str, course_name: str) -> dict[str, str]:
code = course_code.strip().upper()
name = course_name.strip()
with self.connect() as conn:
conn.execute(
"""
INSERT INTO courses (course_code, course_name)
VALUES (?, ?)
ON CONFLICT(course_code) DO UPDATE SET course_name = excluded.course_name
""",
(code, name),
)
return {"course_code": code, "course_name": name}
def list_courses(self) -> list[dict[str, Any]]:
with self.connect() as conn:
rows = conn.execute(
"""
SELECT c.course_code, c.course_name,
COUNT(DISTINCT ce.student_id) AS enrolled_count,
COUNT(DISTINCT cs.session_id) AS session_count
FROM courses c
LEFT JOIN course_enrollments ce ON c.course_code = ce.course_code
LEFT JOIN class_sessions cs ON c.course_code = cs.course_code
GROUP BY c.course_code, c.course_name
ORDER BY c.course_code
"""
).fetchall()
return [dict(r) for r in rows]
def delete_course(self, course_code: str) -> dict[str, Any]:
code = course_code.strip().upper()
with self.connect() as conn:
exists = conn.execute(
"SELECT 1 FROM courses WHERE course_code = ?",
(code,),
).fetchone()
if not exists:
return {"deleted": False, "removed_session_ids": []}
session_rows = conn.execute(
"SELECT session_id FROM class_sessions WHERE course_code = ?",
(code,),
).fetchall()
removed_ids = [r["session_id"] for r in session_rows]
# Remove child rows explicitly so legacy DBs with ON DELETE RESTRICT also delete cleanly
conn.execute("DELETE FROM class_sessions WHERE course_code = ?", (code,))
conn.execute("DELETE FROM course_enrollments WHERE course_code = ?", (code,))
conn.execute("DELETE FROM courses WHERE course_code = ?", (code,))
return {"deleted": True, "removed_session_ids": removed_ids}
def upsert_lecturer(self, lecturer_id: str, name: str, email: str) -> dict[str, str]:
lid = lecturer_id.strip()
with self.connect() as conn:
conn.execute(
"""
INSERT INTO lecturers (lecturer_id, name, email)
VALUES (?, ?, ?)
ON CONFLICT(lecturer_id) DO UPDATE SET
name = excluded.name,
email = excluded.email
""",
(lid, name.strip(), email.strip()),
)
return {"lecturer_id": lid, "name": name.strip(), "email": email.strip()}
def list_lecturers(self) -> list[dict[str, Any]]:
with self.connect() as conn:
rows = conn.execute("SELECT lecturer_id, name, email FROM lecturers ORDER BY name").fetchall()
return [dict(r) for r in rows]
def enroll_student_in_course(self, course_code: str, student_id: str) -> None:
code = course_code.strip().upper()
sid = student_id.strip()
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with self.connect() as conn:
conn.execute(
"""
INSERT INTO course_enrollments (course_code, student_id, enrolled_at)
VALUES (?, ?, ?)
ON CONFLICT(course_code, student_id) DO NOTHING
""",
(code, sid, now),
)
active_sessions = conn.execute(
"SELECT session_id FROM class_sessions WHERE course_code = ? AND is_active = 1",
(code,),
).fetchall()
for s in active_sessions:
conn.execute(
"""
INSERT OR IGNORE INTO attendance_logs
(attendance_id, session_id, student_id, sighting_count, status, is_manual_override)
VALUES (?, ?, ?, 0, 'Absent', 0)
""",
(str(uuid.uuid4()), s["session_id"], sid),
)
def unenroll_student_from_course(self, course_code: str, student_id: str) -> None:
with self.connect() as conn:
conn.execute(
"DELETE FROM course_enrollments WHERE course_code = ? AND student_id = ?",
(course_code.strip().upper(), student_id.strip()),
)
# ------------------------------------------------------------------
# STUDENTS & MULTI-PROFILE FACE EMBEDDINGS
# ------------------------------------------------------------------
def upsert_student(
self,
student_id: str,
student_name: str,
course_code: Optional[str] = None,
) -> dict[str, str]:
sid = student_id.strip()
sname = student_name.strip()
with self.connect() as conn:
conn.execute(
"""
INSERT INTO students (student_id, student_name)
VALUES (?, ?)
ON CONFLICT(student_id) DO UPDATE SET student_name = excluded.student_name
""",
(sid, sname),
)
if course_code:
self.enroll_student_in_course(course_code, sid)
return {"student_id": sid, "student_name": sname}
def get_student(self, student_id: str) -> Optional[dict[str, Any]]:
with self.connect() as conn:
row = conn.execute(
"SELECT student_id, student_name FROM students WHERE student_id = ?",
(student_id.strip(),),
).fetchone()
return dict(row) if row else None
def delete_student(self, student_id: str) -> bool:
sid = student_id.strip()
with self.connect() as conn:
cur = conn.execute("DELETE FROM students WHERE student_id = ?", (sid,))
return cur.rowcount > 0
def upsert_face_profile(
self,
student_id: str,
embedding: np.ndarray,
source_image: str,
) -> str:
sid = student_id.strip()
vec_json = json.dumps([round(float(x), 6) for x in embedding.astype(np.float32).flatten()])
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
pid = str(uuid.uuid4())
with self.connect() as conn:
conn.execute(
"""
INSERT INTO enrolled_face_profiles (profile_id, student_id, embedding_vector, source_image, created_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(student_id, source_image) DO UPDATE SET
embedding_vector = excluded.embedding_vector,
created_at = excluded.created_at
""",
(pid, sid, vec_json, source_image, now),
)
row = conn.execute(
"SELECT profile_id FROM enrolled_face_profiles WHERE student_id = ? AND source_image = ?",
(sid, source_image),
).fetchone()
return str(row["profile_id"]) if row else pid
def delete_face_profile(self, profile_id: str) -> Optional[dict[str, str]]:
with self.connect() as conn:
row = conn.execute(
"""
SELECT p.profile_id, p.student_id, p.source_image, s.student_name
FROM enrolled_face_profiles p
JOIN students s ON p.student_id = s.student_id
WHERE p.profile_id = ?
""",
(profile_id,),
).fetchone()
if not row:
return None
info = dict(row)
conn.execute("DELETE FROM enrolled_face_profiles WHERE profile_id = ?", (profile_id,))
return info
def list_students_with_profiles(self) -> list[dict[str, Any]]:
with self.connect() as conn:
students = conn.execute(
"SELECT student_id, student_name FROM students ORDER BY student_id"
).fetchall()
result: list[dict[str, Any]] = []
for s in students:
sid = s["student_id"]
courses = [
dict(c)
for c in conn.execute(
"""
SELECT c.course_code, c.course_name
FROM course_enrollments ce
JOIN courses c ON ce.course_code = c.course_code
WHERE ce.student_id = ?
ORDER BY c.course_code
""",
(sid,),
).fetchall()
]
profiles = [
dict(p)
for p in conn.execute(
"""
SELECT profile_id, source_image, created_at
FROM enrolled_face_profiles
WHERE student_id = ?
ORDER BY created_at
""",
(sid,),
).fetchall()
]
result.append(
{
"student_id": sid,
"student_name": s["student_name"],
"courses": courses,
"profiles": profiles,
"photo_count": len(profiles),
}
)
return result
def load_enrolled_profiles(self, course_code: Optional[str] = None) -> list[dict[str, Any]]:
with self.connect() as conn:
rows = []
if course_code:
rows = conn.execute(
"""
SELECT p.profile_id, s.student_id, s.student_name, p.embedding_vector, p.source_image
FROM enrolled_face_profiles p
JOIN students s ON p.student_id = s.student_id
JOIN course_enrollments ce ON s.student_id = ce.student_id
WHERE ce.course_code = ?
ORDER BY s.student_id, p.created_at
""",
(course_code.strip().upper(),),
).fetchall()
if not rows:
rows = conn.execute(
"""
SELECT p.profile_id, s.student_id, s.student_name, p.embedding_vector, p.source_image
FROM enrolled_face_profiles p
JOIN students s ON p.student_id = s.student_id
ORDER BY s.student_id, p.created_at
"""
).fetchall()
profiles: list[dict[str, Any]] = []
for r in rows:
vec = np.array(json.loads(r["embedding_vector"]), dtype=np.float32)
profiles.append(
{
"profile_id": r["profile_id"],
"student_id": r["student_id"],
"student_name": r["student_name"],
"full_name": r["student_name"],
"source_image": r["source_image"],
"embedding": vec,
}
)
return profiles
# ------------------------------------------------------------------
# CLASS SESSIONS
# ------------------------------------------------------------------
def create_session(
self,
course_code: str,
lecturer_id: str = "LEC001",
room_number: str = "Room 101",
sampling_interval_sec: float = 3.0,
course_name: Optional[str] = None,
lecturer_name: str = "Course Lecturer",
lecturer_email: str = "lecturer@university.edu",
start_time: Optional[str] = None,
end_time: Optional[str] = None,
deactivate_others: bool = True,
) -> str:
code = course_code.strip().upper()
lid = lecturer_id.strip()
session_id = str(uuid.uuid4())[:8].upper()
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
norm_start = self._normalize_timestamp(start_time) or now
norm_end = self._normalize_timestamp(end_time)
with self.connect() as conn:
conn.execute(
"""
INSERT INTO courses (course_code, course_name)
VALUES (?, ?)
ON CONFLICT(course_code) DO NOTHING
""",
(code, (course_name or f"{code} Lecture").strip()),
)
conn.execute(
"""
INSERT INTO lecturers (lecturer_id, name, email)
VALUES (?, ?, ?)
ON CONFLICT(lecturer_id) DO NOTHING
""",
(lid, lecturer_name.strip(), lecturer_email.strip()),
)
if deactivate_others:
conn.execute(
"UPDATE class_sessions SET is_active = 0, end_time = COALESCE(end_time, ?) WHERE is_active = 1",
(now,),
)
conn.execute(
"""
INSERT INTO class_sessions
(session_id, course_code, lecturer_id, room_number, sampling_interval_sec, start_time, end_time, is_active)
VALUES (?, ?, ?, ?, ?, ?, ?, 1)
""",
(session_id, code, lid, room_number.strip(), float(sampling_interval_sec), norm_start, norm_end),
)
enrolled = conn.execute(
"SELECT student_id FROM course_enrollments WHERE course_code = ?",
(code,),
).fetchall()
if not enrolled:
enrolled = conn.execute("SELECT student_id FROM students").fetchall()
for row in enrolled:
conn.execute(
"""
INSERT OR IGNORE INTO attendance_logs
(attendance_id, session_id, student_id, sighting_count, status, is_manual_override)
VALUES (?, ?, ?, 0, 'Absent', 0)
""",
(str(uuid.uuid4()), session_id, row["student_id"]),
)
return session_id
def delete_session(self, session_id: str) -> bool:
with self.connect() as conn:
cur = conn.execute("DELETE FROM class_sessions WHERE session_id = ?", (session_id.strip(),))
return cur.rowcount > 0
def list_sessions(self) -> list[dict[str, Any]]:
with self.connect() as conn:
rows = conn.execute(
"""
SELECT cs.session_id, cs.course_code, c.course_name,
cs.lecturer_id, l.name AS lecturer_name,
cs.room_number, cs.sampling_interval_sec,
cs.start_time, cs.end_time, cs.is_active
FROM class_sessions cs
JOIN courses c ON cs.course_code = c.course_code
JOIN lecturers l ON cs.lecturer_id = l.lecturer_id
ORDER BY cs.start_time DESC
"""
).fetchall()
return [dict(r) for r in rows]
def finalize_attendance(self, session_id: str, min_sightings: int = 3) -> list[dict[str, Any]]:
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with self.connect() as conn:
sess = conn.execute(
"SELECT course_code FROM class_sessions WHERE session_id = ?",
(session_id,),
).fetchone()
if not sess:
return []
code = sess["course_code"]
conn.execute(
"UPDATE class_sessions SET end_time = COALESCE(end_time, ?), is_active = 0 WHERE session_id = ?",
(now, session_id),
)
students = conn.execute(
"""
SELECT s.student_id, s.student_name
FROM students s
JOIN course_enrollments ce ON s.student_id = ce.student_id
WHERE ce.course_code = ?
ORDER BY s.student_id
""",
(code,),
).fetchall()
if not students:
students = conn.execute("SELECT student_id, student_name FROM students ORDER BY student_id").fetchall()
report: list[dict[str, Any]] = []
for s in students:
sid = s["student_id"]
stats = conn.execute(
"""
SELECT COUNT(*) AS cnt, MIN(timestamp) AS first_ts, MAX(confidence_score) AS max_conf
FROM attendance_sightings
WHERE session_id = ? AND student_id = ?
""",
(session_id, sid),
).fetchone()
cnt = int(stats["cnt"])
first_ts = stats["first_ts"]
max_conf = float(stats["max_conf"]) if stats["max_conf"] is not None else None
status = "Present" if cnt >= min_sightings else "Absent"
conn.execute(
"""
INSERT INTO attendance_logs
(attendance_id, session_id, student_id, sighting_count, first_seen_timestamp, status, is_manual_override, confidence_score)
VALUES (?, ?, ?, ?, ?, ?, 0, ?)
ON CONFLICT(session_id, student_id) DO UPDATE SET
sighting_count = excluded.sighting_count,
first_seen_timestamp = excluded.first_seen_timestamp,
confidence_score = excluded.confidence_score,
status = CASE
WHEN attendance_logs.is_manual_override = 1 THEN attendance_logs.status
ELSE excluded.status
END
""",
(str(uuid.uuid4()), session_id, sid, cnt, first_ts, status, max_conf),
)
report.append(
{
"student_id": sid,
"student_name": s["student_name"],
"status": status,
"sighting_count": cnt,
"first_seen_timestamp": first_ts or "-",
}
)
return report
# ------------------------------------------------------------------
# PIPELINE EVENT PERSISTENCE
# ------------------------------------------------------------------
def persist_events(
self,
session_id: str,
events: list[dict[str, Any]],
min_sightings_present: int = 3,
) -> None:
if not events or not session_id:
return
with self.connect() as conn:
exists = conn.execute(
"SELECT 1 FROM class_sessions WHERE session_id = ?",
(session_id,),
).fetchone()
if not exists:
return
_cp_persist_extra_events(conn, session_id, events)
for ev in events:
etype = ev.get("type")
if etype == "raw_sighting":
conn.execute(
"""
INSERT INTO frame_sightings (sighting_id, session_id, tracking_id, timestamp)
VALUES (?, ?, ?, ?)
""",
(str(uuid.uuid4()), session_id, int(ev.get("track_id", 0)), ev.get("timestamp", "")),
)
elif etype == "attendance_sighting":
sid = str(ev["student_id"])
ts = str(ev.get("timestamp", ""))
sim = max(0.0, min(1.0, float(ev.get("similarity") or ev.get("confidence_score") or 0.0)))
tid = int(ev.get("track_id") or ev.get("tracking_id") or 0)
conn.execute(
"""
INSERT INTO attendance_sightings
(match_id, session_id, student_id, tracking_id, timestamp, confidence_score)
VALUES (?, ?, ?, ?, ?, ?)
""",
(str(uuid.uuid4()), session_id, sid, tid, ts, sim),
)
conn.execute(
"""
INSERT OR IGNORE INTO attendance_logs
(attendance_id, session_id, student_id, sighting_count, status, is_manual_override)
VALUES (?, ?, ?, 0, 'Absent', 0)
""",
(str(uuid.uuid4()), session_id, sid),
)
conn.execute(
"""
UPDATE attendance_logs
SET sighting_count = sighting_count + 1,
first_seen_timestamp = COALESCE(first_seen_timestamp, ?),
confidence_score = MAX(COALESCE(confidence_score, 0.0), ?),
status = CASE
WHEN is_manual_override = 1 THEN status
WHEN (sighting_count + 1) >= ? THEN 'Present'
ELSE 'Absent'
END
WHERE session_id = ? AND student_id = ?
""",
(ts, sim, int(min_sightings_present), session_id, sid),
)
elif etype == "unknown_face":
conn.execute(
"""
INSERT INTO unknown_faces
(unknown_id, session_id, tracking_id, timestamp, crop_file_path, status)
VALUES (?, ?, ?, ?, ?, 'Pending')
ON CONFLICT(session_id, tracking_id) DO NOTHING
""",
(
str(uuid.uuid4()),
session_id,
int(ev.get("track_id", 0)),
str(ev.get("timestamp", "")),
str(ev.get("crop_path") or ev.get("crop_file_path") or ""),
),
)
elif etype == "attention_update" or (
etype == "behavior_update"
and not ev.get("phone_in_use")
and ev.get("behavior_type") != "Phone Use"
):
sid = ev.get("student_id")
if not sid:
continue
raw_state = str(ev.get("attention_state", "Attentive"))
if raw_state == "Low Engage":
raw_state = "Low Engagement"
if raw_state not in {"Attentive", "Low Engagement", "Looking Away"}:
raw_state = "Attentive"
expr = str(ev.get("expression_state", "Not Evaluated"))
if expr not in {"Alert", "Drowsy", "Yawning", "Not Evaluated"}:
expr = "Not Evaluated"
conn.execute(
"""
INSERT INTO attention_logs
(attention_id, session_id, student_id, timestamp, yaw_angle, pitch_angle, expression_state, attention_state)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
str(uuid.uuid4()),
session_id,
str(sid),
str(ev.get("timestamp", "")),
float(ev.get("yaw_angle", 0.0)),
float(ev.get("pitch_angle", 0.0)),
expr,
raw_state,
),
)
elif etype in ("behavior_update", "phone_event") and (
ev.get("phone_in_use")
or ev.get("behavior_type") == "Phone Use"
or etype == "phone_event"
):
sid = ev.get("student_id")
if not sid:
continue
ts = str(ev.get("timestamp", ""))
samples = max(3, int(ev.get("sample_count", 3)))
conn.execute(
"""
INSERT INTO behavior_logs
(log_id, session_id, student_id, timestamp, last_updated_at, behavior_type, sample_count)
VALUES (?, ?, ?, ?, ?, 'Phone Use', ?)
ON CONFLICT(session_id, student_id, behavior_type) DO UPDATE SET
sample_count = behavior_logs.sample_count + 1,
last_updated_at = excluded.last_updated_at
""",
(str(uuid.uuid4()), session_id, str(sid), ts, ts, samples),
)
elif etype == "incident_flag":
raw_flag = str(ev.get("flag_type", "Drinking Flag"))
if raw_flag == "Drinking":
raw_flag = "Drinking Flag"
elif raw_flag == "Smoking":
raw_flag = "Smoking Flag"
conn.execute(
"""
INSERT INTO flagged_events
(event_id, session_id, student_id, tracking_id, flag_type, clip_file_path, confidence_score, status, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, 'Unconfirmed', ?)
""",
(
str(uuid.uuid4()),
session_id,
(None if ev.get("student_id") in (None, "", "None", "Unknown") else str(ev.get("student_id"))),
ev.get("track_id"),
raw_flag,
str(ev.get("clip_path") or ev.get("clip_file_path") or ""),
ev.get("confidence_score"),
str(ev.get("timestamp", "")),
),
)
# ------------------------------------------------------------------
# LECTURER ACTIONS & DASHBOARD QUERIES
# ------------------------------------------------------------------
def override_attendance(self, session_id: str, student_id: str, status: str) -> None:
if status not in {"Present", "Absent"}:
raise ValueError("Status must be Present or Absent")
with self.connect() as conn:
conn.execute(
"""
INSERT INTO attendance_logs
(attendance_id, session_id, student_id, sighting_count, status, is_manual_override)
VALUES (?, ?, ?, 0, ?, 1)
ON CONFLICT(session_id, student_id) DO UPDATE SET
status = excluded.status,
is_manual_override = 1
""",
(str(uuid.uuid4()), session_id, student_id, status),
)
def review_flag(self, event_id: str, action: str) -> Optional[str]:
if action not in {"Confirmed", "Dismissed"}:
raise ValueError("Action must be Confirmed or Dismissed")
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with self.connect() as conn:
row = conn.execute(
"SELECT clip_file_path FROM flagged_events WHERE event_id = ?",
(event_id,),
).fetchone()
if not row:
return None
clip_path = row["clip_file_path"]
if action == "Dismissed":
conn.execute(
"""
UPDATE flagged_events
SET status = 'Dismissed', clip_file_path = NULL, reviewed_at = ?
WHERE event_id = ?
""",
(now, event_id),
)
else:
conn.execute(
"""
UPDATE flagged_events
SET status = 'Confirmed', reviewed_at = ?
WHERE event_id = ?
""",
(now, event_id),
)
if action == "Dismissed" and clip_path:
Path(clip_path).unlink(missing_ok=True)
return action
def assign_unknown(self, unknown_id: str, student_id: str, min_sightings_present: int = 3) -> bool:
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with self.connect() as conn:
unk = conn.execute(
"SELECT session_id, tracking_id, timestamp FROM unknown_faces WHERE unknown_id = ?",
(unknown_id,),
).fetchone()
if not unk:
return False
sid_session = unk["session_id"]
conn.execute(
"""
UPDATE unknown_faces
SET assigned_student_id = ?, status = 'Assigned', reviewed_at = ?
WHERE unknown_id = ?
""",
(student_id, now, unknown_id),
)
conn.execute(
"""
INSERT INTO attendance_sightings
(match_id, session_id, student_id, tracking_id, timestamp, confidence_score)
VALUES (?, ?, ?, ?, ?, 1.0)
""",
(str(uuid.uuid4()), sid_session, student_id, int(unk["tracking_id"]), unk["timestamp"]),
)
conn.execute(
"""
INSERT OR IGNORE INTO attendance_logs
(attendance_id, session_id, student_id, sighting_count, status, is_manual_override)
VALUES (?, ?, ?, 0, 'Absent', 0)
""",
(str(uuid.uuid4()), sid_session, student_id),
)
conn.execute(
"""
UPDATE attendance_logs
SET sighting_count = sighting_count + 1,
first_seen_timestamp = COALESCE(first_seen_timestamp, ?),
status = CASE
WHEN is_manual_override = 1 THEN status
WHEN (sighting_count + 1) >= ? THEN 'Present'
ELSE 'Absent'
END
WHERE session_id = ? AND student_id = ?
""",
(unk["timestamp"], int(min_sightings_present), sid_session, student_id),
)
return True
def get_session_summary(self, session_id: str) -> Optional[dict[str, Any]]:
with self.connect() as conn:
sess = conn.execute(
"""
SELECT cs.*, c.course_name, l.name AS lecturer_name
FROM class_sessions cs
JOIN courses c ON cs.course_code = c.course_code
JOIN lecturers l ON cs.lecturer_id = l.lecturer_id
WHERE cs.session_id = ?
""",
(session_id,),
).fetchone()
if not sess:
return None
code = sess["course_code"]
enrolled_rows = conn.execute(
"""
SELECT s.student_id, s.student_name
FROM students s
JOIN course_enrollments ce ON s.student_id = ce.student_id
WHERE ce.course_code = ?
ORDER BY s.student_id
""",
(code,),
).fetchall()
if not enrolled_rows:
enrolled_rows = conn.execute(
"SELECT student_id, student_name FROM students ORDER BY student_id"
).fetchall()
roster: list[dict[str, Any]] = []
present_count = 0
tot_att = 0
tot_low = 0
tot_away = 0
tot_phone = 0
for s in enrolled_rows:
sid = s["student_id"]
al = conn.execute(
"""
SELECT *
FROM attendance_logs
WHERE session_id = ? AND student_id = ?
""",
(session_id, sid),
).fetchone()
sighting_count = int(al["sighting_count"]) if al else 0
first_seen = al["first_seen_timestamp"] if al else None
status = al["status"] if al else "Absent"
overridden = bool(al["is_manual_override"]) if al else False
if status == "Present":
present_count += 1
att_rows = conn.execute(
"SELECT attention_state FROM attention_logs WHERE session_id = ? AND student_id = ?",
(session_id, sid),
).fetchall()
a_cnt = sum(1 for r in att_rows if r["attention_state"] == "Attentive")
l_cnt = sum(1 for r in att_rows if r["attention_state"] == "Low Engagement")
w_cnt = sum(1 for r in att_rows if r["attention_state"] == "Looking Away")
b_tot = a_cnt + l_cnt + w_cnt
att_pct = round((a_cnt / b_tot) * 100.0, 1) if b_tot else 0.0
ph_row = conn.execute(
"""
SELECT COALESCE(SUM(sample_count), 0) AS samples, COALESCE(SUM(usage_seconds), 0.0) AS usage_sec, MAX(clip_path) AS clip_path
FROM behavior_logs
WHERE session_id = ? AND student_id = ? AND behavior_type = 'Phone Use'
""",
(session_id, sid),
).fetchone()
ph_samples = int(ph_row["samples"]) if ph_row else 0
tot_att += a_cnt
tot_low += l_cnt
tot_away += w_cnt
tot_phone += ph_samples
roster.append(
{
"student_id": sid,
"student_name": s["student_name"],
"sighting_count": sighting_count,
"first_seen_at": first_seen,
"status": status,
"overridden_by_lecturer": overridden,
"attentive_count": a_cnt,
"low_engage_count": l_cnt,
"looking_away_count": w_cnt,
"attention_pct": att_pct,
"phone_count": ph_samples,
"attentive_seconds": round(float(al["attentive_seconds"] or 0.0), 1) if (al and "attentive_seconds" in al.keys()) else 0.0,
"attentive_time_fmt": format_duration(al["attentive_seconds"] if (al and "attentive_seconds" in al.keys()) else 0.0),
"phone_usage_seconds": round(float(ph_row["usage_sec"] or 0.0), 1) if (ph_row and "usage_sec" in ph_row.keys()) else 0.0,
"phone_usage_fmt": format_duration(ph_row["usage_sec"] if (ph_row and "usage_sec" in ph_row.keys()) else 0.0),
"phone_clip_url": f"/clips/{Path(ph_row['clip_path']).name}" if (ph_row and "clip_path" in ph_row.keys() and ph_row["clip_path"]) else None,
}
)
flags = [
dict(f)
for f in conn.execute(
"""
SELECT fe.*, s.student_name
FROM flagged_events fe
LEFT JOIN students s ON fe.student_id = s.student_id
WHERE fe.session_id = ?
ORDER BY fe.created_at DESC
""",
(session_id,),
).fetchall()
]
for f in flags:
clip = f.get("clip_file_path")
f["clip_url"] = f"/clips/{Path(clip).name}" if clip else None
unknowns = [
dict(u)
for u in conn.execute(
"""
SELECT * FROM unknown_faces
WHERE session_id = ?
ORDER BY timestamp DESC
""",
(session_id,),
).fetchall()
]
for u in unknowns:
u["crop_url"] = f"/unknown_faces/{Path(u['crop_file_path']).name}"
raw_count = conn.execute(
"SELECT COUNT(*) AS c FROM frame_sightings WHERE session_id = ?",
(session_id,),
).fetchone()["c"]
_cp_summary = {
"session": dict(sess),
"metrics": {
"enrolled_total": len(roster),
"present_count": present_count,
"attentive_samples": tot_att,
"low_engage_samples": tot_low,
"looking_away_samples": tot_away,
"phone_use_samples": tot_phone,
"pending_flags": sum(1 for f in flags if f["status"] == "Unconfirmed"),
"unassigned_unknowns": sum(1 for u in unknowns if u["status"] == "Pending"),
"raw_tracking_sightings": int(raw_count),
},
"roster": roster,
"incident_flags": flags,
"unknown_faces": unknowns,
}
with self.connect() as _cp_c:
_cp_summary = _cp_enrich_summary(_cp_c, session_id, _cp_summary)
return _cp_summary
def get_student_portal(self, student_id: str) -> Optional[dict[str, Any]]:
sid = student_id.strip()
with self.connect() as conn:
st = conn.execute(
"SELECT student_id, student_name FROM students WHERE student_id = ?",
(sid,),
).fetchone()
if not st:
return None
courses = [
dict(c)
for c in conn.execute(
"""
SELECT c.course_code, c.course_name
FROM course_enrollments ce
JOIN courses c ON ce.course_code = c.course_code
WHERE ce.student_id = ?
ORDER BY c.course_code
""",
(sid,),
).fetchall()
]
sessions = conn.execute(
"""
SELECT cs.session_id, cs.course_code, c.course_name, cs.room_number,
cs.start_time, cs.end_time, cs.is_active,
COALESCE(al.status, 'Absent') AS status,
COALESCE(al.sighting_count, 0) AS sighting_count,
al.first_seen_timestamp
FROM class_sessions cs
JOIN courses c ON cs.course_code = c.course_code
LEFT JOIN attendance_logs al
ON cs.session_id = al.session_id AND al.student_id = ?
WHERE EXISTS (
SELECT 1 FROM course_enrollments ce
WHERE ce.course_code = cs.course_code AND ce.student_id = ?
) OR al.student_id IS NOT NULL
ORDER BY cs.start_time DESC
""",
(sid, sid),
).fetchall()
session_list: list[dict[str, Any]] = []
present_sessions = 0
tot_a = 0
tot_l = 0
tot_w = 0
tot_ph = 0
for s in sessions:
sess_id = s["session_id"]
if s["status"] == "Present":
present_sessions += 1
att_rows = conn.execute(
"SELECT attention_state FROM attention_logs WHERE session_id = ? AND student_id = ?",
(sess_id, sid),
).fetchall()
a_cnt = sum(1 for r in att_rows if r["attention_state"] == "Attentive")
l_cnt = sum(1 for r in att_rows if r["attention_state"] == "Low Engagement")
w_cnt = sum(1 for r in att_rows if r["attention_state"] == "Looking Away")
b_tot = a_cnt + l_cnt + w_cnt
att_pct = round((a_cnt / b_tot) * 100.0, 1) if b_tot else 0.0
ph_row = conn.execute(
"""
SELECT COALESCE(SUM(sample_count), 0) AS samples, COALESCE(SUM(usage_seconds), 0.0) AS usage_sec, MAX(clip_path) AS clip_path
FROM behavior_logs
WHERE session_id = ? AND student_id = ? AND behavior_type = 'Phone Use'
""",
(sess_id, sid),
).fetchone()
ph_samples = int(ph_row["samples"]) if ph_row else 0
tot_a += a_cnt
tot_l += l_cnt
tot_w += w_cnt
tot_ph += ph_samples
item = dict(s)
item["attentive_count"] = a_cnt
item["low_engage_count"] = l_cnt
item["looking_away_count"] = w_cnt
item["attention_pct"] = att_pct
item["phone_count"] = ph_samples
session_list.append(item)
tot_sessions = len(session_list)
tot_beh = tot_a + tot_l + tot_w
return {
"student": dict(st),
"courses": courses,
"overview": {
"sessions_present": present_sessions,
"sessions_total": tot_sessions,
"attendance_rate_pct": round((present_sessions / tot_sessions) * 100.0, 1) if tot_sessions else 0.0,
"overall_attention_pct": round((tot_a / tot_beh) * 100.0, 1) if tot_beh else 0.0,
"total_phone_samples": tot_ph,
},
"sessions": session_list,
}
# _cp_db_enhancements
def _cp_ensure_extra_columns(conn) -> None:
try:
tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()}
if "attendance_logs" in tables:
cols = {r[1] for r in conn.execute("PRAGMA table_info(attendance_logs)").fetchall()}
if "attentive_seconds" not in cols:
conn.execute("ALTER TABLE attendance_logs ADD COLUMN attentive_seconds REAL DEFAULT 0.0")
if "behavior_logs" in tables:
cols = {r[1] for r in conn.execute("PRAGMA table_info(behavior_logs)").fetchall()}
if "usage_seconds" not in cols:
conn.execute("ALTER TABLE behavior_logs ADD COLUMN usage_seconds REAL DEFAULT 0.0")
if "clip_path" not in cols:
conn.execute("ALTER TABLE behavior_logs ADD COLUMN clip_path TEXT DEFAULT ''")
except Exception:
pass
def _cp_persist_extra_events(conn, session_id: str, events: list[dict]) -> None:
_cp_ensure_extra_columns(conn)
for ev in events:
etype = str(ev.get("type", ""))
if etype == "attention_time" and ev.get("student_id"):
delta = float(ev.get("delta_seconds", 0.0))
sid = str(ev["student_id"])
cur = conn.execute(
"""
UPDATE attendance_logs
SET attentive_seconds = COALESCE(attentive_seconds, 0.0) + ?
WHERE session_id = ? AND student_id = ?
""",
(delta, str(session_id), sid),
)
if cur.rowcount == 0:
conn.execute(
"""
INSERT OR IGNORE INTO attendance_logs
(attendance_id, session_id, student_id, sighting_count, status, is_manual_override, attentive_seconds)
VALUES (lower(hex(randomblob(16))), ?, ?, 0, 'Absent', 0, ?)
""",
(str(session_id), sid, delta),
)
elif etype in ("phone_usage", "phone_usage_update"):
usage_sec = float(ev.get("usage_seconds", 0.0))
clip_path = str(ev.get("clip_path", "") or "")
sid = ev.get("student_id")
sid_val = None if sid in (None, "", "None", "Unknown") else str(sid)
ts = str(ev.get("timestamp", ""))
if not sid_val:
continue
if etype == "phone_usage":
conn.execute(
"""
INSERT INTO behavior_logs
(log_id, session_id, student_id, timestamp, last_updated_at, behavior_type, sample_count, usage_seconds, clip_path)
VALUES (lower(hex(randomblob(16))), ?, ?, ?, ?, 'Phone Use', 3, ?, ?)
ON CONFLICT(session_id, student_id, behavior_type) DO UPDATE SET
sample_count = behavior_logs.sample_count + 1,
last_updated_at = excluded.last_updated_at,
usage_seconds = COALESCE(behavior_logs.usage_seconds, 0.0) + excluded.usage_seconds,
clip_path = CASE WHEN excluded.clip_path != '' THEN excluded.clip_path ELSE behavior_logs.clip_path END
""",
(str(session_id), sid_val, ts, ts, usage_sec, clip_path),
)
elif etype == "phone_usage_update":
conn.execute(
"""
UPDATE behavior_logs
SET last_updated_at = ?,
usage_seconds = MAX(COALESCE(usage_seconds, 0.0), ?),
clip_path = CASE WHEN ? != '' THEN ? ELSE clip_path END
WHERE session_id = ? AND student_id = ? AND behavior_type = 'Phone Use'
""",
(ts, usage_sec, clip_path, clip_path, str(session_id), sid_val),
)
def _cp_enrich_summary(conn, session_id: str, summary: dict) -> dict:
if not summary or "roster" not in summary:
return summary
_cp_ensure_extra_columns(conn)
sess = summary.get("session") or {}
is_active = bool(sess.get("is_active", 0))
sample_sec = float(sess.get("sampling_interval_sec") or 2.0)
stale_cutoff = max(5.0, sample_sec * 3.0)
att_sec_map: dict[str, float] = {}
try:
for r in conn.execute(
"SELECT student_id, COALESCE(attentive_seconds, 0.0) AS sec FROM attendance_logs WHERE session_id = ?",
(str(session_id),),
).fetchall():
att_sec_map[str(r["student_id"])] = float(r["sec"] or 0.0)
except Exception:
pass
live_att_map: dict[str, bool] = {}
if is_active:
try:
from datetime import datetime
now_dt = datetime.now()
for r in conn.execute(
"""
SELECT student_id, attention_state, timestamp
FROM attention_logs
WHERE session_id = ?
ORDER BY rowid DESC
""",
(str(session_id),),
).fetchall():
sid = str(r["student_id"])
if sid in live_att_map:
continue
is_att_state = str(r["attention_state"] or "").strip().lower() == "attentive"
fresh = False
ts_raw = r["timestamp"]
if ts_raw:
try:
ts_dt = datetime.fromisoformat(str(ts_raw).replace(" ", "T")).replace(tzinfo=None)
fresh = (now_dt - ts_dt).total_seconds() <= stale_cutoff
except Exception:
fresh = True
live_att_map[sid] = bool(is_att_state and fresh)
except Exception:
pass
phone_map: dict[str, dict] = {}
try:
for r in conn.execute(
"""
SELECT student_id, COALESCE(SUM(usage_seconds), 0.0) AS usage_sec, MAX(clip_path) AS clip_path
FROM behavior_logs
WHERE session_id = ? AND behavior_type = 'Phone Use'
GROUP BY student_id
""",
(str(session_id),),
).fetchall():
cp = str(r["clip_path"] or "")
phone_map[str(r["student_id"])] = {
"usage_sec": float(r["usage_sec"] or 0.0),
"clip_url": f"/clips/{Path(cp).name}" if cp else None,
}
except Exception:
pass
for item in summary["roster"]:
sid = str(item.get("student_id", ""))
sec = att_sec_map.get(sid, float(item.get("attentive_seconds", 0.0)))
# Fallback estimate if attentive_count > 0 and sec == 0
if sec <= 0.0 and int(item.get("attentive_count", 0)) > 0:
sec = round(int(item["attentive_count"]) * sample_sec, 1)
item["attentive_seconds"] = round(sec, 1)
item["attentive_time_fmt"] = format_duration(sec)
item["is_currently_attentive"] = bool(is_active and live_att_map.get(sid, False))
ph = phone_map.get(sid, {})
p_sec = float(ph.get("usage_sec", 0.0))
item["phone_usage_seconds"] = round(p_sec, 1)
item["phone_usage_fmt"] = format_duration(p_sec)
item["phone_clip_url"] = ph.get("clip_url")
return summary
from __future__ import annotations
from core.clip_writer import format_duration
from datetime import datetime
import json
from pathlib import Path
import shutil
import sqlite3
from typing import Any, Optional
import uuid
import numpy as np
class DatabaseRepository:
"""3NF SQLite repository for ClassPulse Edge (13-table schema + dashboard management)."""
def __init__(self, db_path: str | Path = "data/classroom.db") -> None:
self.db_path = Path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._migrate_legacy_if_needed()
self.init_db()
def connect(self) -> sqlite3.Connection:
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON;")
return conn
def _migrate_legacy_if_needed(self) -> None:
"""Backs up an older pre-3NF classroom.db if detected so the 13-table schema initializes cleanly."""
if not self.db_path.exists():
return
try:
conn = sqlite3.connect(self.db_path)
cols = [r[1] for r in conn.execute("PRAGMA table_info(students)").fetchall()]
tables = {
r[0]
for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
}
conn.close()
if (cols and "student_name" not in cols) or ("sessions" in tables and "class_sessions" not in tables):
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup = self.db_path.with_name(f"classroom_legacy_{stamp}.db.bak")
shutil.move(str(self.db_path), str(backup))
except sqlite3.Error:
pass
def init_db(self) -> None:
with self.connect() as conn:
conn.executescript(
"""
PRAGMA foreign_keys = ON;
-- 1. CORE ACADEMIC & BIOMETRIC REGISTRY
CREATE TABLE IF NOT EXISTS courses (
course_code VARCHAR(20) PRIMARY KEY,
course_name VARCHAR(100) NOT NULL
);
CREATE TABLE IF NOT EXISTS lecturers (
lecturer_id VARCHAR(36) PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS students (
student_id VARCHAR(50) PRIMARY KEY,
student_name VARCHAR(100) NOT NULL
);
CREATE TABLE IF NOT EXISTS course_enrollments (
course_code VARCHAR(20) NOT NULL,
student_id VARCHAR(50) NOT NULL,
enrolled_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (course_code, student_id),
FOREIGN KEY (course_code) REFERENCES courses (course_code) ON DELETE CASCADE,
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS enrolled_face_profiles (
profile_id VARCHAR(36) PRIMARY KEY,
student_id VARCHAR(50) NOT NULL,
embedding_vector TEXT NOT NULL,
source_image VARCHAR(150) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (student_id, source_image),
FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE
);
-- 2. SESSION EXECUTION & PRE-BRANCH TRACKING
CREATE TABLE IF NOT EXISTS class_sessions (
session_id VARCHAR(36) PRIMARY KEY,
course_code VARCHAR(20) NOT NULL,
lecturer_id VARCHAR(36) NOT NULL,
room_number VARCHAR(20) NOT NULL,
sampling_interval_sec FLOAT NOT NULL DEFAULT 3.0 CHECK (sampling_interval_sec > 0),
start_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
end_time TIMESTAMP,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
FOREIGN KEY (course_code) REFERENCES courses (course_code) ON DELETE CASCADE,
FOREIGN KEY (lecturer_id) REFERENCES lecturers (lecturer_id) ON DELETE RESTRICT