Update app.py
Browse files
app.py
CHANGED
@@ -1,251 +1,136 @@
|
|
1 |
import streamlit as st
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
-
import
|
5 |
-
import sqlite3
|
6 |
-
from PIL import Image
|
7 |
from keras.models import load_model
|
8 |
-
from
|
|
|
|
|
9 |
import tempfile
|
10 |
|
11 |
-
#
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
hf_token = os.getenv("upload")
|
20 |
-
|
21 |
-
# Ensure the Hugging Face token is available
|
22 |
-
if not hf_token:
|
23 |
-
st.error("Hugging Face token not found. Please set the environment variable.")
|
24 |
-
st.stop()
|
25 |
-
|
26 |
-
# Initialize Hugging Face API
|
27 |
-
api = HfApi()
|
28 |
-
|
29 |
-
# Create Hugging Face repository
|
30 |
-
def create_hugging_face_repo():
|
31 |
-
try:
|
32 |
-
api.create_repo(repo_id=REPO_ID, repo_type="space", space_sdk="streamlit", token=hf_token, exist_ok=True)
|
33 |
-
st.success(f"Repository '{REPO_NAME}' is ready on Hugging Face!")
|
34 |
-
except Exception as e:
|
35 |
-
st.error(f"Error creating Hugging Face repository: {e}")
|
36 |
-
|
37 |
-
# Load the emotion model once, using caching
|
38 |
@st.cache_resource
|
39 |
def load_emotion_model():
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
46 |
|
47 |
-
emotion_model = load_emotion_model()
|
48 |
-
|
49 |
-
# Initialize the face recognizer
|
50 |
-
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
|
51 |
-
|
52 |
-
# Database functions
|
53 |
-
def initialize_database():
|
54 |
-
"""
|
55 |
-
Initializes the SQLite database by creating a table to store student data.
|
56 |
-
"""
|
57 |
-
with sqlite3.connect(DATABASE) as conn:
|
58 |
-
conn.execute("""
|
59 |
-
CREATE TABLE IF NOT EXISTS students (
|
60 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
61 |
-
name TEXT NOT NULL,
|
62 |
-
roll_no TEXT NOT NULL UNIQUE,
|
63 |
-
image_path TEXT NOT NULL,
|
64 |
-
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
65 |
-
)
|
66 |
-
""")
|
67 |
-
conn.commit()
|
68 |
-
|
69 |
-
# Initialize the database
|
70 |
-
initialize_database()
|
71 |
-
|
72 |
-
def save_to_database(name, roll_no, image_path):
|
73 |
-
"""
|
74 |
-
Saves student data (name, roll number, image path) to the SQLite database.
|
75 |
-
Ensures roll number is unique.
|
76 |
-
"""
|
77 |
-
with sqlite3.connect(DATABASE) as conn:
|
78 |
-
try:
|
79 |
-
conn.execute("""
|
80 |
-
INSERT INTO students (name, roll_no, image_path)
|
81 |
-
VALUES (?, ?, ?)
|
82 |
-
""", (name, roll_no, image_path))
|
83 |
-
conn.commit()
|
84 |
-
st.success("Data saved successfully!")
|
85 |
-
except sqlite3.IntegrityError:
|
86 |
-
st.error("Roll number already exists!")
|
87 |
-
|
88 |
-
def save_image_to_hugging_face(image, name, roll_no):
|
89 |
-
"""
|
90 |
-
Saves the captured image locally in the 'known_faces' directory and uploads it to Hugging Face.
|
91 |
-
"""
|
92 |
-
if not os.path.exists(KNOWN_FACES_DIR):
|
93 |
-
os.makedirs(KNOWN_FACES_DIR)
|
94 |
-
|
95 |
-
filename = f"{name}_{roll_no}.jpg"
|
96 |
-
local_path = os.path.join(KNOWN_FACES_DIR, filename)
|
97 |
-
|
98 |
-
# Saving the image to the correct directory
|
99 |
-
image.save(local_path)
|
100 |
-
|
101 |
-
try:
|
102 |
-
api.upload_file(
|
103 |
-
path_or_fileobj=local_path,
|
104 |
-
path_in_repo=filename,
|
105 |
-
repo_id=REPO_ID,
|
106 |
-
repo_type="space",
|
107 |
-
token=hf_token
|
108 |
-
)
|
109 |
-
st.success(f"Image uploaded to Hugging Face: {filename}")
|
110 |
-
except Exception as e:
|
111 |
-
st.error(f"Error uploading image to Hugging Face: {e}")
|
112 |
-
|
113 |
-
return local_path
|
114 |
-
|
115 |
-
# Load known faces
|
116 |
-
def load_known_faces():
|
117 |
-
"""
|
118 |
-
Loads known faces from the 'known_faces' directory and trains the recognizer.
|
119 |
-
"""
|
120 |
-
known_faces = []
|
121 |
-
known_names = []
|
122 |
-
|
123 |
-
for image_name in os.listdir(KNOWN_FACES_DIR):
|
124 |
-
if image_name.endswith(('.jpg', '.jpeg', '.png')):
|
125 |
-
image_path = os.path.join(KNOWN_FACES_DIR, image_name)
|
126 |
-
image = cv2.imread(image_path)
|
127 |
-
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
128 |
-
faces = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml').detectMultiScale(
|
129 |
-
gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)
|
130 |
-
)
|
131 |
-
|
132 |
-
for (x, y, w, h) in faces:
|
133 |
-
roi_gray = gray[y:y+h, x:x+w]
|
134 |
-
known_faces.append(roi_gray)
|
135 |
-
known_names.append(image_name.split('.')[0]) # Assuming file name is the person's name
|
136 |
-
|
137 |
-
if known_faces:
|
138 |
-
face_recognizer.train(known_faces, np.array([i for i in range(len(known_faces))]))
|
139 |
-
else:
|
140 |
-
st.warning("No known faces found for training.")
|
141 |
-
|
142 |
-
return known_names
|
143 |
-
|
144 |
-
# Load known faces at the start
|
145 |
-
known_names = load_known_faces()
|
146 |
-
|
147 |
-
# Process frame for both emotion detection and face recognition
|
148 |
def process_frame(frame):
|
|
|
149 |
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
150 |
-
faces =
|
151 |
-
gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)
|
152 |
-
)
|
153 |
-
|
154 |
-
result_text = ""
|
155 |
for (x, y, w, h) in faces:
|
156 |
roi_gray = gray_frame[y:y+h, x:x+w]
|
157 |
roi_color = frame[y:y+h, x:x+w]
|
158 |
-
face_roi = cv2.resize(roi_color, (
|
159 |
-
face_roi =
|
160 |
-
face_roi =
|
161 |
-
|
162 |
-
|
163 |
-
emotion = EMOTION_LABELS[np.argmax(predictions[0])]
|
164 |
-
|
165 |
-
label, confidence = face_recognizer.predict(roi_gray)
|
166 |
-
name = "Unknown"
|
167 |
-
if confidence < 100:
|
168 |
-
name = known_names[label]
|
169 |
-
|
170 |
-
result_text = f"{name} is feeling {emotion}"
|
171 |
|
|
|
172 |
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
|
173 |
-
cv2.putText(frame,
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
frame
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
+
import time
|
|
|
|
|
5 |
from keras.models import load_model
|
6 |
+
from PIL import Image
|
7 |
+
from huggingface_hub import HfApi, Repository
|
8 |
+
import os
|
9 |
import tempfile
|
10 |
|
11 |
+
# Page configuration
|
12 |
+
st.set_page_config(page_title="Emotion Detection", layout="centered")
|
13 |
+
|
14 |
+
# Title and Subtitle
|
15 |
+
st.markdown("<h1 style='text-align: center;'>Emotion Detection</h1>", unsafe_allow_html=True)
|
16 |
+
st.markdown("<h3 style='text-align: center;'>angry, fear, happy, neutral, sad, surprise</h3>", unsafe_allow_html=True)
|
17 |
+
|
18 |
+
# Load Model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
@st.cache_resource
|
20 |
def load_emotion_model():
|
21 |
+
model = load_model('CNN_Model_acc_75.h5')
|
22 |
+
return model
|
23 |
+
|
24 |
+
start_time = time.time()
|
25 |
+
model = load_emotion_model()
|
26 |
+
st.write(f"Model loaded in {time.time() - start_time:.2f} seconds.")
|
27 |
+
|
28 |
+
# Emotion labels and constants
|
29 |
+
emotion_labels = ['angry', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
30 |
+
img_shape = 48
|
31 |
+
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
def process_frame(frame):
|
34 |
+
"""Detect faces and predict emotions."""
|
35 |
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
36 |
+
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
|
|
|
|
|
|
|
|
|
37 |
for (x, y, w, h) in faces:
|
38 |
roi_gray = gray_frame[y:y+h, x:x+w]
|
39 |
roi_color = frame[y:y+h, x:x+w]
|
40 |
+
face_roi = cv2.resize(roi_color, (img_shape, img_shape))
|
41 |
+
face_roi = np.expand_dims(face_roi, axis=0)
|
42 |
+
face_roi = face_roi / float(img_shape)
|
43 |
+
predictions = model.predict(face_roi)
|
44 |
+
emotion = emotion_labels[np.argmax(predictions[0])]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
+
# Draw rectangle and emotion label
|
47 |
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
|
48 |
+
cv2.putText(frame, emotion, (x, y + h + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
|
49 |
+
return frame
|
50 |
+
|
51 |
+
# Sidebar for input selection
|
52 |
+
st.sidebar.title("Choose Input Source")
|
53 |
+
upload_choice = st.sidebar.radio("Select:", ["Camera", "Upload Video", "Upload Image", "Upload to Hugging Face"])
|
54 |
+
|
55 |
+
if upload_choice == "Camera":
|
56 |
+
# Use Streamlit's camera input widget
|
57 |
+
st.sidebar.info("Click a picture to analyze emotion.")
|
58 |
+
picture = st.camera_input("Take a picture")
|
59 |
+
if picture:
|
60 |
+
image = Image.open(picture)
|
61 |
+
frame = np.array(image)
|
62 |
+
frame = process_frame(frame)
|
63 |
+
st.image(frame, caption="Processed Image", use_column_width=True)
|
64 |
+
|
65 |
+
elif upload_choice == "Upload Video":
|
66 |
+
uploaded_video = st.file_uploader("Upload Video", type=["mp4", "mov", "avi", "mkv", "webm"])
|
67 |
+
if uploaded_video:
|
68 |
+
with tempfile.NamedTemporaryFile(delete=False) as tfile:
|
69 |
+
tfile.write(uploaded_video.read())
|
70 |
+
video_source = cv2.VideoCapture(tfile.name)
|
71 |
+
frame_placeholder = st.empty()
|
72 |
+
while video_source.isOpened():
|
73 |
+
ret, frame = video_source.read()
|
74 |
+
if not ret:
|
75 |
+
break
|
76 |
+
frame = process_frame(frame)
|
77 |
+
frame_placeholder.image(frame, channels="BGR", use_column_width=True)
|
78 |
+
video_source.release()
|
79 |
+
|
80 |
+
elif upload_choice == "Upload Image":
|
81 |
+
uploaded_image = st.file_uploader("Upload Image", type=["png", "jpg", "jpeg"])
|
82 |
+
if uploaded_image:
|
83 |
+
image = Image.open(uploaded_image)
|
84 |
+
frame = np.array(image)
|
85 |
+
frame = process_frame(frame)
|
86 |
+
st.image(frame, caption="Processed Image", use_column_width=True)
|
87 |
+
|
88 |
+
elif upload_choice == "Upload to Hugging Face":
|
89 |
+
st.sidebar.info("Upload images to the 'known_faces' directory in the Hugging Face repository.")
|
90 |
+
|
91 |
+
# Configure Hugging Face Repository
|
92 |
+
REPO_NAME = "face_and_emotion_detection"
|
93 |
+
REPO_ID = "LovnishVerma/" + REPO_NAME
|
94 |
+
hf_token = os.getenv("upload") # Set your Hugging Face token as an environment variable
|
95 |
+
|
96 |
+
if not hf_token:
|
97 |
+
st.error("Hugging Face token not found. Please set it as an environment variable named 'HF_TOKEN'.")
|
98 |
+
st.stop()
|
99 |
+
|
100 |
+
# Initialize Hugging Face API
|
101 |
+
api = HfApi()
|
102 |
+
|
103 |
+
def create_hugging_face_repo():
|
104 |
+
"""Create or verify the Hugging Face repository."""
|
105 |
+
try:
|
106 |
+
api.create_repo(repo_id=REPO_ID, repo_type="dataset", token=hf_token, exist_ok=True)
|
107 |
+
st.success(f"Repository '{REPO_NAME}' is ready on Hugging Face!")
|
108 |
+
except Exception as e:
|
109 |
+
st.error(f"Error creating Hugging Face repository: {e}")
|
110 |
+
|
111 |
+
def upload_to_hugging_face(file):
|
112 |
+
"""Upload a file to the Hugging Face repository."""
|
113 |
+
try:
|
114 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
|
115 |
+
temp_file.write(file.read())
|
116 |
+
temp_file_path = temp_file.name
|
117 |
+
|
118 |
+
api.upload_file(
|
119 |
+
path_or_fileobj=temp_file_path,
|
120 |
+
path_in_repo=f"known_faces/{os.path.basename(temp_file_path)}",
|
121 |
+
repo_id=REPO_ID,
|
122 |
+
token=hf_token,
|
123 |
+
)
|
124 |
+
st.success("File uploaded successfully to Hugging Face!")
|
125 |
+
except Exception as e:
|
126 |
+
st.error(f"Error uploading file to Hugging Face: {e}")
|
127 |
+
|
128 |
+
# Create the repository if it doesn't exist
|
129 |
+
create_hugging_face_repo()
|
130 |
+
|
131 |
+
# Upload image file
|
132 |
+
hf_uploaded_image = st.file_uploader("Upload Image to Hugging Face", type=["png", "jpg", "jpeg"])
|
133 |
+
if hf_uploaded_image:
|
134 |
+
upload_to_hugging_face(hf_uploaded_image)
|
135 |
+
|
136 |
+
st.sidebar.write("Emotion Labels: Angry, Fear, Happy, Neutral, Sad, Surprise")
|