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 Aug 6, 2024
1 parent ae85198 commit c76981c
Show file tree
Hide file tree
Showing 17 changed files with 271 additions and 227 deletions.
1 change: 0 additions & 1 deletion .github/workflows/changelog-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,3 @@ jobs:
# release_name: Release ${{ github.run_number }}
# draft: false
# prerelease: false

2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,4 @@ __pyc
FaceRec/static/Images/uploads/*
Images/dbImages/*
Images/Faces/*
Images/
Images/
54 changes: 30 additions & 24 deletions API/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
from datetime import datetime
from io import BytesIO
from typing import List
from tensorflow.keras.models import load_model

import numpy as np
from bson import ObjectId
from deepface import DeepFace
from dotenv import load_dotenv
Expand All @@ -17,11 +18,11 @@
from fastapi import HTTPException
from fastapi import Response
from fastapi import UploadFile
from keras.preprocessing import image
from matplotlib import pyplot as plt
from PIL import Image
from pydantic import BaseModel
import numpy as np
from keras.preprocessing import image
from tensorflow.keras.models import load_model

from API.database import Database
from API.utils import init_logging_config
Expand All @@ -41,6 +42,8 @@
collection3 = 'VectorDB'

# Models for the data to be sent and received by the server


class Employee(BaseModel):
EmployeeCode: int
Name: str
Expand All @@ -55,42 +58,44 @@ class UpdateEmployee(BaseModel):
Department: str
Images: list[str]


def load_and_preprocess_image(img_path, target_size=(160, 160)):

img = image.load_img(img_path, target_size=target_size)
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array /= 255.0
return img_array


def calculate_embeddings(image_filename):

"""
Calculate embeddings for the provided image.
Args:
image_filename (str): The path to the image file.
Returns:
list: A list of embeddings for the image.
"""

face_image_data = DeepFace.extract_faces(
image_filename, enforce_detection=False,
)
new_image_path = f'Images/Faces/tmp.jpg'

if face_image_data[0]['face'] is not None:
plt.imsave(new_image_path, face_image_data[0]['face'])

img_array = load_and_preprocess_image(new_image_path)
model=load_model('Model/embedding_trial3.h5')
model = load_model('Model/embedding_trial3.h5')
embedding = model.predict(img_array)[0]
embedding_list = embedding.tolist()
logging.info(f'Embedding created')

return embedding_list


@router.post('/recalculate_embeddings')
async def recalculate_embeddings():
"""
Expand All @@ -107,15 +112,15 @@ async def recalculate_embeddings():
for employee in employees_mongo:
print(employee, type(employee))
embeddings = []

# In the initial version, the images were stored in the 'Image' field
if 'Images' in employee:
images = employee['Images']
else:
images = [employee['Image']]

for encoded_image in images:

pil_image = Image.open(BytesIO(base64.b64decode(encoded_image)))
image_filename = f'{employee["Name"]}.png'
pil_image.save(image_filename)
Expand Down Expand Up @@ -172,7 +177,7 @@ async def create_new_faceEntry(Employee: Employee):
# embedding = DeepFace.represent(
# image_filename, model_name='Facenet512', detector_backend='mtcnn',
# )

embeddings.append(calculate_embeddings(image_filename))
# os.remove(image_filename)

Expand Down Expand Up @@ -305,11 +310,11 @@ async def update_employees(EmployeeCode: int, Employee: UpdateEmployee):
image_filename = f'{Employee.Name}.png'
pil_image.save(image_filename)
logging.debug(f'Image saved {Employee.Name}')

# embedding = DeepFace.represent(
# image_filename, model_name='Facenet', detector_backend='mtcnn',
# )

embeddings.append(calculate_embeddings(image_filename))
# os.remove(image_filename)

Expand Down Expand Up @@ -382,28 +387,29 @@ async def recognize_face(Face: UploadFile = File(...)):
logging.info('Recognizing Face')
try:
# Code to calculate embeddings via Original Facenet model

img_data = await Face.read()
image_filename = 'temp.png'
with open(image_filename, 'wb') as f:
f.write(img_data)
# embedding = DeepFace.represent(
# img_path='temp.png', model_name='Facenet512', detector_backend='mtcnn',
# )

# Code to calculate embeddings via Finetuned Facenet model
face_image_data = DeepFace.extract_faces(
image_filename, detector_backend='mtcnn', enforce_detection=False,
)

if face_image_data and face_image_data[0]['face'] is not None:

plt.imsave(f'Images/Faces/tmp.jpg', face_image_data[0]['face'])
face_image_path = f'Images/Faces/tmp.jpg'
img_array = load_and_preprocess_image(face_image_path)

model = load_model('Model/embedding_trial3.h5')
embedding_list = model.predict(img_array)[0] # Get the first prediction
embedding_list = model.predict(
img_array)[0] # Get the first prediction
print(embedding_list, type(embedding_list))
embedding = embedding_list.tolist()
result = client2.vector_search(collection3, embedding)
Expand Down
121 changes: 64 additions & 57 deletions FaceRec/app/main/Edit.py
Original file line number Diff line number Diff line change
@@ -1,87 +1,94 @@
from __future__ import annotations

import base64
import io
import json
import os

import cv2
import requests
from flask import Blueprint
from flask import redirect
from flask import render_template
from flask import request
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",
'Edit_blueprint',
__name__,
template_folder="../../templates/",
static_folder="../../static/",
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)
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"
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")
@Edit_blueprint.route('/video_feed')
def video_feed():
return flask_response(
display_live_video(), mimetype="multipart/x-mixed-replace;boundary=frame"
display_live_video(), mimetype='multipart/x-mixed-replace;boundary=frame',
)


# Route for capturing image from video
@Edit_blueprint.route("/capture", methods=["GET", "POST"])
@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", "")
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")
_, 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"])
@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:
with open(Config.image_data_file) as file:
image_data = json.load(file)
encoded_image = image_data.get("base64_image", "")
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)
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)
os.path.join(Config.upload_image_path[0], x),
),
reverse=True,
)
Expand All @@ -91,42 +98,42 @@ def display_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"])
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:
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", "")
encoded_image = image_data.get('base64_image', '')
payload = {
"Name": Name,
"gender": gender,
"Department": Department,
"Image": encoded_image,
'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
f"http://127.0.0.1:8000/update/{EmployeeCode}", json=payload,
)
url.status_code
# logger.info(url.json())
return redirect("/")

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)
return render_template('edit.html', employee_data=employee_data)
else:
return f"Error {response.status_code}: Failed to retrieve employee data."

Loading

0 comments on commit c76981c

Please sign in to comment.