Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add Frontend Support for vector search function and improve face recognition #43

Merged
merged 12 commits into from
Jul 29, 2024
Merged
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,6 @@ venv/
*.pyc
.vscode/
__pyc
FaceRec/static/Images/uploads/*
Images/dbImages/*
Images/Faces/*
132 changes: 132 additions & 0 deletions FaceRec/app/main/Edit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import base64
import io
import json
import os
import cv2
from flask import Blueprint
from flask import Response as flask_response
from flask import redirect, render_template, request
from PIL import Image
import requests

from FaceRec.config import Config

Edit_blueprint = Blueprint(
"Edit_blueprint",
__name__,
template_folder="../../templates/",
static_folder="../../static/",
)

cap = cv2.VideoCapture(0)


# function for displaying live video
def display_live_video():
while True:
success, frame = cap.read() # Read a frame from the camera
if not success:
break
frame = cv2.flip(frame, 1)
ret, buffer = cv2.imencode(".jpg", frame)
frame = buffer.tobytes
if not ret:
break
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + bytearray(buffer) + b"\r\n\r\n"
)


# Route for displaying video
@Edit_blueprint.route("/video_feed")
def video_feed():
return flask_response(
display_live_video(), mimetype="multipart/x-mixed-replace;boundary=frame"
)


# Route for capturing image from video
@Edit_blueprint.route("/capture", methods=["GET", "POST"])
def capture():
global EmployeeCode
global Name
global gender
global Dept
global encoded_image
EmployeeCode = request.form.get("EmployeeCode", "")
Name = request.form.get("Name", "")
gender = request.form.get("gender", "")
Dept = request.form.get("Department", "")
ret, frame = cap.read(True)
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)
return redirect("Image")


# Route to display captured image
@Edit_blueprint.route("/Image", methods=["GET"])
def display_image():
if os.path.exists(Config.image_data_file):
with open(Config.image_data_file, "r") as file:
image_data = json.load(file)
encoded_image = image_data.get("base64_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 = sorted(
os.listdir(Config.upload_image_path[0]),
key=lambda x: os.path.getatime(
os.path.join(Config.upload_image_path[0], x)
),
reverse=True,
)
if image:
recent_image = image[0]
image_path = os.path.join(Config.upload_image_path[0], recent_image)
else:
recent_image = None
image_path = os.path.join(Config.upload_image_path[0], recent_image)
print("done")
return render_template("index.html", image_path=image_path)

@Edit_blueprint.route("/edit/<int:EmployeeCode>", methods=["POST", "GET"])
def edit(EmployeeCode):
if request.method == "POST":
Name = request.form["Name"]
gender = request.form["Gender"]
Department = request.form["Department"]
with open(Config.image_data_file, "r") as file:
image_data = json.load(file)
encoded_image = image_data.get("base64_image", "")
payload = {
"Name": Name,
"gender": gender,
"Department": Department,
"Image": encoded_image,
}
# logger.info(payload)
try:
url = requests.put(
f"http://127.0.0.1:8000/update/{EmployeeCode}", json=payload
)
Comment on lines +114 to +116

Check failure

Code scanning / CodeQL

Partial server-side request forgery Critical

Part of the URL of this request depends on a
user-provided value
.
url.status_code
# logger.info(url.json())

return redirect("/")

except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
response = requests.get(f"http://127.0.0.1:8000/read/{EmployeeCode}")

Check failure

Code scanning / CodeQL

Partial server-side request forgery Critical

Part of the URL of this request depends on a
user-provided value
.
# logger.info(response.status_code)
# logger.info(response.json())
if response.status_code == 200:
employee_data = response.json()
return render_template("edit.html", employee_data=employee_data)
else:
return f"Error {response.status_code}: Failed to retrieve employee data."

Comment on lines +1 to +132

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CODE REVIEW

  • The code has good use of comments and variable names, making it easy to follow.
  • It's beneficial to encapsulate the logic of video processing in a separate class or function for better maintainability.
  • It'd be good to handle potential exceptions such as when no camera is available.
class VideoProcessor:
    # Add methods for capturing, displaying, and processing video
    pass

These changes will organize the code better and improve the maintainability of the video processing logic.

171 changes: 69 additions & 102 deletions FaceRec/app/main/Employee.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,33 @@
import base64
import json
import os

import cv2
import io
import requests
from flask import Blueprint
from flask import jsonify
from flask import redirect
from flask import render_template
from flask import request

from flask import Blueprint, jsonify, redirect, render_template, request
from PIL import Image
from FaceRec.config import Config


video_capture = cv2.VideoCapture(0)
flk_blueprint = Blueprint(
'flk_blueprint ',
__name__,
template_folder='../../templates/',
static_folder='../../static/',
template_folder="../../templates/",
static_folder="../../static/",
# capture_image="../../Capture image/"
)


@flk_blueprint.route('/')
@flk_blueprint.route("/")
def Main_page():
path = str(Config.upload_image_path[0])
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
else:
pass
return redirect('DisplayingEmployees')


return redirect("DisplayingEmployees")
# Displaying all records
@flk_blueprint.route('/DisplayingEmployees')
def display_information():
Expand All @@ -41,44 +40,44 @@ def display_information():
# logger.info(resp.status_code)
# logger.info(resp.json())
employees = resp.json()

except requests.exceptions.RequestException as e:
print(f'Request failed: {e}')
return render_template('table.html', employees=employees)


print(f"Request failed: {e}")
return render_template("table.html", employees=employees)
# To add employee record
@flk_blueprint.route('/Add_employee')
def add_employee():
return render_template('index.html')


return render_template("index.html")
# To submit the form data to server and save it in database
@flk_blueprint.route('/submit_form', methods=['POST'])
def submit_form():

Employee_Code = request.form['EmployeeCode']
Name = request.form['Name']
gender = request.form['Gender']
Department = request.form['Department']

if request.files['File']:
if 'File' not in request.files:
return jsonify({'message': 'No file part'}), 400
file = request.files['File']
allowed_extensions = {'png', 'jpg', 'jpeg'}
Employee_Code = request.form["EmployeeCode"]
Name = request.form["Name"]
gender = request.form["Gender"]
Department = request.form["Department"]
if request.files["File"]:
if "File" not in request.files:
return jsonify({"message": "No file part"}), 400
file = request.files["File"]
allowed_extensions = {"png", "jpg", "jpeg"}
if (
'.' not in file.filename
or file.filename.split('.')[-1].lower() not in allowed_extensions
):
return jsonify({'message': 'File extension is not valid'}), 400
if file:
image_data = file.read()
encoded_image = base64.b64encode(image_data).decode('utf-8')
with open(Config.image_data_file, 'w') as file:
json.dump({'base64_image': encoded_image}, file)

with open(Config.image_data_file) as file:
encoded_image = base64.b64encode(image_data).decode("utf-8")
with open(Config.image_data_file, "w") as file:
json.dump({"base64_image": encoded_image}, file)
with open(Config.image_data_file, "r") as file:
image_data = json.load(file)
encoded_image = image_data.get('base64_image', '')
jsonify(
Expand All @@ -90,81 +89,49 @@ def submit_form():
'encoded_image': encoded_image,
},
)

payload = {
'EmployeeCode': Employee_Code,
'Name': Name,
'gender': gender,
'Department': Department,
'Image': encoded_image,
}
url = 'http://127.0.0.1:8000/create_new_faceEntry'
try:
resp = requests.post(
url=url,
json={
'EmployeeCode': 134,
'Name': 'Name',
'gender': 'gender',
'Department': 'Department',
'Image': 'your_image',
},
)
resp.status_code
except requests.exceptions.RequestException as e:
print(f'Request failed: {e}')
jsonify({'message': 'Successfully executed'})
print('Executed.')
if resp.status_code == 200:
return redirect('DisplayingEmployees')
url = "http://127.0.0.1:8000/create_new_faceEntry"
payload.status_code
# try:
# resp = requests.post(
# url=url,
# json={
# "EmployeeCode": 134,
# "Name": "Name",
# "gender": "gender",
# "Department": "Department",
# "Image": "your_image",
# },
# )
# resp.status_code
# except requests.exceptions.RequestException as e:
# print(f"Request failed: {e}")
jsonify({"message": "Successfully executed"})
print("Executed.")
if payload.status_code == 200:
return redirect("DisplayingEmployees")
else:
return jsonify({'message': 'Failed to execute'})


return jsonify({"message": "Failed to execute"})
# To edit an employee details
@flk_blueprint.route('/edit/<int:EmployeeCode>', methods=['POST', 'GET'])
def edit(EmployeeCode):
if request.method == 'POST':
Name = request.form['Name']
gender = request.form['Gender']
Department = request.form['Department']
with open(Config.image_data_file) as file:
image_data = json.load(file)
encoded_image = image_data.get('base64_image', '')
payload = {
'Name': Name,
'gender': gender,
'Department': Department,
'Image': encoded_image,
}
# logger.info(payload)
try:
url = requests.put(
f'http://127.0.0.1:8000/update/{EmployeeCode}', json=payload,
)
url.status_code
# logger.info(url.json())

return redirect('/')

except requests.exceptions.RequestException as e:
print(f'Request failed: {e}')
response = requests.get(f'http://127.0.0.1:8000/read/{EmployeeCode}')
# logger.info(response.status_code)
# logger.info(response.json())
if response.status_code == 200:
employee_data = response.json()
return render_template('edit.html', employee_data=employee_data)
else:
return f'Error {response.status_code}: Failed to retrieve employee data.'




# To delete employee details
@flk_blueprint.route('/Delete/<int:EmployeeCode>', methods=['DELETE', 'GET'])
def Delete(EmployeeCode):
if not isinstance(EmployeeCode, int):
return jsonify({'message': 'Employee code should be an integer'}, 400)
response = requests.delete(f'http://127.0.0.1:8000/delete/{EmployeeCode}')
jsonify(response.json())

return redirect('/DisplayingEmployees')

return redirect("/DisplayingEmployees")


Loading
Loading