fr_flask.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. ImageFile.SAFEBLOCK = 2048 * 2048
  9. app = Flask(__name__)
  10. model_file_name = "saved_model.pkl"
  11. clf = None
  12. classes = None
  13. dummy_data = [
  14. {
  15. "name": "Bayu",
  16. "address": "299 St Louis Road Oak Forest, IL 60452",
  17. "nik": "1000076456784631"
  18. },
  19. {
  20. "name": "Dio",
  21. "address": "22 Whitemarsh St. Mansfield, MA 02048",
  22. "nik": "1000024792887549"
  23. },
  24. {
  25. "name": "Hadi",
  26. "address": "643 Honey Creek Dr. Milledgeville, GA 31061",
  27. "nik": "1000038502830420"
  28. },
  29. {
  30. "name": "Kevin",
  31. "address": "881 Cooper Ave. Hummelstown, PA 17036",
  32. "nik": "1000045356476664"
  33. },
  34. {
  35. "name": "Matrix",
  36. "address": "580 Glenwood Dr. Garner, NC 27529",
  37. "nik": "1000023452134598"
  38. },
  39. {
  40. "name": "Surya",
  41. "address": "909 South St Paul Street Hopewell, VA 23860",
  42. "nik": "1000075656784734"
  43. },
  44. ]
  45. ssl = None
  46. @app.route('/predict', methods=['POST'])
  47. def predict():
  48. result = []
  49. if "image" in request.json:
  50. im_b64 = request.json["image"]
  51. elif "image" in request.files:
  52. im_b64 = request.files["image"]
  53. elif "image" in request.form:
  54. im_b64 = request.form["image"]
  55. else:
  56. return {"error": "Error reading image"}
  57. im_bytes = base64.b64decode(im_b64)
  58. im_file = BytesIO(im_bytes)
  59. test_image = face_recognition.load_image_file(im_file)
  60. face_locations = face_recognition.face_locations(test_image)
  61. no = len(face_locations)
  62. for i in range(no):
  63. test_image_enc = face_recognition.face_encodings(test_image)[i]
  64. proba_list = clf.predict_proba([test_image_enc])
  65. i = np.argmax(proba_list)
  66. proba = list(*proba_list)[i]
  67. name = dummy_data[i]["name"]
  68. address = dummy_data[i]["address"]
  69. nik = dummy_data[i]["nik"]
  70. js = {
  71. "id": str(i),
  72. "name": name,
  73. "address": address,
  74. "nik": nik,
  75. "proba": proba
  76. }
  77. result.append(js)
  78. return jsonify(result)
  79. if __name__ == '__main__':
  80. try:
  81. clf = joblib.load(model_file_name)
  82. classes = clf.classes_
  83. print('model loaded')
  84. except FileNotFoundError as e:
  85. print('No model here')
  86. exit(1)
  87. app.run(host='0.0.0.0', port=8349, debug=True, ssl_context=ssl)