File size: 17,629 Bytes
61088ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
700395e
 
 
 
 
 
 
 
 
 
 
 
61088ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import os

os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

import spaces  # noqa: E402  (must come before torch)
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 alltracker import Net  # noqa: E402  (vendored from allenai/robotrack, MIT)

# ---------------------------------------------------------------------------------------------------------------------
# Model — same loading / inference protocol as robotrack.eval_alltracker (384x512, 4 iters, vis x conf >= 0.6, TF32)
# ---------------------------------------------------------------------------------------------------------------------
IMAGE_SIZE = (384, 512)  # H, W
ITERS = 4
SLIDING_THRESHOLD = 128
VIS_THRESHOLD = 0.6

torch.backends.cudnn.deterministic, torch.backends.cudnn.benchmark = True, False
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True

_ckpt = hf_hub_download("allenai/RoboTracker", "robotracker.pth")
_state = torch.load(_ckpt, map_location="cpu", weights_only=True)
model = Net(seqlen=16, init_weights=False)
model.load_state_dict(_state["model"], strict=True)
model = model.to("cuda").eval().requires_grad_(False)
del _state


# ---------------------------------------------------------------------------------------------------------------------
# Video / point helpers
# ---------------------------------------------------------------------------------------------------------------------
def read_video(path, max_frames=None):
    cap = cv2.VideoCapture(str(path))
    fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
    frames = []
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
        if max_frames and len(frames) >= max_frames:
            break
    cap.release()
    if not frames:
        raise gr.Error("Could not decode any frames from this video.")
    return np.stack(frames), float(fps)


def read_frame(path, idx):
    cap = cv2.VideoCapture(str(path))
    n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx))
    ok, frame = cap.read()
    if not ok:  # some containers seek badly: fall back to sequential read
        cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
        for _ in range(int(idx) + 1):
            ok2, f2 = cap.read()
            if not ok2:
                break
            frame, ok = f2, True
    cap.release()
    if not ok:
        return None, n
    return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), n


def parse_points(text):
    """Parse 'x,y,frame' lines (frame optional, default 0) into an [N, 3] float array."""
    pts = []
    for line in (text or "").replace(";", "\n").splitlines():
        line = line.strip()
        if not line:
            continue
        parts = [p for p in line.replace(" ", ",").split(",") if p]
        try:
            x, y = float(parts[0]), float(parts[1])
            t = int(float(parts[2])) if len(parts) > 2 else 0
        except (ValueError, IndexError):
            raise gr.Error(f"Could not parse point '{line}'. Use one 'x,y,frame' per line.")
        pts.append((x, y, t))
    return np.array(pts, np.float32).reshape(-1, 3)


def point_colors(n):
    hsv = np.stack([np.linspace(0, 179, n, endpoint=False), np.full(n, 230), np.full(n, 255)], 1).astype(np.uint8)
    return cv2.cvtColor(hsv[None], cv2.COLOR_HSV2RGB)[0].tolist()


def draw_query_points(frame, points, frame_idx):
    img = frame.copy()
    r = max(4, int(round(min(img.shape[:2]) / 90)))
    colors = point_colors(max(len(points), 1))
    for i, (x, y, t) in enumerate(points):
        if int(t) != int(frame_idx):
            continue
        c = tuple(int(v) for v in colors[i])
        cv2.circle(img, (int(round(x)), int(round(y))), r + 2, (255, 255, 255), -1, cv2.LINE_AA)
        cv2.circle(img, (int(round(x)), int(round(y))), r, c, -1, cv2.LINE_AA)
    return img


