# backend/api/websocket.py from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.middleware.cors import CORSMiddleware import asyncio import json import cv2 import base64 app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.websocket("/ws/video") async def video_websocket(websocket: WebSocket): await websocket.accept() # Initialize components detector = FaceDetector() recognizer = FaceRecognizer() attendance_manager = AttendanceManager(db_session) processor = VideoProcessor(detector, recognizer, attendance_manager) try: async for frame in processor.process_video(): # Encode frame to JPEG _, buffer = cv2.imencode('.jpg', frame) frame_b64 = base64.b64encode(buffer).decode('utf-8') # Send to client await websocket.send_json({ 'frame': frame_b64, 'timestamp': datetime.now().isoformat() }) except WebSocketDisconnect: print("Client disconnected") @app.get("/api/analytics/dashboard") async def get_dashboard_data(): """Get all dashboard metrics""" analytics = AnalyticsService(db_session) return { 'personnel_present': analytics.get_personnel_present(), 'shift_coverage': analytics.get_shift_coverage(), 'staffing_trends': analytics.get_staffing_trends().to_dict(), 'missing_personnel': [ {'id': e.id, 'name': e.name} for e in analytics.get_missing_personnel() ], 'timestamp': datetime.now().isoformat() }