Spaces:
Runtime error
Runtime error
File size: 8,152 Bytes
67ac4d2 0f7caca 67ac4d2 0f7caca 67ac4d2 0f7caca 67ac4d2 0f7caca 67ac4d2 0f7caca 67ac4d2 bb13d79 | 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 | import cv2
import numpy as np
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, status
from sqlalchemy.orm import Session
from app.database.session import get_db
from app.models.models import Student, FaceEmbedding, AttendanceRecord, AttendanceSession
from app.schemas.schemas import StudentCreate, StudentOut, FaceRegistrationResult
from app.core.security import get_current_user_token
from app.core.storage import storage_service
from app.cv.detector import face_detector
from app.cv.embedder import face_embedder
router = APIRouter(prefix="/students", tags=["Students"])
def normalize_image_url(path_str: Optional[str]) -> Optional[str]:
if not path_str:
return None
p = path_str.replace("\\", "/")
if p.startswith("http://") or p.startswith("https://"):
return p
if p.startswith("storage/"):
return "/" + p
if p.startswith("/storage/"):
return p
return "/storage/" + p.lstrip("/")
@router.get("", response_model=List[StudentOut])
def list_students(class_id: Optional[int] = None, db: Session = Depends(get_db), token: dict = Depends(get_current_user_token)):
query = db.query(Student).filter(Student.active == True)
if class_id:
query = query.filter(Student.class_id == class_id)
students = query.order_by(Student.roll_number).all()
results = []
for s in students:
s_out = StudentOut.model_validate(s)
s_out.face_count = len(s.embeddings)
imgs = [normalize_image_url(emb.source_image) for emb in s.embeddings if emb.source_image]
s_out.face_images = [img for img in imgs if img]
s_out.avatar_url = s_out.face_images[0] if len(s_out.face_images) > 0 else None
# Calculate overall attendance %
total = db.query(AttendanceRecord).filter(AttendanceRecord.student_id == s.id).count()
if total > 0:
present = db.query(AttendanceRecord).filter(AttendanceRecord.student_id == s.id, AttendanceRecord.status == "PRESENT").count()
s_out.attendance_percentage = round((present / total) * 100.0, 1)
else:
s_out.attendance_percentage = 100.0
results.append(s_out)
return results
@router.post("", response_model=StudentOut)
def create_student(req: StudentCreate, db: Session = Depends(get_db), token: dict = Depends(get_current_user_token)):
existing = db.query(Student).filter(Student.student_id == req.student_id).first()
if existing:
raise HTTPException(status_code=400, detail=f"Student ID {req.student_id} already exists")
from app.core.security import get_password_hash
student = Student(
student_id=req.student_id,
name=req.name,
roll_number=req.roll_number,
class_id=req.class_id,
email=req.email,
password_hash=get_password_hash(req.student_id)
)
db.add(student)
db.commit()
db.refresh(student)
s_out = StudentOut.model_validate(student)
s_out.face_count = 0
s_out.attendance_percentage = 100.0
s_out.avatar_url = None
s_out.face_images = []
return s_out
@router.get("/{student_id}", response_model=StudentOut)
def get_student_detail(student_id: int, db: Session = Depends(get_db), token: dict = Depends(get_current_user_token)):
student = db.query(Student).filter(Student.id == student_id).first()
if not student:
raise HTTPException(status_code=404, detail="Student not found")
s_out = StudentOut.model_validate(student)
s_out.face_count = len(student.embeddings)
imgs = [normalize_image_url(emb.source_image) for emb in student.embeddings if emb.source_image]
s_out.face_images = [img for img in imgs if img]
s_out.avatar_url = s_out.face_images[0] if len(s_out.face_images) > 0 else None
total = db.query(AttendanceRecord).filter(AttendanceRecord.student_id == student.id).count()
if total > 0:
present = db.query(AttendanceRecord).filter(AttendanceRecord.student_id == student.id, AttendanceRecord.status == "PRESENT").count()
s_out.attendance_percentage = round((present / total) * 100.0, 1)
else:
s_out.attendance_percentage = 100.0
return s_out
@router.post("/{student_id}/face-images", response_model=FaceRegistrationResult)
def upload_student_face_images(
student_id: int,
files: List[UploadFile] = File(...),
db: Session = Depends(get_db),
token: dict = Depends(get_current_user_token)
):
student = db.query(Student).filter(Student.id == student_id).first()
if not student:
raise HTTPException(status_code=404, detail="Student not found")
registered_count = 0
warnings = []
for idx, file in enumerate(files):
if file.content_type not in ["image/jpeg", "image/png", "image/jpg", "image/webp"]:
warnings.append(f"File '{file.filename}': Unsupported image format. Must be JPEG or PNG.")
continue
contents = file.file.read()
nparr = np.frombuffer(contents, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if img is None:
warnings.append(f"File '{file.filename}': Could not decode image.")
continue
detected = face_detector.detect_faces(img)
if len(detected) == 0:
warnings.append(f"File '{file.filename}': No face detected. Please use a clear front-facing photograph.")
continue
elif len(detected) > 1:
warnings.append(f"File '{file.filename}': Multiple faces ({len(detected)}) detected. Reference photos must contain exactly one face.")
continue
# Extract face embedding from the detected face
cropped = detected[0]["cropped_face"]
raw_face = detected[0].get("raw_face")
embedding = face_embedder.compute_embedding(
face_image_bgr=cropped,
full_image_bgr=img,
raw_face=raw_face
)
# Reset file seek for saving
file.file.seek(0)
saved_rel_path = storage_service.save_file(file, subfolder=f"students/{student.id}")
face_emb_record = FaceEmbedding(
student_id=student.id,
embedding=embedding,
source_image=saved_rel_path
)
db.add(face_emb_record)
registered_count += 1
db.commit()
db.refresh(student)
total_faces = len(student.embeddings)
return FaceRegistrationResult(
student_id=student.id,
registered_images=registered_count,
message=f"Successfully registered {registered_count} face embedding(s). Total embeddings stored: {total_faces}.",
warnings=warnings
)
@router.delete("/{student_id}/face-data")
def delete_student_face_data(student_id: int, db: Session = Depends(get_db), token: dict = Depends(get_current_user_token)):
"""
Privacy compliance endpoint: delete all biometric face embeddings and source images for a student.
"""
student = db.query(Student).filter(Student.id == student_id).first()
if not student:
raise HTTPException(status_code=404, detail="Student not found")
embeddings = db.query(FaceEmbedding).filter(FaceEmbedding.student_id == student_id).all()
count = len(embeddings)
for emb in embeddings:
if emb.source_image:
storage_service.delete_file(emb.source_image)
db.delete(emb)
db.commit()
return {"message": f"Successfully deleted all {count} face biometric records for student {student.name}."}
@router.delete("/{student_id}")
def delete_student(student_id: int, db: Session = Depends(get_db), token: dict = Depends(get_current_user_token)):
student = db.query(Student).filter(Student.id == student_id).first()
if not student:
raise HTTPException(status_code=404, detail="Student not found")
# Delete embeddings and records
for emb in student.embeddings:
if emb.source_image:
storage_service.delete_file(emb.source_image)
db.delete(emb)
db.delete(student)
db.commit()
return {"message": f"Student '{student.name}' successfully deleted."}
|