grpc_server.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import grpc
  2. from concurrent import futures
  3. import time
  4. import os
  5. from deepface import DeepFace
  6. import pandas as pd
  7. import face_recognition_pb2
  8. import face_recognition_pb2_grpc
  9. EMPLOYEE_DB_PATH = "data/employees"
  10. class FaceRecognitionServicer(face_recognition_pb2_grpc.FaceRecognitionServiceServicer):
  11. def Recognize(self, request, context):
  12. print("[INFO] Received request...")
  13. # Save temp image
  14. temp_path = "temp_upload.jpg"
  15. with open(temp_path, "wb") as f:
  16. f.write(request.image)
  17. try:
  18. print("[INFO] Running DeepFace search...")
  19. result = DeepFace.find(
  20. img_path=temp_path,
  21. db_path=EMPLOYEE_DB_PATH,
  22. enforce_detection=False
  23. )
  24. # result is a list of pandas DataFrames for each model;
  25. # we only use first result
  26. if isinstance(result, list):
  27. result = result[0]
  28. if result is None or len(result) == 0:
  29. print("[INFO] No match found.")
  30. return face_recognition_pb2.FaceResponse(
  31. name="Unknown",
  32. confidence=0.0
  33. )
  34. # Pick best match
  35. best_row = result.iloc[0]
  36. matched_image_path = best_row["identity"]
  37. name = os.path.splitext(os.path.basename(matched_image_path))[0]
  38. # DeepFace gives "distance" values, convert roughly to confidence
  39. distance = best_row.get("VGG-Face_cosine", 0.3)
  40. confidence = float(max(0.0, 1.0 - distance))
  41. print(f"[INFO] Match: {name}, confidence: {confidence:.2f}")
  42. return face_recognition_pb2.FaceResponse(
  43. name=name,
  44. confidence=confidence
  45. )
  46. except Exception as e:
  47. print("[ERROR] DeepFace failed:", e)
  48. return face_recognition_pb2.FaceResponse(
  49. name="Error",
  50. confidence=0.0
  51. )
  52. finally:
  53. if os.path.exists(temp_path):
  54. os.remove(temp_path)
  55. def serve():
  56. server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  57. face_recognition_pb2_grpc.add_FaceRecognitionServiceServicer_to_server(
  58. FaceRecognitionServicer(), server
  59. )
  60. server.add_insecure_port("[::]:50051")
  61. server.start()
  62. print("[INFO] gRPC Face Recognition server running on port 50051")
  63. server.wait_for_termination()
  64. if __name__ == "__main__":
  65. serve()