fr_flask.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. from PIL import ImageFile
  2. from flask import Flask, request, jsonify
  3. import face_recognition
  4. import base64
  5. from io import BytesIO
  6. import joblib
  7. import numpy as np
  8. import re
  9. import os
  10. import time
  11. ImageFile.SAFEBLOCK = 2048 * 2048
  12. app = Flask(__name__)
  13. model_file_name = "saved_model_2.pkl"
  14. clf = None
  15. classes = None
  16. dummy_data = [
  17. {
  18. "name": "Bayu",
  19. "address": "299 St Louis Road Oak Forest, IL 60452",
  20. "nik": "1000076456784631"
  21. },
  22. {
  23. "name": "Dio",
  24. "address": "22 Whitemarsh St. Mansfield, MA 02048",
  25. "nik": "1000024792887549"
  26. },
  27. {
  28. "name": "Hadi",
  29. "address": "643 Honey Creek Dr. Milledgeville, GA 31061",
  30. "nik": "1000038502830420"
  31. },
  32. {
  33. "name": "Kevin",
  34. "address": "881 Cooper Ave. Hummelstown, PA 17036",
  35. "nik": "1000045356476664"
  36. },
  37. {
  38. "name": "Matrix",
  39. "address": "580 Glenwood Dr. Garner, NC 27529",
  40. "nik": "1000023452134598"
  41. },
  42. {
  43. "name": "Surya",
  44. "address": "909 South St Paul Street Hopewell, VA 23860",
  45. "nik": "1000075656784734"
  46. },
  47. ]
  48. ssl = None
  49. known_people = "application_data/verification_images"
  50. known_faces = []
  51. total_threshold = 0.3
  52. face_model = "large"
  53. if face_model == "large":
  54. model_file_name = "saved_model_2_large.pkl"
  55. def scan_known_people(known_people_folder):
  56. known_face_encodings = []
  57. for file in image_files_in_folder(known_people_folder):
  58. img = face_recognition.load_image_file(file)
  59. encodings = face_recognition.face_encodings(img, model=face_model)
  60. if len(encodings) > 1:
  61. print("WARNING: More than one face found in {}. Only considering the first face.".format(file))
  62. if len(encodings) == 0:
  63. print("WARNING: No faces found in {}. Ignoring file.".format(file))
  64. else:
  65. known_face_encodings.append(encodings[0])
  66. return known_face_encodings
  67. def image_files_in_folder(folder):
  68. img_list = [os.path.join(folder, f) for f in os.listdir(folder) if
  69. re.match(r'.*\.(jpg|jpeg|png|webp)', f, flags=re.I)]
  70. img_list.sort()
  71. return img_list
  72. @app.route('/predict', methods=['POST'])
  73. def predict():
  74. result = []
  75. if "image" in request.json:
  76. im_b64 = request.json["image"]
  77. elif "image" in request.files:
  78. im_b64 = request.files["image"]
  79. elif "image" in request.form:
  80. im_b64 = request.form["image"]
  81. else:
  82. return {"error": "Error reading image"}
  83. im_bytes = base64.b64decode(im_b64)
  84. im_file = BytesIO(im_bytes)
  85. test_image = face_recognition.load_image_file(im_file)
  86. face_locations = face_recognition.face_locations(test_image)
  87. no = len(face_locations)
  88. if no > 0:
  89. for i in range(no):
  90. start_time = time.perf_counter()
  91. test_image_enc = face_recognition.face_encodings(test_image, model=face_model)[i]
  92. proba_list = clf.predict_proba([test_image_enc])
  93. dist = face_recognition.face_distance(known_faces, test_image_enc)
  94. total = np.subtract(proba_list, dist)
  95. i = np.argmax(total)
  96. proba = list(*proba_list)[i]
  97. name = dummy_data[i]["name"]
  98. address = dummy_data[i]["address"]
  99. nik = dummy_data[i]["nik"]
  100. js = {
  101. "id": str(i),
  102. "name": name,
  103. "address": address,
  104. "nik": nik,
  105. "proba": proba,
  106. "delta": total[0][i]
  107. }
  108. if total[0][i] > total_threshold:
  109. result.append(js)
  110. end_time = time.perf_counter()
  111. process_time = end_time - start_time
  112. print(total[0])
  113. print("Process time:", process_time, "s")
  114. print(result)
  115. return jsonify(result)
  116. if __name__ == '__main__':
  117. try:
  118. clf = joblib.load(model_file_name)
  119. classes = clf.classes_
  120. print('model loaded')
  121. known_faces = scan_known_people(known_people)
  122. print('known faces scanned')
  123. except FileNotFoundError as e:
  124. print('No model here')
  125. exit(1)
  126. app.run(host='0.0.0.0', port=8349, debug=True, ssl_context=ssl)