Download any_frame_test.py from syCen/action-worldmodel-bench: direct link, hf CLI and curl.
- Browser
- Download file 30.5 kB
-
https://huggingface.co/datasets/syCen/action-worldmodel-bench/resolve/main/any_frame_test.py
- Command line
-
hf download hf://datasets/syCen/action-worldmodel-bench/any_frame_test.py
-
curl -L -o any_frame_test.py https://huggingface.co/datasets/syCen/action-worldmodel-bench/resolve/main/any_frame_test.py
30.5 kB
| """ | |
| SAM 3 Interactive Video Annotator | |
| ================================== | |
| A Gradio app for interactive video segmentation using SAM 3. | |
| Usage: | |
| python sam3_annotator.py [--port 7860] [--share] | |
| Then SSH tunnel: | |
| ssh -L 7860:holygpu8a11103:7860 scen@login.rc.fas.harvard.edu | |
| Open http://localhost:7860 in your local browser. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| import cv2 | |
| import gradio as gr | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from pycocotools import mask as mask_utils | |
| # ββ SAM 3 imports ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| from sam3.model_builder import build_sam3_video_predictor | |
| # ββ Global state βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| predictor = None # initialized once in main | |
| # ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def encode_mask_rle(mask: np.ndarray): | |
| mask = np.asfortranarray(mask.astype(np.uint8)) | |
| rle = mask_utils.encode(mask) | |
| rle["counts"] = rle["counts"].decode("utf-8") | |
| return rle | |
| def overlay_mask(frame, mask, color=(30, 144, 255), alpha=0.45): | |
| vis = frame.copy().astype(np.float32) | |
| color = np.array(color, dtype=np.float32) | |
| vis[mask] = vis[mask] * (1 - alpha) + color * alpha | |
| return vis.astype(np.uint8) | |
| def extract_first_frame(video_path: str) -> np.ndarray: | |
| """Return the first frame of a video as RGB numpy array.""" | |
| cap = cv2.VideoCapture(video_path) | |
| ret, frame = cap.read() | |
| cap.release() | |
| if not ret: | |
| raise ValueError(f"Cannot read video: {video_path}") | |
| return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
| def get_video_info(video_path: str): | |
| """Return (width, height, fps, num_frames).""" | |
| cap = cv2.VideoCapture(video_path) | |
| w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | |
| h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | |
| fps = cap.get(cv2.CAP_PROP_FPS) | |
| n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) | |
| cap.release() | |
| return w, h, fps, n | |
| def load_all_frames(video_path: str): | |
| cap = cv2.VideoCapture(video_path) | |
| frames = [] | |
| while True: | |
| ret, frame_bgr = cap.read() | |
| if not ret: | |
| break | |
| frames.append(cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)) | |
| cap.release() | |
| return frames | |
| def masks_to_bboxes(masks: dict) -> list: | |
| """Convert a binary mask (H, W) β [x_min, y_min, x_max, y_max].""" | |
| bboxes = [] | |
| for obj_id, mask in masks.items(): | |
| if isinstance(mask, torch.Tensor): | |
| mask = mask.cpu().numpy() | |
| mask = mask.squeeze() | |
| if mask.ndim == 2: | |
| ys, xs = np.where(mask > 0) | |
| if len(xs) == 0: | |
| continue | |
| bboxes.append({ | |
| "obj_id": int(obj_id), | |
| "bbox": [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())], | |
| }) | |
| return bboxes | |
| def overlay_masks_on_frame(frame: np.ndarray, outputs: dict, alpha: float = 0.45) -> np.ndarray: | |
| """ | |
| Overlay coloured segmentation masks on a frame. | |
| `outputs` is the raw dict returned by SAM 3 for one frame. | |
| Auto-detects key names since SAM3 output format may vary. | |
| """ | |
| # Debug: print all keys so we can see what SAM3 returns | |
| print(f"[DEBUG overlay] outputs keys: {list(outputs.keys())}", flush=True) | |
| for k, v in outputs.items(): | |
| if isinstance(v, torch.Tensor): | |
| print(f"[DEBUG overlay] {k}: Tensor shape={v.shape}, dtype={v.dtype}", flush=True) | |
| elif isinstance(v, np.ndarray): | |
| print(f"[DEBUG overlay] {k}: ndarray shape={v.shape}, dtype={v.dtype}", flush=True) | |
| elif isinstance(v, list): | |
| print(f"[DEBUG overlay] {k}: list len={len(v)}, first type={type(v[0]) if v else 'empty'}", flush=True) | |
| else: | |
| print(f"[DEBUG overlay] {k}: {type(v).__name__} = {v}", flush=True) | |
| vis = frame.copy().astype(np.float32) | |
| # Predefined distinct colours (RGB) | |
| COLORS = [ | |
| (30, 144, 255), # dodger blue | |
| (255, 80, 80), # red | |
| (50, 205, 50), # lime green | |
| (255, 165, 0), # orange | |
| (180, 50, 255), # purple | |
| (0, 255, 255), # cyan | |
| (255, 255, 0), # yellow | |
| (255, 105, 180), # hot pink | |
| ] | |
| # ββ Find obj_ids ββ | |
| obj_ids = None | |
| for key in ["obj_ids", "out_obj_ids", "object_ids", "obj_id", "ids"]: | |
| if key in outputs and outputs[key] is not None: | |
| obj_ids = outputs[key] | |
| break | |
| if obj_ids is None: | |
| print("[DEBUG overlay] No obj_ids found, returning raw frame", flush=True) | |
| return frame | |
| # Convert to list if tensor | |
| if isinstance(obj_ids, torch.Tensor): | |
| obj_ids = obj_ids.cpu().tolist() | |
| elif isinstance(obj_ids, np.ndarray): | |
| obj_ids = obj_ids.tolist() | |
| # ββ Find masks ββ | |
| masks_raw = None | |
| for key in ["out_binary_masks", "masks", "video_res_masks", "low_res_masks", "pred_masks", "segmentations"]: | |
| if key in outputs and outputs[key] is not None: | |
| masks_raw = outputs[key] | |
| print(f"[DEBUG overlay] Using masks from key='{key}'", flush=True) | |
| break | |
| if masks_raw is None: | |
| print("[DEBUG overlay] No masks found, returning raw frame", flush=True) | |
| return frame | |
| # ββ Convert masks to numpy bool array ββ | |
| if isinstance(masks_raw, torch.Tensor): | |
| masks_np = (masks_raw > 0).cpu().numpy() | |
| elif isinstance(masks_raw, list): | |
| converted = [] | |
| for m in masks_raw: | |
| if isinstance(m, torch.Tensor): | |
| converted.append((m > 0).cpu().numpy()) | |
| else: | |
| converted.append(np.array(m) > 0) | |
| masks_np = np.array(converted) | |
| else: | |
| masks_np = np.array(masks_raw) > 0 | |
| print(f"[DEBUG overlay] masks_np shape={masks_np.shape}, n_objects={len(obj_ids)}", flush=True) | |
| # ββ Draw each mask ββ | |
| vis_uint8 = vis.astype(np.uint8) # for contour drawing | |
| for i, obj_id in enumerate(obj_ids): | |
| if i >= len(masks_np): | |
| break | |
| color = np.array(COLORS[i % len(COLORS)], dtype=np.float32) | |
| mask = masks_np[i].squeeze() # collapse to (H, W) | |
| if mask.ndim != 2: | |
| print(f"[DEBUG overlay] Skipping obj {obj_id}: mask.ndim={mask.ndim} after squeeze", flush=True) | |
| continue | |
| n_pixels = mask.sum() | |
| print(f"[DEBUG overlay] obj_id={obj_id}: mask has {n_pixels} pixels", flush=True) | |
| if n_pixels == 0: | |
| continue | |
| # Blend colour onto float image | |
| vis[mask] = vis[mask] * (1 - alpha) + color * alpha | |
| # Draw contour on uint8 image | |
| contours, _ = cv2.findContours( | |
| mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE | |
| ) | |
| cv2.drawContours(vis_uint8, contours, -1, tuple(int(c) for c in color), 2) | |
| # Merge: use blended vis but paste contours on top | |
| result = vis.astype(np.uint8) | |
| # Where contours were drawn (vis_uint8 differs from original frame), use those pixels | |
| contour_mask = np.any(vis_uint8 != frame, axis=-1) | |
| result[contour_mask] = vis_uint8[contour_mask] | |
| return result | |
| def draw_clicks_on_frame(frame: np.ndarray, clicks: list) -> np.ndarray: | |
| """Draw positive (green β ) and negative (red β ) clicks on the frame.""" | |
| vis = frame.copy() | |
| for x, y, label in clicks: | |
| color = (0, 255, 0) if label == 1 else (255, 0, 0) | |
| # Draw star-like marker | |
| cv2.drawMarker(vis, (int(x), int(y)), color, | |
| markerType=cv2.MARKER_STAR, markerSize=20, thickness=2) | |
| return vis | |
| # ββ Core workflow functions (called by Gradio) βββββββββββββββββββββββββββββ | |
| def upload_video(video_path_str): | |
| if not video_path_str or not video_path_str.strip(): | |
| return None, "β οΈ Please enter a video path.", gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), None | |
| video_path = video_path_str.strip() | |
| if not os.path.exists(video_path): | |
| return None, f"β οΈ File not found: {video_path}", gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), None | |
| pred = predictor | |
| print(f"[VIDEO] Loading frames from {video_path} β¦", flush=True) | |
| t0 = time.time() | |
| frames = load_all_frames(video_path) | |
| if len(frames) == 0: | |
| raise ValueError(f"Cannot read video: {video_path}") | |
| first_frame = frames[0] | |
| w, h, fps, n_frames = get_video_info(video_path) | |
| print(f"[VIDEO] Loaded: {w}Γ{h}, {n_frames} frames β {time.time() - t0:.1f}s", flush=True) | |
| print(f"[VIDEO] Starting SAM3 session β¦", flush=True) | |
| t0 = time.time() | |
| response = pred.handle_request( | |
| request=dict(type="start_session", resource_path=video_path) | |
| ) | |
| sid = response["session_id"] | |
| print(f"[VIDEO] Session started: {sid} β {time.time() - t0:.1f}s", flush=True) | |
| state = { | |
| "session_id": sid, | |
| "video_path": video_path, | |
| "width": w, | |
| "height": h, | |
| "fps": fps, | |
| "n_frames": n_frames, | |
| "frames": frames, | |
| "current_frame_idx": 0, | |
| "clicks_by_obj": {1: []}, | |
| "current_obj_id": 1, | |
| "next_obj_id": 2, | |
| # "clicks": [], | |
| # "next_obj_id": 1, | |
| "current_outputs": None, | |
| "text_prompt": None, | |
| } | |
| info = f"β Video loaded: {w}Γ{h}, {fps:.1f} fps, {n_frames} frames" | |
| return ( | |
| first_frame, | |
| info, | |
| gr.update(interactive=True), | |
| gr.update(interactive=True), | |
| gr.update(minimum=0, maximum=n_frames - 1, value=0, interactive=True), | |
| state, | |
| ) | |
| def select_frame(state, frame_idx): | |
| if state is None: | |
| return None, "β οΈ Please upload a video first.", state | |
| frame_idx = int(frame_idx) | |
| state["current_frame_idx"] = frame_idx | |
| # state["clicks"] = [] | |
| state["clicks_by_obj"] = {} | |
| state["current_outputs"] = None | |
| state["text_prompt"] = None | |
| return state["frames"][frame_idx], f"π Selected frame {frame_idx}", state | |
| def handle_click(state, evt: gr.SelectData, click_mode, obj_id): | |
| if state is None: | |
| return None, "β οΈ Please upload a video first.", state | |
| frame_idx = int(state.get("current_frame_idx", 0)) | |
| obj_id = int(obj_id) | |
| x, y = evt.index | |
| label = 1 if click_mode == "Positive (include)" else 0 | |
| if "clicks_by_obj" not in state: | |
| state["clicks_by_obj"] = {} | |
| state["clicks_by_obj"].setdefault(obj_id, []) | |
| state["clicks_by_obj"][obj_id].append((x, y, label)) | |
| state["current_obj_id"] = obj_id | |
| state["text_prompt"] = None | |
| pred = predictor | |
| sid = state["session_id"] | |
| w, h = state["width"], state["height"] | |
| clicks = state["clicks_by_obj"][obj_id] | |
| points_abs = np.array([(cx, cy) for cx, cy, _ in clicks]) | |
| labels = np.array([lb for _, _, lb in clicks]) | |
| points_rel = torch.tensor( | |
| [[px / w, py / h] for px, py in points_abs], | |
| dtype=torch.float32, | |
| ) | |
| labels_tensor = torch.tensor(labels, dtype=torch.int32) | |
| response = pred.handle_request( | |
| request=dict( | |
| type="add_prompt", | |
| session_id=sid, | |
| frame_index=frame_idx, | |
| points=points_rel, | |
| point_labels=labels_tensor, | |
| obj_id=obj_id, | |
| ) | |
| ) | |
| out = response["outputs"] | |
| state["current_outputs"] = out | |
| vis = overlay_masks_on_frame(state["frames"][frame_idx], out) | |
| # draw clicks for all objects | |
| for oid, clicks_i in state["clicks_by_obj"].items(): | |
| vis = draw_clicks_on_frame(vis, clicks_i) | |
| total = sum(len(v) for v in state["clicks_by_obj"].values()) | |
| info = f"π±οΈ Frame {frame_idx}: object {obj_id}, total clicks={total}" | |
| return vis, info, state | |
| # def handle_text_prompt(state, text_prompt): | |
| # """Alternative: use a text prompt instead of clicks.""" | |
| # if state is None: | |
| # return None, "β οΈ Please upload a video first.", state | |
| # if not text_prompt.strip(): | |
| # return None, "β οΈ Please enter a text prompt.", state | |
| # pred = predictor | |
| # sid = state["session_id"] | |
| # # Reset and clear clicks | |
| # pred.handle_request(request=dict(type="reset_session", session_id=sid)) | |
| # state["clicks"] = [] | |
| # state["text_prompt"] = text_prompt.strip() # save for propagation | |
| # response = pred.handle_request( | |
| # request=dict( | |
| # type="add_prompt", | |
| # session_id=sid, | |
| # frame_index=prompt_frame_idx, | |
| # text=text_prompt.strip(), | |
| # ) | |
| # ) | |
| # out = response["outputs"] | |
| # state["current_outputs"] = out | |
| # vis = overlay_masks_on_frame(state["first_frame"], out) | |
| # info = f'π Text prompt: "{text_prompt.strip()}"' | |
| # return vis, info, state | |
| def handle_text_prompt(state, text_prompt): | |
| return None, "β οΈ Text prompt is disabled for multi-object click mode.", state | |
| def undo_last_click(state): | |
| if state is None: | |
| return None, "β οΈ No video loaded.", state | |
| frame_idx = int(state.get("current_frame_idx", 0)) | |
| obj_id = int(state.get("current_obj_id", 1)) | |
| curr_frame = state["frames"][frame_idx] | |
| clicks_by_obj = state.get("clicks_by_obj", {}) | |
| clicks = clicks_by_obj.get(obj_id, []) | |
| if not clicks: | |
| return curr_frame.copy(), f"βΉοΈ No clicks to undo for object {obj_id}.", state | |
| clicks.pop() | |
| pred = predictor | |
| sid = state["session_id"] | |
| w, h = state["width"], state["height"] | |
| pred.handle_request(request=dict(type="reset_session", session_id=sid)) | |
| state["current_outputs"] = None | |
| vis = curr_frame.copy() | |
| for oid, obj_clicks in clicks_by_obj.items(): | |
| if not obj_clicks: | |
| continue | |
| points_abs = np.array([(cx, cy) for cx, cy, _ in obj_clicks]) | |
| labels = np.array([lb for _, _, lb in obj_clicks]) | |
| points_rel = torch.tensor( | |
| [[px / w, py / h] for px, py in points_abs], | |
| dtype=torch.float32, | |
| ) | |
| labels_tensor = torch.tensor(labels, dtype=torch.int32) | |
| response = pred.handle_request( | |
| request=dict( | |
| type="add_prompt", | |
| session_id=sid, | |
| frame_index=frame_idx, | |
| points=points_rel, | |
| point_labels=labels_tensor, | |
| obj_id=int(oid), | |
| ) | |
| ) | |
| state["current_outputs"] = response["outputs"] | |
| vis = overlay_masks_on_frame(curr_frame, response["outputs"]) | |
| for _, obj_clicks in clicks_by_obj.items(): | |
| vis = draw_clicks_on_frame(vis, obj_clicks) | |
| total = sum(len(v) for v in clicks_by_obj.values()) | |
| return vis, f"β©οΈ Undone object {obj_id}. Total clicks={total}", state | |
| def clear_all_clicks(state): | |
| if state is None: | |
| return None, "β οΈ No video loaded.", state | |
| pred = predictor | |
| sid = state["session_id"] | |
| pred.handle_request(request=dict(type="reset_session", session_id=sid)) | |
| frame_idx = int(state.get("current_frame_idx", 0)) | |
| state["clicks_by_obj"] = {} | |
| state["current_outputs"] = None | |
| state["text_prompt"] = None | |
| return state["frames"][frame_idx].copy(), "ποΈ All clicks cleared.", state | |
| def propagate_and_export(state, progress=gr.Progress()): | |
| """Propagate masks, export bbox+mask JSON, and render overlay video.""" | |
| if state is None: | |
| return None, None, "β οΈ No video loaded." | |
| if state["current_outputs"] is None: | |
| return None, None, "β οΈ No segmentation to propagate. Add clicks or text prompt first." | |
| pred = predictor | |
| sid = state["session_id"] | |
| w, h = state["width"], state["height"] | |
| n_frames = state["n_frames"] | |
| prompt_frame_idx = int(state.get("current_frame_idx", 0)) | |
| # prompt_frame_idx = int(state.get("current_frame_idx", 0)) | |
| print( | |
| f"[PROPAGATE] Using existing prompted state from frame {prompt_frame_idx} β¦", | |
| flush=True, | |
| ) | |
| session = pred._get_session(sid) | |
| inference_state = session["state"] | |
| if inference_state["previous_stages_out"][prompt_frame_idx] is None: | |
| inference_state["previous_stages_out"][prompt_frame_idx] = "_THIS_FRAME_HAS_OUTPUTS_" | |
| progress(0, desc="Propagating masks through videoβ¦") | |
| all_frame_outputs = {} | |
| frame_count = 0 | |
| for response in pred.handle_stream_request( | |
| # request=dict(type="propagate_in_video", session_id=sid) | |
| request=dict( | |
| type="propagate_in_video", | |
| session_id=sid, | |
| start_frame_index=prompt_frame_idx, | |
| ) | |
| ): | |
| fidx = response["frame_index"] | |
| all_frame_outputs[fidx] = response["outputs"] | |
| frame_count += 1 | |
| if frame_count % 10 == 0: | |
| progress(frame_count / n_frames, desc=f"Frame {frame_count}/{n_frames}") | |
| progress(0.9, desc="Exporting masks and rendering videoβ¦") | |
| result = { | |
| "video_path": state["video_path"], | |
| "width": w, | |
| "height": h, | |
| "fps": state["fps"], | |
| "n_frames": n_frames, | |
| "frames": {}, | |
| } | |
| cap = cv2.VideoCapture(state["video_path"]) | |
| raw_frames = [] | |
| while True: | |
| ret, frame_bgr = cap.read() | |
| if not ret: | |
| break | |
| raw_frames.append(cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)) | |
| cap.release() | |
| overlay_frames = [] | |
| for fidx in sorted(all_frame_outputs.keys()): | |
| out = all_frame_outputs[fidx] | |
| frame_entries = [] | |
| frame_rgb = raw_frames[fidx].copy() if fidx < len(raw_frames) else np.zeros((h, w, 3), dtype=np.uint8) | |
| obj_ids = None | |
| for key in ["out_obj_ids", "obj_ids", "object_ids"]: | |
| if key in out and out[key] is not None: | |
| obj_ids = out[key] | |
| break | |
| if obj_ids is None: | |
| result["frames"][str(fidx)] = [] | |
| overlay_frames.append(frame_rgb) | |
| continue | |
| if isinstance(obj_ids, torch.Tensor): | |
| obj_ids = obj_ids.cpu().numpy() | |
| obj_ids = np.asarray(obj_ids) | |
| masks_raw = None | |
| for key in ["out_binary_masks", "masks", "video_res_masks"]: | |
| if key in out and out[key] is not None: | |
| masks_raw = out[key] | |
| break | |
| masks_np = None | |
| if masks_raw is not None: | |
| if isinstance(masks_raw, torch.Tensor): | |
| masks_np = (masks_raw > 0).cpu().numpy() | |
| else: | |
| masks_np = np.asarray(masks_raw) > 0 | |
| boxes_xywh = out.get("out_boxes_xywh", None) | |
| if boxes_xywh is not None: | |
| if isinstance(boxes_xywh, torch.Tensor): | |
| boxes_xywh = boxes_xywh.cpu().numpy() | |
| boxes_xywh = np.asarray(boxes_xywh) | |
| for i, obj_id in enumerate(obj_ids): | |
| entry = {"obj_id": int(obj_id)} | |
| mask = None | |
| if masks_np is not None and i < len(masks_np): | |
| mask = masks_np[i].squeeze() | |
| if mask.ndim == 2 and mask.sum() > 0: | |
| ys, xs = np.where(mask > 0) | |
| entry["bbox_xyxy"] = [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())] | |
| entry["mask_rle"] = encode_mask_rle(mask) | |
| frame_rgb = overlay_mask(frame_rgb, mask) | |
| if "bbox_xyxy" not in entry and boxes_xywh is not None and i < len(boxes_xywh): | |
| bx, by, bw, bh = boxes_xywh[i] | |
| entry["bbox_xyxy"] = [ | |
| int(bx * w), | |
| int(by * h), | |
| int((bx + bw) * w), | |
| int((by + bh) * h), | |
| ] | |
| frame_entries.append(entry) | |
| result["frames"][str(fidx)] = frame_entries | |
| overlay_frames.append(frame_rgb) | |
| out_dir = os.path.dirname(state["video_path"]) | |
| json_path = os.path.join(out_dir, "sam3_bboxes_masks.json") | |
| with open(json_path, "w") as f: | |
| json.dump(result, f, indent=2) | |
| # overlay_video_path = os.path.join(tempfile.gettempdir(), "sam3_overlay.mp4") | |
| overlay_video_path = os.path.join(out_dir, "sam3_overlay.mp4") | |
| raw_overlay_path = os.path.join(out_dir, "sam3_overlay_raw.mp4") | |
| overlay_video_path = os.path.join(out_dir, "sam3_overlay.mp4") | |
| writer = cv2.VideoWriter( | |
| raw_overlay_path, # θΏιεΏ ι‘»ζ― raw_overlay_path | |
| cv2.VideoWriter_fourcc(*"mp4v"), | |
| state["fps"], | |
| (w, h), | |
| ) | |
| for frame_rgb in overlay_frames: | |
| frame_bgr = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2BGR) | |
| writer.write(frame_bgr) | |
| writer.release() | |
| # Convert to browser-compatible H264 | |
| ret = os.system( | |
| f'ffmpeg -y -i "{raw_overlay_path}" ' | |
| f'-c:v libx264 -pix_fmt yuv420p -movflags +faststart ' | |
| f'"{overlay_video_path}"' | |
| ) | |
| if ret != 0: | |
| print("[WARN] ffmpeg failed, falling back to raw mp4", flush=True) | |
| overlay_video_path = raw_overlay_path | |
| progress(1.0, desc="Done!") | |
| info = f"β Done. JSON saved to: {json_path}\nπ¬ Video saved to: {overlay_video_path}" | |
| return json_path, overlay_video_path, info | |
| # ββ Gradio UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def build_app(): | |
| with gr.Blocks( | |
| title="SAM 3 Video Annotator", | |
| ) as app: | |
| gr.Markdown("# π― SAM 3 β Interactive Video Annotator", elem_classes="main-title") | |
| gr.Markdown( | |
| "Enter a video path on the server β click on the first frame to select objects β " | |
| "propagate through the entire video β download bounding boxes as JSON." | |
| ) | |
| state = gr.State(None) | |
| with gr.Row(): | |
| # ββ Left panel: controls ββ | |
| with gr.Column(scale=1): | |
| # video_input = gr.Textbox( | |
| # label="πΉ Video Path (on server)", | |
| # placeholder="/path/to/video.mp4 or /path/to/jpeg_frames_dir/", | |
| # info="Enter the absolute path to an MP4 file or a JPEG frames directory on the server.", | |
| # ) | |
| DEFAULT_VIDEO_PATH = "/net/holy-isilon/ifs/rc_labs/ydu_lab/sycen/data/omnivitac/grasping_partial/mnt/oss_data/it20260119/Grasping/grasping_gello_flip/videos/0000/camera2.mp4" | |
| video_input = gr.Textbox( | |
| label="πΉ Video Path (on server)", | |
| value=DEFAULT_VIDEO_PATH, | |
| info="Enter the absolute path to an MP4 file or a JPEG frames directory on the server.", | |
| ) | |
| upload_btn = gr.Button("π Load Video", variant="primary") | |
| gr.Markdown("---") | |
| gr.Markdown("### Click Prompts") | |
| obj_id_input = gr.Number( | |
| label="Object ID", | |
| value=1, | |
| precision=0, | |
| ) | |
| click_mode = gr.Radio( | |
| choices=["Positive (include)", "Negative (exclude)"], | |
| value="Positive (include)", | |
| label="Click Mode", | |
| ) | |
| with gr.Row(): | |
| undo_btn = gr.Button("β©οΈ Undo", interactive=False) | |
| clear_btn = gr.Button("ποΈ Clear All", interactive=False) | |
| gr.Markdown("---") | |
| gr.Markdown("### Text Prompt (alternative)") | |
| text_input = gr.Textbox( | |
| label="Text prompt", | |
| placeholder='e.g. "person", "red car", "dog"', | |
| ) | |
| text_btn = gr.Button("π Apply Text Prompt") | |
| gr.Markdown("---") | |
| propagate_btn = gr.Button( | |
| "βΆοΈ Propagate & Export BBoxes", variant="primary", interactive=False | |
| ) | |
| # ββ Right panel: display ββ | |
| with gr.Column(scale=2): | |
| # frame_display = gr.Image( | |
| # label="First Frame (click to annotate)", | |
| # interactive=False, | |
| # type="numpy", | |
| # ) | |
| # video_preview = gr.Video( | |
| # label="Original Video", | |
| # value=DEFAULT_VIDEO_PATH, | |
| # ) | |
| frame_slider = gr.Slider( | |
| minimum=0, | |
| maximum=1, | |
| step=1, | |
| value=0, | |
| label="Annotation frame index", | |
| interactive=False, | |
| ) | |
| frame_display = gr.Image( | |
| label="Selected Frame (click to annotate)", | |
| interactive=True, | |
| type="numpy", | |
| ) | |
| status = gr.Textbox( | |
| label="Status", | |
| interactive=False, | |
| elem_classes="status-box", | |
| value="π Upload a video to get started.", | |
| ) | |
| json_output = gr.File(label="π¦ Download BBox JSON", visible=True) | |
| video_output = gr.Video(label="π¬ Propagated Tracking Video") | |
| # ββ Wiring βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| upload_btn.click( | |
| fn=upload_video, | |
| inputs=[video_input], | |
| outputs=[frame_display, status, undo_btn, propagate_btn, frame_slider, state], | |
| ).then( | |
| fn=lambda: gr.update(interactive=True), | |
| outputs=[clear_btn], | |
| ) | |
| frame_slider.change( | |
| fn=select_frame, | |
| inputs=[state, frame_slider], | |
| outputs=[frame_display, status, state], | |
| ) | |
| # Click on image | |
| frame_display.select( | |
| fn=handle_click, | |
| inputs=[state, click_mode, obj_id_input], | |
| outputs=[frame_display, status, state], | |
| ) | |
| undo_btn.click( | |
| fn=undo_last_click, | |
| inputs=[state], | |
| outputs=[frame_display, status, state], | |
| ) | |
| clear_btn.click( | |
| fn=clear_all_clicks, | |
| inputs=[state], | |
| outputs=[frame_display, status, state], | |
| ) | |
| text_btn.click( | |
| fn=handle_text_prompt, | |
| inputs=[state, text_input], | |
| outputs=[frame_display, status, state], | |
| ) | |
| propagate_btn.click( | |
| fn=propagate_and_export, | |
| inputs=[state], | |
| outputs=[json_output, video_output, status], | |
| ) | |
| return app | |
| # ββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="SAM 3 Interactive Video Annotator") | |
| parser.add_argument("--port", type=int, default=7860) | |
| parser.add_argument("--share", action="store_true", help="Create a public Gradio link") | |
| parser.add_argument("--host", type=str, default="0.0.0.0") | |
| args = parser.parse_args() | |
| # ββ Load model ONCE at startup (before any requests) ββ | |
| import sys | |
| t_total = time.time() | |
| print("=" * 60, flush=True) | |
| print("[INIT] Step 1/4: Importing sam3 internals β¦", flush=True) | |
| t0 = time.time() | |
| from sam3.model_builder import ( | |
| build_sam3_video_predictor as _build_pred, | |
| ) | |
| print(f"[INIT] Step 1/4 done. Import took {time.time() - t0:.1f}s", flush=True) | |
| print("[INIT] Step 2/4: Calling build_sam3_video_predictor() β¦", flush=True) | |
| print("[INIT] (this downloads/loads checkpoints β may be slow on /net storage)", flush=True) | |
| t0 = time.time() | |
| # Monkey-patch torch.load to add timing | |
| _original_torch_load = torch.load | |
| def _timed_torch_load(*args, **kwargs): | |
| path_str = str(args[0]) if args else str(kwargs.get("f", "???")) | |
| # Truncate long paths | |
| display = path_str if len(path_str) < 100 else "β¦" + path_str[-80:] | |
| print(f"[INIT] torch.load: {display}", flush=True) | |
| t = time.time() | |
| result = _original_torch_load(*args, **kwargs) | |
| print(f"[INIT] torch.load done β {time.time() - t:.1f}s", flush=True) | |
| return result | |
| torch.load = _timed_torch_load | |
| predictor = _build_pred() | |
| # Restore original | |
| torch.load = _original_torch_load | |
| print(f"[INIT] Step 2/4 done. Model build took {time.time() - t0:.1f}s", flush=True) | |
| print("[INIT] Step 3/4: Moving model to GPU / compiling β¦", flush=True) | |
| t0 = time.time() | |
| # Force a sync to make sure everything is on GPU | |
| if torch.cuda.is_available(): | |
| torch.cuda.synchronize() | |
| mem = torch.cuda.memory_allocated() / 1024**3 | |
| print(f"[INIT] GPU memory used: {mem:.2f} GB", flush=True) | |
| print(f"[INIT] Step 3/4 done. {time.time() - t0:.1f}s", flush=True) | |
| print(f"[INIT] Step 4/4: Building Gradio app β¦", flush=True) | |
| t0 = time.time() | |
| app = build_app() | |
| print(f"[INIT] Step 4/4 done. {time.time() - t0:.1f}s", flush=True) | |
| print("=" * 60, flush=True) | |
| print(f"[INIT] Total startup: {time.time() - t_total:.1f}s", flush=True) | |
| print(f"[INIT] Launching server on {args.host}:{args.port}", flush=True) | |
| print("=" * 60, flush=True) | |
| app.launch( | |
| allowed_paths=[ | |
| "/net/holy-isilon/ifs/rc_labs/ydu_lab/sycen/data/omnivitac/grasping_partial/mnt/oss_data/it20260119/Grasping/grasping_gello_flip/videos/0000" | |
| ], | |
| server_name=args.host, | |
| server_port=args.port, | |
| share=args.share, | |
| theme=gr.themes.Soft(), | |
| css=".main-title { text-align: center; } .status-box { font-family: monospace; font-size: 0.9em; }", | |
| ) |