Spaces:
Running on Zero

File size: 15,021 Bytes
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6f49fe
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d34691
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d34691
 
 
a863b67
6d34691
 
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
2eec021
a863b67
 
2eec021
 
 
a863b67
 
 
 
 
 
 
 
 
 
 
 
12e4f34
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d34691
 
 
 
 
 
 
a863b67
 
6d34691
 
 
a863b67
 
c6f49fe
 
 
 
12e4f34
 
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6f49fe
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12e4f34
c6f49fe
a863b67
c6f49fe
 
a863b67
 
 
 
 
 
 
 
 
 
 
 
12e4f34
a863b67
12e4f34
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Flow4RT web demo (Gradio): upload a video and explore the result in the interactive 4D viewer.

    pip install -e .[app]
    python app.py                # http://localhost:7860; --share for a public link

Also runs as a Hugging Face Space (ZeroGPU if the `spaces` package is present).
"""

import argparse
import os
import re
import shutil
import tempfile
import threading
import time
import uuid

import gradio as gr
import torch

from flow4rt.inference import frames_to_tensor, load_model, predict, read_frames
from visualize import write_empty_viewer, write_viewer

try:
    import spaces  # Hugging Face ZeroGPU
    gpu = spaces.GPU(duration=120)
except ImportError:
    gpu = lambda fn: fn

ROOT = os.path.dirname(os.path.abspath(__file__))
WEIGHTS = os.path.join(ROOT, "checkpoints", "flow4rt.safetensors")
OUTPUTS = os.path.join(tempfile.gettempdir(), "flow4rt_app")
# The clips of the project page, in its order (sources in examples/CREDITS.md).
EXAMPLES = ["bmx_bowl", "parkour", "soapbox", "forest_car", "toy_car", "rollerblade", "swing", "kite_surf",
            "horsejump_high", "car_turn"]
EXAMPLE_DIR = os.path.join(ROOT, "examples")
MAX_FRAMES = 64
KEEP_HOURS = 6  # results older than this are deleted

# The viewer's design tokens (viewer/template.html), applied to the Gradio page.
FONT = ["-apple-system", "BlinkMacSystemFont", "Segoe UI", "Roboto", "Helvetica", "Arial", "sans-serif"]
ACCENT, ACCENT_INK, ACCENT_SOFT = "#1a73e8", "#0f57b8", "#e8f0fe"
TEXT, INK, SOFT, LINE, LINE_STRONG, TRACK = "#1d232c", "#14181f", "#586272", "#e2e7ee", "#cfd7e2", "#e9edf3"
CHIP = "#f1f4f8"  # the project page's resource pills
SHADOW = "0 1px 2px rgba(16,24,40,.05), 0 6px 20px rgba(16,24,40,.06)"

THEME = gr.themes.Base(font=FONT, font_mono=["ui-monospace", "SFMono-Regular", "Menlo", "monospace"]).set(
    body_background_fill="#fff", body_text_color=TEXT, body_text_color_subdued=SOFT,
    background_fill_primary="#fff", background_fill_secondary="#fff", border_color_primary=LINE,
    block_background_fill="#fff", block_border_color=LINE, block_border_width="1px", block_radius="14px",
    block_shadow=SHADOW, block_padding="14px", block_label_background_fill="#fff", block_label_text_color=SOFT,
    block_label_border_color=LINE, block_title_text_color=SOFT, block_title_text_weight="500",
    block_label_text_weight="500", layout_gap="16px", panel_background_fill="#fff", panel_border_width="0px",
    input_background_fill="#fff", input_border_color=LINE_STRONG, input_border_color_focus=ACCENT,
    input_radius="10px", input_shadow_focus="0 0 0 3px rgba(26,115,232,.28)",
    slider_color=ACCENT, color_accent=ACCENT, color_accent_soft=ACCENT_SOFT, loader_color=ACCENT,
    button_large_radius="999px", button_medium_radius="999px", button_small_radius="999px",
    button_large_text_weight="600", button_primary_background_fill=ACCENT,
    button_primary_background_fill_hover=ACCENT_INK, button_primary_border_color=ACCENT,
    button_primary_text_color="#fff", button_primary_shadow="0 1px 2px rgba(15,87,184,.35), 0 2px 8px rgba(26,115,232,.28)",
    button_secondary_background_fill="#fff", button_secondary_background_fill_hover=ACCENT_SOFT,
    button_secondary_border_color=LINE_STRONG, button_secondary_text_color=INK,
    button_secondary_text_color_hover=ACCENT_INK,
)

CSS = f"""
.gradio-container {{ width: 100% !important; max-width: 1480px !important; margin: 0 auto !important;
  padding: 20px 16px 8px !important; }}
