Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -64,8 +64,7 @@ CONFIG = {
|
|
| 64 |
"MAX_PROCESSING_TIME": 60, # 1 minute limit
|
| 65 |
"FRAME_SKIP": 2, # Process every 2nd frame for speed
|
| 66 |
"BATCH_SIZE": 16, # Frames per batch
|
| 67 |
-
"PARALLEL_WORKERS": max(1, cpu_count() - 1)
|
| 68 |
-
"VIOLATION_COOLDOWN": 5.0 # Seconds before same violation can be reported again for same worker
|
| 69 |
}
|
| 70 |
|
| 71 |
# Setup logging
|
|
@@ -305,12 +304,13 @@ def process_video(video_data):
|
|
| 305 |
|
| 306 |
logger.info(f"Video properties: {duration:.2f}s, {total_frames} frames, {fps:.1f} FPS, {width}x{height}")
|
| 307 |
|
| 308 |
-
workers
|
|
|
|
| 309 |
violations = []
|
| 310 |
-
violation_history = {} # Track when violations were last reported for each worker
|
| 311 |
snapshots = []
|
| 312 |
start_time = time.time()
|
| 313 |
frame_skip = CONFIG["FRAME_SKIP"]
|
|
|
|
| 314 |
|
| 315 |
# Process frames in batches
|
| 316 |
while True:
|
|
@@ -354,6 +354,8 @@ def process_video(video_data):
|
|
| 354 |
|
| 355 |
# Process detections in this frame
|
| 356 |
boxes = result.boxes
|
|
|
|
|
|
|
| 357 |
for box in boxes:
|
| 358 |
cls = int(box.cls)
|
| 359 |
conf = float(box.conf)
|
|
@@ -364,80 +366,92 @@ def process_video(video_data):
|
|
| 364 |
|
| 365 |
bbox = [round(x, 2) for x in box.xywh.cpu().numpy()[0]]
|
| 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 |
-
"timestamp": best_detection["timestamp"],
|
| 429 |
-
"worker_id": worker_id,
|
| 430 |
-
"snapshot_path": snapshot_path,
|
| 431 |
-
"snapshot_url": f"{CONFIG['PUBLIC_URL_BASE']}{snapshot_filename}"
|
| 432 |
-
})
|
| 433 |
-
cap_snapshot.release()
|
| 434 |
-
del violation_history[worker_id] # Reset for this worker
|
| 435 |
-
else:
|
| 436 |
violations.append(detection)
|
| 437 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
|
| 439 |
# Remove inactive workers
|
| 440 |
-
|
|
|
|
|
|
|
|
|
|
| 441 |
|
| 442 |
cap.release()
|
| 443 |
os.remove(video_path)
|
|
@@ -453,32 +467,33 @@ def process_video(video_data):
|
|
| 453 |
pdf_path, pdf_url, pdf_file = generate_violation_pdf(violations, score)
|
| 454 |
report_id, final_pdf_url = push_report_to_salesforce(violations, score, pdf_path, pdf_file)
|
| 455 |
|
| 456 |
-
violation_table = "| Violation | Timestamp (s) | Confidence | Worker ID
|
| 457 |
-
violation_table += "
|
| 458 |
for v in sorted(violations, key=lambda x: x["timestamp"]):
|
| 459 |
display_name = CONFIG["DISPLAY_NAMES"].get(v.get("violation", "Unknown"), "Unknown")
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
for s in snapshots:
|
| 463 |
-
if (s["worker_id"] == v.get("worker_id") and
|
| 464 |
-
s["violation"] == v.get("violation") and
|
| 465 |
-
abs(s["timestamp"] - v.get("timestamp", 0)) < 0.5):
|
| 466 |
-
snapshot_markdown = f"[View]({s['snapshot_url']})"
|
| 467 |
-
break
|
| 468 |
-
|
| 469 |
-
row = f"| {display_name:<22} | {v.get('timestamp', 0.0):.2f} | {v.get('confidence', 0.0):.2f} | {v.get('worker_id', 'N/A')} | {snapshot_markdown} |\n"
|
| 470 |
violation_table += row
|
| 471 |
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 477 |
|
| 478 |
yield (
|
| 479 |
violation_table,
|
| 480 |
f"Safety Score: {score}%",
|
| 481 |
-
|
| 482 |
f"Salesforce Record ID: {report_id or 'N/A'}",
|
| 483 |
final_pdf_url or "N/A"
|
| 484 |
)
|
|
@@ -497,8 +512,8 @@ def gradio_interface(video_file):
|
|
| 497 |
with open(video_file, "rb") as f:
|
| 498 |
video_data = f.read()
|
| 499 |
|
| 500 |
-
for status, score,
|
| 501 |
-
yield status, score,
|
| 502 |
except Exception as e:
|
| 503 |
logger.error(f"Error in Gradio interface: {e}", exc_info=True)
|
| 504 |
yield f"Error: {str(e)}", "", "Error in processing.", "", ""
|
|
@@ -509,7 +524,7 @@ interface = gr.Interface(
|
|
| 509 |
outputs=[
|
| 510 |
gr.Markdown(label="Detected Safety Violations"),
|
| 511 |
gr.Textbox(label="Compliance Score"),
|
| 512 |
-
gr.
|
| 513 |
gr.Textbox(label="Salesforce Record ID"),
|
| 514 |
gr.Textbox(label="Violation Details URL")
|
| 515 |
],
|
|
|
|
| 64 |
"MAX_PROCESSING_TIME": 60, # 1 minute limit
|
| 65 |
"FRAME_SKIP": 2, # Process every 2nd frame for speed
|
| 66 |
"BATCH_SIZE": 16, # Frames per batch
|
| 67 |
+
"PARALLEL_WORKERS": max(1, cpu_count() - 1) # Use all CPU cores except one
|
|
|
|
| 68 |
}
|
| 69 |
|
| 70 |
# Setup logging
|
|
|
|
| 304 |
|
| 305 |
logger.info(f"Video properties: {duration:.2f}s, {total_frames} frames, {fps:.1f} FPS, {width}x{height}")
|
| 306 |
|
| 307 |
+
# Track workers only for helmet violations
|
| 308 |
+
helmet_workers = {} # {worker_id: {"first_detected": timestamp, "bbox": bbox}}
|
| 309 |
violations = []
|
|
|
|
| 310 |
snapshots = []
|
| 311 |
start_time = time.time()
|
| 312 |
frame_skip = CONFIG["FRAME_SKIP"]
|
| 313 |
+
next_worker_id = 1
|
| 314 |
|
| 315 |
# Process frames in batches
|
| 316 |
while True:
|
|
|
|
| 354 |
|
| 355 |
# Process detections in this frame
|
| 356 |
boxes = result.boxes
|
| 357 |
+
frame_violations = set() # Track violations in this frame to avoid duplicates
|
| 358 |
+
|
| 359 |
for box in boxes:
|
| 360 |
cls = int(box.cls)
|
| 361 |
conf = float(box.conf)
|
|
|
|
| 366 |
|
| 367 |
bbox = [round(x, 2) for x in box.xywh.cpu().numpy()[0]]
|
| 368 |
|
| 369 |
+
# For no_helmet violations, track workers and only record first occurrence
|
| 370 |
+
if label == "no_helmet":
|
| 371 |
+
# Check if this is a known worker
|
| 372 |
+
worker_id = None
|
| 373 |
+
for w_id, worker in helmet_workers.items():
|
| 374 |
+
iou = calculate_iou(bbox, worker["bbox"])
|
| 375 |
+
if iou > 0.4: # IOU threshold
|
| 376 |
+
worker_id = w_id
|
| 377 |
+
# Update worker's position
|
| 378 |
+
helmet_workers[w_id]["bbox"] = bbox
|
| 379 |
+
helmet_workers[w_id]["last_seen"] = current_time
|
| 380 |
+
break
|
| 381 |
+
|
| 382 |
+
# If new worker, assign ID and record first violation
|
| 383 |
+
if worker_id is None:
|
| 384 |
+
worker_id = next_worker_id
|
| 385 |
+
next_worker_id += 1
|
| 386 |
+
helmet_workers[worker_id] = {
|
| 387 |
+
"bbox": bbox,
|
| 388 |
+
"first_seen": current_time,
|
| 389 |
+
"last_seen": current_time
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
# Only record first violation for this worker
|
| 393 |
+
detection = {
|
| 394 |
+
"frame": frame_idx,
|
| 395 |
+
"violation": label,
|
| 396 |
+
"confidence": round(conf, 2),
|
| 397 |
+
"bounding_box": bbox,
|
| 398 |
+
"timestamp": current_time,
|
| 399 |
+
"worker_id": worker_id
|
| 400 |
+
}
|
| 401 |
+
violations.append(detection)
|
| 402 |
+
|
| 403 |
+
# Capture snapshot
|
| 404 |
+
cap_snapshot = cv2.VideoCapture(video_path)
|
| 405 |
+
cap_snapshot.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
|
| 406 |
+
ret, snapshot_frame = cap_snapshot.read()
|
| 407 |
+
if ret:
|
| 408 |
+
snapshot_frame = draw_detections(snapshot_frame, [detection])
|
| 409 |
+
snapshot_filename = f"no_helmet_{worker_id}_{frame_idx}.jpg"
|
| 410 |
+
snapshot_path = os.path.join(CONFIG["OUTPUT_DIR"], snapshot_filename)
|
| 411 |
+
cv2.imwrite(snapshot_path, snapshot_frame)
|
| 412 |
+
snapshots.append({
|
| 413 |
+
"violation": "no_helmet",
|
| 414 |
+
"frame": frame_idx,
|
| 415 |
+
"worker_id": worker_id,
|
| 416 |
+
"snapshot_path": snapshot_path,
|
| 417 |
+
"snapshot_url": f"{CONFIG['PUBLIC_URL_BASE']}{snapshot_filename}"
|
| 418 |
+
})
|
| 419 |
+
cap_snapshot.release()
|
| 420 |
+
else:
|
| 421 |
+
# For other violations, only record if not already detected in this frame
|
| 422 |
+
if label not in frame_violations:
|
| 423 |
+
detection = {
|
| 424 |
+
"frame": frame_idx,
|
| 425 |
+
"violation": label,
|
| 426 |
+
"confidence": round(conf, 2),
|
| 427 |
+
"bounding_box": bbox,
|
| 428 |
+
"timestamp": current_time
|
| 429 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
violations.append(detection)
|
| 431 |
+
frame_violations.add(label)
|
| 432 |
+
|
| 433 |
+
# Capture snapshot for first occurrence of this violation type
|
| 434 |
+
cap_snapshot = cv2.VideoCapture(video_path)
|
| 435 |
+
cap_snapshot.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
|
| 436 |
+
ret, snapshot_frame = cap_snapshot.read()
|
| 437 |
+
if ret:
|
| 438 |
+
snapshot_frame = draw_detections(snapshot_frame, [detection])
|
| 439 |
+
snapshot_filename = f"{label}_{frame_idx}.jpg"
|
| 440 |
+
snapshot_path = os.path.join(CONFIG["OUTPUT_DIR"], snapshot_filename)
|
| 441 |
+
cv2.imwrite(snapshot_path, snapshot_frame)
|
| 442 |
+
snapshots.append({
|
| 443 |
+
"violation": label,
|
| 444 |
+
"frame": frame_idx,
|
| 445 |
+
"snapshot_path": snapshot_path,
|
| 446 |
+
"snapshot_url": f"{CONFIG['PUBLIC_URL_BASE']}{snapshot_filename}"
|
| 447 |
+
})
|
| 448 |
+
cap_snapshot.release()
|
| 449 |
|
| 450 |
# Remove inactive workers
|
| 451 |
+
inactive_workers = [w_id for w_id, worker in helmet_workers.items()
|
| 452 |
+
if current_time - worker["last_seen"] > CONFIG["WORKER_TRACKING_DURATION"]]
|
| 453 |
+
for w_id in inactive_workers:
|
| 454 |
+
del helmet_workers[w_id]
|
| 455 |
|
| 456 |
cap.release()
|
| 457 |
os.remove(video_path)
|
|
|
|
| 467 |
pdf_path, pdf_url, pdf_file = generate_violation_pdf(violations, score)
|
| 468 |
report_id, final_pdf_url = push_report_to_salesforce(violations, score, pdf_path, pdf_file)
|
| 469 |
|
| 470 |
+
violation_table = "| Violation | Timestamp (s) | Confidence | Worker ID (Helmet Only) |\n"
|
| 471 |
+
violation_table += "|------------------------|---------------|------------|--------------------------|\n"
|
| 472 |
for v in sorted(violations, key=lambda x: x["timestamp"]):
|
| 473 |
display_name = CONFIG["DISPLAY_NAMES"].get(v.get("violation", "Unknown"), "Unknown")
|
| 474 |
+
worker_id = v.get("worker_id", "N/A") if v.get("violation") == "no_helmet" else "N/A"
|
| 475 |
+
row = f"| {display_name:<22} | {v.get('timestamp', 0.0):.2f} | {v.get('confidence', 0.0):.2f} | {worker_id} |\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 476 |
violation_table += row
|
| 477 |
|
| 478 |
+
# Create HTML for snapshots with clickable links
|
| 479 |
+
snapshots_html = "<div style='display: flex; flex-wrap: wrap; gap: 10px;'>"
|
| 480 |
+
for s in snapshots:
|
| 481 |
+
display_name = CONFIG["DISPLAY_NAMES"].get(s["violation"], "Unknown")
|
| 482 |
+
worker_text = f"Worker {s['worker_id']}" if "worker_id" in s else ""
|
| 483 |
+
snapshots_html += f"""
|
| 484 |
+
<div style='text-align: center; margin: 10px;'>
|
| 485 |
+
<a href='{s['snapshot_url']}' target='_blank'>
|
| 486 |
+
<img src='{s['snapshot_url']}' style='max-width: 200px; max-height: 150px;'/>
|
| 487 |
+
</a>
|
| 488 |
+
<p>{display_name} at frame {s['frame']} {worker_text}</p>
|
| 489 |
+
</div>
|
| 490 |
+
"""
|
| 491 |
+
snapshots_html += "</div>"
|
| 492 |
|
| 493 |
yield (
|
| 494 |
violation_table,
|
| 495 |
f"Safety Score: {score}%",
|
| 496 |
+
snapshots_html,
|
| 497 |
f"Salesforce Record ID: {report_id or 'N/A'}",
|
| 498 |
final_pdf_url or "N/A"
|
| 499 |
)
|
|
|
|
| 512 |
with open(video_file, "rb") as f:
|
| 513 |
video_data = f.read()
|
| 514 |
|
| 515 |
+
for status, score, snapshots_html, record_id, details_url in process_video(video_data):
|
| 516 |
+
yield status, score, snapshots_html, record_id, details_url
|
| 517 |
except Exception as e:
|
| 518 |
logger.error(f"Error in Gradio interface: {e}", exc_info=True)
|
| 519 |
yield f"Error: {str(e)}", "", "Error in processing.", "", ""
|
|
|
|
| 524 |
outputs=[
|
| 525 |
gr.Markdown(label="Detected Safety Violations"),
|
| 526 |
gr.Textbox(label="Compliance Score"),
|
| 527 |
+
gr.HTML(label="Violation Snapshots (Click to enlarge)"),
|
| 528 |
gr.Textbox(label="Salesforce Record ID"),
|
| 529 |
gr.Textbox(label="Violation Details URL")
|
| 530 |
],
|