File size: 28,473 Bytes
282e9e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195c967
 
282e9e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efd1931
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
# # 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