Spaces:
Sleeping
Sleeping
Commit ·
d0d87a8
1
Parent(s): 53a80fb
feat: optimize streaming to JSON coordinates and implement direct backend attendance marking
Browse files
main.py
CHANGED
|
@@ -3,13 +3,16 @@ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
from contextlib import asynccontextmanager
|
| 5 |
|
| 6 |
-
from database import engine, Base
|
| 7 |
from routers import auth, students, subjects, attendance, registration, alerts, admin
|
| 8 |
from services.camera import camera_streamer
|
| 9 |
from services.face_engine import face_engine
|
| 10 |
from services.notifier import manager
|
| 11 |
from seed import seed_db
|
| 12 |
import logging
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
logging.basicConfig(level=logging.INFO)
|
| 15 |
logger = logging.getLogger(__name__)
|
|
@@ -97,6 +100,11 @@ async def camera_stream(websocket: WebSocket):
|
|
| 97 |
if msg.get("type") == "frame":
|
| 98 |
base64_data = msg.get("data")
|
| 99 |
subject_id = msg.get("subject_id")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
if not base64_data:
|
| 101 |
continue
|
| 102 |
|
|
@@ -139,43 +147,82 @@ async def camera_stream(websocket: WebSocket):
|
|
| 139 |
roll_no, confidence = "spoof", 0.0
|
| 140 |
|
| 141 |
faces_info.append({
|
| 142 |
-
"bbox":
|
| 143 |
"roll_no": roll_no,
|
| 144 |
"confidence": confidence,
|
| 145 |
"is_live": is_live
|
| 146 |
})
|
| 147 |
|
| 148 |
-
#
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
-
#
|
| 166 |
-
try:
|
| 167 |
-
_, buffer = cv2.imencode('.jpg', frame)
|
| 168 |
-
b64_frame = base64.b64encode(buffer).decode('utf-8')
|
| 169 |
-
|
| 170 |
-
# Send the processed frame back to the client
|
| 171 |
-
await websocket.send_json({
|
| 172 |
-
"type": "frame",
|
| 173 |
-
"data": b64_frame
|
| 174 |
-
})
|
| 175 |
-
except Exception as e:
|
| 176 |
-
logger.error(f"Failed to encode or send frame: {e}")
|
| 177 |
-
|
| 178 |
-
# Send identified/unknown events to client
|
| 179 |
for f in faces_info:
|
| 180 |
if f['roll_no'] != "unknown" and f['roll_no'] != "spoof":
|
| 181 |
await websocket.send_json({
|
|
|
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
from contextlib import asynccontextmanager
|
| 5 |
|
| 6 |
+
from database import engine, Base, AsyncSessionLocal
|
| 7 |
from routers import auth, students, subjects, attendance, registration, alerts, admin
|
| 8 |
from services.camera import camera_streamer
|
| 9 |
from services.face_engine import face_engine
|
| 10 |
from services.notifier import manager
|
| 11 |
from seed import seed_db
|
| 12 |
import logging
|
| 13 |
+
from sqlalchemy.future import select
|
| 14 |
+
from models import Attendance, Student
|
| 15 |
+
from datetime import date, datetime, timezone
|
| 16 |
|
| 17 |
logging.basicConfig(level=logging.INFO)
|
| 18 |
logger = logging.getLogger(__name__)
|
|
|
|
| 100 |
if msg.get("type") == "frame":
|
| 101 |
base64_data = msg.get("data")
|
| 102 |
subject_id = msg.get("subject_id")
|
| 103 |
+
try:
|
| 104 |
+
subject_id = int(subject_id) if subject_id is not None else None
|
| 105 |
+
except ValueError:
|
| 106 |
+
subject_id = None
|
| 107 |
+
|
| 108 |
if not base64_data:
|
| 109 |
continue
|
| 110 |
|
|
|
|
| 147 |
roll_no, confidence = "spoof", 0.0
|
| 148 |
|
| 149 |
faces_info.append({
|
| 150 |
+
"bbox": [x1, y1, x2, y2],
|
| 151 |
"roll_no": roll_no,
|
| 152 |
"confidence": confidence,
|
| 153 |
"is_live": is_live
|
| 154 |
})
|
| 155 |
|
| 156 |
+
# Send faces coordinates and labels to client for 30fps overlay rendering
|
| 157 |
+
await websocket.send_json({
|
| 158 |
+
"type": "faces",
|
| 159 |
+
"faces": faces_info
|
| 160 |
+
})
|
| 161 |
+
|
| 162 |
+
# Direct database write for recognized faces
|
| 163 |
+
if subject_id is not None:
|
| 164 |
+
for f in faces_info:
|
| 165 |
+
if f['roll_no'] != "unknown" and f['roll_no'] != "spoof" and f['confidence'] >= 0.50:
|
| 166 |
+
try:
|
| 167 |
+
async with AsyncSessionLocal() as db_session:
|
| 168 |
+
# Check if already marked today for this period (default period 1)
|
| 169 |
+
query = select(Attendance).where(
|
| 170 |
+
Attendance.roll_no == f['roll_no'],
|
| 171 |
+
Attendance.subject_id == subject_id,
|
| 172 |
+
Attendance.date == date.today(),
|
| 173 |
+
Attendance.period == 1
|
| 174 |
+
)
|
| 175 |
+
db_res = await db_session.execute(query)
|
| 176 |
+
existing = db_res.scalars().first()
|
| 177 |
+
|
| 178 |
+
if existing:
|
| 179 |
+
# Rate limit Neon DB updates to avoid transactional locks (only update every 15s)
|
| 180 |
+
time_diff = datetime.now(timezone.utc) - existing.marked_at.replace(tzinfo=timezone.utc) if existing.marked_at else None
|
| 181 |
+
if time_diff is None or time_diff.total_seconds() > 15:
|
| 182 |
+
existing.marked_at = datetime.now(timezone.utc)
|
| 183 |
+
await db_session.commit()
|
| 184 |
+
|
| 185 |
+
student_res = await db_session.execute(select(Student).where(Student.roll_no == f['roll_no']))
|
| 186 |
+
student = student_res.scalars().first()
|
| 187 |
+
student_name = student.name if student else "Unknown Student"
|
| 188 |
+
|
| 189 |
+
await manager.broadcast({
|
| 190 |
+
"type": "marked",
|
| 191 |
+
"roll_no": f['roll_no'],
|
| 192 |
+
"name": student_name,
|
| 193 |
+
"subject_id": subject_id,
|
| 194 |
+
"timestamp": existing.marked_at.replace(tzinfo=timezone.utc).isoformat(),
|
| 195 |
+
"status": existing.status
|
| 196 |
+
})
|
| 197 |
+
else:
|
| 198 |
+
new_att = Attendance(
|
| 199 |
+
roll_no=f['roll_no'],
|
| 200 |
+
subject_id=subject_id,
|
| 201 |
+
date=date.today(),
|
| 202 |
+
period=1,
|
| 203 |
+
status='present',
|
| 204 |
+
confidence=f['confidence'],
|
| 205 |
+
marked_at=datetime.now(timezone.utc)
|
| 206 |
+
)
|
| 207 |
+
db_session.add(new_att)
|
| 208 |
+
await db_session.commit()
|
| 209 |
+
|
| 210 |
+
student_res = await db_session.execute(select(Student).where(Student.roll_no == f['roll_no']))
|
| 211 |
+
student = student_res.scalars().first()
|
| 212 |
+
student_name = student.name if student else "Unknown Student"
|
| 213 |
+
|
| 214 |
+
await manager.broadcast({
|
| 215 |
+
"type": "marked",
|
| 216 |
+
"roll_no": f['roll_no'],
|
| 217 |
+
"name": student_name,
|
| 218 |
+
"subject_id": subject_id,
|
| 219 |
+
"timestamp": new_att.marked_at.replace(tzinfo=timezone.utc).isoformat(),
|
| 220 |
+
"status": "present"
|
| 221 |
+
})
|
| 222 |
+
except Exception as db_err:
|
| 223 |
+
logger.error(f"Error marking attendance inside websocket loop: {db_err}")
|
| 224 |
|
| 225 |
+
# Send identified/unknown status message triggers to client
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
for f in faces_info:
|
| 227 |
if f['roll_no'] != "unknown" and f['roll_no'] != "spoof":
|
| 228 |
await websocket.send_json({
|