import numpy as np import cv2 import face_recognition import sqlite3 import streamlit as st from datetime import datetime from PIL import Image # Step 1: Initialize Face Recognition # Load known faces and names known_face_encodings = [] known_face_names = [] # Example: Add known faces try: image_person1 = face_recognition.load_image_file("person1.jpg") encoding_person1 = face_recognition.face_encodings(image_person1)[0] known_face_encodings.append(encoding_person1) known_face_names.append("Person 1") except Exception as e: st.error(f"Error loading known faces: {e}") # Step 2: Set Up Database connection = sqlite3.connect("attendance.db", check_same_thread=False) cursor = connection.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS Attendance ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, timestamp TEXT ) ''') # Function to log attendance def log_attendance(name): timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') cursor.execute("INSERT INTO Attendance (name, timestamp) VALUES (?, ?)", (name, timestamp)) connection.commit() # Step 3: Detect and Recognize Faces def detect_and_mark_attendance(uploaded_image): image = np.array(uploaded_image) rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) face_locations = face_recognition.face_locations(rgb_image) face_encodings = face_recognition.face_encodings(rgb_image, face_locations) for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "Unknown" if True in matches: match_index = matches.index(True) name = known_face_names[match_index] log_attendance(name) # Log to database # Draw a rectangle around the face cv2.rectangle(image, (left, top), (right, bottom), (255, 0, 0), 3) cv2.putText(image, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) return image # Step 4: Fetch Attendance Logs def fetch_attendance(): cursor.execute("SELECT * FROM Attendance") rows = cursor.fetchall() return rows # Streamlit Interface st.title("Face Recognition and Attendance System") st.write("Upload an image to detect faces and mark attendance.") # Image upload uploaded_image = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"]) if uploaded_image is not None: image = Image.open(uploaded_image) st.image(image, caption="Uploaded Image", use_column_width=True) # Process image image_np = np.array(image) processed_image = detect_and_mark_attendance(image_np) st.image(processed_image, caption="Processed Image with Attendance Marked", use_column_width=True) # Display attendance logs st.subheader("Attendance Logs") attendance_data = fetch_attendance() if attendance_data: st.table(attendance_data) else: st.write("No attendance records found.")