Spaces:
Running on Zero
Running on Zero
One GPU call per clip; depth and rendering in batches of 8 frames
Browse files
app.py
CHANGED
|
@@ -20,26 +20,13 @@ MAX_SECONDS = 5.0
|
|
| 20 |
GREEN = np.array([72, 164, 63], np.float32)
|
| 21 |
|
| 22 |
|
| 23 |
-
def
|
| 24 |
-
return int(min(120,
|
| 25 |
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
@spaces.GPU(duration=_track_seconds)
|
| 32 |
-
def gpu_track(frames, prompt, point):
|
| 33 |
-
t0 = time.perf_counter()
|
| 34 |
-
subject, others = engine.track(frames, prompt, point)
|
| 35 |
-
return subject, others, time.perf_counter() - t0
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
@spaces.GPU(duration=_render_seconds)
|
| 39 |
-
def gpu_spotlight(frames, subject, others, strength, gap):
|
| 40 |
-
t0 = time.perf_counter()
|
| 41 |
-
out, depth = engine.spotlight(frames, subject, others, strength=strength, gap=gap)
|
| 42 |
-
return out, depth, time.perf_counter() - t0
|
| 43 |
|
| 44 |
|
| 45 |
def mark(image, point):
|
|
@@ -101,14 +88,12 @@ def run(state, prompt, start, seconds, long_side, strength, gap, progress=gr.Pro
|
|
| 101 |
frames, fps = engine.read_clip(state["video"], seconds, int(long_side), start=start)
|
| 102 |
if len(frames) == 0:
|
| 103 |
raise gr.Error("No frames in this part of the clip.")
|
| 104 |
-
progress(0.15, desc=f"Tracking '{prompt or 'person'}' with SAM 3
|
| 105 |
point = state.get("point") if start == 0 else None
|
| 106 |
-
subject,
|
| 107 |
found = subject.reshape(len(subject), -1).any(1)
|
| 108 |
-
if
|
| 109 |
raise gr.Error(f"SAM 3 found no '{prompt or 'person'}' to keep sharp in this clip.")
|
| 110 |
-
progress(0.55, desc="Depth, spotlight edit and rendering")
|
| 111 |
-
out, depth, t_render = gpu_spotlight(frames, subject, others, float(strength), float(gap))
|
| 112 |
progress(0.9, desc="Encoding")
|
| 113 |
tmp = Path(tempfile.mkdtemp())
|
| 114 |
audio = engine.cut_audio(state["video"], seconds, tmp / "audio.m4a", start=start)
|
|
|
|
| 20 |
GREEN = np.array([72, 164, 63], np.float32)
|
| 21 |
|
| 22 |
|
| 23 |
+
def _gpu_seconds(frames, *args): # ZeroGPU at 768 px: SAM 3 ~0.27 s per frame, depth + rendering ~0.1 s per
|
| 24 |
+
return int(min(120, 30 + 0.4 * len(frames))) # frame, plus ~10 s to build the Triton kernel once per container
|
| 25 |
|
| 26 |
|
| 27 |
+
@spaces.GPU(duration=_gpu_seconds)
|
| 28 |
+
def gpu_process(frames, prompt, point, strength, gap):
|
| 29 |
+
return engine.process(frames, prompt, point, strength, gap)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
def mark(image, point):
|
|
|
|
| 88 |
frames, fps = engine.read_clip(state["video"], seconds, int(long_side), start=start)
|
| 89 |
if len(frames) == 0:
|
| 90 |
raise gr.Error("No frames in this part of the clip.")
|
| 91 |
+
progress(0.15, desc=f"Tracking '{prompt or 'person'}' with SAM 3 and rendering {len(frames)} frames")
|
| 92 |
point = state.get("point") if start == 0 else None
|
| 93 |
+
subject, out, depth, t_track, t_render = gpu_process(frames, prompt or "person", point, float(strength), float(gap))
|
| 94 |
found = subject.reshape(len(subject), -1).any(1)
|
| 95 |
+
if out is None:
|
| 96 |
raise gr.Error(f"SAM 3 found no '{prompt or 'person'}' to keep sharp in this clip.")
|
|
|
|
|
|
|
| 97 |
progress(0.9, desc="Encoding")
|
| 98 |
tmp = Path(tempfile.mkdtemp())
|
| 99 |
audio = engine.cut_audio(state["video"], seconds, tmp / "audio.m4a", start=start)
|
engine.py
CHANGED
|
@@ -82,7 +82,7 @@ def read_clip(path, seconds, long_side, max_fps=30.0, start=0.0):
|
|
| 82 |
cmd = [FFMPEG, "-v", "error", "-ss", f"{start:.3f}", "-t", f"{seconds:.3f}", "-i", str(path),
|
| 83 |
"-vf", f"fps={fps2:.6f},scale={w2}:{h2}:flags=lanczos", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
|
| 84 |
raw = subprocess.run(cmd, capture_output=True, check=True).stdout
|
| 85 |
-
frames = np.frombuffer(raw, np.uint8).reshape(-1, h2, w2, 3)
|
| 86 |
return frames, fps2
|
| 87 |
|
| 88 |
|
|
@@ -103,47 +103,86 @@ def track(frames, prompt="person", point=None):
|
|
| 103 |
return subject.numpy(), others.numpy()
|
| 104 |
|
| 105 |
|
| 106 |
-
def
|
|
|
|
| 107 |
try:
|
| 108 |
-
return
|
| 109 |
-
except Exception as e:
|
| 110 |
if not any("forward" in vars(m) for m in refocuser.renderer.modules()):
|
| 111 |
raise
|
| 112 |
print(f"fused attention unavailable ({type(e).__name__}: {e}); using the reference attention")
|
| 113 |
for m in refocuser.renderer.modules():
|
| 114 |
vars(m).pop("forward", None)
|
| 115 |
-
return
|
| 116 |
|
| 117 |
|
| 118 |
@torch.no_grad()
|
| 119 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
"""Spotlight video (n, h, w, 3) uint8 and the edited depth of the first frame (h, w; 1 = far).
|
| 121 |
|
| 122 |
Depth is smoothed over frames with an exponential moving average (depth_smoothing), the focal depth is the median
|
| 123 |
depth inside the subject mask (smoothed with focus_smoothing), and frames where the subject is missing are
|
| 124 |
-
rendered with their own depth and the last focal depth.
|
|
|
|
| 125 |
out = np.empty_like(frames)
|
| 126 |
prev, d_f, first_depth = None, None, None
|
| 127 |
-
for
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
return out, first_depth
|
| 145 |
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
def write_video(frames, fps, path, audio=None):
|
| 148 |
"""H.264 (yuv420p, plays in browsers) with the audio track, if any."""
|
| 149 |
from flashrefocus.video import VideoWriter
|
|
|
|
| 82 |
cmd = [FFMPEG, "-v", "error", "-ss", f"{start:.3f}", "-t", f"{seconds:.3f}", "-i", str(path),
|
| 83 |
"-vf", f"fps={fps2:.6f},scale={w2}:{h2}:flags=lanczos", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
|
| 84 |
raw = subprocess.run(cmd, capture_output=True, check=True).stdout
|
| 85 |
+
frames = np.frombuffer(bytearray(raw), np.uint8).reshape(-1, h2, w2, 3) # writable, for torch.from_numpy
|
| 86 |
return frames, fps2
|
| 87 |
|
| 88 |
|
|
|
|
| 103 |
return subject.numpy(), others.numpy()
|
| 104 |
|
| 105 |
|
| 106 |
+
def _fallback(fn):
|
| 107 |
+
"""Run fn(); if the fused Triton kernel fails to build here, switch the renderer back to the reference attention."""
|
| 108 |
try:
|
| 109 |
+
return fn()
|
| 110 |
+
except Exception as e:
|
| 111 |
if not any("forward" in vars(m) for m in refocuser.renderer.modules()):
|
| 112 |
raise
|
| 113 |
print(f"fused attention unavailable ({type(e).__name__}: {e}); using the reference attention")
|
| 114 |
for m in refocuser.renderer.modules():
|
| 115 |
vars(m).pop("forward", None)
|
| 116 |
+
return fn()
|
| 117 |
|
| 118 |
|
| 119 |
@torch.no_grad()
|
| 120 |
+
def depth_batch(images):
|
| 121 |
+
"""Depth Anything V2 on a batch (b, 3, H, W) in [0, 1] -> D (b, H, W), each frame normalised on its own, as
|
| 122 |
+
DepthEstimator does for one image."""
|
| 123 |
+
import torch.nn.functional as F
|
| 124 |
+
|
| 125 |
+
from flashrefocus.rendering.depth import disparity_to_depth
|
| 126 |
+
de = refocuser.depth_estimator
|
| 127 |
+
h, w = images.shape[-2:]
|
| 128 |
+
x = F.interpolate(images, de._network_size(h, w), mode="bicubic", align_corners=False)
|
| 129 |
+
x = (x - de.mean.to(x)) / de.std.to(x)
|
| 130 |
+
with torch.autocast("cuda", dtype=torch.float16):
|
| 131 |
+
disparity = de.model(x)
|
| 132 |
+
disparity = F.interpolate(disparity[:, None].float(), (h, w), mode="bilinear", align_corners=True)[:, 0]
|
| 133 |
+
return torch.stack([disparity_to_depth(d) for d in disparity])
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@torch.no_grad()
|
| 137 |
+
def spotlight(frames, subject, others, strength=1.5, gap=0.6, grow=10, depth_smoothing=0.7, focus_smoothing=0.6,
|
| 138 |
+
batch=8):
|
| 139 |
"""Spotlight video (n, h, w, 3) uint8 and the edited depth of the first frame (h, w; 1 = far).
|
| 140 |
|
| 141 |
Depth is smoothed over frames with an exponential moving average (depth_smoothing), the focal depth is the median
|
| 142 |
depth inside the subject mask (smoothed with focus_smoothing), and frames where the subject is missing are
|
| 143 |
+
rendered with their own depth and the last focal depth. Depth estimation and rendering run `batch` frames at a
|
| 144 |
+
time; the result is the same as frame by frame."""
|
| 145 |
out = np.empty_like(frames)
|
| 146 |
prev, d_f, first_depth = None, None, None
|
| 147 |
+
for s in range(0, len(frames), batch):
|
| 148 |
+
images = torch.from_numpy(frames[s:s + batch]).cuda().permute(0, 3, 1, 2).float().div(255)
|
| 149 |
+
depths = depth_batch(images)
|
| 150 |
+
masks = torch.from_numpy(subject[s:s + batch]).cuda()
|
| 151 |
+
other = torch.from_numpy(others[s:s + batch]).cuda()
|
| 152 |
+
scene_depths, edited, focal = [], [], []
|
| 153 |
+
for k in range(len(images)):
|
| 154 |
+
prev = depths[k:k + 1] if prev is None or depth_smoothing <= 0 else \
|
| 155 |
+
depth_smoothing * prev + (1 - depth_smoothing) * depths[k:k + 1]
|
| 156 |
+
m = masks[k]
|
| 157 |
+
present = int(m.sum()) > 50
|
| 158 |
+
target = float(prev[0][m].median()) if present else (d_f if d_f is not None else float(prev.median()))
|
| 159 |
+
d_f = target if d_f is None or focus_smoothing <= 0 else focus_smoothing * d_f + (1 - focus_smoothing) * target
|
| 160 |
+
e = depth_edits.spotlight(prev, m[None], d_f, gap, others=other[k][None], grow=grow)[0] if present else prev
|
| 161 |
+
scene_depths.append(prev)
|
| 162 |
+
edited.append(e)
|
| 163 |
+
focal.append(d_f)
|
| 164 |
+
if first_depth is None:
|
| 165 |
+
first_depth = e[0].float().cpu().numpy()
|
| 166 |
+
y = _fallback(lambda: refocuser.render_batch(images, torch.cat(edited), strength, focal))
|
| 167 |
+
out[s:s + len(images)] = (y.clamp(0, 1) * 255).round().byte().permute(0, 2, 3, 1).cpu().numpy()
|
| 168 |
return out, first_depth
|
| 169 |
|
| 170 |
|
| 171 |
+
@torch.no_grad()
|
| 172 |
+
def process(frames, prompt="person", point=None, strength=1.5, gap=0.6):
|
| 173 |
+
"""Tracking and rendering in one call (one GPU allocation on ZeroGPU). Returns the subject masks, the spotlight
|
| 174 |
+
video, the edited depth of the first frame and the two timings."""
|
| 175 |
+
import time
|
| 176 |
+
t0 = time.perf_counter()
|
| 177 |
+
subject, others = track(frames, prompt, point)
|
| 178 |
+
t1 = time.perf_counter()
|
| 179 |
+
if not subject.reshape(len(subject), -1).any():
|
| 180 |
+
return subject, None, None, t1 - t0, 0.0
|
| 181 |
+
out, depth = spotlight(frames, subject, others, strength=strength, gap=gap)
|
| 182 |
+
torch.cuda.synchronize()
|
| 183 |
+
return subject, out, depth, t1 - t0, time.perf_counter() - t1
|
| 184 |
+
|
| 185 |
+
|
| 186 |
def write_video(frames, fps, path, audio=None):
|
| 187 |
"""H.264 (yuv420p, plays in browsers) with the audio track, if any."""
|
| 188 |
from flashrefocus.video import VideoWriter
|