ArchiMathur commited on
Commit
e920ad7
·
verified ·
1 Parent(s): 726d6d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -532
app.py CHANGED
@@ -1,508 +1,11 @@
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
@@ -623,33 +126,21 @@ class AttendanceSystem:
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 = "best(attendance).pt"
643
  csv_path = "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:
@@ -683,17 +174,18 @@ def change_model_path(model_path, csv_path, state):
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
@@ -710,15 +202,28 @@ with gr.Blocks(title="Attendance System") as app:
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
 
1
+ import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import cv2
3
  import pandas as pd
4
  import gradio as gr
5
  from ultralytics import YOLO
6
  from datetime import datetime, timedelta
 
7
  import numpy as np
8
 
 
9
  class AttendanceSystem:
10
  def __init__(self, model_path, csv_path):
11
  self.model_path = model_path
 
126
  return True, "No records to clear"
127
 
128
 
129
+ # Function for Gradio interface - process images from webcam
130
+ def process_webcam_image(image, state):
 
 
 
 
 
 
 
 
 
 
 
 
131
  if state is None:
132
+ # Default paths - update these to match your Hugging Face deployment
133
+ model_path = "best(attendance).pt" # Make sure to upload this model to your Space
134
  csv_path = "attendance_data.csv"
135
  state = AttendanceSystem(model_path, csv_path)
136
+ # Load model immediately
137
+ state.load_model()
138
 
139
+ if image is None:
140
+ return None, "No image received", "", state
 
 
141
 
142
  # Process the frame
143
+ processed_frame, message, attendance_data, detected_names = state.process_frame(image)
144
 
145
  # Format attendance as HTML table for better display
146
  if attendance_data:
 
174
  return message, state
175
 
176
 
177
+ # Create Gradio interface that works on Hugging Face
178
  with gr.Blocks(title="Attendance System") as app:
179
  gr.Markdown("# Automated Attendance System")
180
  gr.Markdown("This system uses YOLO to detect and record attendance of individuals.")
181
 
182
  with gr.Row():
183
  with gr.Column(scale=2):
184
+ # Use Gradio's webcam component which captures on the client side
185
+ input_image = gr.Image(source="webcam", label="Webcam Feed")
186
+ process_button = gr.Button("Process Image")
187
  output_image = gr.Image(label="Processed Feed")
188
+ status_text = gr.Textbox(label="Status", value="Capture an image and click 'Process Image'")
189
 
190
  with gr.Column(scale=1):
191
  # Attendance records and controls
 
202
  state = gr.State(None)
203
 
204
  # Set up event handlers
205
+ process_button.click(
206
+ process_webcam_image,
207
+ inputs=[input_image, state],
208
+ outputs=[output_image, status_text, attendance_display, state]
209
+ )
210
+
211
+ clear_button.click(
212
+ clear_attendance_records,
213
+ inputs=[state],
214
+ outputs=[status_text, attendance_display, state]
215
+ )
216
+
217
+ update_paths_button.click(
218
+ change_model_path,
219
+ inputs=[model_path_input, csv_path_input, state],
220
+ outputs=[status_text, state]
221
+ )
222
+
223
+ # Create a requirements.txt file for Hugging Face
224
+ with open('requirements.txt', 'w') as f:
225
+ f.write('opencv-python-headless\npandas\ngradio\nultralytics')
226
 
227
  # Launch the app
228
  if __name__ == "__main__":
229
+ app.launch() # Remove share=True for Hugging Face deployment