From 2dfc1586fb4f8b83012588411c92817465f888a6 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sat, 19 Oct 2024 15:44:39 +0000 Subject: [PATCH] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- API/__init__.py | 5 +++- API/database.py | 7 +++-- FaceRec/app/main/Edit.py | 24 ++++++++++++----- FaceRec/app/main/Employee.py | 19 +++++++++----- FaceRec/app/main/Face.py | 14 +++++++--- FaceRec/app/main/VideoImage.py | 47 +++++++++++++++++++++++++--------- FaceRec/app/main/__init__.py | 1 + FaceRec/config.py | 11 ++++++-- Model-Training/eval-mark-I.py | 5 ++++ main.py | 4 +++ testing/test_database.py | 1 + testing/test_face_cycle.py | 5 ++-- testing/test_face_endpoints.py | 18 ++++++++++--- 13 files changed, 123 insertions(+), 38 deletions(-) diff --git a/API/__init__.py b/API/__init__.py index f5e794d..c4a6e9b 100644 --- a/API/__init__.py +++ b/API/__init__.py @@ -1,7 +1,8 @@ from __future__ import annotations -import uvicorn import logging + +import uvicorn from fastapi import FastAPI, HTTPException from API import route @@ -15,6 +16,7 @@ # API Router Fastapp.include_router(route.router) + @Fastapp.get("/") def read_root(): try: @@ -23,6 +25,7 @@ def read_root(): logger.error(f"Error in root endpoint: {e}") raise HTTPException(status_code=500, detail="Internal Server Error") + # Function to run FastAPI server def run_fastapi_app(): try: diff --git a/API/database.py b/API/database.py index 305a466..a99822f 100644 --- a/API/database.py +++ b/API/database.py @@ -1,13 +1,15 @@ from __future__ import annotations -from datetime import datetime import logging +from datetime import datetime + from pymongo import MongoClient, errors # Initialize logger logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) + class Database: def __init__(self, uri="mongodb://localhost:27017/", db_name="ImageDB"): """ @@ -148,5 +150,6 @@ def vector_search(self, collection, embedding): result_arr = [i for i in result] return result_arr except errors.PyMongoError as e: - logger.error(f"Error performing vector search in {collection}: {e}") + logger.error( + f"Error performing vector search in {collection}: {e}") return [] diff --git a/FaceRec/app/main/Edit.py b/FaceRec/app/main/Edit.py index 860b835..8764009 100644 --- a/FaceRec/app/main/Edit.py +++ b/FaceRec/app/main/Edit.py @@ -28,6 +28,7 @@ print("Error: Could not open video capture.") # You can raise an exception or handle it as needed + # Function for displaying live video def display_live_video(): """ @@ -51,6 +52,7 @@ def display_live_video(): bytearray(buffer) + b"\r\n\r\n" ) + # Route for displaying video @Edit_blueprint.route("/video_feed") def video_feed(): @@ -63,6 +65,7 @@ def video_feed(): mimetype="multipart/x-mixed-replace;boundary=frame", ) + # Route for capturing image from video @Edit_blueprint.route("/capture", methods=["GET", "POST"]) def capture(): @@ -91,7 +94,7 @@ def capture(): Name = request.form.get("Name", "") gender = request.form.get("gender", "") Dept = request.form.get("Department", "") - + try: ret, frame = cap.read(True) if not ret: @@ -101,7 +104,7 @@ def capture(): frame = cv2.flip(frame, 1) _, buffer = cv2.imencode(".jpg", frame) encoded_image = base64.b64encode(buffer).decode("utf-8") - + with open(Config.image_data_file, "w") as file: json.dump({"base64_image": encoded_image}, file) except Exception as e: @@ -109,6 +112,7 @@ def capture(): return redirect("Image") + # Route to display captured image @Edit_blueprint.route("/Image", methods=["GET"]) def display_image(): @@ -154,7 +158,8 @@ def display_image(): if image: recent_image = image[0] - image_path = os.path.join(Config.upload_image_path[0], recent_image) + image_path = os.path.join( + Config.upload_image_path[0], recent_image) else: recent_image = None image_path = "" @@ -166,7 +171,10 @@ def display_image(): return render_template("index.html", image_path=image_path) except Exception as e: print(f"Error while displaying image: {e}") - return render_template("index.html", image_path="") # Show a default image or handle error + return render_template( + "index.html", image_path="" + ) # Show a default image or handle error + @Edit_blueprint.route("/edit/", methods=["POST", "GET"]) def edit(EmployeeCode): @@ -221,7 +229,9 @@ def edit(EmployeeCode): if url.status_code == 200: return redirect("/") else: - print(f"Error: Failed to update employee data with status code {url.status_code}") + print( + f"Error: Failed to update employee data with status code {url.status_code}" + ) except requests.exceptions.RequestException as e: print(f"Request failed: {e}") @@ -234,7 +244,9 @@ def edit(EmployeeCode): employee_data = response.json() return render_template("edit.html", employee_data=employee_data) else: - print(f"Error: Failed to retrieve employee data with status code {response.status_code}") + print( + f"Error: Failed to retrieve employee data with status code {response.status_code}" + ) return f"Error {response.status_code}: Failed to retrieve employee data." except requests.exceptions.RequestException as e: print(f"Request failed: {e}") diff --git a/FaceRec/app/main/Employee.py b/FaceRec/app/main/Employee.py index 4a016e9..8e57026 100644 --- a/FaceRec/app/main/Employee.py +++ b/FaceRec/app/main/Employee.py @@ -2,12 +2,12 @@ import base64 import json +import logging import os import cv2 import requests from flask import Blueprint, jsonify, redirect, render_template, request -import logging from FaceRec.config import Config @@ -47,7 +47,9 @@ def display_information(): logger.info("Employee data retrieved successfully.") except requests.exceptions.RequestException as e: logger.error(f"Request failed: {e}") - employees = [] # Handle the error gracefully by setting employees to an empty list + employees = ( + [] + ) # Handle the error gracefully by setting employees to an empty list return render_template("table.html", employees=employees) @@ -74,7 +76,7 @@ def submit_form(): return jsonify({"message": "No file part"}), 400 file = request.files["File"] allowed_extensions = {"png", "jpg", "jpeg"} - if file and file.filename.split('.')[-1].lower() not in allowed_extensions: + if file and file.filename.split(".")[-1].lower() not in allowed_extensions: return jsonify({"message": "File extension is not valid"}), 400 image_data = file.read() @@ -94,7 +96,9 @@ def submit_form(): } # Send request to FastAPI - response = requests.post("http://127.0.0.1:8000/create_new_faceEntry", json=payload) + response = requests.post( + "http://127.0.0.1:8000/create_new_faceEntry", json=payload + ) response.raise_for_status() # Raise an error for bad responses logger.info("Employee record created successfully.") @@ -116,7 +120,8 @@ def delete(EmployeeCode): return jsonify({"message": "Employee code should be an integer"}), 400 try: - response = requests.delete(f"http://127.0.0.1:8000/delete/{EmployeeCode}") + response = requests.delete( + f"http://127.0.0.1:8000/delete/{EmployeeCode}") response.raise_for_status() # Raise an error for bad responses logger.info(f"Employee {EmployeeCode} deleted successfully.") except requests.exceptions.RequestException as e: @@ -157,7 +162,9 @@ def update_employee(EmployeeCode): "Department": Department, } - response = requests.put(f"http://127.0.0.1:8000/update/{EmployeeCode}", json=payload) + response = requests.put( + f"http://127.0.0.1:8000/update/{EmployeeCode}", json=payload + ) response.raise_for_status() # Raise an error for bad responses logger.info(f"Employee {EmployeeCode} updated successfully.") diff --git a/FaceRec/app/main/Face.py b/FaceRec/app/main/Face.py index 3ae4e68..9ada059 100644 --- a/FaceRec/app/main/Face.py +++ b/FaceRec/app/main/Face.py @@ -2,6 +2,7 @@ import base64 import json +import logging import os import cv2 @@ -9,7 +10,6 @@ from flask import Blueprint from flask import Response as flask_response from flask import redirect, render_template, request -import logging from FaceRec.config import Config @@ -98,7 +98,9 @@ def recognize(): # Capture the image file for recognition with open("captured_image.jpg", "rb") as img_file: files = {"image": (img_file, "image/jpeg")} - fastapi_url = "http://127.0.0.1:8000/recognize_face" # Replace with your FastAPI URL + fastapi_url = ( + "http://127.0.0.1:8000/recognize_face" # Replace with your FastAPI URL + ) response = requests.post(fastapi_url, files=files) response.raise_for_status() # Raise an error for bad responses logger.info("Recognition request successful.") @@ -106,8 +108,12 @@ def recognize(): except requests.exceptions.RequestException as e: logger.error(f"Recognition request failed: {e}") - return render_template("recognition.html", response_text="Recognition failed. Please try again.") + return render_template( + "recognition.html", response_text="Recognition failed. Please try again." + ) except Exception as e: logger.error(f"An unexpected error occurred: {e}") - return render_template("recognition.html", response_text="An unexpected error occurred.") + return render_template( + "recognition.html", response_text="An unexpected error occurred." + ) diff --git a/FaceRec/app/main/VideoImage.py b/FaceRec/app/main/VideoImage.py index 2d24de9..99150e2 100644 --- a/FaceRec/app/main/VideoImage.py +++ b/FaceRec/app/main/VideoImage.py @@ -3,8 +3,8 @@ import base64 import io import json -import os import logging +import os import cv2 import requests @@ -28,6 +28,7 @@ cap = cv2.VideoCapture(0) + # Function for displaying live video def display_live_video(): """ @@ -51,6 +52,7 @@ def display_live_video(): bytearray(buffer) + b"\r\n\r\n" ) + # Route for displaying video @employee_blueprint.route("/video_feed") def video_feed(): @@ -64,6 +66,7 @@ def video_feed(): mimetype="multipart/x-mixed-replace;boundary=frame", ) + # Route for capturing image from video @employee_blueprint.route("/capture", methods=["GET", "POST"]) def capture(): @@ -76,13 +79,13 @@ def capture(): Name = request.form.get("Name", "") gender = request.form.get("gender", "") Dept = request.form.get("Department", "") - + try: ret, frame = cap.read() if not ret: logger.error("Failed to capture frame for employee image.") return jsonify({"error": "Failed to capture image"}), 500 - + frame = cv2.flip(frame, 1) _, buffer = cv2.imencode(".jpg", frame) encoded_image = base64.b64encode(buffer).decode("utf-8") @@ -97,6 +100,7 @@ def capture(): logger.error(f"Error capturing image: {e}") return jsonify({"error": "Error capturing image"}), 500 + # Route to display captured image @employee_blueprint.route("/Image", methods=["GET"]) def display_image(): @@ -114,21 +118,29 @@ def display_image(): decoded_image_data = base64.b64decode(encoded_image) image = Image.open(io.BytesIO(decoded_image_data)) filename = "final.png" - image.save(os.path.join(Config.upload_image_path[0], filename), quality=100) + image.save(os.path.join( + Config.upload_image_path[0], filename), quality=100) recent_images = sorted( os.listdir(Config.upload_image_path[0]), - key=lambda x: os.path.getatime(os.path.join(Config.upload_image_path[0], x)), + key=lambda x: os.path.getatime( + os.path.join(Config.upload_image_path[0], x) + ), reverse=True, ) - image_path = os.path.join(Config.upload_image_path[0], recent_images[0]) if recent_images else None + image_path = ( + os.path.join(Config.upload_image_path[0], recent_images[0]) + if recent_images + else None + ) logger.info("Image displayed successfully.") except Exception as e: logger.error(f"Error displaying image: {e}") return jsonify({"error": "Error displaying image"}), 500 - + return render_template("index.html", image_path=image_path) + # Route for recognition capturing @employee_blueprint.route("/capturing", methods=["GET", "POST"]) def capturing(): @@ -155,6 +167,7 @@ def capturing(): logger.error(f"Error capturing recognition image: {e}") return jsonify({"error": "Error capturing recognition image"}), 500 + # Route to display captured image for recognition @employee_blueprint.route("/Pic", methods=["GET", "POST"]) def display_pic(): @@ -167,18 +180,28 @@ def display_pic(): decoded_image_data = base64.b64decode(encoded_image) image = Image.open(io.BytesIO(decoded_image_data)) filename = "final.png" - image.save(os.path.join(Config.upload_image_path[0], filename), quality=100) + image.save(os.path.join( + Config.upload_image_path[0], filename), quality=100) recent_images = sorted( os.listdir(Config.upload_image_path[0]), - key=lambda x: os.path.getatime(os.path.join(Config.upload_image_path[0], x)), + key=lambda x: os.path.getatime( + os.path.join(Config.upload_image_path[0], x) + ), reverse=True, ) - image_path = os.path.join(Config.upload_image_path[0], recent_images[0]) if recent_images else None - + image_path = ( + os.path.join(Config.upload_image_path[0], recent_images[0]) + if recent_images + else None + ) + logger.info("Displaying recognition image.") files = { - "Face": open(os.path.join(Config.upload_image_path[0], "final.png"), "rb"), + "Face": open( + os.path.join( + Config.upload_image_path[0], "final.png"), "rb" + ), } fastapi_url = "http://127.0.0.1:8000/recognize_face" req = requests.post(fastapi_url, files=files) diff --git a/FaceRec/app/main/__init__.py b/FaceRec/app/main/__init__.py index 21782e0..b84d5e2 100644 --- a/FaceRec/app/main/__init__.py +++ b/FaceRec/app/main/__init__.py @@ -22,6 +22,7 @@ except Exception as e: print(f"Error registering blueprints: {e}") + # Function to run the server of Flask def run_flask(): try: diff --git a/FaceRec/config.py b/FaceRec/config.py index 613b977..754fc95 100644 --- a/FaceRec/config.py +++ b/FaceRec/config.py @@ -4,6 +4,7 @@ basedir = os.path.abspath(os.path.dirname(__file__)) + # This class named Config is likely used for storing configuration settings or parameters in a Python program. class Config: try: @@ -19,9 +20,15 @@ class Config: print(f"Error setting upload_image_path: {e}") upload_image_path = None # Default to None or handle it as needed - ALLOWED_EXTENSIONS = ["jpg", "jpeg", "png", "jfif"] # Use a list, not a tuple with a list inside + ALLOWED_EXTENSIONS = [ + "jpg", + "jpeg", + "png", + "jfif", + ] # Use a list, not a tuple with a list inside try: - image_data_file = os.path.join(basedir, "static/Images/image_data.json") + image_data_file = os.path.join( + basedir, "static/Images/image_data.json") except Exception as e: print(f"Error setting image_data_file path: {e}") image_data_file = None # Default to None or handle it as needed diff --git a/Model-Training/eval-mark-I.py b/Model-Training/eval-mark-I.py index 087ded8..1dfc2e5 100644 --- a/Model-Training/eval-mark-I.py +++ b/Model-Training/eval-mark-I.py @@ -1,11 +1,13 @@ from __future__ import annotations import os + import numpy as np from keras.models import load_model from keras.preprocessing import image from sklearn.metrics.pairwise import euclidean_distances + # Function to load and preprocess images def load_and_preprocess_image(img_path, target_size=(160, 160)): try: @@ -18,6 +20,7 @@ def load_and_preprocess_image(img_path, target_size=(160, 160)): print(f"Error loading image {img_path}: {e}") return None + # Function to generate embeddings def generate_embeddings(model, dataset_path): embeddings = [] @@ -41,6 +44,7 @@ def generate_embeddings(model, dataset_path): labels = np.array(labels) return embeddings, labels + # Function to calculate intra-cluster distances def calculate_intra_cluster_distances(embeddings, labels): unique_labels = np.unique(labels) @@ -59,6 +63,7 @@ def calculate_intra_cluster_distances(embeddings, labels): return np.array(distances) + # Load the pre-trained FaceNet model model_path = "facenet_model.h5" model = load_model(model_path) diff --git a/main.py b/main.py index a3c828c..7ccebdd 100644 --- a/main.py +++ b/main.py @@ -2,6 +2,7 @@ import logging from concurrent.futures import ThreadPoolExecutor + from API import run_fastapi_app from FaceRec.app.main import run_flask @@ -9,6 +10,7 @@ logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) + # Function to run Flask app with exception handling def run_flask_app(): try: @@ -16,6 +18,7 @@ def run_flask_app(): except Exception as e: logger.error(f"Error starting Flask app: {e}") + # Function to run FastAPI app with exception handling def run_fastapi_app_with_handling(): try: @@ -23,6 +26,7 @@ def run_fastapi_app_with_handling(): except Exception as e: logger.error(f"Error starting FastAPI app: {e}") + # Multithreading used to start both FastAPI and Flask apps at the same time. if __name__ == "__main__": with ThreadPoolExecutor(max_workers=2) as executor: diff --git a/testing/test_database.py b/testing/test_database.py index ffaf29e..e247b90 100644 --- a/testing/test_database.py +++ b/testing/test_database.py @@ -13,6 +13,7 @@ init_logging_config() + def test_vector_search(): """ Test that the vector_search function returns the correct result. diff --git a/testing/test_face_cycle.py b/testing/test_face_cycle.py index 27f18fe..415e0c6 100644 --- a/testing/test_face_cycle.py +++ b/testing/test_face_cycle.py @@ -10,6 +10,7 @@ client = TestClient(router) + @patch("API.database.Database.find_one_and_delete") @patch("API.database.Database.update_one") @patch("API.database.Database.find_one") @@ -51,7 +52,7 @@ def test_face_lifecycle( with open("./test-faces/devansh.jpg", "rb") as image_file: encoded_string1 = base64.b64encode(image_file.read()).decode("utf-8") - + response1 = client.post( "/create_new_faceEntry", json={ @@ -67,7 +68,7 @@ def test_face_lifecycle( with open("./test-faces/devansh.jpg", "rb") as image_file: encoded_string2 = base64.b64encode(image_file.read()).decode("utf-8") - + response2 = client.post( "/create_new_faceEntry", json={ diff --git a/testing/test_face_endpoints.py b/testing/test_face_endpoints.py index 7cafcce..a0f1fa5 100644 --- a/testing/test_face_endpoints.py +++ b/testing/test_face_endpoints.py @@ -6,6 +6,7 @@ import pytest from fastapi.testclient import TestClient + from API.route import router from API.utils import init_logging_config @@ -14,10 +15,12 @@ client = TestClient(router) + # Exception handling utility function def log_exception(message: str): logging.error(message) + @pytest.mark.run(order=1) def test_register_face1(): """ @@ -47,7 +50,8 @@ def test_register_face1(): "API.database.Database.find_one_and_delete", mock_find_one_and_delete ): with open("./test-faces/devansh.jpg", "rb") as image_file: - encoded_string1 = base64.b64encode(image_file.read()).decode("utf-8") + encoded_string1 = base64.b64encode( + image_file.read()).decode("utf-8") response1 = client.post( "/create_new_faceEntry", @@ -67,6 +71,7 @@ def test_register_face1(): log_exception(f"Error in test_register_face1: {e}") pytest.fail(f"Test failed due to exception: {e}") + @pytest.mark.run(order=2) def test_register_face2(): """ @@ -96,7 +101,8 @@ def test_register_face2(): "API.database.Database.find_one_and_delete", mock_find_one_and_delete ): with open("./test-faces/devansh.jpg", "rb") as image_file: - encoded_string2 = base64.b64encode(image_file.read()).decode("utf-8") + encoded_string2 = base64.b64encode( + image_file.read()).decode("utf-8") response2 = client.post( "/create_new_faceEntry", @@ -116,6 +122,7 @@ def test_register_face2(): log_exception(f"Error in test_register_face2: {e}") pytest.fail(f"Test failed due to exception: {e}") + @pytest.mark.run(order=3) def test_get_all_faces_after_registration(): """ @@ -142,6 +149,7 @@ def test_get_all_faces_after_registration(): log_exception(f"Error in test_get_all_faces_after_registration: {e}") pytest.fail(f"Test failed due to exception: {e}") + @pytest.mark.run(order=4) def test_update_face(): """ @@ -171,7 +179,8 @@ def test_update_face(): "API.database.Database.find_one_and_delete", mock_find_one_and_delete ): with open("./test-faces/devansh.jpg", "rb") as image_file: - encoded_string2 = base64.b64encode(image_file.read()).decode("utf-8") + encoded_string2 = base64.b64encode( + image_file.read()).decode("utf-8") response = client.put( "/update/1", @@ -188,6 +197,7 @@ def test_update_face(): log_exception(f"Error in test_update_face: {e}") pytest.fail(f"Test failed due to exception: {e}") + @pytest.mark.run(order=5) def test_delete_face(): """ @@ -201,6 +211,7 @@ def test_delete_face(): log_exception(f"Error in test_delete_face: {e}") pytest.fail(f"Test failed due to exception: {e}") + @pytest.mark.run(order=6) def test_recognize_face_fail(): """ @@ -225,6 +236,7 @@ def test_recognize_face_fail(): log_exception(f"Error in test_recognize_face_fail: {e}") pytest.fail(f"Test failed due to exception: {e}") + @pytest.mark.run(order=7) def test_recognize_face_success(): """