"""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 = """
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.