import face_recognition # used for recognizing face
import cv2 # used for accessing system camera
import os # used for accessing directory
from datetme import datetime, timedelta
import pandas as pd # This library is used for operations on dataframe and CSV file
import numpy as np # For handling numerical operations (like face distance comparison)

# Function to encode faces from images in a directory
def encode_faces(directory):
known_faces = []
known_names = []

print(os.listdir(directory))

# Loop through each file in the directory and check if it's a valid image format or not
for filename in os.listdir(directory):
if filename.endswith((".jpg", ".png")):
print("Filename:", filename)
image_path = os.path.join(directory, filename)
image = face_recognition.load_image_file(image_path)
print("image_path", image_path)

encodings = face_recognition.face_encodings(image)
print("encodings", encodings)
# Store all encodings for a single image
for encoding in encodings:
known_faces.append(encoding)
known_names.append(os.path.splitext(filename)[0]) # Use the filename without extension as the name
print(f"Loaded encoding for: {os.path.splitext(filename)[0]}") # Print loaded names for debugging
return known_faces, known_names

# Global set to track recognized faces in the current session
recognized_faces = set()

# Function to mark attendance in a CSV file and prevent duplicate entries
def mark_attendance(name, subject, frame_name, csv_directory):
now = datetime.now()
timestamp = now.strftime("%Y-%m-%d %H:%M:%S")

# Define CSV file path using subject name and current date
csv_filename = f"{subject}_attendance_{now.strftime('%Y%m%d')}.csv"
csv_path = os.path.join(csv_directory, csv_filename)

# If the file doesn't exist, create it with appropriate headers
if not os.path.exists(csv_path):
df = pd.DataFrame(columns=["Name", "Timestamp", "Framename"])
df.to_csv(csv_path, index=False)

# Read the existing CSV file
df = pd.read_csv(csv_path)

# Check if the name already exists in the CSV file for this session (no duplicates)
if name not in df["Name"].values:
recognized_faces.add(name) # Add the recognized face to the set
new_entry = pd.DataFrame({"Name": [name], "Timestamp": [timestamp], "Framename": [frame_name]})
df = pd.concat([df, new_entry], ignore_index=True)
df.to_csv(csv_path, index=False)

# Print the attendance entry
print(f"Attendance marked: {name} at {timestamp} (Framename: {frame_name})")
else:
print(f"Attendance for {name} already recorded.")

# Main function for face recognition attendance system
def recognize_faces(subject_name, csv_directory, duration=30):
global recognized_faces

# Initialize the video capture from webcam
video_capture = cv2.VideoCapture(0)

# Load known faces and names from the specified directory
known_faces, known_names = encode_faces("//home/feni//Desktop//Diploma_Clg_work//Sem5//Iml_microproject//known_faces")

start_time = datetime.now()
end_time = start_time + timedelta(seconds=duration)
print("Known faces loaded:", known_names)

while True:
# Check if the attendance session time is up
if datetime.now() >= end_time:
print("Attendance session successfully completed.")
break

ret, frame = video_capture.read()
# If the frame is not captured correctly, skip the loop
if not ret:
continue

# Detect face locations and face encodings in the current frame
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)

# Loop through detected faces and compare them with known faces
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
matches = face_recognition.compare_faces(known_faces, face_encoding)
face_distances = face_recognition.face_distance(known_faces, face_encoding)
name = "Unknown"
frame_name = None # Initialize frame name

# If there are matches, find the best match (smallest distance)
if True in matches:
best_match_index = np.argmin(face_distances) # Find the face with the smallest distance
if matches[best_match_index]:
name = known_names[best_match_index]
frame_name = f"{name}.jpg" # Set the frame name as the person's image filename
mark_attendance(name, subject_name, frame_name, csv_directory) # Mark attendance for the recognized person

# Draw a rectangle around the face and label it with the name
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, f"Enrollment: {name}", (left + 6, bottom + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)

# Display the video frame with the bounding boxes
cv2.imshow('Video', frame)

# Exit the loop if the 'q' key is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
print("Session manually terminated by user.")
break

# Release the video capture and close any OpenCV windows
video_capture.release()
cv2.destroyAllWindows()


# Function to find and clean the most recent CSV file by removing duplicate names
def remove_duplicate_entries(csv_directory, subject):
# Find the most recent CSV file for the given subject
files = [f for f in os.listdir(csv_directory) if f.startswith(subject) and f.endswith('.csv')]
if not files:
print(f"No attendance file found for subject: {subject}")
return
# Sort files by modified time and get the most recent file
latest_file = max([os.path.join(csv_directory, f) for f in files], key=os.path.getmtime)
print(f"Cleaning duplicates in: {latest_file}")

# Read the CSV file
df = pd.read_csv(latest_file)
# Drop duplicate names, keeping only the first occurrence
df_cleaned = df.drop_duplicates(subset='Name', keep='first')

# Save the cleaned dataframe back to the same CSV file
df_cleaned.to_csv(latest_file, index=False)
print(f"Duplicates removed. Updated file saved: {latest_file}")


# Run the face recognition attendance system with subject name input from user
if __name__ == "__main__":
subject_name = input("Please enter the subject name: ")
# Specify the directory where the CSV file will be saved
csv_directory = "//home//feni//Desktop//Diploma_Clg_work//Sem5//Iml_microproject//Recorded_attendace" # location of where the attendance CSV file is saved
# Ensure the directory exists
if not os.path.exists(csv_directory):
os.makedirs(csv_directory)

print("**** Press 'q' to stop session. ****")
print(f"Attendance session for {subject_name} started.")
recognize_faces(subject_name, csv_directory, duration=30)
# Call the function to remove duplicates in the most recent attendance file
remove_duplicate_entries(csv_directory, subject_name)

Comments

Popular posts from this blog

How to make personal ai using python || Jarvish ai using python

How to make travel website using html and css? ||How to make Tourism website using html and css? || How to make travel website ||How to make tourism website

How to make car racing game using python languge