Jelajahi Sumber

refactor & update requirements.txt

kevin 2 tahun lalu
induk
melakukan
a9582b7bc9
2 mengubah file dengan 66 tambahan dan 52 penghapusan
  1. 62 51
      fr_flask.py
  2. 4 1
      requirements.txt

+ 62 - 51
fr_flask.py

@@ -60,7 +60,7 @@ face_model = "large"
 if face_model == "large":
     model_file_name = "saved_model_2_large.pkl"
 
-TRAINING_FOLDER = os.path.join("data","train")
+TRAINING_FOLDER = os.path.join("data", "train")
 PROFILE_FOLDER = os.path.join("application_data", "verification_images")
 app.config["TRAINING_FOLDER"] = TRAINING_FOLDER
 app.config["PROFILE_FOLDER"] = PROFILE_FOLDER
@@ -68,7 +68,9 @@ app.config["PROFILE_FOLDER"] = PROFILE_FOLDER
 db_user = "facer"
 db_pass = "9Y6Bqg3JwQxXa"
 
-db = mysql.connector.connect(user=db_user, password=db_pass, unix_socket="/opt/lampp/var/mysql/mysql.sock", database='face_recognition')
+db = mysql.connector.connect(user=db_user, password=db_pass, unix_socket="/opt/lampp/var/mysql/mysql.sock",
+                             database='face_recognition')
+
 
 def scan_known_people(known_people_folder):
     known_face_encodings = []
@@ -92,37 +94,40 @@ def image_files_in_folder(folder):
     img_list.sort()
     return img_list
 
-def load_db(id):
-    db = mysql.connector.connect(user=db_user, password=db_pass, unix_socket="/opt/lampp/var/mysql/mysql.sock",
-                                 database='face_recognition')
-    cursor = db.cursor()
-    result = {"name": "Unknown", "address": "", "nik": ""}
+
+def load_db(data_id):
+    db_con = mysql.connector.connect(user=db_user, password=db_pass, unix_socket="/opt/lampp/var/mysql/mysql.sock",
+                                     database='face_recognition')
+    db_cursor = db_con.cursor()
+    db_result = {"name": "Unknown", "address": "", "nik": ""}
     try:
-        query = "SELECT `NIK`, `NAME`, `ADDRESS` FROM `face_recognition` WHERE `ID` = {}".format(id)
-        cursor.execute(query)
-        for (nik, name, address) in cursor:
-            result['nik'] = nik
-            result['name'] = name
-            result['address'] = address
+        db_query = "SELECT `NIK`, `NAME`, `ADDRESS` FROM `face_recognition` WHERE `ID` = %s"
+        db_cursor.execute(db_query, data_id)
+        for (nik, name, address) in db_cursor:
+            db_result['nik'] = nik
+            db_result['name'] = name
+            db_result['address'] = address
     finally:
-        cursor.close()
-        db.close()
-    return result
+        db_cursor.close()
+        db_con.close()
+    return db_result
+
 
 def save_db(nik, name, address):
-    db = mysql.connector.connect(user=db_user, password=db_pass, unix_socket="/opt/lampp/var/mysql/mysql.sock",
-                                 database='face_recognition')
-    id = None
-    cursor = db.cursor()
+    db_con = mysql.connector.connect(user=db_user, password=db_pass, unix_socket="/opt/lampp/var/mysql/mysql.sock",
+                                     database='face_recognition')
+    data_id = None
+    db_cursor = db_con.cursor()
     try:
-        query = 'INSERT INTO `face_recognition` (`NIK`, `NAME`, `ADDRESS`) VALUES ("{}", "{}", "{}")'.format(nik,name,address)
-        cursor.execute(query)
-        db.commit()
-        id = cursor.lastrowid
+        db_query = 'INSERT INTO `face_recognition` (`NIK`, `NAME`, `ADDRESS`) VALUES (%s, %s, %s)'
+        db_cursor.execute(db_query, (nik, name, address))
+        db_con.commit()
+        data_id = db_cursor.lastrowid
     finally:
-        cursor.close()
-        db.close()
-    return id
+        db_cursor.close()
+        db_con.close()
+    return data_id
+
 
 def get_face(image, crop=False):
     max_height = image.height
