123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152 |
- from PIL import ImageFile
- from flask import Flask, request, jsonify
- import face_recognition
- import base64
- from io import BytesIO
- import joblib
- import numpy as np
- import re
- import os
- import time
- ImageFile.SAFEBLOCK = 2048 * 2048
- app = Flask(__name__)
- model_file_name = "saved_model_2.pkl"
- clf = None
- classes = None
- dummy_data = [
- {
- "name": "Bayu",
- "address": "299 St Louis Road Oak Forest, IL 60452",
- "nik": "1000076456784631"
- },
- {
- "name": "Dio",
- "address": "22 Whitemarsh St. Mansfield, MA 02048",
- "nik": "1000024792887549"
- },
- {
- "name": "Hadi",
- "address": "643 Honey Creek Dr. Milledgeville, GA 31061",
- "nik": "1000038502830420"
- },
- {
- "name": "Kevin",
- "address": "881 Cooper Ave. Hummelstown, PA 17036",
- "nik": "1000045356476664"
- },
- {
- "name": "Matrix",
- "address": "580 Glenwood Dr. Garner, NC 27529",
- "nik": "1000023452134598"
- },
- {
- "name": "Surya",
- "address": "909 South St Paul Street Hopewell, VA 23860",
- "nik": "1000075656784734"
- },
- ]
- ssl = None
- known_people = "application_data/verification_images"
- known_faces = []
- total_threshold = 0.2
- face_model = "large"
- if face_model == "large":
- model_file_name = "saved_model_2_large.pkl"
- def scan_known_people(known_people_folder):
- known_face_encodings = []
- for file in image_files_in_folder(known_people_folder):
- img = face_recognition.load_image_file(file)
- encodings = face_recognition.face_encodings(img, model=face_model)
- if len(encodings) > 1:
- print("WARNING: More than one face found in {}. Only considering the first face.".format(file))
- if len(encodings) == 0:
- print("WARNING: No faces found in {}. Ignoring file.".format(file))
- else:
- known_face_encodings.append(encodings[0])
- return known_face_encodings
- def image_files_in_folder(folder):
- img_list = [os.path.join(folder, f) for f in os.listdir(folder) if
- re.match(r'.*\.(jpg|jpeg|png|webp)', f, flags=re.I)]
- img_list.sort()
- return img_list
- @app.route('/predict', methods=['POST'])
- def predict():
- result = []
- if "image" in request.json:
- im_b64 = request.json["image"]
- elif "image" in request.files:
- im_b64 = request.files["image"]
- elif "image" in request.form:
- im_b64 = request.form["image"]
- else:
- return {"error": "Error reading image"}
- im_bytes = base64.b64decode(im_b64)
- im_file = BytesIO(im_bytes)
- test_image = face_recognition.load_image_file(im_file)
- face_locations = face_recognition.face_locations(test_image)
- no = len(face_locations)
- if no > 0:
- for i in range(no):
- start_time = time.perf_counter()
- test_image_enc = face_recognition.face_encodings(test_image, model=face_model)[i]
- proba_list = clf.predict_proba([test_image_enc])
- dist = face_recognition.face_distance(known_faces, test_image_enc)
- total = np.subtract(proba_list, dist)
- i = np.argmax(total)
- proba = list(*proba_list)[i]
- name = dummy_data[i]["name"]
- address = dummy_data[i]["address"]
- nik = dummy_data[i]["nik"]
- if total[0][i] > total_threshold:
- js = {
- "id": str(i),
- "name": name,
- "address": address,
- "nik": nik,
- "proba": proba,
- "delta": total[0][i]
- }
- else:
- js = {
- "id": -1,
- "name": "Unknown",
- "address": "",
- "nik": "",
- "proba": 0.0,
- "delta": 0.0
- }
- if total[0][i] > total_threshold or (not result and i == no - 1):
- result.append(js)
- end_time = time.perf_counter()
- process_time = end_time - start_time
- print(total[0])
- print("Process time:", process_time, "s")
- print(result)
- return jsonify(result)
- try:
- clf = joblib.load(model_file_name)
- classes = clf.classes_
- print('model loaded')
- known_faces = scan_known_people(known_people)
- print('known faces scanned')
- except FileNotFoundError as e:
- print('No model here')
- exit(1)
- if __name__ == '__main__':
- app.run(host='0.0.0.0', port=8349, debug=True, ssl_context=ssl)
|