Update app.py
Browse files
app.py
CHANGED
@@ -1,322 +1,173 @@
|
|
1 |
import streamlit as st
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
-
import time
|
5 |
import os
|
6 |
-
|
|
|
7 |
from PIL import Image
|
8 |
-
import
|
9 |
from huggingface_hub import HfApi
|
10 |
-
|
11 |
-
# Larger title
|
12 |
-
st.markdown("<h1 style='text-align: center;'>Emotion Detection with Face Recognition</h1>", unsafe_allow_html=True)
|
13 |
-
|
14 |
-
# Smaller subtitle
|
15 |
-
st.markdown("<h3 style='text-align: center;'>angry, fear, happy, neutral, sad, surprise</h3>", unsafe_allow_html=True)
|
16 |
-
|
17 |
-
start = time.time()
|
18 |
|
19 |
# Constants
|
20 |
-
KNOWN_FACES_DIR = "known_faces"
|
21 |
-
DATABASE = "students.db"
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
-
#
|
24 |
-
|
25 |
|
26 |
-
#
|
27 |
-
hf_token = os.getenv("upload") # The key must match the secret name set in Hugging Face
|
28 |
if not hf_token:
|
29 |
-
|
|
|
30 |
|
31 |
-
# Initialize Hugging Face
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
-
#
|
35 |
-
|
36 |
-
|
37 |
-
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
-
|
40 |
-
try:
|
41 |
-
api.create_repo(repo_id=REPO_ID, repo_type=REPO_TYPE, space_sdk="streamlit", token=hf_token, exist_ok=True)
|
42 |
-
st.success(f"Repository '{REPO_NAME}' is ready on Hugging Face!")
|
43 |
-
except Exception as e:
|
44 |
-
st.error(f"Error creating repository: {e}")
|
45 |
|
|
|
|
|
46 |
|
47 |
-
# Database
|
48 |
def initialize_database():
|
49 |
"""
|
50 |
-
Initializes the SQLite database by creating a table to store student data
|
51 |
-
such as name, roll number, image path, and registration timestamp.
|
52 |
"""
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
)
|
63 |
-
|
64 |
-
conn.commit()
|
65 |
-
conn.close()
|
66 |
|
67 |
def save_to_database(name, roll_no, image_path):
|
68 |
"""
|
69 |
-
Saves
|
70 |
Ensures roll number is unique.
|
71 |
-
|
72 |
-
Args:
|
73 |
-
name (str): The name of the student.
|
74 |
-
roll_no (str): The roll number of the student.
|
75 |
-
image_path (str): Path to the stored image of the student.
|
76 |
"""
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
st.error("Roll number already exists!")
|
88 |
-
finally:
|
89 |
-
conn.close()
|
90 |
|
91 |
def save_image_to_hugging_face(image, name, roll_no):
|
92 |
"""
|
93 |
Saves the captured image locally in the 'known_faces' directory and uploads it to Hugging Face.
|
94 |
-
The image is renamed using the format 'UserName_RollNo.jpg'.
|
95 |
-
|
96 |
-
Args:
|
97 |
-
image (PIL Image): The image object captured by the user.
|
98 |
-
name (str): The name of the student.
|
99 |
-
roll_no (str): The roll number of the student.
|
100 |
-
|
101 |
-
Returns:
|
102 |
-
str: The local path where the image is saved.
|
103 |
"""
|
104 |
-
# Rename the image using the format 'UserName_RollNo.jpg'
|
105 |
filename = f"{name}_{roll_no}.jpg"
|
106 |
local_path = os.path.join(KNOWN_FACES_DIR, filename)
|
107 |
-
|
108 |
-
# Save the image locally to the known_faces directory
|
109 |
image.save(local_path)
|
110 |
|
111 |
-
# Try uploading the image to Hugging Face
|
112 |
try:
|
113 |
api.upload_file(
|
114 |
path_or_fileobj=local_path,
|
115 |
path_in_repo=filename,
|
116 |
repo_id=REPO_ID,
|
117 |
-
repo_type=
|
118 |
-
token=hf_token
|
119 |
)
|
120 |
st.success(f"Image uploaded to Hugging Face: {filename}")
|
121 |
except Exception as e:
|
122 |
st.error(f"Error uploading image to Hugging Face: {e}")
|
123 |
-
|
124 |
-
return local_path
|
125 |
-
|
126 |
-
# Initialize the database when the app starts
|
127 |
-
initialize_database()
|
128 |
-
|
129 |
-
# Streamlit user interface (UI)
|
130 |
-
st.title("Student Registration with Hugging Face Image Upload")
|
131 |
-
|
132 |
-
# Input fields for student details
|
133 |
-
name = st.text_input("Enter your name")
|
134 |
-
roll_no = st.text_input("Enter your roll number")
|
135 |
-
|
136 |
-
# Choose input method for the image (webcam or file upload)
|
137 |
-
capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
|
138 |
-
|
139 |
-
# Handle webcam capture or file upload
|
140 |
-
if capture_mode == "Use Webcam":
|
141 |
-
try:
|
142 |
-
picture = st.camera_input("Take a picture") # Capture image using webcam
|
143 |
-
except Exception as e:
|
144 |
-
st.error(f"Error accessing webcam: {e}")
|
145 |
-
picture = None
|
146 |
-
|
147 |
-
elif capture_mode == "Upload File":
|
148 |
-
picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"]) # Upload image from file system
|
149 |
-
|
150 |
-
# Save data and process image on button click
|
151 |
-
if st.button("Register"):
|
152 |
-
if not name or not roll_no:
|
153 |
-
st.error("Please fill in both name and roll number.")
|
154 |
-
elif not picture:
|
155 |
-
st.error("Please upload or capture an image.")
|
156 |
-
else:
|
157 |
-
try:
|
158 |
-
# Open the image based on capture mode
|
159 |
-
if capture_mode == "Use Webcam" and picture:
|
160 |
-
image = Image.open(picture)
|
161 |
-
elif capture_mode == "Upload File" and picture:
|
162 |
-
image = Image.open(picture)
|
163 |
-
|
164 |
-
# Save the image locally and upload it to Hugging Face
|
165 |
-
image_path = save_image_to_hugging_face(image, name, roll_no)
|
166 |
-
save_to_database(name, roll_no, image_path)
|
167 |
-
except Exception as e:
|
168 |
-
st.error(f"An error occurred: {e}")
|
169 |
-
|
170 |
-
# Display registered student data
|
171 |
-
if st.checkbox("Show registered students"):
|
172 |
-
conn = sqlite3.connect(DATABASE)
|
173 |
-
cursor = conn.cursor()
|
174 |
-
cursor.execute("SELECT name, roll_no, image_path, timestamp FROM students")
|
175 |
-
rows = cursor.fetchall()
|
176 |
-
conn.close()
|
177 |
|
178 |
-
|
179 |
-
for row in rows:
|
180 |
-
name, roll_no, image_path, timestamp = row
|
181 |
-
st.write(f"**Name:** {name}, **Roll No:** {roll_no}, **Timestamp:** {timestamp}")
|
182 |
-
st.image(image_path, caption=f"{name} ({roll_no})", use_column_width=True)
|
183 |
-
|
184 |
-
|
185 |
-
# Constants
|
186 |
-
DB_FILE = "students.db"
|
187 |
-
KNOWN_FACES_DIR = "known_faces"
|
188 |
-
EMOTION_MODEL_FILE = "CNN_Model_acc_75.h5"
|
189 |
-
EMOTION_LABELS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
|
190 |
-
|
191 |
-
# Hugging Face Repository Details
|
192 |
-
REPO_NAME = "face_and_emotion_detection"
|
193 |
-
REPO_ID = f"LovnishVerma/{REPO_NAME}" # Replace with your Hugging Face username and repository name
|
194 |
-
|
195 |
-
# Ensure Directories
|
196 |
-
os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
|
197 |
-
|
198 |
-
# Load Hugging Face Token
|
199 |
-
hf_token = os.getenv("upload")
|
200 |
-
if not hf_token:
|
201 |
-
st.error("Hugging Face token not found. Please set the environment variable.")
|
202 |
-
|
203 |
-
# Initialize Hugging Face API
|
204 |
-
api = HfApi()
|
205 |
-
try:
|
206 |
-
api.create_repo(repo_id=REPO_ID, repo_type="space", space_sdk="streamlit", token=hf_token, exist_ok=True)
|
207 |
-
st.success(f"Repository '{REPO_NAME}' is ready on Hugging Face!")
|
208 |
-
except Exception as e:
|
209 |
-
st.error(f"Error creating Hugging Face repository: {e}")
|
210 |
-
|
211 |
-
# Load Emotion Model
|
212 |
-
try:
|
213 |
-
emotion_model = load_model(EMOTION_MODEL_FILE)
|
214 |
-
except Exception as e:
|
215 |
-
st.error(f"Error loading emotion model: {e}")
|
216 |
-
|
217 |
-
# Database Functions
|
218 |
-
def create_table():
|
219 |
-
with sqlite3.connect(DB_FILE) as conn:
|
220 |
-
conn.execute("""CREATE TABLE IF NOT EXISTS students (
|
221 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
222 |
-
name TEXT NOT NULL,
|
223 |
-
roll_number TEXT NOT NULL UNIQUE,
|
224 |
-
image_path TEXT NOT NULL)""")
|
225 |
-
conn.commit()
|
226 |
-
|
227 |
-
def insert_student(name, roll_number, image_path):
|
228 |
-
try:
|
229 |
-
with sqlite3.connect(DB_FILE) as conn:
|
230 |
-
conn.execute("INSERT INTO students (name, roll_number, image_path) VALUES (?, ?, ?)",
|
231 |
-
(name, roll_number, image_path))
|
232 |
-
conn.commit()
|
233 |
-
except sqlite3.IntegrityError:
|
234 |
-
st.warning("Roll number already exists!")
|
235 |
-
|
236 |
-
def get_all_students():
|
237 |
-
with sqlite3.connect(DB_FILE) as conn:
|
238 |
-
cursor = conn.execute("SELECT * FROM students")
|
239 |
-
return cursor.fetchall()
|
240 |
-
|
241 |
-
# Load the emotion model
|
242 |
-
@st.cache_resource
|
243 |
-
def load_emotion_model():
|
244 |
-
model = load_model('CNN_Model_acc_75.h5') # Ensure this file is in your Space
|
245 |
-
return model
|
246 |
-
|
247 |
-
model = load_emotion_model()
|
248 |
-
print("time taken to load model: ", time.time() - start)
|
249 |
-
|
250 |
-
# Emotion labels
|
251 |
-
emotion_labels = ['angry', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
252 |
-
|
253 |
-
# Load known faces (from images in a folder)
|
254 |
-
known_faces = []
|
255 |
-
known_names = []
|
256 |
-
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
|
257 |
|
|
|
258 |
def load_known_faces():
|
259 |
-
|
260 |
-
|
|
|
|
|
|
|
|
|
|
|
261 |
if image_name.endswith(('.jpg', '.jpeg', '.png')):
|
262 |
-
image_path = os.path.join(
|
263 |
image = cv2.imread(image_path)
|
264 |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
265 |
-
|
266 |
-
|
267 |
-
|
|
|
268 |
for (x, y, w, h) in faces:
|
269 |
roi_gray = gray[y:y+h, x:x+w]
|
270 |
-
# We only need the face, so we crop it and store it for training
|
271 |
known_faces.append(roi_gray)
|
272 |
known_names.append(image_name.split('.')[0]) # Assuming file name is the person's name
|
273 |
-
|
274 |
-
|
275 |
-
|
|
|
|
|
276 |
|
277 |
load_known_faces()
|
278 |
|
279 |
-
#
|
280 |
-
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
281 |
-
img_shape = 48
|
282 |
-
|
283 |
def process_frame(frame):
|
284 |
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
285 |
-
faces =
|
286 |
-
|
287 |
-
|
288 |
|
|
|
289 |
for (x, y, w, h) in faces:
|
290 |
roi_gray = gray_frame[y:y+h, x:x+w]
|
291 |
roi_color = frame[y:y+h, x:x+w]
|
292 |
-
face_roi = cv2.resize(roi_color, (
|
293 |
-
face_roi = cv2.cvtColor(face_roi, cv2.COLOR_BGR2RGB)
|
294 |
-
face_roi = np.expand_dims(face_roi, axis=0)
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
emotion = emotion_labels[np.argmax(predictions[0])]
|
300 |
-
|
301 |
-
# Face recognition using LBPH
|
302 |
label, confidence = face_recognizer.predict(roi_gray)
|
303 |
name = "Unknown"
|
304 |
if confidence < 100:
|
305 |
name = known_names[label]
|
306 |
|
307 |
-
# Format the result text as "Name is feeling Emotion"
|
308 |
result_text = f"{name} is feeling {emotion}"
|
309 |
|
310 |
-
# Draw bounding box and label on the frame
|
311 |
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
|
312 |
cv2.putText(frame, result_text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
313 |
|
314 |
return frame, result_text
|
315 |
|
316 |
-
# Video feed
|
317 |
def video_feed(video_source):
|
318 |
-
frame_placeholder = st.empty()
|
319 |
-
text_placeholder = st.empty()
|
320 |
|
321 |
while True:
|
322 |
ret, frame = video_source.read()
|
@@ -325,42 +176,72 @@ def video_feed(video_source):
|
|
325 |
|
326 |
frame, result_text = process_frame(frame)
|
327 |
|
328 |
-
# Display the frame in the placeholder
|
329 |
frame_placeholder.image(frame, channels="BGR", use_column_width=True)
|
330 |
-
|
331 |
-
# Display the result text in the text placeholder
|
332 |
text_placeholder.markdown(f"<h3 style='text-align: center;'>{result_text}</h3>", unsafe_allow_html=True)
|
333 |
|
334 |
-
#
|
335 |
-
|
336 |
-
|
337 |
-
if upload_choice == "Camera":
|
338 |
-
# Use Streamlit's built-in camera input widget for capturing images from the webcam
|
339 |
-
image = st.camera_input("Take a picture")
|
340 |
-
|
341 |
-
if image is not None:
|
342 |
-
# Convert the image to a numpy array
|
343 |
-
frame = np.array(Image.open(image))
|
344 |
-
frame, result_text = process_frame(frame)
|
345 |
-
st.image(frame, caption='Processed Image', use_column_width=True)
|
346 |
-
st.markdown(f"<h3 style='text-align: center;'>{result_text}</h3>", unsafe_allow_html=True)
|
347 |
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
st.
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
364 |
video_feed(video_source)
|
365 |
|
366 |
-
|
|
|
|
1 |
import streamlit as st
|
2 |
import cv2
|
3 |
import numpy as np
|
|
|
4 |
import os
|
5 |
+
import sqlite3
|
6 |
+
import time
|
7 |
from PIL import Image
|
8 |
+
from keras.models import load_model
|
9 |
from huggingface_hub import HfApi
|
10 |
+
import tempfile
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
# Constants
|
13 |
+
KNOWN_FACES_DIR = "known_faces"
|
14 |
+
DATABASE = "students.db"
|
15 |
+
EMOTION_MODEL_FILE = "CNN_Model_acc_75.h5"
|
16 |
+
EMOTION_LABELS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
|
17 |
+
REPO_NAME = "face_and_emotion_detection"
|
18 |
+
REPO_ID = "LovnishVerma/" + REPO_NAME
|
19 |
+
IMG_SHAPE = 48
|
20 |
+
hf_token = os.getenv("upload")
|
21 |
|
22 |
+
# Initialize Hugging Face API
|
23 |
+
api = HfApi()
|
24 |
|
25 |
+
# Ensure the Hugging Face token is available
|
|
|
26 |
if not hf_token:
|
27 |
+
st.error("Hugging Face token not found. Please set the environment variable.")
|
28 |
+
st.stop()
|
29 |
|
30 |
+
# Initialize the Hugging Face repository
|
31 |
+
def create_hugging_face_repo():
|
32 |
+
try:
|
33 |
+
api.create_repo(repo_id=REPO_ID, repo_type="space", space_sdk="streamlit", token=hf_token, exist_ok=True)
|
34 |
+
st.success(f"Repository '{REPO_NAME}' is ready on Hugging Face!")
|
35 |
+
except Exception as e:
|
36 |
+
st.error(f"Error creating Hugging Face repository: {e}")
|
37 |
|
38 |
+
# Load the emotion model once, using caching
|
39 |
+
@st.cache_resource
|
40 |
+
def load_emotion_model():
|
41 |
+
try:
|
42 |
+
model = load_model(EMOTION_MODEL_FILE)
|
43 |
+
return model
|
44 |
+
except Exception as e:
|
45 |
+
st.error(f"Error loading emotion model: {e}")
|
46 |
+
st.stop()
|
47 |
|
48 |
+
emotion_model = load_emotion_model()
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
+
# Initialize the face recognizer
|
51 |
+
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
|
52 |
|
53 |
+
# Database functions
|
54 |
def initialize_database():
|
55 |
"""
|
56 |
+
Initializes the SQLite database by creating a table to store student data.
|
|
|
57 |
"""
|
58 |
+
with sqlite3.connect(DATABASE) as conn:
|
59 |
+
conn.execute("""
|
60 |
+
CREATE TABLE IF NOT EXISTS students (
|
61 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
62 |
+
name TEXT NOT NULL,
|
63 |
+
roll_no TEXT NOT NULL UNIQUE,
|
64 |
+
image_path TEXT NOT NULL,
|
65 |
+
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
66 |
+
)
|
67 |
+
""")
|
68 |
+
conn.commit()
|
|
|
|
|
69 |
|
70 |
def save_to_database(name, roll_no, image_path):
|
71 |
"""
|
72 |
+
Saves student data (name, roll number, image path) to the SQLite database.
|
73 |
Ensures roll number is unique.
|
|
|
|
|
|
|
|
|
|
|
74 |
"""
|
75 |
+
with sqlite3.connect(DATABASE) as conn:
|
76 |
+
try:
|
77 |
+
conn.execute("""
|
78 |
+
INSERT INTO students (name, roll_no, image_path)
|
79 |
+
VALUES (?, ?, ?)
|
80 |
+
""", (name, roll_no, image_path))
|
81 |
+
conn.commit()
|
82 |
+
st.success("Data saved successfully!")
|
83 |
+
except sqlite3.IntegrityError:
|
84 |
+
st.error("Roll number already exists!")
|
|
|
|
|
|
|
85 |
|
86 |
def save_image_to_hugging_face(image, name, roll_no):
|
87 |
"""
|
88 |
Saves the captured image locally in the 'known_faces' directory and uploads it to Hugging Face.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
"""
|
|
|
90 |
filename = f"{name}_{roll_no}.jpg"
|
91 |
local_path = os.path.join(KNOWN_FACES_DIR, filename)
|
|
|
|
|
92 |
image.save(local_path)
|
93 |
|
|
|
94 |
try:
|
95 |
api.upload_file(
|
96 |
path_or_fileobj=local_path,
|
97 |
path_in_repo=filename,
|
98 |
repo_id=REPO_ID,
|
99 |
+
repo_type="space",
|
100 |
+
token=hf_token
|
101 |
)
|
102 |
st.success(f"Image uploaded to Hugging Face: {filename}")
|
103 |
except Exception as e:
|
104 |
st.error(f"Error uploading image to Hugging Face: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
|
106 |
+
return local_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
|
108 |
+
# Load known faces
|
109 |
def load_known_faces():
|
110 |
+
"""
|
111 |
+
Loads known faces from the 'known_faces' directory and trains the recognizer.
|
112 |
+
"""
|
113 |
+
known_faces = []
|
114 |
+
known_names = []
|
115 |
+
|
116 |
+
for image_name in os.listdir(KNOWN_FACES_DIR):
|
117 |
if image_name.endswith(('.jpg', '.jpeg', '.png')):
|
118 |
+
image_path = os.path.join(KNOWN_FACES_DIR, image_name)
|
119 |
image = cv2.imread(image_path)
|
120 |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
121 |
+
faces = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml').detectMultiScale(
|
122 |
+
gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)
|
123 |
+
)
|
124 |
+
|
125 |
for (x, y, w, h) in faces:
|
126 |
roi_gray = gray[y:y+h, x:x+w]
|
|
|
127 |
known_faces.append(roi_gray)
|
128 |
known_names.append(image_name.split('.')[0]) # Assuming file name is the person's name
|
129 |
+
|
130 |
+
if known_faces:
|
131 |
+
face_recognizer.train(known_faces, np.array([i for i in range(len(known_faces))]))
|
132 |
+
else:
|
133 |
+
st.warning("No known faces found for training.")
|
134 |
|
135 |
load_known_faces()
|
136 |
|
137 |
+
# Process frame for both emotion detection and face recognition
|
|
|
|
|
|
|
138 |
def process_frame(frame):
|
139 |
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
140 |
+
faces = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml').detectMultiScale(
|
141 |
+
gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)
|
142 |
+
)
|
143 |
|
144 |
+
result_text = ""
|
145 |
for (x, y, w, h) in faces:
|
146 |
roi_gray = gray_frame[y:y+h, x:x+w]
|
147 |
roi_color = frame[y:y+h, x:x+w]
|
148 |
+
face_roi = cv2.resize(roi_color, (IMG_SHAPE, IMG_SHAPE))
|
149 |
+
face_roi = cv2.cvtColor(face_roi, cv2.COLOR_BGR2RGB)
|
150 |
+
face_roi = np.expand_dims(face_roi, axis=0) / 255.0
|
151 |
+
|
152 |
+
predictions = emotion_model.predict(face_roi)
|
153 |
+
emotion = EMOTION_LABELS[np.argmax(predictions[0])]
|
154 |
+
|
|
|
|
|
|
|
155 |
label, confidence = face_recognizer.predict(roi_gray)
|
156 |
name = "Unknown"
|
157 |
if confidence < 100:
|
158 |
name = known_names[label]
|
159 |
|
|
|
160 |
result_text = f"{name} is feeling {emotion}"
|
161 |
|
|
|
162 |
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
|
163 |
cv2.putText(frame, result_text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
164 |
|
165 |
return frame, result_text
|
166 |
|
167 |
+
# Video feed handler
|
168 |
def video_feed(video_source):
|
169 |
+
frame_placeholder = st.empty()
|
170 |
+
text_placeholder = st.empty()
|
171 |
|
172 |
while True:
|
173 |
ret, frame = video_source.read()
|
|
|
176 |
|
177 |
frame, result_text = process_frame(frame)
|
178 |
|
|
|
179 |
frame_placeholder.image(frame, channels="BGR", use_column_width=True)
|
|
|
|
|
180 |
text_placeholder.markdown(f"<h3 style='text-align: center;'>{result_text}</h3>", unsafe_allow_html=True)
|
181 |
|
182 |
+
# Streamlit interface
|
183 |
+
def main():
|
184 |
+
st.title("Student Registration with Face Recognition and Emotion Detection")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
|
186 |
+
name = st.text_input("Enter your name")
|
187 |
+
roll_no = st.text_input("Enter your roll number")
|
188 |
+
|
189 |
+
capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
|
190 |
+
|
191 |
+
if capture_mode == "Use Webcam":
|
192 |
+
picture = st.camera_input("Take a picture")
|
193 |
+
else:
|
194 |
+
picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
|
195 |
+
|
196 |
+
if st.button("Register"):
|
197 |
+
if not name or not roll_no:
|
198 |
+
st.error("Please fill in both name and roll number.")
|
199 |
+
elif not picture:
|
200 |
+
st.error("Please upload or capture an image.")
|
201 |
+
else:
|
202 |
+
try:
|
203 |
+
image = Image.open(picture)
|
204 |
+
image_path = save_image_to_hugging_face(image, name, roll_no)
|
205 |
+
save_to_database(name, roll_no, image_path)
|
206 |
+
except Exception as e:
|
207 |
+
st.error(f"An error occurred: {e}")
|
208 |
+
|
209 |
+
if st.checkbox("Show registered students"):
|
210 |
+
with sqlite3.connect(DATABASE) as conn:
|
211 |
+
cursor = conn.cursor()
|
212 |
+
cursor.execute("SELECT name, roll_no, image_path, timestamp FROM students")
|
213 |
+
rows = cursor.fetchall()
|
214 |
+
|
215 |
+
for row in rows:
|
216 |
+
name, roll_no, image_path, timestamp = row
|
217 |
+
st.write(f"**Name:** {name}, **Roll No:** {roll_no}, **Timestamp:** {timestamp}")
|
218 |
+
st.image(image_path, caption=f"{name} ({roll_no})", use_column_width=True)
|
219 |
+
|
220 |
+
upload_choice = st.sidebar.radio("Choose input source", ["Upload Image", "Upload Video", "Camera"])
|
221 |
+
|
222 |
+
if upload_choice == "Camera":
|
223 |
+
image = st.camera_input("Take a picture")
|
224 |
+
if image:
|
225 |
+
frame = np.array(Image.open(image))
|
226 |
+
frame, result_text = process_frame(frame)
|
227 |
+
st.image(frame, caption='Processed Image', use_column_width=True)
|
228 |
+
st.markdown(f"<h3 style='text-align: center;'>{result_text}</h3>", unsafe_allow_html=True)
|
229 |
+
elif upload_choice == "Upload Image":
|
230 |
+
uploaded_image = st.file_uploader("Upload Image", type=["png", "jpg", "jpeg", "gif"])
|
231 |
+
if uploaded_image:
|
232 |
+
image = Image.open(uploaded_image)
|
233 |
+
frame = np.array(image)
|
234 |
+
frame, result_text = process_frame(frame)
|
235 |
+
st.image(frame, caption='Processed Image', use_column_width=True)
|
236 |
+
st.markdown(f"<h3 style='text-align: center;'>{result_text}</h3>", unsafe_allow_html=True)
|
237 |
+
elif upload_choice == "Upload Video":
|
238 |
+
video_file = st.file_uploader("Upload Video", type=["mp4", "mov", "avi"])
|
239 |
+
if video_file:
|
240 |
+
temp_video_file = tempfile.NamedTemporaryFile(delete=False)
|
241 |
+
temp_video_file.write(video_file.read())
|
242 |
+
temp_video_file.close()
|
243 |
+
video_source = cv2.VideoCapture(temp_video_file.name)
|
244 |
video_feed(video_source)
|
245 |
|
246 |
+
if __name__ == "__main__":
|
247 |
+
main()
|