Harshil07 commited on
Commit
6376429
·
verified ·
1 Parent(s): 83f0302

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -14
app.py CHANGED
@@ -223,6 +223,9 @@ def propagate_in_video(video_predictor, session_id):
223
  return outputs_per_frame
224
 
225
 
 
 
 
226
  # ----------------------------------------------------------------------
227
  # Main inference entrypoint
228
  # ----------------------------------------------------------------------
@@ -281,35 +284,59 @@ def run_sam3(file_path, prompt, progress=gr.Progress()):
281
  video_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
282
  cap.release()
283
 
284
- progress(0.4, desc="Tracking objects through video...")
 
 
 
 
285
  with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):
286
- response = video_predictor.handle_request(
287
- request=dict(type="start_session", resource_path=file_path)
288
- )
289
- session_id = response["session_id"]
290
 
291
- # Loop through ALL classes and add them to the session with unique obj_ids
292
  for obj_idx, class_name in enumerate(class_names):
 
 
 
 
 
 
 
293
  video_predictor.handle_request(
294
  request=dict(
295
  type="add_prompt",
296
  session_id=session_id,
297
  frame_index=0,
298
- obj_id=obj_idx,
299
  text=class_name
300
  )
301
  )
302
-
303
- outputs_per_frame = propagate_in_video(video_predictor, session_id)
304
-
305
- progress(0.85, desc="Rendering overlay video...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  out_path = f"/tmp/output/sam3_overlay_{timestamp}.mp4"
307
- save_masklet_video(video_frames, outputs_per_frame, out_path=out_path, alpha=0.5, fps=video_fps)
 
 
308
 
309
- video_predictor.handle_request(request=dict(type="close_session", session_id=session_id))
310
  progress(1.0, desc="Done!")
311
 
312
- status = f"Tracked {len(outputs_per_frame)} frames for: {tracked_classes_str}"
313
  return (
314
  gr.update(visible=False),
315
  gr.update(value=out_path, visible=True),
 
223
  return outputs_per_frame
224
 
225
 
226
+ # ----------------------------------------------------------------------
227
+ # Main inference entrypoint
228
+ # ----------------------------------------------------------------------
229
  # ----------------------------------------------------------------------
230
  # Main inference entrypoint
231
  # ----------------------------------------------------------------------
 
284
  video_frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
285
  cap.release()
286
 
287
+ progress(0.3, desc="Tracking objects (multi-pass)...")
288
+
289
+ # Prepare a master dictionary to hold masks for ALL classes
290
+ master_outputs_per_frame = {i: [] for i in range(len(video_frames))}
291
+
292
  with torch.inference_mode(), torch.autocast(device_type=DEVICE, dtype=torch.bfloat16):
 
 
 
 
293
 
294
+ # Run a separate tracking session for each class to prevent them from overwriting each other
295
  for obj_idx, class_name in enumerate(class_names):
296
+ progress(0.3 + (0.5 * (obj_idx / len(class_names))), desc=f"Tracking '{class_name}' ({obj_idx+1}/{len(class_names)})...")
297
+
298
+ response = video_predictor.handle_request(
299
+ request=dict(type="start_session", resource_path=file_path)
300
+ )
301
+ session_id = response["session_id"]
302
+
303
  video_predictor.handle_request(
304
  request=dict(
305
  type="add_prompt",
306
  session_id=session_id,
307
  frame_index=0,
308
+ obj_id=obj_idx, # Assigns a unique ID so the renderer uses different colors
309
  text=class_name
310
  )
311
  )
312
+
313
+ # Merge the outputs into our master dictionary
314
+ for frame_output in video_predictor.handle_stream_request(
315
+ request=dict(type="propagate_in_video", session_id=session_id, propagation_direction="both")
316
+ ):
317
+ idx = frame_output["frame_index"]
318
+ out_data = frame_output["outputs"]
319
+
320
+ # Safely handle SAM3 output regardless of whether it returns a list or a dict
321
+ if isinstance(out_data, dict):
322
+ if isinstance(master_outputs_per_frame[idx], list):
323
+ master_outputs_per_frame[idx] = {}
324
+ master_outputs_per_frame[idx].update(out_data)
325
+ else:
326
+ master_outputs_per_frame[idx].extend(out_data)
327
+
328
+ # Clean up the session before starting the next class
329
+ video_predictor.handle_request(request=dict(type="close_session", session_id=session_id))
330
+
331
+ progress(0.85, desc="Rendering combined overlay video...")
332
  out_path = f"/tmp/output/sam3_overlay_{timestamp}.mp4"
333
+
334
+ # Feed the fully merged master dictionary to the visualizer
335
+ save_masklet_video(video_frames, master_outputs_per_frame, out_path=out_path, alpha=0.5, fps=video_fps)
336
 
 
337
  progress(1.0, desc="Done!")
338
 
339
+ status = f"Tracked {len(video_frames)} frames for: {tracked_classes_str}"
340
  return (
341
  gr.update(visible=False),
342
  gr.update(value=out_path, visible=True),