"""DANIEL student depth — attention-free monocular depth for onboard robot navigation. Runs the float PyTorch student (v5, 24.5M params, ResNet-34 U-Net, distilled from Depth Anything V2-Large) from itaimizlish/daniel-student-depth on a single image. Input: RGB image. Output: relative inverse-depth (disparity) map, near = bright, rendered with the authors' INFERNO percentile-stretch convention. """ import spaces # must be imported before any torch/CUDA-touching import import time from pathlib import Path import cv2 import gradio as gr import numpy as np import torch import torch.nn as nn import torchvision from huggingface_hub import hf_hub_download # ---------------------------------------------------------------- model ---- # Architecture replicated 1:1 from the authors' onboard/student_depth.py # (DANIEL repo, MIT license). Input 288x512 RGB in [0, 1]; output relative # disparity (near = high) at 288x512. def build_student() -> nn.Module: """Build the 24.5M-param attention-free depth student (ResNet-34 U-Net).""" def block(i: int, o: int) -> nn.Module: return nn.Sequential( nn.Conv2d(i, o, 3, padding=1, bias=False), nn.BatchNorm2d(o), nn.ReLU(inplace=True), nn.Conv2d(o, o, 3, padding=1, bias=False), nn.BatchNorm2d(o), nn.ReLU(inplace=True), ) class Student(nn.Module): def __init__(self) -> None: super().__init__() # weights=None: the trained checkpoint below replaces every # parameter, so the ImageNet download would be wasted bytes. r = torchvision.models.resnet34(weights=None) self.stem = nn.Sequential(r.conv1, r.bn1, r.relu) # /2, 64ch self.pool = r.maxpool self.l1, self.l2, self.l3, self.l4 = ( r.layer1, r.layer2, r.layer3, r.layer4 ) self.d4 = block(512 + 256, 256) self.d3 = block(256 + 128, 128) self.d2 = block(128 + 64, 64) self.d1 = block(64 + 64, 48) self.d0 = block(48, 32) self.head = nn.Conv2d(32, 1, 3, padding=1) self.register_buffer( "mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1) ) self.register_buffer( "std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1) ) def forward(self, x: torch.Tensor) -> torch.Tensor: up = lambda t: nn.functional.interpolate( t, scale_factor=2, mode="bilinear", align_corners=False ) x = (x - self.mean) / self.std s0 = self.stem(x) s1 = self.l1(self.pool(s0)) s2 = self.l2(s1) s3 = self.l3(s2) s4 = self.l4(s3) y = self.d4(torch.cat([up(s4), s3], 1)) y = self.d3(torch.cat([up(y), s2], 1)) y = self.d2(torch.cat([up(y), s1], 1)) y = self.d1(torch.cat([up(y), s0], 1)) return self.head(self.d0(up(y)))[:, 0] # H x W disparity return Student() H, W = 288, 512 # model input resolution (height x width) _student = build_student() _ckpt = hf_hub_download( "itaimizlish/daniel-student-depth", "student_v5.pt", repo_type="model" ) _student.load_state_dict(torch.load(_ckpt, map_location="cpu")) _student.eval().to("cuda") # ------------------------------------------------------- pre/post (deployed path, from onboard/edge_depth.py) ---- def crop_box(h: int, w: int, out_h: int, out_w: int) -> tuple: """Center-crop box (x, y, cw, ch) of aspect out_w/out_h inside an h x w frame.""" a = out_w / out_h cw, ch = (w, round(w / a)) if w / h < a else (round(h * a), h) return (w - cw) // 2, (h - ch) // 2, cw, ch def preprocess(rgb: np.ndarray) -> torch.Tensor: """Center-crop to the model's aspect, INTER_AREA-resize to 512x288, scale to [0,1].""" x, y, cw, ch = crop_box(rgb.shape[0], rgb.shape[1], H, W) img = cv2.resize( rgb[y : y + ch, x : x + cw], (W, H), interpolation=cv2.INTER_AREA ) arr = (img.astype(np.float32) / 255.0).transpose(2, 0, 1)[None] return torch.from_numpy(np.ascontiguousarray(arr)) def colour_disp(d: np.ndarray) -> np.ndarray: """Percentile-stretched INFERNO rendering of disparity (near = bright).""" lo, hi = np.percentile(d, [1, 99]) norm = np.clip((d - lo) / (hi - lo + 1e-8), 0, 1) bgr = cv2.applyColorMap((norm * 255).astype(np.uint8), cv2.COLORMAP_INFERNO) return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) # ------------------------------------------------------------------ app ---- @spaces.GPU(duration=10) def predict_depth( image, max_side: int = 1280 ) -> tuple[np.ndarray, np.ndarray, str]: """Estimate a relative depth map from a single RGB image. Args: image: input RGB image (upload, webcam, or example). max_side: longest side (px) the image is downscaled to before the crop, to bound the pre-processing cost on huge inputs. Returns: Tuple of (colorized depth, grayscale disparity, status text). """ if image is None: raise ValueError("Please provide an input image first.") t0 = time.perf_counter() if isinstance(image, str): bgr = cv2.imread(image, cv2.IMREAD_COLOR) if bgr is None: raise ValueError(f"Could not read image: {image}") rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) else: rgb = np.asarray(image.data if hasattr(image, "data") else image) if rgb.ndim == 3 and rgb.shape[2] == 4: # RGBA -> RGB rgb = cv2.cvtColor(rgb, cv2.COLOR_RGBA2RGB) if rgb.dtype != np.uint8: if rgb.max() <= 1.0: rgb = (rgb * 255) rgb = rgb.astype(np.uint8) h, w = rgb.shape[:2] if max(h, w) > max_side: s = max_side / max(h, w) rgb = cv2.resize( rgb, (max(1, round(w * s)), max(1, round(h * s))), interpolation=cv2.INTER_AREA, ) x = preprocess(rgb).to("cuda") with torch.no_grad(): disp = _student(x)[0].float().cpu().numpy() # 288x512, near = high coloured = colour_disp(disp) gray = (np.clip(disp, 0, None) / max(disp.max(), 1e-8) * 255).astype(np.uint8) ms = (time.perf_counter() - t0) * 1000 x0, y0, cw, ch = crop_box(rgb.shape[0], rgb.shape[1], H, W) status = ( f"inference {ms:.0f} ms · input {rgb.shape[1]}x{rgb.shape[0]} -> " f"crop ({x0},{y0},{cw},{ch}) -> {W}x{H} · disparity range " f"[{disp.min():.2f}, {disp.max():.2f}]" ) return coloured, gray, status EXAMPLES = sorted(str(p) for p in Path("examples").glob("*.jpg")) CSS = """ #col-container { max-width: 1100px; margin: 0 auto; } .dark .gradio-container { color: var(--body-text-color); } """ TITLE = """ # DANIEL student depth **Attention-free monocular depth for onboard robot navigation** — a 24.5M-parameter ResNet-34 U-Net distilled from Depth Anything V2-Large, built to run on a $35 single-board computer. Upload an image (or click an example) to get the relative depth map the robot actually navigates on. [Paper](https://huggingface.co/papers/2611.32718) · [GitHub](https://github.com/itaim18/DANIEL) · [Model](https://huggingface.co/itaimizlish/daniel-student-depth) """ with gr.Blocks() as demo: gr.Markdown(TITLE) with gr.Column(elem_id="col-container"): with gr.Row(): with gr.Column(): input_img = gr.Image( type="numpy", label="Input image", sources=["upload", "clipboard", "webcam"] ) run_btn = gr.Button("Estimate depth", variant="primary") with gr.Column(): depth_img = gr.Image( type="numpy", label="Depth (relative, near = bright)", interactive=False ) disp_img = gr.Image( type="numpy", label="Raw disparity (grayscale)", interactive=False ) status_txt = gr.Markdown() with gr.Accordion("Advanced options", open=False): max_side = gr.Slider( minimum=512, maximum=4096, value=1280, step=64, label="Downscale longest side to (px)", info="Bounds pre-processing cost on very large inputs; the model always sees 512x288.", ) gr.Examples( examples=[[p] for p in EXAMPLES], inputs=[input_img], outputs=[depth_img, disp_img, status_txt], fn=predict_depth, cache_examples=True, cache_mode="lazy", ) run_btn.click( predict_depth, inputs=[input_img, max_side], outputs=[depth_img, disp_img, status_txt], api_name="predict_depth", ) if __name__ == "__main__": demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)