File size: 2,035 Bytes
c1ff2a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cv2
import numpy as np

from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from sqlalchemy.orm import Session

from app.database.database import get_db
from app.database.models import Person
from app.services.face_detector import detect_faces
from app.services.embedding import get_embedding
from app.services.face_quality import check_face_quality

router = APIRouter(prefix="/register", tags=["Register"])


@router.post("/")
async def register_person(
    name: str,
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
):
    """
    Register a new person from an uploaded image.
    """

    # قراءة الصورة
    contents = await file.read()

    image = cv2.imdecode(
        np.frombuffer(contents, np.uint8),
        cv2.IMREAD_COLOR,
    )

    if image is None:
        raise HTTPException(
            status_code=400,
            detail="الصورة غير صالحة"
        )

    # كشف الوجه
    boxes = detect_faces(image)

    if len(boxes) == 0:
        raise HTTPException(
            status_code=400,
            detail="لم يتم العثور على أي وجه"
        )

    # أول وجه فقط
    x1, y1, x2, y2 = boxes[0]

    face_crop = image[y1:y2, x1:x2]

    if face_crop.size == 0:
        raise HTTPException(
            status_code=400,
            detail="فشل استخراج الوجه"
        )

    # فحص الجودة
    quality = check_face_quality(face_crop)

    if not quality["ok"]:
        raise HTTPException(
            status_code=400,
            detail=quality["message"]
        )

    # استخراج الـ Embedding
    embedding = get_embedding(face_crop)

    # حفظه في قاعدة البيانات
    person = Person(
        name=name,
        embedding=embedding.tolist(),
    )

    db.add(person)
    db.commit()
    db.refresh(person)

    return {
        "id": person.id,
        "name": person.name,
        "quality": quality,
        "message": "تم التسجيل بنجاح"
    }