LovnishVerma commited on
Commit
65b65aa
·
verified ·
1 Parent(s): 68a75d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -80
app.py CHANGED
@@ -4,90 +4,79 @@ import os
4
  import numpy as np
5
  from keras.models import load_model
6
  from PIL import Image
7
- from huggingface_hub import HfApi
8
  from datetime import datetime
9
 
10
  # Constants
11
- KNOWN_FACES_DIR = "known_faces" # Directory to save user images
 
12
  EMOTION_MODEL_FILE = "CNN_Model_acc_75.h5"
13
  EMOTION_LABELS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
14
- REPO_NAME = "face_and_emotion_detection"
15
- REPO_ID = f"LovnishVerma/{REPO_NAME}"
16
 
17
- # Ensure the directories exist
18
- os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
19
-
20
- # Initialize Hugging Face API
21
- hf_token = os.getenv("upload") # Replace with your actual Hugging Face token
22
- api = HfApi()
23
-
24
- # Load emotion detection model
25
  try:
26
  emotion_model = load_model(EMOTION_MODEL_FILE)
27
  except Exception as e:
28
  st.error(f"Error loading emotion model: {e}")
29
  st.stop()
30
 
31
- # Face and Emotion Detection Function
32
- def detect_faces_and_emotions(image):
33
- """Detect faces and emotions in the image"""
34
- gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
35
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
36
- faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- emotion_label = None
39
- for (x, y, w, h) in faces:
40
- face = gray_image[y:y+h, x:x+w]
41
- resized_face = cv2.resize(face, (48, 48)) # Resize face to 48x48
42
- rgb_face = cv2.cvtColor(resized_face, cv2.COLOR_GRAY2RGB)
43
- normalized_face = rgb_face / 255.0
44
- reshaped_face = np.reshape(normalized_face, (1, 48, 48, 3))
45
 
46
- # Predict the emotion
47
- emotion_prediction = emotion_model.predict(reshaped_face)
48
- emotion_label = np.argmax(emotion_prediction)
 
 
49
 
50
- return faces, EMOTION_LABELS[emotion_label] if emotion_label else None
51
 
52
- # Face Recognition Function
53
- def recognize_face(image):
54
- """Recognize the face in the uploaded image by comparing with known faces"""
55
- recognizer = cv2.face.LBPHFaceRecognizer_create()
56
-
57
- known_faces = []
58
- labels = []
59
-
60
- # Load known faces from the directory
61
- for filename in os.listdir(KNOWN_FACES_DIR):
62
- if filename.endswith(".jpg"):
63
- image_path = os.path.join(KNOWN_FACES_DIR, filename)
64
- known_image = cv2.imread(image_path)
65
- gray_image = cv2.cvtColor(known_image, cv2.COLOR_BGR2GRAY)
66
- faces = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml').detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=5)
67
-
68
- for (x, y, w, h) in faces:
69
- face = gray_image[y:y+h, x:x+w]
70
- known_faces.append(face)
71
- labels.append(filename.split(".")[0]) # Use image name as label
72
-
73
- if known_faces:
74
- recognizer.train(known_faces, np.array(range(len(labels)))) # Train recognizer with known faces
75
-
76
- # Detect faces in the uploaded image
77
- gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
78
- faces = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml').detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=5)
79
-
80
- recognized_name = "Unknown"
81
- for (x, y, w, h) in faces:
82
- face = gray_image[y:y+h, x:x+w]
83
- label, confidence = recognizer.predict(face)
84
- if confidence < 100: # Confidence threshold
85
- recognized_name = labels[label] # Get the name from labels
86
-
87
- return recognized_name
88
 
89
- # Streamlit UI
90
- st.title("Student Registration with Face Recognition and Emotion Detection")
91
 
92
  # Input fields for student details
93
  name = st.text_input("Enter your name")
@@ -116,19 +105,90 @@ if st.button("Register"):
116
  elif capture_mode == "Upload File" and picture:
117
  image = Image.open(picture)
118
 
