Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/depthpro2-l: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/spaces/hugging-apps/depthpro2-l/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/depthpro2-l/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/depthpro2-l/resolve/main/app.py
17.7 kB
| """Gradio demo for apple/DepthPro2-L β metric monocular depth for photos and videos. | |
| Depth Pro 2 (arXiv:2611.26603) predicts sharp metric depth in meters for every pixel of a | |
| single photo, and steady depth across the frames of a video. This Space runs the L variant | |
| (334M parameters) with its focal-length estimator (apple/DepthPro2-focal), so photos without | |
| EXIF focal data still come out in meters. | |
| """ | |
| import spaces # ZeroGPU: must be imported before torch. | |
| import time | |
| from fractions import Fraction | |
| from functools import partial | |
| from pathlib import Path | |
| import av | |
| import gradio as gr | |
| import numpy as np | |
| import torch | |
| from matplotlib import colormaps | |
| from PIL import Image | |
| from depth_pro_2 import DepthPro2, load_rgb, upright | |
| from depth_pro_2.model import to_normalized_tensor | |
| from depth_pro_2.network.fov import FOVEstimator | |
| from huggingface_hub import hf_hub_download | |
| from safetensors.torch import load_file | |
| # Inputs are downscaled first: the model card reports ~21.7 GiB peak VRAM for a 1080p 32-frame | |
| # clip on a B200, and ZeroGPU's default slice gives 48 GB β a still image at 1536 px and a | |
| # 64-frame clip at 960 px stay comfortably inside while running in seconds. | |
| MAX_IMAGE_SIDE = 1536 | |
| MAX_VIDEO_SIDE = 960 | |
| MAX_VIDEO_FRAMES = 64 | |
| ASSETS = Path(__file__).resolve().parent / "assets" | |
| # Weights are created from the Hub and placed on CUDA at module scope, as ZeroGPU's docs | |
| # direct: the placement is hijacked, packed to disk, and streamed into VRAM on the first | |
| # @spaces.GPU call; a lazy .to("cuda") inside a handler would pay that cost on every request. | |
| # bfloat16 is how Apple trains and evaluates the model. The L config ships "fov": false, so | |
| # the focal-length estimator is attached from its own repo, apple/DepthPro2-focal. | |
| model = DepthPro2.from_pretrained("apple/DepthPro2-L", precision=torch.bfloat16) | |
| model.fov = FOVEstimator(precision=torch.bfloat16) | |
| model.fov.load_state_dict( | |
| load_file(hf_hub_download("apple/DepthPro2-focal", "model.safetensors")) | |
| ) | |
| model = model.eval().to("cuda") | |
| # From an RGB uint8 (H, W, 3) array to a normalized (3, H, W) CUDA tensor. | |
| transform = partial(to_normalized_tensor, device=torch.device("cuda")) | |
| # Output rendering, 1:1 with depth_pro_2.cli: inverse metric depth (1/m, zero at sky) drives a | |
| # 256-entry Turbo LUT with 20% headroom above the nearest point; the 16-bit PNG is inverse | |
| # depth on the same scale (white = near, black = infinitely far); the NPZ holds meters and | |
| # the focal length. depth_meters = f_px / (width * inverse_depth), infinite at sky. | |
| COLOR_LUT = (colormaps["turbo"](np.linspace(0, 1, 256))[:, :3] * 255).astype(np.uint8) | |
| COLOR_HEADROOM = 0.2 | |
| FRAGMENTED_MP4 = "frag_keyframe+empty_moov+default_base_moof" | |
| def inverse_metric_depth(prediction) -> np.ndarray: | |
| """1/depth in 1/m as a float32 host array, zero where infinitely far (cli.inverse_metric_depth).""" | |
| inv = prediction["inverse_depth"].float().cpu().numpy() | |
| return inv * (inv.shape[-1] / float(prediction["focallength_px"])) | |
| def color_scale(inv: np.ndarray) -> float: | |
| """The inverse depth mapped to the top of the color map (cli.color_scale).""" | |
| high = float(inv.max()) | |
| return high * (1.0 + COLOR_HEADROOM) if high > 0 else 1.0 | |
| def colorize(inv: np.ndarray, scale: float) -> np.ndarray: | |
| """Turbo-map inverse depth, 0 at sky to `scale` at the nearest point, as RGB uint8 (cli).""" | |
| return COLOR_LUT[np.clip(inv * (256 / scale), 0, 255).astype(np.int32)] | |
| def grayscale16(inv: np.ndarray, scale: float) -> Image.Image: | |
| """Inverse depth as 16-bit grayscale, 0 at infinitely far (cli.grayscale16).""" | |
| return Image.fromarray((np.clip(inv / scale, 0, 1) * 65535).round().astype(np.uint16)) | |
| def resize(img: np.ndarray, f_px: float | None, max_side: int): | |
| """Downscale so the longer side is at most `max_side`, scaling a known f_px to match.""" | |
| height, width = img.shape[:2] | |
| scale = max_side / max(height, width) | |
| if scale >= 1.0: | |
| return img, f_px | |
| out = Image.fromarray(img).resize((round(width * scale), round(height * scale)), Image.LANCZOS) | |
| return np.asarray(out), None if f_px is None else f_px * scale | |
| def write_npz(path: Path, depth_meters: np.ndarray, inv: np.ndarray, f_px: float) -> None: | |
| """Depth in meters, inverse metric depth, and the focal length (cli.write_npz, extended).""" | |
| np.savez(path, depth=depth_meters, inverse_metric_depth=inv, focallength_px=np.float32(f_px)) | |
| def _as_path(value) -> str | None: | |
| """An uploaded component value as a filepath, whether Gradio passed str, FileData or dict.""" | |
| if value is None: | |
| return None | |
| if isinstance(value, str): | |
| return value | |
| path = getattr(value, "path", None) | |
| if isinstance(value, dict): | |
| path = value.get("path") or value.get("url") | |
| return path | |
| def _percentiles(depth_meters: np.ndarray) -> tuple[float, float, float]: | |
| """5th/50th/95th percentile depth in meters over the finite pixels, for the caption.""" | |
| finite = depth_meters[np.isfinite(depth_meters)] | |
| if finite.size == 0: | |
| return (0.0, 0.0, 0.0) | |
| lo, mid, hi = np.percentile(finite, [5, 50, 95]) | |
| return (float(lo), float(mid), float(hi)) | |
| def _out_dir() -> Path: | |
| """A fresh per-call output directory (handlers run concurrently; no fixed paths).""" | |
| path = Path(f"/tmp/outputs/{int(time.time() * 1000)}") | |
| path.mkdir(parents=True, exist_ok=True) | |
| return path | |
| def _run_image(img: np.ndarray, f_px: float | None) -> dict: | |
| """DepthPro2-L on one photo already downscaled; returns host arrays and stats.""" | |
| started = time.perf_counter() | |
| prediction = model.infer(transform(img), f_px=f_px) | |
| if prediction["depth"] is None: | |
| raise ValueError("no focal length available") | |
| inv = inverse_metric_depth(prediction) | |
| return { | |
| "inv": inv, | |
| "scale": color_scale(inv), | |
| "f_px": float(prediction["focallength_px"]), | |
| "depth_meters": prediction["depth"].float().cpu().numpy(), | |
| "elapsed": time.perf_counter() - started, | |
| } | |
| def predict_depth(image, max_side=MAX_IMAGE_SIDE, save_npz=False, save_png16=False, request: gr.Request = None): | |
| """Estimate metric depth (meters) for an uploaded photo. | |
| The photo's EXIF focal length is used when present; otherwise the focal-length | |
| estimator (apple/DepthPro2-focal) infers it. Returns a Turbo colorized depth map | |
| (dark blue = infinitely far, e.g. sky) plus optional downloads: a 16-bit | |
| inverse-depth PNG and an NPZ with depth in meters and the focal length in pixels. | |
| """ | |
| path = _as_path(image) | |
| if not path: | |
| raise gr.Error("Upload a photo first β or click one of the examples below.") | |
| try: | |
| img, f_px = load_rgb(path) | |
| except Exception as err: | |
| raise gr.Error( | |
| f"That upload could not be read as an image ({type(err).__name__}) β try a JPG or PNG." | |
| ) from err | |
| if max_side and max_side < MAX_IMAGE_SIDE: | |
| img, f_px = resize(img, f_px, int(max_side)) | |
| try: | |
| result = _run_image(img, f_px) | |
| except ValueError: | |
| raise gr.Error( | |
| "The photo's focal length could not be read from EXIF or estimated β try another photo." | |
| ) | |
| inv, scale = result["inv"], result["scale"] | |
| files = [] | |
| if save_png16: | |
| png16 = _out_dir() / "depth16.png" | |
| grayscale16(inv, scale).save(png16, compress_level=1) | |
| files.append(str(png16)) | |
| if save_npz: | |
| npz = _out_dir() / "depth.npz" | |
| write_npz(npz, result["depth_meters"], inv, result["f_px"]) | |
| files.append(str(npz)) | |
| lo, mid, hi = _percentiles(result["depth_meters"]) | |
| caption = ( | |
| f"**focal length {result['f_px']:.1f} px** ({'EXIF' if f_px is not None else 'estimated'}) Β· " | |
| f"depth 5β95th pct **{lo:.2f}β{hi:.2f} m** (median {mid:.2f} m) Β· " | |
| f"{result['elapsed']:.1f} s on GPU" | |
| ) | |
| return colorize(inv, scale), caption, files | |
| def _video_duration(video, *args, **kwargs): | |
| """ZeroGPU duration for a video call: a probe + per-frame cost, capped (measured, then tuned).""" | |
| try: | |
| frames = _probe_frames(_as_path(video) or "") | |
| except Exception: | |
| frames = MAX_VIDEO_FRAMES | |
| # Measured on ZeroGPU: ~10 s on GPU for a 61-frame 960 px clip (warm); the constant | |
| # covers cold-start weight streaming and heavier decodes, the slope the per-frame cost. | |
| return min(120, 30 + int(frames * 0.4)) | |
| def _probe_frames(path: str) -> int: | |
| """Count a video's frames, capped at MAX_VIDEO_FRAMES.""" | |
| with av.open(path) as container: | |
| stream = container.streams.video[0] | |
| if stream.frames: | |
| return min(int(stream.frames), MAX_VIDEO_FRAMES) | |
| duration = (container.duration or 0) / av.time_base | |
| fps = float(stream.average_rate or 30) | |
| return min(max(int(round(duration * fps)), 1), MAX_VIDEO_FRAMES) | |
| def _run_video(path: str) -> tuple[str, str]: | |
| """DepthPro2-L over a video's first frames; returns the side-by-side MP4 path and its caption. | |
| Depth and source frames are tiled into one MP4 so both play in sync. Rendering matches | |
| the CLI: one Turbo scale anchored on the first frame, BT.601 limited-range H.264. | |
| """ | |
| started = time.perf_counter() | |
| container = av.open(path) | |
| stream = container.streams.video[0] | |
| stream.thread_type = "AUTO" | |
| rate = stream.average_rate or 30 | |
| fps = Fraction(rate).limit_denominator(1001) | |
| imgs = [] | |
| for frame in container.decode(stream): | |
| imgs.append(resize(upright(frame), None, MAX_VIDEO_SIDE)[0]) | |
| if len(imgs) >= MAX_VIDEO_FRAMES: | |
| break | |
| if not imgs: | |
| raise ValueError("Could not decode any frames from that video.") | |
| # The card's video path: overlapping clips (window 16, overlap 4, buffered mode), the | |
| # focal length estimated once over the first window. | |
| predictions = model.infer_video(transform(f) for f in imgs) | |
| first = next(predictions) | |
| f_px = float(first["focallength_px"]) | |
| inv = inverse_metric_depth(first) | |
| scale = color_scale(inv) | |
| out = _out_dir() / "depth-side-by-side.mp4" | |
| written = 0 | |
| with av.open(str(out), "w", options={"movflags": FRAGMENTED_MP4}) as encoder: | |
| writer = None | |
| def add_frame(pixels: np.ndarray): | |
| nonlocal writer | |
| if writer is None: | |
| writer = encoder.add_stream("libx264", rate=fps) | |
| writer.height, writer.width = pixels.shape[:2] | |
| writer.pix_fmt = "yuv420p" | |
| writer.max_b_frames = 0 | |
| # BT.601 limited range from sRGB, or QuickTime shifts the colors (cli.VideoWriter). | |
| writer.colorspace = 6 | |
| writer.color_range = 1 | |
| writer.color_primaries = 1 | |
| writer.color_trc = 13 | |
| frame = av.VideoFrame.from_ndarray(np.ascontiguousarray(pixels), format="rgb24") | |
| for packet in writer.encode(frame): | |
| encoder.mux(packet) | |
| for index, prediction in enumerate([first] + list(predictions)): | |
| inv = inverse_metric_depth(prediction) | |
| depth_rgb = colorize(inv, scale) | |
| source = imgs[index] | |
| # Tile depth | source side by side, 1px divider, both sides padded to even dims | |
| # for yuv420p. | |
| height = max(depth_rgb.shape[0], source.shape[0]) | |
| width = depth_rgb.shape[1] + source.shape[1] + 1 | |
| canvas = np.zeros((height + height % 2, width + width % 2, 3), dtype=np.uint8) | |
| canvas[: depth_rgb.shape[0], : depth_rgb.shape[1]] = depth_rgb | |
| canvas[: source.shape[0], depth_rgb.shape[1] + 1 : width] = source | |
| add_frame(canvas) | |
| written += 1 | |
| if writer is not None: | |
| for packet in writer.encode(): | |
| encoder.mux(packet) | |
| if writer is None: | |
| raise ValueError("Could not decode any frames from that video.") | |
| elapsed = time.perf_counter() - started | |
| caption = ( | |
| f"**{written} frames** at {float(fps):.1f} fps Β· focal length **{f_px:.1f} px** (estimated) Β· " | |
| f"{elapsed:.1f} s on GPU" | |
| ) | |
| return str(out), caption | |
| def predict_depth_video(video, request: gr.Request = None): | |
| """Estimate metric depth for an uploaded video (first 64 frames). | |
| The frames are processed together in overlapping clips, so depth stays steady across | |
| them; the focal length is estimated from the first clip. Returns the depth video | |
| tiled side by side with its source. | |
| """ | |
| path = _as_path(video) | |
| if not path: | |
| raise gr.Error("Upload a video first β or click the example below.") | |
| try: | |
| return _run_video(path) | |
| except ValueError as err: | |
| raise gr.Error(f"Could not decode any frames from that video ({err}).") | |
| CSS = """ | |
| #col-container { max-width: 1200px; margin: 0 auto; } | |
| .dark .gradio-container { color: var(--body-text-color); } | |
| """ | |
| with gr.Blocks(title="Depth Pro 2 L β metric depth") as demo: | |
| gr.Markdown( | |
| """ | |
| # Depth Pro 2 L β metric monocular depth | |
| Sharp **metric depth in meters** for every pixel of a photo, and steady depth across the | |
| frames of a video, from [apple/DepthPro2-L](https://huggingface.co/apple/DepthPro2-L) | |
| ([paper](https://arxiv.org/abs/2611.26603) Β· | |
| [code](https://github.com/apple-aiml-research/ml-depth-pro-2)). The focal length comes | |
| from the photo's EXIF when present, otherwise from the bundled | |
| [focal-length estimator](https://huggingface.co/apple/DepthPro2-focal) β so depth comes | |
| out in meters either way. Colors follow the official CLI: Turbo, dark blue = infinitely | |
| far (sky), 20% headroom above the nearest point. | |
| """ | |
| ) | |
| with gr.Tabs(): | |
| with gr.TabItem("π· Photo"): | |
| with gr.Column(elem_id="col-container"): | |
| with gr.Row(): | |
| with gr.Column(): | |
| image_in = gr.Image(type="filepath", label="Photo", sources=["upload", "clipboard"]) | |
| photo_btn = gr.Button("Estimate depth", variant="primary") | |
| with gr.Column(): | |
| depth_out = gr.Image(type="numpy", label="Depth (meters, Turbo)", format="png") | |
| photo_caption = gr.Markdown() | |
| files_out = gr.Files(label="Downloads") | |
| with gr.Accordion("Advanced options", open=False): | |
| with gr.Row(): | |
| with gr.Column(): | |
| max_side = gr.Slider( | |
| minimum=512, | |
| maximum=MAX_IMAGE_SIDE, | |
| value=MAX_IMAGE_SIDE, | |
| step=64, | |
| label="Max long-side resolution (px)", | |
| info="Inputs are downscaled to this before inference, to bound VRAM.", | |
| ) | |
| with gr.Column(): | |
| save_png16 = gr.Checkbox( | |
| value=False, | |
| label="16-bit inverse-depth PNG", | |
| info="White = near, black = infinitely far, on the preview's scale.", | |
| ) | |
| save_npz_img = gr.Checkbox( | |
| value=False, | |
| label="Depth in meters as NPZ", | |
| info="depth, inverse_metric_depth, focallength_px.", | |
| ) | |
| gr.Examples( | |
| examples=[["assets/example.jpg"]], | |
| inputs=[image_in], | |
| fn=predict_depth, | |
| outputs=[depth_out, photo_caption, files_out], | |
| cache_examples=True, | |
| cache_mode="lazy", | |
| label="Apple's example photo (no EXIF focal β exercises the focal estimator)", | |
| ) | |
| with gr.TabItem("π¬ Video"): | |
| with gr.Column(elem_id="col-container"): | |
| with gr.Row(): | |
| with gr.Column(): | |
| video_in = gr.Video(label="Video") | |
| video_btn = gr.Button("Estimate depth", variant="primary") | |
| with gr.Column(): | |
| depth_vid_out = gr.Video(label="Depth | Source") | |
| video_caption = gr.Markdown() | |
| gr.Examples( | |
| examples=[["assets/example.mp4"]], | |
| inputs=[video_in], | |
| fn=predict_depth_video, | |
| outputs=[depth_vid_out, video_caption], | |
| cache_examples=True, | |
| cache_mode="lazy", | |
| label="Apple's example video (64 frames, 1920Γ1440 β capped to 960 px)", | |
| ) | |
| gr.Markdown( | |
| """ | |
| --- | |
| Example assets are Apple's own, from the | |
| [ml-depth-pro-2](https://github.com/apple-aiml-research/ml-depth-pro-2) repository. | |
| The model weights are under the **Apple ML Research license β research / non-commercial | |
| use only**. | |
| """ | |
| ) | |
| photo_btn.click( | |
| fn=predict_depth, | |
| inputs=[image_in, max_side, save_npz_img, save_png16], | |
| outputs=[depth_out, photo_caption, files_out], | |
| api_name="predict_depth", | |
| ) | |
| video_btn.click( | |
| fn=predict_depth_video, | |
| inputs=[video_in], | |
| outputs=[depth_vid_out, video_caption], | |
| api_name="predict_depth_video", | |
| ) | |
| demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True) | |