File size: 21,361 Bytes
099d157 | 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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | """
The Sentinel Interface β FastAPI Backend
Main application with REST API + WebSocket endpoints for real-time emotion analysis.
"""
import os
import sys
import json
import base64
import asyncio
import traceback
from datetime import datetime
import io
import csv
import numpy as np
import cv2
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, UploadFile, File, Form, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse, HTMLResponse, StreamingResponse
from pydantic import BaseModel
from typing import Optional, List
# Ensure models are importable
sys.path.insert(0, os.path.dirname(__file__))
import database as db
# ββ App Setup ββββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(
title="The Sentinel Interface API",
description="Multisource Emotion Detection & Engagement Optimization for E-Learning",
version="1.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ββ Lazy Model Loading βββββββββββββββββββββββββββββββββββββ
# Models are loaded on first use to speed up server startup
_models_loaded = {
"face": False,
"face_mesh": False,
"speech": False,
"text": False,
}
def get_face_model():
from models.face_model import predict_emotion
_models_loaded["face"] = True
return predict_emotion
def get_face_mesh():
from models.face_mesh import process_frame, reset as reset_mesh
_models_loaded["face_mesh"] = True
return process_frame, reset_mesh
def get_speech_model():
from models.speech_model import analyze_audio_bytes, analyze_audio_file
_models_loaded["speech"] = True
return analyze_audio_bytes, analyze_audio_file
def get_text_model():
from models.text_model import analyze_text, batch_analyze
_models_loaded["text"] = True
return analyze_text, batch_analyze
def get_engagement_calc():
from models.engagement import calculate_engagement
return calculate_engagement
@app.on_event("startup")
async def startup_event():
print("=" * 60)
print(" THE SENTINEL INTERFACE β Backend Server")
print(" Multisource Emotion Detection & Engagement Optimization")
print("=" * 60)
print(f" Frontend: {FRONTEND_DIR}")
print(f" Database: {db.DB_PATH}")
print(" API Docs: http://localhost:8000/docs")
print("=" * 60)
print("[System] Firing up core models for instant response...")
# Trigger lazy loaders to preload models into RAM before first API request hits
try:
from models.face_model import get_cnn_model
get_cnn_model()
_models_loaded["face"] = True
except Exception as e:
print(f"[System] Face model warning: {e}")
try: get_text_model()
except Exception as e:
print(f"[System] Text model warning: {e}")
try: get_speech_model()
except Exception as e:
print(f"[System] Speech model warning: {e}")
print("[System] Pre-loading complete. Systems nominal.")
# ββ Pydantic Models ββββββββββββββββββββββββββββββββββββββββ
class TextRequest(BaseModel):
text: str
student_id: Optional[str] = "default"
class MultimodalRequest(BaseModel):
face_data: Optional[dict] = None
speech_data: Optional[dict] = None
text: Optional[str] = None
student_id: Optional[str] = "default"
class SessionSaveRequest(BaseModel):
student_id: str = "default"
engagement_score: float
dominant_emotion: str = "neutral"
face_emotion: Optional[dict] = None
speech_emotion: Optional[dict] = None
text_sentiment: Optional[dict] = None
summary: str = ""
session_start_time: Optional[str] = None # ISO string from frontend
# ββ REST API Endpoints βββββββββββββββββββββββββββββββββββββ
@app.get("/api/health")
async def health_check():
return {
"status": "online",
"service": "The Sentinel Interface",
"version": "1.0.0",
"models_loaded": _models_loaded,
"timestamp": datetime.now().isoformat(),
}
@app.post("/api/analyze/face")
async def analyze_face(file: UploadFile = File(...)):
"""
Analyze uploaded face image using the ML Vision Transformer (ViT) model.
Same capability as the AI used in conversations β pre-trained on facial expression datasets.
Falls back to DeepFace, then pixel heuristic if ViT is unavailable.
"""
try:
contents = await file.read()
nparr = np.frombuffer(contents, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if img is None:
raise HTTPException(status_code=400, detail="Invalid image file")
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
from models.image_emotion_model import predict_from_image
result = predict_from_image(img_rgb)
return result
except HTTPException:
raise
except Exception as e:
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analyze/speech")
async def analyze_speech(file: UploadFile = File(...)):
"""Analyze uploaded audio file for speech emotion."""
try:
contents = await file.read()
# Save to temp file for librosa
import tempfile
suffix = os.path.splitext(file.filename)[1] if file.filename else ".wav"
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
tmp.write(contents)
tmp_path = tmp.name
try:
_, analyze_file = get_speech_model()
result = analyze_file(tmp_path)
return result
finally:
os.unlink(tmp_path)
except Exception as e:
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analyze/text")
async def analyze_text_endpoint(request: TextRequest):
"""Analyze text for sentiment and emotion."""
try:
analyze, _ = get_text_model()
result = analyze(request.text)
return result
except Exception as e:
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analyze/text/batch")
async def analyze_text_batch(texts: List[str]):
"""Batch analyze multiple texts."""
try:
_, batch = get_text_model()
result = batch(texts)
return result
except Exception as e:
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/analyze/multimodal")
async def analyze_multimodal(request: MultimodalRequest):
"""Combined multimodal emotion analysis."""
try:
face_result = None
speech_result = None
text_result = None
if request.text:
analyze, _ = get_text_model()
text_result = analyze(request.text)
calc = get_engagement_calc()
engagement = calc(
face_result=request.face_data,
speech_result=request.speech_data,
text_result=text_result,
)
return {
"face": request.face_data,
"speech": request.speech_data,
"text": text_result,
"engagement": engagement,
}
except Exception as e:
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
# ββ Session & Performance Endpoints βββββββββββββββββββββββ
@app.post("/api/session/start")
async def start_session(student_id: str = "default"):
"""Start a new monitoring session."""
session_id = db.create_session(student_id)
return {"session_id": session_id, "student_id": student_id, "started_at": datetime.now().isoformat()}
@app.post("/api/session/end")
async def end_session(session_id: int, avg_engagement: float = 0, dominant_emotion: str = "neutral"):
"""End a monitoring session."""
db.end_session(session_id, avg_engagement, dominant_emotion)
return {"session_id": session_id, "ended_at": datetime.now().isoformat()}
@app.post("/api/session/save")
async def save_session(request: SessionSaveRequest):
"""Save session performance data."""
session_id = db.create_session(request.student_id, start_time=request.session_start_time)
db.save_performance(
student_id=request.student_id,
session_id=session_id,
engagement_score=request.engagement_score,
face_emotion=request.face_emotion,
speech_emotion=request.speech_emotion,
text_sentiment=request.text_sentiment,
summary=request.summary,
)
db.end_session(session_id, request.engagement_score, request.dominant_emotion)
return {"status": "saved", "session_id": session_id}
@app.get("/api/performance/{student_id}")
async def get_performance(student_id: str):
"""Get student performance history."""
perf = db.get_student_performance(student_id)
stats = db.get_overall_stats(student_id)
sessions = db.get_all_sessions(student_id)
return {
"student_id": student_id,
"performance": perf,
"overall_stats": stats,
"sessions": sessions,
}
@app.get("/api/stats/{session_id}")
async def get_stats(session_id: str):
"""Get the 4 metric stats. If session_id is specific, drill down."""
# Always get global stats to keep Total Sessions
stats = db.get_overall_stats("all")
if session_id.lower() != 'all':
try:
sid = int(session_id)
details = db.get_session_details(sid)
if not details:
raise HTTPException(status_code=404, detail="User Not Found")
# Override metrics with session specific ones
stats['avg_engagement'] = details['avg_engagement']
stats['peak_engagement'] = details['peak_engagement']
stats['min_engagement'] = details['min_engagement']
# Attach session info
stats['session_info'] = {
"id": sid,
"date_time": details['date_time'],
"duration_mins": details['duration_mins']
}
except ValueError:
raise HTTPException(status_code=404, detail="User Not Found")
return stats
@app.get("/api/sessions/latest")
async def get_latest_sessions():
"""Get all global sessions and performance records."""
perf = db.get_student_performance("all")
sessions = db.get_all_sessions("all")
return {
"performance": perf,
"sessions": sessions
}
@app.delete("/api/sessions/{session_id}")
async def delete_session(session_id: int):
"""Delete a session completely and cascade/reindex."""
success = db.delete_session(session_id)
if not success:
raise HTTPException(status_code=500, detail="Failed to delete session")
return {"status": "deleted", "deleted_id": session_id}
@app.get("/api/sessions/export")
async def export_sessions():
"""Export all sessions as a CSV file."""
import re
from datetime import datetime, timedelta
conn = db.get_connection()
# Join with student_performance to get exactly the data needed
rows = conn.execute("""
SELECT s.*, p.overall_summary, p.engagement_score
FROM sessions s
LEFT JOIN student_performance p ON s.id = p.session_id
ORDER BY s.id ASC
""").fetchall()
sessions = [dict(r) for r in rows]
conn.close()
output = io.StringIO()
writer = csv.writer(output)
# Headers exactly as requested by user
writer.writerow([
'session id', 'date', 'start time', 'end time',
'duration', 'engagement', 'average engagement', 'dominant emotion'
])
for s in sessions:
try:
start_str = s.get('start_time', '').replace('Z', '')
start_dt = datetime.fromisoformat(start_str) if start_str else datetime.now()
diff_sec = 0
parsed_from_summary = False
# ALWAYS prioritize parsing the true duration from the summary if available
if s.get('overall_summary'):
match = re.search(r'(?:lasted\s*(\d+)\s*minutes|Session:\s*(\d+)min)', s['overall_summary'])
if match:
val = match.group(1) or match.group(2)
diff_sec = int(val) * 60
parsed_from_summary = True
# Fallback to timestamp delta
if not parsed_from_summary:
end_str = s.get('end_time', '').replace('Z', '')
end_dt = datetime.fromisoformat(end_str) if end_str else start_dt
if end_dt < start_dt: end_dt = start_dt
diff_sec = (end_dt - start_dt).total_seconds()
# Mathematically calculate the end time from the start time
calculated_end_dt = start_dt + timedelta(seconds=diff_sec)
# Format dates using Excel string formula to strictly prevent ######## masking
date_str = f'="{start_dt.strftime("%Y-%m-%d")}"'
start_time_str = f'="{start_dt.strftime("%Y-%m-%d %H:%M")}"'
end_time_str = f'="{calculated_end_dt.strftime("%Y-%m-%d %H:%M")}"'
if diff_sec < 60:
duration_str = "0 minutes"
else:
duration_str = f"{round(diff_sec/60.0, 1)} minutes"
except:
date_str = "Error"
start_time_str = "Error"
end_time_str = "Error"
duration_str = "0 minutes"
writer.writerow([
s.get('id'),
date_str,
start_time_str,
end_time_str,
duration_str,
f"{s.get('engagement_score', 0):.1f}%" if s.get('engagement_score') is not None else "0.0%",
f"{s.get('avg_engagement', 0):.1f}%" if s.get('avg_engagement') is not None else "0.0%",
s.get('dominant_emotion')
])
output.seek(0)
return StreamingResponse(
iter([output.getvalue()]),
media_type="text/csv",
headers={"Content-Disposition": "attachment; filename=sentinel_sessions_export.csv"}
)
# ββ WebSocket for Real-time Face Analysis βββββββββββββββββ
@app.websocket("/ws/face")
async def websocket_face(websocket: WebSocket):
"""
Real-time face analysis via WebSocket.
Client sends base64-encoded video frames.
Server returns face mesh landmarks + emotion data.
"""
await websocket.accept()
print("[WebSocket] Face analysis client connected")
process_frame, reset_mesh = get_face_mesh()
predict_emotion = get_face_model()
calc_engagement = get_engagement_calc()
reset_mesh()
from models.face_model import reset_calibration
reset_calibration()
# Initialize analysis state for current session
motion_score = 0
emotion_result = {"emotion": "Neutral", "confidence": 0, "probabilities": {}, "engagement_score": 50, "provider": "Initializing"}
engagement = {"overall_score": 50, "level": "Neutral", "factors": {}}
frame_count = 0
session_id = db.create_session("default")
state_total_engagement = 0
state_engagement_samples = 0
state_dominant_emotion = "neutral"
try:
while True:
data = await websocket.receive_text()
msg = json.loads(data)
if msg.get("type") == "frame":
frame_count += 1
# Decode base64 image
img_data = base64.b64decode(msg["data"])
nparr = np.frombuffer(img_data, np.uint8)
frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if frame is None:
await websocket.send_json({"type": "error", "message": "Invalid frame"})
continue
# Convert BGR to RGB for MediaPipe
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Process face mesh
mesh_result = process_frame(frame_rgb)
# Emotion analysis (every 3rd frame for performance)
if frame_count % 3 == 0:
# Pass the RGB frame to the PyTorch CNN alongside landmarks for crop guidance
landmarks = mesh_result.get("landmarks", []) if mesh_result.get("detected") else None
emotion_result = predict_emotion(frame_rgb, landmarks)
# Calculate engagement
engagement = calc_engagement(face_result=emotion_result)
state_total_engagement += engagement.get("overall_score", 0)
state_engagement_samples += 1
state_dominant_emotion = emotion_result.get("emotion", "neutral")
# Log every 10th frame
if frame_count % 10 == 0:
db.log_emotion(
session_id, "face",
emotion_result.get("emotion", "neutral"),
emotion_result.get("confidence", 0),
{"engagement": engagement.get("overall_score", 0)}
)
# Send response
response = {
"type": "analysis",
"frame_id": frame_count,
"mesh": {
"detected": mesh_result["detected"],
"landmarks": mesh_result.get("landmarks", []),
"landmark_count": mesh_result.get("landmark_count", 0),
},
"blink": mesh_result.get("blink", {}),
"head_pose": mesh_result.get("head_pose", {}),
"emotion": emotion_result,
"engagement": engagement,
}
await websocket.send_json(response)
elif msg.get("type") == "ping":
await websocket.send_json({"type": "pong"})
elif msg.get("type") == "stop":
break
except WebSocketDisconnect:
print("[WebSocket] Client disconnected")
except Exception as e:
print(f"[WebSocket] Error: {e}")
traceback.print_exc()
finally:
# End session
avg_eng = state_total_engagement / max(state_engagement_samples, 1)
db.end_session(session_id, avg_eng, state_dominant_emotion)
print(f"[WebSocket] Session {session_id} ended. Total frames: {frame_count}")
# ββ WebSocket for Real-time Speech Analysis βββββββββββββββ
@app.websocket("/ws/speech")
async def websocket_speech(websocket: WebSocket):
"""
Real-time speech analysis via WebSocket.
Client sends audio chunks.
Server returns emotion + frequency visualization data.
"""
await websocket.accept()
print("[WebSocket] Speech analysis client connected")
try:
while True:
data = await websocket.receive_bytes()
if len(data) < 1000:
await websocket.send_json({
"type": "waiting",
"message": "Collecting audio data..."
})
continue
analyze_bytes, _ = get_speech_model()
result = analyze_bytes(data)
await websocket.send_json({
"type": "analysis",
**result,
})
except WebSocketDisconnect:
print("[WebSocket] Speech client disconnected")
except Exception as e:
print(f"[WebSocket] Speech error: {e}")
traceback.print_exc()
# ββ Serve Frontend Static Files βββββββββββββββββββββββββββ
FRONTEND_DIR = os.path.join(os.path.dirname(__file__), "..", "frontend")
@app.get("/")
async def serve_index():
return FileResponse(os.path.join(FRONTEND_DIR, "index.html"))
@app.get("/live")
@app.get("/live.html")
async def serve_live():
return FileResponse(os.path.join(FRONTEND_DIR, "live.html"))
@app.get("/scan")
@app.get("/scan.html")
async def serve_scan():
return FileResponse(os.path.join(FRONTEND_DIR, "scan.html"))
@app.get("/stats")
@app.get("/stats.html")
async def serve_stats():
return FileResponse(os.path.join(FRONTEND_DIR, "stats.html"))
# Mount static files (CSS, JS, images)
if os.path.exists(os.path.join(FRONTEND_DIR, "css")):
app.mount("/css", StaticFiles(directory=os.path.join(FRONTEND_DIR, "css")), name="css")
if os.path.exists(os.path.join(FRONTEND_DIR, "js")):
app.mount("/js", StaticFiles(directory=os.path.join(FRONTEND_DIR, "js")), name="js")
if os.path.exists(os.path.join(FRONTEND_DIR, "assets")):
app.mount("/assets", StaticFiles(directory=os.path.join(FRONTEND_DIR, "assets")), name="assets")
if __name__ == "__main__":
import uvicorn
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)
|