multimodalart HF Staff commited on
Commit
eafeb70
·
verified ·
1 Parent(s): b228fa4

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,13 +1,39 @@
1
  ---
2
- title: Daniel Student Depth
3
- emoji: 🚀
4
- colorFrom: yellow
5
  colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: DANIEL Student Depth
3
+ emoji: 🤖
4
+ colorFrom: blue
5
  colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.32.0
 
8
  app_file: app.py
9
+ python_version: "3.10"
10
+ short_description: Attention-free depth student for onboard robot navigation
11
+ startup_duration_timeout: 15m
12
  ---
13
 
14
+ # DANIEL student depth
15
+
16
+ Demo of the attention-free monocular depth student from
17
+ **"Seeing to Drive on a Single Board: Attention-Free Depth for Onboard Robot Navigation"**.
18
+
19
+ A 24.5M-parameter ResNet-34 U-Net distilled from Depth Anything V2-Large — no
20
+ attention, no LayerNorm, no softmax — designed so a robot can navigate from a
21
+ single camera on a Raspberry Pi 5 + Hailo-8L. This Space runs the float PyTorch
22
+ `student_v5` checkpoint ([itaimizlish/daniel-student-depth](https://huggingface.co/itaimizlish/daniel-student-depth))
23
+ on GPU: upload an image and get the relative inverse-depth (disparity) map,
24
+ rendered with the authors' percentile-stretched INFERNO convention (near = bright).
25
+
26
+ Pre-processing matches the deployed `edge_depth` path exactly: center-crop to the
27
+ model's 16:9 aspect, INTER_AREA resize to 512×288, scale to [0, 1].
28
+
29
+ ## Credits
30
+
31
+ Example images are held-out benchmark frames from the authors' dataset
32
+ [itaimizlish/daniel-yard-depth](https://huggingface.co/datasets/itaimizlish/daniel-yard-depth)
33
+ (bench split — simulated scenes 07/08/09 and real robot drives),
34
+ [CC-BY-NC-4.0](https://creativecommons.org/licenses/by-nc/4.0/).
35
+ Model weights are CC-BY-NC-4.0; the DANIEL source code is MIT
36
+ ([GitHub](https://github.com/itaim18/DANIEL)).
37
+
38
+ - Paper: https://huggingface.co/papers/2611.32718
39
+ - GitHub: https://github.com/itaim18/DANIEL
app.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DANIEL student depth — attention-free monocular depth for onboard robot navigation.
2
+
3
+ Runs the float PyTorch student (v5, 24.5M params, ResNet-34 U-Net, distilled from
4
+ Depth Anything V2-Large) from itaimizlish/daniel-student-depth on a single image.
5
+ Input: RGB image. Output: relative inverse-depth (disparity) map, near = bright,
6
+ rendered with the authors' INFERNO percentile-stretch convention.
7
+ """
8
+
9
+ import spaces # must be imported before any torch/CUDA-touching import
10
+
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import cv2
15
+ import gradio as gr
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn as nn
19
+ import torchvision
20
+ from huggingface_hub import hf_hub_download
21
+
22
+ # ---------------------------------------------------------------- model ----
23
+ # Architecture replicated 1:1 from the authors' onboard/student_depth.py
24
+ # (DANIEL repo, MIT license). Input 288x512 RGB in [0, 1]; output relative
25
+ # disparity (near = high) at 288x512.
26
+
27
+
28
+ def build_student() -> nn.Module:
29
+ """Build the 24.5M-param attention-free depth student (ResNet-34 U-Net)."""
30
+
31
+ def block(i: int, o: int) -> nn.Module:
32
+ return nn.Sequential(
33
+ nn.Conv2d(i, o, 3, padding=1, bias=False),
34
+ nn.BatchNorm2d(o),
35
+ nn.ReLU(inplace=True),
36
+ nn.Conv2d(o, o, 3, padding=1, bias=False),
37
+ nn.BatchNorm2d(o),
38
+ nn.ReLU(inplace=True),
39
+ )
40
+
41
+ class Student(nn.Module):
42
+ def __init__(self) -> None:
43
+ super().__init__()
44
+ # weights=None: the trained checkpoint below replaces every
45
+ # parameter, so the ImageNet download would be wasted bytes.
46
+ r = torchvision.models.resnet34(weights=None)
47
+ self.stem = nn.Sequential(r.conv1, r.bn1, r.relu) # /2, 64ch
48
+ self.pool = r.maxpool
49
+ self.l1, self.l2, self.l3, self.l4 = (
50
+ r.layer1, r.layer2, r.layer3, r.layer4
51
+ )
52
+ self.d4 = block(512 + 256, 256)
53
+ self.d3 = block(256 + 128, 128)
54
+ self.d2 = block(128 + 64, 64)
55
+ self.d1 = block(64 + 64, 48)
56
+ self.d0 = block(48, 32)
57
+ self.head = nn.Conv2d(32, 1, 3, padding=1)
58
+ self.register_buffer(
59
+ "mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
60
+ )
61
+ self.register_buffer(
62
+ "std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
63
+ )
64
+
65
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
66
+ up = lambda t: nn.functional.interpolate(
67
+ t, scale_factor=2, mode="bilinear", align_corners=False
68
+ )
69
+ x = (x - self.mean) / self.std
70
+ s0 = self.stem(x)
71
+ s1 = self.l1(self.pool(s0))
72
+ s2 = self.l2(s1)
73
+ s3 = self.l3(s2)
74
+ s4 = self.l4(s3)
75
+ y = self.d4(torch.cat([up(s4), s3], 1))
76
+ y = self.d3(torch.cat([up(y), s2], 1))
77
+ y = self.d2(torch.cat([up(y), s1], 1))
78
+ y = self.d1(torch.cat([up(y), s0], 1))
79
+ return self.head(self.d0(up(y)))[:, 0] # H x W disparity
80
+
81
+ return Student()
82
+
83
+
84
+ H, W = 288, 512 # model input resolution (height x width)
85
+
86
+ _student = build_student()
87
+ _ckpt = hf_hub_download(
88
+ "itaimizlish/daniel-student-depth", "student_v5.pt", repo_type="model"
89
+ )
90
+ _student.load_state_dict(torch.load(_ckpt, map_location="cpu"))
91
+ _student.eval().to("cuda")
92
+
93
+
94
+ # ------------------------------------------------------- pre/post (deployed path, from onboard/edge_depth.py) ----
95
+
96
+
97
+ def crop_box(h: int, w: int, out_h: int, out_w: int) -> tuple:
98
+ """Center-crop box (x, y, cw, ch) of aspect out_w/out_h inside an h x w frame."""
99
+ a = out_w / out_h
100
+ cw, ch = (w, round(w / a)) if w / h < a else (round(h * a), h)
101
+ return (w - cw) // 2, (h - ch) // 2, cw, ch
102
+
103
+
104
+ def preprocess(rgb: np.ndarray) -> torch.Tensor:
105
+ """Center-crop to the model's aspect, INTER_AREA-resize to 512x288, scale to [0,1]."""
106
+ x, y, cw, ch = crop_box(rgb.shape[0], rgb.shape[1], H, W)
107
+ img = cv2.resize(
108
+ rgb[y : y + ch, x : x + cw], (W, H), interpolation=cv2.INTER_AREA
109
+ )
110
+ arr = (img.astype(np.float32) / 255.0).transpose(2, 0, 1)[None]
111
+ return torch.from_numpy(np.ascontiguousarray(arr))
112
+
113
+
114
+ def colour_disp(d: np.ndarray) -> np.ndarray:
115
+ """Percentile-stretched INFERNO rendering of disparity (near = bright)."""
116
+ lo, hi = np.percentile(d, [1, 99])
117
+ norm = np.clip((d - lo) / (hi - lo + 1e-8), 0, 1)
118
+ bgr = cv2.applyColorMap((norm * 255).astype(np.uint8), cv2.COLORMAP_INFERNO)
119
+ return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
120
+
121
+
122
+ # ------------------------------------------------------------------ app ----
123
+
124
+
125
+ @spaces.GPU(duration=45)
126
+ def predict_depth(
127
+ image, max_side: int = 1280
128
+ ) -> tuple[np.ndarray, np.ndarray, str]:
129
+ """Estimate a relative depth map from a single RGB image.
130
+
131
+ Args:
132
+ image: input RGB image (upload, webcam, or example).
133
+ max_side: longest side (px) the image is downscaled to before the crop,
134
+ to bound the pre-processing cost on huge inputs.
135
+
136
+ Returns:
137
+ Tuple of (colorized depth, grayscale disparity, status text).
138
+ """
139
+ if image is None:
140
+ raise ValueError("Please provide an input image first.")
141
+ t0 = time.perf_counter()
142
+
143
+ if isinstance(image, str):
144
+ bgr = cv2.imread(image, cv2.IMREAD_COLOR)
145
+ if bgr is None:
146
+ raise ValueError(f"Could not read image: {image}")
147
+ rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
148
+ else:
149
+ rgb = np.asarray(image.data if hasattr(image, "data") else image)
150
+ if rgb.ndim == 3 and rgb.shape[2] == 4: # RGBA -> RGB
151
+ rgb = cv2.cvtColor(rgb, cv2.COLOR_RGBA2RGB)
152
+ if rgb.dtype != np.uint8:
153
+ if rgb.max() <= 1.0:
154
+ rgb = (rgb * 255)
155
+ rgb = rgb.astype(np.uint8)
156
+
157
+ h, w = rgb.shape[:2]
158
+ if max(h, w) > max_side:
159
+ s = max_side / max(h, w)
160
+ rgb = cv2.resize(
161
+ rgb, (max(1, round(w * s)), max(1, round(h * s))),
162
+ interpolation=cv2.INTER_AREA,
163
+ )
164
+
165
+ x = preprocess(rgb).to("cuda")
166
+ with torch.no_grad():
167
+ disp = _student(x)[0].float().cpu().numpy() # 288x512, near = high
168
+
169
+ coloured = colour_disp(disp)
170
+ gray = (np.clip(disp, 0, None) / max(disp.max(), 1e-8) * 255).astype(np.uint8)
171
+
172
+ ms = (time.perf_counter() - t0) * 1000
173
+ x0, y0, cw, ch = crop_box(rgb.shape[0], rgb.shape[1], H, W)
174
+ status = (
175
+ f"inference {ms:.0f} ms · input {rgb.shape[1]}x{rgb.shape[0]} -> "
176
+ f"crop ({x0},{y0},{cw},{ch}) -> {W}x{H} · disparity range "
177
+ f"[{disp.min():.2f}, {disp.max():.2f}]"
178
+ )
179
+ return coloured, gray, status
180
+
181
+
182
+ EXAMPLES = sorted(str(p) for p in Path("examples").glob("*.jpg"))
183
+
184
+ CSS = """
185
+ #col-container { max-width: 1100px; margin: 0 auto; }
186
+ .dark .gradio-container { color: var(--body-text-color); }
187
+ """
188
+
189
+ TITLE = """
190
+ # DANIEL student depth
191
+ **Attention-free monocular depth for onboard robot navigation** — a 24.5M-parameter
192
+ ResNet-34 U-Net distilled from Depth Anything V2-Large, built to run on a
193
+ $35 single-board computer. Upload an image (or click an example) to get the
194
+ relative depth map the robot actually navigates on.
195
+
196
+ [Paper](https://huggingface.co/papers/2611.32718) ·
197
+ [GitHub](https://github.com/itaim18/DANIEL) ·
198
+ [Model](https://huggingface.co/itaimizlish/daniel-student-depth)
199
+ """
200
+
201
+ with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo:
202
+ gr.Markdown(TITLE)
203
+ with gr.Column(elem_id="col-container"):
204
+ with gr.Row():
205
+ with gr.Column():
206
+ input_img = gr.Image(
207
+ type="numpy", label="Input image", sources=["upload", "clipboard", "webcam"]
208
+ )
209
+ run_btn = gr.Button("Estimate depth", variant="primary")
210
+ with gr.Column():
211
+ depth_img = gr.Image(
212
+ type="numpy", label="Depth (relative, near = bright)", interactive=False
213
+ )
214
+ disp_img = gr.Image(
215
+ type="numpy", label="Raw disparity (grayscale)", interactive=False
216
+ )
217
+ status_txt = gr.Markdown()
218
+ with gr.Accordion("Advanced options", open=False):
219
+ max_side = gr.Slider(
220
+ minimum=512, maximum=4096, value=1280, step=64,
221
+ label="Downscale longest side to (px)",
222
+ info="Bounds pre-processing cost on very large inputs; the model always sees 512x288.",
223
+ )
224
+ gr.Examples(
225
+ examples=[[p] for p in EXAMPLES],
226
+ inputs=[input_img],
227
+ outputs=[depth_img, disp_img, status_txt],
228
+ fn=predict_depth,
229
+ cache_examples=True,
230
+ cache_mode="lazy",
231
+ )
232
+ run_btn.click(
233
+ predict_depth,
234
+ inputs=[input_img, max_side],
235
+ outputs=[depth_img, disp_img, status_txt],
236
+ api_name="predict_depth",
237
+ )
238
+
239
+ if __name__ == "__main__":
240
+ demo.launch(mcp_server=True)
examples/real_r000.jpg ADDED
examples/real_r040.jpg ADDED
examples/real_r080.jpg ADDED
examples/sim_b000.jpg ADDED
examples/sim_b001.jpg ADDED
examples/sim_b003.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ opencv-python
4
+ numpy
5
+ pillow