Spaces:
Running on Zero

TransLayers / app.py
little612pea's picture
Link the TransLayers arXiv paper
e2e6aab verified
Raw History Blame Contribute Delete
11.2 kB
import json
import os
import sys
import tempfile
from pathlib import Path
import av
import gradio as gr
import matplotlib
import numpy as np
import spaces
import torch
from huggingface_hub import hf_hub_download, snapshot_download
from huggingface_hub.constants import HF_HOME
from PIL import Image
ROOT = Path(__file__).parent
FPS, WINDOW, STRIDE = 16, 45, 36
MAX_FRAMES = 8 * FPS
W, H = 832, 480
def read_clip(path):
if not path:
raise gr.Error("Choose a video first.")
frames = []
try:
with av.open(path, options={"protocol_whitelist": "file", "format_whitelist": "mov,matroska,webm,avi"}) as video:
stream = video.streams.video[0]
if stream.width * stream.height > 4096 * 2160:
raise gr.Error("Use a video at 4K resolution or smaller.")
start = None
rate = float(stream.average_rate or FPS)
for i, frame in enumerate(video.decode(stream)):
timestamp = float(frame.time) if frame.time is not None else i / rate
if start is None:
start = timestamp
if timestamp - start + 0.00001 < len(frames) / FPS:
if i > 1200:
break
continue
image = frame.to_image().convert("RGB")
scale = min(W/image.width, H/image.height)
w, h = max(1, round(image.width*scale)), max(1, round(image.height*scale))
x, y = (W-w)//2, (H-h)//2
rgb = np.asarray(image.resize((w,h), Image.Resampling.LANCZOS))
canvas = np.pad(rgb, ((y,H-h-y),(x,W-w-x),(0,0)), mode="edge")
while len(frames) < MAX_FRAMES and len(frames)/FPS <= timestamp-start+0.00001:
frames.append(canvas)
if len(frames) == MAX_FRAMES:
break
except (av.error.FFmpegError, IndexError, ValueError) as exc:
raise gr.Error("Please upload a readable video file.") from exc
if not frames:
raise gr.Error("This file contains no readable video frames.")
count = len(frames)
frames.extend([frames[-1]]*max(0, WINDOW-count))
return np.stack(frames), count, (x,y,w,h)
def window_starts(length):
last = max(0, length - WINDOW)
starts = list(range(0, last + 1, STRIDE))
if starts[-1] != last:
starts.append(last)
return starts
def gpu_budget(frames, bundle, base, vae, destination):
return 50 + 20 * (len(window_starts(len(frames))) - 1)
@spaces.GPU(duration=gpu_budget)
def predict_clip(frames, bundle, base, vae, destination):
sys.path.insert(0, str(Path(bundle)/"engine"))
from predict import load_model, predict_window
model = load_model(Path(bundle)/"adapter.pt", Path(bundle)/"query.pt", base, vae)
result = np.lib.format.open_memmap(destination, mode="w+", dtype="float32",
shape=(4, len(frames), H, W))
previous_end = 0
for start in window_starts(len(frames)):
end = start + WINDOW
current = predict_window(frames[start:end], *model)
overlap = previous_end - start
if overlap > 0:
alpha = np.linspace(0, 1, overlap, dtype=np.float32)[None,:,None,None]
current[:,:overlap] = (1-alpha)*result[:,start:previous_end] + alpha*current[:,:overlap]
result[:,start:end] = current
previous_end = end
result.flush()
def write_video(colors, path):
with av.open(str(path), "w") as output:
stream = output.add_stream("libx264", rate=FPS)
h, w = colors.shape[1:3]
stream.width, stream.height = w+w%2, h+h%2
stream.pix_fmt = "yuv420p"
for rgb in colors:
padded = np.pad(rgb, ((0,h%2),(0,w%2),(0,0)), mode="edge")
for packet in stream.encode(av.VideoFrame.from_ndarray(padded, format="rgb24")):
output.mux(packet)
for packet in stream.encode():
output.mux(packet)
def recover(video, progress=gr.Progress()):
progress(0.05, desc="Reading video")
frames, count, (x,y,w,h) = read_clip(video)
progress(0.12, desc="Loading model")
bundle = snapshot_download("little612pea/TransLayers-runtime", revision=(ROOT/"runtime-revision.txt").read_text().strip(), token=os.environ["MODEL_ACCESS"])
base = hf_hub_download("FayeHongfeiZhang/DVD", "dvd_1.1.safetensors", revision="769534dec2d77f8da3667719568fbe57fe69cd9b", token=False)
vae = hf_hub_download("Wan-AI/Wan2.1-T2V-1.3B", "Wan2.1_VAE.pth", revision="37ec512624d61f7aa208f7ea8140a131f93afc9a", token=False)
progress(0.30, desc="Predicting four depth layers")
outputs = []
with tempfile.TemporaryDirectory() as tmp:
output = str(Path(tmp)/"depth.npy")
predict_clip(frames, bundle, base, vae, output)
values = np.load(output, mmap_mode="r")[:,:count,y:y+h,x:x+w]
progress(0.85, desc="Encoding depth videos")
lo, hi = np.percentile(values, (2,98))
lut = (matplotlib.colormaps["Spectral_r"](np.linspace(0,1,256))[:,:3]*255).round().astype(np.uint8)
for k, layer in zip((1,3,5,7), values):
ids = np.clip((layer-lo) / max(hi-lo,1e-8)*255,0,255).astype(np.uint8)
path = Path(tmp)/f"L{k}.mp4"
write_video(lut[ids], path)
outputs.append(gr.processing_utils.save_file_to_cache(str(path), cache_dir=demo.GRADIO_CACHE))
return tuple(outputs)
EXAMPLES = json.loads((ROOT/"examples.json").read_text())
LAYERS = [(1, "First surface"), (3, "Third surface"), (5, "Fifth surface"), (7, "Seventh surface")]
def example_media(example):
folder = ROOT/"examples"/example["folder"]
return [str(folder/"rgb.mp4"), *[str(folder/f"ours_{k}.mp4") for k, _ in LAYERS]]
def input_heading(title):
return f"<div class='tl-input-heading'><h2 class='tl-heading'>Input video</h2><span>{title}</span></div>"
def select_example(example):
def select():
return [*example_media(example), input_heading(example["title"]), gr.Button(interactive=True)]
return select
def reset_results(has_input):
return [None] * len(LAYERS) + [input_heading("Uploaded video" if has_input else ""),
gr.Button(interactive=has_input)]
header = """
<header class="tl-hero">
<div class="tl-title"><span class="tl-mark" aria-hidden="true"><i></i><i></i><i></i><i></i></span><h1>TransLayers</h1></div>
<p>Video layered depth recovery in transparent scenes</p>
<nav aria-label="Project links">
<a href="https://little612pea.github.io/TransLayers/" target="_blank" rel="noopener"><span class="tl-mini-mark tl-mark" aria-hidden="true"><i></i><i></i><i></i><i></i></span>Project page</a>
<a href="https://github.com/little612pea/TransLayers" target="_blank" rel="noopener"><svg viewBox="0 0 24 24" aria-hidden="true" fill="currentColor"><path d="M12 .3a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.24c-3.34.73-4.04-1.42-4.04-1.42-.55-1.39-1.34-1.76-1.34-1.76-1.09-.75.08-.73.08-.73 1.2.09 1.83 1.24 1.83 1.24 1.07 1.83 2.81 1.3 3.49.99.11-.78.42-1.3.76-1.6-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.12-3.18 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.29-1.55 3.3-1.23 3.3-1.23.66 1.66.25 2.88.12 3.18.77.84 1.24 1.91 1.24 3.22 0 4.61-2.81 5.63-5.49 5.93.43.37.82 1.1.82 2.22v3.3c0 .32.22.69.83.57A12 12 0 0 0 12 .3Z"/></svg>GitHub</a>
<a href="https://huggingface.co/datasets/little612pea/Translayers-vid-Preview" target="_blank" rel="noopener"><span class="tl-hug" aria-hidden="true">🤗</span>Dataset</a>
<a href="https://arxiv.org/pdf/2612.01792" title="Read the paper on arXiv" target="_blank" rel="noopener"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none"><path d="M5 2h10l5 5v15H5z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/><path d="M15 2v5h5" stroke="currentColor"/><rect x="1" y="10" width="21" height="10" rx="2" fill="#b42318"/><path d="M4 17.5v-5h2a1.35 1.35 0 0 1 0 2.7H4m5.5 2.3v-5h1.1a2.5 2.5 0 0 1 0 5zm6.1 0v-5H19m-3.4 2.4h2.6" stroke="#fff" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round"/></svg>Paper</a>
</nav>
</header>
"""
theme = gr.themes.Base(primary_hue=gr.themes.colors.blue, neutral_hue=gr.themes.colors.slate,
font=["Inter", "Arial", "sans-serif"])
with gr.Blocks(title="TransLayers", theme=theme, css=(ROOT/"style.css").read_text(),
js=(ROOT/"video-upload.js").read_text(), delete_cache=(3600,3600)) as demo:
gr.HTML(header)
with gr.Row(elem_id="tl-workspace", equal_height=False):
with gr.Column(scale=4, min_width=260, elem_id="tl-input"):
heading = gr.HTML(input_heading(""))
clip = gr.Video(sources=["upload"], show_label=False, interactive=True, include_audio=False,
loop=True, show_download_button=False, elem_id="tl-rgb")
with gr.Row(elem_id="tl-actions"):
run = gr.Button("Predict layers", variant="primary", size="sm", interactive=False)
gr.HTML("<p class='tl-note'>Up to 50 MB. Inference uses the first 8 seconds at 16 fps.</p>")
with gr.Column(scale=6, min_width=350, elem_id="tl-results"):
gr.HTML("<h2 class='tl-heading'>Depth layers</h2>")
panels = []
for start in (0,2):
with gr.Row(elem_classes=["tl-pair"]):
for index in range(start,start+2):
k, name = LAYERS[index]
with gr.Column(min_width=0, elem_classes=["tl-layer"]):
gr.HTML(f"<div class='tl-label l{k}'><b>L{k}</b> {name}</div>")
panels.append(gr.Video(show_label=False, interactive=False,
loop=True, elem_classes=["tl-depth"]))
gr.HTML("""<div class="tl-examples-intro"><div><h2 class="tl-heading">Example videos</h2>
<p>Select a scene to load its input and four recorded predictions.</p></div>
<a href="https://little612pea.github.io/TransLayers/media-credits.html" target="_blank" rel="noopener">Media credits ↗</a></div>""")
with gr.Row(elem_id="tl-gallery"):
for example in EXAMPLES:
tile = gr.Button(example["title"], icon=str(ROOT/"examples"/example["folder"]/"rgb.jpg"),
elem_classes=["tl-tile"], min_width=0)
tile.click(select_example(example), outputs=[clip,*panels,heading,run], api_name=False,
queue=False, show_progress="minimal")
clip.upload(lambda: reset_results(True), outputs=[*panels,heading,run], api_name=False,
concurrency_id="video-workspace", show_progress="hidden")
clip.clear(lambda: reset_results(False), outputs=[*panels,heading,run], api_name=False,
concurrency_id="video-workspace", show_progress="hidden")
run.click(recover, inputs=clip, outputs=panels, api_name="predict", concurrency_limit=1,
concurrency_id="video-workspace")
demo.queue(max_size=8).launch(ssr_mode=False, max_file_size="50mb", blocked_paths=[str(HF_HOME)])