Spaces:
Running on Zero

github-actions[bot] commited on
Commit
c6f49fe
·
1 Parent(s): 1e790a1

Sync from GitHub main@3bc6783

Browse files
Files changed (4) hide show
  1. app.py +12 -16
  2. viewer/template.html +28 -13
  3. viewer/viewer.js +6 -0
  4. visualize.py +19 -4
app.py CHANGED
@@ -19,7 +19,7 @@ import gradio as gr
19
  import torch
20
 
21
  from flow4rt.inference import frames_to_tensor, load_model, predict, read_frames
22
- from visualize import write_viewer
23
 
24
  try:
25
  import spaces # Hugging Face ZeroGPU
@@ -110,13 +110,6 @@ footer {{ display: none !important; }}
110
  #viewer, #viewer .html-container, #viewer .prose {{ padding: 0 !important; margin: 0 !important;
111
  overflow: visible !important; max-width: none !important; }}
112
  #viewer iframe {{ display: block; width: calc(100% + 32px); margin: 0 -16px; height: min(820px, 90vh); border: 0; }}
113
- .empty {{ height: 360px; display: flex; flex-direction: column; align-items: center;
114
- justify-content: center; gap: 4px; color: {SOFT}; text-align: center; padding: 0 24px;
115
- border: 1.5px dashed {LINE_STRONG}; border-radius: 14px; background: #fafbfd; }}
116
- .empty b {{ color: {INK}; font-size: 1.05rem; }}
117
- .empty .dots {{ display: flex; gap: 6px; margin-bottom: 10px; }}
118
- .empty .dots i {{ width: 8px; height: 8px; border-radius: 50%; background: {LINE_STRONG}; }}
119
- .empty .dots i:nth-child(2) {{ background: #bcd3f8; }} .empty .dots i:nth-child(3) {{ background: {ACCENT}; }}
120
  """
121
 
122
  # Narrow windows, in <head>: Gradio rewrites the selectors inside the @media rules of `css`.
@@ -162,9 +155,11 @@ HEADER = """<div id="header"><div>
162
  <a href="https://huggingface.co/Shenhan/Flow4RT" target="_blank">Model</a>
163
  </div></div>"""
164
 
165
- EMPTY = """<div class="empty"><div class="dots"><i></i><i></i><i></i></div>
166
- <b>The 4D viewer appears here</b>
167
- <span>Upload a video or pick an example, then press Run.</span></div>"""
 
 
168
 
169
 
170
  def weights_path() -> str:
@@ -215,7 +210,7 @@ def pick_example(clip):
215
  def clean_old_results():
216
  for d in os.listdir(OUTPUTS):
217
  path = os.path.join(OUTPUTS, d)
218
- if d != "thumbs" and time.time() - os.path.getmtime(path) > KEEP_HOURS * 3600:
219
  shutil.rmtree(path, ignore_errors=True)
220
 
221
 
@@ -239,9 +234,11 @@ def run(video, max_frames, stride, progress=gr.Progress()):
239
  name = re.sub(r"[^\w.-]+", "_", os.path.splitext(os.path.basename(video))[0])
240
  page = write_viewer(pred, os.path.join(out, f"flow4rt_{name}.html"), name, max_inline=float("inf"))
241
  print(f"{name}: {len(frames)} frames, read {t1 - t0:.1f} s, model {t2 - t1:.1f} s, viewer {time.time() - t2:.1f} s")
242
- iframe = f'<iframe src="/gradio_api/file={page}" allowfullscreen></iframe>'
243
- return iframe, gr.update(value=page, visible=True)
244
 
 
 
245
 
246
  with gr.Blocks(title="Flow4RT") as app:
247
  gr.HTML(HEADER)
@@ -255,7 +252,7 @@ with gr.Blocks(title="Flow4RT") as app:
255
  stride = gr.Slider(1, 4, value=1, step=1, label="Frame stride", info="use every n-th frame")
256
  button = gr.Button("Run", variant="primary", size="lg", elem_id="run")
257
  with gr.Column(elem_id="result"):
258
- viewer = gr.HTML(EMPTY, elem_id="viewer", padding=False)
259
  download = gr.DownloadButton("Download", visible=False, elem_id="download")
260
  pick.change(pick_example, pick, video)
261
  button.click(run, [video, max_frames, stride], [viewer, download])
@@ -267,7 +264,6 @@ if __name__ == "__main__":
267
  parser.add_argument("--port", type=int, default=7860)
268
  parser.add_argument("--share", action="store_true", help="create a public gradio.live link")
269
  args = parser.parse_args()
270
- os.makedirs(OUTPUTS, exist_ok=True)
271
  if os.environ.get("SPACE_ID"):
272
  get_model() # ZeroGPU expects the model on "cuda" at startup, in the main process
273
  else:
 
19
  import torch
20
 
21
  from flow4rt.inference import frames_to_tensor, load_model, predict, read_frames
22
+ from visualize import write_empty_viewer, write_viewer
23
 
24
  try:
25
  import spaces # Hugging Face ZeroGPU
 
110
  #viewer, #viewer .html-container, #viewer .prose {{ padding: 0 !important; margin: 0 !important;
111
  overflow: visible !important; max-width: none !important; }}
112
  #viewer iframe {{ display: block; width: calc(100% + 32px); margin: 0 -16px; height: min(820px, 90vh); border: 0; }}
 
 
 
 
 
 
 
113
  """
114
 
115
  # Narrow windows, in <head>: Gradio rewrites the selectors inside the @media rules of `css`.
 
155
  <a href="https://huggingface.co/Shenhan/Flow4RT" target="_blank">Model</a>
156
  </div></div>"""
157
 
158
+ EMPTY_PAGE = "empty_viewer.html" # in OUTPUTS: the viewer without data, shown until the first result
159
+
160
+
161
+ def viewer_iframe(page: str) -> str:
162
+ return f'<iframe src="/gradio_api/file={page}" allowfullscreen></iframe>'
163
 
164
 
165
  def weights_path() -> str:
 
210
  def clean_old_results():
211
  for d in os.listdir(OUTPUTS):
212
  path = os.path.join(OUTPUTS, d)
213
+ if d not in ("thumbs", EMPTY_PAGE) and time.time() - os.path.getmtime(path) > KEEP_HOURS * 3600:
214
  shutil.rmtree(path, ignore_errors=True)
215
 
216
 
 
234
  name = re.sub(r"[^\w.-]+", "_", os.path.splitext(os.path.basename(video))[0])
235
  page = write_viewer(pred, os.path.join(out, f"flow4rt_{name}.html"), name, max_inline=float("inf"))
236
  print(f"{name}: {len(frames)} frames, read {t1 - t0:.1f} s, model {t2 - t1:.1f} s, viewer {time.time() - t2:.1f} s")
237
+ return viewer_iframe(page), gr.update(value=page, visible=True)
238
+
239
 
240
+ os.makedirs(OUTPUTS, exist_ok=True)
241
+ empty_page = write_empty_viewer(os.path.join(OUTPUTS, EMPTY_PAGE), "Upload a video or pick an example, then press Run.")
242
 
243
  with gr.Blocks(title="Flow4RT") as app:
244
  gr.HTML(HEADER)
 
252
  stride = gr.Slider(1, 4, value=1, step=1, label="Frame stride", info="use every n-th frame")
253
  button = gr.Button("Run", variant="primary", size="lg", elem_id="run")
254
  with gr.Column(elem_id="result"):
255
+ viewer = gr.HTML(viewer_iframe(empty_page), elem_id="viewer", padding=False)
256
  download = gr.DownloadButton("Download", visible=False, elem_id="download")
257
  pick.change(pick_example, pick, video)
258
  button.click(run, [video, max_frames, stride], [viewer, download])
 
264
  parser.add_argument("--port", type=int, default=7860)
265
  parser.add_argument("--share", action="store_true", help="create a public gradio.live link")
266
  args = parser.parse_args()
 
267
  if os.environ.get("SPACE_ID"):
268
  get_model() # ZeroGPU expects the model on "cuda" at startup, in the main process
269
  else:
viewer/template.html CHANGED
@@ -54,16 +54,19 @@ input[type=range]::-moz-range-thumb { width: 10px; height: 10px; border-radius:
54
  .ctl > .lab { color: var(--text-soft); font-weight: 500; white-space: nowrap; }
55
  .ctl input[type=range] { width: 110px; }
56
  .ctl .val { min-width: 34px; color: var(--text-soft); font-variant-numeric: tabular-nums; }
57
- /* On / off options as chips. */
58
  .check { display: inline-flex; gap: 7px; align-items: center; height: var(--ctl-sm); padding: 0 13px 0 9px; border-radius: 999px;
59
- border: 1px solid var(--line-strong); background: #fff; color: var(--text-soft); font-size: .85rem; font-weight: 500;
60
  cursor: pointer; user-select: none; transition: background var(--ease), border-color var(--ease), color var(--ease); }
61
  .check:hover { color: var(--ink); }
62
  .check input { -webkit-appearance: none; appearance: none; flex: none; width: 14px; height: 14px; margin: 0; border-radius: 50%;
63
  border: 1.5px solid #b3bdcb; background: #fff center / 10px no-repeat; cursor: inherit; }
64
  .check input:checked { border-color: var(--accent); background-color: var(--accent);
65
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M2.5 6.2l2.4 2.4 4.6-5' fill='none' stroke='white' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); }
66
- .check:has(input:checked) { background: var(--accent-soft); border-color: #bcd3f8; color: var(--accent-ink); }
 
 
 
67
  .check.off { opacity: .4; cursor: not-allowed; }
68
 
69
  .viewer { display: grid; grid-template-columns: minmax(0, 1fr) 260px; gap: 18px; padding: 16px; height: 100vh; }
@@ -81,7 +84,9 @@ input[type=range]::-moz-range-thumb { width: 10px; height: 10px; border-radius:
81
  .timeline { display: flex; align-items: center; gap: 12px; margin-top: 12px; }
82
  .timeline input[type=range] { flex: 1; }
83
  .tlabel { min-width: 70px; text-align: right; font-size: .8rem; color: var(--text-soft); font-variant-numeric: tabular-nums; }
84
- .controls { display: flex; flex-wrap: wrap; gap: 12px 22px; align-items: center; margin-top: 14px; }
 
 
85
  .side { display: flex; flex-direction: column; gap: 12px; overflow-y: auto; }
86
  .side figure { margin: 0; }
87
  .side figcaption { font-size: .78rem; color: var(--text-soft); margin-bottom: 3px; }
@@ -90,10 +95,16 @@ input[type=range]::-moz-range-thumb { width: 10px; height: 10px; border-radius:
90
  .imgbox canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
91
  .scene-title { font-weight: 700; font-size: 1.05rem; color: var(--ink); }
92
  .scene-sub { color: var(--text-soft); font-size: .85rem; }
 
 
 
 
 
93
  @media (max-width: 900px) {
94
  .viewer { grid-template-columns: minmax(0, 1fr); height: auto; }
95
  .canvas-box { flex: none; aspect-ratio: 4 / 3; }
96
  .side { display: grid; grid-template-columns: 1fr 1fr; }
 
97
  }
98
  </style>
99
  </head>
@@ -111,15 +122,19 @@ input[type=range]::-moz-range-thumb { width: 10px; height: 10px; border-radius:
111
  <span class="tlabel"></span>
112
  </div>
113
  <div class="controls">
114
- <div class="seg seg-mode"><button data-v="track">Tracking</button><button data-v="recon">Reconstruction</button></div>
115
- <label class="ctl"><span class="lab">Confidence ≥</span><input type="range" id="opt-conf" min="0" max="90" step="5" value="20"><span class="val"></span></label>
116
- <label class="ctl"><span class="lab">Point size</span><input type="range" id="opt-size" min="0.3" max="2.5" step="0.05" value="1"></label>
117
- <button class="btn reset">Reset view</button>
118
- <label class="check"><input type="checkbox" id="opt-trails" checked> Tracks</label>
119
- <label class="check"><input type="checkbox" id="opt-moving" checked> Dynamic only</label>
120
- <label class="check"><input type="checkbox" id="opt-current" checked> Current frame</label>
121
- <label class="check"><input type="checkbox" id="opt-accum"> Accumulate frames</label>
122
- <label class="check"><input type="checkbox" id="opt-cams" checked> Cameras</label>
 
 
 
 
123
  </div>
124
  </div>
125
  <aside class="side">
 
54
  .ctl > .lab { color: var(--text-soft); font-weight: 500; white-space: nowrap; }
55
  .ctl input[type=range] { width: 110px; }
56
  .ctl .val { min-width: 34px; color: var(--text-soft); font-variant-numeric: tabular-nums; }
57
+ /* On / off options as chips, on the same soft track as the switches beside them (.seg); tinted blue when on. */
58
  .check { display: inline-flex; gap: 7px; align-items: center; height: var(--ctl-sm); padding: 0 13px 0 9px; border-radius: 999px;
59
+ border: 1px solid transparent; background: var(--track); color: var(--text-soft); font-size: .85rem; font-weight: 500;
60
  cursor: pointer; user-select: none; transition: background var(--ease), border-color var(--ease), color var(--ease); }
61
  .check:hover { color: var(--ink); }
62
  .check input { -webkit-appearance: none; appearance: none; flex: none; width: 14px; height: 14px; margin: 0; border-radius: 50%;
63
  border: 1.5px solid #b3bdcb; background: #fff center / 10px no-repeat; cursor: inherit; }
64
  .check input:checked { border-color: var(--accent); background-color: var(--accent);
65
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M2.5 6.2l2.4 2.4 4.6-5' fill='none' stroke='white' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); }
66
+ .check:has(input:checked) { background: var(--accent-soft); color: var(--accent-ink); }
67
+ /* Reset view: a plain action among them, in their colours. */
68
+ .controls .reset { background: var(--track); border-color: transparent; color: var(--text-soft); font-weight: 500; }
69
+ .controls .reset:hover { background: var(--accent-soft); border-color: transparent; color: var(--accent-ink); }
70
  .check.off { opacity: .4; cursor: not-allowed; }
71
 
72
  .viewer { display: grid; grid-template-columns: minmax(0, 1fr) 260px; gap: 18px; padding: 16px; height: 100vh; }
 
84
  .timeline { display: flex; align-items: center; gap: 12px; margin-top: 12px; }
85
  .timeline input[type=range] { flex: 1; }
86
  .tlabel { min-width: 70px; text-align: right; font-size: .8rem; color: var(--text-soft); font-variant-numeric: tabular-nums; }
87
+ .controls { display: flex; flex-direction: column; gap: 12px; margin-top: 14px; }
88
+ /* Two rows: the view's settings, then Reset view and the on / off options; each wraps in narrow windows. */
89
+ .controls .row { display: flex; flex-wrap: wrap; gap: 12px 22px; align-items: center; }
90
  .side { display: flex; flex-direction: column; gap: 12px; overflow-y: auto; }
91
  .side figure { margin: 0; }
92
  .side figcaption { font-size: .78rem; color: var(--text-soft); margin-bottom: 3px; }
 
95
  .imgbox canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
96
  .scene-title { font-weight: 700; font-size: 1.05rem; color: var(--ink); }
97
  .scene-sub { color: var(--text-soft); font-size: .85rem; }
98
+ /* Without data (the web demo before its first run): a blank canvas with a note, inert controls, empty frames. */
99
+ .no-data .overlay { background: transparent; color: var(--text-soft); font-weight: 500; }
100
+ .no-data .timeline, .no-data .controls { opacity: .5; pointer-events: none; }
101
+ .no-data .imgbox { aspect-ratio: 16 / 9; background: var(--track); border-color: transparent; }
102
+ .no-data .imgbox img, .no-data .hint, .no-data .side > div:first-child { display: none; }
103
  @media (max-width: 900px) {
104
  .viewer { grid-template-columns: minmax(0, 1fr); height: auto; }
105
  .canvas-box { flex: none; aspect-ratio: 4 / 3; }
106
  .side { display: grid; grid-template-columns: 1fr 1fr; }
107
+ .side > div:first-child { grid-column: 1 / -1; } /* the title above the two frames, side by side */
108
  }
109
  </style>
110
  </head>
 
122
  <span class="tlabel"></span>
123
  </div>
124
  <div class="controls">
125
+ <div class="row">
126
+ <div class="seg seg-mode"><button data-v="track">Tracking</button><button data-v="recon">Reconstruction</button></div>
127
+ <label class="ctl"><span class="lab">Confidence ≥</span><input type="range" id="opt-conf" min="0" max="90" step="5" value="20"><span class="val"></span></label>
128
+ <label class="ctl"><span class="lab">Point size</span><input type="range" id="opt-size" min="0.3" max="2.5" step="0.05" value="1"></label>
129
+ </div>
130
+ <div class="row">
131
+ <button class="btn reset">Reset view</button>
132
+ <label class="check"><input type="checkbox" id="opt-trails" checked> Tracks</label>
133
+ <label class="check"><input type="checkbox" id="opt-moving" checked> Dynamic only</label>
134
+ <label class="check"><input type="checkbox" id="opt-current" checked> Current frame</label>
135
+ <label class="check"><input type="checkbox" id="opt-accum"> Accumulate frames</label>
136
+ <label class="check"><input type="checkbox" id="opt-cams" checked> Cameras</label>
137
+ </div>
138
  </div>
139
  </div>
140
  <aside class="side">
viewer/viewer.js CHANGED
@@ -191,6 +191,12 @@
191
  overlay.textContent = 'This browser lacks DecompressionStream; please use a recent Chrome, Firefox, Safari or Edge.';
192
  return;
193
  }
 
 
 
 
 
 
194
  const { meta, recon, track, trails } = await decode(window.F4RT.parts);
195
  const T = meta.T;
196
  const opt = id => $('#opt-' + id);
 
191
  overlay.textContent = 'This browser lacks DecompressionStream; please use a recent Chrome, Firefox, Safari or Edge.';
192
  return;
193
  }
194
+ if (!window.F4RT.parts.length) { // a viewer without data (write_empty_viewer): a blank canvas with a note
195
+ document.body.classList.add('no-data');
196
+ overlay.textContent = window.F4RT.empty || 'No data';
197
+ $('.playbtn').innerHTML = ICON_PLAY;
198
+ return;
199
+ }
200
  const { meta, recon, track, trails } = await decode(window.F4RT.parts);
201
  const T = meta.T;
202
  const opt = id => $('#opt-' + id);
visualize.py CHANGED
@@ -190,6 +190,24 @@ def export(pred, args):
190
  return [meta, track] + recon
191
 
192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  def write_viewer(pred, out, name="", anchor=0, stride=2, track_grid=4, max_tracks=400, min_motion=0.3,
194
  max_dev=0.25, chunk=16, max_inline=MAX_INLINE) -> str:
195
  """Writes the viewer of the predictions to out; returns the path of the page (a folder's
@@ -197,10 +215,7 @@ def write_viewer(pred, out, name="", anchor=0, stride=2, track_grid=4, max_track
197
  args = argparse.Namespace(name=name, anchor=anchor, stride=stride, track_grid=track_grid, max_tracks=max_tracks,
198
  min_motion=min_motion, max_dev=max_dev, chunk=chunk)
199
  payloads = [f"F4RT.add({json.dumps(p, separators=(',', ':'))});\n" for p in export(pred, args)]
200
- read = lambda path: open(os.path.join(VIEWER, path)).read()
201
- scripts = "".join(f"<script>\n{read(os.path.join('vendor', f))}</script>\n" for f in VENDOR)
202
- scripts += f"<script>\n{read('viewer.js')}</script>\n"
203
- page = read("template.html").replace("{{TITLE}}", name)
204
 
205
  size = sum(map(len, payloads))
206
  if size <= max_inline:
 
190
  return [meta, track] + recon
191
 
192
 
193
+ def viewer_page(name=""):
194
+ """The viewer's page (with a {{SCRIPTS}} placeholder for the data) and its inlined scripts."""
195
+ read = lambda path: open(os.path.join(VIEWER, path)).read()
196
+ scripts = "".join(f"<script>\n{read(os.path.join('vendor', f))}</script>\n" for f in VENDOR)
197
+ scripts += f"<script>\n{read('viewer.js')}</script>\n"
198
+ return read("template.html").replace("{{TITLE}}", name), scripts
199
+
200
+
201
+ def write_empty_viewer(out, message="") -> str:
202
+ """Writes the viewer without data: a blank canvas showing the message and inert controls (the web demo
203
+ shows it until the first result). Returns out."""
204
+ page, scripts = viewer_page()
205
+ data = f"<script>F4RT.empty = {json.dumps(message)};</script>\n"
206
+ with open(out, "w") as f:
207
+ f.write(page.replace("{{SCRIPTS}}", data + scripts))
208
+ return out
209
+
210
+
211
  def write_viewer(pred, out, name="", anchor=0, stride=2, track_grid=4, max_tracks=400, min_motion=0.3,
212
  max_dev=0.25, chunk=16, max_inline=MAX_INLINE) -> str:
213
  """Writes the viewer of the predictions to out; returns the path of the page (a folder's
 
215
  args = argparse.Namespace(name=name, anchor=anchor, stride=stride, track_grid=track_grid, max_tracks=max_tracks,
216
  min_motion=min_motion, max_dev=max_dev, chunk=chunk)
217
  payloads = [f"F4RT.add({json.dumps(p, separators=(',', ':'))});\n" for p in export(pred, args)]
218
+ page, scripts = viewer_page(name)
 
 
 
219
 
220
  size = sum(map(len, payloads))
221
  if size <= max_inline: