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()