119
- # Convert the image to numpy array for processing
120
- img_array = np.array(image)
121
-
122
- # Detect faces and emotions
123
- faces, emotion_label = detect_faces_and_emotions(img_array)
124
- if faces:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  st.success(f"Emotion Detected: {emotion_label}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  else:
127
  st.warning("No face detected.")
128
-
129
- # Perform face recognition
130
- recognized_name = recognize_face(img_array)
131
- st.success(f"Face Recognized as: {recognized_name}")
132
-
133
- except Exception as e:
134
- st.error(f"An error occurred: {e}")
 
4
  import numpy as np
5
  from keras.models import load_model
6
  from PIL import Image
7
+ import sqlite3
8
  from datetime import datetime
9
 
10
  # Constants
11
+ ROOT_DIR = os.getcwd() # Root directory of the project
12
+ DATABASE = "students.db" # SQLite database file to store student information
13
  EMOTION_MODEL_FILE = "CNN_Model_acc_75.h5"
14
  EMOTION_LABELS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
 
 
15
 
16
+ # Load the emotion detection model
 
 
 
 
 
 
 
17
  try:
18
  emotion_model = load_model(EMOTION_MODEL_FILE)
19
  except Exception as e:
20
  st.error(f"Error loading emotion model: {e}")
21
  st.stop()
22
 
23
+ # Database Functions
24
+ def initialize_database():
25
+ """ Initializes the SQLite database by creating the students table if it doesn't exist. """
26
+ conn = sqlite3.connect(DATABASE)
27
+ cursor = conn.cursor()
28
+ cursor.execute("""
29
+ CREATE TABLE IF NOT EXISTS students (
30
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
31
+ name TEXT NOT NULL,
32
+ roll_no TEXT NOT NULL UNIQUE,
33
+ image_path TEXT NOT NULL,
34
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
35
+ )
36
+ """)
37
+ conn.commit()
38
+ conn.close()
39
+
40
+ def save_to_database(name, roll_no, image_path):
41
+ """ Saves the student's data to the database. """
42
+ conn = sqlite3.connect(DATABASE)
43
+ cursor = conn.cursor()
44
+ try:
45
+ cursor.execute("""
46
+ INSERT INTO students (name, roll_no, image_path)
47
+ VALUES (?, ?, ?)
48
+ """, (name, roll_no, image_path))
49
+ conn.commit()
50
+ st.success("Data saved successfully!")
51
+ except sqlite3.IntegrityError:
52
+ st.error("Roll number already exists!")
53
+ finally:
54
+ conn.close()
55
+
56
+ def save_image_to_root_directory(image, name, roll_no):
57
+ """ Saves the image locally in the root directory. """
58
+ # Construct the local file path
59
+ filename = f"{name}_{roll_no}.jpg"
60
+ local_path = os.path.join(ROOT_DIR, filename)
61
 
62
+ try:
63
+ # Convert image to RGB if necessary
64
+ if image.mode != "RGB":
65
+ image = image.convert("RGB")
 
 
 
66
 
67
+ # Save the image to the root directory
68
+ image.save(local_path)
69
+ st.success(f"Image saved to {local_path}.")
70
+ except Exception as e:
71
+ st.error(f"Error saving image: {e}")
72
 
73
+ return local_path
74
 
75
+ # Initialize the database when the app starts
76
+ initialize_database()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ # Streamlit user interface (UI)
79
+ st.title("Student Registration with Image Upload and Face Recognition")
80
 
81
  # Input fields for student details
82
  name = st.text_input("Enter your name")
 
105
  elif capture_mode == "Upload File" and picture:
106
  image = Image.open(picture)
107
 
108
+ # Save the image locally in the root directory
109
+ image_path = save_image_to_root_directory(image, name, roll_no)
110
+ save_to_database(name, roll_no, image_path)
111
+ except Exception as e:
112
+ st.error(f"An error occurred: {e}")
113
+
114
+ # Face and Emotion Detection Function
115
+ def detect_faces_and_emotions(image):
116
+ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
117
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
118
+ faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=5)
119
+
120
+ for (x, y, w, h) in faces:
121
+ face = gray_image[y:y+h, x:x+w]
122
+ resized_face = cv2.resize(face, (48, 48)) # Resize face to 48x48
123
+ rgb_face = cv2.cvtColor(resized_face, cv2.COLOR_GRAY2RGB)
124
+ normalized_face = rgb_face / 255.0
125
+ reshaped_face = np.reshape(normalized_face, (1, 48, 48, 3))
126
+
127
+ # Predict the emotion
128
+ emotion_prediction = emotion_model.predict(reshaped_face)
129
+ emotion_label = np.argmax(emotion_prediction)
130
+ return EMOTION_LABELS[emotion_label]
131
+ return None
132
+
133
+ # Face Recognition: Compare uploaded image with all images in the root directory
134
+ def recognize_face(image_path):
135
+ """ Compares the uploaded image with all images in the root directory """
136
+ img = cv2.imread(image_path)
137
+ gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
138
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
139
+ faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=5)
140
+
141
+ recognized_name = None
142
+ for (x, y, w, h) in faces:
143
+ face = gray_image[y:y+h, x:x+w]
144
+ for filename in os.listdir(ROOT_DIR):
145
+ if filename.endswith(('.jpg', '.jpeg', '.png')):
146
+ stored_image = cv2.imread(os.path.join(ROOT_DIR, filename))
147
+ stored_gray = cv2.cvtColor(stored_image, cv2.COLOR_BGR2GRAY)
148
+ stored_faces = face_cascade.detectMultiScale(stored_gray)
149
+ for (sx, sy, sw, sh) in stored_faces:
150
+ stored_face = stored_gray[sy:sy+sh, sx:sx+sw]
151
+ resized_stored_face = cv2.resize(stored_face, (48, 48))
152
+ rgb_stored_face = cv2.cvtColor(resized_stored_face, cv2.COLOR_GRAY2RGB)
153
+ stored_normalized_face = rgb_stored_face / 255.0
154
+ stored_reshaped_face = np.reshape(stored_normalized_face, (1, 48, 48, 3))
155
+
156
+ # Compare the faces (you can use a more advanced method like facial embeddings, but for simplicity, this is just basic comparison)
157
+ if np.allclose(stored_reshaped_face, face):
158
+ recognized_name = filename.split('_')[0] # Extract the name from the file name
159
+ break
160
+ return recognized_name
161
+
162
+ # UI for Emotion and Face Detection
163
+ if st.sidebar.selectbox("Menu", ["Register Student", "Face Recognition and Emotion Detection"]) == "Face Recognition and Emotion Detection":
164
+ st.subheader("Recognize Faces and Detect Emotions")
165
+ action = st.radio("Choose Action", ["Upload Image", "Use Webcam"])
166
+
167
+ if action == "Upload Image":
168
+ uploaded_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
169
+ if uploaded_file:
170
+ img = Image.open(uploaded_file)
171
+ img_array = np.array(img)
172
+ emotion_label = detect_faces_and_emotions(img_array)
173
+ recognized_name = recognize_face(uploaded_file)
174
+ if emotion_label:
175
  st.success(f"Emotion Detected: {emotion_label}")
176
+ if recognized_name:
177
+ st.success(f"Face Recognized: {recognized_name}")
178
+ else:
179
+ st.warning("No face detected.")
180
+
181
+ elif action == "Use Webcam":
182
+ st.info("Use the camera input widget to capture an image.")
183
+ camera_image = st.camera_input("Take a picture")
184
+ if camera_image:
185
+ img = Image.open(camera_image)
186
+ img_array = np.array(img)
187
+ emotion_label = detect_faces_and_emotions(img_array)
188
+ recognized_name = recognize_face(camera_image)
189
+ if emotion_label:
190
+ st.success(f"Emotion Detected: {emotion_label}")
191
+ if recognized_name:
192
+ st.success(f"Face Recognized: {recognized_name}")
193
  else:
194
  st.warning("No face detected.")