face_recognition_logic.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import os
  2. import tempfile
  3. from deepface import DeepFace
  4. EMPLOYEE_DB_PATH = "data/employees"
  5. DEFAULT_MODEL = "VGG-Face"
  6. DETECTOR_BACKEND = "opencv"
  7. def recognize_face(image_bytes, model_name=None):
  8. model = model_name if model_name else DEFAULT_MODEL
  9. temp_file = None
  10. print("request image" + model_name)
  11. try:
  12. # Save incoming image to a temporary file
  13. with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
  14. temp_file = tmp.name
  15. tmp.write(image_bytes)
  16. # Run DeepFace search
  17. result = DeepFace.find(
  18. img_path=temp_file,
  19. db_path=EMPLOYEE_DB_PATH,
  20. detector_backend=DETECTOR_BACKEND,
  21. model_name=model,
  22. enforce_detection=False
  23. )
  24. if isinstance(result, list):
  25. result = result[0]
  26. if result is None or len(result) == 0:
  27. return {"name": "Unknown", "confidence": 0.0, "image": b""}
  28. # Best match
  29. best_row = result.iloc[0]
  30. matched_image_path = best_row["identity"]
  31. name = os.path.splitext(os.path.basename(matched_image_path))[0]
  32. # Distance metric key depends on model
  33. key = f"{model}_cosine"
  34. distance = best_row.get(key, 0.3)
  35. confidence = float(max(0.0, 1.0 - distance))
  36. # Read matched image bytes
  37. with open(matched_image_path, "rb") as f:
  38. matched_image_bytes = f.read()
  39. return {"name": name, "confidence": confidence, "image": matched_image_bytes}
  40. finally:
  41. if temp_file and os.path.exists(temp_file):
  42. os.remove(temp_file)