footer {{ display: none !important; }}
#header {{ display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px 24px;
  padding: 4px 2px 6px; }}
#header h1 {{ margin: 0; font-size: 1.6rem; line-height: 1.2; font-weight: 700; color: {INK}; letter-spacing: -.01em; }}
#header h1 i {{ font-style: normal; color: {ACCENT}; }}
#header h1 span {{ color: {SOFT}; font-weight: 500; }}
#header .links {{ display: flex; gap: 8px; }}
/* The links as the project page's resource pills: grey, no outline, blue on hover. */
#header .links a {{ display: inline-flex; align-items: center; gap: 5px; height: 30px; padding: 0 12px 0 9px; border-radius: 999px;
  border: 1px solid transparent; background: {CHIP}; color: {TEXT}; font-size: .85rem; font-weight: 500;
  text-decoration: none; transition: background .16s, border-color .16s, color .16s; }}
#header .links a:hover {{ background: {ACCENT_SOFT}; color: {ACCENT_INK}; border-color: transparent; }}
#header .links svg {{ width: 13px; height: 13px; flex: none; }}
/* One card for the settings, examples and the Run button; the blocks inside it are flat. */
#settings {{ border: 1px solid {LINE}; border-radius: 14px; box-shadow: {SHADOW}; background: #fff;
  padding: 14px 16px 16px; gap: 14px; }}
#settings .block, #settings .form {{ border: 0 !important; box-shadow: none !important; padding: 0 !important;
  background: none !important; overflow: visible !important; }}
#settings .form {{ gap: 14px !important; flex: none !important; }}
/* Examples: a vertical list of clips left of the video, played while hovered. */
#examples {{ border: 1px solid {LINE}; border-radius: 14px; box-shadow: {SHADOW}; background: #fff; padding: 12px;
  gap: 8px; }}
#examples .html-container, #examples .prose, #examples .block {{ padding: 0 !important; border: 0 !important;
  box-shadow: none !important; background: none !important; }}
.card-title {{ font-size: .85rem; font-weight: 500; color: {SOFT}; margin: 0 2px; line-height: 1.2; }}
.ex-list {{ display: grid; grid-template-columns: 1fr 1fr; align-content: start; gap: 8px; height: 330px; margin-top: 8px; overflow-y: auto; padding-right: 2px; }}
#examples .ex {{ position: relative; display: block; width: 100%; height: 0; padding: 0 0 56.25%; border-radius: 10px; overflow: hidden;
  border: 1px solid {LINE}; background: {TRACK}; box-shadow: none; cursor: pointer;
  transition: border-color .16s, box-shadow .16s; }}
#examples .ex:hover {{ border-color: {ACCENT}; }}
#examples .ex.on {{ border-color: {ACCENT}; box-shadow: 0 0 0 2px {ACCENT}; }}
#examples .ex video {{ position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; display: block;
  pointer-events: none; }}
#example-pick {{ display: none !important; }}
#run {{ margin-top: auto; flex: none; height: 44px; min-height: 44px; }}
/* The viewer brings its own 16px padding and canvas card: align its canvas with the cards above. */
#viewer, #viewer .html-container, #viewer .prose {{ padding: 0 !important; margin: 0 !important;
  overflow: visible !important; max-width: none !important; }}
#viewer iframe {{ display: block; width: calc(100% + 32px); margin: 0 -16px; height: min(820px, 90vh); border: 0; }}
"""

# Narrow windows, in <head>: Gradio rewrites the selectors inside the @media rules of `css`.
HEAD = """<style>
/* Narrow windows: the viewer stacks its side panel under the canvas (below 900px) and the page sizes the
   iframe to it. */
