PrashanthB461 commited on
Commit
e71a357
·
verified ·
1 Parent(s): c5fb18c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -15
app.py CHANGED
@@ -203,7 +203,7 @@ def process_video(video_data):
203
 
204
  video = cv2.VideoCapture(video_path)
205
  if not video.isOpened():
206
- raise ValueError("Could not open video file")
207
 
208
  violations, snapshots = [], []
209
  frame_count, processed_frames = 0, 0
@@ -272,24 +272,31 @@ def process_video(video_data):
272
  # ==========================
273
  # Gradio Interface
274
  # ==========================
275
- def gradio_interface(video_file):
276
  if not video_file:
277
- return "No file uploaded.", "", "No file uploaded.", "", "No file uploaded."
278
  try:
279
  with open(video_file, "rb") as f:
280
  video_data = f.read()
281
  result = process_video(video_data)
282
 
283
- # Format violations as a Markdown table
284
  violation_table = "No violations detected."
285
  if result["violations"]:
286
- header = "| Violation | Timestamp | Confidence | Bounding Box |\n"
287
- separator = "|---------------|-----------|------------|--------------------------|\n"
288
  rows = []
289
  for v in result["violations"]:
290
- # Simplify violation names (e.g., "no_helmet" to "helmet")
291
- violation_name = v["violation"].replace("no_", "").replace("unsafe_", "")
292
- row = f"| {violation_name:<13} | {v['timestamp']:.2f}s | {v['confidence']:.2f} | {v['bounding_box']} |"
 
 
 
 
 
 
 
293
  rows.append(row)
294
  violation_table = header + separator + "\n".join(rows)
295
 
@@ -297,33 +304,42 @@ def gradio_interface(video_file):
297
  snapshots_text = "No snapshots captured."
298
  if result["snapshots"]:
299
  snapshots_text = "\n".join(
300
- f"- Snapshot for {s['violation'].replace('no_', '').replace('unsafe_', '')} at frame {s['frame']}: {s['snapshot_url']}"
301
  for s in result["snapshots"]
302
  )
303
 
 
 
 
304
  return (
305
  violation_table,
306
  f"Safety Score: {result['score']}%",
307
  snapshots_text,
308
  f"Salesforce Record ID: {result['salesforce_record_id'] or 'N/A'}",
309
- f"Violation Details URL: {result['violation_details_url'] or 'N/A'}"
 
310
  )
311
  except Exception as e:
312
  logger.error(f"Error in Gradio interface: {e}")
313
- return f"Error: {str(e)}", "", "Error in processing.", "", "Error in processing."
314
 
 
315
  interface = gr.Interface(
316
  fn=gradio_interface,
317
- inputs=gr.Video(label="Upload Site Video"),
 
 
 
318
  outputs=[
319
  gr.Markdown(label="Detected Safety Violations"),
320
  gr.Textbox(label="Compliance Score"),
321
  gr.Markdown(label="Snapshots"),
322
  gr.Textbox(label="Salesforce Record ID"),
323
- gr.Textbox(label="Violation Details URL")
 
324
  ],
325
  title="Worksite Safety Violation Analyzer",
326
- description="Upload short site videos to detect safety violations (e.g., no helmet, no harness, unsafe posture)."
327
  )
328
 
329
  if __name__ == "__main__":
 
203
 
204
  video = cv2.VideoCapture(video_path)
205
  if not video.isOpened():
206
+ raise ValueValueError("Could not open video file")
207
 
208
  violations, snapshots = [], []
209
  frame_count, processed_frames = 0, 0
 
272
  # ==========================
273
  # Gradio Interface
274
  # ==========================
275
+ def gradio_interface(video_file, selected_snapshot_url=None):
276
  if not video_file:
277
+ return "No file uploaded.", "", "No file uploaded.", "", "No file uploaded.", None
278
  try:
279
  with open(video_file, "rb") as f:
280
  video_data = f.read()
281
  result = process_video(video_data)
282
 
283
+ # Format violations as a Markdown table with Violation Details column
284
  violation_table = "No violations detected."
285
  if result["violations"]:
286
+ header = "| Violation | Timestamp | Confidence | Bounding Box | Violation Details |\n"
287
+ separator = "|------------------|-----------|------------|--------------------------|-------------------|\n"
288
  rows = []
289
  for v in result["violations"]:
290
+ # Use original violation names (e.g., "no_helmet", "unsafe_posture")
291
+ violation_name = v["violation"]
292
+ # Find the corresponding snapshot URL
293
+ snapshot_url = next(
294
+ (s["snapshot_url"] for s in result["snapshots"] if s["frame"] == v["frame"] and s["violation"] == v["violation"]),
295
+ ""
296
+ )
297
+ # Create a clickable link for the snapshot URL
298
+ details_link = f"[View Snapshot]({snapshot_url})" if snapshot_url else "N/A"
299
+ row = f"| {violation_name:<16} | {v['timestamp']:.2f}s | {v['confidence']:.2f} | {v['bounding_box']} | {details_link} |"
300
  rows.append(row)
301
  violation_table = header + separator + "\n".join(rows)
302
 
 
304
  snapshots_text = "No snapshots captured."
305
  if result["snapshots"]:
306
  snapshots_text = "\n".join(
307
+ f"- Snapshot for {s['violation']} at frame {s['frame']}: [{s['snapshot_url']}]({s['snapshot_url']})"
308
  for s in result["snapshots"]
309
  )
310
 
311
+ # Display the selected snapshot image
312
+ snapshot_image = selected_snapshot_url if selected_snapshot_url else None
313
+
314
  return (
315
  violation_table,
316
  f"Safety Score: {result['score']}%",
317
  snapshots_text,
318
  f"Salesforce Record ID: {result['salesforce_record_id'] or 'N/A'}",
319
+ f"URL: {result['violation_details_url'] or 'N/A'}",
320
+ snapshot_image
321
  )
322
  except Exception as e:
323
  logger.error(f"Error in Gradio interface: {e}")
324
+ return f"Error: {str(e)}", "", "Error in processing.", "", "Error in processing.", None
325
 
326
+ # Update Gradio interface to include snapshot URL input and image output
327
  interface = gr.Interface(
328
  fn=gradio_interface,
329
+ inputs=[
330
+ gr.Video(label="Upload Site Video"),
331
+ gr.Textbox(label="Snapshot URL (Click a link in the table or snapshots)", placeholder="Paste snapshot URL here", interactive=True)
332
+ ],
333
  outputs=[
334
  gr.Markdown(label="Detected Safety Violations"),
335
  gr.Textbox(label="Compliance Score"),
336
  gr.Markdown(label="Snapshots"),
337
  gr.Textbox(label="Salesforce Record ID"),
338
+ gr.Textbox(label="URL"),
339
+ gr.Image(label="Selected Snapshot")
340
  ],
341
  title="Worksite Safety Violation Analyzer",
342
+ description="Upload short site videos to detect safety violations (e.g., no helmet, no harness, unsafe posture). Click a snapshot link to view the image."
343
  )
344
 
345
  if __name__ == "__main__":