Spaces:
Running on Zero
Running on Zero
File size: 10,922 Bytes
bd5ba20 503bbda bd5ba20 503bbda bd5ba20 503bbda bd5ba20 503bbda bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 9c00052 bd5ba20 503bbda 9c00052 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 207 208 209 210 211 212 213 214 215 | """Video spotlight with FlashReFocus for the Hugging Face Space (ZeroGPU), on the flashrefocus package (a copy of the
repository's).
One subject stays sharp and everyone else is blurred, frame by frame: SAM 3 tracks every instance of a text prompt
("person"), one track is chosen as the subject, Depth Anything V2 estimates each frame's depth (smoothed over time),
the depth is edited with depth_edits.spotlight (the subject on the focal plane, everything else at least `gap` away
from it) and the renderer renders the frame. Video frames are already sharp, so Stage I (restoration) is not loaded.
ZeroGPU gives a GPU only inside @spaces.GPU calls: the models are built on the CPU and moved to `cuda` at import time;
frames and masks stay on the CPU between calls. The renderer runs its attention as the fused Triton kernel of
flashrefocus/rendering/fused.py, with a fallback to the reference attention. The renderer weights come from a private
model repository and SAM 3 is gated: both are read with the HF_TOKEN secret."""
import functools
import json
import os
import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import numpy as np
import torch
from huggingface_hub import hf_hub_download
HERE = Path(__file__).resolve().parent
WEIGHT_REPO = os.environ.get("FLASHREFOCUS_WEIGHT_REPO", "ming0531/FlashReFocus-weights")
def fetch_weights():
"""Depth Anything V2 and the renderer into ./weights (skipped when FLASHREFOCUS_WEIGHTS points to a local copy)."""
if "FLASHREFOCUS_WEIGHTS" in os.environ:
return
w = HERE / "weights"
hf_hub_download("depth-anything/Depth-Anything-V2-Large", "depth_anything_v2_vitl.pth", local_dir=w)
hf_hub_download(WEIGHT_REPO, "renderer.pt", local_dir=w, token=os.environ.get("HF_TOKEN"))
os.environ["FLASHREFOCUS_WEIGHTS"] = str(w)
fetch_weights()
# Triton keeps the fused kernel's autotuning result in memory only; cache it on disk for new worker processes.
os.environ.setdefault("TRITON_CACHE_AUTOTUNING", "1")
from transformers import Sam3VideoModel, Sam3VideoProcessor # noqa: E402
from flashrefocus import Refocuser, Scene, paths, segment # noqa: E402
from flashrefocus.image_io import image_to_tensor # noqa: E402
from flashrefocus.rendering import DepthEstimator, depth_edits, load_renderer # noqa: E402
from flashrefocus.rendering.fused import enable_fused # noqa: E402
from flashrefocus.video import ffmpeg_exe # noqa: E402
# Depth Anything V2 at its native 518 on the short side: the frames here are at most 960 px wide, and the 1024 used for
# photographs would upsample them (4.5x slower per frame for no added detail).
refocuser = Refocuser(None, DepthEstimator.from_pretrained(device="cpu", input_size=518).to("cuda"),
enable_fused(load_renderer(paths.RENDERER, "cpu")).to("cuda"))
segment._SAM3[("cuda", torch.bfloat16)] = ( # track_subject finds the model here
Sam3VideoModel.from_pretrained("facebook/sam3", token=os.environ.get("HF_TOKEN"), dtype=torch.bfloat16).to("cuda").eval(),
Sam3VideoProcessor.from_pretrained("facebook/sam3", token=os.environ.get("HF_TOKEN")))
FFMPEG = ffmpeg_exe()
_GPU_THREAD = None
def on_gpu_thread(fn):
"""Run fn on one long-lived thread of the GPU worker process. Measured on ZeroGPU: in the thread of each @spaces.GPU
call, the first run at every tensor shape costs ~0.5 s again in every call; on a persistent thread that set-up is
paid once. The thread is created inside the first GPU call (the main process has no GPU)."""
@functools.wraps(fn)
def wrapper(*args, **kwargs):
global _GPU_THREAD
if _GPU_THREAD is None:
_GPU_THREAD = ThreadPoolExecutor(max_workers=1, thread_name_prefix="flashrefocus-gpu")
return _GPU_THREAD.submit(fn, *args, **kwargs).result()
return wrapper
def probe(path):
"""(width, height, fps, duration) of a video as displayed (ffmpeg applies the rotation tag)."""
import imageio_ffmpeg
reader = imageio_ffmpeg.read_frames(str(path))
meta = next(reader)
reader.close()
w, h = first_frame(path).size
return w, h, float(meta.get("fps") or 30.0), float(meta.get("duration") or 0.0)
def first_frame(path):
"""The first frame as an RGB PIL image, as displayed."""
import io
from PIL import Image
png = subprocess.run([FFMPEG, "-v", "error", "-i", str(path), "-frames:v", "1", "-f", "image2pipe", "-c:v", "png",
"-"], capture_output=True, check=True).stdout
return Image.open(io.BytesIO(png)).convert("RGB")
def read_clip(path, seconds, long_side, max_fps=30.0, start=0.0):
"""The first `seconds` of a video (from `start`) as (n, h, w, 3) uint8, long side at most `long_side`, both sides
multiples of 16, at most `max_fps` frames per second. Returns the frames and the frame rate."""
w, h, fps, _ = probe(path)
s = min(1.0, long_side / max(w, h))
w2, h2 = max(16, int(w * s) // 16 * 16), max(16, int(h * s) // 16 * 16)
fps2 = min(fps, max_fps)
cmd = [FFMPEG, "-v", "error", "-ss", f"{start:.3f}", "-t", f"{seconds:.3f}", "-i", str(path),
"-vf", f"fps={fps2:.6f},scale={w2}:{h2}:flags=lanczos", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
raw = subprocess.run(cmd, capture_output=True, check=True).stdout
frames = np.frombuffer(bytearray(raw), np.uint8).reshape(-1, h2, w2, 3) # writable, for torch.from_numpy
return frames, fps2
def cut_audio(path, seconds, out, start=0.0):
"""The audio of the same span as a separate file (None if the video has no audio)."""
r = subprocess.run([FFMPEG, "-v", "error", "-y", "-ss", f"{start:.3f}", "-t", f"{seconds:.3f}", "-i", str(path),
"-vn", "-c:a", "aac", "-b:a", "160k", str(out)], capture_output=True)
return out if r.returncode == 0 and Path(out).exists() and Path(out).stat().st_size > 0 else None
@torch.no_grad()
def track(frames, prompt="person", point=None):
"""SAM 3 subject and other-people masks, (n, h, w) bool each. point: (x, y) fractions of the first frame (the
track under it), or None for the most central person."""
select = "point" if point is not None else "most_central"
subject, others = segment.track_subject(frames, prompt=prompt or "person", select=select,
point=point or (0.5, 0.5), device="cuda", dtype=torch.bfloat16)
return subject.numpy(), others.numpy()
def _fallback(fn):
"""Run fn(); if the fused Triton kernel fails to build here, switch the renderer back to the reference attention."""
try:
return fn()
except Exception as e:
if not any("forward" in vars(m) for m in refocuser.renderer.modules()):
raise
print(f"fused attention unavailable ({type(e).__name__}: {e}); using the reference attention")
for m in refocuser.renderer.modules():
vars(m).pop("forward", None)
return fn()
@torch.no_grad()
def depth_batch(images):
"""Depth Anything V2 on a batch (b, 3, H, W) in [0, 1] -> D (b, H, W), each frame normalised on its own, as
DepthEstimator does for one image."""
import torch.nn.functional as F
from flashrefocus.rendering.depth import disparity_to_depth
de = refocuser.depth_estimator
h, w = images.shape[-2:]
x = F.interpolate(images, de._network_size(h, w), mode="bicubic", align_corners=False)
x = (x - de.mean.to(x)) / de.std.to(x)
with torch.autocast("cuda", dtype=torch.float16):
disparity = de.model(x)
disparity = F.interpolate(disparity[:, None].float(), (h, w), mode="bilinear", align_corners=True)[:, 0]
return torch.stack([disparity_to_depth(d) for d in disparity])
@torch.no_grad()
def spotlight(frames, subject, others, strength=1.5, gap=0.6, grow=10, depth_smoothing=0.7, focus_smoothing=0.6,
batch=8):
"""Spotlight video (n, h, w, 3) uint8 and the edited depth of the first frame (h, w; 1 = far).
Depth is smoothed over frames with an exponential moving average (depth_smoothing), the focal depth is the median
depth inside the subject mask (smoothed with focus_smoothing), and frames where the subject is missing are
rendered with their own depth and the last focal depth. Depth estimation and rendering run `batch` frames at a
time; the result is the same as frame by frame."""
out = np.empty_like(frames)
prev, d_f, first_depth = None, None, None
for s in range(0, len(frames), batch):
images = torch.from_numpy(frames[s:s + batch]).cuda().permute(0, 3, 1, 2).float().div(255)
depths = depth_batch(images)
masks = torch.from_numpy(subject[s:s + batch]).cuda()
other = torch.from_numpy(others[s:s + batch]).cuda()
scene_depths, edited, focal = [], [], []
for k in range(len(images)):
prev = depths[k:k + 1] if prev is None or depth_smoothing <= 0 else \
depth_smoothing * prev + (1 - depth_smoothing) * depths[k:k + 1]
m = masks[k]
present = int(m.sum()) > 50
target = float(prev[0][m].median()) if present else (d_f if d_f is not None else float(prev.median()))
d_f = target if d_f is None or focus_smoothing <= 0 else focus_smoothing * d_f + (1 - focus_smoothing) * target
e = depth_edits.spotlight(prev, m[None], d_f, gap, others=other[k][None], grow=grow)[0] if present else prev
scene_depths.append(prev)
edited.append(e)
focal.append(d_f)
if first_depth is None:
first_depth = e[0].float().cpu().numpy()
y = _fallback(lambda: refocuser.render_batch(images, torch.cat(edited), strength, focal))
out[s:s + len(images)] = (y.clamp(0, 1) * 255).round().byte().permute(0, 2, 3, 1).cpu().numpy()
return out, first_depth
@on_gpu_thread
@torch.no_grad()
def process(frames, prompt="person", point=None, strength=1.5, gap=0.6):
"""Tracking and rendering in one call (one GPU allocation on ZeroGPU). Returns the subject masks, the spotlight
video, the edited depth of the first frame and the two timings."""
import time
t0 = time.perf_counter()
subject, others = track(frames, prompt, point)
t1 = time.perf_counter()
if not subject.reshape(len(subject), -1).any():
return subject, None, None, t1 - t0, 0.0
out, depth = spotlight(frames, subject, others, strength=strength, gap=gap)
torch.cuda.synchronize()
return subject, out, depth, t1 - t0, time.perf_counter() - t1
def write_video(frames, fps, path, audio=None):
"""H.264 (yuv420p, plays in browsers) with the audio track, if any."""
from flashrefocus.video import VideoWriter
with VideoWriter(path, fps=fps, quality=18, audio_from=audio) as writer:
writer.write(frames)
return path
if __name__ == "__main__":
print(json.dumps({"ffmpeg": FFMPEG}))
|