Spaces:
Sleeping
Sleeping
File size: 3,790 Bytes
5cc12ff 8a1e4b6 5cc12ff 8a1e4b6 5cc12ff 8a1e4b6 1631231 5cc12ff 1631231 8a1e4b6 5cc12ff 1631231 8a1e4b6 1631231 8a1e4b6 1631231 5cc12ff 1631231 5cc12ff 8a1e4b6 5cc12ff 8a1e4b6 5cc12ff 340457a 5cc12ff 8a1e4b6 5cc12ff 8a1e4b6 5cc12ff 8a1e4b6 1631231 8a1e4b6 1631231 8a1e4b6 1631231 8a1e4b6 1631231 |
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 |
import streamlit as st
import sqlite3
import cv2
import datetime
import pandas as pd
from PIL import Image
import os
# Create a directory for storing photos
os.makedirs("photos", exist_ok=True)
def create_database():
"""Creates the attendance database."""
conn = sqlite3.connect('attendance.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS attendance (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rollno TEXT,
name TEXT,
photo_path TEXT,
emotion TEXT,
timestamp TEXT
)''')
conn.commit()
conn.close()
def detect_emotion(frame):
"""Dummy emotion detection function."""
# Placeholder for actual emotion detection logic
return "Happy"
def mark_attendance(rollno, name, frame):
"""Marks attendance for the user."""
conn = sqlite3.connect('attendance.db')
c = conn.cursor()
timestamp = datetime.datetime.now()
date_str = timestamp.strftime("%Y-%m-%d")
time_str = timestamp.strftime("%H:%M:%S")
# Save the captured photo
photo_path = f"photos/{rollno}_{name.replace(' ', '_')}.jpg"
photo = Image.fromarray(frame)
photo.save(photo_path)
# Detect emotion (dummy function)
emotion = detect_emotion(frame)
# Insert record into the database
c.execute("INSERT INTO attendance (rollno, name, photo_path, emotion, timestamp) VALUES (?, ?, ?, ?, ?)",
(rollno, name, photo_path, emotion, timestamp))
conn.commit()
conn.close()
def get_attendance_records():
"""Fetches all attendance records."""
conn = sqlite3.connect('attendance.db')
c = conn.cursor()
c.execute("SELECT rollno, name, photo_path, emotion, timestamp FROM attendance")
records = c.fetchall()
conn.close()
return records
def capture_photo():
"""Captures a photo using the webcam."""
cap = cv2.VideoCapture(0)
st.info("Click 'Capture' to take a photo.")
while cap.isOpened():
ret, frame = cap.read()
if not ret:
st.error("Failed to capture image.")
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
st.image(frame, channels="RGB")
if st.button("Capture"):
cap.release()
cv2.destroyAllWindows()
return frame
if st.button("Cancel"):
cap.release()
cv2.destroyAllWindows()
return None
# Initialize the database
create_database()
st.title("Attendance System")
menu = st.sidebar.selectbox("Menu", ["Click Photo", "Database"])
if menu == "Click Photo":
st.header("Mark Attendance by Clicking Photo")
rollno = st.text_input("Enter your Roll Number:")
name = st.text_input("Enter your Name:")
if rollno and name:
frame = capture_photo()
if frame is not None:
mark_attendance(rollno, name, frame)
st.success(f"Attendance marked for {name} (Roll No: {rollno})")
st.image(frame, caption="Captured Image", channels="RGB")
elif menu == "Database":
st.header("Attendance Records")
records = get_attendance_records()
data = []
for rollno, name, photo_path, emotion, timestamp in records:
photo = Image.open(photo_path) if os.path.exists(photo_path) else None
date, time = timestamp.split(" ")
data.append((rollno, photo, name, emotion, date, time))
df = pd.DataFrame(data, columns=["Roll No", "Photo", "Name", "Emotion", "Date", "Time"])
st.write("### Attendance Records")
for idx, row in df.iterrows():
st.image(row["Photo"], caption=f"Roll No: {row['Roll No']} - Name: {row['Name']} - Emotion: {row['Emotion']}")
st.table(df.drop(columns=["Photo"])) # Exclude photo for table display
|