| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- import os
- import tempfile
- from deepface import DeepFace
- EMPLOYEE_DB_PATH = "data/employees"
- DEFAULT_MODEL = "VGG-Face"
- DETECTOR_BACKEND = "opencv"
- def recognize_face(image_bytes, model_name=None):
- model = model_name if model_name else DEFAULT_MODEL
- temp_file = None
- print("request image" + model_name)
- try:
- # Save incoming image to a temporary file
- with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
- temp_file = tmp.name
- tmp.write(image_bytes)
- # Run DeepFace search
- result = DeepFace.find(
- img_path=temp_file,
- db_path=EMPLOYEE_DB_PATH,
- detector_backend=DETECTOR_BACKEND,
- model_name=model,
- enforce_detection=False
- )
- if isinstance(result, list):
- result = result[0]
- if result is None or len(result) == 0:
- return {"name": "Unknown", "confidence": 0.0, "image": b""}
- # Best match
- best_row = result.iloc[0]
- matched_image_path = best_row["identity"]
- name = os.path.splitext(os.path.basename(matched_image_path))[0]
- # Distance metric key depends on model
- key = f"{model}_cosine"
- distance = best_row.get(key, 0.3)
- confidence = float(max(0.0, 1.0 - distance))
- # Read matched image bytes
- with open(matched_image_path, "rb") as f:
- matched_image_bytes = f.read()
- return {"name": name, "confidence": confidence, "image": matched_image_bytes}
- finally:
- if temp_file and os.path.exists(temp_file):
- os.remove(temp_file)
|