grpc_server.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import tempfile
  2. import grpc
  3. import sys
  4. from concurrent import futures
  5. import os
  6. from deepface import DeepFace
  7. sys.path.insert(0, os.path.join(os.path.dirname(__file__), "proto"))
  8. from proto import face_recognition_pb2
  9. from proto import face_recognition_pb2_grpc
  10. EMPLOYEE_DB_PATH = "data/employees"
  11. class FaceRecognitionServicer(face_recognition_pb2_grpc.FaceRecognitionServiceServicer):
  12. def Recognize(self, request, context):
  13. print("[INFO] Received recognition request...")
  14. temp_file = None
  15. try:
  16. # Save incoming image to a temporary file
  17. with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
  18. temp_file = tmp.name
  19. tmp.write(request.image)
  20. print("[INFO] Running DeepFace search...")
  21. result = DeepFace.find(
  22. img_path=temp_file,
  23. db_path=EMPLOYEE_DB_PATH,
  24. detector_backend="opencv",
  25. enforce_detection=False
  26. )
  27. if isinstance(result, list):
  28. result = result[0]
  29. if result is None or len(result) == 0:
  30. print("[INFO] No match found.")
  31. return face_recognition_pb2.FaceResponse(
  32. name="Unknown",
  33. confidence=0.0,
  34. image=b""
  35. )
  36. best_row = result.iloc[0]
  37. matched_image_path = best_row["identity"]
  38. name = os.path.splitext(os.path.basename(matched_image_path))[0]
  39. # Convert distance to rough confidence
  40. distance = best_row.get("VGG-Face_cosine", 0.3)
  41. confidence = float(max(0.0, 1.0 - distance))
  42. # Read matched image bytes
  43. with open(matched_image_path, "rb") as f:
  44. matched_image_bytes = f.read()
  45. print(f"[INFO] Match: {name}, confidence: {confidence:.2f}")
  46. return face_recognition_pb2.FaceResponse(
  47. name=name,
  48. confidence=confidence,
  49. image=matched_image_bytes
  50. )
  51. except Exception as e:
  52. print("[ERROR] DeepFace failed:", e)
  53. return face_recognition_pb2.FaceResponse(
  54. name="Error",
  55. confidence=0.0,
  56. image=b""
  57. )
  58. finally:
  59. if temp_file and os.path.exists(temp_file):
  60. try:
  61. os.remove(temp_file)
  62. except Exception as cleanup_error:
  63. print(f"[WARN] Could not delete temp file {temp_file}: {cleanup_error}")
  64. def GetAllEmployees(self, request, context):
  65. try:
  66. employee_files = [
  67. f for f in os.listdir(EMPLOYEE_DB_PATH)
  68. if f.lower().endswith((".jpg", ".png", ".jpeg"))
  69. ]
  70. employees = []
  71. for file in employee_files:
  72. path = os.path.join(EMPLOYEE_DB_PATH, file)
  73. name = os.path.splitext(file)[0]
  74. with open(path, "rb") as f:
  75. image_bytes = f.read()
  76. employees.append(face_recognition_pb2.Employee(
  77. name=name,
  78. image=image_bytes
  79. ))
  80. return face_recognition_pb2.EmployeeListResponse(
  81. employees=employees
  82. )
  83. except Exception as e:
  84. print("[ERROR] Failed to list employees:", e)
  85. return face_recognition_pb2.EmployeeListResponse(employees=[])
  86. def DeleteEmployee(self, request, context):
  87. try:
  88. found = False
  89. for file in os.listdir(EMPLOYEE_DB_PATH):
  90. if os.path.splitext(file)[0] == request.name:
  91. os.remove(os.path.join(EMPLOYEE_DB_PATH, file))
  92. found = True
  93. break
  94. message = "Deleted successfully" if found else "Employee not found"
  95. return face_recognition_pb2.DeleteEmployeeResponse(
  96. success=found,
  97. message=message
  98. )
  99. except Exception as e:
  100. print("[ERROR] Failed to delete employee:", e)
  101. return face_recognition_pb2.DeleteEmployeeResponse(
  102. success=False,
  103. message=str(e)
  104. )
  105. def serve():
  106. server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  107. face_recognition_pb2_grpc.add_FaceRecognitionServiceServicer_to_server(
  108. FaceRecognitionServicer(), server
  109. )
  110. server.add_insecure_port("[::]:50051")
  111. server.start()
  112. print("[INFO] gRPC Face Recognition server running on port 50051")
  113. server.wait_for_termination()
  114. if __name__ == "__main__":
  115. os.makedirs(EMPLOYEE_DB_PATH, exist_ok=True)
  116. serve()