@@ -150,13 +155,15 @@ def get_face(image, crop=False):
             cropped = image.crop((new_left, new_top, new_right, new_bottom))
             resized = cropped.resize((250, 250))
         else:
-            resized = image.resize((250,250))
+            resized = image.resize((250, 250))
         return resized
     return None
 
-@app.route('/',methods=['GET', 'POST'])
+
+@app.route('/', methods=['GET', 'POST'])
 def test():
-    return jsonify({"status" : "0"})
+    return jsonify({"status": "0"})
+
 
 @app.route('/upload', methods=['POST'])
 def upload():
@@ -173,7 +180,7 @@ def upload():
             training = request.files.getlist("training[]")
         else:
             files_length = len(request.files)
-            training_names = [f'training{x}' for x in range(files_length-1)]
+            training_names = [f'training{x}' for x in range(files_length - 1)]
             for x in training_names:
                 training.append(request.files[x])
         print(training)
@@ -194,24 +201,26 @@ def upload():
                 detected_training.append(new_training_image)
                 detected_training_fn.append(file.filename)
         if not detected_training:
-            return jsonify({"status": "4", "message": "No face found on any training images, please upload a different picture"})
+            return jsonify(
+                {"status": "4", "message": "No face found on any training images, please upload a different picture"})
         print(detected_training)
         print(detected_training_fn)
         # Save
-        id = save_db(nik, name, address)
-        print(id)
-        if not id:
+        user_id = save_db(nik, name, address)
+        print(user_id)
+        if not user_id:
             return jsonify({"status": "1", "message": "Error uploading data, please try again"})
-        new_profile_image.save(os.path.join(app.config["PROFILE_FOLDER"], f'{id}.jpg'))
-        id_dir = os.path.join(app.config['TRAINING_FOLDER'], str(id))
+        new_profile_image.save(os.path.join(app.config["PROFILE_FOLDER"], f'{user_id}.jpg'))
+        id_dir = os.path.join(app.config['TRAINING_FOLDER'], str(user_id))
         if not os.path.exists(id_dir):
             os.mkdir(id_dir)
         for (image, filename) in zip(detected_training, detected_training_fn):
-            image.save(os.path.join(app.config['TRAINING_FOLDER'], str(id), filename))
+            image.save(os.path.join(app.config['TRAINING_FOLDER'], str(user_id), filename))
         return jsonify({"status": "0", "message": "Upload successful"})
     except Exception as exc:
         return jsonify({"status": "1", "message": f"Error uploading data, please try again | {exc}"})
 
+
 @app.route('/train', methods=['GET', 'POST'])
 def train():
     try:
@@ -220,25 +229,27 @@ def train():
     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:
+        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)
-            p = subprocess.Popen(cmd_array, start_new_session=True)
+            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 = []
+    db_result = []
     if "image" in request.json:
         im_b64 = request.json["image"]
     elif "image" in request.files:
@@ -295,18 +306,19 @@ def predict():
                     "delta": 0.0
                 }
             print(total[0][i] > total_threshold)
-            print(not result)
+            print(not db_result)
             print(i == no - 1)
-            print((not result and i == no - 1))
-            if total[0][i] > total_threshold or (not result and i == no - 1):
-                result.append(js)
+            print((not db_result and i == no - 1))
+            if total[0][i] > total_threshold or (not db_result and i == no - 1):
+                db_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)
+    print(db_result)
+    return jsonify(db_result)
+
 
 try:
     clf = joblib.load(model_file_name)
@@ -321,17 +333,16 @@ try:
     try:
         query = "SELECT `ID` FROM `face_recognition` ORDER BY `ID`"
         cursor.execute(query)
-        for id in cursor:
-            ids.append(id[0])
+        for data_id in cursor:
+            ids.append(data_id[0])
     finally:
         cursor.close()
         db.close()
-    print("ids: ",ids)
+    print("ids: ", ids)
 
 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)

+ 4 - 1
requirements.txt

@@ -2,4 +2,7 @@ joblib
 face-recognition
 Flask
 scikit-learn
-gunicorn
+gunicorn
+mysql-connector-python
+Pillow
+numpy