123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208 |
- 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
- import shlex
- import subprocess
- from face_recognition_svm import train_svm
- 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"
- },
- {
- "name": "Abi",
- "address": "47 Rockville Road Leland, NC 28451",
- "nik": "1000084937284959"
- },
- ]
- ssl = None
- known_people = "application_data/verification_images"
- known_faces = []
- total_threshold = 0.1
- face_model = "large"
- if face_model == "large":
- model_file_name = "saved_model_2_large.pkl"
- UPLOAD_FOLDER = ""
- 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
- def load_db():
- pass
- def save_db(nik, name, address):
- pass
- @app.route('/', methods=['GET', 'POST'])
- def test():
- return jsonify({"status": "0"})
- @app.route('/upload', methods=['POST'])
- def upload():
- profile = request.files["profile"]
- nik = request.form["nik"]
- name = request.form["name"]
- address = request.form["address"]
- @app.route('/train', methods=['GET', 'POST'])
- def train():
- try:
- train_svm(model_file_name)
- return jsonify({"status": "0", "message": "Train successful"})
- except Exception as exc:
- return jsonify({"status": "1", "message": f"Error training model: {exc}"})
- @app.route('/reload', methods=['GET', 'POST'])
- def face_reload():
- pid = None
- try:
- with open("app.pid", "r") as f:
- pid = f.readline()
- if pid:
- cmd = f"kill -s HUP {pid}"
- cmd_array = shlex.split(cmd)
- print(cmd_array)
- subprocess.Popen(cmd_array, start_new_session=True)
- else:
- return jsonify({"status": "1", "message": f"Reload unsucessful"})
- except Exception as exc:
- return jsonify({"status": "2", "message": f"Reload unsucessful: {exc}"})
- @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(time.strftime("%c"))
- 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)
|