face / app.py
NarzullayevMe's picture
Create app.py
9659e2e verified
raw
history blame
1.97 kB
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from deepface import DeepFace
import os
import uuid
# FastAPI ilovasini yaratamiz
app = FastAPI(title="Face Verification API")
# Talabalarning asl rasmlari saqlanadigan papka
STUDENT_IMAGE_DIR = "student_images"
os.makedirs(STUDENT_IMAGE_DIR, exist_ok=True)
@app.get("/")
def read_root():
return {"message": "Face Verification API ishga tushdi. /verify/ manziliga POST so'rov yuborishingiz mumkin."}
@app.post("/verify/")
async def verify_face(
image: UploadFile = File(..., description="Kameradan olingan talaba rasmi"),
pinfl: str = Form(..., description="Talabaning PINFL raqami")
):
live_image_path = f"{str(uuid.uuid4())}.jpg"
try:
# 1. Talabaning tizimdagi asl rasmini topish
student_image_path = os.path.join(STUDENT_IMAGE_DIR, f"{pinfl}.jpg")
if not os.path.exists(student_image_path):
raise HTTPException(status_code=404, detail=f"{pinfl} raqamli talaba uchun tizimda rasm topilmadi.")
# 2. Kelgan rasmni vaqtinchalik saqlash
with open(live_image_path, "wb") as buffer:
buffer.write(await image.read())
# 3. DeepFace orqali solishtirish
result = DeepFace.verify(
img1_path=student_image_path,
img2_path=live_image_path,
model_name="VGG-Face",
detector_backend="mtcnn"
)
# 4. Natijani JSON formatida qaytarish
similarity = (1 - result['distance']) * 100
return {
"is_match": bool(result["verified"]),
"similarity_percentage": round(similarity, 2),
"pinfl": pinfl
}
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=f"Ichki xatolik yuz berdi: {str(e)}")
finally:
# Vaqtinchalik faylni o'chirish
if os.path.exists(live_image_path):
os.remove(live_image_path)