fr_flask_0.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. import shlex
  12. import subprocess
  13. from face_recognition_svm import train_svm
  14. ImageFile.SAFEBLOCK = 2048 * 2048
  15. app = Flask(__name__)
  16. model_file_name = "saved_model_2.pkl"
  17. clf = None
  18. classes = None
  19. dummy_data = [
  20. {
  21. "name": "Bayu",
  22. "address": "299 St Louis Road Oak Forest, IL 60452",
  23. "nik": "1000076456784631"
  24. },
  25. {
  26. "name": "Dio",
  27. "address": "22 Whitemarsh St. Mansfield, MA 02048",
  28. "nik": "1000024792887549"
  29. },
  30. {
  31. "name": "Hadi",
  32. "address": "643 Honey Creek Dr. Milledgeville, GA 31061",
  33. "nik": "1000038502830420"
  34. },
  35. {
  36. "name": "Kevin",
  37. "address": "881 Cooper Ave. Hummelstown, PA 17036",
  38. "nik": "1000045356476664"
  39. },
  40. {
  41. "name": "Matrix",
  42. "address": "580 Glenwood Dr. Garner, NC 27529",
  43. "nik": "1000023452134598"
  44. },
  45. {
  46. "name": "Surya",
  47. "address": "909 South St Paul Street Hopewell, VA 23860",
  48. "nik": "1000075656784734"
  49. },
  50. {
  51. "name": "Abi",
  52. "address": "47 Rockville Road Leland, NC 28451",
  53. "nik": "1000084937284959"
  54. },
  55. ]
  56. ssl = None
  57. known_people = "application_data/verification_images"
  58. known_faces = []
  59. total_threshold = 0.1
  60. face_model = "large"
  61. if face_model == "large":
  62. model_file_name = "saved_model_2_large.pkl"
  63. UPLOAD_FOLDER = ""
  64. def scan_known_people(known_people_folder):
  65. known_face_encodings = []
  66. for file in image_files_in_folder(known_people_folder):
  67. img = face_recognition.load_image_file(file)
  68. encodings = face_recognition.face_encodings(img, model=face_model)
  69. if len(encodings) > 1:
  70. print("WARNING: More than one face found in {}. Only considering the first face.".format(file))
  71. if len(encodings) == 0:
  72. print("WARNING: No faces found in {}. Ignoring file.".format(file))
  73. else:
  74. known_face_encodings.append(encodings[0])
  75. return known_face_encodings
  76. def image_files_in_folder(folder):
  77. img_list = [os.path.join(folder, f) for f in os.listdir(folder) if
  78. re.match(r'.*\.(jpg|jpeg|png|webp)', f, flags=re.I)]
  79. img_list.sort()
  80. return img_list
  81. def load_db():
  82. pass
  83. def save_db(nik, name, address):
  84. pass
  85. @app.route('/upload', methods=['POST'])
  86. def upload():
  87. profile = request.files["profile"]
  88. nik = request.form["nik"]
  89. name = request.form["name"]
  90. address = request.form["address"]
  91. @app.route('/train', methods=['GET', 'POST'])
  92. def train():
  93. try:
  94. train_svm(model_file_name)
  95. return jsonify({"status": "0", "message": "Train successful"})
  96. except Exception as exc:
  97. return jsonify({"status": "1", "message": f"Error training model: {exc}"})
  98. @app.route('/reload', methods=['GET', 'POST'])
  99. def face_reload():
  100. pid = None
  101. try:
  102. with open("app.pid", "r") as f:
  103. pid = f.readline()
  104. if pid:
  105. cmd = f"kill -s HUP {pid}"
  106. cmd_array = shlex.split(cmd)
  107. print(cmd_array)
  108. subprocess.Popen(cmd_array, start_new_session=True)
  109. else:
  110. return jsonify({"status": "1", "message": f"Reload unsucessful"})
  111. except Exception as exc:
  112. return jsonify({"status": "2", "message": f"Reload unsucessful: {exc}"})
  113. @app.route('/predict', methods=['POST'])
  114. def predict():
  115. result = []
  116. if "image" in request.json:
  117. im_b64 = request.json["image"]
  118. elif "image" in request.files:
  119. im_b64 = request.files["image"]
  120. elif "image" in request.form:
  121. im_b64 = request.form["image"]
  122. else:
  123. return {"error": "Error reading image"}
  124. im_bytes = base64.b64decode(im_b64)
  125. im_file = BytesIO(im_bytes)
  126. test_image = face_recognition.load_image_file(im_file)
  127. face_locations = face_recognition.face_locations(test_image)
  128. no = len(face_locations)
  129. if no > 0:
  130. for i in range(no):
  131. start_time = time.perf_counter()
  132. test_image_enc = face_recognition.face_encodings(test_image, model=face_model)[i]
  133. proba_list = clf.predict_proba([test_image_enc])
  134. dist = face_recognition.face_distance(known_faces, test_image_enc)
  135. total = np.subtract(proba_list, dist)
  136. i = np.argmax(total)
  137. proba = list(*proba_list)[i]
  138. name = dummy_data[i]["name"]
  139. address = dummy_data[i]["address"]
  140. nik = dummy_data[i]["nik"]
  141. if total[0][i] > total_threshold:
  142. js = {
  143. "id": str(i),
  144. "name": name,
  145. "address": address,
  146. "nik": nik,
  147. "proba": proba,
  148. "delta": total[0][i]
  149. }
  150. else:
  151. js = {
  152. "id": "-1",
  153. "name": "Unknown",
  154. "address": "",
  155. "nik": "",
  156. "proba": 0.0,
  157. "delta": 0.0
  158. }
  159. if total[0][i] > total_threshold or (not result and i == no - 1):
  160. result.append(js)
  161. end_time = time.perf_counter()
  162. process_time = end_time - start_time
  163. print(time.strftime("%c"))
  164. print(total[0])
  165. print("Process time:", process_time, "s")
  166. print(result)
  167. return jsonify(result)
  168. try:
  169. clf = joblib.load(model_file_name)
  170. classes = clf.classes_
  171. print('model loaded')
  172. known_faces = scan_known_people(known_people)
  173. print('known faces scanned')
  174. except FileNotFoundError as e:
  175. print('No model here')
  176. exit(1)
  177. if __name__ == '__main__':
  178. app.run(host='0.0.0.0', port=8349, debug=True, ssl_context=ssl)