faceRecog / attendanceCam.py
ArchiMathur's picture
Update attendanceCam.py
195c967 verified
# # import cv2
# # from ultralytics import YOLO
# # import time
# # from datetime import datetime, timedelta
# # import numpy
# # import csv
# #
# # # Load YOLO model
# # model = YOLO("D:\\live attendance\\best(attendance).pt")
# #
# # # Initialize webcam
# # cap = cv2.VideoCapture(0) # 0 is usually the default camera
# #
# # # Dictionary to store attendance records
# # attendance_records = {}
# #
# # # CSV file to store attendance data
# # csv_file = open(r"D:\\live attendance\\attendance_data.csv", "w", newline="")
# # csv_writer = csv.writer(csv_file)
# # csv_writer.writerow(["Name", "Time"])
# #
# #
# # while True:
# # # Read a frame from the webcam
# # ret, frame = cap.read()
# # if not ret:
# # print("Failed to capture image")
# # break
# #
# # # Detect objects
# # results = model(frame)
# #
# # # Iterate through results
# # for result in results:
# # boxes = result.boxes
# # for box in boxes: # Iterate through detected boxes
# # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
# # class_id = int(box.cls[0]) # Get the class ID
# # confidence = box.conf[0] # Get the confidence score
# #
# # # Get the class name from YOLO class names
# # class_name = model.names[class_id]
# #
# # # Draw rectangle around detected object
# # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
# # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
# # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# #
# # # Check if attendance can be marked
# # current_time = datetime.now()
# # if class_name not in attendance_records:
# # # Mark attendance for the first time
# # attendance_records[class_name] = current_time
# # print(f"Attendance marked for {class_name} at {current_time}")
# # # Write to CSV
# # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")])
# # else:
# # last_attendance_time = attendance_records[class_name]
# # # Check if 24 hours have passed
# # if current_time - last_attendance_time >= timedelta(days=1):
# # attendance_records[class_name] = current_time
# # print(f"Attendance marked for {class_name} at {current_time}")
# #
# # # Write to CSV
# # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")])
# # # csv_file.flush() # Ensure it's saved immediately
# #
# # # Show the frame with detections
# # cv2.imshow("Detected Objects", frame)
# #
# # # Break the loop on 'q' key press
# # if cv2.waitKey(1) & 0xFF == ord('q'):
# # break
# #
# # # Release the video capture object and close all OpenCV windows
# # cap.release()
# # cv2.destroyAllWindows()
# #
# # # import cv2
# # # from ultralytics import YOLO
# # # import time
# # # from datetime import datetime, timedelta
# # # import csv
# # #
# # # # Load YOLO model
# # # model = YOLO("D:\\live attendance\\best(attendance).pt")
# # #
# # # # Initialize webcam
# # # cap = cv2.VideoCapture(0) # 0 is usually the default camera
# # #
# # # # Dictionary to store attendance records
# # # attendance_records = {}
# # #
# # # # CSV file to store attendance data
# # # # csv_file = open("D:\\live attendance\\attendance_data.csv", "w", newline="")
# # # # csv_writer = csv.writer(csv_file)
# # # # csv_writer.writerow(["Name", "Time"])
# # #
# # # with open('D:\\live attendance\\attendance_data.csv', 'w', newline='') as csv_file:
# # # writer = csv.writer(csv_file)
# # # writer.writerows(["Name", "Time"])
# # #
# # # while True:
# # # # Read a frame from the webcam
# # # ret, frame = cap.read()
# # # if not ret:
# # # print("Failed to capture image")
# # # break
# # #
# # # # Detect objects
# # # results = model(frame)
# # #
# # # # Iterate through results
# # # for result in results:
# # # boxes = result.boxes
# # # for box in boxes: # Iterate through detected boxes
# # # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
# # # class_id = int(box.cls[0]) # Get the class ID
# # # confidence = box.conf[0] # Get the confidence score
# # #
# # # # Get the class name from YOLO class names
# # # class_name = model.names[class_id]
# # #
# # # # Draw rectangle around detected object
# # # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
# # # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
# # # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# # #
# # # # Check if attendance can be marked
# # # current_time = datetime.now()
# # # if class_name not in attendance_records:
# # # # Mark attendance for the first time
# # # attendance_records[class_name] = current_time
# # # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")]) # Save to CSV
# # # print(f"Attendance marked for {class_name} at {current_time}")
# # # else:
# # # last_attendance_time = attendance_records[class_name]
# # # # Check if 24 hours have passed
# # # if current_time - last_attendance_time >= timedelta(days=1):
# # # attendance_records[class_name] = current_time
# # # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")]) # Save to CSV
# # # print(f"Attendance marked for {class_name} at {current_time}")
# # #
# # # # Show the frame with detections
# # # cv2.imshow("Detected Objects", frame)
# # #
# # # # Break the loop on 'q' key press
# # # if cv2.waitKey(1) & 0xFF == ord('q'):
# # # break
# # #
# # # # Release the video capture object and close all OpenCV windows
# # # cap.release()
# # # csv_file.close() # Close the CSV file
# # # cv2.destroyAllWindows()
#
# # import cv2
# # from ultralytics import YOLO
# # from datetime import datetime, timedelta
# # import csv
# #
# # # Load YOLO model
# # model = YOLO("D:\\live attendance\\best(attendance).pt")
# #
# # # Initialize webcam
# # cap = cv2.VideoCapture(0) # 0 is usually the default camera
# #
# # # Dictionary to store attendance records
# # attendance_records = {}
# #
# # # CSV file to store attendance data
# # csv_file_path = r"D:\\live attendance\\attendance_data.csv"
# # with open(csv_file_path, "a", newline="") as csv_file:#think here
# # csv_writer = csv.writer(csv_file)
# #
# #
# # while True:
# # # Read a frame from the webcam
# # ret, frame = cap.read()
# # if not ret:
# # print("Failed to capture image")
# # break
# #
# # # Detect objects
# # results = model(frame)
# #
# # # Iterate through results
# # for result in results:
# # boxes = result.boxes
# # for box in boxes: # Iterate through detected boxes
# # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
# # class_id = int(box.cls[0]) # Get the class ID
# # confidence = box.conf[0] # Get the confidence score
# #
# # # Get the class name from YOLO class names
# # class_name = model.names[class_id]
# #
# # # Draw rectangle around detected object
# # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
# # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
# # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# #
# # # Check if attendance can be marked
# # current_time = datetime.now()
# # if class_name not in attendance_records:
# # # Mark attendance for the first time
# # attendance_records[class_name] = current_time#think here
# # print(f"Attendance marked for {class_name} at {current_time}")
# # # Write to CSV
# # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")])
# # else:
# # last_attendance_time = attendance_records[class_name]
# # # Check if 24 hours have passed
# # if current_time - last_attendance_time >= timedelta(days=1):
# # attendance_records[class_name] = current_time
# # print(f"Attendance marked for {class_name} at {current_time}")
# # # Write to CSV
# # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")])
# #
# # # Show the frame with detections
# # cv2.imshow("Detected Objects", frame)
# #
# # # Break the loop on 'q' key press
# # if cv2.waitKey(1) & 0xFF == ord('q'):
# # break
# #
# # # Release the video capture object and close all OpenCV windows
# # cap.release()
# # cv2.destroyAllWindows()
#
#
# # import cv2
# # import pandas as pd
# # from ultralytics import YOLO
# # from datetime import datetime, timedelta
# #
# # # Load the model
# # model = YOLO("D:\\live attendance\\best(attendance).pt")
# #
# # # Open camera (0 for default camera, 1 for external camera)
# # cap = cv2.VideoCapture(0)
# #
# # # Initialize lists to store class names and timestamps
# # class_names_list = []
# # time_list = []
# #
# # # Initialize a list to keep track of last attendance times
# # last_attendance_times = []
# #
# # while True:
# # # Read a frame from the webcam
# # ret, frame = cap.read()
# # if not ret:
# # print("Failed to capture image")
# # break
# #
# # # Detect objects
# # results = model(frame)
# #
# # # Iterate through results
# # for result in results:
# # boxes = result.boxes
# # for box in boxes: # Iterate through detected boxes
# # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
# # class_id = int(box.cls[0]) # Get the class ID
# # confidence = box.conf[0] # Get the confidence score
# #
# # # Get the class name from YOLO class names
# # class_name = model.names[class_id]
# #
# # # Draw rectangle around detected object
# # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
# # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
# # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# #
# # # Get the current time
# # current_time = datetime.now()
# # current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
# #
# # # Check if the class name is already in the list
# # if class_name not in class_names_list:
# # # Mark attendance for the first time
# # class_names_list.append(class_name)
# # time_list.append(current_time_str)
# # last_attendance_times.append( class_names_list+time_list) # Store the time of attendance
# # print(f"Attendance marked for {class_name} at {current_time_str}")
# # else:
# #
# # # Check if 24 hours have passed since last recorded attendance
# # if current_time - last_attendance_times[class_name] >= timedelta(days=1):
# # last_attendance_times[class_name] = current_time # Update the last attendance time
# # time_list[class_names_list.index(class_name)] = current_time_str # Update the time in the list
# # print(f"Attendance marked for {class_name} at {current_time_str}")
# #
# # # Display output
# # cv2.imshow("Object Detection", frame)
# #
# # # Exit on 'q' press
# # if cv2.waitKey(1) & 0xFF == ord('q'):
# # break
# #
# # # Release camera and close window
# # cap.release()
# # cv2.destroyAllWindows()
# #
# # # Save class names and timestamps to CSV
# # df = pd.DataFrame({
# # "Class Name": class_names_list,
# # "Time": time_list
# # })
# # df.to_csv("D:\\live attendance\\attendance_data.csv", index=False)
# #
# # print("Detections saved ")
#
# # import cv2
# # import pandas as pd
# # from ultralytics import YOLO
# # from datetime import datetime
# #
# # # Load the YOLO model
# # model = YOLO("D:\\live attendance\\best(attendance).pt")
# #
# # # Open camera (0 for default camera, 1 for external camera)
# # cap = cv2.VideoCapture(0)
# #
# # # Initialize lists to store class names and timestamps
# # class_names_list = []
# # time_list = []
# #
# # while True:
# # # Read a frame from the webcam
# # ret, frame = cap.read()
# # if not ret:
# # print("Failed to capture image")
# # break
# #
# # # Detect objects
# # results = model(frame)
# #
# # # Check if any results are detected
# # if results: # Check if results are not empty
# # for result in results:
# # boxes = result.boxes
# # for box in boxes: # Iterate through detected boxes
# # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
# # class_id = int(box.cls[0]) # Get the class ID
# # confidence = box.conf[0] # Get the confidence score
# #
# # # Get the class name from YOLO class names
# # class_name = model.names[class_id]
# #
# # # Draw rectangle around detected object
# # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
# # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
# # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# #
# # # Get the current time
# # current_time = datetime.now()
# # current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
# #
# # # Record attendance for every detected class
# # if class_name not in class_names_list:
# # class_names_list.append(class_name)
# # time_list.append(current_time_str)
# # print(f"Attendance marked for {class_name} at {current_time_str}")
# # else:
# # print(f"{class_name} already recorded.")
# #
# # else:
# # print("No results detected.")
# #
# # # Display output
# # cv2.imshow("Object Detection", frame)
# #
# # # Exit on 'q' press
# # if cv2.waitKey(1) & 0xFF == ord('q'):
# # break
# #
# # # Release camera and close window
# # cap.release()
# # cv2.destroyAllWindows()
# #
# # # Check if lists are populated before saving
# # print("Class Names:", class_names_list)
# # print("Time List:", time_list)
# #
# # # Save class names and timestamps to CSV
# # if class_names_list and time_list: # Only save if there is data
# # df = pd.DataFrame({
# # "Class Name": class_names_list,
# # "Time": time_list
# # })
# # try:
# # df.to_csv("D:\\live attendance\\attendance_data.csv", index=False)
# # print("Detections saved to CSV.")
# # except Exception as e:
# # print(f"Error saving to CSV: {e}")
# # else:
# # print("No attendance data to save.")
#
#
# import cv2
# import pandas as pd
# from ultralytics import YOLO
# from datetime import datetime, timedelta
#
# # Load the YOLO model
# model = YOLO("D:\\live attendance\\best(attendance).pt")
#
# # model = YOLO("C:\\Users\\Dell\\Downloads\\best (2).pt")
#
# # Open camera (0 for default camera, 1 for external camera)
# cap = cv2.VideoCapture(0)
#
# # Initialize lists to store class names and timestamps
# class_names_list = []
# time_list = []
#
# while True:
# # Read a frame from the webcam
# ret, frame = cap.read()
# if not ret:
# print("Failed to capture image")
# break
#
# # Detect objects
# results = model(frame)
#
# # Check if any results are detected
# if results: # Check if results are not empty
# for result in results:
# boxes = result.boxes
# for box in boxes: # Iterate through detected boxes
# x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
# class_id = int(box.cls[0]) # Get the class ID
# confidence = box.conf[0] # Get the confidence score
#
# # Get the class name from YOLO class names
# class_name = model.names[class_id]
#
# # Draw rectangle around detected object
# cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
# cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
# cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
#
# # Get the current time
# current_time = datetime.now()
# current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
#
# # Check if the class has been recorded and if 24 hours have passed
# if class_name in class_names_list:
# index = class_names_list.index(class_name)
# last_recorded_time = datetime.strptime(time_list[index], "%Y-%m-%d %H:%M:%S")
#
# # If less than 24 hours have passed since the last recording
# if (current_time - last_recorded_time) < timedelta(hours=24):
# print(f"{class_name} already recorded within the last 24 hours.")
# continue
#
# # Record attendance for the class
# class_names_list.append(class_name)
# time_list.append(current_time_str)
# print(f"Attendance marked for {class_name} at {current_time_str}")
#
# else:
# print("No results detected.")
#
# # Display output
# cv2.imshow("Object Detection", frame)
#
# # Exit on 'q' press
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#
# # Release camera and close window
# cap.release()
# cv2.destroyAllWindows()
#
# # Check if lists are populated before saving
# print("Class Names:", class_names_list)
# print("Time List:", time_list)
#
# # Save class names and timestamps to CSV
# if class_names_list and time_list: # Only save if there is data
# df = pd.DataFrame({
# "Class Name": class_names_list,
# "Time": time_list
# })
# try:
# df.to_csv("D:\\live attendance\\attendance_data.csv", index=False)
# print("Detections saved to CSV.")
# except Exception as e:
# print(f"Error saving to CSV: {e}")
# else:
# print("No attendance data to save.")
import cv2
import pandas as pd
import gradio as gr
from ultralytics import YOLO
from datetime import datetime, timedelta
import os
import numpy as np
class AttendanceSystem:
def __init__(self, model_path, csv_path):
self.model_path = model_path
self.csv_path = csv_path
self.model = None
self.class_names_list = []
self.time_list = []
self.load_previous_attendance()
def load_model(self):
"""Load the YOLO model"""
if self.model is None:
try:
self.model = YOLO(self.model_path)
return True, "Model loaded successfully!"
except Exception as e:
return False, f"Error loading model: {str(e)}"
return True, "Model already loaded"
def load_previous_attendance(self):
"""Load previous attendance data if CSV exists"""
if os.path.exists(self.csv_path):
try:
df = pd.read_csv(self.csv_path)
if not df.empty:
self.class_names_list = df["Class Name"].tolist()
self.time_list = df["Time"].tolist()
return True, f"Loaded {len(self.class_names_list)} previous attendance records"
except Exception as e:
return False, f"Error loading previous attendance: {str(e)}"
return False, "No previous attendance data found"
def process_frame(self, frame):
"""Process a single frame and update attendance"""
if self.model is None:
success, message = self.load_model()
if not success:
return frame, message, [], []
# Create a copy of the frame to draw on
display_frame = frame.copy()
# Store detected names in this frame
detected_names = []
# Detect objects
results = self.model(frame)
# Check if any results are detected
if results:
for result in results:
boxes = result.boxes
for box in boxes:
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int)
class_id = int(box.cls[0])
confidence = float(box.conf[0])
# Get the class name from YOLO class names
class_name = self.model.names[class_id]
detected_names.append(class_name)
# Draw rectangle around detected object
cv2.rectangle(display_frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(display_frame, f"{class_name}: {confidence:.2f}",
(x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# Get the current time
current_time = datetime.now()
current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
# Check if the class has been recorded already
person_already_recorded = False
for idx, name in enumerate(self.class_names_list):
if name == class_name:
last_recorded_time = datetime.strptime(self.time_list[idx], "%Y-%m-%d %H:%M:%S")
# If less than 24 hours have passed since the last recording
if (current_time - last_recorded_time) < timedelta(hours=24):
person_already_recorded = True
break
# Record attendance if not already recorded in the last 24 hours
if not person_already_recorded:
self.class_names_list.append(class_name)
self.time_list.append(current_time_str)
self.save_attendance()
# Create attendance list for display
attendance_data = []
for name, time_str in zip(self.class_names_list, self.time_list):
attendance_data.append(f"{name} - {time_str}")
return display_frame, f"Detected: {', '.join(detected_names) if detected_names else 'None'}", attendance_data, detected_names
def save_attendance(self):
"""Save attendance data to CSV"""
if self.class_names_list and self.time_list:
df = pd.DataFrame({
"Class Name": self.class_names_list,
"Time": self.time_list
})
try:
df.to_csv(self.csv_path, index=False)
return True, "Attendance saved to CSV"
except Exception as e:
return False, f"Error saving to CSV: {str(e)}"
return False, "No attendance data to save"
def clear_attendance(self):
"""Clear attendance records"""
self.class_names_list = []
self.time_list = []
if os.path.exists(self.csv_path):
try:
os.remove(self.csv_path)
return True, "Attendance records cleared"
except Exception as e:
return False, f"Error clearing records: {str(e)}"
return True, "No records to clear"
# Function to capture webcam input
def capture_webcam():
cap = cv2.VideoCapture(0)
if not cap.isOpened():
return None
ret, frame = cap.read()
cap.release()
if ret:
return frame
return None
# Function for Gradio interface
def process_webcam(state):
if state is None:
# Default paths - update these to match your system
model_path = "best(attendance).pt"
csv_path = "attendance_data.csv"
state = AttendanceSystem(model_path, csv_path)
# Capture frame from webcam
frame = capture_webcam()
if frame is None:
return None, "Failed to capture webcam frame", "", state
# Process the frame
processed_frame, message, attendance_data, detected_names = state.process_frame(frame)
# Format attendance as HTML table for better display
if attendance_data:
attendance_html = "<table style='width:100%; border-collapse: collapse;'>"
attendance_html += "<tr><th style='border:1px solid black; padding:8px;'>Name</th><th style='border:1px solid black; padding:8px;'>Time</th></tr>"
for record in attendance_data:
name, time_str = record.split(" - ", 1)
attendance_html += f"<tr><td style='border:1px solid black; padding:8px;'>{name}</td><td style='border:1px solid black; padding:8px;'>{time_str}</td></tr>"
attendance_html += "</table>"
else:
attendance_html = "No attendance records."
return processed_frame, message, attendance_html, state
def clear_attendance_records(state):
if state is not None:
success, message = state.clear_attendance()
return message, "<table></table>", state
return "System not initialized", "<table></table>", None
def change_model_path(model_path, csv_path, state):
if not model_path or not csv_path:
return "Please provide both paths", state
state = AttendanceSystem(model_path, csv_path)
success, message = state.load_model()
return message, state
# Create Gradio interface - compatible with older Gradio versions
with gr.Blocks(title="Attendance System") as app:
gr.Markdown("# Automated Attendance System")
gr.Markdown("This system uses YOLO to detect and record attendance of individuals.")
with gr.Row():
with gr.Column(scale=2):
# For older Gradio versions, use a button to capture webcam
webcam_button = gr.Button("Capture from Webcam")
output_image = gr.Image(label="Processed Feed")
status_text = gr.Textbox(label="Status", value="Click 'Capture from Webcam' to start")
with gr.Column(scale=1):
# Attendance records and controls
attendance_display = gr.HTML(label="Attendance Records", value="No records yet.")
clear_button = gr.Button("Clear Attendance Records")
# Configuration options
with gr.Accordion("Configuration", open=False):
model_path_input = gr.Textbox(label="Model Path", value="best(attendance).pt")
csv_path_input = gr.Textbox(label="CSV Output Path", value="attendance_data.csv")
update_paths_button = gr.Button("Update Paths")
# State for storing the attendance system object
state = gr.State(None)
# Set up event handlers
webcam_button.click(process_webcam, inputs=[state],
outputs=[output_image, status_text, attendance_display, state])
clear_button.click(clear_attendance_records, inputs=[state],
outputs=[status_text, attendance_display, state])
update_paths_button.click(change_model_path, inputs=[model_path_input, csv_path_input, state],
outputs=[status_text, state])
# Launch the app
if __name__ == "__main__":
app.launch(share=True) # Set share=False if you don't want to create a public link