Spaces:
Running on Zero
Running on Zero
File size: 11,159 Bytes
bd5ba20 9c46849 bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 2b2c2a2 bd5ba20 9c46849 bd5ba20 | 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 | """FlashReFocus video spotlight (Hugging Face Space, ZeroGPU).
1. Upload a short clip; its first frame is shown. Click the person to keep sharp (default: the most central person).
2. SAM 3 tracks every instance of the prompt ("person") and keeps the chosen track as the subject.
3. Every frame: Depth Anything V2 depth (smoothed over time), the spotlight depth edit (subject on the focal plane,
everything else at least `gap` away), and the FlashReFocus renderer. The audio of the clip is kept.
"""
import tempfile
import time
from pathlib import Path
import gradio as gr
import numpy as np
import spaces
from PIL import Image, ImageDraw
import engine
MAX_SECONDS = 5.0
EXAMPLES = ["examples/friends_street.mp4", "examples/three_friends.mp4", "examples/stage_dancers.mp4",
"examples/dance_troupe.mp4"]
GREEN = np.array([72, 164, 63], np.float32)
def _gpu_seconds(frames, *args): # ZeroGPU at 768 px: SAM 3 ~0.27 s per frame, depth + rendering ~0.1 s per
return int(min(120, 30 + 0.4 * len(frames))) # frame, plus ~10 s to build the Triton kernel once per container
@spaces.GPU(duration=_gpu_seconds)
def gpu_process(frames, prompt, point, strength, gap):
return engine.process(frames, prompt, point, strength, gap)
def mark(image, point):
"""The first frame with a ring at the clicked point."""
im = image.copy()
if point is not None:
d = ImageDraw.Draw(im)
x, y = point[0] * (im.width - 1), point[1] * (im.height - 1)
r = max(8, im.width // 60)
d.ellipse((x - r, y - r, x + r, y + r), outline=(255, 255, 255), width=max(3, r // 3))
d.ellipse((x - r // 3, y - r // 3, x + r // 3, y + r // 3), fill=(72, 164, 63))
return im
def overlay(frame, mask):
"""Frame with the subject mask in green."""
a = frame.astype(np.float32).copy()
a[mask] = 0.55 * a[mask] + 0.45 * GREEN
return Image.fromarray(a.astype(np.uint8))
def depth_image(depth):
return Image.fromarray((np.clip(1 - depth, 0, 1) * 255).astype(np.uint8)) # near is bright
def on_video(video):
if video is None:
return None, {"video": None, "point": None, "frame": None}, "Upload a clip first."
frame = engine.first_frame(video)
w, h, fps, dur = engine.probe(video)
state = {"video": video, "point": None, "frame": frame, "duration": dur}
msg = (f"Clip: {w}×{h}, {fps:.0f} fps, {dur:.1f} s. **Click the person to keep sharp** (otherwise the most central "
f"person is used), then press 🎬 Spotlight. At most {MAX_SECONDS:.0f} s are processed.")
return frame, state, msg
def on_click(state, evt: gr.SelectData):
if not state or state.get("frame") is None:
return None, state, "Upload a clip first."
frame = state["frame"]
x, y = evt.index
point = (x / max(1, frame.width - 1), y / max(1, frame.height - 1))
state = dict(state, point=point)
return mark(frame, point), state, f"Subject: the person at ({x}, {y}). Press 🎬 Spotlight."
def on_clear(state):
if not state or state.get("frame") is None:
return None, state, "Upload a clip first."
return state["frame"], dict(state, point=None), "Subject: the most central person. Press 🎬 Spotlight."
def run(state, prompt, start, seconds, long_side, strength, gap, progress=gr.Progress()):
if not state or state.get("video") is None:
raise gr.Error("Upload a clip first.")
start = max(0.0, min(float(start), max(0.0, state.get("duration", 0) - 0.5)))
seconds = min(float(seconds), MAX_SECONDS)
progress(0.05, desc="Reading frames")
frames, fps = engine.read_clip(state["video"], seconds, int(long_side), start=start)
if len(frames) == 0:
raise gr.Error("No frames in this part of the clip.")
progress(0.15, desc=f"Tracking '{prompt or 'person'}' with SAM 3 and rendering {len(frames)} frames")
point = state.get("point") if start == 0 else None
subject, out, depth, t_track, t_render = gpu_process(frames, prompt or "person", point, float(strength), float(gap))
found = subject.reshape(len(subject), -1).any(1)
if out is None:
raise gr.Error(f"SAM 3 found no '{prompt or 'person'}' to keep sharp in this clip.")
progress(0.9, desc="Encoding")
tmp = Path(tempfile.mkdtemp())
audio = engine.cut_audio(state["video"], seconds, tmp / "audio.m4a", start=start)
path = engine.write_video(out, fps, str(tmp / "spotlight.mp4"), audio)
first = int(np.argmax(found))
msg = (f"{len(frames)} frames at {frames.shape[2]}×{frames.shape[1]}: SAM 3 tracking {t_track:.1f} s, depth + "
f"spotlight + rendering {t_render:.1f} s ({1000 * t_render / len(frames):.0f} ms per frame). The subject was "
f"found in {found.mean():.0%} of the frames.")
return path, overlay(frames[first], subject[first]), depth_image(depth), msg
@spaces.GPU(duration=180)
def warm_up(frames):
"""Start-up run on the GPU worker: SAM 3, depth and the renderer once (the Triton kernel is built and tuned here),
so the first visitor does not wait for it."""
t0 = time.perf_counter()
engine.process(frames, "person", None, 1.5, 0.6)
print(f"warm-up done in {time.perf_counter() - t0:.1f} s", flush=True)
try:
for _side in (768, 512, 960): # the long sides offered, on a 16:9 example clip
warm_up(engine.read_clip(EXAMPLES[1], 0.5, _side)[0])
except Exception as e: # never block the start of the Space
print(f"warm-up skipped ({type(e).__name__}: {e})", flush=True)
HEADER = """
<div id="header">
<div class="title"><div><h1>FlashReFocus: Video Spotlight</h1><p>Keep one person sharp and blur everyone else, frame
by frame. SAM 3 tracks the people, Depth Anything V2 gives each frame's depth, and the FlashReFocus renderer renders
the edited depth.</p></div></div>
<div class="authors">Ching-Heng Cheng<sup>1*</sup> · <a href="https://ming053l.github.io/" target="_blank">Chia-Ming Lee</a><sup>2,3*</sup> ·
<a href="https://www.albany.edu/faculty/mchang2/" target="_blank">Ming-Ching Chang</a><sup>2</sup> ·
<a href="https://scholar.google.com/citations?user=gMBvzGoAAAAJ&hl=en" target="_blank">Xin Li</a><sup>2</sup> ·
<a href="https://cchsu.info/" target="_blank">Chih-Chung Hsu</a><sup>1,3†</sup><br>
<small><sup>1</sup>National Cheng Kung University · <sup>2</sup>State University of New York at Albany ·
<sup>3</sup>National Yang Ming Chiao Tung University · * equal contribution · † corresponding author</small></div>
<div class="links">
<a href="https://huggingface.co/spaces/ming0531/FlashReFocus" target="_blank">📷 Photo demo</a>
<a href="https://ming053l.github.io/FlashReFocus/" target="_blank">🌐 Project page</a>
<a href="https://ming053l.github.io/FlashReFocus/assets/FlashReFocus.pdf" target="_blank">📄 Paper</a>
<a href="https://github.com/ming053l/FlashReFocus" target="_blank">💻 Code</a>
</div>
<div class="tip">A single focal plane cannot do this when the people around the subject stand at nearly the same
depth: they would stay as sharp as the subject. The spotlight edit moves everyone but the subject away from the
focal plane in the depth map, so only the subject stays sharp. The renderer was trained on single photographs with
one focal plane; this use is zero-shot.</div>
</div>
"""
CSS = """
#header {margin-bottom: 4px}
#header .title {display: flex; align-items: center; justify-content: center; text-align: center}
#header h1 {margin: 0; font-size: 2.0em; color: #2E7D32}
#header .title p {margin: 4px 0 0; color: var(--body-text-color-subdued)}
#header .authors {text-align: center; margin-top: 10px; line-height: 1.6}
#header .authors a {color: #2E7D32; text-decoration: none; font-weight: 600}
#header .authors small {color: var(--body-text-color-subdued)}
#header .links {display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin: 12px 0}
#header .links a {padding: 5px 14px; border-radius: 999px; border: 1px solid #48A43F; color: #2E7D32;
text-decoration: none; font-weight: 600}
#header .links a:hover {background: #48A43F; color: white}
#header .tip {background: #f1f8ef; border-left: 4px solid #48A43F; padding: 10px 14px; border-radius: 8px;
color: #1f3d1f}
.step h3 {margin: 6px 0 2px; color: #2E7D32}
#status {background: #f1f8ef; border-left: 4px solid #48A43F; padding: 8px 14px; border-radius: 8px; min-height: 2.4em}
#status p {margin: 0; color: #1f3d1f}
"""
with gr.Blocks(title="FlashReFocus Video Spotlight", theme=gr.themes.Soft(primary_hue="green"), css=CSS) as demo:
gr.HTML(HEADER)
state = gr.State({"video": None, "point": None, "frame": None})
with gr.Row():
with gr.Column():
gr.Markdown("### ① Upload a short clip", elem_classes="step")
video = gr.Video(label="Input clip", sources=["upload"], height=300)
gr.Examples(EXAMPLES, inputs=video, label="Examples (5 s clips from Pexels)")
gr.Markdown("### ② Click the person to keep sharp", elem_classes="step")
first = gr.Image(label="First frame (click the subject)", type="pil", interactive=False, height=300)
with gr.Row():
prompt = gr.Textbox(value="person", label="What to track (SAM 3 text prompt)", scale=3)
clear = gr.Button("Use the most central", size="sm", scale=1)
with gr.Accordion("Settings", open=False):
start = gr.Number(value=0.0, minimum=0.0, label="Start at (seconds; a click is used only from 0 s)")
seconds = gr.Slider(1, MAX_SECONDS, value=3, step=0.5, label="Length (seconds)")
long_side = gr.Radio([512, 768, 960], value=768, label="Long side (pixels)")
strength = gr.Slider(0.5, 2.0, value=1.5, step=0.05, label="🔆 Blur strength K",
info="1: the widest aperture seen in training; above 1 extrapolates.")
gap = gr.Slider(0.2, 1.0, value=0.6, step=0.05, label="Depth gap",
info="How far everything but the subject is moved from the focal plane.")
btn = gr.Button("🎬 Spotlight", variant="primary", size="lg")
with gr.Column():
gr.Markdown("### ③ Result", elem_classes="step")
status = gr.Markdown("Upload a clip to start.", elem_id="status")
out = gr.Video(label="Spotlight result", height=360, autoplay=True)
with gr.Row():
subj = gr.Image(label="Tracked subject (green)", type="pil", interactive=False, height=180)
dep = gr.Image(label="Edited depth, first frame (near is bright)", type="pil", interactive=False,
height=180)
video.change(on_video, [video], [first, state, status])
first.select(on_click, [state], [first, state, status])
clear.click(on_clear, [state], [first, state, status])
btn.click(run, [state, prompt, start, seconds, long_side, strength, gap], [out, subj, dep, status])
if __name__ == "__main__":
demo.queue(max_size=10).launch(show_api=False)
|