PrashanthB461 commited on
Commit
4c4b661
·
verified ·
1 Parent(s): 2232624

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -9
app.py CHANGED
@@ -23,7 +23,7 @@ import tempfile
23
  import shutil
24
 
25
  # ========================== # Configuration and Setup # ==========================
26
- # Use a temporary directory for storage
27
  TEMP_DIR = tempfile.mkdtemp(prefix="Ultralytics_")
28
  os.environ['YOLO_CONFIG_DIR'] = TEMP_DIR
29
 
@@ -31,10 +31,11 @@ os.environ['YOLO_CONFIG_DIR'] = TEMP_DIR
31
  OUTPUT_DIR = os.path.join(TEMP_DIR, "output")
32
  os.makedirs(OUTPUT_DIR, exist_ok=True)
33
 
 
34
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
35
  logger = logging.getLogger(__name__)
36
 
37
- # Check for FFmpeg availability
38
  def check_ffmpeg():
39
  try:
40
  subprocess.run(["ffmpeg", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
@@ -215,9 +216,9 @@ CONFIG = {
215
  "improper_tool_use": "Improper Tool Use"
216
  },
217
  "SF_CREDENTIALS": {
218
- "username": "prashanth1ai@safety.com",
219
- "password": "SaiPrash461",
220
- "security_token": "AP4AQnPoidIKPvSvNEfAHyoK",
221
  "domain": "login"
222
  },
223
  "PUBLIC_URL_BASE": "https://huggingface.co/spaces/PrashanthB461/AI_Safety_Demo2/resolve/main/static/output/",
@@ -635,7 +636,7 @@ def process_video(video_data):
635
  detection = {
636
  "worker_id": worker_id,
637
  "violation": label,
638
- "confidence": round(conf, 2),
639
  "bounding_box": bbox,
640
  "timestamp": current_time
641
  }
@@ -667,7 +668,8 @@ def process_video(video_data):
667
  "worker_id": worker_id,
668
  "timestamp": current_time,
669
  "snapshot_path": snapshot_path,
670
- "snapshot_url": f"{CONFIG['PUBLIC_URL_BASE']}{snapshot_filename}"
 
671
  })
672
 
673
  logger.info(f"Captured snapshot for {label} violation by worker {worker_id} at {current_time:.2f}s")
@@ -680,17 +682,28 @@ def process_video(video_data):
680
  processing_time = time.time() - start_time
681
  logger.info(f"Processing complete in {processing_time:.2f}s")
682
 
 
 
 
683
  violations = []
684
  for worker_id, worker_violations in unique_violations.items():
685
  for label, detection_time in worker_violations.items():
 
 
 
 
 
686
  violation = {
687
  "worker_id": worker_id,
688
  "violation": label,
689
  "timestamp": detection_time,
690
- "confidence": next((s["confidence"] for s in snapshots if s["worker_id"] == worker_id and s["violation"] == label), 0.0)
691
  }
692
  violations.append(violation)
693
 
 
 
 
694
  if not violations:
695
  logger.info("No violations detected after processing")
696
  yield "No violations detected in the video.", "Safety Score: 100%", "No snapshots captured.", "N/A", "N/A"
@@ -702,6 +715,7 @@ def process_video(video_data):
702
  # Push to Salesforce with fallback
703
  record_id, final_pdf_url = push_report_to_salesforce(violations, score, pdf_path, pdf_file)
704
 
 
705
  violation_table = "| Violation | Worker ID | Time (s) | Confidence |\n"
706
  violation_table += "|-----------|-----------|----------|------------|\n"
707
 
@@ -709,7 +723,12 @@ def process_video(video_data):
709
  display_name = CONFIG["DISPLAY_NAMES"].get(v.get("violation", "Unknown"), "Unknown")
710
  worker_id = v.get("worker_id", "Unknown")
711
  timestamp = v.get("timestamp", 0.0)
712
- confidence = v.get("confidence", 0.0)
 
 
 
 
 
713
 
714
  violation_table += f"| {display_name} | {worker_id} | {timestamp:.2f} | {confidence:.2f} |\n"
715
 
 
23
  import shutil
24
 
25
  # ========================== # Configuration and Setup # ==========================
