import os os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") import spaces # noqa: E402 (must come before torch) import contextlib # noqa: E402 import io # noqa: E402 import tempfile # noqa: E402 import time # noqa: E402 import cv2 # noqa: E402 import gradio as gr # noqa: E402 import imageio_ffmpeg # noqa: E402 import numpy as np # noqa: E402 import torch # noqa: E402 from huggingface_hub import hf_hub_download # noqa: E402 from cowtracker import CoWTrackerWindowed # noqa: E402 MODEL_ID = "allenai/RoboTracker-Warp" INF_H, INF_W = 336, 560 # CoWTracker / RoboTrack evaluation resolution # RoboTrack eval protocol uses 100-frame windows (stride = window, <=10 memory frames). With 10 memory frames + # the first frame that is 111 frames per pass (~46GB, at the edge of a 48GB ZeroGPU slice), so we use 90 here # to keep every pass at <=101 frames (~42GB peak). WINDOW_LEN = 90 MAX_FRAMES_LIMIT = 300 # ---------------------------------------------------------------- model ckpt_path = hf_hub_download(MODEL_ID, "robotracker_warp.pth") _log = io.StringIO() with contextlib.redirect_stdout(_log): model = CoWTrackerWindowed.from_checkpoint( ckpt_path, window_len=WINDOW_LEN, stride=WINDOW_LEN, device="cpu", dtype=torch.float16 ) _msg = [l for l in _log.getvalue().splitlines() if l.startswith("Load message")] print(_msg) if not _msg or "All keys matched successfully" not in _msg[0]: raise RuntimeError(f"Checkpoint keys do not match the model: {_msg}") model = model.to("cuda").eval() # ---------------------------------------------------------------- helpers def read_video(path: str, max_frames: int): cap = cv2.VideoCapture(path) fps = cap.get(cv2.CAP_PROP_FPS) or 24.0 frames = [] while len(frames) < max_frames: ok, f = cap.read() if not ok: break frames.append(cv2.cvtColor(f, cv2.COLOR_BGR2RGB)) cap.release() if not frames: raise gr.Error("Could not read any frames from the video.") return np.stack(frames), float(fps) def parse_points(text: str): pts = [] for chunk in (text or "").replace("\n", ";").split(";"): chunk = chunk.strip().strip("()[]") if not chunk: continue try: x, y = [float(v) for v in chunk.split(",")[:2]] except ValueError: raise gr.Error(f"Could not parse point '{chunk}'. Use the format 'x,y; x,y'.") pts.append((x, y)) return pts def grid_points(H, W, n): xs = np.linspace(0, W - 1, n + 2)[1:-1] ys = np.linspace(0, H - 1, n + 2)[1:-1] return [(float(x), float(y)) for y in ys for x in xs] def color_palette(n): hsv = np.stack([np.linspace(0, 179, n, endpoint=False), np.full(n, 220), np.full(n, 255)], -1) rgb = cv2.cvtColor(hsv.astype(np.uint8)[None], cv2.COLOR_HSV2RGB)[0] return [tuple(int(c) for c in col) for col in rgb] def render(frames, tracks, vis, trail, radius): """frames T,H,W,3 uint8; tracks T,N,2 (pixels); vis T,N bool.""" T, H, W, _ = frames.shape N = tracks.shape[1] colors = color_palette(N) out = [] for t in range(T): img = frames[t].copy() overlay = img.copy() t0 = max(0, t - trail) for i in range(N): for s in range(t0, t): if vis[s, i] and vis[s + 1, i]: p0 = tuple(int(round(v)) for v in tracks[s, i]) p1 = tuple(int(round(v)) for v in tracks[s + 1, i]) cv2.line(overlay, p0, p1, colors[i], max(1, radius // 2), cv2.LINE_AA) img = cv2.addWeighted(overlay, 0.7, img, 0.3, 0) for i in range(N): p = tuple(int(round(v)) for v in tracks[t, i]) if vis[t, i]: cv2.circle(img, p, radius, colors[i], -1, cv2.LINE_AA) cv2.circle(img, p, radius, (255, 255, 255), 1, cv2.LINE_AA) else: cv2.circle(img, p, radius, colors[i], 1, cv2.LINE_AA) out.append(img) return np.stack(out) def write_mp4(frames, fps): T, H, W, _ = frames.shape path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name w = imageio_ffmpeg.write_frames( path, (W, H), fps=fps, codec="libx264", pix_fmt_out="yuv420p", output_params=["-crf", "20"], macro_block_size=2, ) w.send(None) for f in frames: w.send(np.ascontiguousarray(f)) w.close() return path def first_frame(video): """Return the first frame of the uploaded video (for clicking query points).""" if not video: return None frames, _ = read_video(video, 1) return frames[0] def add_point(points: str, evt: gr.SelectData): x, y = evt.index[0], evt.index[1] pts = (points or "").strip() new = f"{int(x)},{int(y)}" return f"{pts}; {new}" if pts else new def preview_points(video, points): """Draw the current query points on the first frame.""" img = first_frame(video) if img is None: return None try: pts = parse_points(points) except gr.Error: return img img = img.copy() r = max(3, int(round(min(img.shape[:2]) / 120))) for (x, y), c in zip(pts, color_palette(max(1, len(pts)))): cv2.circle(img, (int(x), int(y)), r + 1, c, -1, cv2.LINE_AA) cv2.circle(img, (int(x), int(y)), r + 1, (255, 255, 255), 1, cv2.LINE_AA) return img def _duration(video, points="", max_frames=150, *args, **kwargs): # measured on ZeroGPU: ~0.14 s/frame (150 frames: 21 s, 300 frames: 43 s) + ~15% margin return int(min(60, max(15, 1.15 * (3 + 0.14 * min(int(max_frames), MAX_FRAMES_LIMIT))))) @spaces.GPU(duration=_duration) def track( video: str, points: str = "", max_frames: int = 150, grid_size: int = 12, vis_threshold: float = 0.6, trail_length: int = 12, ): """Track query points through a video with RoboTracker-Warp. Args: video: Path to the input video. Points are queried on its first frame. points: Query points on the first frame as 'x,y; x,y' in pixel coordinates of the input video. Leave empty to track a uniform grid of points. max_frames: Number of frames (from the start of the video) to track. grid_size: Grid size (N x N points) used when no query points are given. vis_threshold: A point is drawn as visible when visibility x confidence >= this value. trail_length: Number of past frames drawn as a trail behind each point. Returns: The video with tracked points drawn, and a .npz with tracks (T,N,2) and visibility (T,N). """ if not video: raise gr.Error("Please upload a video.") t_start = time.perf_counter() frames, fps = read_video(video, int(min(max_frames, MAX_FRAMES_LIMIT))) T, H0, W0, _ = frames.shape if T < 2: raise gr.Error("The video needs at least 2 frames.") pts = parse_points(points) if not pts: pts = grid_points(H0, W0, int(grid_size)) q = np.array(pts, np.float32) q[:, 0] = q[:, 0].clip(0, W0 - 1) q[:, 1] = q[:, 1].clip(0, H0 - 1) # Resize to the inference resolution exactly as the RoboTrack evaluation does. small = np.stack([cv2.resize(f, (INF_W, INF_H), interpolation=cv2.INTER_LINEAR) for f in frames]) to_inf = np.array([(INF_W - 1) / (W0 - 1), (INF_H - 1) / (H0 - 1)], np.float32) q_inf = q * to_inf xi = torch.from_numpy(q_inf[:, 0]).round().long().clamp(0, INF_W - 1) yi = torch.from_numpy(q_inf[:, 1]).round().long().clamp(0, INF_H - 1) video_t = torch.from_numpy(small).to("cuda").permute(0, 3, 1, 2).float() # T,3,H,W in 0..255 with torch.no_grad(), torch.amp.autocast(device_type="cuda", dtype=torch.float16): pred = model(video_t) xi, yi = xi.to("cuda"), yi.to("cuda") tr = pred["track"][0][:, yi, xi].float().cpu().numpy() # T,N,2 at inference res vp = (pred["vis"][0][:, yi, xi].float() * pred["conf"][0][:, yi, xi].float()).cpu().numpy() del pred, video_t torch.cuda.empty_cache() t_model = time.perf_counter() - t_start tracks = tr / to_inf # back to input-video pixels vis = vp >= float(vis_threshold) vis[0] = True radius = max(2, int(round(min(H0, W0) / 160))) if len(pts) > 64: radius = max(2, radius - 1) painted = render(frames, tracks, vis, int(trail_length), radius) out_video = write_mp4(painted, fps) npz_path = tempfile.NamedTemporaryFile(suffix=".npz", delete=False).name np.savez(npz_path, tracks=tracks.astype(np.float32), visibility=vp.astype(np.float32), queries=q) print(f"[track] peak_mem={torch.cuda.max_memory_allocated() / 2**30:.1f}GB") print(f"[track] T={T} N={len(pts)} {W0}x{H0} model+io={t_model:.1f}s total={time.perf_counter() - t_start:.1f}s") return out_video, npz_path # ---------------------------------------------------------------- UI CSS = """ #col-container { max-width: 1200px; margin: 0 auto; } .dark .gradio-container { color: var(--body-text-color); } """ with gr.Blocks(title="RoboTracker-Warp") as demo: with gr.Column(elem_id="col-container"): gr.Markdown( """ # RoboTracker-Warp — point tracking for robot manipulation video [RoboTracker-Warp](https://huggingface.co/allenai/RoboTracker-Warp) is Ai2's ~1B-param tracker: [CoWTracker](https://github.com/facebookresearch/cowtracker) fine-tuned on RoboTrack-15M. Upload a video, **click on the first frame** to place query points (or leave empty to track a grid), then press **Track**. [Paper](https://arxiv.org/abs/2611.35306) · [Code](https://github.com/allenai/robotrack) · [Project page](https://robotrack.allen.ai) · Non-commercial (CC-BY-NC 4.0 weights, FAIR NC research license code). """ ) with gr.Row(): with gr.Column(): video_in = gr.Video(label="Input video", sources=["upload"], height=320) frame_img = gr.Image( label="First frame — click to add query points", type="numpy", interactive=False, height=320 ) points = gr.Textbox( label="Query points (x,y; x,y — pixels on the first frame). Empty = grid.", placeholder="Click on the first frame above, or type e.g. 287,210; 490,229", ) with gr.Row(): clear_btn = gr.Button("Clear points") run_btn = gr.Button("Track", variant="primary") with gr.Column(): video_out = gr.Video(label="Tracked points", autoplay=True, loop=True, height=420) file_out = gr.File(label="Tracks (.npz: tracks T×N×2, visibility T×N)") with gr.Accordion("Advanced settings", open=False): max_frames = gr.Slider(16, MAX_FRAMES_LIMIT, value=150, step=1, label="Max frames to track") grid_size = gr.Slider(4, 24, value=12, step=1, label="Grid size when no points are given (N×N)") vis_threshold = gr.Slider(0.05, 0.95, value=0.6, step=0.05, label="Visibility threshold (vis × conf)") trail_length = gr.Slider(0, 60, value=12, step=1, label="Trail length (frames)") gr.Examples( examples=[ ["examples/droid_franka.mp4", "287,210; 490,229"], ["examples/molmoact2_yam_box.mp4", "391,203; 269,195; 247,288; 198,221; 383,56; 351,75"], ["examples/molmoact2_so100_battery.mp4", ""], ], inputs=[video_in, points], outputs=[video_out, file_out], fn=track, cache_examples=True, cache_mode="lazy", label="Examples from RoboTrack-Bench (DROID, MolmoAct2) — points are the benchmark's annotated query points", ) video_in.change(preview_points, [video_in, points], frame_img, api_visibility="private") points.change(preview_points, [video_in, points], frame_img, api_visibility="private") frame_img.select(add_point, [points], points, api_visibility="private") clear_btn.click(lambda: "", None, points, api_visibility="private") run_btn.click( track, [video_in, points, max_frames, grid_size, vis_threshold, trail_length], [video_out, file_out], api_name="track", ) if __name__ == "__main__": demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)