LovnishVerma commited on
Commit
a4d9380
·
verified ·
1 Parent(s): a81d730

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -98
app.py CHANGED
@@ -1,13 +1,12 @@
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
@@ -17,7 +16,7 @@ DATABASE = "students.db" # SQLite database file to store student information
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()
@@ -64,13 +63,18 @@ def save_to_database(name, roll_no, image_path):
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,
@@ -81,7 +85,7 @@ def save_image_to_hugging_face(image, name, roll_no):
81
  st.success(f"Image uploaded to Hugging Face: {filename}")
82
  except Exception as e:
83
  st.error(f"Error uploading image to Hugging Face: {e}")
84
-
85
  return local_path
86
 
87
  # Process each frame for emotion detection
@@ -103,101 +107,61 @@ def process_frame(frame):
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, faces # Return the frame and the detected faces
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 - Streamlit tabs
120
- st.title("Student Registration and Attendance System")
121
-
122
- tabs = st.selectbox("Choose Functionality", ["Register Student", "Record Attendance", "View Attendance"])
123
-
124
- if tabs == "Register Student":
125
- st.subheader("Student Registration")
126
-
127
- # Choose input method for the image (webcam or file upload)
128
- capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
129
-
130
- if capture_mode == "Use Webcam":
131
- picture = st.camera_input("Take a picture") # Capture image using webcam
132
- elif capture_mode == "Upload File":
133
- picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
134
-
135
- # Input fields for student details
136
- name = st.text_input("Enter your name")
137
- roll_no = st.text_input("Enter your roll number")
138
-
139
- # Handle image upload or webcam capture
140
- if st.button("Register"):
141
- if not name or not roll_no:
142
- st.error("Please fill in both name and roll number.")
143
- elif not picture:
144
- st.error("Please upload or capture an image.")
145
- else:
146
- try:
147
- # Open the image based on capture mode
148
- if capture_mode == "Use Webcam" and picture:
149
- image = Image.open(picture)
150
- elif capture_mode == "Upload File" and picture:
151
- image = Image.open(picture)
152
-
153
- # Save the image locally and upload it to Hugging Face
154
- image_path = save_image_to_hugging_face(image, name, roll_no)
155
-
156
- # Save user data to the database
157
- save_to_database(name, roll_no, image_path)
158
-
159
- st.success("Registration Successful!")
160
-
161
- except Exception as e:
162
- st.error(f"An error occurred: {e}")
163
-
164
- elif tabs == "Record Attendance":
165
- st.subheader("Record Attendance")
166
-
167
- # Initialize the webcam for face detection and emotion recognition
168
- cap = cv2.VideoCapture(0)
169
-
170
- while True:
171
- ret, frame = cap.read()
172
- if not ret:
173
- break
174
-
175
- # Process the frame to detect faces and emotions
176
- frame, faces = process_frame(frame)
177
-
178
- # Show the image with detected faces and emotions
179
- st.image(frame, channels="BGR", use_column_width=True)
180
-
181
- # When a face is detected, assume it's the person for attendance
182
- if len(faces) > 0:
183
- # Assume the first face detected corresponds to the student
184
- x, y, w, h = faces[0]
185
- # Extract the emotion from the frame (for simplicity, use the first detected face)
186
- name = "John Doe" # Replace with the actual name after face recognition
187
- roll_no = "12345" # Replace with the actual roll number
188
- emotion = emotion_labels[np.argmax(model.predict(cv2.resize(frame[y:y+h, x:x+w], (48, 48)).reshape(1, 48, 48, 3)))] # Get emotion of detected face
189
-
190
- # Record attendance based on the detected information
191
- if st.button("Record Attendance"):
192
- record_attendance(name, roll_no, emotion)
193
- st.success(f"Attendance recorded for {name} ({roll_no}) with emotion: {emotion}")
194
  break # Stop after capturing one frame
195
 
196
- cap.release()
197
 
198
- elif tabs == "View Attendance":
199
- st.subheader("View Attendance Records")
200
 
 
 
