Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,26 +3,9 @@ import cv2
|
|
| 3 |
import gradio as gr
|
| 4 |
import torch
|
| 5 |
import numpy as np
|
| 6 |
-
from
|
| 7 |
import time
|
| 8 |
|
| 9 |
-
# Salesforce connection details (replace these with your actual credentials)
|
| 10 |
-
sf = Salesforce(username='prashanth@safetyanaluzer.com', password='SaiPrash461', security_token='MOA3BXBfGyqnjBneog8a9IcGw')
|
| 11 |
-
|
| 12 |
-
# Test Salesforce connection
|
| 13 |
-
try:
|
| 14 |
-
# Simple query to verify the connection
|
| 15 |
-
result = sf.query("SELECT Id FROM Safety_Video_Report__c LIMIT 1")
|
| 16 |
-
print("✅ Salesforce connection successful.")
|
| 17 |
-
except Exception as e:
|
| 18 |
-
print(f"❌ Error connecting to Salesforce: {e}")
|
| 19 |
-
|
| 20 |
-
try:
|
| 21 |
-
from ultralytics import YOLO
|
| 22 |
-
except ImportError as e:
|
| 23 |
-
print("❌ Ultralytics not installed. Run: pip install ultralytics")
|
| 24 |
-
raise
|
| 25 |
-
|
| 26 |
# ==========================
|
| 27 |
# Configuration
|
| 28 |
# ==========================
|
|
@@ -40,29 +23,14 @@ VIOLATION_LABELS = {
|
|
| 40 |
# ==========================
|
| 41 |
# Device Setup
|
| 42 |
# ==========================
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
print(f"✅ Using device: {device}")
|
| 46 |
-
except Exception as e:
|
| 47 |
-
print(f"⚠️ Error setting device: {e}")
|
| 48 |
-
device = torch.device("cpu")
|
| 49 |
|
| 50 |
# ==========================
|
| 51 |
# Load Model (Use YOLOv8n for Faster Inference)
|
| 52 |
# ==========================
|
| 53 |
-
if os.path.isfile(MODEL_PATH)
|
| 54 |
-
|
| 55 |
-
print(f"✅ Found model at: {selected_model}")
|
| 56 |
-
else:
|
| 57 |
-
print(f"⚠️ Model file '{MODEL_PATH}' not found. Falling back to: {FALLBACK_MODEL}")
|
| 58 |
-
selected_model = FALLBACK_MODEL
|
| 59 |
-
|
| 60 |
-
try:
|
| 61 |
-
model = YOLO(selected_model)
|
| 62 |
-
print(f"✅ Model loaded: {selected_model}")
|
| 63 |
-
except Exception as e:
|
| 64 |
-
print(f"❌ Failed to load model: {e}")
|
| 65 |
-
raise
|
| 66 |
|
| 67 |
# ==========================
|
| 68 |
# Video Processing with Optimizations
|
|
@@ -83,7 +51,6 @@ def process_video(video_path, frame_skip=5, max_frames=100):
|
|
| 83 |
if not ret:
|
| 84 |
break
|
| 85 |
|
| 86 |
-
# Skip frames to reduce processing time (process only every 'frame_skip' frame)
|
| 87 |
if frame_count % frame_skip != 0:
|
| 88 |
frame_count += 1
|
| 89 |
continue
|
|
@@ -108,11 +75,9 @@ def process_video(video_path, frame_skip=5, max_frames=100):
|
|
| 108 |
frame_count += 1
|
| 109 |
processed_frame_count += 1
|
| 110 |
|
| 111 |
-
# Stop processing after a fixed number of frames to save time
|
| 112 |
if processed_frame_count >= max_frames:
|
| 113 |
break
|
| 114 |
|
| 115 |
-
# Check elapsed time, stop if we exceed 30 seconds
|
| 116 |
elapsed_time = time.time() - start_time
|
| 117 |
if elapsed_time > 30:
|
| 118 |
print("⏰ Exceeded 30 seconds of processing time.")
|
|
@@ -121,14 +86,14 @@ def process_video(video_path, frame_skip=5, max_frames=100):
|
|
| 121 |
video.release()
|
| 122 |
score = calculate_safety_score(violations)
|
| 123 |
|
| 124 |
-
#
|
| 125 |
-
|
| 126 |
|
| 127 |
-
return violations, score
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
print(f"❌ Error processing video: {e}")
|
| 131 |
-
return [], f"Error: {e}"
|
| 132 |
|
| 133 |
# ==========================
|
| 134 |
# Safety Score Calculation
|
|
@@ -145,64 +110,13 @@ def calculate_safety_score(violations):
|
|
| 145 |
base_score -= penalties.get(v["violation"], 0)
|
| 146 |
return max(base_score, 0)
|
| 147 |
|
| 148 |
-
def send_to_salesforce(violations, score, video_path):
|
| 149 |
-
# Dynamic values (e.g., from user input)
|
| 150 |
-
site_name = "Construction Site 1" # Replace with dynamic data from your app
|
| 151 |
-
uploaded_by = "JohnDoe" # Replace with actual user info (e.g., from session or UI)
|
| 152 |
-
upload_date = "2025-05-08T12:00:00Z" # Replace with actual upload date
|
| 153 |
-
status = "Reviewed" # Update based on video processing result
|
| 154 |
-
|
| 155 |
-
print("Starting file upload to Salesforce...")
|
| 156 |
-
# Video file upload
|
| 157 |
-
file_id = upload_video_to_salesforce(video_path) # Upload the video and get the file ID
|
| 158 |
-
print(f"File uploaded to Salesforce with ID: {file_id}")
|
| 159 |
-
|
| 160 |
-
# Violations details: Frame number, violation type, confidence level
|
| 161 |
-
violations_details = "\n".join([f"Frame {v['frame']}: {v['violation']} (Confidence: {v['confidence']})" for v in violations])
|
| 162 |
-
|
| 163 |
-
# Data to be inserted into Salesforce
|
| 164 |
-
data = {
|
| 165 |
-
'Site__c': site_name,
|
| 166 |
-
'Uploaded_By__c': uploaded_by,
|
| 167 |
-
'Upload_Date__c': upload_date,
|
| 168 |
-
'Status__c': status,
|
| 169 |
-
'Compliance_Score__c': score,
|
| 170 |
-
'Violations_Found__c': len(violations),
|
| 171 |
-
'Violations_Details__c': violations_details,
|
| 172 |
-
'Video_File__c': file_id, # This is the file ID from ContentVersion
|
| 173 |
-
'PDF_Report_URL__c': "http://path_to_pdf_report" # Replace with actual PDF report URL if available
|
| 174 |
-
}
|
| 175 |
-
|
| 176 |
-
try:
|
| 177 |
-
print(f"Creating Salesforce record with data: {data}") # Log data being sent to Salesforce
|
| 178 |
-
result = sf.Safety_Video_Report__c.create(data) # Changed the object name to Safety_Video_Report__c
|
| 179 |
-
print(f"✅ Successfully created new report in Salesforce with ID: {result['id']}")
|
| 180 |
-
except Exception as e:
|
| 181 |
-
print(f"❌ Error creating/updating record in Salesforce: {e}")
|
| 182 |
-
|
| 183 |
# ==========================
|
| 184 |
-
#
|
| 185 |
# ==========================
|
| 186 |
-
def
|
| 187 |
-
with
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
content_version_data = {
|
| 191 |
-
'Title': 'Safety Video',
|
| 192 |
-
'PathOnClient': 'safety_video.mp4', # Path of the file on the client's system
|
| 193 |
-
'VersionData': video_data, # Video file content as binary
|
| 194 |
-
'FirstPublishLocationId': 'your_salesforce_library_id', # Library ID (if required, or leave blank)
|
| 195 |
-
}
|
| 196 |
-
|
| 197 |
-
try:
|
| 198 |
-
# Create a new ContentVersion record to upload the video
|
| 199 |
-
content_version = sf.ContentVersion.create(content_version_data)
|
| 200 |
-
file_id = content_version['Id'] # This is the ContentDocument ID
|
| 201 |
-
print(f"✅ Video uploaded to Salesforce with File ID: {file_id}")
|
| 202 |
-
return file_id
|
| 203 |
-
except Exception as e:
|
| 204 |
-
print(f"❌ Error uploading video to Salesforce: {e}")
|
| 205 |
-
return None
|
| 206 |
|
| 207 |
# ==========================
|
| 208 |
# Gradio Interface
|
|
@@ -211,16 +125,13 @@ def gradio_interface(video_file):
|
|
| 211 |
if not video_file:
|
| 212 |
return "Please upload a video file.", ""
|
| 213 |
|
| 214 |
-
violations, score = process_video(video_file)
|
| 215 |
-
return violations, f"Safety Score: {score}%"
|
| 216 |
|
| 217 |
interface = gr.Interface(
|
| 218 |
fn=gradio_interface,
|
| 219 |
inputs=gr.Video(label="Upload Site Video"),
|
| 220 |
-
outputs=[
|
| 221 |
-
gr.JSON(label="Detected Safety Violations"),
|
| 222 |
-
gr.Textbox(label="Compliance Score")
|
| 223 |
-
],
|
| 224 |
title="Worksite Safety Violation Analyzer",
|
| 225 |
description="Upload short site videos to detect safety violations (e.g., no helmet, no harness, unsafe posture)."
|
| 226 |
)
|
|
|
|
| 3 |
import gradio as gr
|
| 4 |
import torch
|
| 5 |
import numpy as np
|
| 6 |
+
from ultralytics import YOLO
|
| 7 |
import time
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
# ==========================
|
| 10 |
# Configuration
|
| 11 |
# ==========================
|
|
|
|
| 23 |
# ==========================
|
| 24 |
# Device Setup
|
| 25 |
# ==========================
|
| 26 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
+
print(f"✅ Using device: {device}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
# ==========================
|
| 30 |
# Load Model (Use YOLOv8n for Faster Inference)
|
| 31 |
# ==========================
|
| 32 |
+
selected_model = MODEL_PATH if os.path.isfile(MODEL_PATH) else FALLBACK_MODEL
|
| 33 |
+
model = YOLO(selected_model)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
# ==========================
|
| 36 |
# Video Processing with Optimizations
|
|
|
|
| 51 |
if not ret:
|
| 52 |
break
|
| 53 |
|
|
|
|
| 54 |
if frame_count % frame_skip != 0:
|
| 55 |
frame_count += 1
|
| 56 |
continue
|
|
|
|
| 75 |
frame_count += 1
|
| 76 |
processed_frame_count += 1
|
| 77 |
|
|
|
|
| 78 |
if processed_frame_count >= max_frames:
|
| 79 |
break
|
| 80 |
|
|
|
|
| 81 |
elapsed_time = time.time() - start_time
|
| 82 |
if elapsed_time > 30:
|
| 83 |
print("⏰ Exceeded 30 seconds of processing time.")
|
|
|
|
| 86 |
video.release()
|
| 87 |
score = calculate_safety_score(violations)
|
| 88 |
|
| 89 |
+
# Generate the PDF report URL (using an external method or library)
|
| 90 |
+
pdf_report_url = generate_pdf_report(violations, score)
|
| 91 |
|
| 92 |
+
return violations, score, pdf_report_url
|
| 93 |
|
| 94 |
except Exception as e:
|
| 95 |
print(f"❌ Error processing video: {e}")
|
| 96 |
+
return [], f"Error: {e}", None
|
| 97 |
|
| 98 |
# ==========================
|
| 99 |
# Safety Score Calculation
|
|
|
|
| 110 |
base_score -= penalties.get(v["violation"], 0)
|
| 111 |
return max(base_score, 0)
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
# ==========================
|
| 114 |
+
# PDF Report Generation
|
| 115 |
# ==========================
|
| 116 |
+
def generate_pdf_report(violations, score):
|
| 117 |
+
# Create a PDF with violation details (This can be done using an external library or template)
|
| 118 |
+
pdf_url = "http://path_to_pdf_report" # URL to the generated PDF (replace with actual URL)
|
| 119 |
+
return pdf_url
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
# ==========================
|
| 122 |
# Gradio Interface
|
|
|
|
| 125 |
if not video_file:
|
| 126 |
return "Please upload a video file.", ""
|
| 127 |
|
| 128 |
+
violations, score, pdf_url = process_video(video_file)
|
| 129 |
+
return violations, f"Safety Score: {score}%", pdf_url
|
| 130 |
|
| 131 |
interface = gr.Interface(
|
| 132 |
fn=gradio_interface,
|
| 133 |
inputs=gr.Video(label="Upload Site Video"),
|
| 134 |
+
outputs=[gr.JSON(label="Detected Safety Violations"), gr.Textbox(label="Compliance Score"), gr.Textbox(label="PDF Report URL")],
|
|
|
|
|
|
|
|
|
|
| 135 |
title="Worksite Safety Violation Analyzer",
|
| 136 |
description="Upload short site videos to detect safety violations (e.g., no helmet, no harness, unsafe posture)."
|
| 137 |
)
|