@media (max-width: 900px) {
  .main.fillable { padding-left: 0 !important; padding-right: 0 !important; }
  .gradio-container { padding: 12px 12px 8px !important; }
  #viewer iframe { width: 100% !important; margin: 0 !important; height: 1000px; }
  #video { height: 240px !important; }
  #header h1 { font-size: 1.3rem !important; }
  .ex-list { height: 236px !important; }
}
</style>"""

# The viewer is light-only: keep the page light as well.
JS = """() => { const u = new URL(location.href);
  if (u.searchParams.get('__theme') !== 'light') { u.searchParams.set('__theme', 'light'); location.replace(u.href); return; }
  // Example clips: play while hovered; a click passes the clip's name to the hidden #example-pick textbox.
  document.addEventListener('mouseover', e => { const v = e.target.closest('.ex')?.querySelector('video');
    if (v && v.paused) v.play().catch(() => {}); });
  document.addEventListener('mouseout', e => { const b = e.target.closest('.ex');
    if (b && !b.contains(e.relatedTarget)) { const v = b.querySelector('video'); v.pause(); v.currentTime = 0; } });
  document.addEventListener('click', e => { const b = e.target.closest('.ex'); if (!b) return;
    document.querySelectorAll('.ex').forEach(x => x.classList.toggle('on', x === b));
    const box = document.querySelector('#example-pick textarea, #example-pick input');
    box.value = b.dataset.clip; box.dispatchEvent(new Event('input', { bubbles: true })); });
  // In a narrow window the viewer is as tall as its content: size its iframe to it.
  document.addEventListener('load', e => { const f = e.target;
    if (f.tagName !== 'IFRAME' || !f.closest('#viewer')) return;
    const fit = () => { if (innerWidth <= 900) f.style.height = f.contentDocument.documentElement.scrollHeight + 'px';
                        else f.style.height = ''; };
    new ResizeObserver(fit).observe(f.contentDocument.body); addEventListener('resize', fit); fit(); }, true);
}"""

def icon(paths: str) -> str:
    """A line icon in the text colour, as the project page's resource pills (globe, brackets, cube)."""
    return ('<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" '
            f'stroke-linejoin="round" aria-hidden="true">{paths}</svg>')


HEADER = f"""<div id="header"><div>
<h1>Flow<i>4RT</i>: <span>Seeing Motion through Geometry</span></h1>
</div><div class="links">
<a href="https://shenhanqian.github.io/flow4rt" target="_blank">{icon('<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/>')}Project page</a>
<a href="https://github.com/ShenhanQian/Flow4RT" target="_blank">{icon('<path d="M8 7l-5 5 5 5M16 7l5 5-5 5"/>')}Code</a>
<a href="https://huggingface.co/Shenhan/Flow4RT" target="_blank">{icon('<path d="M12 2l9 5v10l-9 5-9-5V7z"/><path d="M12 22V12M21 7l-9 5-9-5"/>')}Model</a>
</div></div>"""

EMPTY_PAGE = "empty_viewer.html"  # in OUTPUTS: the viewer without data, shown until the first result


def viewer_iframe(page: str) -> str:
    """The viewer in an iframe, with its Download button (?download)."""
    return f'<iframe src="/gradio_api/file={page}?download" allowfullscreen></iframe>'


def weights_path() -> str:
    if os.path.exists(WEIGHTS):
        return WEIGHTS
    from huggingface_hub import hf_hub_download
    return hf_hub_download("Shenhan/Flow4RT", "flow4rt.safetensors")


_model, _model_lock = None, threading.Lock()


def get_model():
    global _model
    with _model_lock:
        if _model is None:
            _model = load_model(weights_path(), device="cuda" if torch.cuda.is_available() else "cpu")
    return _model


@gpu
def infer(frames):
    model = get_model()
    pred = predict(model, frames_to_tensor(frames).to(next(model.parameters()).device))
    return {k: v.cpu().numpy() for k, v in pred.items()}


