Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -129,75 +129,6 @@ def generate_violation_pdf(violations, score):
|
|
| 129 |
logger.error(f"Error generating PDF: {e}")
|
| 130 |
return "", "", None
|
| 131 |
|
| 132 |
-
@retry(stop_max_attempt_number=3, wait_fixed=2000)
|
| 133 |
-
def upload_pdf_to_salesforce(sf, pdf_file, report_id):
|
| 134 |
-
try:
|
| 135 |
-
if not pdf_file:
|
| 136 |
-
logger.error("No PDF file provided for upload")
|
| 137 |
-
return ""
|
| 138 |
-
encoded_pdf = base64.b64encode(pdf_file.getvalue()).decode('utf-8')
|
| 139 |
-
content_version_data = {
|
| 140 |
-
"Title": f"Safety_Violation_Report_{int(time.time())}",
|
| 141 |
-
"PathOnClient": f"safety_violation_{int(time.time())}.pdf",
|
| 142 |
-
"VersionData": encoded_pdf,
|
| 143 |
-
"FirstPublishLocationId": report_id
|
| 144 |
-
}
|
| 145 |
-
content_version = sf.ContentVersion.create(content_version_data)
|
| 146 |
-
result = sf.query(f"SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = '{content_version['id']}'")
|
| 147 |
-
if not result['records']:
|
| 148 |
-
logger.error("Failed to retrieve ContentVersion")
|
| 149 |
-
return ""
|
| 150 |
-
file_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_version['id']}"
|
| 151 |
-
logger.info(f"PDF uploaded to Salesforce: {file_url}")
|
| 152 |
-
return file_url
|
| 153 |
-
except Exception as e:
|
| 154 |
-
logger.error(f"Error uploading PDF to Salesforce: {e}")
|
| 155 |
-
return ""
|
| 156 |
-
|
| 157 |
-
@retry(stop_max_attempt_number=3, wait_fixed=2000)
|
| 158 |
-
def push_report_to_salesforce(violations, score, pdf_path, pdf_file):
|
| 159 |
-
try:
|
| 160 |
-
sf = connect_to_salesforce()
|
| 161 |
-
violations_text = "\n".join(
|
| 162 |
-
f"{CONFIG['DISPLAY_NAMES'].get(v['violation'], v['violation'])} at {v['timestamp']:.2f}s (Confidence: {v['confidence']})"
|
| 163 |
-
for v in violations
|
| 164 |
-
) or "No violations detected."
|
| 165 |
-
pdf_url = f"{CONFIG['PUBLIC_URL_BASE']}{os.path.basename(pdf_path)}" if pdf_path else ""
|
| 166 |
-
|
| 167 |
-
record_data = {
|
| 168 |
-
"Compliance_Score__c": score,
|
| 169 |
-
"Violations_Found__c": len(violations),
|
| 170 |
-
"Violations_Details__c": violations_text,
|
| 171 |
-
"Status__c": "Pending",
|
| 172 |
-
"PDF_Report_URL__c": pdf_url
|
| 173 |
-
}
|
| 174 |
-
logger.info(f"Creating Salesforce record with data: {record_data}")
|
| 175 |
-
try:
|
| 176 |
-
record = sf.Safety_Video_Report__c.create(record_data)
|
| 177 |
-
logger.info(f"Created Safety_Video_Report__c record: {record['id']}")
|
| 178 |
-
except Exception as e:
|
| 179 |
-
logger.error(f"Failed to create Safety_Video_Report__c: {e}")
|
| 180 |
-
record = sf.Account.create({"Name": f"Safety_Report_{int(time.time())}"})
|
| 181 |
-
logger.warning(f"Fell back to Account record: {record['id']}")
|
| 182 |
-
record_id = record["id"]
|
| 183 |
-
|
| 184 |
-
if pdf_file:
|
| 185 |
-
uploaded_url = upload_pdf_to_salesforce(sf, pdf_file, record_id)
|
| 186 |
-
if uploaded_url:
|
| 187 |
-
try:
|
| 188 |
-
sf.Safety_Video_Report__c.update(record_id, {"PDF_Report_URL__c": uploaded_url})
|
| 189 |
-
logger.info(f"Updated record {record_id} with PDF URL: {uploaded_url}")
|
| 190 |
-
except Exception as e:
|
| 191 |
-
logger.error(f"Failed to update Safety_Video_Report__c: {e}")
|
| 192 |
-
sf.Account.update(record_id, {"Description": uploaded_url})
|
| 193 |
-
logger.info(f"Updated Account record {record_id} with PDF URL")
|
| 194 |
-
pdf_url = uploaded_url
|
| 195 |
-
|
| 196 |
-
return record_id, pdf_url
|
| 197 |
-
except Exception as e:
|
| 198 |
-
logger.error(f"Salesforce record creation failed: {e}", exc_info=True)
|
| 199 |
-
return None, ""
|
| 200 |
-
|
| 201 |
def calculate_safety_score(violations):
|
| 202 |
penalties = {
|
| 203 |
"no_helmet": 25,
|
|
@@ -224,7 +155,7 @@ def process_video(video_data):
|
|
| 224 |
fps = video.get(cv2.CAP_PROP_FPS)
|
| 225 |
|
| 226 |
snapshot_taken = {label: False for label in CONFIG["VIOLATION_LABELS"].values()}
|
| 227 |
-
|
| 228 |
|
| 229 |
while True:
|
| 230 |
ret, frame = video.read()
|
|
@@ -244,21 +175,21 @@ def process_video(video_data):
|
|
| 244 |
for box in result.boxes:
|
| 245 |
cls, conf = int(box.cls), float(box.conf)
|
| 246 |
label = CONFIG["VIOLATION_LABELS"].get(cls, None)
|
| 247 |
-
if label not in CONFIG["VIOLATION_LABELS"].values():
|
| 248 |
-
continue
|
| 249 |
-
if conf < CONFIG["CONFIDENCE_THRESHOLD"]:
|
| 250 |
continue
|
| 251 |
-
|
|
|
|
|
|
|
| 252 |
continue
|
| 253 |
-
seen_violations.add(label)
|
| 254 |
|
| 255 |
-
|
| 256 |
"frame": frame_count,
|
| 257 |
"violation": label,
|
| 258 |
"confidence": round(conf, 2),
|
|
|
|
| 259 |
"timestamp": frame_count / fps
|
| 260 |
}
|
| 261 |
-
violations.append(
|
| 262 |
|
| 263 |
if not snapshot_taken[label]:
|
| 264 |
snapshot_path = os.path.join(CONFIG["OUTPUT_DIR"], f"snapshot_{frame_count}_{label}.jpg")
|
|
@@ -329,13 +260,13 @@ def gradio_interface(video_file):
|
|
| 329 |
|
| 330 |
violation_table = "No violations detected."
|
| 331 |
if result["violations"]:
|
| 332 |
-
header = "| Violation | Timestamp (s) | Confidence |
|
| 333 |
-
separator = "
|
| 334 |
rows = []
|
| 335 |
violation_name_map = CONFIG["DISPLAY_NAMES"]
|
| 336 |
for v in result["violations"]:
|
| 337 |
display_name = violation_name_map.get(v["violation"], v["violation"])
|
| 338 |
-
row = f"| {display_name:<22} | {v['timestamp']:.2f} | {v['confidence']:.2f} |"
|
| 339 |
rows.append(row)
|
| 340 |
violation_table = header + separator + "\n".join(rows)
|
| 341 |
|
|
|
|
| 129 |
logger.error(f"Error generating PDF: {e}")
|
| 130 |
return "", "", None
|
| 131 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
def calculate_safety_score(violations):
|
| 133 |
penalties = {
|
| 134 |
"no_helmet": 25,
|
|
|
|
| 155 |
fps = video.get(cv2.CAP_PROP_FPS)
|
| 156 |
|
| 157 |
snapshot_taken = {label: False for label in CONFIG["VIOLATION_LABELS"].values()}
|
| 158 |
+
detected_violations = {}
|
| 159 |
|
| 160 |
while True:
|
| 161 |
ret, frame = video.read()
|
|
|
|
| 175 |
for box in result.boxes:
|
| 176 |
cls, conf = int(box.cls), float(box.conf)
|
| 177 |
label = CONFIG["VIOLATION_LABELS"].get(cls, None)
|
| 178 |
+
if label not in CONFIG["VIOLATION_LABELS"].values() or conf < CONFIG["CONFIDENCE_THRESHOLD"]:
|
|
|
|
|
|
|
| 179 |
continue
|
| 180 |
+
|
| 181 |
+
violation_key = f"{label}_{frame_count}"
|
| 182 |
+
if violation_key in detected_violations:
|
| 183 |
continue
|
|
|
|
| 184 |
|
| 185 |
+
detected_violations[violation_key] = {
|
| 186 |
"frame": frame_count,
|
| 187 |
"violation": label,
|
| 188 |
"confidence": round(conf, 2),
|
| 189 |
+
"bounding_box": [round(x, 2) for x in box.xywh.cpu().numpy()[0]],
|
| 190 |
"timestamp": frame_count / fps
|
| 191 |
}
|
| 192 |
+
violations.append(detected_violations[violation_key])
|
| 193 |
|
| 194 |
if not snapshot_taken[label]:
|
| 195 |
snapshot_path = os.path.join(CONFIG["OUTPUT_DIR"], f"snapshot_{frame_count}_{label}.jpg")
|
|
|
|
| 260 |
|
| 261 |
violation_table = "No violations detected."
|
| 262 |
if result["violations"]:
|
| 263 |
+
header = "| Violation | Timestamp (s) | Confidence | Bounding Box |\n"
|
| 264 |
+
separator = "|------------------------|---------------|------------|--------------------------|\n"
|
| 265 |
rows = []
|
| 266 |
violation_name_map = CONFIG["DISPLAY_NAMES"]
|
| 267 |
for v in result["violations"]:
|
| 268 |
display_name = violation_name_map.get(v["violation"], v["violation"])
|
| 269 |
+
row = f"| {display_name:<22} | {v['timestamp']:.2f} | {v['confidence']:.2f} | {v['bounding_box']} |"
|
| 270 |
rows.append(row)
|
| 271 |
violation_table = header + separator + "\n".join(rows)
|
| 272 |
|