File size: 2,758 Bytes
52cae38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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)}")