def render_tracks(frames, tracks, visible, query_frames, trail_length):
    """Draw trails + points on the original-resolution frames. Filled = visible, ring = occluded."""
    T, H, W = frames.shape[:3]
    N = tracks.shape[1]
    colors = [tuple(int(v) for v in c) for c in point_colors(max(N, 1))]
    r = max(3, int(round(min(H, W) / 110)))
    th = max(1, r // 2)
    out = []
    for t in range(T):
        img = frames[t].copy()
        overlay = img.copy()
        for n in range(N):
            if t < query_frames[n]:
                continue
            t0 = max(int(query_frames[n]), t - trail_length)
            seg = [tracks[s, n] for s in range(t0, t + 1) if visible[s, n]]
            if len(seg) > 1:
                cv2.polylines(overlay, [np.round(np.array(seg)).astype(np.int32)], False, colors[n], th, cv2.LINE_AA)
        img = cv2.addWeighted(overlay, 0.7, img, 0.3, 0)
        for n in range(N):
            if t < query_frames[n]:
                continue
            x, y = int(round(tracks[t, n, 0])), int(round(tracks[t, n, 1]))
            if visible[t, n]:
                cv2.circle(img, (x, y), r + 1, (255, 255, 255), -1, cv2.LINE_AA)
                cv2.circle(img, (x, y), r, colors[n], -1, cv2.LINE_AA)
            else:
                cv2.circle(img, (x, y), r, colors[n], th, cv2.LINE_AA)
        out.append(img)
    return out


def write_mp4(frames, fps, path):
    H, W = frames[0].shape[:2]
    H2, W2 = H - H % 2, W - W % 2
    writer = imageio_ffmpeg.write_frames(path, (W2, H2), fps=fps, codec="libx264", pix_fmt_out="yuv420p",
                                         quality=7, macro_block_size=1, ffmpeg_log_level="error")
    writer.send(None)
    for f in frames:
        writer.send(np.ascontiguousarray(f[:H2, :W2]))
    writer.close()


@torch.no_grad()
def run_tracker(frames_small, query_xy, query_frames):
    """robotrack.eval_alltracker.track: one dense pass per distinct query frame, read off the query pixels."""
    device = "cuda"
    video = torch.from_numpy(frames_small).to(device).permute(0, 3, 1, 2).float()[None]  # 1,T,3,H,W
    T, H, W = video.shape[1], video.shape[3], video.shape[4]
    ys, xs = torch.meshgrid(torch.arange(H, device=device), torch.arange(W, device=device), indexing="ij")
    grid = torch.stack([xs, ys]).float()[None, None]
    query_frames = torch.as_tensor(query_frames, device=device)
    query_xy = torch.as_tensor(query_xy, device=device)
    N = len(query_frames)
    tracks = torch.zeros(T, N, 2, device=device)
    vis_prob = torch.zeros(T, N, device=device)
    for t in torch.unique(query_frames).tolist():
        idx = torch.nonzero(query_frames == t)[:, 0]
        traj_map = grid.repeat(1, T, 1, 1, 1)
        conf_map = torch.zeros_like(traj_map)
        if t < T - 1:
            clip = video[:, t:]
            forward = model.forward_sliding if clip.shape[1] > SLIDING_THRESHOLD else model
            flow, visconf, *_ = forward(clip, iters=ITERS, sw=None, is_training=False)
            traj_map[:, t:] = flow.to(device) + grid
            conf_map[:, t:] = visconf.to(device)
        x = query_xy[idx, 0].round().long().clamp(0, W - 1)
        y = query_xy[idx, 1].round().long().clamp(0, H - 1)
        tracks[:, idx] = traj_map[0, :, :, y, x].permute(0, 2, 1)
        conf = conf_map[0, :, :, y, x]
        vis_prob[:, idx] = conf[:, 0] * conf[:, 1]
    return tracks.cpu().numpy(), vis_prob.cpu().numpy()


# ---------------------------------------------------------------------------------------------------------------------
# Main entry point
# ---------------------------------------------------------------------------------------------------------------------
def _gpu_duration(video, points="", max_frames=150, *args, **kwargs):
    # Measured on ZeroGPU: ~5.5 s fixed (decode + warm-up + encode) and ~0.013 s per frame per dense pass,
    # plus ~0.01 s/frame rendering. +15% margin.
    try:
        passes = max(1, len({int(r[2]) for r in parse_points(points)}))
    except Exception:
        passes = 1
    T = int(max_frames)
    return int(min(120, max(10, np.ceil((5.5 + passes * T * 0.013 + T * 0.01) * 1.15))))


@spaces.GPU(duration=_gpu_duration)
def track_points(video: str, points: str = "", max_frames: int = 150, grid_size: int = 10,
                 trail_length: int = 12, vis_threshold: float = VIS_THRESHOLD):
    """Track query points through a video with RoboTracker.

    Args:
        video: path to the input video (robot manipulation footage works best).
        points: query points, one 'x,y,frame' per line in original video pixels (frame defaults to 0).
            If empty, a uniform grid of points on the first frame is tracked.
        max_frames: maximum number of frames (from the start of the video) to process.
        grid_size: grid side length used when no points are given (grid_size x grid_size points).
        trail_length: number of past frames drawn as a trail behind every point.
        vis_threshold: a point is drawn as visible when visibility x confidence >= this threshold.

    Returns:
        The annotated video (filled dots = visible, rings = occluded) and an .npz file with
        `tracks` [T, N, 2] (x, y in original pixels), `visibility` [T, N] and `query_frames` [N].
    """
    if not video:
        raise gr.Error("Please upload a video first.")
    t_start = time.perf_counter()
    frames, fps = read_video(video, int(max_frames))
    T, H0, W0 = frames.shape[:3]
    if T < 2:
        raise gr.Error("The video needs at least 2 frames.")

    pts = parse_points(points)
    if len(pts) == 0:
        g = max(2, int(grid_size))
        xs = np.linspace(W0 * 0.06, W0 * 0.94, g)
        ys = np.linspace(H0 * 0.06, H0 * 0.94, g)
        gx, gy = np.meshgrid(xs, ys)
        pts = np.stack([gx.ravel(), gy.ravel(), np.zeros(g * g)], 1).astype(np.float32)
    keep = (pts[:, 2] >= 0) & (pts[:, 2] < T)
    if not keep.any():
        raise gr.Error(f"All query frames are outside the processed {T} frames. Increase 'Max frames'.")
    if not keep.all():
        gr.Warning(f"Dropped {int((~keep).sum())} point(s) whose query frame is beyond the processed {T} frames.")
    pts = pts[keep]
    pts[:, 0] = pts[:, 0].clip(0, W0 - 1)
    pts[:, 1] = pts[:, 1].clip(0, H0 - 1)

    Hs, Ws = IMAGE_SIZE
    small = np.stack([cv2.resize(f, (Ws, Hs), interpolation=cv2.INTER_LINEAR) for f in frames])
    to_small = np.array([(Ws - 1) / max(W0 - 1, 1), (Hs - 1) / max(H0 - 1, 1)], np.float32)
    query_xy = pts[:, :2] * to_small
    query_frames = pts[:, 2].astype(np.int64)

    t_model = time.perf_counter()
    tracks, vis_prob = run_tracker(small, query_xy, query_frames)
    t_model = time.perf_counter() - t_model

    tracks = tracks / to_small  # back to original pixels
    visible = vis_prob >= float(vis_threshold)
    rendered = render_tracks(frames, tracks, visible, query_frames, int(trail_length))

    out_dir = tempfile.mkdtemp()
    out_video = os.path.join(out_dir, "robotracker_tracks.mp4")
    write_mp4(rendered, fps, out_video)
    out_npz = os.path.join(out_dir, "robotracker_tracks.npz")
    np.savez_compressed(out_npz, tracks=tracks.astype(np.float32), visibility=visible,
                        visibility_prob=vis_prob.astype(np.float32), query_frames=query_frames.astype(np.int32))
    print(f"[track] T={T} N={len(pts)} passes={len(np.unique(query_frames))} "
          f"model={t_model:.1f}s total={time.perf_counter() - t_start:.1f}s", flush=True)
    return out_video, out_npz


# ---------------------------------------------------------------------------------------------------------------------
# UI callbacks (CPU only)
# ---------------------------------------------------------------------------------------------------------------------
def on_video_change(video, points, max_frames):
    if not video:
        return None, gr.update(value=0, maximum=1)
    frame, n = read_frame(video, 0)
    if frame is None:
        return None, gr.update(value=0, maximum=1)
    last = max(1, min(n, int(max_frames)) - 1)
    return draw_query_points(frame, parse_points(points), 0), gr.update(value=0, maximum=last)


def on_frame_change(video, frame_idx, points):
    if not video:
        return None
    frame, _ = read_frame(video, int(frame_idx))
    if frame is None:
        return None
    return draw_query_points(frame, parse_points(points), int(frame_idx))


def on_click(video, frame_idx, points, evt: gr.SelectData):
    if not video:
        raise gr.Error("Upload a video first.")
    x, y = evt.index[0], evt.index[1]
    line = f"{int(x)},{int(y)},{int(frame_idx)}"
    points = (points.strip() + "\n" + line).strip() if points and points.strip() else line
    frame, _ = read_frame(video, int(frame_idx))
    return points, draw_query_points(frame, parse_points(points), int(frame_idx))


def on_clear(video, frame_idx):
    if not video:
        return "", None
    frame, _ = read_frame(video, int(frame_idx))
    return "", frame


# ---------------------------------------------------------------------------------------------------------------------
# Layout
# ---------------------------------------------------------------------------------------------------------------------
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""

EXAMPLES = [
    ["examples/droid_franka_blocks.mp4",
     "717,423,0\n631,478,0\n536,373,0\n612,431,0\n485,350,0\n661,457,0\n704,586,0\n613,358,0\n467,398,0"],
    ["examples/yam_cups.mp4",
     "87,230,0\n220,215,0\n382,95,0\n230,191,0\n75,333,81\n160,175,0\n98,344,67\n179,231,0\n50,349,79\n164,154,0"],
    ["examples/yam_fold_clothes.mp4",
     "613,334,0\n458,282,0\n306,139,0\n75,248,0\n438,119,0\n318,70,0\n307,124,0\n188,156,0\n594,238,0\n497,132,0"],
    ["examples/so100_banana.mp4", "300,370,0\n423,363,0\n356,259,62\n356,78,59\n374,161,0"],
]

with gr.Blocks(title="RoboTracker") as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(
            "# 🦾 RoboTracker: point tracking for robot manipulation\n"
            "[RoboTracker](https://huggingface.co/allenai/RoboTracker) is AllTracker fine-tuned on RoboTrack-15M. "
            "Upload a video, **click on the frame to pick points** (scrub the slider to query points on later frames), "
            "and RoboTracker follows every point through the clip, telling you where it is and whether it is visible. "
            "No points? A uniform grid is tracked.  \n"
            "[Code](https://github.com/allenai/robotrack) · [Paper](https://arxiv.org/abs/2611.35306) · "
            "[Project page](https://robotrack.allen.ai) · [Benchmark](https://huggingface.co/datasets/allenai/RoboTrack-Bench)"
        )
        with gr.Row():
            with gr.Column():
                video_in = gr.Video(label="Input video", sources=["upload"])
                frame_view = gr.Image(label="Click to add query points", type="numpy", interactive=False)
                frame_idx = gr.Slider(0, 1, value=0, step=1, label="Query frame")
                points = gr.Textbox(label="Query points (x,y,frame per line, original pixels)", lines=4,
                                    placeholder="Click on the frame above, or type e.g. 320,240,0")
                with gr.Row():
                    clear_btn = gr.Button("Clear points")
                    run_btn = gr.Button("Track points", variant="primary")
            with gr.Column():
                video_out = gr.Video(label="Tracks (filled = visible, ring = occluded)", autoplay=True)
                npz_out = gr.File(label="Tracks + visibility (.npz)")
        with gr.Accordion("Advanced settings", open=False):
            max_frames = gr.Slider(16, 300, value=150, step=1, label="Max frames (from the start of the video)")
            grid_size = gr.Slider(2, 24, value=10, step=1, label="Grid size (used when no points are given)")
            trail_length = gr.Slider(0, 60, value=12, step=1, label="Trail length (frames)")
            vis_threshold = gr.Slider(0.05, 0.95, value=VIS_THRESHOLD, step=0.05, label="Visibility threshold")

        gr.Examples(
            examples=EXAMPLES,
            inputs=[video_in, points],
            outputs=[video_out, npz_out],
            fn=track_points,
            cache_examples=True,
            cache_mode="lazy",
            label="RoboTrack-Bench clips (with the benchmark's annotated query points)",
        )
        gr.Markdown(
            "Example clips come from [RoboTrack-Bench](https://huggingface.co/datasets/allenai/RoboTrack-Bench): "
            "DROID (CC-BY-4.0) and MolmoAct2 (Apache-2.0). Frames are processed at 384×512 as in the paper."
        )

    video_in.change(on_video_change, [video_in, points, max_frames], [frame_view, frame_idx], api_visibility="private")
    frame_idx.release(on_frame_change, [video_in, frame_idx, points], frame_view, api_visibility="private")
    points.blur(on_frame_change, [video_in, frame_idx, points], frame_view, api_visibility="private")
    frame_view.select(on_click, [video_in, frame_idx, points], [points, frame_view], api_visibility="private")
    clear_btn.click(on_clear, [video_in, frame_idx], [points, frame_view], api_visibility="private")
    run_btn.click(track_points, [video_in, points, max_frames, grid_size, trail_length, vis_threshold],
                  [video_out, npz_out], api_name="track")

if __name__ == "__main__":
    demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)