LovnishVerma commited on
Commit
8fa939c
·
verified ·
1 Parent(s): 4e1645c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -235
app.py CHANGED
@@ -1,251 +1,136 @@
1
  import streamlit as st
2
  import cv2
3
  import numpy as np
4
- import os
5
- import sqlite3
6
- from PIL import Image
7
  from keras.models import load_model
8
- from huggingface_hub import HfApi
 
 
9
  import tempfile
10
 
11
- # Constants
12
- KNOWN_FACES_DIR = "known_faces"
13
- DATABASE = "students.db"
14
- EMOTION_MODEL_FILE = "CNN_Model_acc_75.h5"
15
- EMOTION_LABELS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
16
- REPO_NAME = "face_and_emotion_detection"
17
- REPO_ID = "LovnishVerma/" + REPO_NAME
18
- IMG_SHAPE = 48
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
- try:
41
- model = load_model(EMOTION_MODEL_FILE)
42
- return model
43
- except Exception as e:
44
- st.error(f"Error loading emotion model: {e}")
45
- st.stop()
 
 
 
 
 
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 = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml').detectMultiScale(
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, (IMG_SHAPE, IMG_SHAPE))
159
- face_roi = cv2.cvtColor(face_roi, cv2.COLOR_BGR2RGB)
160
- face_roi = np.expand_dims(face_roi, axis=0) / 255.0
161
-
162
- predictions = emotion_model.predict(face_roi)
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, result_text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
174
-
175
- return frame, result_text
176
-
177
- # Video feed handler
178
- def video_feed(video_source):
179
- frame_placeholder = st.empty()
180
- text_placeholder = st.empty()
181
-
182
- while True:
183
- ret, frame = video_source.read()
184
- if not ret:
185
- break
186
-
187
- frame, result_text = process_frame(frame)
188
-
189
- frame_placeholder.image(frame, channels="BGR", use_column_width=True)
190
- text_placeholder.markdown(f"<h3 style='text-align: center;'>{result_text}</h3>", unsafe_allow_html=True)
191
-
192
- # Streamlit interface
193
- def main():
194
- st.title("Student Registration with Face Recognition and Emotion Detection")
195
-
196
- # Step 1: Student Registration
197
- registration_mode = st.sidebar.radio("Choose an option", ["Register Student", "Face and Emotion Recognition"])
198
-
199
- if registration_mode == "Register Student":
200
- name = st.text_input("Enter your name")
201
- roll_no = st.text_input("Enter your roll number")
202
-
203
- capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
204
-
205
- if capture_mode == "Use Webcam":
206
- picture = st.camera_input("Take a picture")
207
- else:
208
- picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
209
-
210
- if st.button("Register"):
211
- if not name or not roll_no:
212
- st.error("Please fill in both name and roll number.")
213
- elif not picture:
214
- st.error("Please upload or capture an image.")
215
- else:
216
- try:
217
- image = Image.open(picture)
218
- image_path = save_image_to_hugging_face(image, name, roll_no)
219
- save_to_database(name, roll_no, image_path)
220
- except Exception as e:
221
- st.error(f"An error occurred: {e}")
222
-
223
- elif registration_mode == "Face and Emotion Recognition":
224
- upload_choice = st.radio("Choose input source", ["Upload Image", "Upload Video", "Camera"])
225
-
226
- if upload_choice == "Camera":
227
- image = st.camera_input("Take a picture")
228
- if image:
229
- frame = np.array(Image.open(image))
230
- frame, result_text = process_frame(frame)
231
- st.image(frame, caption='Processed Image', use_column_width=True)
232
- st.markdown(f"<h3 style='text-align: center;'>{result_text}</h3>", unsafe_allow_html=True)
233
- elif upload_choice == "Upload Image":
234
- uploaded_image = st.file_uploader("Upload Image", type=["png", "jpg", "jpeg", "gif"])
235
- if uploaded_image:
236
- image = Image.open(uploaded_image)
237
- frame = np.array(image)
238
- frame, result_text = process_frame(frame)
239
- st.image(frame, caption='Processed Image', use_column_width=True)
240
- st.markdown(f"<h3 style='text-align: center;'>{result_text}</h3>", unsafe_allow_html=True)
241
- elif upload_choice == "Upload Video":
242
- video_file = st.file_uploader("Upload Video", type=["mp4", "mov", "avi"])
243
- if video_file:
244
- temp_video_file = tempfile.NamedTemporaryFile(delete=False)
245
- temp_video_file.write(video_file.read())
246
- temp_video_file.close()
247
- video_source = cv2.VideoCapture(temp_video_file.name)
248
- video_feed(video_source)
249
-
250
- if __name__ == "__main__":
251
- main()
 
 
 
 
 
 
 
 
 
 
 
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")