PrashanthB461 commited on
Commit
b1af4af
·
verified ·
1 Parent(s): 92ea314

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -44
app.py CHANGED
@@ -19,10 +19,12 @@ DEFAULT_MODEL_PATH = "models/yolov8_safety.pt"
19
  FALLBACK_MODEL = "yolov8n.pt"
20
  MODEL_PATH = os.getenv("SAFETY_MODEL_PATH", DEFAULT_MODEL_PATH)
21
 
22
- # Use static/output for publicly accessible files
23
  STATIC_OUTPUT_DIR = "static/output"
24
  os.makedirs(STATIC_OUTPUT_DIR, exist_ok=True)
25
 
 
 
 
26
  VIOLATION_LABELS = {
27
  0: "no_helmet",
28
  1: "no_harness",
@@ -48,7 +50,7 @@ except Exception as e:
48
  raise
49
 
50
  # ==========================
51
- # Salesforce connection (hardcoded creds for testing)
52
  # ==========================
53
  def connect_to_salesforce():
54
  try:
@@ -74,43 +76,27 @@ def violations_to_text(violations):
74
  lines.append(line)
75
  return "\n".join(lines)
76
 
77
- def push_report_to_salesforce(score, violations, pdf_filename):
 
 
 
78
  try:
79
  sf = connect_to_salesforce()
80
-
81
  violations_count = len(violations)
82
  violations_details = violations_to_text(violations)
83
 
84
- # Upload the PDF to Salesforce Files
85
- with open(pdf_filename, "rb") as f:
86
- pdf_data = f.read()
87
- file_name = os.path.basename(pdf_filename)
88
-
89
- # Upload to ContentVersion (Salesforce Files)
90
- print(f"Uploading file to Salesforce Files: {file_name}")
91
- file_upload = sf.ContentVersion.create({
92
- 'Title': file_name,
93
- 'PathOnClient': file_name,
94
- 'VersionData': pdf_data
95
- })
96
-
97
- file_id = file_upload.get('id')
98
- print(f"File uploaded with ID: {file_id}")
99
-
100
- # Get the public URL for the uploaded file (direct download link)
101
- public_url = f"https://{sf.sf_instance}.salesforce.com/sfc/servlet.shepherd/version/download/{file_id}"
102
-
103
- # Create the record in Salesforce
104
  print(f"Creating Salesforce record with compliance score: {score} and violations found: {violations_count}")
105
  record = sf.Safety_Video_Report__c.create({
106
  "Compliance_Score__c": score,
107
  "Violations_Found__c": violations_count,
108
  "Violations_Details__c": violations_details,
109
  "Status__c": "Pending",
110
- "PDF_Report_URL__c": public_url
111
  })
112
- print(f"✅ Salesforce record created with Id: {record.get('id')}")
113
- return record.get("id")
 
114
 
115
  except SalesforceMalformedRequest as e:
116
  print(f"❌ Salesforce malformed request: {e}")
@@ -140,7 +126,8 @@ def calculate_safety_score(violations):
140
  # ==========================
141
  def generate_pdf_report(violations, snapshots, score):
142
  try:
143
- pdf_path = os.path.join(STATIC_OUTPUT_DIR, f"report_{int(time.time())}.pdf")
 
144
  c = canvas.Canvas(pdf_path, pagesize=letter)
145
  width, height = letter
146
 
@@ -176,11 +163,15 @@ def generate_pdf_report(violations, snapshots, score):
176
  c.save()
177
  print(f"PDF generated at {pdf_path}")
178
 
179
- return pdf_path
 
 
 
 
180
 
181
  except Exception as e:
182
  print(f"❌ Error generating PDF: {e}")
183
- return ""
184
 
185
  # ==========================
186
  # Video Processing
@@ -230,12 +221,13 @@ def process_video(video_data, frame_skip=5, max_frames=100):
230
  }
231
  violations.append(violation)
232
 
233
- snapshot_path = os.path.join(STATIC_OUTPUT_DIR, f"snapshot_{frame_count}_{label}.jpg")
 
234
  cv2.imwrite(snapshot_path, frame)
235
  snapshots.append({
236
  "violation": label,
237
  "frame": frame_count,
238
- "snapshot_url": f"https://huggingface.co/spaces/PrashanthB461/AI_Safety_Demo1/resolve/main/static/output/{os.path.basename(snapshot_path)}"
239
  })
240
 
241
  frame_count += 1
@@ -252,13 +244,14 @@ def process_video(video_data, frame_skip=5, max_frames=100):
252
  os.remove(video_path)
