Spaces:
Build error
Build error
File size: 7,418 Bytes
054eff1 673ae48 3332de0 673ae48 054eff1 673ae48 3332de0 054eff1 3332de0 673ae48 3332de0 054eff1 3332de0 054eff1 3332de0 673ae48 3332de0 054eff1 3332de0 054eff1 3332de0 054eff1 3332de0 054eff1 3332de0 054eff1 3332de0 054eff1 3332de0 054eff1 3332de0 054eff1 3332de0 054eff1 3332de0 673ae48 054eff1 3332de0 054eff1 3332de0 054eff1 3332de0 673ae48 054eff1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | import streamlit as st
import cv2
import numpy as np
import face_recognition
import os
import pandas as pd
from datetime import datetime
# Set page config
st.set_page_config(page_title="Face Recognition Attendance System", layout="wide")
# Initialize session state for known faces and attendance
if 'known_face_encodings' not in st.session_state:
st.session_state.known_face_encodings = []
if 'known_face_names' not in st.session_state:
st.session_state.known_face_names = []
if 'attendance_log' not in st.session_state:
st.session_state.attendance_log = pd.DataFrame(columns=["Name", "Time"])
# Create directories if they don't exist
os.makedirs("registered_faces", exist_ok=True)
os.makedirs("attendance_records", exist_ok=True)
# Function to load registered faces
def load_registered_faces():
st.session_state.known_face_encodings = []
st.session_state.known_face_names = []
for filename in os.listdir("registered_faces"):
if filename.endswith(".jpg") or filename.endswith(".png"):
image_path = os.path.join("registered_faces", filename)
image = face_recognition.load_image_file(image_path)
encodings = face_recognition.face_encodings(image)
if len(encodings) > 0:
st.session_state.known_face_encodings.append(encodings[0])
st.session_state.known_face_names.append(os.path.splitext(filename)[0])
# Function to register a new face
def register_new_face():
st.subheader("Register New User")
col1, col2 = st.columns(2)
with col1:
name = st.text_input("Enter Full Name")
picture = st.camera_input("Take a picture for registration")
if picture and name:
# Save the image
image_path = os.path.join("registered_faces", f"{name}.jpg")
with open(image_path, "wb") as f:
f.write(picture.getbuffer())
# Load and encode the face
image = face_recognition.load_image_file(image_path)
encodings = face_recognition.face_encodings(image)
if len(encodings) > 0:
st.session_state.known_face_encodings.append(encodings[0])
st.session_state.known_face_names.append(name)
st.success(f"Successfully registered {name}!")
load_registered_faces() # Reload faces
else:
st.error("No face detected. Please try again.")
with col2:
if 'known_face_names' in st.session_state and st.session_state.known_face_names:
st.write("Registered Users:")
st.write(pd.DataFrame(st.session_state.known_face_names, columns=["Name"]))
# Function to mark attendance
def mark_attendance():
st.subheader("Mark Attendance")
run_attendance = st.checkbox('Start Camera for Attendance')
frame_placeholder = st.empty()
if run_attendance:
video_capture = cv2.VideoCapture(0)
while run_attendance:
ret, frame = video_capture.read()
if not ret:
st.error("Failed to capture video")
break
# Convert to RGB (face_recognition uses RGB)
rgb_frame = frame[:, :, ::-1]
# Find faces
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# Compare with known faces
matches = face_recognition.compare_faces(
st.session_state.known_face_encodings,
face_encoding,
tolerance=0.5
)
name = "Unknown"
if True in matches:
first_match_index = matches.index(True)
name = st.session_state.known_face_names[first_match_index]
# Log attendance if not already logged
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if name not in st.session_state.attendance_log["Name"].values:
new_entry = {"Name": name, "Time": now}
st.session_state.attendance_log = pd.concat(
[st.session_state.attendance_log, pd.DataFrame([new_entry])],
ignore_index=True
)
st.success(f"Attendance marked for {name} at {now}")
# Draw rectangle and name on the face
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left + 6, bottom - 6),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
# Display the frame
frame_placeholder.image(frame, channels="BGR")
# Check if user stopped the camera
if not st.session_state.get('run_attendance', True):
break
video_capture.release()
# Show attendance log
if not st.session_state.attendance_log.empty:
st.subheader("Today's Attendance")
st.dataframe(st.session_state.attendance_log)
# Export button
if st.button("Export Attendance to CSV"):
csv_path = os.path.join("attendance_records", f"attendance_{datetime.now().strftime('%Y%m%d')}.csv")
st.session_state.attendance_log.to_csv(csv_path, index=False)
st.success(f"Attendance exported to {csv_path}")
# Main app
def main():
st.title("Face Recognition Attendance System")
menu = ["Home", "Register Face", "Mark Attendance", "View Records"]
choice = st.sidebar.selectbox("Menu", menu)
if choice == "Home":
st.write("""
### Welcome to the Face Recognition Attendance System!
- **Register Face**: Add new users by capturing their facial data.
- **Mark Attendance**: Use the webcam to recognize and log attendance.
- **View Records**: Check and export attendance logs.
""")
elif choice == "Register Face":
load_registered_faces()
register_new_face()
elif choice == "Mark Attendance":
load_registered_faces()
mark_attendance()
elif choice == "View Records":
st.subheader("Attendance Records")
if os.path.exists("attendance_records"):
files = os.listdir("attendance_records")
if files:
selected_file = st.selectbox("Select a record", files)
df = pd.read_csv(os.path.join("attendance_records", selected_file))
st.dataframe(df)
# Export button
if st.button("Export Selected Record"):
st.download_button(
label="Download CSV",
data=df.to_csv(index=False),
file_name=selected_file,
mime="text/csv"
)
else:
st.warning("No attendance records found.")
if __name__ == "__main__":
main() |