Vikas01's picture
Update app.py
f58a881
raw
history blame
6.74 kB
from flask import *
from PIL import Image
import face_recognition
import cv2
import numpy as np
import csv
from datetime import datetime
############################################
# import matplotlib.pyplot as plt
# import pylab # this allows you to control figure size
# pylab.rcParams['figure.figsize'] = (10.0, 8.0) # this controls figure size in the notebook
# import io
# import streamlit as st
# bytes_data=None
from flask_socketio import SocketIO,emit
import base64
##################################################3
# import gradio as gr
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socket = SocketIO(app,async_mode="eventlet")
def base64_to_image(base64_string):
# Extract the base64 encoded binary data from the input string
base64_data = base64_string.split(",")[1]
# Decode the base64 data to bytes
image_bytes = base64.b64decode(base64_data)
# Convert the bytes to numpy array
image_array = np.frombuffer(image_bytes, dtype=np.uint8)
# Decode the numpy array as an image using OpenCV
image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
return image
@socket.on("connect")
def test_connect():
print("Connected")
emit("my response", {"data": "Connected"})
@socket.on("image")
def receive_image(image):
# Decode the base64-encoded image data
image = base64_to_image(image)
image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)
# emit("processed_image", image)
# Make the image a numpy array and reshape it to the models input shape.
image = np.asarray(image, dtype=np.float32).reshape(1, 224, 224, 3)
image = (image / 127.5) - 1
# Predicts the model
prediction = model.predict(image)
index = np.argmax(prediction)
class_name = class_names[index]
confidence_score = prediction[0][index]
emit("result",{"name":str(class_name),"score":str(confidence_score)})
# flag1 = True
# @app.route('/at')
# def testme():
# global flag1
# # return "i am in testme"
# while flag1 is True:
# img_file_buffer=st.camera_input("Take a picture")
# if img_file_buffer is not None:
# test_image = Image.open(img_file_buffer)
# st.image(test_image, use_column_width=True)
# if bytes_data is None:
# flag1 = False
# st.stop()
# def attend():
# # Face recognition variables
# known_faces_names = ["Sarwan Sir", "Vikas","Lalit","Jasmeen","Anita Ma'am"]
# known_face_encodings = []
# # Load known face encodings
# sir_image = face_recognition.load_image_file("photos/sir.jpeg")
# sir_encoding = face_recognition.face_encodings(sir_image)[0]
# vikas_image = face_recognition.load_image_file("photos/vikas.jpg")
# vikas_encoding = face_recognition.face_encodings(vikas_image)[0]
# lalit_image = face_recognition.load_image_file("photos/lalit.jpg")
# lalit_encoding = face_recognition.face_encodings(lalit_image)[0]
# jasmine_image = face_recognition.load_image_file("photos/jasmine.jpg")
# jasmine_encoding = face_recognition.face_encodings(jasmine_image)[0]
# maam_image = face_recognition.load_image_file("photos/maam.png")
# maam_encoding = face_recognition.face_encodings(maam_image)[0]
# known_face_encodings = [sir_encoding, vikas_encoding,lalit_encoding,jasmine_encoding,maam_encoding]
# students = known_faces_names.copy()
# face_locations = []
# face_encodings = []
# face_names = []
# now = datetime.now()
# current_date = now.strftime("%Y-%m-%d")
# csv_file = open(f"{current_date}.csv", "a+", newline="")
# csv_writer = csv.writer(csv_file)
# # Function to run face recognition
# def run_face_recognition():
# video_capture = cv2.VideoCapture(0)
# s = True
# existing_names = set(row[0] for row in csv.reader(csv_file)) # Collect existing names from the CSV file
# while s:
# _, frame = video_capture.read()
# small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# rgb_small_frame = small_frame[:, :, ::-1]
# face_locations = face_recognition.face_locations(rgb_small_frame)
# face_encodings = face_recognition.face_encodings(small_frame, face_locations)
# face_names = []
# for face_encoding in face_encodings:
# matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
# name = ""
# face_distance = face_recognition.face_distance(known_face_encodings, face_encoding)
# best_match_index = np.argmin(face_distance)
# if matches[best_match_index]:
# name = known_faces_names[best_match_index]
# face_names.append(name)
# for name in face_names:
# if name in known_faces_names and name in students and name not in existing_names:
# students.remove(name)
# print(students)
# print(f"Attendance recorded for {name}")
# current_time = now.strftime("%H-%M-%S")
# csv_writer.writerow([name, current_time, "Present"])
# existing_names.add(name) # Add the name to the set of existing names
# s = False # Set s to False to exit the loop after recording attendance
# break # Break the loop once attendance has been recorded for a name
# cv2.imshow("Attendance System", frame)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
# video_capture.release()
# cv2.destroyAllWindows()
# csv_file.close()
# # Call the function to run face recognition
# run_face_recognition()
# return redirect(url_for('show_table'))
###########################################################################
@app.route('/table')
def show_table():
# Get the current date
current_date = datetime.now().strftime("%Y-%m-%d")
# Read the CSV file to get attendance data
attendance=[]
try:
with open(f"{current_date}.csv", newline="") as csv_file:
csv_reader = csv.reader(csv_file)
attendance = list(csv_reader)
except FileNotFoundError:
pass
# Render the table.html template and pass the attendance data
return render_template('attendance.html', attendance=attendance)
@app.route("/")
def home():
return render_template('index.html')
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860)