Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,13 @@
|
|
1 |
import os
|
2 |
import sqlite3
|
3 |
-
|
4 |
import streamlit as st
|
5 |
from datetime import datetime
|
6 |
from PIL import Image
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# Constants
|
9 |
KNOWN_FACES_DIR = "known_faces" # Directory to save user images
|
@@ -12,12 +16,10 @@ DATABASE = "students.db" # SQLite database file to store student information
|
|
12 |
# Ensure the directory exists
|
13 |
os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
|
14 |
|
15 |
-
#
|
16 |
hf_token = os.getenv("upload") # The key must match the secret name set in Hugging Face
|
17 |
if not hf_token:
|
18 |
-
raise ValueError("Hugging Face token not found. Ensure it's set as a secret in
|
19 |
-
|
20 |
-
# Initialize Hugging Face API
|
21 |
api = HfApi()
|
22 |
|
23 |
# Repository Details on Hugging Face
|
@@ -25,19 +27,13 @@ REPO_NAME = "face_and_emotion_detection" # Replace with your Hugging Face repos
|
|
25 |
REPO_ID = "LovnishVerma/" + REPO_NAME # Replace "LovnishVerma" with your Hugging Face username
|
26 |
REPO_TYPE = "space" # 'space' type for Streamlit-based projects
|
27 |
|
28 |
-
#
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
except Exception as e:
|
33 |
-
st.error(f"Error creating repository: {e}")
|
34 |
|
35 |
-
#
|
36 |
def initialize_database():
|
37 |
-
"""
|
38 |
-
Initializes the SQLite database by creating a table to store student data
|
39 |
-
such as name, roll number, image path, and registration timestamp.
|
40 |
-
"""
|
41 |
conn = sqlite3.connect(DATABASE)
|
42 |
cursor = conn.cursor()
|
43 |
cursor.execute("""
|
@@ -52,16 +48,8 @@ def initialize_database():
|
|
52 |
conn.commit()
|
53 |
conn.close()
|
54 |
|
|
|
55 |
def save_to_database(name, roll_no, image_path):
|
56 |
-
"""
|
57 |
-
Saves the student's information (name, roll number, image path) to the SQLite database.
|
58 |
-
Ensures roll number is unique.
|
59 |
-
|
60 |
-
Args:
|
61 |
-
name (str): The name of the student.
|
62 |
-
roll_no (str): The roll number of the student.
|
63 |
-
image_path (str): Path to the stored image of the student.
|
64 |
-
"""
|
65 |
conn = sqlite3.connect(DATABASE)
|
66 |
cursor = conn.cursor()
|
67 |
try:
|
@@ -76,34 +64,19 @@ def save_to_database(name, roll_no, image_path):
|
|
76 |
finally:
|
77 |
conn.close()
|
78 |
|
|
|
79 |
def save_image_to_hugging_face(image, name, roll_no):
|
80 |
-
"""
|
81 |
-
Saves the captured image locally in the 'known_faces' directory and uploads it to Hugging Face.
|
82 |
-
The image is renamed using the format 'UserName_RollNo.jpg'.
|
83 |
-
|
84 |
-
Args:
|
85 |
-
image (PIL Image): The image object captured by the user.
|
86 |
-
name (str): The name of the student.
|
87 |
-
roll_no (str): The roll number of the student.
|
88 |
-
|
89 |
-
Returns:
|
90 |
-
str: The local path where the image is saved.
|
91 |
-
"""
|
92 |
-
# Rename the image using the format 'UserName_RollNo.jpg'
|
93 |
filename = f"{name}_{roll_no}.jpg"
|
94 |
local_path = os.path.join(KNOWN_FACES_DIR, filename)
|
95 |
-
|
96 |
-
# Save the image locally to the known_faces directory
|
97 |
image.save(local_path)
|
98 |
|
99 |
-
# Try uploading the image to Hugging Face
|
100 |
try:
|
101 |
api.upload_file(
|
102 |
path_or_fileobj=local_path,
|
103 |
path_in_repo=filename,
|
104 |
repo_id=REPO_ID,
|
105 |
repo_type=REPO_TYPE,
|
106 |
-
token=hf_token
|
107 |
)
|
108 |
st.success(f"Image uploaded to Hugging Face: {filename}")
|
109 |
except Exception as e:
|
@@ -111,31 +84,54 @@ def save_image_to_hugging_face(image, name, roll_no):
|
|
111 |
|
112 |
return local_path
|
113 |
|
114 |
-
#
|
115 |
-
|
|
|
|
|
116 |
|
117 |
-
|
118 |
-
|
|
|
119 |
|
120 |
-
|
121 |
-
|
122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
|
124 |
# Choose input method for the image (webcam or file upload)
|
125 |
capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
|
126 |
|
127 |
-
# Handle webcam capture or file upload
|
128 |
if capture_mode == "Use Webcam":
|
129 |
-
|
130 |
-
picture = st.camera_input("Take a picture") # Capture image using webcam
|
131 |
-
except Exception as e:
|
132 |
-
st.error(f"Error accessing webcam: {e}")
|
133 |
-
picture = None
|
134 |
-
|
135 |
elif capture_mode == "Upload File":
|
136 |
-
picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
|
|
|
|
|
|
|
|
|
137 |
|
138 |
-
#
|
139 |
if st.button("Register"):
|
140 |
if not name or not roll_no:
|
141 |
st.error("Please fill in both name and roll number.")
|
@@ -148,21 +144,38 @@ if st.button("Register"):
|
|
148 |
image = Image.open(picture)
|
149 |
elif capture_mode == "Upload File" and picture:
|
150 |
image = Image.open(picture)
|
151 |
-
|
152 |
# Save the image locally and upload it to Hugging Face
|
153 |
image_path = save_image_to_hugging_face(image, name, roll_no)
|
|
|
|
|
154 |
save_to_database(name, roll_no, image_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
except Exception as e:
|
156 |
st.error(f"An error occurred: {e}")
|
157 |
|
158 |
-
# Display registered
|
159 |
if st.checkbox("Show registered students"):
|
160 |
conn = sqlite3.connect(DATABASE)
|
161 |
cursor = conn.cursor()
|
162 |
cursor.execute("SELECT name, roll_no, image_path, timestamp FROM students")
|
163 |
rows = cursor.fetchall()
|
164 |
conn.close()
|
165 |
-
|
166 |
st.write("### Registered Students")
|
167 |
for row in rows:
|
168 |
name, roll_no, image_path, timestamp = row
|
|
|
1 |
import os
|
2 |
import sqlite3
|
3 |
+
import cv2
|
4 |
import streamlit as st
|
5 |
from datetime import datetime
|
6 |
from PIL import Image
|
7 |
+
import numpy as np
|
8 |
+
from keras.models import load_model
|
9 |
+
from huggingface_hub import HfApi
|
10 |
+
import time
|
11 |
|
12 |
# Constants
|
13 |
KNOWN_FACES_DIR = "known_faces" # Directory to save user images
|
|
|
16 |
# Ensure the directory exists
|
17 |
os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
|
18 |
|
19 |
+
# Initialize Hugging Face API
|
20 |
hf_token = os.getenv("upload") # The key must match the secret name set in Hugging Face
|
21 |
if not hf_token:
|
22 |
+
raise ValueError("Hugging Face token not found. Ensure it's set as a secret in Hugging Face")
|
|
|
|
|
23 |
api = HfApi()
|
24 |
|
25 |
# Repository Details on Hugging Face
|
|
|
27 |
REPO_ID = "LovnishVerma/" + REPO_NAME # Replace "LovnishVerma" with your Hugging Face username
|
28 |
REPO_TYPE = "space" # 'space' type for Streamlit-based projects
|
29 |
|
30 |
+
# Load emotion detection model
|
31 |
+
model = load_model('CNN_Model_acc_75.h5')
|
32 |
+
emotion_labels = ['angry', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
33 |
+
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
|
|
|
|
34 |
|
35 |
+
# Initialize the SQLite database
|
36 |
def initialize_database():
|
|
|
|
|
|
|
|
|
37 |
conn = sqlite3.connect(DATABASE)
|
38 |
cursor = conn.cursor()
|
39 |
cursor.execute("""
|
|
|
48 |
conn.commit()
|
49 |
conn.close()
|
50 |
|
51 |
+
# Save student information in the SQLite database
|
52 |
def save_to_database(name, roll_no, image_path):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
conn = sqlite3.connect(DATABASE)
|
54 |
cursor = conn.cursor()
|
55 |
try:
|
|
|
64 |
finally:
|
65 |
conn.close()
|
66 |
|
67 |
+
# Save the captured image to Hugging Face and return the local path
|
68 |
def save_image_to_hugging_face(image, name, roll_no):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
filename = f"{name}_{roll_no}.jpg"
|
70 |
local_path = os.path.join(KNOWN_FACES_DIR, filename)
|
|
|
|
|
71 |
image.save(local_path)
|
72 |
|
|
|
73 |
try:
|
74 |
api.upload_file(
|
75 |
path_or_fileobj=local_path,
|
76 |
path_in_repo=filename,
|
77 |
repo_id=REPO_ID,
|
78 |
repo_type=REPO_TYPE,
|
79 |
+
token=hf_token
|
80 |
)
|
81 |
st.success(f"Image uploaded to Hugging Face: {filename}")
|
82 |
except Exception as e:
|
|
|
84 |
|
85 |
return local_path
|
86 |
|
87 |
+
# Process each frame for emotion detection
|
88 |
+
def process_frame(frame):
|
89 |
+
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
90 |
+
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
|
91 |
|
92 |
+
for (x, y, w, h) in faces:
|
93 |
+
roi_gray = gray_frame[y:y+h, x:x+w]
|
94 |
+
roi_color = frame[y:y+h, x:x+w]
|
95 |
|
96 |
+
face_roi = cv2.resize(roi_color, (48, 48))
|
97 |
+
face_roi = np.expand_dims(face_roi, axis=0)
|
98 |
+
face_roi = face_roi / float(48)
|
99 |
+
predictions = model.predict(face_roi)
|
100 |
+
emotion = emotion_labels[np.argmax(predictions[0])]
|
101 |
+
|
102 |
+
# Display emotion text on face
|
103 |
+
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
|
104 |
+
cv2.putText(frame, emotion, (x, y+h), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
105 |
+
|
106 |
+
return frame
|
107 |
+
|
108 |
+
# Attendance recording
|
109 |
+
def record_attendance(name, roll_no, emotion):
|
110 |
+
conn = sqlite3.connect(DATABASE)
|
111 |
+
cursor = conn.cursor()
|
112 |
+
cursor.execute("""
|
113 |
+
INSERT INTO students (name, roll_no, image_path, timestamp)
|
114 |
+
VALUES (?, ?, ?, ?)
|
115 |
+
""", (name, roll_no, f"known_faces/{name}_{roll_no}.jpg", datetime.now()))
|
116 |
+
conn.commit()
|
117 |
+
conn.close()
|
118 |
+
|
119 |
+
# User Interface
|
120 |
+
st.title("Student Registration and Attendance")
|
121 |
|
122 |
# Choose input method for the image (webcam or file upload)
|
123 |
capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
|
124 |
|
|
|
125 |
if capture_mode == "Use Webcam":
|
126 |
+
picture = st.camera_input("Take a picture") # Capture image using webcam
|
|
|
|
|
|
|
|
|
|
|
127 |
elif capture_mode == "Upload File":
|
128 |
+
picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
|
129 |
+
|
130 |
+
# Input fields for student details
|
131 |
+
name = st.text_input("Enter your name")
|
132 |
+
roll_no = st.text_input("Enter your roll number")
|
133 |
|
134 |
+
# Handle image upload or webcam capture
|
135 |
if st.button("Register"):
|
136 |
if not name or not roll_no:
|
137 |
st.error("Please fill in both name and roll number.")
|
|
|
144 |
image = Image.open(picture)
|
145 |
elif capture_mode == "Upload File" and picture:
|
146 |
image = Image.open(picture)
|
147 |
+
|
148 |
# Save the image locally and upload it to Hugging Face
|
149 |
image_path = save_image_to_hugging_face(image, name, roll_no)
|
150 |
+
|
151 |
+
# Save user data to the database
|
152 |
save_to_database(name, roll_no, image_path)
|
153 |
+
|
154 |
+
# Detect faces and emotions
|
155 |
+
cap = cv2.VideoCapture(0)
|
156 |
+
while True:
|
157 |
+
ret, frame = cap.read()
|
158 |
+
if not ret:
|
159 |
+
break
|
160 |
+
|
161 |
+
frame = process_frame(frame)
|
162 |
+
st.image(frame, channels="BGR", use_column_width=True)
|
163 |
+
record_attendance(name, roll_no, emotion)
|
164 |
+
break # Stop after capturing one frame
|
165 |
+
|
166 |
+
cap.release()
|
167 |
+
|
168 |
except Exception as e:
|
169 |
st.error(f"An error occurred: {e}")
|
170 |
|
171 |
+
# Display registered students
|
172 |
if st.checkbox("Show registered students"):
|
173 |
conn = sqlite3.connect(DATABASE)
|
174 |
cursor = conn.cursor()
|
175 |
cursor.execute("SELECT name, roll_no, image_path, timestamp FROM students")
|
176 |
rows = cursor.fetchall()
|
177 |
conn.close()
|
178 |
+
|
179 |
st.write("### Registered Students")
|
180 |
for row in rows:
|
181 |
name, roll_no, image_path, timestamp = row
|