26
+ # Use a temporary directory for storage to avoid file system issues on Hugging Face Spaces
27
  TEMP_DIR = tempfile.mkdtemp(prefix="Ultralytics_")
28
  os.environ['YOLO_CONFIG_DIR'] = TEMP_DIR
29
 
 
31
  OUTPUT_DIR = os.path.join(TEMP_DIR, "output")
32
  os.makedirs(OUTPUT_DIR, exist_ok=True)
33
 
34
+ # Configure logging for better debugging
35
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
36
  logger = logging.getLogger(__name__)
37
 
38
+ # Check for FFmpeg availability to ensure video processing works
39
  def check_ffmpeg():
40
  try:
41
  subprocess.run(["ffmpeg", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
 
216
  "improper_tool_use": "Improper Tool Use"
217
  },
218
  "SF_CREDENTIALS": {
219
+ "username": os.getenv("SF_USERNAME", "prashanth1ai@safety.com"),
220
+ "password": os.getenv("SF_PASSWORD", "SaiPrash461"),
221
+ "security_token": os.getenv("SF_SECURITY_TOKEN", "AP4AQnPoidIKPvSvNEfAHyoK"),
222
  "domain": "login"
223
  },
224
  "PUBLIC_URL_BASE": "https://huggingface.co/spaces/PrashanthB461/AI_Safety_Demo2/resolve/main/static/output/",
 
636
  detection = {
637
  "worker_id": worker_id,
638
  "violation": label,
639
+ "confidence": round(float(conf), 2), # Ensure confidence is a float
640
  "bounding_box": bbox,
641
  "timestamp": current_time
642
  }
 
668
  "worker_id": worker_id,
669
  "timestamp": current_time,
670
  "snapshot_path": snapshot_path,
671
+ "snapshot_url": f"{CONFIG['PUBLIC_URL_BASE']}{snapshot_filename}",
672
+ "confidence": round(float(conf), 2) # Ensure confidence is stored as float
673
  })
674
 
675
  logger.info(f"Captured snapshot for {label} violation by worker {worker_id} at {current_time:.2f}s")
 
682
  processing_time = time.time() - start_time
683
  logger.info(f"Processing complete in {processing_time:.2f}s")
684
 
685
+ # Log the snapshots for debugging
686
+ logger.info(f"Snapshots: {snapshots}")
687
+
688
  violations = []
689
  for worker_id, worker_violations in unique_violations.items():
690
  for label, detection_time in worker_violations.items():
691
+ # Find the confidence from snapshots, ensuring it's a float
692
+ confidence = next(
693
+ (float(s["confidence"]) for s in snapshots if s["worker_id"] == worker_id and s["violation"] == label),
694
+ 0.0
695
+ )
696
  violation = {
697
  "worker_id": worker_id,
698
  "violation": label,
699
  "timestamp": detection_time,
700
+ "confidence": confidence
701
  }
702
  violations.append(violation)
703
 
704
+ # Log the violations for debugging
705
+ logger.info(f"Violations: {violations}")
706
+
707
  if not violations:
708
  logger.info("No violations detected after processing")
709
  yield "No violations detected in the video.", "Safety Score: 100%", "No snapshots captured.", "N/A", "N/A"
 
715
  # Push to Salesforce with fallback
716
  record_id, final_pdf_url = push_report_to_salesforce(violations, score, pdf_path, pdf_file)
717
 
718
+ # Generate violation table with robust error handling
719
  violation_table = "| Violation | Worker ID | Time (s) | Confidence |\n"
720
  violation_table += "|-----------|-----------|----------|------------|\n"
721
 
 
723
  display_name = CONFIG["DISPLAY_NAMES"].get(v.get("violation", "Unknown"), "Unknown")
724
  worker_id = v.get("worker_id", "Unknown")
725
  timestamp = v.get("timestamp", 0.0)
726
+ # Ensure confidence is a valid float
727
+ try:
728
+ confidence = float(v.get("confidence", 0.0))
729
+ except (ValueError, TypeError) as e:
730
+ logger.error(f"Invalid confidence value in violation {v}: {e}")
731
+ confidence = 0.0
732
 
733
  violation_table += f"| {display_name} | {worker_id} | {timestamp:.2f} | {confidence:.2f} |\n"
734