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"

Input video

{title}
" 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 = """

TransLayers

Video layered depth recovery in transparent scenes

""" 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("

Up to 50 MB. Inference uses the first 8 seconds at 16 fps.

") with gr.Column(scale=6, min_width=350, elem_id="tl-results"): gr.HTML("

Depth layers

") 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"
L{k} {name}
") panels.append(gr.Video(show_label=False, interactive=False, loop=True, elem_classes=["tl-depth"])) gr.HTML("""

Example videos

Select a scene to load its input and four recorded predictions.

Media credits ↗
""") 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)])