Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,11 +5,7 @@ import torch
|
|
| 5 |
import numpy as np
|
| 6 |
from ultralytics import YOLO
|
| 7 |
import time
|
| 8 |
-
from reportlab.lib.pagesizes import letter
|
| 9 |
-
from reportlab.pdfgen import canvas
|
| 10 |
-
from reportlab.lib.utils import ImageReader
|
| 11 |
import base64
|
| 12 |
-
from PIL import Image
|
| 13 |
from simple_salesforce import Salesforce
|
| 14 |
|
| 15 |
# ==========================
|
|
@@ -51,13 +47,18 @@ except Exception as e:
|
|
| 51 |
# Salesforce connection
|
| 52 |
# ==========================
|
| 53 |
def connect_to_salesforce():
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
def violations_to_text(violations):
|
| 63 |
lines = []
|
|
@@ -74,31 +75,33 @@ def generate_violation_text_file(violations):
|
|
| 74 |
f.write("Worksite Safety Violation Details\n")
|
| 75 |
f.write("=" * 40 + "\n")
|
| 76 |
f.write(violations_to_text(violations))
|
| 77 |
-
print(f"Text file generated at {text_path}")
|
| 78 |
-
|
|
|
|
|
|
|
| 79 |
except Exception as e:
|
| 80 |
print(f"❌ Error generating text file: {e}")
|
| 81 |
-
return ""
|
| 82 |
-
|
| 83 |
-
def push_report_to_salesforce(score, violations, pdf_filename, text_filename):
|
| 84 |
-
sf = connect_to_salesforce()
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
text_url = f"{PUBLIC_BASE_URL}{os.path.basename(text_filename)}" if text_filename else ""
|
| 92 |
|
| 93 |
-
|
| 94 |
-
record = sf.Safety_Video_Report__c.create({
|
| 95 |
"Compliance_Score__c": score,
|
| 96 |
"Violations_Found__c": violations_count,
|
| 97 |
"Violations_Details__c": violations_details,
|
| 98 |
"Status__c": "Pending",
|
| 99 |
-
"PDF_Report_URL__c":
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
| 102 |
print(f"✅ Salesforce record created with Id: {record.get('id')}")
|
| 103 |
return record.get("id")
|
| 104 |
except Exception as e:
|
|
@@ -120,51 +123,6 @@ def calculate_safety_score(violations):
|
|
| 120 |
base_score -= penalties.get(v["violation"], 0)
|
| 121 |
return max(base_score, 0)
|
| 122 |
|
| 123 |
-
# ==========================
|
| 124 |
-
# PDF Report Generation
|
| 125 |
-
# ==========================
|
| 126 |
-
def generate_pdf_report(violations, snapshots, score):
|
| 127 |
-
try:
|
| 128 |
-
pdf_path = os.path.join(STATIC_OUTPUT_DIR, f"report_{int(time.time())}.pdf")
|
| 129 |
-
c = canvas.Canvas(pdf_path, pagesize=letter)
|
| 130 |
-
width, height = letter
|
| 131 |
-
|
| 132 |
-
c.setFont("Helvetica-Bold", 16)
|
| 133 |
-
c.drawString(50, height - 50, "Worksite Safety Compliance Report")
|
| 134 |
-
|
| 135 |
-
c.setFont("Helvetica", 12)
|
| 136 |
-
c.drawString(50, height - 80, f"Compliance Score: {score}%")
|
| 137 |
-
|
| 138 |
-
y = height - 120
|
| 139 |
-
c.setFont("Helvetica-Bold", 12)
|
| 140 |
-
c.drawString(50, y, "Detected Violations:")
|
| 141 |
-
y -= 20
|
| 142 |
-
|
| 143 |
-
for v in violations:
|
| 144 |
-
c.setFont("Helvetica", 10)
|
| 145 |
-
text = f"Violation: {v['violation']}, Timestamp: {v['timestamp']:.2f}s, Confidence: {v['confidence']}"
|
| 146 |
-
c.drawString(50, y, text)
|
| 147 |
-
y -= 20
|
| 148 |
-
|
| 149 |
-
snapshot = next((s for s in snapshots if s["frame"] == v["frame"] and s["violation"] == v["violation"]), None)
|
| 150 |
-
if snapshot:
|
| 151 |
-
local_img_path = os.path.join(STATIC_OUTPUT_DIR, os.path.basename(snapshot["snapshot_url"]))
|
| 152 |
-
if os.path.exists(local_img_path):
|
| 153 |
-
img = ImageReader(local_img_path)
|
| 154 |
-
c.drawImage(img, 50, y - 100, width=200, height=150)
|
| 155 |
-
y -= 170
|
| 156 |
-
|
| 157 |
-
if y < 50:
|
| 158 |
-
c.showPage()
|
| 159 |
-
y = height - 50
|
| 160 |
-
|
| 161 |
-
c.save()
|
| 162 |
-
print(f"PDF generated at {pdf_path}")
|
| 163 |
-
return pdf_path
|
| 164 |
-
except Exception as e:
|
| 165 |
-
print(f"❌ Error generating PDF: {e}")
|
| 166 |
-
return ""
|
| 167 |
-
|
| 168 |
# ==========================
|
| 169 |
# Video Processing
|
| 170 |
# ==========================
|
|
@@ -174,7 +132,7 @@ def process_video(video_data, frame_skip=5, max_frames=100):
|
|
| 174 |
video_path = os.path.join(STATIC_OUTPUT_DIR, f"temp_{int(time.time())}.mp4")
|
| 175 |
with open(video_path, "wb") as f:
|
| 176 |
f.write(video_data)
|
| 177 |
-
print(f"Video saved to {video_path}")
|
| 178 |
|
| 179 |
video = cv2.VideoCapture(video_path)
|
| 180 |
if not video.isOpened():
|
|
@@ -235,24 +193,21 @@ def process_video(video_data, frame_skip=5, max_frames=100):
|
|
| 235 |
os.remove(video_path)
|
| 236 |
|
| 237 |
score = calculate_safety_score(violations)
|
| 238 |
-
|
| 239 |
-
text_path = generate_violation_text_file(violations)
|
| 240 |
|
| 241 |
-
if
|
| 242 |
-
report_id = push_report_to_salesforce(score, violations,
|
| 243 |
-
print(f"Salesforce record created with Id: {report_id}")
|
| 244 |
else:
|
| 245 |
report_id = None
|
| 246 |
-
|
| 247 |
-
with open(pdf_path, "rb") as f:
|
| 248 |
-
pdf_base64 = base64.b64encode(f.read()).decode('utf-8')
|
| 249 |
|
| 250 |
return {
|
| 251 |
"violations": violations,
|
| 252 |
"snapshots": snapshots,
|
| 253 |
"score": score,
|
| 254 |
-
"
|
| 255 |
-
"
|
| 256 |
}
|
| 257 |
|
| 258 |
except Exception as e:
|
|
@@ -261,8 +216,8 @@ def process_video(video_data, frame_skip=5, max_frames=100):
|
|
| 261 |
"violations": [],
|
| 262 |
"snapshots": [],
|
| 263 |
"score": 0,
|
| 264 |
-
"pdf_base64": "",
|
| 265 |
"salesforce_record_id": None,
|
|
|
|
| 266 |
"error": str(e)
|
| 267 |
}
|
| 268 |
|
|
@@ -272,7 +227,7 @@ def process_video(video_data, frame_skip=5, max_frames=100):
|
|
| 272 |
def gradio_interface(video_file):
|
| 273 |
try:
|
| 274 |
if not video_file:
|
| 275 |
-
return {"error": "Please upload a video file."}, "",
|
| 276 |
|
| 277 |
with open(video_file, "rb") as f:
|
| 278 |
video_data = f.read()
|
|
@@ -281,13 +236,13 @@ def gradio_interface(video_file):
|
|
| 281 |
return (
|
| 282 |
result.get("violations", []),
|
| 283 |
f"Safety Score: {result.get('score', 0)}%",
|
| 284 |
-
result.get("pdf_base64", ""),
|
| 285 |
result.get("snapshots", []),
|
| 286 |
-
f"Salesforce Record ID: {result.get('salesforce_record_id', '')}"
|
|
|
|
| 287 |
)
|
| 288 |
except Exception as e:
|
| 289 |
print(f"❌ Error in gradio_interface: {e}")
|
| 290 |
-
return {"error": str(e)}, "",
|
| 291 |
|
| 292 |
interface = gr.Interface(
|
| 293 |
fn=gradio_interface,
|
|
@@ -295,9 +250,9 @@ interface = gr.Interface(
|
|
| 295 |
outputs=[
|
| 296 |
gr.JSON(label="Detected Safety Violations"),
|
| 297 |
gr.Textbox(label="Compliance Score"),
|
| 298 |
-
gr.Textbox(label="PDF Base64 (for API use)"),
|
| 299 |
gr.JSON(label="Snapshots"),
|
| 300 |
-
gr.Textbox(label="Salesforce Record ID")
|
|
|
|
| 301 |
],
|
| 302 |
title="Worksite Safety Violation Analyzer",
|
| 303 |
description="Upload short site videos to detect safety violations (e.g., no helmet, no harness, unsafe posture)."
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
from ultralytics import YOLO
|
| 7 |
import time
|
|
|
|
|
|
|
|
|
|
| 8 |
import base64
|
|
|
|
| 9 |
from simple_salesforce import Salesforce
|
| 10 |
|
| 11 |
# ==========================
|
|
|
|
| 47 |
# Salesforce connection
|
| 48 |
# ==========================
|
| 49 |
def connect_to_salesforce():
|
| 50 |
+
try:
|
| 51 |
+
sf = Salesforce(
|
| 52 |
+
username="prashanth1ai@safety.com",
|
| 53 |
+
password="SaiPrash461",
|
| 54 |
+
security_token="AP4AQnPoidIKPvSvNEfAHyoK",
|
| 55 |
+
domain="login"
|
| 56 |
+
)
|
| 57 |
+
print("✅ Connected to Salesforce")
|
| 58 |
+
return sf
|
| 59 |
+
except Exception as e:
|
| 60 |
+
print(f"❌ Salesforce connection failed: {e}")
|
| 61 |
+
raise
|
| 62 |
|
| 63 |
def violations_to_text(violations):
|
| 64 |
lines = []
|
|
|
|
| 75 |
f.write("Worksite Safety Violation Details\n")
|
| 76 |
f.write("=" * 40 + "\n")
|
| 77 |
f.write(violations_to_text(violations))
|
| 78 |
+
print(f"✅ Text file generated at {text_path}")
|
| 79 |
+
public_url = f"https://huggingface.co/spaces/PrashanthB461/AI_Safety_Demo1/resolve/main/static/output/{text_filename}"
|
| 80 |
+
print(f"✅ Text file URL: {public_url}")
|
| 81 |
+
return text_path, public_url
|
| 82 |
except Exception as e:
|
| 83 |
print(f"❌ Error generating text file: {e}")
|
| 84 |
+
return "", ""
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
def push_report_to_salesforce(score, violations, text_filename):
|
| 87 |
+
try:
|
| 88 |
+
sf = connect_to_salesforce()
|
| 89 |
+
violations_count = len(violations)
|
| 90 |
+
violations_details = violations_to_text(violations)
|
| 91 |
|
| 92 |
+
PUBLIC_BASE_URL = "https://huggingface.co/spaces/PrashanthB461/AI_Safety_Demo1/resolve/main/static/output/"
|
| 93 |
+
text_url = f"{PUBLIC_BASE_URL}{os.path.basename(text_filename)}"
|
|
|
|
| 94 |
|
| 95 |
+
record_data = {
|
|
|
|
| 96 |
"Compliance_Score__c": score,
|
| 97 |
"Violations_Found__c": violations_count,
|
| 98 |
"Violations_Details__c": violations_details,
|
| 99 |
"Status__c": "Pending",
|
| 100 |
+
"PDF_Report_URL__c": text_url # Store text file URL in PDF_Report_URL__c
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
print(f"Attempting to create Salesforce record with data: {record_data}")
|
| 104 |
+
record = sf.Safety_Video_Report__c.create(record_data)
|
| 105 |
print(f"✅ Salesforce record created with Id: {record.get('id')}")
|
| 106 |
return record.get("id")
|
| 107 |
except Exception as e:
|
|
|
|
| 123 |
base_score -= penalties.get(v["violation"], 0)
|
| 124 |
return max(base_score, 0)
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
# ==========================
|
| 127 |
# Video Processing
|
| 128 |
# ==========================
|
|
|
|
| 132 |
video_path = os.path.join(STATIC_OUTPUT_DIR, f"temp_{int(time.time())}.mp4")
|
| 133 |
with open(video_path, "wb") as f:
|
| 134 |
f.write(video_data)
|
| 135 |
+
print(f"✅ Video saved to {video_path}")
|
| 136 |
|
| 137 |
video = cv2.VideoCapture(video_path)
|
| 138 |
if not video.isOpened():
|
|
|
|
| 193 |
os.remove(video_path)
|
| 194 |
|
| 195 |
score = calculate_safety_score(violations)
|
| 196 |
+
text_path, text_url = generate_violation_text_file(violations)
|
|
|
|
| 197 |
|
| 198 |
+
if text_path:
|
| 199 |
+
report_id = push_report_to_salesforce(score, violations, text_path)
|
| 200 |
+
print(f"✅ Salesforce record created with Id: {report_id}")
|
| 201 |
else:
|
| 202 |
report_id = None
|
| 203 |
+
print("❌ No text file generated, skipping Salesforce record creation")
|
|
|
|
|
|
|
| 204 |
|
| 205 |
return {
|
| 206 |
"violations": violations,
|
| 207 |
"snapshots": snapshots,
|
| 208 |
"score": score,
|
| 209 |
+
"salesforce_record_id": report_id,
|
| 210 |
+
"violation_details_url": text_url
|
| 211 |
}
|
| 212 |
|
| 213 |
except Exception as e:
|
|
|
|
| 216 |
"violations": [],
|
| 217 |
"snapshots": [],
|
| 218 |
"score": 0,
|
|
|
|
| 219 |
"salesforce_record_id": None,
|
| 220 |
+
"violation_details_url": "",
|
| 221 |
"error": str(e)
|
| 222 |
}
|
| 223 |
|
|
|
|
| 227 |
def gradio_interface(video_file):
|
| 228 |
try:
|
| 229 |
if not video_file:
|
| 230 |
+
return {"error": "Please upload a video file."}, "", [], ""
|
| 231 |
|
| 232 |
with open(video_file, "rb") as f:
|
| 233 |
video_data = f.read()
|
|
|
|
| 236 |
return (
|
| 237 |
result.get("violations", []),
|
| 238 |
f"Safety Score: {result.get('score', 0)}%",
|
|
|
|
| 239 |
result.get("snapshots", []),
|
| 240 |
+
f"Salesforce Record ID: {result.get('salesforce_record_id', '')}",
|
| 241 |
+
f"Violation Details URL: {result.get('violation_details_url', '')}"
|
| 242 |
)
|
| 243 |
except Exception as e:
|
| 244 |
print(f"❌ Error in gradio_interface: {e}")
|
| 245 |
+
return {"error": str(e)}, "", [], "", ""
|
| 246 |
|
| 247 |
interface = gr.Interface(
|
| 248 |
fn=gradio_interface,
|
|
|
|
| 250 |
outputs=[
|
| 251 |
gr.JSON(label="Detected Safety Violations"),
|
| 252 |
gr.Textbox(label="Compliance Score"),
|
|
|
|
| 253 |
gr.JSON(label="Snapshots"),
|
| 254 |
+
gr.Textbox(label="Salesforce Record ID"),
|
| 255 |
+
gr.Textbox(label="Violation Details URL")
|
| 256 |
],
|
| 257 |
title="Worksite Safety Violation Analyzer",
|
| 258 |
description="Upload short site videos to detect safety violations (e.g., no helmet, no harness, unsafe posture)."
|