def example_list() -> str:
    """The example clips as muted videos, with their first frame as the poster."""
    os.makedirs(os.path.join(OUTPUTS, "thumbs"), exist_ok=True)
    items = []
    for clip in EXAMPLES:
        poster = os.path.join(OUTPUTS, "thumbs", f"{clip}.jpg")
        if not os.path.exists(poster):
            frame = read_frames(os.path.join(EXAMPLE_DIR, f"{clip}.mp4"), max_frames=1)[0]
            frame.thumbnail((480, 480))
            frame.save(poster, quality=85)
        items.append(f'<button class="ex" data-clip="{clip}" aria-label="{clip}"><video muted loop playsinline '
                     f'preload="none" poster="/gradio_api/file={poster}" '
                     f'src="/gradio_api/file={os.path.join(EXAMPLE_DIR, clip)}.mp4"></video></button>')
    return '<div class="ex-list">' + "".join(items) + "</div>"


def pick_example(clip):
    return os.path.join(EXAMPLE_DIR, f"{clip}.mp4") if clip in EXAMPLES else gr.skip()


def clean_old_results():
    for d in os.listdir(OUTPUTS):
        path = os.path.join(OUTPUTS, d)
        if d not in ("thumbs", EMPTY_PAGE) and time.time() - os.path.getmtime(path) > KEEP_HOURS * 3600:
            shutil.rmtree(path, ignore_errors=True)


def run(video, max_frames, stride, progress=gr.Progress()):
    if video is None:
        raise gr.Error("Upload a video or pick an example first.")
    t0 = time.time()
    progress(0.05, desc="Reading frames")
    frames = read_frames(video, max_frames=int(max_frames), stride=int(stride))
    if len(frames) < 2:
        raise gr.Error("The video needs at least two frames.")
    progress(0.15, desc=f"Running Flow4RT on {len(frames)} frames")
    t1 = time.time()
    pred = infer(frames)
    t2 = time.time()

    progress(0.75, desc="Building the viewer")
    clean_old_results()
    out = os.path.join(OUTPUTS, uuid.uuid4().hex)
    os.makedirs(out)
    name = re.sub(r"[^\w.-]+", "_", os.path.splitext(os.path.basename(video))[0])
    page = write_viewer(pred, os.path.join(out, f"flow4rt_{name}.html"), name, max_inline=float("inf"))
    print(f"{name}: {len(frames)} frames, read {t1 - t0:.1f} s, model {t2 - t1:.1f} s, viewer {time.time() - t2:.1f} s")
    return viewer_iframe(page)


os.makedirs(OUTPUTS, exist_ok=True)
empty_page = write_empty_viewer(os.path.join(OUTPUTS, EMPTY_PAGE), "Upload a video or pick an example, then press Run.")

with gr.Blocks(title="Flow4RT") as app:
    gr.HTML(HEADER)
    with gr.Row(elem_id="inputs", equal_height=True):
        with gr.Column(scale=4, min_width=260, elem_id="examples"):
            gr.HTML('<div class="card-title">Examples</div>' + example_list(), padding=False)
            pick = gr.Textbox(elem_id="example-pick", show_label=False, container=False)
        video = gr.Video(label="Video", sources=["upload"], height=380, scale=6, elem_id="video")
        with gr.Column(scale=3, min_width=260, elem_id="settings"):
            max_frames = gr.Slider(2, MAX_FRAMES, value=48, step=1, label="Frames", info="from the start of the video")
            stride = gr.Slider(1, 4, value=1, step=1, label="Frame stride", info="use every n-th frame")
            button = gr.Button("Run", variant="primary", size="lg", elem_id="run")
    viewer = gr.HTML(viewer_iframe(empty_page), elem_id="viewer", padding=False)
    pick.change(pick_example, pick, video)
    button.click(run, [video, max_frames, stride], viewer)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--host", default=os.environ.get("GRADIO_SERVER_NAME", "127.0.0.1"))
    parser.add_argument("--port", type=int, default=7860)
    parser.add_argument("--share", action="store_true", help="create a public gradio.live link")
    args = parser.parse_args()
    if os.environ.get("SPACE_ID"):
        get_model()  # ZeroGPU expects the model on "cuda" at startup, in the main process
    else:
        threading.Thread(target=get_model, daemon=True).start()  # load the weights while the page starts
    app.queue(default_concurrency_limit=1).launch(
        server_name=args.host, server_port=args.port, share=args.share, allowed_paths=[OUTPUTS, EXAMPLE_DIR],
        theme=THEME, css=CSS, js=JS, head=HEAD)