253
 
254
  score = calculate_safety_score(violations)
255
- pdf_path = generate_pdf_report(violations, snapshots, score)
 
 
 
256
 
257
- if pdf_path:
258
- report_id = push_report_to_salesforce(score, violations, pdf_path)
259
- print(f"Salesforce record created with Id: {report_id}")
260
- else:
261
- report_id = None
262
 
263
  with open(pdf_path, "rb") as f:
264
  pdf_base64 = base64.b64encode(f.read()).decode('utf-8')
@@ -268,7 +261,8 @@ def process_video(video_data, frame_skip=5, max_frames=100):
268
  "snapshots": snapshots,
269
  "score": score,
270
  "pdf_base64": pdf_base64,
271
- "salesforce_record_id": report_id
 
272
  }
273
 
274
  except Exception as e:
@@ -278,6 +272,7 @@ def process_video(video_data, frame_skip=5, max_frames=100):
278
  "snapshots": [],
279
  "score": 0,
280
  "pdf_base64": "",
 
281
  "salesforce_record_id": None,
282
  "error": str(e)
283
  }
@@ -288,7 +283,7 @@ def process_video(video_data, frame_skip=5, max_frames=100):
288
  def gradio_interface(video_file):
289
  try:
290
  if not video_file:
291
- return "Error: Please upload a video file.", "", "", [], ""
292
 
293
  with open(video_file, "rb") as f:
294
  video_data = f.read()
@@ -296,15 +291,16 @@ def gradio_interface(video_file):
296
  result = process_video(video_data)
297
  violation_text = violations_to_text(result.get("violations", []))
298
  return (
299
- violation_text, # Returning violation details as plain text
300
  f"Safety Score: {result.get('score', 0)}%",
301
  result.get("pdf_base64", ""),
302
  result.get("snapshots", []),
 
303
  f"Salesforce Record ID: {result.get('salesforce_record_id', '')}"
304
  )
305
  except Exception as e:
306
  print(f"❌ Error in gradio_interface: {e}")
307
- return f"Error: {e}", "", "", [], ""
308
 
309
  interface = gr.Interface(
310
  fn=gradio_interface,
@@ -314,12 +310,13 @@ interface = gr.Interface(
314
  gr.Textbox(label="Compliance Score"),
315
  gr.Textbox(label="PDF Base64 (for API use)"),
316
  gr.JSON(label="Snapshots"),
 
317
  gr.Textbox(label="Salesforce Record ID")
318
  ],
319
  title="Worksite Safety Violation Analyzer",
320
- description="Upload short site videos to detect safety violations (e.g., no helmet, no harness, unsafe posture)."
321
  )
322
 
323
  if __name__ == "__main__":
324
  print("🚀 Launching Safety Analyzer App...")
325
- interface.launch()
 
19
  FALLBACK_MODEL = "yolov8n.pt"
20
  MODEL_PATH = os.getenv("SAFETY_MODEL_PATH", DEFAULT_MODEL_PATH)
21
 
 
22
  STATIC_OUTPUT_DIR = "static/output"
23
  os.makedirs(STATIC_OUTPUT_DIR, exist_ok=True)
24
 
25
+ # Base URL for publicly accessible files (adjust based on your hosting platform)
26
+ BASE_PUBLIC_URL = "https://huggingface.co/spaces/PrashanthB461/AI_Safety_Demo1/resolve/main/static/output/"
27
+
28
  VIOLATION_LABELS = {
29
  0: "no_helmet",
30
  1: "no_harness",
 
50
  raise
51
 
52
  # ==========================
53
+ # Salesforce Connection
54
  # ==========================
55
  def connect_to_salesforce():
56
  try:
 
76
  lines.append(line)
77
  return "\n".join(lines)
78
 
79
+ # ==========================
80
+ # Salesforce Record Creation
81
+ # ==========================
82
+ def push_report_to_salesforce(score, violations, pdf_url):
83
  try:
84
  sf = connect_to_salesforce()
 
85
  violations_count = len(violations)
86
  violations_details = violations_to_text(violations)
87
 
88
+ # Create the record in the custom object Safety_Video_Report__c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  print(f"Creating Salesforce record with compliance score: {score} and violations found: {violations_count}")
90
  record = sf.Safety_Video_Report__c.create({
91
  "Compliance_Score__c": score,
92
  "Violations_Found__c": violations_count,
93
  "Violations_Details__c": violations_details,
94
  "Status__c": "Pending",
95
+ "PDF_Report_URL__c": pdf_url
96
  })
97
+ record_id = record.get('id')
98
+ print(f"✅ Salesforce record created with Id: {record_id}")
99
+ return record_id
100
 
101
  except SalesforceMalformedRequest as e:
102
  print(f"❌ Salesforce malformed request: {e}")
 
126
  # ==========================
127
  def generate_pdf_report(violations, snapshots, score):
128
  try:
129
+ pdf_filename = f"report_{int(time.time())}.pdf"
130
+ pdf_path = os.path.join(STATIC_OUTPUT_DIR, pdf_filename)
131
  c = canvas.Canvas(pdf_path, pagesize=letter)
132
  width, height = letter
133
 
 
163
  c.save()
164
  print(f"PDF generated at {pdf_path}")
165
 
166
+ # Generate public URL for the PDF
167
+ pdf_url = f"{BASE_PUBLIC_URL}{pdf_filename}"
168
+ print(f"Public PDF URL: {pdf_url}")
169
+
170
+ return pdf_path, pdf_url
171
 
172
  except Exception as e:
173
  print(f"❌ Error generating PDF: {e}")
174
+ return "", ""
175
 
176
  # ==========================
177
  # Video Processing
 
221
  }
