Spaces:
Sleeping
Sleeping
Commit ·
d0d87a8
1
Parent(s): 53a80fb
feat: optimize streaming to JSON coordinates and implement direct backend attendance marking
Browse files2 unmodified lines345678910111213141581 unmodified lines97989910010110236 unmodified lines1391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801812 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewarefrom contextlib import asynccontextmanagerfrom database import engine, Basefrom routers import auth, students, subjects, attendance, registration, alerts, adminfrom services.camera import camera_streamerfrom services.face_engine import face_enginefrom services.notifier import managerfrom seed import seed_dbimport logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)81 unmodified linesif msg.get("type") == "frame":base64_data = msg.get("data")subject_id = msg.get("subject_id")if not base64_data:continue36 unmodified linesroll_no, confidence = "spoof", 0.0faces_info.append({"bbox": face['bbox'],"roll_no": roll_no,"confidence": confidence,"is_live": is_live})# Draw bounding boxes and labels on the framefor f in faces_info:x1, y1, x2, y2 = f['bbox']if f['roll_no'] == "spoof":label = "Spoof Detected"color = (0, 165, 255) # Orangeelif f['roll_no'] == "unknown":label = "Unknown"color = (0, 0, 255) # Redelse:label = f"{f['roll_no']} ({int(f['confidence']*100)}%)"color = (0, 255, 0) # Greencv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)cv2.putText(frame, label, (x1, max(0, y1 - 10)),cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)# Encode processed frame back to base64try:_, buffer = cv2.imencode('.jpg', frame)b64_frame = base64.b64encode(buffer).decode('utf-8')# Send the processed frame back to the clientawait websocket.send_json({"type": "frame","data": b64_frame})except Exception as e:logger.error(f"Failed to encode or send frame: {e}")# Send identified/unknown events to clientfor f in faces_info:if f['roll_no'] != "unknown" and f['roll_no'] != "spoof":await websocket.send_json({2 unmodified lines345678910111213141516171881 unmodified lines10010110210310410510610710810911036 unmodified lines1471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewarefrom contextlib import asynccontextmanagerfrom database import engine, Base, AsyncSessionLocalfrom routers import auth, students, subjects, attendance, registration, alerts, adminfrom services.camera import camera_streamerfrom services.face_engine import face_enginefrom services.notifier import managerfrom seed import seed_dbimport loggingfrom sqlalchemy.future import selectfrom models import Attendance, Studentfrom datetime import date, datetime, timezonelogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)81 unmodified linesif msg.get("type") == "frame":base64_data = msg.get("data")subject_id = msg.get("subject_id")try:subject_id = int(subject_id) if subject_id is not None else Noneexcept ValueError:subject_id = Noneif not base64_data:continue36 unmodified linesroll_no, confidence = "spoof", 0.0faces_info.append({"bbox": [x1, y1, x2, y2],"roll_no": roll_no,"confidence": confidence,"is_live": is_live})# Send faces coordinates and labels to client for 30fps overlay renderingawait websocket.send_json({"type": "faces","faces": faces_info})# Direct database write for recognized facesif subject_id is not None:for f in faces_info:if f['roll_no'] != "unknown" and f['roll_no'] != "spoof" and f['confidence'] >= 0.50:try:async with AsyncSessionLocal() as db_session:# Check if already marked today for this period (default period 1)query = select(Attendance).where(Attendance.roll_no == f['roll_no'],Attendance.subject_id == subject_id,Attendance.date == date.today(),Attendance.period == 1)db_res = await db_session.execute(query)existing = db_res.scalars().first()if existing:# Rate limit Neon DB updates to avoid transactional locks (only update every 15s)time_diff = datetime.now(timezone.utc) - existing.marked_at.replace(tzinfo=timezone.utc) if existing.marked_at else Noneif time_diff is None or time_diff.total_seconds() > 15:existing.marked_at = datetime.now(timezone.utc)await db_session.commit()student_res = await db_session.execute(select(Student).where(Student.roll_no == f['roll_no']))student = student_res.scalars().first()student_name = student.name if student else "Unknown Student"await manager.broadcast({"type": "marked","roll_no": f['roll_no'],"name": student_name,"subject_id": subject_id,"timestamp": existing.marked_at.replace(tzinfo=timezone.utc).isoformat(),"status": existing.status})else:new_att = Attendance(roll_no=f['roll_no'],subject_id=subject_id,date=date.today(),period=1,status='present',confidence=f['confidence'],marked_at=datetime.now(timezone.utc))db_session.add(new_att)await db_session.commit()student_res = await db_session.execute(select(Student).where(Student.roll_no == f['roll_no']))student = student_res.scalars().first()student_name = student.name if student else "Unknown Student"await manager.broadcast({"type": "marked","roll_no": f['roll_no'],"name": student_name,"subject_id": subject_id,"timestamp": new_att.marked_at.replace(tzinfo=timezone.utc).isoformat(),"status": "present"})except Exception as db_err:logger.error(f"Error marking attendance inside websocket loop: {db_err}")# Send identified/unknown status message triggers to clientfor f in faces_info:if f['roll_no'] != "unknown" and f['roll_no'] != "spoof":await websocket.send_json({
main.py+79-32