Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Oct 19, 2024
1 parent ed215ed commit 2dfc158
Show file tree
Hide file tree
Showing 13 changed files with 123 additions and 38 deletions.
5 changes: 4 additions & 1 deletion API/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

import uvicorn
import logging

import uvicorn
from fastapi import FastAPI, HTTPException

from API import route
Expand All @@ -15,6 +16,7 @@
# API Router
Fastapp.include_router(route.router)


@Fastapp.get("/")
def read_root():
try:
Expand All @@ -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:
Expand Down
7 changes: 5 additions & 2 deletions API/database.py
Original file line number Diff line number Diff line change
@@ -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"):
"""
Expand Down Expand Up @@ -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 []
24 changes: 18 additions & 6 deletions FaceRec/app/main/Edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
"""
Expand All @@ -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():
Expand All @@ -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():
Expand Down Expand Up @@ -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:
Expand All @@ -101,14 +104,15 @@ 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:
print(f"Error while capturing image: {e}")

return redirect("Image")


# Route to display captured image
@Edit_blueprint.route("/Image", methods=["GET"])
def display_image():
Expand Down Expand Up @@ -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 = ""
Expand All @@ -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/<int:EmployeeCode>", methods=["POST", "GET"])
def edit(EmployeeCode):
Expand Down Expand Up @@ -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}")

Expand All @@ -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}")
Expand Down
19 changes: 13 additions & 6 deletions FaceRec/app/main/Employee.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)


Expand All @@ -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()
Expand All @@ -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.")

Expand All @@ -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:
Expand Down Expand Up @@ -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.")

Expand Down
14 changes: 10 additions & 4 deletions FaceRec/app/main/Face.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

import base64
import json
import logging
import os

import cv2
import requests
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

Expand Down Expand Up @@ -98,16 +98,22 @@ 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.")
return render_template("recognition.html", response_text=response.text)

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."
)
47 changes: 35 additions & 12 deletions FaceRec/app/main/VideoImage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import base64
import io
import json
import os
import logging
import os

import cv2
import requests
Expand All @@ -28,6 +28,7 @@

cap = cv2.VideoCapture(0)


# Function for displaying live video
def display_live_video():
"""
Expand All @@ -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():
Expand All @@ -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():
Expand All @@ -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")
Expand All @@ -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():
Expand All @@ -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():
Expand All @@ -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():
Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions FaceRec/app/main/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading

0 comments on commit 2dfc158

Please sign in to comment.