Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,7 @@ import gradio as gr
|
|
| 2 |
import cv2
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
-
from datetime import datetime, date
|
| 6 |
import face_recognition
|
| 7 |
import pickle
|
| 8 |
import os
|
|
@@ -10,51 +10,79 @@ from io import BytesIO
|
|
| 10 |
import base64
|
| 11 |
from PIL import Image
|
| 12 |
import json
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
class
|
| 15 |
def __init__(self):
|
| 16 |
self.known_face_encodings = []
|
| 17 |
self.known_face_names = []
|
|
|
|
| 18 |
self.attendance_records = []
|
| 19 |
-
self.
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
data = pickle.load(f)
|
| 27 |
self.known_face_encodings = data.get("encodings", [])
|
| 28 |
self.known_face_names = data.get("names", [])
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
with open("attendance_records.json", "r") as f:
|
| 36 |
self.attendance_records = json.load(f)
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
}
|
| 46 |
-
with open("known_faces.pkl", "wb") as f:
|
| 47 |
-
pickle.dump(data, f)
|
| 48 |
|
| 49 |
-
def
|
| 50 |
-
"""Save
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
def
|
| 55 |
-
"""
|
| 56 |
if image is None or not name.strip():
|
| 57 |
-
return "β Please provide both image and name!", self.
|
| 58 |
|
| 59 |
# Convert PIL image to RGB array
|
| 60 |
if isinstance(image, Image.Image):
|
|
@@ -65,102 +93,250 @@ class AttendanceAnalyzer:
|
|
| 65 |
face_encodings = face_recognition.face_encodings(image, face_locations)
|
| 66 |
|
| 67 |
if len(face_encodings) == 0:
|
| 68 |
-
return "β No face detected in the image! Please try again with a clear face image.", self.
|
| 69 |
|
| 70 |
if len(face_encodings) > 1:
|
| 71 |
-
return "β Multiple faces detected! Please upload an image with only one face.", self.
|
| 72 |
|
| 73 |
# Check if person already exists
|
| 74 |
name = name.strip().title()
|
| 75 |
if name in self.known_face_names:
|
| 76 |
-
return f"β {name} is already registered!", self.
|
| 77 |
|
| 78 |
-
#
|
|
|
|
|
|
|
|
|
|
| 79 |
self.known_face_encodings.append(face_encodings[0])
|
| 80 |
self.known_face_names.append(name)
|
| 81 |
-
self.
|
| 82 |
-
|
| 83 |
-
return f"β
{name} has been successfully registered!", self.get_registered_faces_info()
|
| 84 |
-
|
| 85 |
-
def mark_attendance(self, image):
|
| 86 |
-
"""Mark attendance for detected faces"""
|
| 87 |
-
if image is None:
|
| 88 |
-
return "β Please provide an image!", self.get_today_attendance()
|
| 89 |
-
|
| 90 |
-
if len(self.known_face_encodings) == 0:
|
| 91 |
-
return "β No registered faces found! Please register faces first.", self.get_today_attendance()
|
| 92 |
-
|
| 93 |
-
# Convert PIL image to RGB array
|
| 94 |
-
if isinstance(image, Image.Image):
|
| 95 |
-
image = np.array(image)
|
| 96 |
|
| 97 |
-
#
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
if len(face_encodings) == 0:
|
| 102 |
-
return "β No faces detected in the image!", self.get_today_attendance()
|
| 103 |
|
| 104 |
-
|
| 105 |
-
recognized_faces = []
|
| 106 |
-
unknown_faces = 0
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
if
|
| 127 |
-
#
|
| 128 |
-
self.
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
else:
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
def
|
| 157 |
-
"""Get
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
if not self.known_face_names:
|
| 159 |
-
return "No
|
| 160 |
|
| 161 |
-
info = f"**Registered
|
| 162 |
-
for i, name in enumerate(self.known_face_names, 1):
|
| 163 |
-
info += f"{i}. {name}\n"
|
| 164 |
return info
|
| 165 |
|
| 166 |
def get_today_attendance(self):
|
|
@@ -169,11 +345,12 @@ class AttendanceAnalyzer:
|
|
| 169 |
today_records = [r for r in self.attendance_records if r["date"] == today]
|
| 170 |
|
| 171 |
if not today_records:
|
| 172 |
-
return f"**Today's Attendance ({today}):**\nNo attendance marked yet."
|
| 173 |
|
| 174 |
-
info = f"**Today's Attendance ({today}):**\n"
|
| 175 |
for record in today_records:
|
| 176 |
-
|
|
|
|
| 177 |
|
| 178 |
return info
|
| 179 |
|
|
@@ -182,6 +359,12 @@ class AttendanceAnalyzer:
|
|
| 182 |
if not start_date or not end_date:
|
| 183 |
return "Please select both start and end dates."
|
| 184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
# Filter records by date range
|
| 186 |
filtered_records = [
|
| 187 |
r for r in self.attendance_records
|
|
@@ -191,148 +374,183 @@ class AttendanceAnalyzer:
|
|
| 191 |
if not filtered_records:
|
| 192 |
return f"No attendance records found between {start_date} and {end_date}."
|
| 193 |
|
| 194 |
-
# Create DataFrame for
|
| 195 |
df = pd.DataFrame(filtered_records)
|
| 196 |
|
| 197 |
# Summary statistics
|
| 198 |
total_days = (pd.to_datetime(end_date) - pd.to_datetime(start_date)).days + 1
|
| 199 |
-
|
| 200 |
total_attendances = len(df)
|
|
|
|
| 201 |
|
| 202 |
-
report = f"
|
| 203 |
-
report += f"
|
| 204 |
report += f"β’ Total Days: {total_days}\n"
|
| 205 |
-
report += f"β’ Unique
|
| 206 |
-
report += f"β’ Total Attendances: {total_attendances}\n
|
|
|
|
| 207 |
|
| 208 |
# Individual attendance counts
|
| 209 |
if not df.empty:
|
| 210 |
-
attendance_counts = df['name'].
|
| 211 |
-
report += f"
|
| 212 |
-
for
|
| 213 |
-
percentage = (count / total_days) * 100
|
| 214 |
-
report += f"β’ {name}: {count} days ({percentage:.1f}%)\n"
|
| 215 |
|
| 216 |
return report
|
| 217 |
|
| 218 |
def export_attendance_csv(self):
|
| 219 |
"""Export attendance records to CSV"""
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
|
| 229 |
-
# Initialize the attendance
|
| 230 |
-
|
| 231 |
|
| 232 |
-
# Create Gradio interface
|
| 233 |
def create_interface():
|
| 234 |
with gr.Blocks(
|
| 235 |
-
title="Attendance
|
| 236 |
theme=gr.themes.Soft(),
|
| 237 |
css="""
|
| 238 |
.gradio-container {
|
| 239 |
-
max-width:
|
| 240 |
}
|
| 241 |
.tab-nav {
|
| 242 |
font-weight: bold;
|
| 243 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
"""
|
| 245 |
) as demo:
|
| 246 |
|
| 247 |
gr.Markdown(
|
| 248 |
"""
|
| 249 |
-
#
|
| 250 |
|
| 251 |
-
**
|
| 252 |
|
| 253 |
-
|
| 254 |
-
-
|
| 255 |
-
- Automatic
|
| 256 |
-
-
|
| 257 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
"""
|
| 259 |
)
|
| 260 |
|
| 261 |
with gr.Tabs():
|
| 262 |
-
#
|
| 263 |
-
with gr.Tab("
|
| 264 |
-
gr.Markdown("###
|
| 265 |
|
| 266 |
with gr.Row():
|
| 267 |
with gr.Column(scale=1):
|
| 268 |
-
|
| 269 |
-
label="
|
| 270 |
-
|
| 271 |
-
|
| 272 |
)
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
)
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
)
|
| 283 |
|
| 284 |
with gr.Column(scale=1):
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
interactive=False
|
| 289 |
)
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
|
|
|
| 293 |
)
|
| 294 |
-
|
| 295 |
-
register_btn.click(
|
| 296 |
-
fn=analyzer.register_face,
|
| 297 |
-
inputs=[register_image, register_name],
|
| 298 |
-
outputs=[register_output, registered_faces_info]
|
| 299 |
-
)
|
| 300 |
|
| 301 |
-
#
|
| 302 |
-
with gr.Tab("
|
| 303 |
-
gr.Markdown("###
|
| 304 |
|
| 305 |
with gr.Row():
|
| 306 |
with gr.Column(scale=1):
|
| 307 |
-
|
| 308 |
-
label="Upload Photo
|
| 309 |
type="pil",
|
| 310 |
height=300
|
| 311 |
)
|
| 312 |
-
|
| 313 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
variant="primary",
|
| 315 |
size="lg"
|
| 316 |
)
|
| 317 |
|
| 318 |
with gr.Column(scale=1):
|
| 319 |
-
|
| 320 |
-
label="
|
| 321 |
-
lines=
|
| 322 |
interactive=False
|
| 323 |
)
|
| 324 |
-
|
| 325 |
-
value=
|
| 326 |
-
label="
|
| 327 |
)
|
| 328 |
-
|
| 329 |
-
mark_attendance_btn.click(
|
| 330 |
-
fn=analyzer.mark_attendance,
|
| 331 |
-
inputs=[attendance_image],
|
| 332 |
-
outputs=[attendance_output, today_attendance]
|
| 333 |
-
)
|
| 334 |
|
| 335 |
-
# Reports Tab
|
| 336 |
with gr.Tab("π Reports & Analytics", elem_classes="tab-nav"):
|
| 337 |
gr.Markdown("### Attendance Reports and Data Export")
|
| 338 |
|
|
@@ -341,11 +559,11 @@ def create_interface():
|
|
| 341 |
gr.Markdown("#### π
Generate Report")
|
| 342 |
start_date = gr.Date(
|
| 343 |
label="Start Date",
|
| 344 |
-
value=date.today().replace(day=1)
|
| 345 |
)
|
| 346 |
end_date = gr.Date(
|
| 347 |
label="End Date",
|
| 348 |
-
value=date.today()
|
| 349 |
)
|
| 350 |
generate_report_btn = gr.Button(
|
| 351 |
"π Generate Report",
|
|
@@ -372,77 +590,107 @@ def create_interface():
|
|
| 372 |
value="Select date range and click 'Generate Report' to view attendance analytics.",
|
| 373 |
label="Attendance Report"
|
| 374 |
)
|
| 375 |
-
|
| 376 |
-
generate_report_btn.click(
|
| 377 |
-
fn=analyzer.get_attendance_report,
|
| 378 |
-
inputs=[start_date, end_date],
|
| 379 |
-
outputs=[report_output]
|
| 380 |
-
)
|
| 381 |
-
|
| 382 |
-
def export_and_show(analyzer=analyzer):
|
| 383 |
-
file_path, status = analyzer.export_attendance_csv()
|
| 384 |
-
if file_path:
|
| 385 |
-
return status, gr.update(visible=True, value=file_path)
|
| 386 |
-
else:
|
| 387 |
-
return status, gr.update(visible=False)
|
| 388 |
-
|
| 389 |
-
export_btn.click(
|
| 390 |
-
fn=export_and_show,
|
| 391 |
-
outputs=[export_status, export_file]
|
| 392 |
-
)
|
| 393 |
|
| 394 |
-
#
|
| 395 |
-
with gr.Tab("βΉοΈ
|
| 396 |
gr.Markdown(
|
| 397 |
"""
|
| 398 |
-
## π
|
| 399 |
|
| 400 |
-
###
|
| 401 |
-
-
|
| 402 |
-
-
|
| 403 |
-
-
|
| 404 |
-
-
|
| 405 |
|
| 406 |
-
###
|
| 407 |
-
-
|
| 408 |
-
-
|
| 409 |
-
-
|
| 410 |
-
- The system will show which people were recognized and marked present
|
| 411 |
|
| 412 |
-
###
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 416 |
|
| 417 |
-
###
|
| 418 |
-
-
|
| 419 |
-
-
|
| 420 |
-
-
|
| 421 |
-
-
|
| 422 |
-
-
|
| 423 |
|
| 424 |
-
###
|
| 425 |
-
- **
|
| 426 |
-
- **
|
| 427 |
-
- **
|
| 428 |
-
- **
|
| 429 |
-
- **Export Capability**: Generate CSV reports for external analysis
|
| 430 |
|
| 431 |
-
###
|
| 432 |
-
-
|
| 433 |
-
-
|
| 434 |
-
-
|
| 435 |
-
-
|
| 436 |
"""
|
| 437 |
)
|
| 438 |
|
| 439 |
-
#
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
)
|
| 447 |
|
| 448 |
return demo
|
|
@@ -454,5 +702,6 @@ if __name__ == "__main__":
|
|
| 454 |
server_name="0.0.0.0",
|
| 455 |
server_port=7860,
|
| 456 |
share=False,
|
| 457 |
-
show_error=True
|
|
|
|
| 458 |
)
|
|
|
|
| 2 |
import cv2
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
+
from datetime import datetime, date, timedelta
|
| 6 |
import face_recognition
|
| 7 |
import pickle
|
| 8 |
import os
|
|
|
|
| 10 |
import base64
|
| 11 |
from PIL import Image
|
| 12 |
import json
|
| 13 |
+
import threading
|
| 14 |
+
import time
|
| 15 |
+
import queue
|
| 16 |
|
| 17 |
+
class AttendanceSystem:
|
| 18 |
def __init__(self):
|
| 19 |
self.known_face_encodings = []
|
| 20 |
self.known_face_names = []
|
| 21 |
+
self.known_face_ids = []
|
| 22 |
self.attendance_records = []
|
| 23 |
+
self.next_worker_id = 1
|
| 24 |
+
self.video_capture = None
|
| 25 |
+
self.is_streaming = False
|
| 26 |
+
self.frame_queue = queue.Queue(maxsize=2)
|
| 27 |
+
self.recognition_thread = None
|
| 28 |
+
self.last_recognition_time = {}
|
| 29 |
+
self.recognition_cooldown = 5 # seconds between recognitions for same person
|
| 30 |
+
|
| 31 |
+
# Create directories for data storage
|
| 32 |
+
os.makedirs("data", exist_ok=True)
|
| 33 |
+
os.makedirs("data/faces", exist_ok=True)
|
| 34 |
+
|
| 35 |
+
self.load_data()
|
| 36 |
+
|
| 37 |
+
def load_data(self):
|
| 38 |
+
"""Load all stored data"""
|
| 39 |
+
try:
|
| 40 |
+
# Load face encodings and worker data
|
| 41 |
+
if os.path.exists("data/workers.pkl"):
|
| 42 |
+
with open("data/workers.pkl", "rb") as f:
|
| 43 |
data = pickle.load(f)
|
| 44 |
self.known_face_encodings = data.get("encodings", [])
|
| 45 |
self.known_face_names = data.get("names", [])
|
| 46 |
+
self.known_face_ids = data.get("ids", [])
|
| 47 |
+
self.next_worker_id = data.get("next_id", 1)
|
| 48 |
+
|
| 49 |
+
# Load attendance records
|
| 50 |
+
if os.path.exists("data/attendance.json"):
|
| 51 |
+
with open("data/attendance.json", "r") as f:
|
|
|
|
| 52 |
self.attendance_records = json.load(f)
|
| 53 |
+
|
| 54 |
+
except Exception as e:
|
| 55 |
+
print(f"Error loading data: {e}")
|
| 56 |
+
self.known_face_encodings = []
|
| 57 |
+
self.known_face_names = []
|
| 58 |
+
self.known_face_ids = []
|
| 59 |
+
self.attendance_records = []
|
| 60 |
+
self.next_worker_id = 1
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
def save_data(self):
|
| 63 |
+
"""Save all data to files"""
|
| 64 |
+
try:
|
| 65 |
+
# Save worker data
|
| 66 |
+
worker_data = {
|
| 67 |
+
"encodings": self.known_face_encodings,
|
| 68 |
+
"names": self.known_face_names,
|
| 69 |
+
"ids": self.known_face_ids,
|
| 70 |
+
"next_id": self.next_worker_id
|
| 71 |
+
}
|
| 72 |
+
with open("data/workers.pkl", "wb") as f:
|
| 73 |
+
pickle.dump(worker_data, f)
|
| 74 |
+
|
| 75 |
+
# Save attendance records
|
| 76 |
+
with open("data/attendance.json", "w") as f:
|
| 77 |
+
json.dump(self.attendance_records, f, indent=2)
|
| 78 |
+
|
| 79 |
+
except Exception as e:
|
| 80 |
+
print(f"Error saving data: {e}")
|
| 81 |
|
| 82 |
+
def register_worker_manual(self, image, name):
|
| 83 |
+
"""Manual worker registration"""
|
| 84 |
if image is None or not name.strip():
|
| 85 |
+
return "β Please provide both image and name!", self.get_registered_workers_info()
|
| 86 |
|
| 87 |
# Convert PIL image to RGB array
|
| 88 |
if isinstance(image, Image.Image):
|
|
|
|
| 93 |
face_encodings = face_recognition.face_encodings(image, face_locations)
|
| 94 |
|
| 95 |
if len(face_encodings) == 0:
|
| 96 |
+
return "β No face detected in the image! Please try again with a clear face image.", self.get_registered_workers_info()
|
| 97 |
|
| 98 |
if len(face_encodings) > 1:
|
| 99 |
+
return "β Multiple faces detected! Please upload an image with only one face.", self.get_registered_workers_info()
|
| 100 |
|
| 101 |
# Check if person already exists
|
| 102 |
name = name.strip().title()
|
| 103 |
if name in self.known_face_names:
|
| 104 |
+
return f"β {name} is already registered!", self.get_registered_workers_info()
|
| 105 |
|
| 106 |
+
# Generate new worker ID
|
| 107 |
+
worker_id = f"W{self.next_worker_id:04d}"
|
| 108 |
+
|
| 109 |
+
# Add the face encoding, name, and ID
|
| 110 |
self.known_face_encodings.append(face_encodings[0])
|
| 111 |
self.known_face_names.append(name)
|
| 112 |
+
self.known_face_ids.append(worker_id)
|
| 113 |
+
self.next_worker_id += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
# Save face image
|
| 116 |
+
face_image = Image.fromarray(image)
|
| 117 |
+
face_image.save(f"data/faces/{worker_id}_{name.replace(' ', '_')}.jpg")
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
self.save_data()
|
|
|
|
|
|
|
| 120 |
|
| 121 |
+
return f"β
{name} has been successfully registered with ID: {worker_id}!", self.get_registered_workers_info()
|
| 122 |
+
|
| 123 |
+
def register_worker_auto(self, face_encoding, face_image):
|
| 124 |
+
"""Automatic worker registration for unrecognized faces"""
|
| 125 |
+
try:
|
| 126 |
+
# Generate new worker ID and name
|
| 127 |
+
worker_id = f"W{self.next_worker_id:04d}"
|
| 128 |
+
worker_name = f"Unknown_Worker_{self.next_worker_id}"
|
| 129 |
+
|
| 130 |
+
# Add to database
|
| 131 |
+
self.known_face_encodings.append(face_encoding)
|
| 132 |
+
self.known_face_names.append(worker_name)
|
| 133 |
+
self.known_face_ids.append(worker_id)
|
| 134 |
+
self.next_worker_id += 1
|
| 135 |
+
|
| 136 |
+
# Save face image
|
| 137 |
+
face_pil = Image.fromarray(cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB))
|
| 138 |
+
face_pil.save(f"data/faces/{worker_id}_{worker_name}.jpg")
|
| 139 |
+
|
| 140 |
+
self.save_data()
|
| 141 |
+
|
| 142 |
+
return worker_id, worker_name
|
| 143 |
+
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print(f"Error in auto registration: {e}")
|
| 146 |
+
return None, None
|
| 147 |
+
|
| 148 |
+
def mark_attendance(self, worker_id, worker_name):
|
| 149 |
+
"""Mark attendance for a worker"""
|
| 150 |
+
try:
|
| 151 |
+
today = date.today().isoformat()
|
| 152 |
+
current_time = datetime.now()
|
| 153 |
+
|
| 154 |
+
# Check if already marked today
|
| 155 |
+
already_marked = any(
|
| 156 |
+
record["worker_id"] == worker_id and record["date"] == today
|
| 157 |
+
for record in self.attendance_records
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
if not already_marked:
|
| 161 |
+
# Mark attendance
|
| 162 |
+
self.attendance_records.append({
|
| 163 |
+
"worker_id": worker_id,
|
| 164 |
+
"name": worker_name,
|
| 165 |
+
"date": today,
|
| 166 |
+
"time": current_time.strftime("%H:%M:%S"),
|
| 167 |
+
"timestamp": current_time.isoformat(),
|
| 168 |
+
"status": "Present",
|
| 169 |
+
"method": "Auto"
|
| 170 |
+
})
|
| 171 |
+
self.save_data()
|
| 172 |
+
return True
|
| 173 |
+
return False
|
| 174 |
+
|
| 175 |
+
except Exception as e:
|
| 176 |
+
print(f"Error marking attendance: {e}")
|
| 177 |
+
return False
|
| 178 |
+
|
| 179 |
+
def process_video_frame(self, frame):
|
| 180 |
+
"""Process a single video frame for face recognition"""
|
| 181 |
+
try:
|
| 182 |
+
# Resize frame for faster processing
|
| 183 |
+
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
|
| 184 |
+
rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
|
| 185 |
+
|
| 186 |
+
# Find faces in the frame
|
| 187 |
+
face_locations = face_recognition.face_locations(rgb_small_frame)
|
| 188 |
+
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
|
| 189 |
|
| 190 |
+
current_time = time.time()
|
| 191 |
+
|
| 192 |
+
for (face_encoding, face_location) in zip(face_encodings, face_locations):
|
| 193 |
+
# Scale back up face locations
|
| 194 |
+
top, right, bottom, left = face_location
|
| 195 |
+
top *= 4
|
| 196 |
+
right *= 4
|
| 197 |
+
bottom *= 4
|
| 198 |
+
left *= 4
|
| 199 |
|
| 200 |
+
# Extract face image
|
| 201 |
+
face_image = frame[top:bottom, left:right]
|
| 202 |
+
|
| 203 |
+
# Compare with known faces
|
| 204 |
+
matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding, tolerance=0.6)
|
| 205 |
+
face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)
|
| 206 |
+
|
| 207 |
+
worker_id = None
|
| 208 |
+
worker_name = "Unknown"
|
| 209 |
+
color = (0, 0, 255) # Red for unknown
|
| 210 |
+
|
| 211 |
+
if len(face_distances) > 0:
|
| 212 |
+
best_match_index = np.argmin(face_distances)
|
| 213 |
|
| 214 |
+
if matches[best_match_index] and face_distances[best_match_index] < 0.6:
|
| 215 |
+
# Known worker
|
| 216 |
+
worker_id = self.known_face_ids[best_match_index]
|
| 217 |
+
worker_name = self.known_face_names[best_match_index]
|
| 218 |
+
color = (0, 255, 0) # Green for known
|
| 219 |
+
|
| 220 |
+
# Check cooldown period
|
| 221 |
+
if worker_id not in self.last_recognition_time or \
|
| 222 |
+
current_time - self.last_recognition_time[worker_id] > self.recognition_cooldown:
|
| 223 |
+
|
| 224 |
+
# Mark attendance
|
| 225 |
+
if self.mark_attendance(worker_id, worker_name):
|
| 226 |
+
print(f"β
Attendance marked for {worker_name} ({worker_id})")
|
| 227 |
+
|
| 228 |
+
self.last_recognition_time[worker_id] = current_time
|
| 229 |
else:
|
| 230 |
+
# Unknown face - auto register
|
| 231 |
+
if face_image.size > 0:
|
| 232 |
+
new_id, new_name = self.register_worker_auto(face_encoding, face_image)
|
| 233 |
+
if new_id:
|
| 234 |
+
worker_id = new_id
|
| 235 |
+
worker_name = new_name
|
| 236 |
+
color = (255, 165, 0) # Orange for newly registered
|
| 237 |
+
print(f"π New worker registered: {new_name} ({new_id})")
|
| 238 |
+
|
| 239 |
+
# Mark attendance for new worker
|
| 240 |
+
self.mark_attendance(worker_id, worker_name)
|
| 241 |
+
|
| 242 |
+
# Draw rectangle and label
|
| 243 |
+
cv2.rectangle(frame, (left, top), (right, bottom), color, 2)
|
| 244 |
+
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), color, cv2.FILLED)
|
| 245 |
+
|
| 246 |
+
label = f"{worker_name}"
|
| 247 |
+
if worker_id:
|
| 248 |
+
label += f" ({worker_id})"
|
| 249 |
+
|
| 250 |
+
cv2.putText(frame, label, (left + 6, bottom - 6),
|
| 251 |
+
cv2.FONT_HERSHEY_DUPLEX, 0.6, (255, 255, 255), 1)
|
| 252 |
+
|
| 253 |
+
return frame
|
| 254 |
+
|
| 255 |
+
except Exception as e:
|
| 256 |
+
print(f"Error processing frame: {e}")
|
| 257 |
+
return frame
|
| 258 |
+
|
| 259 |
+
def start_video_stream(self, camera_source=0):
|
| 260 |
+
"""Start video streaming and recognition"""
|
| 261 |
+
try:
|
| 262 |
+
if self.is_streaming:
|
| 263 |
+
return "β οΈ Video stream is already running!"
|
| 264 |
+
|
| 265 |
+
self.video_capture = cv2.VideoCapture(camera_source)
|
| 266 |
+
if not self.video_capture.isOpened():
|
| 267 |
+
return "β Could not open camera/video source!"
|
| 268 |
+
|
| 269 |
+
self.is_streaming = True
|
| 270 |
+
|
| 271 |
+
def video_loop():
|
| 272 |
+
while self.is_streaming:
|
| 273 |
+
ret, frame = self.video_capture.read()
|
| 274 |
+
if not ret:
|
| 275 |
+
break
|
| 276 |
+
|
| 277 |
+
# Process frame for face recognition
|
| 278 |
+
processed_frame = self.process_video_frame(frame)
|
| 279 |
+
|
| 280 |
+
# Add to queue for display
|
| 281 |
+
if not self.frame_queue.full():
|
| 282 |
+
try:
|
| 283 |
+
self.frame_queue.put_nowait(processed_frame)
|
| 284 |
+
except queue.Full:
|
| 285 |
+
pass
|
| 286 |
+
|
| 287 |
+
time.sleep(0.1) # Limit processing rate
|
| 288 |
+
|
| 289 |
+
self.recognition_thread = threading.Thread(target=video_loop)
|
| 290 |
+
self.recognition_thread.daemon = True
|
| 291 |
+
self.recognition_thread.start()
|
| 292 |
+
|
| 293 |
+
return "β
Video stream started successfully!"
|
| 294 |
+
|
| 295 |
+
except Exception as e:
|
| 296 |
+
return f"β Error starting video stream: {e}"
|
| 297 |
+
|
| 298 |
+
def stop_video_stream(self):
|
| 299 |
+
"""Stop video streaming"""
|
| 300 |
+
try:
|
| 301 |
+
self.is_streaming = False
|
| 302 |
+
|
| 303 |
+
if self.video_capture:
|
| 304 |
+
self.video_capture.release()
|
| 305 |
+
self.video_capture = None
|
| 306 |
+
|
| 307 |
+
if self.recognition_thread:
|
| 308 |
+
self.recognition_thread.join(timeout=2)
|
| 309 |
+
|
| 310 |
+
# Clear frame queue
|
| 311 |
+
while not self.frame_queue.empty():
|
| 312 |
+
try:
|
| 313 |
+
self.frame_queue.get_nowait()
|
| 314 |
+
except queue.Empty:
|
| 315 |
+
break
|
| 316 |
+
|
| 317 |
+
return "β
Video stream stopped successfully!"
|
| 318 |
+
|
| 319 |
+
except Exception as e:
|
| 320 |
+
return f"β Error stopping video stream: {e}"
|
| 321 |
|
| 322 |
+
def get_current_frame(self):
|
| 323 |
+
"""Get current frame for display"""
|
| 324 |
+
try:
|
| 325 |
+
if not self.frame_queue.empty():
|
| 326 |
+
frame = self.frame_queue.get_nowait()
|
| 327 |
+
return frame
|
| 328 |
+
return None
|
| 329 |
+
except queue.Empty:
|
| 330 |
+
return None
|
| 331 |
+
|
| 332 |
+
def get_registered_workers_info(self):
|
| 333 |
+
"""Get information about registered workers"""
|
| 334 |
if not self.known_face_names:
|
| 335 |
+
return "No workers registered yet."
|
| 336 |
|
| 337 |
+
info = f"**Registered Workers ({len(self.known_face_names)}):**\n\n"
|
| 338 |
+
for i, (worker_id, name) in enumerate(zip(self.known_face_ids, self.known_face_names), 1):
|
| 339 |
+
info += f"{i}. **{name}** (ID: {worker_id})\n"
|
| 340 |
return info
|
| 341 |
|
| 342 |
def get_today_attendance(self):
|
|
|
|
| 345 |
today_records = [r for r in self.attendance_records if r["date"] == today]
|
| 346 |
|
| 347 |
if not today_records:
|
| 348 |
+
return f"**Today's Attendance ({today}):**\n\nNo attendance marked yet."
|
| 349 |
|
| 350 |
+
info = f"**Today's Attendance ({today}):**\n\n"
|
| 351 |
for record in today_records:
|
| 352 |
+
method_icon = "π€" if record.get("method") == "Auto" else "π€"
|
| 353 |
+
info += f"{method_icon} **{record['name']}** (ID: {record['worker_id']}) - {record['time']}\n"
|
| 354 |
|
| 355 |
return info
|
| 356 |
|
|
|
|
| 359 |
if not start_date or not end_date:
|
| 360 |
return "Please select both start and end dates."
|
| 361 |
|
| 362 |
+
# Convert to string format if needed
|
| 363 |
+
if hasattr(start_date, 'strftime'):
|
| 364 |
+
start_date = start_date.strftime('%Y-%m-%d')
|
| 365 |
+
if hasattr(end_date, 'strftime'):
|
| 366 |
+
end_date = end_date.strftime('%Y-%m-%d')
|
| 367 |
+
|
| 368 |
# Filter records by date range
|
| 369 |
filtered_records = [
|
| 370 |
r for r in self.attendance_records
|
|
|
|
| 374 |
if not filtered_records:
|
| 375 |
return f"No attendance records found between {start_date} and {end_date}."
|
| 376 |
|
| 377 |
+
# Create DataFrame for analysis
|
| 378 |
df = pd.DataFrame(filtered_records)
|
| 379 |
|
| 380 |
# Summary statistics
|
| 381 |
total_days = (pd.to_datetime(end_date) - pd.to_datetime(start_date)).days + 1
|
| 382 |
+
unique_workers = df['worker_id'].nunique()
|
| 383 |
total_attendances = len(df)
|
| 384 |
+
auto_registrations = len(df[df['method'] == 'Auto'])
|
| 385 |
|
| 386 |
+
report = f"**π Attendance Report ({start_date} to {end_date})**\n\n"
|
| 387 |
+
report += f"**Summary:**\n"
|
| 388 |
report += f"β’ Total Days: {total_days}\n"
|
| 389 |
+
report += f"β’ Unique Workers: {unique_workers}\n"
|
| 390 |
+
report += f"β’ Total Attendances: {total_attendances}\n"
|
| 391 |
+
report += f"β’ Auto Detections: {auto_registrations}\n\n"
|
| 392 |
|
| 393 |
# Individual attendance counts
|
| 394 |
if not df.empty:
|
| 395 |
+
attendance_counts = df.groupby(['worker_id', 'name']).size().reset_index(name='count')
|
| 396 |
+
report += f"**π₯ Individual Attendance:**\n"
|
| 397 |
+
for _, row in attendance_counts.iterrows():
|
| 398 |
+
percentage = (row['count'] / total_days) * 100
|
| 399 |
+
report += f"β’ **{row['name']}** ({row['worker_id']}): {row['count']} days ({percentage:.1f}%)\n"
|
| 400 |
|
| 401 |
return report
|
| 402 |
|
| 403 |
def export_attendance_csv(self):
|
| 404 |
"""Export attendance records to CSV"""
|
| 405 |
+
try:
|
| 406 |
+
if not self.attendance_records:
|
| 407 |
+
return None, "No attendance records to export."
|
| 408 |
+
|
| 409 |
+
df = pd.DataFrame(self.attendance_records)
|
| 410 |
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
| 411 |
+
csv_file = f"attendance_report_{timestamp}.csv"
|
| 412 |
+
df.to_csv(csv_file, index=False)
|
| 413 |
+
|
| 414 |
+
return csv_file, f"β
Attendance exported to {csv_file}"
|
| 415 |
+
|
| 416 |
+
except Exception as e:
|
| 417 |
+
return None, f"β Error exporting data: {e}"
|
| 418 |
|
| 419 |
+
# Initialize the attendance system
|
| 420 |
+
attendance_system = AttendanceSystem()
|
| 421 |
|
|
|
|
| 422 |
def create_interface():
|
| 423 |
with gr.Blocks(
|
| 424 |
+
title="π― Advanced Attendance System with Live Recognition",
|
| 425 |
theme=gr.themes.Soft(),
|
| 426 |
css="""
|
| 427 |
.gradio-container {
|
| 428 |
+
max-width: 1400px !important;
|
| 429 |
}
|
| 430 |
.tab-nav {
|
| 431 |
font-weight: bold;
|
| 432 |
}
|
| 433 |
+
.status-box {
|
| 434 |
+
padding: 10px;
|
| 435 |
+
border-radius: 5px;
|
| 436 |
+
margin: 5px 0;
|
| 437 |
+
}
|
| 438 |
"""
|
| 439 |
) as demo:
|
| 440 |
|
| 441 |
gr.Markdown(
|
| 442 |
"""
|
| 443 |
+
# π― Advanced Attendance System with Live Face Recognition
|
| 444 |
|
| 445 |
+
**Comprehensive facial recognition system with automatic worker registration and attendance tracking**
|
| 446 |
|
| 447 |
+
## π **Key Features:**
|
| 448 |
+
- **π₯ Live Video Stream Recognition** - Real-time face detection from camera/CCTV
|
| 449 |
+
- **π€ Automatic Worker Registration** - Auto-register unknown faces with unique IDs
|
| 450 |
+
- **π€ Manual Registration** - Register workers manually with photos
|
| 451 |
+
- **π
24-Hour Attendance Rule** - One attendance mark per worker per day
|
| 452 |
+
- **π Advanced Analytics** - Detailed reports and data export
|
| 453 |
+
- **πΎ Persistent Data Storage** - All data saved locally in `/data` folder
|
| 454 |
+
|
| 455 |
+
## π **Data Storage Location:**
|
| 456 |
+
- **Worker Database:** `/data/workers.pkl`
|
| 457 |
+
- **Attendance Records:** `/data/attendance.json`
|
| 458 |
+
- **Face Images:** `/data/faces/` folder
|
| 459 |
"""
|
| 460 |
)
|
| 461 |
|
| 462 |
with gr.Tabs():
|
| 463 |
+
# Live Recognition Tab
|
| 464 |
+
with gr.Tab("π₯ Live Recognition", elem_classes="tab-nav"):
|
| 465 |
+
gr.Markdown("### Real-time Face Recognition and Attendance")
|
| 466 |
|
| 467 |
with gr.Row():
|
| 468 |
with gr.Column(scale=1):
|
| 469 |
+
camera_source = gr.Number(
|
| 470 |
+
label="Camera Source (0 for default camera, or RTSP URL)",
|
| 471 |
+
value=0,
|
| 472 |
+
precision=0
|
| 473 |
)
|
| 474 |
+
|
| 475 |
+
with gr.Row():
|
| 476 |
+
start_stream_btn = gr.Button(
|
| 477 |
+
"π₯ Start Live Recognition",
|
| 478 |
+
variant="primary",
|
| 479 |
+
size="lg"
|
| 480 |
+
)
|
| 481 |
+
stop_stream_btn = gr.Button(
|
| 482 |
+
"βΉοΈ Stop Stream",
|
| 483 |
+
variant="secondary",
|
| 484 |
+
size="lg"
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
stream_status = gr.Textbox(
|
| 488 |
+
label="Stream Status",
|
| 489 |
+
value="Ready to start...",
|
| 490 |
+
interactive=False,
|
| 491 |
+
lines=2
|
| 492 |
)
|
| 493 |
+
|
| 494 |
+
gr.Markdown(
|
| 495 |
+
"""
|
| 496 |
+
**π Instructions:**
|
| 497 |
+
1. Click "Start Live Recognition" to begin
|
| 498 |
+
2. System will automatically detect and register new faces
|
| 499 |
+
3. Known workers will be marked present (once per day)
|
| 500 |
+
4. New workers get auto-assigned IDs (W0001, W0002, etc.)
|
| 501 |
+
|
| 502 |
+
**π¨ Color Coding:**
|
| 503 |
+
- π’ **Green:** Known worker (attendance marked)
|
| 504 |
+
- π **Orange:** New worker (auto-registered)
|
| 505 |
+
- π΄ **Red:** Face detected but processing
|
| 506 |
+
"""
|
| 507 |
)
|
| 508 |
|
| 509 |
with gr.Column(scale=1):
|
| 510 |
+
live_attendance_display = gr.Markdown(
|
| 511 |
+
value=attendance_system.get_today_attendance(),
|
| 512 |
+
label="Live Attendance Updates"
|
|
|
|
| 513 |
)
|
| 514 |
+
|
| 515 |
+
refresh_attendance_btn = gr.Button(
|
| 516 |
+
"π Refresh Attendance",
|
| 517 |
+
variant="secondary"
|
| 518 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 519 |
|
| 520 |
+
# Manual Registration Tab
|
| 521 |
+
with gr.Tab("π€ Manual Registration", elem_classes="tab-nav"):
|
| 522 |
+
gr.Markdown("### Register Workers Manually")
|
| 523 |
|
| 524 |
with gr.Row():
|
| 525 |
with gr.Column(scale=1):
|
| 526 |
+
register_image = gr.Image(
|
| 527 |
+
label="Upload Worker's Photo",
|
| 528 |
type="pil",
|
| 529 |
height=300
|
| 530 |
)
|
| 531 |
+
register_name = gr.Textbox(
|
| 532 |
+
label="Worker's Full Name",
|
| 533 |
+
placeholder="Enter full name...",
|
| 534 |
+
lines=1
|
| 535 |
+
)
|
| 536 |
+
register_btn = gr.Button(
|
| 537 |
+
"π€ Register Worker",
|
| 538 |
variant="primary",
|
| 539 |
size="lg"
|
| 540 |
)
|
| 541 |
|
| 542 |
with gr.Column(scale=1):
|
| 543 |
+
register_output = gr.Textbox(
|
| 544 |
+
label="Registration Status",
|
| 545 |
+
lines=3,
|
| 546 |
interactive=False
|
| 547 |
)
|
| 548 |
+
registered_workers_info = gr.Markdown(
|
| 549 |
+
value=attendance_system.get_registered_workers_info(),
|
| 550 |
+
label="Registered Workers Database"
|
| 551 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
|
| 553 |
+
# Reports & Analytics Tab
|
| 554 |
with gr.Tab("π Reports & Analytics", elem_classes="tab-nav"):
|
| 555 |
gr.Markdown("### Attendance Reports and Data Export")
|
| 556 |
|
|
|
|
| 559 |
gr.Markdown("#### π
Generate Report")
|
| 560 |
start_date = gr.Date(
|
| 561 |
label="Start Date",
|
| 562 |
+
value=date.today().replace(day=1)
|
| 563 |
)
|
| 564 |
end_date = gr.Date(
|
| 565 |
label="End Date",
|
| 566 |
+
value=date.today()
|
| 567 |
)
|
| 568 |
generate_report_btn = gr.Button(
|
| 569 |
"π Generate Report",
|
|
|
|
| 590 |
value="Select date range and click 'Generate Report' to view attendance analytics.",
|
| 591 |
label="Attendance Report"
|
| 592 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
|
| 594 |
+
# System Info Tab
|
| 595 |
+
with gr.Tab("βΉοΈ System Information", elem_classes="tab-nav"):
|
| 596 |
gr.Markdown(
|
| 597 |
"""
|
| 598 |
+
## π System Guide
|
| 599 |
|
| 600 |
+
### π₯ Live Recognition System
|
| 601 |
+
- **Camera Setup:** Use camera index (0, 1, 2...) or RTSP URL for IP cameras
|
| 602 |
+
- **Auto Registration:** Unknown faces automatically get worker IDs (W0001, W0002...)
|
| 603 |
+
- **24-Hour Rule:** Each worker can only be marked present once per day
|
| 604 |
+
- **Real-time Processing:** Continuous face detection and recognition
|
| 605 |
|
| 606 |
+
### π€ Manual Registration
|
| 607 |
+
- Upload clear, front-facing photos for best results
|
| 608 |
+
- One face per image for registration
|
| 609 |
+
- Workers get unique IDs automatically assigned
|
|
|
|
| 610 |
|
| 611 |
+
### π Data Storage Structure
|
| 612 |
+
```
|
| 613 |
+
/data/
|
| 614 |
+
βββ workers.pkl # Worker database (encodings, names, IDs)
|
| 615 |
+
βββ attendance.json # All attendance records
|
| 616 |
+
βββ faces/ # Saved face images
|
| 617 |
+
βββ W0001_John_Doe.jpg
|
| 618 |
+
βββ W0002_Jane_Smith.jpg
|
| 619 |
+
βββ ...
|
| 620 |
+
```
|
| 621 |
|
| 622 |
+
### π§ Technical Features
|
| 623 |
+
- **Face Recognition:** Uses state-of-the-art face_recognition library
|
| 624 |
+
- **Tolerance:** 0.6 threshold for face matching accuracy
|
| 625 |
+
- **Threading:** Separate threads for video processing and UI
|
| 626 |
+
- **Queue Management:** Efficient frame processing with queue system
|
| 627 |
+
- **Error Handling:** Robust error handling and recovery
|
| 628 |
|
| 629 |
+
### π¨ Troubleshooting
|
| 630 |
+
- **Camera Issues:** Check camera permissions and connections
|
| 631 |
+
- **Poor Recognition:** Ensure good lighting and clear face visibility
|
| 632 |
+
- **Performance:** Reduce video resolution for better performance
|
| 633 |
+
- **Storage:** Check disk space for face image storage
|
|
|
|
| 634 |
|
| 635 |
+
### π Privacy & Security
|
| 636 |
+
- All data stored locally in `/data` folder
|
| 637 |
+
- No external API calls or data transmission
|
| 638 |
+
- Face images saved securely with worker IDs
|
| 639 |
+
- Attendance records in JSON format for easy backup
|
| 640 |
"""
|
| 641 |
)
|
| 642 |
|
| 643 |
+
# Event handlers
|
| 644 |
+
start_stream_btn.click(
|
| 645 |
+
fn=attendance_system.start_video_stream,
|
| 646 |
+
inputs=[camera_source],
|
| 647 |
+
outputs=[stream_status]
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
stop_stream_btn.click(
|
| 651 |
+
fn=attendance_system.stop_video_stream,
|
| 652 |
+
outputs=[stream_status]
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
refresh_attendance_btn.click(
|
| 656 |
+
fn=attendance_system.get_today_attendance,
|
| 657 |
+
outputs=[live_attendance_display]
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
register_btn.click(
|
| 661 |
+
fn=attendance_system.register_worker_manual,
|
| 662 |
+
inputs=[register_image, register_name],
|
| 663 |
+
outputs=[register_output, registered_workers_info]
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
generate_report_btn.click(
|
| 667 |
+
fn=attendance_system.get_attendance_report,
|
| 668 |
+
inputs=[start_date, end_date],
|
| 669 |
+
outputs=[report_output]
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
def export_and_show():
|
| 673 |
+
file_path, status = attendance_system.export_attendance_csv()
|
| 674 |
+
if file_path:
|
| 675 |
+
return status, gr.update(visible=True, value=file_path)
|
| 676 |
+
else:
|
| 677 |
+
return status, gr.update(visible=False)
|
| 678 |
+
|
| 679 |
+
export_btn.click(
|
| 680 |
+
fn=export_and_show,
|
| 681 |
+
outputs=[export_status, export_file]
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
# Auto-refresh attendance every 10 seconds when streaming
|
| 685 |
+
def auto_refresh():
|
| 686 |
+
if attendance_system.is_streaming:
|
| 687 |
+
return attendance_system.get_today_attendance()
|
| 688 |
+
return gr.update()
|
| 689 |
+
|
| 690 |
+
demo.load(
|
| 691 |
+
fn=auto_refresh,
|
| 692 |
+
outputs=[live_attendance_display],
|
| 693 |
+
every=10
|
| 694 |
)
|
| 695 |
|
| 696 |
return demo
|
|
|
|
| 702 |
server_name="0.0.0.0",
|
| 703 |
server_port=7860,
|
| 704 |
share=False,
|
| 705 |
+
show_error=True,
|
| 706 |
+
debug=True
|
| 707 |
)
|