-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
261 lines (211 loc) · 9.56 KB
/
Copy pathapp.py
File metadata and controls
261 lines (211 loc) · 9.56 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import cv2
import face_recognition
import os
import numpy as np
from datetime import datetime
import pandas as pd
import tkinter as tk
from tkinter import messagebox, Toplevel, Label, Entry, Button
import holidays
EMPLOYEES_FILE = 'employees.xlsx'
ATTENDANCE_FILE = 'attendance.xlsx'
FACES_DIR = 'faces'
os.makedirs(FACES_DIR, exist_ok=True)
# Initialize Excel Files
if not os.path.exists(EMPLOYEES_FILE):
df = pd.DataFrame(columns=['Employee ID', 'Name'])
df.to_excel(EMPLOYEES_FILE, index=False)
if not os.path.exists(ATTENDANCE_FILE):
df = pd.DataFrame(columns=['S.No.', 'Employee ID', 'Name', 'Date', 'Time', 'Attendance', 'Attendance Percentage'])
df.to_excel(ATTENDANCE_FILE, index=False)
def get_working_days_since_start_of_year():
import datetime as dt
today = dt.date.today()
start_date = dt.date(today.year, 1, 1)
in_holidays = holidays.country_holidays('IN', years=today.year)
working_days = 0
current_date = start_date
while current_date <= today:
if current_date.weekday() != 6 and current_date not in in_holidays: # 6 is Sunday
working_days += 1
current_date += dt.timedelta(days=1)
return max(1, working_days)
def load_encodings():
images = []
classNames = []
empIds = []
mylist = os.listdir(FACES_DIR)
for cl in mylist:
if cl.endswith(('.png', '.jpg', '.jpeg')):
curImg = cv2.imread(f'{FACES_DIR}/{cl}')
images.append(curImg)
name_ext = os.path.splitext(cl)[0]
parts = name_ext.split('_', 1)
if len(parts) == 2:
emp_id, name = parts
else:
emp_id = "Unknown"
name = name_ext
classNames.append(name)
empIds.append(emp_id)
encodeList = []
for img in images:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
try:
encoded_face = face_recognition.face_encodings(img)[0]
encodeList.append(encoded_face)
except IndexError:
encodeList.append(None)
valid_encodings = []
valid_names = []
valid_ids = []
for enc, name, emp_id in zip(encodeList, classNames, empIds):
if enc is not None:
valid_encodings.append(enc)
valid_names.append(name)
valid_ids.append(emp_id)
return valid_encodings, valid_names, valid_ids
def mark_attendance(emp_id, name):
try:
df = pd.read_excel(ATTENDANCE_FILE)
except:
df = pd.DataFrame(columns=['S.No.', 'Employee ID', 'Name', 'Date', 'Time', 'Attendance', 'Attendance Percentage'])
now = datetime.now()
date_str = now.strftime('%d-%m-%Y')
time_str = now.strftime('%H:%M:%S')
# Check if already marked today
df['Employee ID'] = df['Employee ID'].astype(str)
already_marked = df[(df['Employee ID'] == str(emp_id)) & (df['Date'] == date_str)]
if not already_marked.empty:
return False, "Already marked today"
total_present = len(df[df['Employee ID'] == str(emp_id)]) + 1
total_working_days = get_working_days_since_start_of_year()
percentage = (total_present / total_working_days) * 100
s_no = len(df) + 1
new_row = {
'S.No.': s_no,
'Employee ID': str(emp_id),
'Name': name,
'Date': date_str,
'Time': time_str,
'Attendance': 'Present',
'Attendance Percentage': round(percentage, 2)
}
new_df = pd.DataFrame([new_row])
df = pd.concat([df, new_df], ignore_index=True)
df.to_excel(ATTENDANCE_FILE, index=False)
return True, f"Marked ({round(percentage, 2)}%)"
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Face Recognition Attendance System")
self.geometry("400x300")
Label(self, text="Attendance System", font=("Helvetica", 16)).pack(pady=20)
Button(self, text="Login (Face Recognition)", width=30, height=2, command=self.login).pack(pady=10)
Button(self, text="New User Registration", width=30, height=2, command=self.new_user_registration).pack(pady=10)
def new_user_registration(self):
reg_win = Toplevel(self)
reg_win.title("Register New User")
reg_win.geometry("300x250")
Label(reg_win, text="Employee ID:").pack(pady=5)
emp_id_entry = Entry(reg_win)
emp_id_entry.pack(pady=5)
Label(reg_win, text="Name:").pack(pady=5)
name_entry = Entry(reg_win)
name_entry.pack(pady=5)
def capture_and_register():
emp_id = emp_id_entry.get().strip()
name = name_entry.get().strip()
if not emp_id or not name:
messagebox.showerror("Error", "Please enter both fields")
return
# Check if emp_id exists
try:
emp_df = pd.read_excel(EMPLOYEES_FILE)
if str(emp_id) in emp_df['Employee ID'].astype(str).values:
messagebox.showerror("Error", "Employee ID already exists!")
return
except:
pass
messagebox.showinfo("Instructions", "Look at the camera. Press 'SPACE' to capture your face, or 'ESC' to cancel.")
cap = cv2.VideoCapture(0)
img_path = os.path.join(FACES_DIR, f"{emp_id}_{name}.jpg")
while True:
success, img = cap.read()
if not success:
break
# Draw instructions
cv2.putText(img, "Press SPACE to Capture, ESC to Cancel", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.imshow('Registration - Capture Face', img)
key = cv2.waitKey(1) & 0xFF
if key == 32: # SPACE
cv2.imwrite(img_path, img)
break
elif key == 27: # ESC
cap.release()
cv2.destroyAllWindows()
return
cap.release()
cv2.destroyAllWindows()
# Save to Excel
try:
emp_df = pd.read_excel(EMPLOYEES_FILE)
except:
emp_df = pd.DataFrame(columns=['Employee ID', 'Name'])
new_row = {'Employee ID': emp_id, 'Name': name}
emp_df = pd.concat([emp_df, pd.DataFrame([new_row])], ignore_index=True)
emp_df.to_excel(EMPLOYEES_FILE, index=False)
messagebox.showinfo("Success", "User Registered successfully!")
reg_win.destroy()
Button(reg_win, text="Register and Capture Face", command=capture_and_register).pack(pady=20)
def login(self):
encodings, names, emp_ids = load_encodings()
if not encodings:
messagebox.showerror("Error", "No users registered yet.")
return
cap = cv2.VideoCapture(0)
while True:
success, img = cap.read()
if not success:
break
imgS = cv2.resize(img, (0,0), None, 0.25, 0.25)
imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
faces_in_frame = face_recognition.face_locations(imgS)
encoded_faces = face_recognition.face_encodings(imgS, faces_in_frame)
for encode_face, faceloc in zip(encoded_faces, faces_in_frame):
matches = face_recognition.compare_faces(encodings, encode_face)
faceDist = face_recognition.face_distance(encodings, encode_face)
if len(faceDist) > 0:
matchIndex = np.argmin(faceDist)
if matches[matchIndex]:
name = names[matchIndex]
emp_id = emp_ids[matchIndex]
y1, x2, y2, x1 = faceloc
y1, x2, y2, x1 = y1*4, x2*4, y2*4, x1*4
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
success_mark, msg = mark_attendance(emp_id, name)
display_text = f"{name}: {msg}"
cv2.putText(img, display_text, (x1, y2+25), cv2.FONT_HERSHEY_COMPLEX, 0.7, (255,0,0), 2)
cv2.imshow('Login - Face Recognition', img)
cv2.waitKey(2000)
cap.release()
cv2.destroyAllWindows()
if success_mark:
messagebox.showinfo("Success", f"Welcome {name}! Attendance marked.\n{msg}")
else:
messagebox.showwarning("Warning", f"{name}, {msg}")
return
else:
y1, x2, y2, x1 = faceloc
y1, x2, y2, x1 = y1*4, x2*4, y2*4, x1*4
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.putText(img, "Unknown", (x1, y2+25), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
cv2.putText(img, "Press ESC to Cancel", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.imshow('Login - Face Recognition', img)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
app = App()
app.mainloop()