ArchiMathur commited on
Commit
a401535
·
verified ·
1 Parent(s): efd1931

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +724 -0
app.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # import cv2
2
+ # # from ultralytics import YOLO
3
+ # # import time
4
+ # # from datetime import datetime, timedelta
5
+ # # import numpy
6
+ # # import csv
7
+ # #
8
+ # # # Load YOLO model
9
+ # # model = YOLO("D:\\live attendance\\best(attendance).pt")
10
+ # #
11
+ # # # Initialize webcam
12
+ # # cap = cv2.VideoCapture(0) # 0 is usually the default camera
13
+ # #
14
+ # # # Dictionary to store attendance records
15
+ # # attendance_records = {}
16
+ # #
17
+ # # # CSV file to store attendance data
18
+ # # csv_file = open(r"D:\\live attendance\\attendance_data.csv", "w", newline="")
19
+ # # csv_writer = csv.writer(csv_file)
20
+ # # csv_writer.writerow(["Name", "Time"])
21
+ # #
22
+ # #
23
+ # # while True:
24
+ # # # Read a frame from the webcam
25
+ # # ret, frame = cap.read()
26
+ # # if not ret:
27
+ # # print("Failed to capture image")
28
+ # # break
29
+ # #
30
+ # # # Detect objects
31
+ # # results = model(frame)
32
+ # #
33
+ # # # Iterate through results
34
+ # # for result in results:
35
+ # # boxes = result.boxes
36
+ # # for box in boxes: # Iterate through detected boxes
37
+ # # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
38
+ # # class_id = int(box.cls[0]) # Get the class ID
39
+ # # confidence = box.conf[0] # Get the confidence score
40
+ # #
41
+ # # # Get the class name from YOLO class names
42
+ # # class_name = model.names[class_id]
43
+ # #
44
+ # # # Draw rectangle around detected object
45
+ # # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
46
+ # # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
47
+ # # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
48
+ # #
49
+ # # # Check if attendance can be marked
50
+ # # current_time = datetime.now()
51
+ # # if class_name not in attendance_records:
52
+ # # # Mark attendance for the first time
53
+ # # attendance_records[class_name] = current_time
54
+ # # print(f"Attendance marked for {class_name} at {current_time}")
55
+ # # # Write to CSV
56
+ # # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")])
57
+ # # else:
58
+ # # last_attendance_time = attendance_records[class_name]
59
+ # # # Check if 24 hours have passed
60
+ # # if current_time - last_attendance_time >= timedelta(days=1):
61
+ # # attendance_records[class_name] = current_time
62
+ # # print(f"Attendance marked for {class_name} at {current_time}")
63
+ # #
64
+ # # # Write to CSV
65
+ # # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")])
66
+ # # # csv_file.flush() # Ensure it's saved immediately
67
+ # #
68
+ # # # Show the frame with detections
69
+ # # cv2.imshow("Detected Objects", frame)
70
+ # #
71
+ # # # Break the loop on 'q' key press
72
+ # # if cv2.waitKey(1) & 0xFF == ord('q'):
73
+ # # break
74
+ # #
75
+ # # # Release the video capture object and close all OpenCV windows
76
+ # # cap.release()
77
+ # # cv2.destroyAllWindows()
78
+ # #
79
+ # # # import cv2
80
+ # # # from ultralytics import YOLO
81
+ # # # import time
82
+ # # # from datetime import datetime, timedelta
83
+ # # # import csv
84
+ # # #
85
+ # # # # Load YOLO model
86
+ # # # model = YOLO("D:\\live attendance\\best(attendance).pt")
87
+ # # #
88
+ # # # # Initialize webcam
89
+ # # # cap = cv2.VideoCapture(0) # 0 is usually the default camera
90
+ # # #
91
+ # # # # Dictionary to store attendance records
92
+ # # # attendance_records = {}
93
+ # # #
94
+ # # # # CSV file to store attendance data
95
+ # # # # csv_file = open("D:\\live attendance\\attendance_data.csv", "w", newline="")
96
+ # # # # csv_writer = csv.writer(csv_file)
97
+ # # # # csv_writer.writerow(["Name", "Time"])
98
+ # # #
99
+ # # # with open('D:\\live attendance\\attendance_data.csv', 'w', newline='') as csv_file:
100
+ # # # writer = csv.writer(csv_file)
101
+ # # # writer.writerows(["Name", "Time"])
102
+ # # #
103
+ # # # while True:
104
+ # # # # Read a frame from the webcam
105
+ # # # ret, frame = cap.read()
106
+ # # # if not ret:
107
+ # # # print("Failed to capture image")
108
+ # # # break
109
+ # # #
110
+ # # # # Detect objects
111
+ # # # results = model(frame)
112
+ # # #
113
+ # # # # Iterate through results
114
+ # # # for result in results:
115
+ # # # boxes = result.boxes
116
+ # # # for box in boxes: # Iterate through detected boxes
117
+ # # # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
118
+ # # # class_id = int(box.cls[0]) # Get the class ID
119
+ # # # confidence = box.conf[0] # Get the confidence score
120
+ # # #
121
+ # # # # Get the class name from YOLO class names
122
+ # # # class_name = model.names[class_id]
123
+ # # #
124
+ # # # # Draw rectangle around detected object
125
+ # # # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
126
+ # # # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
127
+ # # # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
128
+ # # #
129
+ # # # # Check if attendance can be marked
130
+ # # # current_time = datetime.now()
131
+ # # # if class_name not in attendance_records:
132
+ # # # # Mark attendance for the first time
133
+ # # # attendance_records[class_name] = current_time
134
+ # # # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")]) # Save to CSV
135
+ # # # print(f"Attendance marked for {class_name} at {current_time}")
136
+ # # # else:
137
+ # # # last_attendance_time = attendance_records[class_name]
138
+ # # # # Check if 24 hours have passed
139
+ # # # if current_time - last_attendance_time >= timedelta(days=1):
140
+ # # # attendance_records[class_name] = current_time
141
+ # # # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")]) # Save to CSV
142
+ # # # print(f"Attendance marked for {class_name} at {current_time}")
143
+ # # #
144
+ # # # # Show the frame with detections
145
+ # # # cv2.imshow("Detected Objects", frame)
146
+ # # #
147
+ # # # # Break the loop on 'q' key press
148
+ # # # if cv2.waitKey(1) & 0xFF == ord('q'):
149
+ # # # break
150
+ # # #
151
+ # # # # Release the video capture object and close all OpenCV windows
152
+ # # # cap.release()
153
+ # # # csv_file.close() # Close the CSV file
154
+ # # # cv2.destroyAllWindows()
155
+ #
156
+ # # import cv2
157
+ # # from ultralytics import YOLO
158
+ # # from datetime import datetime, timedelta
159
+ # # import csv
160
+ # #
161
+ # # # Load YOLO model
162
+ # # model = YOLO("D:\\live attendance\\best(attendance).pt")
163
+ # #
164
+ # # # Initialize webcam
165
+ # # cap = cv2.VideoCapture(0) # 0 is usually the default camera
166
+ # #
167
+ # # # Dictionary to store attendance records
168
+ # # attendance_records = {}
169
+ # #
170
+ # # # CSV file to store attendance data
171
+ # # csv_file_path = r"D:\\live attendance\\attendance_data.csv"
172
+ # # with open(csv_file_path, "a", newline="") as csv_file:#think here
173
+ # # csv_writer = csv.writer(csv_file)
174
+ # #
175
+ # #
176
+ # # while True:
177
+ # # # Read a frame from the webcam
178
+ # # ret, frame = cap.read()
179
+ # # if not ret:
180
+ # # print("Failed to capture image")
181
+ # # break
182
+ # #
183
+ # # # Detect objects
184
+ # # results = model(frame)
185
+ # #
186
+ # # # Iterate through results
187
+ # # for result in results:
188
+ # # boxes = result.boxes
189
+ # # for box in boxes: # Iterate through detected boxes
190
+ # # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
191
+ # # class_id = int(box.cls[0]) # Get the class ID
192
+ # # confidence = box.conf[0] # Get the confidence score
193
+ # #
194
+ # # # Get the class name from YOLO class names
195
+ # # class_name = model.names[class_id]
196
+ # #
197
+ # # # Draw rectangle around detected object
198
+ # # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
199
+ # # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
200
+ # # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
201
+ # #
202
+ # # # Check if attendance can be marked
203
+ # # current_time = datetime.now()
204
+ # # if class_name not in attendance_records:
205
+ # # # Mark attendance for the first time
206
+ # # attendance_records[class_name] = current_time#think here
207
+ # # print(f"Attendance marked for {class_name} at {current_time}")
208
+ # # # Write to CSV
209
+ # # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")])
210
+ # # else:
211
+ # # last_attendance_time = attendance_records[class_name]
212
+ # # # Check if 24 hours have passed
213
+ # # if current_time - last_attendance_time >= timedelta(days=1):
214
+ # # attendance_records[class_name] = current_time
215
+ # # print(f"Attendance marked for {class_name} at {current_time}")
216
+ # # # Write to CSV
217
+ # # csv_writer.writerow([class_name, current_time.strftime("%Y-%m-%d %H:%M:%S")])
218
+ # #
219
+ # # # Show the frame with detections
220
+ # # cv2.imshow("Detected Objects", frame)
221
+ # #
222
+ # # # Break the loop on 'q' key press
223
+ # # if cv2.waitKey(1) & 0xFF == ord('q'):
224
+ # # break
225
+ # #
226
+ # # # Release the video capture object and close all OpenCV windows
227
+ # # cap.release()
228
+ # # cv2.destroyAllWindows()
229
+ #
230
+ #
231
+ # # import cv2
232
+ # # import pandas as pd
233
+ # # from ultralytics import YOLO
234
+ # # from datetime import datetime, timedelta
235
+ # #
236
+ # # # Load the model
237
+ # # model = YOLO("D:\\live attendance\\best(attendance).pt")
238
+ # #
239
+ # # # Open camera (0 for default camera, 1 for external camera)
240
+ # # cap = cv2.VideoCapture(0)
241
+ # #
242
+ # # # Initialize lists to store class names and timestamps
243
+ # # class_names_list = []
244
+ # # time_list = []
245
+ # #
246
+ # # # Initialize a list to keep track of last attendance times
247
+ # # last_attendance_times = []
248
+ # #
249
+ # # while True:
250
+ # # # Read a frame from the webcam
251
+ # # ret, frame = cap.read()
252
+ # # if not ret:
253
+ # # print("Failed to capture image")
254
+ # # break
255
+ # #
256
+ # # # Detect objects
257
+ # # results = model(frame)
258
+ # #
259
+ # # # Iterate through results
260
+ # # for result in results:
261
+ # # boxes = result.boxes
262
+ # # for box in boxes: # Iterate through detected boxes
263
+ # # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
264
+ # # class_id = int(box.cls[0]) # Get the class ID
265
+ # # confidence = box.conf[0] # Get the confidence score
266
+ # #
267
+ # # # Get the class name from YOLO class names
268
+ # # class_name = model.names[class_id]
269
+ # #
270
+ # # # Draw rectangle around detected object
271
+ # # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
272
+ # # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
273
+ # # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
274
+ # #
275
+ # # # Get the current time
276
+ # # current_time = datetime.now()
277
+ # # current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
278
+ # #
279
+ # # # Check if the class name is already in the list
280
+ # # if class_name not in class_names_list:
281
+ # # # Mark attendance for the first time
282
+ # # class_names_list.append(class_name)
283
+ # # time_list.append(current_time_str)
284
+ # # last_attendance_times.append( class_names_list+time_list) # Store the time of attendance
285
+ # # print(f"Attendance marked for {class_name} at {current_time_str}")
286
+ # # else:
287
+ # #
288
+ # # # Check if 24 hours have passed since last recorded attendance
289
+ # # if current_time - last_attendance_times[class_name] >= timedelta(days=1):
290
+ # # last_attendance_times[class_name] = current_time # Update the last attendance time
291
+ # # time_list[class_names_list.index(class_name)] = current_time_str # Update the time in the list
292
+ # # print(f"Attendance marked for {class_name} at {current_time_str}")
293
+ # #
294
+ # # # Display output
295
+ # # cv2.imshow("Object Detection", frame)
296
+ # #
297
+ # # # Exit on 'q' press
298
+ # # if cv2.waitKey(1) & 0xFF == ord('q'):
299
+ # # break
300
+ # #
301
+ # # # Release camera and close window
302
+ # # cap.release()
303
+ # # cv2.destroyAllWindows()
304
+ # #
305
+ # # # Save class names and timestamps to CSV
306
+ # # df = pd.DataFrame({
307
+ # # "Class Name": class_names_list,
308
+ # # "Time": time_list
309
+ # # })
310
+ # # df.to_csv("D:\\live attendance\\attendance_data.csv", index=False)
311
+ # #
312
+ # # print("Detections saved ")
313
+ #
314
+ # # import cv2
315
+ # # import pandas as pd
316
+ # # from ultralytics import YOLO
317
+ # # from datetime import datetime
318
+ # #
319
+ # # # Load the YOLO model
320
+ # # model = YOLO("D:\\live attendance\\best(attendance).pt")
321
+ # #
322
+ # # # Open camera (0 for default camera, 1 for external camera)
323
+ # # cap = cv2.VideoCapture(0)
324
+ # #
325
+ # # # Initialize lists to store class names and timestamps
326
+ # # class_names_list = []
327
+ # # time_list = []
328
+ # #
329
+ # # while True:
330
+ # # # Read a frame from the webcam
331
+ # # ret, frame = cap.read()
332
+ # # if not ret:
333
+ # # print("Failed to capture image")
334
+ # # break
335
+ # #
336
+ # # # Detect objects
337
+ # # results = model(frame)
338
+ # #
339
+ # # # Check if any results are detected
340
+ # # if results: # Check if results are not empty
341
+ # # for result in results:
342
+ # # boxes = result.boxes
343
+ # # for box in boxes: # Iterate through detected boxes
344
+ # # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
345
+ # # class_id = int(box.cls[0]) # Get the class ID
346
+ # # confidence = box.conf[0] # Get the confidence score
347
+ # #
348
+ # # # Get the class name from YOLO class names
349
+ # # class_name = model.names[class_id]
350
+ # #
351
+ # # # Draw rectangle around detected object
352
+ # # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
353
+ # # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
354
+ # # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
355
+ # #
356
+ # # # Get the current time
357
+ # # current_time = datetime.now()
358
+ # # current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
359
+ # #
360
+ # # # Record attendance for every detected class
361
+ # # if class_name not in class_names_list:
362
+ # # class_names_list.append(class_name)
363
+ # # time_list.append(current_time_str)
364
+ # # print(f"Attendance marked for {class_name} at {current_time_str}")
365
+ # # else:
366
+ # # print(f"{class_name} already recorded.")
367
+ # #
368
+ # # else:
369
+ # # print("No results detected.")
370
+ # #
371
+ # # # Display output
372
+ # # cv2.imshow("Object Detection", frame)
373
+ # #
374
+ # # # Exit on 'q' press
375
+ # # if cv2.waitKey(1) & 0xFF == ord('q'):
376
+ # # break
377
+ # #
378
+ # # # Release camera and close window
379
+ # # cap.release()
380
+ # # cv2.destroyAllWindows()
381
+ # #
382
+ # # # Check if lists are populated before saving
383
+ # # print("Class Names:", class_names_list)
384
+ # # print("Time List:", time_list)
385
+ # #
386
+ # # # Save class names and timestamps to CSV
387
+ # # if class_names_list and time_list: # Only save if there is data
388
+ # # df = pd.DataFrame({
389
+ # # "Class Name": class_names_list,
390
+ # # "Time": time_list
391
+ # # })
392
+ # # try:
393
+ # # df.to_csv("D:\\live attendance\\attendance_data.csv", index=False)
394
+ # # print("Detections saved to CSV.")
395
+ # # except Exception as e:
396
+ # # print(f"Error saving to CSV: {e}")
397
+ # # else:
398
+ # # print("No attendance data to save.")
399
+ #
400
+ #
401
+ # import cv2
402
+ # import pandas as pd
403
+ # from ultralytics import YOLO
404
+ # from datetime import datetime, timedelta
405
+ #
406
+ # # Load the YOLO model
407
+ # model = YOLO("D:\\live attendance\\best(attendance).pt")
408
+ #
409
+ # # model = YOLO("C:\\Users\\Dell\\Downloads\\best (2).pt")
410
+ #
411
+ # # Open camera (0 for default camera, 1 for external camera)
412
+ # cap = cv2.VideoCapture(0)
413
+ #
414
+ # # Initialize lists to store class names and timestamps
415
+ # class_names_list = []
416
+ # time_list = []
417
+ #
418
+ # while True:
419
+ # # Read a frame from the webcam
420
+ # ret, frame = cap.read()
421
+ # if not ret:
422
+ # print("Failed to capture image")
423
+ # break
424
+ #
425
+ # # Detect objects
426
+ # results = model(frame)
427
+ #
428
+ # # Check if any results are detected
429
+ # if results: # Check if results are not empty
430
+ # for result in results:
431
+ # boxes = result.boxes
432
+ # for box in boxes: # Iterate through detected boxes
433
+ # x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int) # Extract coordinates
434
+ # class_id = int(box.cls[0]) # Get the class ID
435
+ # confidence = box.conf[0] # Get the confidence score
436
+ #
437
+ # # Get the class name from YOLO class names
438
+ # class_name = model.names[class_id]
439
+ #
440
+ # # Draw rectangle around detected object
441
+ # cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw rectangle
442
+ # cv2.putText(frame, f"{class_name}: {confidence:.2f}", (x1, y1 - 10),
443
+ # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
444
+ #
445
+ # # Get the current time
446
+ # current_time = datetime.now()
447
+ # current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
448
+ #
449
+ # # Check if the class has been recorded and if 24 hours have passed
450
+ # if class_name in class_names_list:
451
+ # index = class_names_list.index(class_name)
452
+ # last_recorded_time = datetime.strptime(time_list[index], "%Y-%m-%d %H:%M:%S")
453
+ #
454
+ # # If less than 24 hours have passed since the last recording
455
+ # if (current_time - last_recorded_time) < timedelta(hours=24):
456
+ # print(f"{class_name} already recorded within the last 24 hours.")
457
+ # continue
458
+ #
459
+ # # Record attendance for the class
460
+ # class_names_list.append(class_name)
461
+ # time_list.append(current_time_str)
462
+ # print(f"Attendance marked for {class_name} at {current_time_str}")
463
+ #
464
+ # else:
465
+ # print("No results detected.")
466
+ #
467
+ # # Display output
468
+ # cv2.imshow("Object Detection", frame)
469
+ #
470
+ # # Exit on 'q' press
471
+ # if cv2.waitKey(1) & 0xFF == ord('q'):
472
+ # break
473
+ #
474
+ # # Release camera and close window
475
+ # cap.release()
476
+ # cv2.destroyAllWindows()
477
+ #
478
+ # # Check if lists are populated before saving
479
+ # print("Class Names:", class_names_list)
480
+ # print("Time List:", time_list)
481
+ #
482
+ # # Save class names and timestamps to CSV
483
+ # if class_names_list and time_list: # Only save if there is data
484
+ # df = pd.DataFrame({
485
+ # "Class Name": class_names_list,
486
+ # "Time": time_list
487
+ # })
488
+ # try:
489
+ # df.to_csv("D:\\live attendance\\attendance_data.csv", index=False)
490
+ # print("Detections saved to CSV.")
491
+ # except Exception as e:
492
+ # print(f"Error saving to CSV: {e}")
493
+ # else:
494
+ # print("No attendance data to save.")
495
+
496
+
497
+ import cv2
498
+ import pandas as pd
499
+ import gradio as gr
500
+ from ultralytics import YOLO
501
+ from datetime import datetime, timedelta
502
+ import os
503
+ import numpy as np
504
+
505
+
506
+ class AttendanceSystem:
507
+ def __init__(self, model_path, csv_path):
508
+ self.model_path = model_path
509
+ self.csv_path = csv_path
510
+ self.model = None
511
+ self.class_names_list = []
512
+ self.time_list = []
513
+ self.load_previous_attendance()
514
+
515
+ def load_model(self):
516
+ """Load the YOLO model"""
517
+ if self.model is None:
518
+ try:
519
+ self.model = YOLO(self.model_path)
520
+ return True, "Model loaded successfully!"
521
+ except Exception as e:
522
+ return False, f"Error loading model: {str(e)}"
523
+ return True, "Model already loaded"
524
+
525
+ def load_previous_attendance(self):
526
+ """Load previous attendance data if CSV exists"""
527
+ if os.path.exists(self.csv_path):
528
+ try:
529
+ df = pd.read_csv(self.csv_path)
530
+ if not df.empty:
531
+ self.class_names_list = df["Class Name"].tolist()
532
+ self.time_list = df["Time"].tolist()
533
+ return True, f"Loaded {len(self.class_names_list)} previous attendance records"
534
+ except Exception as e:
535
+ return False, f"Error loading previous attendance: {str(e)}"
536
+ return False, "No previous attendance data found"
537
+
538
+ def process_frame(self, frame):
539
+ """Process a single frame and update attendance"""
540
+ if self.model is None:
541
+ success, message = self.load_model()
542
+ if not success:
543
+ return frame, message, [], []
544
+
545
+ # Create a copy of the frame to draw on
546
+ display_frame = frame.copy()
547
+
548
+ # Store detected names in this frame
549
+ detected_names = []
550
+
551
+ # Detect objects
552
+ results = self.model(frame)
553
+
554
+ # Check if any results are detected
555
+ if results:
556
+ for result in results:
557
+ boxes = result.boxes
558
+ for box in boxes:
559
+ x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int)
560
+ class_id = int(box.cls[0])
561
+ confidence = float(box.conf[0])
562
+
563
+ # Get the class name from YOLO class names
564
+ class_name = self.model.names[class_id]
565
+ detected_names.append(class_name)
566
+
567
+ # Draw rectangle around detected object
568
+ cv2.rectangle(display_frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
569
+ cv2.putText(display_frame, f"{class_name}: {confidence:.2f}",
570
+ (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
571
+
572
+ # Get the current time
573
+ current_time = datetime.now()
574
+ current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
575
+
576
+ # Check if the class has been recorded already
577
+ person_already_recorded = False
578
+ for idx, name in enumerate(self.class_names_list):
579
+ if name == class_name:
580
+ last_recorded_time = datetime.strptime(self.time_list[idx], "%Y-%m-%d %H:%M:%S")
581
+ # If less than 24 hours have passed since the last recording
582
+ if (current_time - last_recorded_time) < timedelta(hours=24):
583
+ person_already_recorded = True
584
+ break
585
+
586
+ # Record attendance if not already recorded in the last 24 hours
587
+ if not person_already_recorded:
588
+ self.class_names_list.append(class_name)
589
+ self.time_list.append(current_time_str)
590
+ self.save_attendance()
591
+
592
+ # Create attendance list for display
593
+ attendance_data = []
594
+ for name, time_str in zip(self.class_names_list, self.time_list):
595
+ attendance_data.append(f"{name} - {time_str}")
596
+
597
+ return display_frame, f"Detected: {', '.join(detected_names) if detected_names else 'None'}", attendance_data, detected_names
598
+
599
+ def save_attendance(self):
600
+ """Save attendance data to CSV"""
601
+ if self.class_names_list and self.time_list:
602
+ df = pd.DataFrame({
603
+ "Class Name": self.class_names_list,
604
+ "Time": self.time_list
605
+ })
606
+ try:
607
+ df.to_csv(self.csv_path, index=False)
608
+ return True, "Attendance saved to CSV"
609
+ except Exception as e:
610
+ return False, f"Error saving to CSV: {str(e)}"
611
+ return False, "No attendance data to save"
612
+
613
+ def clear_attendance(self):
614
+ """Clear attendance records"""
615
+ self.class_names_list = []
616
+ self.time_list = []
617
+ if os.path.exists(self.csv_path):
618
+ try:
619
+ os.remove(self.csv_path)
620
+ return True, "Attendance records cleared"
621
+ except Exception as e:
622
+ return False, f"Error clearing records: {str(e)}"
623
+ return True, "No records to clear"
624
+
625
+
626
+ # Function to capture webcam input
627
+ def capture_webcam():
628
+ cap = cv2.VideoCapture(0)
629
+ if not cap.isOpened():
630
+ return None
631
+ ret, frame = cap.read()
632
+ cap.release()
633
+ if ret:
634
+ return frame
635
+ return None
636
+
637
+
638
+ # Function for Gradio interface
639
+ def process_webcam(state):
640
+ if state is None:
641
+ # Default paths - update these to match your system
642
+ model_path = "D:\\live attendance\\best(attendance).pt"
643
+ csv_path = "D:\\live attendance\\attendance_data.csv"
644
+ state = AttendanceSystem(model_path, csv_path)
645
+
646
+ # Capture frame from webcam
647
+ frame = capture_webcam()
648
+ if frame is None:
649
+ return None, "Failed to capture webcam frame", "", state
650
+
651
+ # Process the frame
652
+ processed_frame, message, attendance_data, detected_names = state.process_frame(frame)
653
+
654
+ # Format attendance as HTML table for better display
655
+ if attendance_data:
656
+ attendance_html = "<table style='width:100%; border-collapse: collapse;'>"
657
+ attendance_html += "<tr><th style='border:1px solid black; padding:8px;'>Name</th><th style='border:1px solid black; padding:8px;'>Time</th></tr>"
658
+
659
+ for record in attendance_data:
660
+ name, time_str = record.split(" - ", 1)
661
+ 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>"
662
+
663
+ attendance_html += "</table>"
664
+ else:
665
+ attendance_html = "No attendance records."
666
+
667
+ return processed_frame, message, attendance_html, state
668
+
669
+
670
+ def clear_attendance_records(state):
671
+ if state is not None:
672
+ success, message = state.clear_attendance()
673
+ return message, "<table></table>", state
674
+ return "System not initialized", "<table></table>", None
675
+
676
+
677
+ def change_model_path(model_path, csv_path, state):
678
+ if not model_path or not csv_path:
679
+ return "Please provide both paths", state
680
+
681
+ state = AttendanceSystem(model_path, csv_path)
682
+ success, message = state.load_model()
683
+ return message, state
684
+
685
+
686
+ # Create Gradio interface - compatible with older Gradio versions
687
+ with gr.Blocks(title="Attendance System") as app:
688
+ gr.Markdown("# Automated Attendance System")
689
+ gr.Markdown("This system uses YOLO to detect and record attendance of individuals.")
690
+
691
+ with gr.Row():
692
+ with gr.Column(scale=2):
693
+ # For older Gradio versions, use a button to capture webcam
694
+ webcam_button = gr.Button("Capture from Webcam")
695
+ output_image = gr.Image(label="Processed Feed")
696
+ status_text = gr.Textbox(label="Status", value="Click 'Capture from Webcam' to start")
697
+
698
+ with gr.Column(scale=1):
699
+ # Attendance records and controls
700
+ attendance_display = gr.HTML(label="Attendance Records", value="No records yet.")
701
+ clear_button = gr.Button("Clear Attendance Records")
702
+
703
+ # Configuration options
704
+ with gr.Accordion("Configuration", open=False):
705
+ model_path_input = gr.Textbox(label="Model Path", value="D:\\live attendance\\best(attendance).pt")
706
+ csv_path_input = gr.Textbox(label="CSV Output Path", value="D:\\live attendance\\attendance_data.csv")
707
+ update_paths_button = gr.Button("Update Paths")
708
+
709
+ # State for storing the attendance system object
710
+ state = gr.State(None)
711
+
712
+ # Set up event handlers
713
+ webcam_button.click(process_webcam, inputs=[state],
714
+ outputs=[output_image, status_text, attendance_display, state])
715
+
716
+ clear_button.click(clear_attendance_records, inputs=[state],
717
+ outputs=[status_text, attendance_display, state])
718
+
719
+ update_paths_button.click(change_model_path, inputs=[model_path_input, csv_path_input, state],
720
+ outputs=[status_text, state])
721
+
722
+ # Launch the app
723
+ if __name__ == "__main__":
724
+ app.launch(share=True) # Set share=False if you don't want to create a public link