Spaces:
Configuration error
Configuration error
| import datetime | |
| 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 Attendance | |
| from app.services.face_detector import detect_faces | |
| from app.services.embedding import get_embedding | |
| from app.services.recognition import load_all_persons, identify_person | |
| router = APIRouter(prefix="/attendance", tags=["Attendance"]) | |
| async def take_attendance( | |
| file: UploadFile = File(...), | |
| db: Session = Depends(get_db), | |
| ): | |
| """ | |
| Register attendance from an uploaded image. | |
| """ | |
| known_persons = load_all_persons(db) | |
| if not known_persons: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="لا يوجد أشخاص مسجلين" | |
| ) | |
| # قراءة الصورة | |
| 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="لم يتم العثور على أي وجه" | |
| ) | |
| present = [] | |
| today = datetime.date.today() | |
| for box in boxes: | |
| x1, y1, x2, y2 = box | |
| face_crop = image[y1:y2, x1:x2] | |
| if face_crop.size == 0: | |
| continue | |
| embedding = get_embedding(face_crop) | |
| person_id, name, score = identify_person( | |
| embedding, | |
| known_persons | |
| ) | |
| if person_id is None: | |
| present.append({ | |
| "name": "Unknown", | |
| "score": round(float(score), 4) | |
| }) | |
| continue | |
| already_exists = ( | |
| db.query(Attendance) | |
| .filter( | |
| Attendance.person_id == person_id, | |
| Attendance.date == today, | |
| ) | |
| .first() | |
| ) | |
| if not already_exists: | |
| attendance = Attendance( | |
| person_id=person_id, | |
| date=today, | |
| time=datetime.datetime.now().time(), | |
| status="Present", | |
| ) | |
| db.add(attendance) | |
| db.commit() | |
| present.append({ | |
| "id": person_id, | |
| "name": name, | |
| "score": round(float(score), 4), | |
| "status": "Present", | |
| }) | |
| return { | |
| "count": len(present), | |
| "results": present, | |
| } |