fr_flask.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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_folder = "application_data/verification_images"
  50. face_encodings = []
  51. total_threshold = 0.2
  52. def scan_known_people(known_people_folder):
  53. known_names = []
  54. known_face_encodings = []
  55. for file in image_files_in_folder(known_people_folder):
  56. img = face_recognition.load_image_file(file)
  57. encodings = face_recognition.face_encodings(img)
  58. if len(encodings) > 1:
  59. print("WARNING: More than one face found in {}. Only considering the first face.".format(file))
  60. if len(encodings) == 0:
  61. print("WARNING: No faces found in {}. Ignoring file.".format(file))
  62. else:
  63. known_face_encodings.append(encodings[0])
  64. return known_face_encodings
  65. def image_files_in_folder(folder):
  66. img_list = [os.path.join(folder, f) for f in os.listdir(folder) if
  67. re.match(r'.*\.(jpg|jpeg|png|webp)', f, flags=re.I)]
  68. img_list.sort()
  69. return img_list
  70. @app.route('/predict', methods=['POST'])
  71. def predict():
  72. result = []
  73. if "image" in request.json:
  74. im_b64 = request.json["image"]
  75. elif "image" in request.files:
  76. im_b64 = request.files["image"]
  77. elif "image" in request.form:
  78. im_b64 = request.form["image"]
  79. else:
  80. return {"error": "Error reading image"}
  81. im_bytes = base64.b64decode(im_b64)
  82. im_file = BytesIO(im_bytes)
  83. test_image = face_recognition.load_image_file(im_file)
  84. face_locations = face_recognition.face_locations(test_image)
  85. no = len(face_locations)
  86. if no > 0:
  87. for i in range(no):
  88. start_time = time.perf_counter()
  89. test_image_enc = face_recognition.face_encodings(test_image)[i]
  90. proba_list = clf.predict_proba([test_image_enc])
  91. dist = face_recognition.face_distance(face_encodings, test_image_enc)
  92. total = np.subtract(proba_list, dist)
  93. i = np.argmax(total)
  94. proba = list(*proba_list)[i]
  95. name = dummy_data[i]["name"]
  96. address = dummy_data[i]["address"]
  97. nik = dummy_data[i]["nik"]
  98. js = {
  99. "id": str(i),
  100. "name": name,
  101. "address": address,
  102. "nik": nik,
  103. "proba": proba
  104. }
  105. if total[0][i] > total_threshold:
  106. result.append(js)
  107. end_time = time.perf_counter()
  108. process_time = end_time - start_time
  109. print(total[0])
  110. print("Process time:", process_time, "s")
  111. print(result)
  112. return jsonify(result)
  113. if __name__ == '__main__':
  114. try:
  115. clf = joblib.load(model_file_name)
  116. classes = clf.classes_
  117. print('model loaded')
  118. face_encodings = scan_known_people(known_people_folder)
  119. print('known faces scanned')
  120. except FileNotFoundError as e:
  121. print('No model here')
  122. exit(1)
  123. app.run(host='0.0.0.0', port=8349, debug=True, ssl_context=ssl)