222
  violations.append(violation)
223
 
224
+ snapshot_filename = f"snapshot_{frame_count}_{label}.jpg"
225
+ snapshot_path = os.path.join(STATIC_OUTPUT_DIR, snapshot_filename)
226
  cv2.imwrite(snapshot_path, frame)
227
  snapshots.append({
228
  "violation": label,
229
  "frame": frame_count,
230
+ "snapshot_url": f"{BASE_PUBLIC_URL}{snapshot_filename}"
231
  })
232
 
233
  frame_count += 1
 
244
  os.remove(video_path)
245
 
246
  score = calculate_safety_score(violations)
247
+ pdf_path, pdf_url = generate_pdf_report(violations, snapshots, score)
248
+
249
+ if not pdf_path:
250
+ raise Exception("Failed to generate PDF report")
251
 
252
+ # Create Salesforce record with the PDF URL
253
+ record_id = push_report_to_salesforce(score, violations, pdf_url)
254
+ print(f"Salesforce record created with Id: {record_id}")
 
 
255
 
256
  with open(pdf_path, "rb") as f:
257
  pdf_base64 = base64.b64encode(f.read()).decode('utf-8')
 
261
  "snapshots": snapshots,
262
  "score": score,
263
  "pdf_base64": pdf_base64,
264
+ "pdf_url": pdf_url,
265
+ "salesforce_record_id": record_id
266
  }
267
 
268
  except Exception as e:
 
272
  "snapshots": [],
273
  "score": 0,
274
  "pdf_base64": "",
275
+ "pdf_url": "",
276
  "salesforce_record_id": None,
277
  "error": str(e)
278
  }
 
283
  def gradio_interface(video_file):
284
  try:
285
  if not video_file:
286
+ return "Error: Please upload a video file.", "", "", [], "", ""
287
 
288
  with open(video_file, "rb") as f:
289
  video_data = f.read()
 
291
  result = process_video(video_data)
292
  violation_text = violations_to_text(result.get("violations", []))
293
  return (
294
+ violation_text,
295
  f"Safety Score: {result.get('score', 0)}%",
296
  result.get("pdf_base64", ""),
297
  result.get("snapshots", []),
298
+ f"PDF URL: {result.get('pdf_url', '')}",
299
  f"Salesforce Record ID: {result.get('salesforce_record_id', '')}"
300
  )
301
  except Exception as e:
302
  print(f"❌ Error in gradio_interface: {e}")
303
+ return f"Error: {e}", "", "", [], "", ""
304
 
305
  interface = gr.Interface(
306
  fn=gradio_interface,
 
310
  gr.Textbox(label="Compliance Score"),
311
  gr.Textbox(label="PDF Base64 (for API use)"),
312
  gr.JSON(label="Snapshots"),
313
+ gr.Textbox(label="PDF URL"),
314
  gr.Textbox(label="Salesforce Record ID")
315
  ],
316
  title="Worksite Safety Violation Analyzer",
317
+ description="Upload short site videos to detect safety violations (e.g., no helmet, no harness, unsafe posture). The PDF URL is saved in a Salesforce custom object."
318
  )
319
 
320
  if __name__ == "__main__":
321
  print("🚀 Launching Safety Analyzer App...")
322
+ interface.launch()