201
  conn = sqlite3.connect(DATABASE)
202
  cursor = conn.cursor()
203
  cursor.execute("SELECT name, roll_no, image_path, timestamp FROM students")
 
1
  import os
2
  import sqlite3
 
3
  import streamlit as st
 
4
  from PIL import Image
5
  import numpy as np
6
+ import cv2
7
  from keras.models import load_model
8
+ from datetime import datetime
9
  from huggingface_hub import HfApi
 
10
 
11
  # Constants
12
  KNOWN_FACES_DIR = "known_faces" # Directory to save user images
 
16
  os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
17
 
18
  # Initialize Hugging Face API
19
+ hf_token = os.getenv("upload") # Ensure this is set correctly as a secret in Hugging Face
20
  if not hf_token:
21
  raise ValueError("Hugging Face token not found. Ensure it's set as a secret in Hugging Face")
22
  api = HfApi()
 
63
  finally:
64
  conn.close()
65
 
66
+ # Save the captured image locally in known_faces directory and upload to Hugging Face
67
  def save_image_to_hugging_face(image, name, roll_no):
68
+ # Create a filename based on the student name and roll number
69
  filename = f"{name}_{roll_no}.jpg"
70
  local_path = os.path.join(KNOWN_FACES_DIR, filename)
71
+
72
+ # Save the image locally
73
  image.save(local_path)
74
+ st.success(f"Image saved locally to {local_path}")
75
+
76
  try:
77
+ # Upload the image to Hugging Face repository
78
  api.upload_file(
79
  path_or_fileobj=local_path,
80
  path_in_repo=filename,
 
85
  st.success(f"Image uploaded to Hugging Face: {filename}")
86
  except Exception as e:
87
  st.error(f"Error uploading image to Hugging Face: {e}")
88
+
89
  return local_path
90
 
91
  # Process each frame for emotion detection
 
107
  cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
108
  cv2.putText(frame, emotion, (x, y+h), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
109
 
110
+ return frame
111
+
112
+ # User Interface for registration
113
+ st.title("Student Registration and Attendance")
114
+
115
+ # Choose input method for the image (webcam or file upload)
116
+ capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
117
+
118
+ if capture_mode == "Use Webcam":
119
+ picture = st.camera_input("Take a picture") # Capture image using webcam
120
+ elif capture_mode == "Upload File":
121
+ picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
122
+
123
+ # Input fields for student details
124
+ name = st.text_input("Enter your name")
125
+ roll_no = st.text_input("Enter your roll number")
126
+
127
+ # Handle image upload or webcam capture
128
+ if st.button("Register"):
129
+ if not name or not roll_no:
130
+ st.error("Please fill in both name and roll number.")
131
+ elif not picture:
132
+ st.error("Please upload or capture an image.")
133
+ else:
134
+ try:
135
+ # Open the image based on capture mode
136
+ if capture_mode == "Use Webcam" and picture:
137
+ image = Image.open(picture)
138
+ elif capture_mode == "Upload File" and picture:
139
+ image = Image.open(picture)
140
+
141
+ # Save the image locally and upload it to Hugging Face
142
+ image_path = save_image_to_hugging_face(image, name, roll_no)
143
+
144
+ # Save user data to the database
145
+ save_to_database(name, roll_no, image_path)
146
+
147
+ # Detect faces and emotions
148
+ cap = cv2.VideoCapture(0)
149
+ while True:
150
+ ret, frame = cap.read()
151
+ if not ret:
152
+ break
153
+
154
+ frame = process_frame(frame)
155
+ st.image(frame, channels="BGR", use_column_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  break # Stop after capturing one frame
157
 
158
+ cap.release()
159
 
160
+ except Exception as e:
161
+ st.error(f"An error occurred: {e}")
162
 
163
+ # Display registered students and attendance history
164
+ if st.checkbox("Show registered students"):
165
  conn = sqlite3.connect(DATABASE)
166
  cursor = conn.cursor()
167
  cursor.execute("SELECT name, roll_no, image_path, timestamp FROM students")