Spaces:
Running on Zero

File size: 4,713 Bytes
7547a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pathlib import Path
from typing import Any

import gradio as gr
import numpy as np
import spaces
from huggingface_hub import hf_hub_download

import demo_core

ROOT = Path(__file__).resolve().parent
CHECKPOINT_DIR = ROOT / "checkpoints"
MODEL_REPO = "Charlie839242/StreamTAP3D"

EXAMPLES = [
    ["assets/camel.mp4", "assets/camel_mask.png", 128, 1, 256, 4],
    ["assets/horse.mp4", "assets/horse_mask.png", 128, 1, 256, 4],
    ["assets/skating.mp4", "assets/skating_mask.png", 128, 1, 256, 4],
    ["assets/swing.mp4", "assets/swing_mask.png", 128, 1, 256, 4],
]


def _video_path(video: Any) -> str:
    if video is None:
        raise gr.Error("Please upload or select a video.")
    if isinstance(video, str):
        return video
    if isinstance(video, dict):
        path = video.get("video") or video.get("path") or video.get("name")
        if path:
            return path
    if hasattr(video, "name"):
        return video.name
    raise gr.Error("Cannot read the uploaded video path.")


def ensure_checkpoints() -> None:
    CHECKPOINT_DIR.mkdir(parents=True, exist_ok=True)
    for filename in ("tracker.pth", "abot_recon.safetensors"):
        hf_hub_download(MODEL_REPO, filename=filename, local_dir=str(CHECKPOINT_DIR))


def overlay_mask(image: np.ndarray, mask: np.ndarray, color=(36, 132, 255), alpha: float = 0.45) -> np.ndarray:
    image = np.asarray(image).copy()
    mask = demo_core.mask_to_binary(mask).astype(bool)
    overlay = image.copy()
    overlay[mask] = np.array(color, dtype=np.uint8)
    return np.where(mask[..., None], (image * (1.0 - alpha) + overlay * alpha).astype(np.uint8), image)


def load_first_frame(video):
    path = _video_path(video)
    frame = demo_core.read_first_frame(path)
    return frame, None


def preview_uploaded_mask(video, uploaded_mask):
    if video is None:
        return None
    frame = demo_core.read_first_frame(_video_path(video))
    if uploaded_mask is None:
        return frame
    mask = demo_core.validate_mask_size(uploaded_mask, tuple(frame.shape[:2]))
    return overlay_mask(frame, mask)


@spaces.GPU(duration=100)
def run_demo(video, uploaded_mask, max_frames, frame_stride, num_points, trajectory_length):
    video_path = _video_path(video)
    if uploaded_mask is None:
        raise gr.Error("请上传与视频原始分辨率一致的第一帧 mask。")

    ensure_checkpoints()
    first_frame = demo_core.read_first_frame(video_path)
    mask = demo_core.validate_mask_size(uploaded_mask, tuple(first_frame.shape[:2]))

    return demo_core.run(
        video_path,
        mask,
        max_frames=int(max_frames),
        frame_stride=int(frame_stride),
        num_points=int(num_points),
        trajectory_length=int(trajectory_length),
        mask_margin=demo_core.DEFAULT_MASK_MARGIN,
    )


with gr.Blocks(title="StreamTAP3D ZeroGPU Demo") as demo:
    gr.Markdown(
        "# StreamTAP3D Demo\n"
        "Upload a video and a first-frame mask with exactly the same original resolution as the video. "
        "Free ZeroGPU quota is limited, so keep clips short."
    )
    with gr.Row():
        with gr.Column():
            video = gr.Video(label="Input video", sources=["upload"])
            uploaded_mask = gr.Image(
                label="First-frame mask (must match video resolution)",
                type="numpy",
                image_mode="RGBA",
            )
            max_frames = gr.Slider(1, 128, value=128, step=1, label="Max frames")
            frame_stride = gr.Slider(1, 8, value=1, step=1, label="Frame stride")
            num_points = gr.Slider(1, 256, value=256, step=1, label="Tracking points")
            trajectory_length = gr.Slider(4, 8, value=4, step=1, label="Trajectory length")
            run_button = gr.Button("Run StreamTAP3D", variant="primary")
        with gr.Column():
            first_frame = gr.Image(label="First frame / mask preview", type="numpy")
            output_video = gr.Video(label="Output")

    video.change(
        load_first_frame,
        inputs=[video],
        outputs=[first_frame, output_video],
    )
    uploaded_mask.change(
        preview_uploaded_mask,
        inputs=[video, uploaded_mask],
        outputs=[first_frame],
    )
    run_button.click(
        run_demo,
        inputs=[video, uploaded_mask, max_frames, frame_stride, num_points, trajectory_length],
        outputs=[output_video],
    )
    gr.Examples(
        examples=EXAMPLES,
        inputs=[video, uploaded_mask, max_frames, frame_stride, num_points, trajectory_length],
        outputs=[output_video],
        fn=run_demo,
        cache_examples=False,
    )

if __name__ == "__main__":
    ensure_checkpoints()
    demo.queue(max_size=4).launch()