face-recognition-api / api /recognize.py
MusinguziBenard's picture
Upload 4 files
52cae38 verified
Raw
History Blame Contribute Delete
2.76 kB
# api/recognize.py
from fastapi import APIRouter, File, UploadFile, Form, HTTPException, Header
from services.face_service import get_face_service
import config
import json
import logging
router = APIRouter()
face_service = get_face_service()
logger = logging.getLogger(__name__)
@router.post("/recognize")
async def recognize_face(
x_api_key: str = Header(...),
embeddings: str = Form(...),
image: UploadFile = File(...)
):
if x_api_key != config.Config.API_KEY:
raise HTTPException(status_code=401, detail="Invalid API key")
try:
contents = await image.read()
if len(contents) == 0:
raise HTTPException(status_code=400, detail="Empty image file")
face_data, error = face_service.extract_face(contents)
if not face_data:
return {
"success": False,
"message": error or "No face detected",
"face_detected": False,
"student_id": None,
"confidence": 0
}
try:
stored_embeddings = json.loads(embeddings)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid embeddings format")
if len(stored_embeddings) == 0:
return {
"success": False,
"message": "No embeddings provided",
"face_detected": True,
"student_id": None,
"confidence": 0
}
best_match, confidence = face_service.compare_faces(
face_data['embedding'],
stored_embeddings
)
if best_match and confidence >= config.Config.CONFIDENCE_THRESHOLD:
return {
"success": True,
"message": "Face recognized successfully",
"student_id": best_match['student_id'],
"student_name": best_match.get('student_name', 'Unknown'),
"admission_no": best_match.get('admission_no', ''),
"confidence": float(confidence),
"face_detected": True
}
else:
return {
"success": False,
"message": f"Face not recognized (confidence: {confidence:.2f})",
"student_id": None,
"confidence": float(confidence),
"face_detected": True
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Recognition error: {e}")
raise HTTPException(status_code=500, detail=f"Recognition failed: {str(e)}")