Umut Kocasari Claude Opus 4.8 commited on
Commit
4db294e
·
1 Parent(s): 7dd9e15

Add FaceAnything Gradio demo app

Browse files

Up to 40 input images; Joint (all-at-once) vs One-by-one inference modes.
Outputs: canonical/depth/normals 2D videos, a colorful 3D point-track point
cloud (.ply) in the 3D viewer with a per-frame slider + downloadable .zip,
and a bonus 2D track overlay video. Exposes the repo's hyperparameters
(process_res, background removal, predicted poses, conf cut, track count/k/
threshold, fps, frame cap). Vendors src/ (faceanything + depth_anything_3);
checkpoint added separately via LFS.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +15 -0
  2. README.md +79 -2
  3. app.py +500 -0
  4. packages.txt +1 -0
  5. requirements.txt +27 -0
  6. src/depth_anything_3/api.py +448 -0
  7. src/depth_anything_3/app/css_and_html.py +594 -0
  8. src/depth_anything_3/app/gradio_app.py +724 -0
  9. src/depth_anything_3/app/modules/__init__.py +43 -0
  10. src/depth_anything_3/app/modules/event_handlers.py +619 -0
  11. src/depth_anything_3/app/modules/file_handlers.py +304 -0
  12. src/depth_anything_3/app/modules/model_inference.py +260 -0
  13. src/depth_anything_3/app/modules/ui_components.py +477 -0
  14. src/depth_anything_3/app/modules/utils.py +207 -0
  15. src/depth_anything_3/app/modules/visualization.py +434 -0
  16. src/depth_anything_3/cfg.py +144 -0
  17. src/depth_anything_3/cli.py +803 -0
  18. src/depth_anything_3/configs/da3-base.yaml +45 -0
  19. src/depth_anything_3/configs/da3-giant.yaml +71 -0
  20. src/depth_anything_3/configs/da3-large.yaml +45 -0
  21. src/depth_anything_3/configs/da3-small.yaml +45 -0
  22. src/depth_anything_3/configs/da3metric-large.yaml +28 -0
  23. src/depth_anything_3/configs/da3mono-large.yaml +28 -0
  24. src/depth_anything_3/configs/da3nested-giant-large.yaml +10 -0
  25. src/depth_anything_3/model/__init__.py +20 -0
  26. src/depth_anything_3/model/cam_dec.py +45 -0
  27. src/depth_anything_3/model/cam_enc.py +86 -0
  28. src/depth_anything_3/model/da3.py +461 -0
  29. src/depth_anything_3/model/dinov2/dinov2.py +64 -0
  30. src/depth_anything_3/model/dinov2/layers/__init__.py +25 -0
  31. src/depth_anything_3/model/dinov2/layers/attention.py +100 -0
  32. src/depth_anything_3/model/dinov2/layers/block.py +143 -0
  33. src/depth_anything_3/model/dinov2/layers/drop_path.py +35 -0
  34. src/depth_anything_3/model/dinov2/layers/layer_scale.py +31 -0
  35. src/depth_anything_3/model/dinov2/layers/mlp.py +40 -0
  36. src/depth_anything_3/model/dinov2/layers/patch_embed.py +94 -0
  37. src/depth_anything_3/model/dinov2/layers/rope.py +200 -0
  38. src/depth_anything_3/model/dinov2/layers/swiglu_ffn.py +62 -0
  39. src/depth_anything_3/model/dinov2/vision_transformer.py +462 -0
  40. src/depth_anything_3/model/dpt.py +458 -0
  41. src/depth_anything_3/model/dualdpt.py +500 -0
  42. src/depth_anything_3/model/gs_adapter.py +200 -0
  43. src/depth_anything_3/model/gsdpt.py +139 -0
  44. src/depth_anything_3/model/reference_view_selector.py +223 -0
  45. src/depth_anything_3/model/utils/attention.py +109 -0
  46. src/depth_anything_3/model/utils/block.py +81 -0
  47. src/depth_anything_3/model/utils/gs_renderer.py +340 -0
  48. src/depth_anything_3/model/utils/head_utils.py +230 -0
  49. src/depth_anything_3/model/utils/transform.py +208 -0
  50. src/depth_anything_3/registry.py +50 -0
.gitignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ .ipynb_checkpoints/
5
+
6
+ # local model weights — add the real one via Git LFS (see README)
7
+ checkpoints/*.pt
8
+
9
+ # runtime / scratch
10
+ output/
11
+ outputs/
12
+ .gradio/
13
+ flagged/
14
+ *.log
15
+ .DS_Store
README.md CHANGED
@@ -9,7 +9,84 @@ python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
  license: cc-by-nc-4.0
12
- short_description: FaceAnything Demo
 
 
 
 
 
 
 
 
13
  ---
14
 
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  app_file: app.py
10
  pinned: false
11
  license: cc-by-nc-4.0
12
+ short_description: 4D face reconstruction & tracking from an image sequence
13
+ models:
14
+ - depth-anything/DA3-GIANT-1.1
15
+ tags:
16
+ - face
17
+ - 4d-reconstruction
18
+ - depth
19
+ - normals
20
+ - point-tracking
21
  ---
22
 
23
+ # Face Anything Gradio demo
24
+
25
+ 4D face reconstruction and tracking from **any image sequence** (up to 40 frames),
26
+ in a single feed-forward pass. The model jointly predicts depth and **canonical
27
+ facial coordinates**, from which the demo derives:
28
+
29
+ - **Canonical 2D video** — per-frame canonical facial-coordinate map
30
+ - **Depth 2D video** — per-frame depth map (JET)
31
+ - **Normals 2D video** — per-frame surface normals (from depth)
32
+ - **3D point cloud with colorful tracks** — viewable/orbitable in the 3D viewer,
33
+ with a frame slider to scrub the sequence and a downloadable `.zip` of every
34
+ frame's track point cloud
35
+ - *(bonus)* a 2D point-track overlay video
36
+
37
+ **Two inference modes** (the repo's `--process-mode`):
38
+
39
+ - **Joint (all-at-once)** — all frames processed together → more 3D-consistent.
40
+ - **One-by-one** — each frame processed independently → more surface detail and
41
+ lower memory (pairs well with a higher processing resolution).
42
+
43
+ Exposed hyperparameters (defaults match the published `run_inference.py`):
44
+ processing resolution, background removal (Robust Video Matting), predicted vs.
45
+ monocular camera poses, depth-confidence cut, number/blur/threshold of point
46
+ tracks, output FPS, and a frame cap.
47
+
48
+ ## Deploying this Space
49
+
50
+ The Gradio code (`app.py`) and the model source (`src/faceanything`,
51
+ `src/depth_anything_3`) are included here. To make the Space runnable you still
52
+ need the **checkpoint** (~15 GB), which is not committed:
53
+
54
+ 1. Add the checkpoint with Git LFS at `checkpoints/checkpoint.pt`:
55
+ ```bash
56
+ git lfs install
57
+ git lfs track "checkpoints/*.pt"
58
+ mkdir -p checkpoints
59
+ # copy or download checkpoint.pt into checkpoints/
60
+ git add .gitattributes checkpoints/checkpoint.pt
61
+ ```
62
+ Or point the app elsewhere with the `FACEANYTHING_CHECKPOINT` env var (Space
63
+ *Settings → Variables and secrets*), or fetch it at startup.
64
+
65
+ 2. Pick the hardware. This needs a CUDA GPU. On **ZeroGPU**, `@spaces.GPU` is used
66
+ automatically; raise `FACEANYTHING_GPU_DURATION` (seconds, default 180) if long
67
+ clips time out. On a dedicated GPU Space, `spaces` degrades to a no-op.
68
+
69
+ 3. The DA3 backbone config/architecture is pulled from the public model
70
+ `depth-anything/DA3-GIANT-1.1` on first run (its weights are then overwritten by
71
+ the checkpoint). Set `HF_HOME` to reuse a local cache.
72
+
73
+ ### Environment variables
74
+
75
+ | Variable | Default | Purpose |
76
+ |---|---|---|
77
+ | `FACEANYTHING_CHECKPOINT` | `checkpoints/checkpoint.pt` | path to the weights |
78
+ | `FACEANYTHING_ROOT` | the app dir | root holding `src/` and `checkpoints/` |
79
+ | `FACEANYTHING_BASE_MODEL` | `depth-anything/DA3-GIANT-1.1` | DA3 backbone id |
80
+ | `FACEANYTHING_GPU_DURATION` | `180` | ZeroGPU seconds per request |
81
+ | `FACEANYTHING_MAX_IMAGES` | `40` | hard cap on uploaded frames |
82
+
83
+ ## Running locally
84
+
85
+ ```bash
86
+ export FACEANYTHING_ROOT=/path/to/FaceAnything # source checkout (has src/, checkpoints/)
87
+ pip install -r requirements.txt
88
+ python app.py
89
+ ```
90
+
91
+ Project page: <https://kocasariumut.github.io/FaceAnything/> ·
92
+ Code: <https://github.com/kocasariumut/FaceAnything>
app.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FaceAnything — Gradio demo (Hugging Face Space).
2
+
3
+ Upload up to 40 face images (a short clip, in order). The model reconstructs the
4
+ clip in a single feed-forward pass and the app returns:
5
+
6
+ * canonical 2D video — per-frame canonical facial-coordinate map (original | map)
7
+ * depth 2D video — per-frame JET depth map
8
+ * normals 2D video — per-frame surface-normal map (from depth)
9
+ * a colorful 3D point-track point cloud (.ply) you can orbit in the 3D viewer,
10
+ with a frame slider to scrub through the sequence, plus a downloadable .zip
11
+ of every frame's track point cloud.
12
+
13
+ Two inference modes are exposed (the repo's `--process-mode`):
14
+ * Joint (all-at-once) — all frames processed together: more 3D-consistent.
15
+ * One-by-one — each frame independently: more surface detail, less
16
+ memory (pairs well with a higher processing resolution).
17
+
18
+ The heavy lifting reuses the published `faceanything` package unchanged; this app
19
+ only orchestrates it and renders the requested outputs. The expensive Open3D
20
+ orbit-video renderer is intentionally NOT used — the canonical/depth/normals
21
+ videos and the track point clouds are produced from cheap NumPy ops.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ import sys
27
+ import glob
28
+ import shutil
29
+ import tempfile
30
+ import traceback
31
+
32
+ import numpy as np
33
+
34
+
35
+ # --------------------------------------------------------------------------- #
36
+ # Locate the published FaceAnything source + checkpoint.
37
+ #
38
+ # For a real deployment, vendor the model code and weights into this Space:
39
+ # * copy the source repo's `src/` here (or `pip install` the package), and
40
+ # * place the checkpoint at `checkpoints/checkpoint.pt` (Git LFS).
41
+ # For local testing against the source checkout, point FACEANYTHING_ROOT at it:
42
+ # export FACEANYTHING_ROOT=/cluster/eriador/ukocasari/projects/FaceAnything
43
+ # --------------------------------------------------------------------------- #
44
+ APP_DIR = os.path.dirname(os.path.abspath(__file__))
45
+ FA_ROOT = os.environ.get("FACEANYTHING_ROOT", APP_DIR)
46
+
47
+
48
+ def _ensure_faceanything_importable():
49
+ """Make `import faceanything` work, trying a few sensible source locations."""
50
+ try:
51
+ import faceanything # noqa: F401 (already installed / vendored)
52
+ return
53
+ except Exception:
54
+ pass
55
+ for cand in (os.path.join(APP_DIR, "src"), os.path.join(FA_ROOT, "src")):
56
+ if os.path.isdir(os.path.join(cand, "faceanything")) and cand not in sys.path:
57
+ sys.path.insert(0, cand)
58
+
59
+
60
+ _ensure_faceanything_importable()
61
+
62
+ CHECKPOINT = os.environ.get(
63
+ "FACEANYTHING_CHECKPOINT", os.path.join(FA_ROOT, "checkpoints", "checkpoint.pt")
64
+ )
65
+ BASE_MODEL = os.environ.get("FACEANYTHING_BASE_MODEL", "depth-anything/DA3-GIANT-1.1")
66
+ GPU_DURATION = int(os.environ.get("FACEANYTHING_GPU_DURATION", "180"))
67
+ MAX_IMAGES = int(os.environ.get("FACEANYTHING_MAX_IMAGES", "40"))
68
+
69
+
70
+ # --------------------------------------------------------------------------- #
71
+ # ZeroGPU decorator — falls back to a no-op when `spaces` is unavailable
72
+ # (e.g. running on a plain GPU box / cluster), so the same file runs anywhere.
73
+ # --------------------------------------------------------------------------- #
74
+ try:
75
+ import spaces
76
+
77
+ GPU = spaces.GPU
78
+ except Exception: # pragma: no cover - only on non-Spaces hosts
79
+
80
+ def GPU(func=None, **_kwargs):
81
+ if callable(func):
82
+ return func
83
+
84
+ def _deco(f):
85
+ return f
86
+
87
+ return _deco
88
+
89
+
90
+ import gradio as gr
91
+
92
+
93
+ # --------------------------------------------------------------------------- #
94
+ # Model (loaded once, lazily, inside the GPU context and cached across calls)
95
+ # --------------------------------------------------------------------------- #
96
+ _MODEL = None
97
+ _MODEL_DEVICE = None
98
+
99
+
100
+ def _get_model(device: str):
101
+ global _MODEL, _MODEL_DEVICE
102
+ if _MODEL is not None and _MODEL_DEVICE == device:
103
+ return _MODEL
104
+ from faceanything.model import load_model
105
+
106
+ if not os.path.exists(CHECKPOINT):
107
+ raise FileNotFoundError(
108
+ f"Checkpoint not found at '{CHECKPOINT}'. Set FACEANYTHING_CHECKPOINT or "
109
+ f"place checkpoint.pt under checkpoints/ (see README)."
110
+ )
111
+ _MODEL = load_model(CHECKPOINT, base_model=BASE_MODEL, device=device)
112
+ _MODEL_DEVICE = device
113
+ return _MODEL
114
+
115
+
116
+ # --------------------------------------------------------------------------- #
117
+ # Helpers
118
+ # --------------------------------------------------------------------------- #
119
+ def _prepare_inputs(files, max_frames, workdir):
120
+ """Copy uploaded images into a clean folder and return naturally-sorted paths."""
121
+ from faceanything.io_utils import load_frame_paths
122
+
123
+ if not files:
124
+ raise gr.Error("Please upload at least one image.")
125
+ img_dir = os.path.join(workdir, "images")
126
+ os.makedirs(img_dir, exist_ok=True)
127
+ for f in files:
128
+ src = f if isinstance(f, str) else getattr(f, "name", None)
129
+ if not src or not os.path.exists(src):
130
+ continue
131
+ shutil.copy(src, os.path.join(img_dir, os.path.basename(src)))
132
+ paths, _ = load_frame_paths(img_dir, max_frames=int(max_frames), stride=1)
133
+ return paths
134
+
135
+
136
+ def _save_view_ply(path, points, colors):
137
+ """Save a track point cloud oriented for a Y-up web viewer (OpenCV -> GL-ish).
138
+
139
+ Negate Y and Z (OpenCV is +Y-down / +Z-forward) and recentre so the face sits
140
+ upright, facing the camera, near the origin in the 3D viewer.
141
+ """
142
+ from faceanything.export import save_ply
143
+
144
+ pts = np.asarray(points, np.float32).copy()
145
+ finite = np.isfinite(pts).all(axis=1)
146
+ pts = pts[finite]
147
+ cols = np.asarray(colors)[finite]
148
+ if pts.shape[0]:
149
+ pts[:, 1] *= -1.0
150
+ pts[:, 2] *= -1.0
151
+ pts -= np.median(pts, axis=0, keepdims=True)
152
+ return save_ply(path, pts, cols)
153
+
154
+
155
+ @GPU(duration=GPU_DURATION)
156
+ def run(
157
+ files,
158
+ mode,
159
+ process_res,
160
+ remove_bg,
161
+ use_predicted_poses,
162
+ conf_percentile,
163
+ n_tracks,
164
+ track_k,
165
+ track_threshold,
166
+ fps,
167
+ max_frames,
168
+ progress=gr.Progress(),
169
+ ):
170
+ """End-to-end inference + visualization. Returns the 5 outputs + viewer state."""
171
+ import torch
172
+
173
+ # Imported here so the UI still builds even if heavy deps are missing.
174
+ from faceanything.predict import run_inference
175
+ from faceanything.geometry import (
176
+ point_cloud_from_depth,
177
+ unproject_depth,
178
+ pointmap_to_normals,
179
+ )
180
+ from faceanything.colorize import (
181
+ depth_to_jet,
182
+ normals_to_rgb,
183
+ canonical_to_rgb,
184
+ )
185
+ from faceanything.tracking import compute_track_colors
186
+ from faceanything.export import save_ply
187
+ from faceanything.render import side_by_side, write_video
188
+
189
+ device = "cuda" if torch.cuda.is_available() else "cpu"
190
+ workdir = tempfile.mkdtemp(prefix="faceanything_demo_")
191
+ log = []
192
+
193
+ def _say(frac, msg):
194
+ log.append(msg)
195
+ progress(frac, desc=msg)
196
+
197
+ try:
198
+ _say(0.02, "Preparing inputs…")
199
+ frame_paths = _prepare_inputs(files, min(int(max_frames), MAX_IMAGES), workdir)
200
+ n_in = len(frame_paths)
201
+ if n_in == 0:
202
+ raise gr.Error("No valid images found in the upload.")
203
+ log.append(f"{n_in} frame(s) | mode: {mode} | process_res: {int(process_res)}")
204
+
205
+ # ---- background removal (optional) ----
206
+ mask_paths = None
207
+ if remove_bg:
208
+ _say(0.08, "Removing background (Robust Video Matting)…")
209
+ from faceanything.background import generate_masks
210
+
211
+ mask_paths = generate_masks(
212
+ frame_paths, os.path.join(workdir, "masks"), device=device
213
+ )
214
+
215
+ # ---- model + inference ----
216
+ _say(0.15, "Loading model (first run downloads/loads the checkpoint)…")
217
+ model = _get_model(device)
218
+ _say(0.30, f"Running inference on {n_in} frame(s)…")
219
+ pred = run_inference(
220
+ model,
221
+ frame_paths,
222
+ mask_paths=mask_paths,
223
+ process_res=int(process_res),
224
+ monocular=not bool(use_predicted_poses),
225
+ conf_percentile=float(conf_percentile),
226
+ per_frame=(mode == "One-by-one"),
227
+ )
228
+ N = int(pred.depth.shape[0])
229
+ has_canon = pred.canonical is not None
230
+ log.append(f"Inference done: {N} frame(s), depth {tuple(pred.depth.shape[1:])}, "
231
+ f"canonical: {has_canon}")
232
+
233
+ # ---- per-frame clouds + global color ranges (mirrors run_inference.py) ----
234
+ _say(0.55, "Building point clouds and color maps…")
235
+ clouds = []
236
+ for i in range(N):
237
+ pts, rgb, canon, pix = point_cloud_from_depth(
238
+ pred.depth[i], pred.images[i], pred.intrinsics[i],
239
+ extrinsics=None, valid_mask=pred.valid[i],
240
+ deformation=pred.canonical[i] if has_canon else None,
241
+ )
242
+ depth_vals = pred.depth[i][pix[:, 0], pix[:, 1]]
243
+ clouds.append(dict(points=pts, rgb=rgb, canonical=canon,
244
+ depth_vals=depth_vals, pix=pix))
245
+
246
+ all_depth = (np.concatenate([c["depth_vals"] for c in clouds])
247
+ if N else np.zeros(1))
248
+ dmin, dmax = (np.percentile(all_depth, [2, 98]) if all_depth.size else (0.0, 1.0))
249
+ if dmax <= dmin:
250
+ dmax = dmin + 1e-6
251
+ canon_ranges = None
252
+ if has_canon:
253
+ allc = np.concatenate([c["canonical"] for c in clouds
254
+ if c["canonical"] is not None])
255
+ _, canon_ranges = canonical_to_rgb(allc.reshape(-1, 1, 3), None)
256
+
257
+ # ---- 2D maps (image space) ----
258
+ def frame2d(modality, i):
259
+ v = pred.valid[i]
260
+ if modality == "depth":
261
+ return depth_to_jet(pred.depth[i], v, dmin, dmax)
262
+ if modality == "normals":
263
+ nmap = pointmap_to_normals(
264
+ unproject_depth(pred.depth[i], pred.intrinsics[i], None)[0])
265
+ img = normals_to_rgb(nmap)
266
+ img[~v] = 255
267
+ return img
268
+ if modality == "canonical":
269
+ img, _ = canonical_to_rgb(pred.canonical[i], v, ranges=canon_ranges)
270
+ return img
271
+ raise ValueError(modality)
272
+
273
+ vids_dir = os.path.join(workdir, "videos")
274
+ os.makedirs(vids_dir, exist_ok=True)
275
+
276
+ def make_2d_video(modality):
277
+ seq = [side_by_side(pred.images[i], frame2d(modality, i)) for i in range(N)]
278
+ seq = seq * 30 if len(seq) == 1 else seq # avoid 1-frame videos
279
+ out = os.path.join(vids_dir, f"{modality}_2d.mp4")
280
+ write_video(seq, out, fps=int(fps))
281
+ return out
282
+
283
+ _say(0.65, "Rendering depth 2D video…")
284
+ depth_vid = make_2d_video("depth")
285
+ _say(0.72, "Rendering normals 2D video…")
286
+ normals_vid = make_2d_video("normals")
287
+ canonical_vid = None
288
+ if has_canon:
289
+ _say(0.79, "Rendering canonical 2D video…")
290
+ canonical_vid = make_2d_video("canonical")
291
+
292
+ # ---- colorful point tracks (canonical NN matching) ----
293
+ tracks_zip = None
294
+ tracks2d_vid = None
295
+ view_plys = []
296
+ if has_canon:
297
+ _say(0.86, f"Computing {int(n_tracks)} colorful point tracks…")
298
+ track_colors, track_overlay = compute_track_colors(
299
+ [dict(canonical=c["canonical"], rgb=c["rgb"], pix=c["pix"])
300
+ for c in clouds],
301
+ n_tracks=int(n_tracks), k=int(track_k),
302
+ threshold=float(track_threshold),
303
+ )
304
+
305
+ ply_dir = os.path.join(workdir, "ply_tracks") # repo convention
306
+ view_dir = os.path.join(workdir, "ply_tracks_view") # viewer-oriented
307
+ os.makedirs(ply_dir, exist_ok=True)
308
+ os.makedirs(view_dir, exist_ok=True)
309
+ for i in range(N):
310
+ save_ply(os.path.join(ply_dir, f"frame_{i:04d}.ply"),
311
+ clouds[i]["points"], track_colors[i])
312
+ vp = os.path.join(view_dir, f"frame_{i:04d}.ply")
313
+ _save_view_ply(vp, clouds[i]["points"], track_colors[i])
314
+ view_plys.append(vp)
315
+ tracks_zip = shutil.make_archive(
316
+ os.path.join(workdir, "track_pointclouds"), "zip", ply_dir)
317
+
318
+ # bonus: 2D track overlay video (colorful seeds on the original frames)
319
+ _say(0.93, "Rendering 2D track overlay video…")
320
+
321
+ def _paint(img, pix, col, radius):
322
+ H, W = img.shape[:2]
323
+ for dr in range(-radius, radius + 1):
324
+ for dc in range(-radius, radius + 1):
325
+ rr = np.clip(pix[:, 0] + dr, 0, H - 1)
326
+ cc = np.clip(pix[:, 1] + dc, 0, W - 1)
327
+ img[rr, cc] = col
328
+
329
+ t_seq = []
330
+ for i in range(N):
331
+ img = pred.images[i].copy()
332
+ img[~pred.valid[i]] = 255
333
+ pix, col = track_overlay[i]
334
+ if pix.shape[0]:
335
+ _paint(img, pix, col, radius=max(2, round(img.shape[0] / 160)))
336
+ t_seq.append(side_by_side(pred.images[i], img))
337
+ t_seq = t_seq * 30 if len(t_seq) == 1 else t_seq
338
+ tracks2d_vid = os.path.join(vids_dir, "tracks_2d.mp4")
339
+ write_video(t_seq, tracks2d_vid, fps=int(fps))
340
+
341
+ _say(1.0, "Done.")
342
+
343
+ model3d = view_plys[0] if view_plys else None
344
+ if not has_canon:
345
+ log.append("WARNING: model produced no canonical output — canonical "
346
+ "video and point tracks were skipped (check the checkpoint).")
347
+
348
+ # keep viewer plys around (outside the temp dir gradio might clean)
349
+ status = "\n".join(f"• {m}" for m in log)
350
+ slider_update = gr.Slider(
351
+ minimum=0, maximum=max(0, N - 1), step=1, value=0,
352
+ label="Track point-cloud frame", visible=bool(view_plys),
353
+ interactive=N > 1,
354
+ )
355
+ return (
356
+ model3d,
357
+ canonical_vid,
358
+ depth_vid,
359
+ normals_vid,
360
+ tracks2d_vid,
361
+ tracks_zip,
362
+ view_plys,
363
+ slider_update,
364
+ status,
365
+ )
366
+ except gr.Error:
367
+ raise
368
+ except Exception as e: # surface the traceback in the UI instead of a blank fail
369
+ tb = traceback.format_exc()
370
+ raise gr.Error(f"Inference failed: {e}\n\n{tb[-1500:]}")
371
+
372
+
373
+ def pick_frame(idx, view_plys):
374
+ """Swap the 3D viewer to a different frame's track point cloud."""
375
+ if not view_plys:
376
+ return None
377
+ idx = int(idx)
378
+ idx = max(0, min(idx, len(view_plys) - 1))
379
+ return view_plys[idx]
380
+
381
+
382
+ # --------------------------------------------------------------------------- #
383
+ # UI
384
+ # --------------------------------------------------------------------------- #
385
+ DESCRIPTION = """
386
+ # 🧑‍🎨 Face Anything — 4D Face Reconstruction from Any Image Sequence
387
+
388
+ Upload **up to 40 face images** (a short clip, named so they sort in order).
389
+ The model jointly predicts depth and **canonical facial coordinates** in a single
390
+ feed-forward pass, from which we derive canonical / depth / normal maps and dense,
391
+ temporally-consistent **3D point tracks**.
392
+
393
+ [Project page](https://kocasariumut.github.io/FaceAnything/) ·
394
+ [arXiv](https://arxiv.org/abs/2604.19702) ·
395
+ [Code](https://github.com/kocasariumut/FaceAnything)
396
+ """
397
+
398
+
399
+ def build_demo():
400
+ with gr.Blocks(title="Face Anything") as demo:
401
+ gr.Markdown(DESCRIPTION)
402
+ view_state = gr.State([])
403
+
404
+ with gr.Row():
405
+ # ---------------- inputs ----------------
406
+ with gr.Column(scale=1):
407
+ files = gr.File(
408
+ label=f"Input images (up to {MAX_IMAGES}, in temporal order)",
409
+ file_count="multiple",
410
+ file_types=["image"],
411
+ type="filepath",
412
+ )
413
+ gallery = gr.Gallery(
414
+ label="Preview", columns=6, height=180, show_label=True,
415
+ object_fit="contain",
416
+ )
417
+ mode = gr.Radio(
418
+ choices=["Joint", "One-by-one"],
419
+ value="Joint",
420
+ label="Inference mode",
421
+ info="Joint (all-at-once): more 3D-consistent across frames. "
422
+ "One-by-one: more surface detail, lower memory.",
423
+ )
424
+ with gr.Row():
425
+ remove_bg = gr.Checkbox(
426
+ value=True, label="Remove background",
427
+ info="Robust Video Matting (recommended).",
428
+ )
429
+ use_poses = gr.Checkbox(
430
+ value=False, label="Use predicted camera poses",
431
+ info="Multi-view world frame instead of per-frame monocular.",
432
+ )
433
+ process_res = gr.Slider(
434
+ 252, 1036, value=504, step=14,
435
+ label="Processing resolution",
436
+ info="Higher = more detail (and more memory). Multiples of 14.",
437
+ )
438
+
439
+ with gr.Accordion("Point-track settings", open=False):
440
+ n_tracks = gr.Slider(10, 500, value=100, step=10,
441
+ label="Number of tracks (seeds)")
442
+ track_k = gr.Slider(1, 100, value=25, step=1,
443
+ label="Neighbours recolored per track (k)")
444
+ track_threshold = gr.Slider(
445
+ 0.001, 0.1, value=0.01, step=0.001,
446
+ label="Canonical match threshold")
447
+
448
+ with gr.Accordion("Advanced", open=False):
449
+ conf_percentile = gr.Slider(
450
+ 0, 95, value=0, step=5,
451
+ label="Confidence percentile cut",
452
+ info="Drop the least-confident depth pixels (0 = keep all).")
453
+ fps = gr.Slider(1, 30, value=10, step=1, label="Output video FPS")
454
+ max_frames = gr.Slider(
455
+ 1, MAX_IMAGES, value=MAX_IMAGES, step=1,
456
+ label="Max frames to use")
457
+
458
+ run_btn = gr.Button("Reconstruct", variant="primary")
459
+
460
+ # ---------------- outputs ----------------
461
+ with gr.Column(scale=1):
462
+ model3d = gr.Model3D(
463
+ label="3D point cloud with colorful tracks",
464
+ clear_color=[0.0, 0.0, 0.0, 0.0],
465
+ height=420,
466
+ )
467
+ frame_slider = gr.Slider(
468
+ 0, 0, value=0, step=1, visible=False,
469
+ label="Track point-cloud frame")
470
+ tracks_zip = gr.File(label="Download all track point clouds (.zip)")
471
+ with gr.Tab("Canonical (2D)"):
472
+ canonical_vid = gr.Video(label="Canonical facial-coordinate map")
473
+ with gr.Tab("Depth (2D)"):
474
+ depth_vid = gr.Video(label="Depth map")
475
+ with gr.Tab("Normals (2D)"):
476
+ normals_vid = gr.Video(label="Surface-normal map")
477
+ with gr.Tab("Tracks (2D)"):
478
+ tracks2d_vid = gr.Video(label="2D point-track overlay")
479
+ status = gr.Textbox(label="Log", lines=6, interactive=False)
480
+
481
+ # preview uploaded files in the gallery
482
+ files.change(lambda fs: fs or [], inputs=files, outputs=gallery)
483
+
484
+ run_btn.click(
485
+ run,
486
+ inputs=[files, mode, process_res, remove_bg, use_poses,
487
+ conf_percentile, n_tracks, track_k, track_threshold,
488
+ fps, max_frames],
489
+ outputs=[model3d, canonical_vid, depth_vid, normals_vid, tracks2d_vid,
490
+ tracks_zip, view_state, frame_slider, status],
491
+ concurrency_limit=1,
492
+ )
493
+ frame_slider.change(pick_frame, inputs=[frame_slider, view_state],
494
+ outputs=model3d)
495
+ return demo
496
+
497
+
498
+ if __name__ == "__main__":
499
+ demo = build_demo()
500
+ demo.queue(max_size=8).launch()
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FaceAnything Space dependencies.
2
+ #
3
+ # torch / torchvision are provided by the Space runtime (ZeroGPU / GPU image) and
4
+ # are intentionally NOT pinned here so they match the platform CUDA build.
5
+ #
6
+ # xformers is intentionally omitted: the model falls back to a pure-PyTorch SwiGLU
7
+ # when it is absent (see dinov2/layers/swiglu_ffn.py), and pinning it tends to
8
+ # conflict with the runtime's torch on ZeroGPU. Add it back if you want the fused
9
+ # kernel and your torch build is compatible.
10
+
11
+ spaces
12
+
13
+ numpy==1.26.4
14
+ scipy==1.16.3
15
+ einops==0.8.1
16
+ omegaconf==2.3.0
17
+ safetensors==0.7.0
18
+ e3nn==0.5.8
19
+
20
+ opencv-python-headless==4.11.0.86
21
+ pillow
22
+ imageio==2.37.2
23
+ imageio-ffmpeg==0.6.0
24
+ trimesh==4.10.0
25
+ plyfile==1.1.3
26
+ matplotlib==3.10.7
27
+ tqdm==4.67.1
src/depth_anything_3/api.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Depth Anything 3 API module.
16
+
17
+ This module provides the main API for Depth Anything 3, including model loading,
18
+ inference, and export capabilities. It supports both single and nested model architectures.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import time
24
+ from typing import Optional, Sequence
25
+ import numpy as np
26
+ import torch
27
+ import torch.nn as nn
28
+ from huggingface_hub import PyTorchModelHubMixin
29
+ from PIL import Image
30
+
31
+ from depth_anything_3.cfg import create_object, load_config
32
+ from depth_anything_3.registry import MODEL_REGISTRY
33
+ from depth_anything_3.specs import Prediction
34
+ from depth_anything_3.utils.export import export
35
+ from depth_anything_3.utils.geometry import affine_inverse
36
+ from depth_anything_3.utils.io.input_processor import InputProcessor
37
+ from depth_anything_3.utils.io.output_processor import OutputProcessor
38
+ from depth_anything_3.utils.logger import logger
39
+ from depth_anything_3.utils.pose_align import align_poses_umeyama
40
+
41
+ torch.backends.cudnn.benchmark = False
42
+ # logger.info("CUDNN Benchmark Disabled")
43
+
44
+ SAFETENSORS_NAME = "model.safetensors"
45
+ CONFIG_NAME = "config.json"
46
+
47
+
48
+ class DepthAnything3(nn.Module, PyTorchModelHubMixin):
49
+ """
50
+ Depth Anything 3 main API class.
51
+
52
+ This class provides a high-level interface for depth estimation using Depth Anything 3.
53
+ It supports both single and nested model architectures with metric scaling capabilities.
54
+
55
+ Features:
56
+ - Hugging Face Hub integration via PyTorchModelHubMixin
57
+ - Support for multiple model presets (vitb, vitg, nested variants)
58
+ - Automatic mixed precision inference
59
+ - Export capabilities for various formats (GLB, PLY, NPZ, etc.)
60
+ - Camera pose estimation and metric depth scaling
61
+
62
+ Usage:
63
+ # Load from Hugging Face Hub
64
+ model = DepthAnything3.from_pretrained("huggingface/model-name")
65
+
66
+ # Or create with specific preset
67
+ model = DepthAnything3(preset="vitg")
68
+
69
+ # Run inference
70
+ prediction = model.inference(images, export_dir="output", export_format="glb")
71
+ """
72
+
73
+ _commit_hash: str | None = None # Set by mixin when loading from Hub
74
+
75
+ def __init__(self, model_name: str = "da3-large", **kwargs):
76
+ """
77
+ Initialize DepthAnything3 with specified preset.
78
+
79
+ Args:
80
+ model_name: The name of the model preset to use.
81
+ Examples: 'da3-giant', 'da3-large', 'da3metric-large', 'da3nested-giant-large'.
82
+ **kwargs: Additional keyword arguments (currently unused).
83
+ """
84
+ super().__init__()
85
+ self.model_name = model_name
86
+
87
+ # Build the underlying network
88
+ self.config = load_config(MODEL_REGISTRY[self.model_name])
89
+ self.model = create_object(self.config)
90
+ self.model.eval()
91
+
92
+ # Initialize processors
93
+ self.input_processor = InputProcessor()
94
+ self.output_processor = OutputProcessor()
95
+
96
+ # Device management (set by user)
97
+ self.device = None
98
+
99
+ #@torch.inference_mode()
100
+ def forward(
101
+ self,
102
+ image: torch.Tensor,
103
+ extrinsics: torch.Tensor | None = None,
104
+ intrinsics: torch.Tensor | None = None,
105
+ export_feat_layers: list[int] | None = None,
106
+ infer_gs: bool = False,
107
+ use_ray_pose: bool = False,
108
+ ref_view_strategy: str = "saddle_balanced",
109
+ ) -> dict[str, torch.Tensor]:
110
+ """
111
+ Forward pass through the model.
112
+
113
+ Args:
114
+ image: Input batch with shape ``(B, N, 3, H, W)`` on the model device.
115
+ extrinsics: Optional camera extrinsics with shape ``(B, N, 4, 4)``.
116
+ intrinsics: Optional camera intrinsics with shape ``(B, N, 3, 3)``.
117
+ export_feat_layers: Layer indices to return intermediate features for.
118
+ infer_gs: Enable Gaussian Splatting branch.
119
+ use_ray_pose: Use ray-based pose estimation instead of camera decoder.
120
+ ref_view_strategy: Strategy for selecting reference view from multiple views.
121
+
122
+ Returns:
123
+ Dictionary containing model predictions
124
+ """
125
+ # Determine optimal autocast dtype
126
+ autocast_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
127
+ #with torch.no_grad():
128
+ with torch.autocast(device_type=image.device.type, dtype=autocast_dtype):
129
+ return self.model(
130
+ image, extrinsics, intrinsics, export_feat_layers, infer_gs, use_ray_pose, ref_view_strategy
131
+ )
132
+
133
+ def inference(
134
+ self,
135
+ image: list[np.ndarray | Image.Image | str],
136
+ extrinsics: np.ndarray | None = None,
137
+ intrinsics: np.ndarray | None = None,
138
+ align_to_input_ext_scale: bool = True,
139
+ infer_gs: bool = False,
140
+ use_ray_pose: bool = False,
141
+ ref_view_strategy: str = "saddle_balanced",
142
+ render_exts: np.ndarray | None = None,
143
+ render_ixts: np.ndarray | None = None,
144
+ render_hw: tuple[int, int] | None = None,
145
+ process_res: int = 504,
146
+ process_res_method: str = "upper_bound_resize",
147
+ export_dir: str | None = None,
148
+ export_format: str = "mini_npz",
149
+ export_feat_layers: Sequence[int] | None = None,
150
+ # GLB export parameters
151
+ conf_thresh_percentile: float = 40.0,
152
+ num_max_points: int = 1_000_000,
153
+ show_cameras: bool = True,
154
+ # Feat_vis export parameters
155
+ feat_vis_fps: int = 15,
156
+ # Other export parameters, e.g., gs_ply, gs_video
157
+ export_kwargs: Optional[dict] = {},
158
+ ) -> Prediction:
159
+ """
160
+ Run inference on input images.
161
+
162
+ Args:
163
+ image: List of input images (numpy arrays, PIL Images, or file paths)
164
+ extrinsics: Camera extrinsics (N, 4, 4)
165
+ intrinsics: Camera intrinsics (N, 3, 3)
166
+ align_to_input_ext_scale: whether to align the input pose scale to the prediction
167
+ infer_gs: Enable the 3D Gaussian branch (needed for `gs_ply`/`gs_video` exports)
168
+ use_ray_pose: Use ray-based pose estimation instead of camera decoder (default: False)
169
+ ref_view_strategy: Strategy for selecting reference view from multiple views.
170
+ Options: "first", "middle", "saddle_balanced", "saddle_sim_range".
171
+ Default: "saddle_balanced". For single view input (S ≤ 2), no reordering is performed.
172
+ render_exts: Optional render extrinsics for Gaussian video export
173
+ render_ixts: Optional render intrinsics for Gaussian video export
174
+ render_hw: Optional render resolution for Gaussian video export
175
+ process_res: Processing resolution
176
+ process_res_method: Resize method for processing
177
+ export_dir: Directory to export results
178
+ export_format: Export format (mini_npz, npz, glb, ply, gs, gs_video)
179
+ export_feat_layers: Layer indices to export intermediate features from
180
+ conf_thresh_percentile: [GLB] Lower percentile for adaptive confidence threshold (default: 40.0) # noqa: E501
181
+ num_max_points: [GLB] Maximum number of points in the point cloud (default: 1,000,000)
182
+ show_cameras: [GLB] Show camera wireframes in the exported scene (default: True)
183
+ feat_vis_fps: [FEAT_VIS] Frame rate for output video (default: 15)
184
+ export_kwargs: additional arguments to export functions.
185
+
186
+ Returns:
187
+ Prediction object containing depth maps and camera parameters
188
+ """
189
+ if "gs" in export_format:
190
+ assert infer_gs, "must set `infer_gs=True` to perform gs-related export."
191
+
192
+ if "colmap" in export_format:
193
+ assert isinstance(image[0], str), "`image` must be image paths for COLMAP export."
194
+
195
+ # Preprocess images
196
+ imgs_cpu, extrinsics, intrinsics = self._preprocess_inputs(
197
+ image, extrinsics, intrinsics, process_res, process_res_method
198
+ )
199
+
200
+ # Prepare tensors for model
201
+ imgs, ex_t, in_t = self._prepare_model_inputs(imgs_cpu, extrinsics, intrinsics)
202
+
203
+ # Normalize extrinsics
204
+ ex_t_norm = self._normalize_extrinsics(ex_t.clone() if ex_t is not None else None)
205
+
206
+ # Run model forward pass
207
+ export_feat_layers = list(export_feat_layers) if export_feat_layers is not None else []
208
+
209
+ raw_output = self._run_model_forward(
210
+ imgs, ex_t_norm, in_t, export_feat_layers, infer_gs, use_ray_pose, ref_view_strategy
211
+ )
212
+
213
+ # Convert raw output to prediction
214
+ prediction = self._convert_to_prediction(raw_output)
215
+
216
+ # Align prediction to extrinsincs
217
+ prediction = self._align_to_input_extrinsics_intrinsics(
218
+ extrinsics, intrinsics, prediction, align_to_input_ext_scale
219
+ )
220
+
221
+ # Add processed images for visualization
222
+ prediction = self._add_processed_images(prediction, imgs_cpu)
223
+
224
+ # Export if requested
225
+ if export_dir is not None:
226
+
227
+ if "gs" in export_format:
228
+ if infer_gs and "gs_video" not in export_format:
229
+ export_format = f"{export_format}-gs_video"
230
+ if "gs_video" in export_format:
231
+ if "gs_video" not in export_kwargs:
232
+ export_kwargs["gs_video"] = {}
233
+ export_kwargs["gs_video"].update(
234
+ {
235
+ "extrinsics": render_exts,
236
+ "intrinsics": render_ixts,
237
+ "out_image_hw": render_hw,
238
+ }
239
+ )
240
+ # Add GLB export parameters
241
+ if "glb" in export_format:
242
+ if "glb" not in export_kwargs:
243
+ export_kwargs["glb"] = {}
244
+ export_kwargs["glb"].update(
245
+ {
246
+ "conf_thresh_percentile": conf_thresh_percentile,
247
+ "num_max_points": num_max_points,
248
+ "show_cameras": show_cameras,
249
+ }
250
+ )
251
+ # Add Feat_vis export parameters
252
+ if "feat_vis" in export_format:
253
+ if "feat_vis" not in export_kwargs:
254
+ export_kwargs["feat_vis"] = {}
255
+ export_kwargs["feat_vis"].update(
256
+ {
257
+ "fps": feat_vis_fps,
258
+ }
259
+ )
260
+ # Add COLMAP export parameters
261
+ if "colmap" in export_format:
262
+ if "colmap" not in export_kwargs:
263
+ export_kwargs["colmap"] = {}
264
+ export_kwargs["colmap"].update(
265
+ {
266
+ "image_paths": image,
267
+ "conf_thresh_percentile": conf_thresh_percentile,
268
+ "process_res_method": process_res_method,
269
+ }
270
+ )
271
+ self._export_results(prediction, export_format, export_dir, **export_kwargs)
272
+
273
+ return prediction
274
+
275
+ def _preprocess_inputs(
276
+ self,
277
+ image: list[np.ndarray | Image.Image | str],
278
+ extrinsics: np.ndarray | None = None,
279
+ intrinsics: np.ndarray | None = None,
280
+ process_res: int = 504,
281
+ process_res_method: str = "upper_bound_resize",
282
+ ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
283
+ """Preprocess input images using input processor."""
284
+ start_time = time.time()
285
+ imgs_cpu, extrinsics, intrinsics = self.input_processor(
286
+ image,
287
+ extrinsics.copy() if extrinsics is not None else None,
288
+ intrinsics.copy() if intrinsics is not None else None,
289
+ process_res,
290
+ process_res_method,
291
+ )
292
+ end_time = time.time()
293
+ logger.info(
294
+ "Processed Images Done taking",
295
+ end_time - start_time,
296
+ "seconds. Shape: ",
297
+ imgs_cpu.shape,
298
+ )
299
+ return imgs_cpu, extrinsics, intrinsics
300
+
301
+ def _prepare_model_inputs(
302
+ self,
303
+ imgs_cpu: torch.Tensor,
304
+ extrinsics: torch.Tensor | None,
305
+ intrinsics: torch.Tensor | None,
306
+ ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
307
+ """Prepare tensors for model input."""
308
+ device = self._get_model_device()
309
+
310
+ # Move images to model device
311
+ imgs = imgs_cpu.to(device, non_blocking=True)[None].float()
312
+
313
+ # Convert camera parameters to tensors
314
+ ex_t = (
315
+ extrinsics.to(device, non_blocking=True)[None].float()
316
+ if extrinsics is not None
317
+ else None
318
+ )
319
+ in_t = (
320
+ intrinsics.to(device, non_blocking=True)[None].float()
321
+ if intrinsics is not None
322
+ else None
323
+ )
324
+
325
+ return imgs, ex_t, in_t
326
+
327
+ def _normalize_extrinsics(self, ex_t: torch.Tensor | None) -> torch.Tensor | None:
328
+ """Normalize extrinsics"""
329
+ if ex_t is None:
330
+ return None
331
+ transform = affine_inverse(ex_t[:, :1])
332
+ ex_t_norm = ex_t @ transform
333
+ c2ws = affine_inverse(ex_t_norm)
334
+ translations = c2ws[..., :3, 3]
335
+ dists = translations.norm(dim=-1)
336
+ median_dist = torch.median(dists)
337
+ median_dist = torch.clamp(median_dist, min=1e-1)
338
+ ex_t_norm[..., :3, 3] = ex_t_norm[..., :3, 3] / median_dist
339
+ return ex_t_norm
340
+
341
+ def _align_to_input_extrinsics_intrinsics(
342
+ self,
343
+ extrinsics: torch.Tensor | None,
344
+ intrinsics: torch.Tensor | None,
345
+ prediction: Prediction,
346
+ align_to_input_ext_scale: bool = True,
347
+ ransac_view_thresh: int = 10,
348
+ ) -> Prediction:
349
+ """Align depth map to input extrinsics"""
350
+ if extrinsics is None:
351
+ return prediction
352
+ prediction.intrinsics = intrinsics.numpy()
353
+ _, _, scale, aligned_extrinsics = align_poses_umeyama(
354
+ prediction.extrinsics,
355
+ extrinsics.numpy(),
356
+ ransac=len(extrinsics) >= ransac_view_thresh,
357
+ return_aligned=True,
358
+ random_state=42,
359
+ )
360
+ if align_to_input_ext_scale:
361
+ prediction.extrinsics = extrinsics[..., :3, :].numpy()
362
+ prediction.depth /= scale
363
+ if prediction.deformation is not None:
364
+ prediction.deformation /= scale # still buggy because it does not consider rotation
365
+ else:
366
+ prediction.extrinsics = aligned_extrinsics
367
+ return prediction
368
+
369
+ def _run_model_forward(
370
+ self,
371
+ imgs: torch.Tensor,
372
+ ex_t: torch.Tensor | None,
373
+ in_t: torch.Tensor | None,
374
+ export_feat_layers: Sequence[int] | None = None,
375
+ infer_gs: bool = False,
376
+ use_ray_pose: bool = False,
377
+ ref_view_strategy: str = "saddle_balanced",
378
+ ) -> dict[str, torch.Tensor]:
379
+ """Run model forward pass."""
380
+ device = imgs.device
381
+ need_sync = device.type == "cuda"
382
+ if need_sync:
383
+ torch.cuda.synchronize(device)
384
+ start_time = time.time()
385
+ feat_layers = list(export_feat_layers) if export_feat_layers is not None else None
386
+ output = self.forward(imgs, ex_t, in_t, feat_layers, infer_gs, use_ray_pose, ref_view_strategy)
387
+ if need_sync:
388
+ torch.cuda.synchronize(device)
389
+ end_time = time.time()
390
+ logger.info(f"Model Forward Pass Done. Time: {end_time - start_time} seconds")
391
+ return output
392
+
393
+ def _convert_to_prediction(self, raw_output: dict[str, torch.Tensor]) -> Prediction:
394
+ """Convert raw model output to Prediction object."""
395
+ start_time = time.time()
396
+ output = self.output_processor(raw_output)
397
+ end_time = time.time()
398
+ logger.info(f"Conversion to Prediction Done. Time: {end_time - start_time} seconds")
399
+ return output
400
+
401
+ def _add_processed_images(self, prediction: Prediction, imgs_cpu: torch.Tensor) -> Prediction:
402
+ """Add processed images to prediction for visualization."""
403
+ # Convert from (N, 3, H, W) to (N, H, W, 3) and denormalize
404
+ processed_imgs = imgs_cpu.permute(0, 2, 3, 1).cpu().numpy() # (N, H, W, 3)
405
+
406
+ # Denormalize from ImageNet normalization
407
+ mean = np.array([0.485, 0.456, 0.406])
408
+ std = np.array([0.229, 0.224, 0.225])
409
+ processed_imgs = processed_imgs * std + mean
410
+ processed_imgs = np.clip(processed_imgs, 0, 1)
411
+ processed_imgs = (processed_imgs * 255).astype(np.uint8)
412
+
413
+ prediction.processed_images = processed_imgs
414
+ return prediction
415
+
416
+ def _export_results(
417
+ self, prediction: Prediction, export_format: str, export_dir: str, **kwargs
418
+ ) -> None:
419
+ """Export results to specified format and directory."""
420
+ start_time = time.time()
421
+ export(prediction, export_format, export_dir, **kwargs)
422
+ end_time = time.time()
423
+ logger.info(f"Export Results Done. Time: {end_time - start_time} seconds")
424
+
425
+ def _get_model_device(self) -> torch.device:
426
+ """
427
+ Get the device where the model is located.
428
+
429
+ Returns:
430
+ Device where the model parameters are located
431
+
432
+ Raises:
433
+ ValueError: If no tensors are found in the model
434
+ """
435
+ if self.device is not None:
436
+ return self.device
437
+
438
+ # Find device from parameters
439
+ for param in self.parameters():
440
+ self.device = param.device
441
+ return param.device
442
+
443
+ # Find device from buffers
444
+ for buffer in self.buffers():
445
+ self.device = buffer.device
446
+ return buffer.device
447
+
448
+ raise ValueError("No tensor found in model")
src/depth_anything_3/app/css_and_html.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: E501
2
+
3
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ """
18
+ CSS and HTML content for the Depth Anything 3 Gradio application.
19
+ This module contains all the CSS styles and HTML content blocks
20
+ used in the Gradio interface.
21
+ """
22
+
23
+ # CSS Styles for the Gradio interface
24
+ GRADIO_CSS = """
25
+ /* Add Font Awesome CDN with all styles including brands and colors */
26
+ @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');
27
+
28
+ /* Add custom styles for colored icons */
29
+ .fa-color-blue {
30
+ color: #3b82f6;
31
+ }
32
+
33
+ .fa-color-purple {
34
+ color: #8b5cf6;
35
+ }
36
+
37
+ .fa-color-cyan {
38
+ color: #06b6d4;
39
+ }
40
+
41
+ .fa-color-green {
42
+ color: #10b981;
43
+ }
44
+
45
+ .fa-color-yellow {
46
+ color: #f59e0b;
47
+ }
48
+
49
+ .fa-color-red {
50
+ color: #ef4444;
51
+ }
52
+
53
+ .link-btn {
54
+ display: inline-flex;
55
+ align-items: center;
56
+ gap: 8px;
57
+ text-decoration: none;
58
+ padding: 12px 24px;
59
+ border-radius: 50px;
60
+ font-weight: 500;
61
+ transition: all 0.3s ease;
62
+ }
63
+
64
+ /* Dark mode tech theme */
65
+ @media (prefers-color-scheme: dark) {
66
+ html, body {
67
+ background: #1e293b;
68
+ color: #ffffff;
69
+ }
70
+
71
+ .gradio-container {
72
+ background: #1e293b;
73
+ color: #ffffff;
74
+ }
75
+
76
+ .link-btn {
77
+ background: rgba(255, 255, 255, 0.2);
78
+ color: white;
79
+ backdrop-filter: blur(10px);
80
+ border: 1px solid rgba(255, 255, 255, 0.3);
81
+ }
82
+
83
+ .link-btn:hover {
84
+ background: rgba(255, 255, 255, 0.3);
85
+ transform: translateY(-2px);
86
+ box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
87
+ }
88
+
89
+ .tech-bg {
90
+ background: linear-gradient(135deg, #0f172a, #1e293b); /* Darker colors */
91
+ position: relative;
92
+ overflow: hidden;
93
+ }
94
+
95
+ .tech-bg::before {
96
+ content: '';
97
+ position: absolute;
98
+ top: 0;
99
+ left: 0;
100
+ right: 0;
101
+ bottom: 0;
102
+ background:
103
+ radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.15) 0%, transparent 50%), /* Reduced opacity */
104
+ radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.15) 0%, transparent 50%), /* Reduced opacity */
105
+ radial-gradient(circle at 40% 40%, rgba(18, 194, 233, 0.1) 0%, transparent 50%); /* Reduced opacity */
106
+ animation: techPulse 8s ease-in-out infinite;
107
+ }
108
+
109
+ .gradio-container .panel,
110
+ .gradio-container .block,
111
+ .gradio-container .form {
112
+ background: rgba(0, 0, 0, 0.3);
113
+ border: 1px solid rgba(59, 130, 246, 0.2);
114
+ border-radius: 10px;
115
+ }
116
+
117
+ .gradio-container * {
118
+ color: #ffffff;
119
+ }
120
+
121
+ .gradio-container label {
122
+ color: #e0e0e0;
123
+ }
124
+
125
+ .gradio-container .markdown {
126
+ color: #e0e0e0;
127
+ }
128
+ }
129
+
130
+ /* Light mode tech theme */
131
+ @media (prefers-color-scheme: light) {
132
+ html, body {
133
+ background: #ffffff;
134
+ color: #1e293b;
135
+ }
136
+
137
+ .gradio-container {
138
+ background: #ffffff;
139
+ color: #1e293b;
140
+ }
141
+
142
+ .tech-bg {
143
+ background: linear-gradient(135deg, #ffffff, #f1f5f9);
144
+ position: relative;
145
+ overflow: hidden;
146
+ }
147
+
148
+ .link-btn {
149
+ background: rgba(59, 130, 246, 0.15);
150
+ color: var(--body-text-color);
151
+ border: 1px solid rgba(59, 130, 246, 0.3);
152
+ }
153
+
154
+ .link-btn:hover {
155
+ background: rgba(59, 130, 246, 0.25);
156
+ transform: translateY(-2px);
157
+ box-shadow: 0 8px 25px rgba(59, 130, 246, 0.2);
158
+ }
159
+
160
+ .tech-bg::before {
161
+ content: '';
162
+ position: absolute;
163
+ top: 0;
164
+ left: 0;
165
+ right: 0;
166
+ bottom: 0;
167
+ background:
168
+ radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.1) 0%, transparent 50%),
169
+ radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.1) 0%, transparent 50%),
170
+ radial-gradient(circle at 40% 40%, rgba(18, 194, 233, 0.08) 0%, transparent 50%);
171
+ animation: techPulse 8s ease-in-out infinite;
172
+ }
173
+
174
+ .gradio-container .panel,
175
+ .gradio-container .block,
176
+ .gradio-container .form {
177
+ background: rgba(255, 255, 255, 0.8);
178
+ border: 1px solid rgba(59, 130, 246, 0.3);
179
+ border-radius: 10px;
180
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
181
+ }
182
+
183
+ .gradio-container * {
184
+ color: #1e293b;
185
+ }
186
+
187
+ .gradio-container label {
188
+ color: #334155;
189
+ }
190
+
191
+ .gradio-container .markdown {
192
+ color: #334155;
193
+ }
194
+ }
195
+
196
+
197
+
198
+
199
+ @keyframes techPulse {
200
+ 0%, 100% { opacity: 0.5; }
201
+ 50% { opacity: 0.8; }
202
+ }
203
+
204
+ /* Custom log with tech gradient */
205
+ .custom-log * {
206
+ font-style: italic;
207
+ font-size: 22px !important;
208
+ background: linear-gradient(135deg, #3b82f6, #8b5cf6);
209
+ background-size: 400% 400%;
210
+ -webkit-background-clip: text;
211
+ background-clip: text;
212
+ font-weight: bold !important;
213
+ color: transparent !important;
214
+ text-align: center !important;
215
+ animation: techGradient 3s ease infinite;
216
+ }
217
+
218
+ @keyframes techGradient {
219
+ 0% { background-position: 0% 50%; }
220
+ 50% { background-position: 100% 50%; }
221
+ 100% { background-position: 0% 50%; }
222
+ }
223
+
224
+ @keyframes metricPulse {
225
+ 0%, 100% { background-position: 0% 50%; }
226
+ 50% { background-position: 100% 50%; }
227
+ }
228
+
229
+ @keyframes pointcloudPulse {
230
+ 0%, 100% { background-position: 0% 50%; }
231
+ 50% { background-position: 100% 50%; }
232
+ }
233
+
234
+ @keyframes camerasPulse {
235
+ 0%, 100% { background-position: 0% 50%; }
236
+ 50% { background-position: 100% 50%; }
237
+ }
238
+
239
+ @keyframes gaussiansPulse {
240
+ 0%, 100% { background-position: 0% 50%; }
241
+ 50% { background-position: 100% 50%; }
242
+ }
243
+
244
+ /* Special colors for key terms - Global styles */
245
+ .metric-text {
246
+ background: linear-gradient(45deg, #ff6b6b, #ff8e53, #ff6b6b);
247
+ background-size: 200% 200%;
248
+ -webkit-background-clip: text;
249
+ background-clip: text;
250
+ color: transparent !important;
251
+ animation: metricPulse 2s ease-in-out infinite;
252
+ font-weight: 700;
253
+ text-shadow: 0 0 10px rgba(255, 107, 107, 0.5);
254
+ }
255
+
256
+ .pointcloud-text {
257
+ background: linear-gradient(45deg, #4ecdc4, #44a08d, #4ecdc4);
258
+ background-size: 200% 200%;
259
+ -webkit-background-clip: text;
260
+ background-clip: text;
261
+ color: transparent !important;
262
+ animation: pointcloudPulse 2.5s ease-in-out infinite;
263
+ font-weight: 700;
264
+ text-shadow: 0 0 10px rgba(78, 205, 196, 0.5);
265
+ }
266
+
267
+ .cameras-text {
268
+ background: linear-gradient(45deg, #667eea, #764ba2, #667eea);
269
+ background-size: 200% 200%;
270
+ -webkit-background-clip: text;
271
+ background-clip: text;
272
+ color: transparent !important;
273
+ animation: camerasPulse 3s ease-in-out infinite;
274
+ font-weight: 700;
275
+ text-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
276
+ }
277
+
278
+ .gaussians-text {
279
+ background: linear-gradient(45deg, #f093fb, #f5576c, #f093fb);
280
+ background-size: 200% 200%;
281
+ -webkit-background-clip: text;
282
+ background-clip: text;
283
+ color: transparent !important;
284
+ animation: gaussiansPulse 2.2s ease-in-out infinite;
285
+ font-weight: 700;
286
+ text-shadow: 0 0 10px rgba(240, 147, 251, 0.5);
287
+ }
288
+
289
+ .example-log * {
290
+ font-style: italic;
291
+ font-size: 16px !important;
292
+ background: linear-gradient(135deg, #3b82f6, #8b5cf6);
293
+ -webkit-background-clip: text;
294
+ background-clip: text;
295
+ color: transparent !important;
296
+ }
297
+
298
+ #my_radio .wrap {
299
+ display: flex;
300
+ flex-wrap: nowrap;
301
+ justify-content: center;
302
+ align-items: center;
303
+ }
304
+
305
+ #my_radio .wrap label {
306
+ display: flex;
307
+ width: 50%;
308
+ justify-content: center;
309
+ align-items: center;
310
+ margin: 0;
311
+ padding: 10px 0;
312
+ box-sizing: border-box;
313
+ }
314
+
315
+ /* Align navigation buttons with dropdown bottom */
316
+ .navigation-row {
317
+ display: flex !important;
318
+ align-items: flex-end !important;
319
+ gap: 8px !important;
320
+ }
321
+
322
+ .navigation-row > div:nth-child(1),
323
+ .navigation-row > div:nth-child(3) {
324
+ align-self: flex-end !important;
325
+ }
326
+
327
+ .navigation-row > div:nth-child(2) {
328
+ flex: 1 !important;
329
+ }
330
+
331
+ /* Make thumbnails clickable with pointer cursor */
332
+ .clickable-thumbnail img {
333
+ cursor: pointer !important;
334
+ }
335
+
336
+ .clickable-thumbnail:hover img {
337
+ cursor: pointer !important;
338
+ opacity: 0.8;
339
+ transition: opacity 0.3s ease;
340
+ }
341
+
342
+ /* Make thumbnail containers narrower horizontally */
343
+ .clickable-thumbnail {
344
+ padding: 5px 2px !important;
345
+ margin: 0 2px !important;
346
+ }
347
+
348
+ .clickable-thumbnail .image-container {
349
+ margin: 0 !important;
350
+ padding: 0 !important;
351
+ }
352
+
353
+ .scene-info {
354
+ text-align: center !important;
355
+ padding: 5px 2px !important;
356
+ margin: 0 !important;
357
+ }
358
+ """
359
+
360
+
361
+ def get_header_html(logo_base64=None):
362
+ """
363
+ Generate the main header HTML with logo and title.
364
+
365
+ Args:
366
+ logo_base64 (str, optional): Base64 encoded logo image
367
+
368
+ Returns:
369
+ str: HTML string for the header
370
+ """
371
+ return """
372
+ <div class="tech-bg" style="text-align: center; margin-bottom: 5px; padding: 40px 20px; border-radius: 15px; position: relative; overflow: hidden;">
373
+ <div style="position: relative; z-index: 2;">
374
+ <h1 style="margin: 0; font-size: 3.5em; font-weight: 700;
375
+ background: linear-gradient(135deg, #3b82f6, #8b5cf6);
376
+ background-size: 400% 400%;
377
+ -webkit-background-clip: text;
378
+ background-clip: text;
379
+ color: transparent;
380
+ animation: techGradient 3s ease infinite;
381
+ text-shadow: 0 0 30px rgba(59, 130, 246, 0.5);
382
+ letter-spacing: 2px;">
383
+ Depth Anything 3
384
+ </h1>
385
+ <p style="margin: 15px 0 0 0; font-size: 2.16em; font-weight: 300;" class="header-subtitle">
386
+ Recovering the Visual Space from Any Views
387
+ </p>
388
+ <div style="margin-top: 20px;">
389
+ <!-- Revert buttons to original inline styles -->
390
+ <a href="https://depth-anything-3.github.io" target="_blank" class="link-btn">
391
+ <i class="fas fa-globe" style="margin-right: 8px;"></i> Project Page
392
+ </a>
393
+ <a href="https://arxiv.org/abs/2406.09414" target="_blank" class="link-btn">
394
+ <i class="fas fa-file-pdf" style="margin-right: 8px;"></i> Paper
395
+ </a>
396
+ <a href="https://github.com/ByteDance-Seed/Depth-Anything-3" target="_blank" class="link-btn">
397
+ <i class="fab fa-github" style="margin-right: 8px;"></i> Code
398
+ </a>
399
+ </div>
400
+ </div>
401
+ </div>
402
+
403
+ <style>
404
+ /* Ensure tech-bg class is properly applied in dark mode */
405
+ @media (prefers-color-scheme: dark) {
406
+ .header-subtitle {
407
+ color: #cbd5e1;
408
+ }
409
+ /* Increase priority to ensure background color is properly applied */
410
+ .tech-bg {
411
+ background: linear-gradient(135deg, #0f172a, #1e293b) !important;
412
+ }
413
+ }
414
+
415
+ @media (prefers-color-scheme: light) {
416
+ .header-subtitle {
417
+ color: #475569;
418
+ }
419
+ /* Also add explicit background color for light mode */
420
+ .tech-bg {
421
+ background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(139, 92, 246, 0.1) 100%) !important;
422
+ }
423
+ }
424
+ </style>
425
+ """
426
+
427
+
428
+ def get_description_html():
429
+ """
430
+ Generate the main description and getting started HTML.
431
+
432
+ Returns:
433
+ str: HTML string for the description
434
+ """
435
+ return """
436
+ <div class="description-container" style="padding: 25px; border-radius: 15px; margin: 0 0 20px 0;">
437
+ <h2 class="description-title" style="margin-top: 0; font-size: 1.6em; text-align: center;">
438
+ <i class="fas fa-bullseye fa-color-red" style="margin-right: 8px;"></i> What This Demo Does
439
+ </h2>
440
+ <div class="description-content" style="padding: 20px; border-radius: 10px; margin: 15px 0; text-align: center;">
441
+ <p class="description-main" style="line-height: 1.6; margin: 0; font-size: 1.45em;">
442
+ <strong>Upload images or videos</strong> → <strong>Get <span class="metric-text">Metric</span> <span class="pointcloud-text">Point Clouds</span>, <span class="cameras-text">Cameras</span> and <span class="gaussians-text">Novel Views</span></strong> → <strong>Explore in 3D</strong>
443
+ </p>
444
+ </div>
445
+
446
+ <div style="text-align: center; margin-top: 15px;">
447
+ <p class="description-tip" style="font-style: italic; margin: 0;">
448
+ <i class="fas fa-lightbulb fa-color-yellow" style="margin-right: 8px;"></i> <strong>Tip:</strong> Landscape-oriented images or videos are preferred for best 3D recovering.
449
+ </p>
450
+ </div>
451
+ </div>
452
+
453
+ <style>
454
+ @media (prefers-color-scheme: dark) {
455
+ .description-container {
456
+ background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(139, 92, 246, 0.1) 100%);
457
+ border: 1px solid rgba(59, 130, 246, 0.2);
458
+ }
459
+ .description-title { color: #3b82f6; }
460
+ .description-content { background: rgba(0, 0, 0, 0.3); }
461
+ .description-main { color: #e0e0e0; }
462
+ .description-text { color: #cbd5e1; }
463
+ .description-tip { color: #cbd5e1; }
464
+ }
465
+
466
+ @media (prefers-color-scheme: light) {
467
+ .description-container {
468
+ background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(139, 92, 246, 0.05) 100%);
469
+ border: 1px solid rgba(59, 130, 246, 0.3);
470
+ }
471
+ .description-title { color: #3b82f6; }
472
+ .description-content { background: transparent; }
473
+ .description-main { color: #1e293b; }
474
+ .description-text { color: #475569; }
475
+ .description-tip { color: #475569; }
476
+ }
477
+ </style>
478
+ """
479
+
480
+
481
+ def get_acknowledgements_html():
482
+ """
483
+ Generate the acknowledgements section HTML.
484
+
485
+ Returns:
486
+ str: HTML string for the acknowledgements
487
+ """
488
+ return """
489
+ <div style="background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(139, 92, 246, 0.1) 100%);
490
+ padding: 25px; border-radius: 15px; margin: 20px 0; border: 1px solid rgba(59, 130, 246, 0.2);">
491
+ <h3 style="color: #3b82f6; margin-top: 0; text-align: center; font-size: 1.4em;">
492
+ <i class="fas fa-trophy fa-color-yellow" style="margin-right: 8px;"></i> Research Credits & Acknowledgments
493
+ </h3>
494
+
495
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 15px 0;">
496
+ <!-- Original Research Section (Left) -->
497
+ <div style="text-align: center;">
498
+ <h4 style="color: #8b5cf6; margin: 10px 0;"><i class="fas fa-flask fa-color-green" style="margin-right: 8px;"></i> Original Research</h4>
499
+ <p style="color: #e0e0e0; margin: 5px 0;">
500
+ <a href="https://depth-anything-3.github.io" target="_blank"
501
+ style="color: #3b82f6; text-decoration: none; font-weight: 600;">
502
+ Depth Anything 3
503
+ </a>
504
+ </p>
505
+ </div>
506
+
507
+ <!-- Previous Versions Section (Right) -->
508
+ <div style="text-align: center;">
509
+ <h4 style="color: #8b5cf6; margin: 10px 0;"><i class="fas fa-history fa-color-blue" style="margin-right: 8px;"></i> Previous Versions</h4>
510
+ <div style="display: flex; flex-direction: row; gap: 15px; justify-content: center; align-items: center;">
511
+ <p style="color: #e0e0e0; margin: 0;">
512
+ <a href="https://huggingface.co/spaces/LiheYoung/Depth-Anything" target="_blank"
513
+ style="color: #3b82f6; text-decoration: none; font-weight: 600;">
514
+ Depth-Anything
515
+ </a>
516
+ </p>
517
+ <span style="color: #e0e0e0;">•</span>
518
+ <p style="color: #e0e0e0; margin: 0;">
519
+ <a href="https://huggingface.co/spaces/depth-anything/Depth-Anything-V2" target="_blank"
520
+ style="color: #3b82f6; text-decoration: none; font-weight: 600;">
521
+ Depth-Anything-V2
522
+ </a>
523
+ </p>
524
+ </div>
525
+ </div>
526
+ </div>
527
+
528
+ <!-- HF Demo Adapted from - Centered at the bottom of the whole block -->
529
+ <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid rgba(59, 130, 246, 0.3); text-align: center;">
530
+ <p style="color: #a0a0a0; font-size: 0.9em; margin: 0;">
531
+ <i class="fas fa-code-branch fa-color-gray" style="margin-right: 5px;"></i> HF demo adapted from <a href="https://huggingface.co/spaces/facebook/map-anything" target="_blank" style="color: inherit; text-decoration: none;">Map Anything</a>
532
+ </p>
533
+ </div>
534
+ </div>
535
+ """
536
+
537
+
538
+ def get_gradio_theme():
539
+ """
540
+ Get the configured Gradio theme with adaptive tech colors.
541
+
542
+ Returns:
543
+ gr.themes.Base: Configured Gradio theme
544
+ """
545
+ import gradio as gr
546
+
547
+ return gr.themes.Base(
548
+ primary_hue=gr.themes.Color(
549
+ c50="#eff6ff",
550
+ c100="#dbeafe",
551
+ c200="#bfdbfe",
552
+ c300="#93c5fd",
553
+ c400="#60a5fa",
554
+ c500="#3b82f6",
555
+ c600="#2563eb",
556
+ c700="#1d4ed8",
557
+ c800="#1e40af",
558
+ c900="#1e3a8a",
559
+ c950="#172554",
560
+ ),
561
+ secondary_hue=gr.themes.Color(
562
+ c50="#f5f3ff",
563
+ c100="#ede9fe",
564
+ c200="#ddd6fe",
565
+ c300="#c4b5fd",
566
+ c400="#a78bfa",
567
+ c500="#8b5cf6",
568
+ c600="#7c3aed",
569
+ c700="#6d28d9",
570
+ c800="#5b21b6",
571
+ c900="#4c1d95",
572
+ c950="#2e1065",
573
+ ),
574
+ neutral_hue=gr.themes.Color(
575
+ c50="#f8fafc",
576
+ c100="#f1f5f9",
577
+ c200="#e2e8f0",
578
+ c300="#cbd5e1",
579
+ c400="#94a3b8",
580
+ c500="#64748b",
581
+ c600="#475569",
582
+ c700="#334155",
583
+ c800="#1e293b",
584
+ c900="#0f172a",
585
+ c950="#020617",
586
+ ),
587
+ )
588
+
589
+
590
+ # Measure tab instructions HTML
591
+ MEASURE_INSTRUCTIONS_HTML = """
592
+ ### Click points on the image to compute distance.
593
+ > <i class="fas fa-triangle-exclamation fa-color-red" style="margin-right: 5px;"></i> Metric scale estimation is difficult on aerial/drone images.
594
+ """
src/depth_anything_3/app/gradio_app.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Refactored Gradio App for Depth Anything 3.
17
+
18
+ This is the main application file that orchestrates all components.
19
+ The original functionality has been split into modular components for better maintainability.
20
+ """
21
+
22
+ import argparse
23
+ import os
24
+ from typing import Any, Dict, List
25
+ import gradio as gr
26
+
27
+ from depth_anything_3.app.css_and_html import GRADIO_CSS, get_gradio_theme
28
+ from depth_anything_3.app.modules.event_handlers import EventHandlers
29
+ from depth_anything_3.app.modules.ui_components import UIComponents
30
+
31
+ # Set environment variables
32
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
33
+
34
+
35
+ class DepthAnything3App:
36
+ """
37
+ Main application class for Depth Anything 3 Gradio app.
38
+ """
39
+
40
+ def __init__(self, model_dir: str = None, workspace_dir: str = None, gallery_dir: str = None):
41
+ """
42
+ Initialize the application.
43
+
44
+ Args:
45
+ model_dir: Path to the model directory
46
+ workspace_dir: Path to the workspace directory
47
+ gallery_dir: Path to the gallery directory
48
+ """
49
+ self.model_dir = model_dir
50
+ self.workspace_dir = workspace_dir
51
+ self.gallery_dir = gallery_dir
52
+
53
+ # Set environment variables for directories
54
+ if self.model_dir:
55
+ os.environ["DA3_MODEL_DIR"] = self.model_dir
56
+ if self.workspace_dir:
57
+ os.environ["DA3_WORKSPACE_DIR"] = self.workspace_dir
58
+ if self.gallery_dir:
59
+ os.environ["DA3_GALLERY_DIR"] = self.gallery_dir
60
+
61
+ self.event_handlers = EventHandlers()
62
+ self.ui_components = UIComponents()
63
+
64
+ def cache_examples(
65
+ self,
66
+ show_cam: bool = True,
67
+ filter_black_bg: bool = False,
68
+ filter_white_bg: bool = False,
69
+ save_percentage: float = 20.0,
70
+ num_max_points: int = 1000,
71
+ cache_gs_tag: str = "",
72
+ gs_trj_mode: str = "smooth",
73
+ gs_video_quality: str = "low",
74
+ ) -> None:
75
+ """
76
+ Pre-cache all example scenes at startup.
77
+
78
+ Args:
79
+ show_cam: Whether to show camera in visualization
80
+ filter_black_bg: Whether to filter black background
81
+ filter_white_bg: Whether to filter white background
82
+ save_percentage: Filter percentage for point cloud
83
+ num_max_points: Maximum number of points
84
+ cache_gs_tag: Tag to match scene names for high-res+3DGS caching (e.g., "dl3dv")
85
+ gs_trj_mode: Trajectory mode for 3DGS
86
+ gs_video_quality: Video quality for 3DGS
87
+ """
88
+ from depth_anything_3.app.modules.utils import get_scene_info
89
+
90
+ examples_dir = os.path.join(self.workspace_dir, "examples")
91
+ if not os.path.exists(examples_dir):
92
+ print(f"Examples directory not found: {examples_dir}")
93
+ return
94
+
95
+ scenes = get_scene_info(examples_dir)
96
+ if not scenes:
97
+ print("No example scenes found to cache.")
98
+ return
99
+
100
+ print(f"\n{'='*60}")
101
+ print(f"Caching {len(scenes)} example scenes...")
102
+ print(f"{'='*60}\n")
103
+
104
+ for i, scene in enumerate(scenes, 1):
105
+ scene_name = scene["name"]
106
+
107
+ # Check if scene name matches the gs tag for high-res+3DGS caching
108
+ use_high_res_gs = cache_gs_tag and cache_gs_tag.lower() in scene_name.lower()
109
+
110
+ if use_high_res_gs:
111
+ print(f"[{i}/{len(scenes)}] Caching scene: {scene_name} (HIGH-RES + 3DGS)")
112
+ print(f" - Number of images: {scene['num_images']}")
113
+ print(f" - Matched tag: '{cache_gs_tag}' - using high_res + 3DGS")
114
+ else:
115
+ print(f"[{i}/{len(scenes)}] Caching scene: {scene_name} (LOW-RES)")
116
+ print(f" - Number of images: {scene['num_images']}")
117
+
118
+ try:
119
+ # Load example scene
120
+ _, target_dir, _, _, _, _, _, _, _ = self.event_handlers.load_example_scene(
121
+ scene_name
122
+ )
123
+
124
+ if target_dir and target_dir != "None":
125
+ # Run reconstruction with appropriate settings
126
+ print(" - Running reconstruction...")
127
+ result = self.event_handlers.gradio_demo(
128
+ target_dir=target_dir,
129
+ show_cam=show_cam,
130
+ filter_black_bg=filter_black_bg,
131
+ filter_white_bg=filter_white_bg,
132
+ process_res_method="high_res" if use_high_res_gs else "low_res",
133
+ save_percentage=save_percentage,
134
+ num_max_points=num_max_points,
135
+ infer_gs=use_high_res_gs,
136
+ ref_view_strategy="saddle_balanced",
137
+ gs_trj_mode=gs_trj_mode,
138
+ gs_video_quality=gs_video_quality,
139
+ )
140
+
141
+ # Check if successful
142
+ if result[0] is not None: # reconstruction_output
143
+ print(f" ✓ Scene '{scene_name}' cached successfully")
144
+ else:
145
+ print(f" ✗ Scene '{scene_name}' caching failed: {result[1]}")
146
+ else:
147
+ print(f" ✗ Scene '{scene_name}' loading failed")
148
+
149
+ except Exception as e:
150
+ print(f" ✗ Error caching scene '{scene_name}': {str(e)}")
151
+
152
+ print()
153
+
154
+ print("=" * 60)
155
+ print("Example scene caching completed!")
156
+ print("=" * 60 + "\n")
157
+
158
+ def create_app(self) -> gr.Blocks:
159
+ """
160
+ Create and configure the Gradio application.
161
+
162
+ Returns:
163
+ Configured Gradio Blocks interface
164
+ """
165
+
166
+ # Initialize theme
167
+ def get_theme():
168
+ return get_gradio_theme()
169
+
170
+ with gr.Blocks(theme=get_theme(), css=GRADIO_CSS) as demo:
171
+ # State variables for the tabbed interface
172
+ is_example = gr.Textbox(label="is_example", visible=False, value="None")
173
+ processed_data_state = gr.State(value=None)
174
+ measure_points_state = gr.State(value=[])
175
+ selected_image_index_state = gr.State(value=0) # Track selected image index
176
+ # current_view_index = gr.State(value=0) # noqa: F841 Track current view index
177
+
178
+ # Header and description
179
+ self.ui_components.create_header_section()
180
+ self.ui_components.create_description_section()
181
+
182
+ target_dir_output = gr.Textbox(label="Target Dir", visible=False, value="None")
183
+
184
+ # Main content area
185
+ with gr.Row():
186
+ with gr.Column(scale=2):
187
+ # Upload section
188
+ (
189
+ input_video,
190
+ s_time_interval,
191
+ input_images,
192
+ image_gallery,
193
+ ) = self.ui_components.create_upload_section()
194
+
195
+ with gr.Column(scale=4):
196
+ with gr.Column():
197
+ # gr.Markdown("**Metric 3D Reconstruction (Point Cloud and Camera Poses)**")
198
+ # Reconstruction control section (buttons) - moved below tabs
199
+
200
+ log_output = gr.Markdown(
201
+ "Please upload a video or images, then click Reconstruct.",
202
+ elem_classes=["custom-log"],
203
+ )
204
+
205
+ # Tabbed interface
206
+ with gr.Tabs():
207
+ with gr.Tab("Point Cloud & Cameras"):
208
+ reconstruction_output = (
209
+ self.ui_components.create_3d_viewer_section()
210
+ )
211
+
212
+ with gr.Tab("Metric Depth"):
213
+ (
214
+ prev_measure_btn,
215
+ measure_view_selector,
216
+ next_measure_btn,
217
+ measure_image,
218
+ measure_depth_image,
219
+ measure_text,
220
+ ) = self.ui_components.create_measure_section()
221
+
222
+ with gr.Tab("3DGS Rendered Novel Views"):
223
+ gs_video, gs_info = self.ui_components.create_nvs_video()
224
+
225
+ # Inference control section (before inference)
226
+ (process_res_method_dropdown, infer_gs, ref_view_strategy_dropdown) = (
227
+ self.ui_components.create_inference_control_section()
228
+ )
229
+
230
+ # Display control section - includes 3DGS options, buttons, and Visualization Options # noqa: E501
231
+ (
232
+ show_cam,
233
+ filter_black_bg,
234
+ filter_white_bg,
235
+ save_percentage,
236
+ num_max_points,
237
+ gs_trj_mode,
238
+ gs_video_quality,
239
+ submit_btn,
240
+ clear_btn,
241
+ ) = self.ui_components.create_display_control_section()
242
+
243
+ # bind visibility of gs_trj_mode to infer_gs
244
+ infer_gs.change(
245
+ fn=lambda checked: (
246
+ gr.update(visible=checked),
247
+ gr.update(visible=checked),
248
+ gr.update(visible=checked),
249
+ gr.update(visible=(not checked)),
250
+ ),
251
+ inputs=infer_gs,
252
+ outputs=[gs_trj_mode, gs_video_quality, gs_video, gs_info],
253
+ )
254
+
255
+ # Example scenes section
256
+ gr.Markdown("## Example Scenes")
257
+
258
+ scenes = self.ui_components.create_example_scenes_section()
259
+ scene_components = self.ui_components.create_example_scene_grid(scenes)
260
+
261
+ # Set up event handlers
262
+ self._setup_event_handlers(
263
+ demo,
264
+ is_example,
265
+ processed_data_state,
266
+ measure_points_state,
267
+ target_dir_output,
268
+ input_video,
269
+ input_images,
270
+ s_time_interval,
271
+ image_gallery,
272
+ reconstruction_output,
273
+ log_output,
274
+ show_cam,
275
+ filter_black_bg,
276
+ filter_white_bg,
277
+ process_res_method_dropdown,
278
+ save_percentage,
279
+ submit_btn,
280
+ clear_btn,
281
+ num_max_points,
282
+ infer_gs,
283
+ ref_view_strategy_dropdown,
284
+ selected_image_index_state,
285
+ measure_view_selector,
286
+ measure_image,
287
+ measure_depth_image,
288
+ measure_text,
289
+ prev_measure_btn,
290
+ next_measure_btn,
291
+ scenes,
292
+ scene_components,
293
+ gs_video,
294
+ gs_info,
295
+ gs_trj_mode,
296
+ gs_video_quality,
297
+ )
298
+
299
+ # Acknowledgements
300
+ self.ui_components.create_acknowledgements_section()
301
+
302
+ return demo
303
+
304
+ def _setup_event_handlers(
305
+ self,
306
+ demo: gr.Blocks,
307
+ is_example: gr.Textbox,
308
+ processed_data_state: gr.State,
309
+ measure_points_state: gr.State,
310
+ target_dir_output: gr.Textbox,
311
+ input_video: gr.Video,
312
+ input_images: gr.File,
313
+ s_time_interval: gr.Slider,
314
+ image_gallery: gr.Gallery,
315
+ reconstruction_output: gr.Model3D,
316
+ log_output: gr.Markdown,
317
+ show_cam: gr.Checkbox,
318
+ filter_black_bg: gr.Checkbox,
319
+ filter_white_bg: gr.Checkbox,
320
+ process_res_method_dropdown: gr.Dropdown,
321
+ save_percentage: gr.Slider,
322
+ submit_btn: gr.Button,
323
+ clear_btn: gr.ClearButton,
324
+ num_max_points: gr.Slider,
325
+ infer_gs: gr.Checkbox,
326
+ ref_view_strategy_dropdown: gr.Dropdown,
327
+ selected_image_index_state: gr.State,
328
+ measure_view_selector: gr.Dropdown,
329
+ measure_image: gr.Image,
330
+ measure_depth_image: gr.Image,
331
+ measure_text: gr.Markdown,
332
+ prev_measure_btn: gr.Button,
333
+ next_measure_btn: gr.Button,
334
+ scenes: List[Dict[str, Any]],
335
+ scene_components: List[gr.Image],
336
+ gs_video: gr.Video,
337
+ gs_info: gr.Markdown,
338
+ gs_trj_mode: gr.Dropdown,
339
+ gs_video_quality: gr.Dropdown,
340
+ ) -> None:
341
+ """
342
+ Set up all event handlers for the application.
343
+
344
+ Args:
345
+ demo: Gradio Blocks interface
346
+ All other arguments: Gradio components to connect
347
+ """
348
+ # Configure clear button
349
+ clear_btn.add(
350
+ [
351
+ input_video,
352
+ input_images,
353
+ reconstruction_output,
354
+ log_output,
355
+ target_dir_output,
356
+ image_gallery,
357
+ gs_video,
358
+ ]
359
+ )
360
+
361
+ # Main reconstruction button
362
+ submit_btn.click(
363
+ fn=self.event_handlers.clear_fields, inputs=[], outputs=[reconstruction_output]
364
+ ).then(fn=self.event_handlers.update_log, inputs=[], outputs=[log_output]).then(
365
+ fn=self.event_handlers.gradio_demo,
366
+ inputs=[
367
+ target_dir_output,
368
+ show_cam,
369
+ filter_black_bg,
370
+ filter_white_bg,
371
+ process_res_method_dropdown,
372
+ save_percentage,
373
+ # pass num_max_points
374
+ num_max_points,
375
+ infer_gs,
376
+ ref_view_strategy_dropdown,
377
+ gs_trj_mode,
378
+ gs_video_quality,
379
+ ],
380
+ outputs=[
381
+ reconstruction_output,
382
+ log_output,
383
+ processed_data_state,
384
+ measure_image,
385
+ measure_depth_image,
386
+ measure_text,
387
+ measure_view_selector,
388
+ gs_video,
389
+ gs_video, # gs_video visibility
390
+ gs_info, # gs_info visibility
391
+ ],
392
+ ).then(
393
+ fn=lambda: "False",
394
+ inputs=[],
395
+ outputs=[is_example], # set is_example to "False"
396
+ )
397
+
398
+ # Real-time visualization updates
399
+ self._setup_visualization_handlers(
400
+ show_cam,
401
+ filter_black_bg,
402
+ filter_white_bg,
403
+ process_res_method_dropdown,
404
+ target_dir_output,
405
+ is_example,
406
+ reconstruction_output,
407
+ log_output,
408
+ )
409
+
410
+ # File upload handlers
411
+ input_video.change(
412
+ fn=self.event_handlers.handle_uploads,
413
+ inputs=[input_video, input_images, s_time_interval],
414
+ outputs=[reconstruction_output, target_dir_output, image_gallery, log_output],
415
+ )
416
+ input_images.change(
417
+ fn=self.event_handlers.handle_uploads,
418
+ inputs=[input_video, input_images, s_time_interval],
419
+ outputs=[reconstruction_output, target_dir_output, image_gallery, log_output],
420
+ )
421
+
422
+ # Navigation handlers
423
+ self._setup_navigation_handlers(
424
+ prev_measure_btn,
425
+ next_measure_btn,
426
+ measure_view_selector,
427
+ measure_image,
428
+ measure_depth_image,
429
+ measure_points_state,
430
+ processed_data_state,
431
+ )
432
+
433
+ # Measurement handler
434
+ measure_image.select(
435
+ fn=self.event_handlers.measure,
436
+ inputs=[processed_data_state, measure_points_state, measure_view_selector],
437
+ outputs=[measure_image, measure_depth_image, measure_points_state, measure_text],
438
+ )
439
+
440
+ # Example scene handlers
441
+ self._setup_example_scene_handlers(
442
+ scenes,
443
+ scene_components,
444
+ reconstruction_output,
445
+ target_dir_output,
446
+ image_gallery,
447
+ log_output,
448
+ is_example,
449
+ processed_data_state,
450
+ measure_view_selector,
451
+ measure_image,
452
+ measure_depth_image,
453
+ gs_video,
454
+ gs_info,
455
+ )
456
+
457
+ def _setup_visualization_handlers(
458
+ self,
459
+ show_cam: gr.Checkbox,
460
+ filter_black_bg: gr.Checkbox,
461
+ filter_white_bg: gr.Checkbox,
462
+ process_res_method_dropdown: gr.Dropdown,
463
+ target_dir_output: gr.Textbox,
464
+ is_example: gr.Textbox,
465
+ reconstruction_output: gr.Model3D,
466
+ log_output: gr.Markdown,
467
+ ) -> None:
468
+ """Set up visualization update handlers."""
469
+ # Common inputs for visualization updates
470
+ viz_inputs = [
471
+ target_dir_output,
472
+ show_cam,
473
+ is_example,
474
+ filter_black_bg,
475
+ filter_white_bg,
476
+ process_res_method_dropdown,
477
+ ]
478
+
479
+ # Set up change handlers for all visualization controls
480
+ for component in [show_cam, filter_black_bg, filter_white_bg]:
481
+ component.change(
482
+ fn=self.event_handlers.update_visualization,
483
+ inputs=viz_inputs,
484
+ outputs=[reconstruction_output, log_output],
485
+ )
486
+
487
+ def _setup_navigation_handlers(
488
+ self,
489
+ prev_measure_btn: gr.Button,
490
+ next_measure_btn: gr.Button,
491
+ measure_view_selector: gr.Dropdown,
492
+ measure_image: gr.Image,
493
+ measure_depth_image: gr.Image,
494
+ measure_points_state: gr.State,
495
+ processed_data_state: gr.State,
496
+ ) -> None:
497
+ """Set up navigation handlers for measure tab."""
498
+ # Measure tab navigation
499
+ prev_measure_btn.click(
500
+ fn=lambda processed_data, current_selector: self.event_handlers.navigate_measure_view(
501
+ processed_data, current_selector, -1
502
+ ),
503
+ inputs=[processed_data_state, measure_view_selector],
504
+ outputs=[
505
+ measure_view_selector,
506
+ measure_image,
507
+ measure_depth_image,
508
+ measure_points_state,
509
+ ],
510
+ )
511
+
512
+ next_measure_btn.click(
513
+ fn=lambda processed_data, current_selector: self.event_handlers.navigate_measure_view(
514
+ processed_data, current_selector, 1
515
+ ),
516
+ inputs=[processed_data_state, measure_view_selector],
517
+ outputs=[
518
+ measure_view_selector,
519
+ measure_image,
520
+ measure_depth_image,
521
+ measure_points_state,
522
+ ],
523
+ )
524
+
525
+ measure_view_selector.change(
526
+ fn=lambda processed_data, selector_value: (
527
+ self.event_handlers.update_measure_view(
528
+ processed_data, int(selector_value.split()[1]) - 1
529
+ )
530
+ if selector_value
531
+ else (None, None, [])
532
+ ),
533
+ inputs=[processed_data_state, measure_view_selector],
534
+ outputs=[measure_image, measure_depth_image, measure_points_state],
535
+ )
536
+
537
+ def _setup_example_scene_handlers(
538
+ self,
539
+ scenes: List[Dict[str, Any]],
540
+ scene_components: List[gr.Image],
541
+ reconstruction_output: gr.Model3D,
542
+ target_dir_output: gr.Textbox,
543
+ image_gallery: gr.Gallery,
544
+ log_output: gr.Markdown,
545
+ is_example: gr.Textbox,
546
+ processed_data_state: gr.State,
547
+ measure_view_selector: gr.Dropdown,
548
+ measure_image: gr.Image,
549
+ measure_depth_image: gr.Image,
550
+ gs_video: gr.Video,
551
+ gs_info: gr.Markdown,
552
+ ) -> None:
553
+ """Set up example scene handlers."""
554
+
555
+ def load_and_update_measure(name):
556
+ result = self.event_handlers.load_example_scene(name)
557
+ # result = (reconstruction_output, target_dir, image_paths, log_message, processed_data, measure_view_selector, gs_video, gs_video_vis, gs_info_vis) # noqa: E501
558
+
559
+ # Update measure view if processed_data is available
560
+ measure_img = None
561
+ measure_depth = None
562
+ if result[4] is not None: # processed_data exists
563
+ measure_img, measure_depth, _ = (
564
+ self.event_handlers.visualization_handler.update_measure_view(result[4], 0)
565
+ )
566
+
567
+ return result + ("True", measure_img, measure_depth)
568
+
569
+ for i, scene in enumerate(scenes):
570
+ if i < len(scene_components):
571
+ scene_components[i].select(
572
+ fn=lambda name=scene["name"]: load_and_update_measure(name),
573
+ outputs=[
574
+ reconstruction_output,
575
+ target_dir_output,
576
+ image_gallery,
577
+ log_output,
578
+ processed_data_state,
579
+ measure_view_selector,
580
+ gs_video,
581
+ gs_video, # gs_video_visibility
582
+ gs_info, # gs_info_visibility
583
+ is_example,
584
+ measure_image,
585
+ measure_depth_image,
586
+ ],
587
+ )
588
+
589
+ def launch(self, host: str = "127.0.0.1", port: int = 7860, **kwargs) -> None:
590
+ """
591
+ Launch the application.
592
+
593
+ Args:
594
+ host: Host address to bind to
595
+ port: Port number to bind to
596
+ **kwargs: Additional arguments for demo.launch()
597
+ """
598
+ demo = self.create_app()
599
+ demo.queue(max_size=20).launch(
600
+ show_error=True, ssr_mode=False, server_name=host, server_port=port, **kwargs
601
+ )
602
+
603
+
604
+ def main():
605
+ """Main function to run the application."""
606
+ parser = argparse.ArgumentParser(
607
+ description="Depth Anything 3 Gradio Application",
608
+ formatter_class=argparse.RawDescriptionHelpFormatter,
609
+ epilog="""
610
+ Examples:
611
+ # Basic usage
612
+ python gradio_app.py --help
613
+ python gradio_app.py --host 0.0.0.0 --port 8080
614
+ python gradio_app.py --model-dir /path/to/model --workspace-dir /path/to/workspace
615
+
616
+ # Cache examples at startup (all low-res)
617
+ python gradio_app.py --cache-examples
618
+
619
+ # Cache with selective high-res+3DGS for scenes matching tag
620
+ python gradio_app.py --cache-examples --cache-gs-tag dl3dv
621
+ # This will use high-res + 3DGS for scenes containing "dl3dv" in their name,
622
+ # and low-res only for other scenes
623
+ """,
624
+ )
625
+
626
+ # Server configuration
627
+ parser.add_argument(
628
+ "--host", default="127.0.0.1", help="Host address to bind to (default: 127.0.0.1)"
629
+ )
630
+ parser.add_argument(
631
+ "--port", type=int, default=7860, help="Port number to bind to (default: 7860)"
632
+ )
633
+
634
+ # Directory configuration
635
+ parser.add_argument(
636
+ "--model-dir",
637
+ default="depth-anything/DA3NESTED-GIANT-LARGE",
638
+ help="Path to the model directory (default: depth-anything/DA3NESTED-GIANT-LARGE)",
639
+ )
640
+ parser.add_argument(
641
+ "--workspace-dir",
642
+ default="workspace/gradio", # noqa: E501
643
+ help="Path to the workspace directory (default: workspace/gradio)", # noqa: E501
644
+ )
645
+ parser.add_argument(
646
+ "--gallery-dir",
647
+ default="workspace/gallery",
648
+ help="Path to the gallery directory (default: workspace/gallery)", # noqa: E501
649
+ )
650
+
651
+ # Additional Gradio options
652
+ parser.add_argument("--share", action="store_true", help="Create a public link for the app")
653
+ parser.add_argument("--debug", action="store_true", help="Enable debug mode")
654
+
655
+ # Example caching options
656
+ parser.add_argument(
657
+ "--cache-examples",
658
+ action="store_true",
659
+ help="Pre-cache all example scenes at startup for faster loading",
660
+ )
661
+ parser.add_argument(
662
+ "--cache-gs-tag",
663
+ type=str,
664
+ default="",
665
+ help="Tag to match scene names for high-res+3DGS caching (e.g., 'dl3dv'). Scenes containing this tag will use high_res and infer_gs=True; others will use low_res only.", # noqa: E501
666
+ )
667
+
668
+ args = parser.parse_args()
669
+
670
+ # Create directories if they don't exist
671
+ os.makedirs(args.workspace_dir, exist_ok=True)
672
+ os.makedirs(args.gallery_dir, exist_ok=True)
673
+
674
+ # Initialize and launch the application
675
+ app = DepthAnything3App(
676
+ model_dir=args.model_dir, workspace_dir=args.workspace_dir, gallery_dir=args.gallery_dir
677
+ )
678
+
679
+ # Prepare launch arguments
680
+ launch_kwargs = {"share": args.share, "debug": args.debug}
681
+
682
+ print("Starting Depth Anything 3 Gradio App...")
683
+ print(f"Host: {args.host}")
684
+ print(f"Port: {args.port}")
685
+ print(f"Model Directory: {args.model_dir}")
686
+ print(f"Workspace Directory: {args.workspace_dir}")
687
+ print(f"Gallery Directory: {args.gallery_dir}")
688
+ print(f"Share: {args.share}")
689
+ print(f"Debug: {args.debug}")
690
+ print(f"Cache Examples: {args.cache_examples}")
691
+ if args.cache_examples:
692
+ if args.cache_gs_tag:
693
+ print(
694
+ f"Cache GS Tag: '{args.cache_gs_tag}' (scenes matching this tag will use high-res + 3DGS)" # noqa: E501
695
+ ) # noqa: E501
696
+ else:
697
+ print("Cache GS Tag: None (all scenes will use low-res only)")
698
+
699
+ # Pre-cache examples if requested
700
+ if args.cache_examples:
701
+ print("\n" + "=" * 60)
702
+ print("Pre-caching mode enabled")
703
+ if args.cache_gs_tag:
704
+ print(f"Scenes containing '{args.cache_gs_tag}' will use HIGH-RES + 3DGS")
705
+ print("Other scenes will use LOW-RES only")
706
+ else:
707
+ print("All scenes will use LOW-RES only")
708
+ print("=" * 60)
709
+ app.cache_examples(
710
+ show_cam=True,
711
+ filter_black_bg=False,
712
+ filter_white_bg=False,
713
+ save_percentage=5.0,
714
+ num_max_points=1000,
715
+ cache_gs_tag=args.cache_gs_tag,
716
+ gs_trj_mode="smooth",
717
+ gs_video_quality="low",
718
+ )
719
+
720
+ app.launch(host=args.host, port=args.port, **launch_kwargs)
721
+
722
+
723
+ if __name__ == "__main__":
724
+ main()
src/depth_anything_3/app/modules/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Modules package for Depth Anything 3 Gradio app.
17
+
18
+ This package contains all the modular components for the Gradio application.
19
+ """
20
+
21
+ from depth_anything_3.app.modules.event_handlers import EventHandlers
22
+ from depth_anything_3.app.modules.file_handlers import FileHandler
23
+ from depth_anything_3.app.modules.model_inference import ModelInference
24
+ from depth_anything_3.app.modules.ui_components import UIComponents
25
+ from depth_anything_3.app.modules.utils import (
26
+ create_depth_visualization,
27
+ get_logo_base64,
28
+ get_scene_info,
29
+ save_to_gallery_func,
30
+ )
31
+ from depth_anything_3.app.modules.visualization import VisualizationHandler
32
+
33
+ __all__ = [
34
+ "ModelInference",
35
+ "FileHandler",
36
+ "VisualizationHandler",
37
+ "EventHandlers",
38
+ "UIComponents",
39
+ "create_depth_visualization",
40
+ "save_to_gallery_func",
41
+ "get_scene_info",
42
+ "get_logo_base64",
43
+ ]
src/depth_anything_3/app/modules/event_handlers.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Event handling module for Depth Anything 3 Gradio app.
17
+
18
+ This module handles all event callbacks and user interactions.
19
+ """
20
+
21
+ import os
22
+ import time
23
+ from glob import glob
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+ import gradio as gr
26
+ import numpy as np
27
+ import torch
28
+
29
+ from depth_anything_3.app.modules.file_handlers import FileHandler
30
+ from depth_anything_3.app.modules.model_inference import ModelInference
31
+ from depth_anything_3.utils.memory import cleanup_cuda_memory
32
+ from depth_anything_3.app.modules.visualization import VisualizationHandler
33
+
34
+
35
+ class EventHandlers:
36
+ """
37
+ Handles all event callbacks and user interactions for the Gradio app.
38
+ """
39
+
40
+ def __init__(self):
41
+ """Initialize the event handlers."""
42
+ self.model_inference = ModelInference()
43
+ self.file_handler = FileHandler()
44
+ self.visualization_handler = VisualizationHandler()
45
+
46
+ def clear_fields(self) -> None:
47
+ """
48
+ Clears the 3D viewer, the stored target_dir, and empties the gallery.
49
+ """
50
+ return None
51
+
52
+ def update_log(self) -> str:
53
+ """
54
+ Display a quick log message while waiting.
55
+ """
56
+ return "Loading and Reconstructing..."
57
+
58
+ def save_current_visualization(
59
+ self,
60
+ target_dir: str,
61
+ save_percentage: float,
62
+ show_cam: bool,
63
+ filter_black_bg: bool,
64
+ filter_white_bg: bool,
65
+ processed_data: Optional[Dict],
66
+ scene_name: str = "",
67
+ ) -> str:
68
+ """
69
+ Save current visualization results to gallery with specified save percentage.
70
+
71
+ Args:
72
+ target_dir: Directory containing results
73
+ save_percentage: Percentage of points to save (0-100)
74
+ show_cam: Whether to show cameras
75
+ filter_black_bg: Whether to filter black background
76
+ filter_white_bg: Whether to filter white background
77
+ processed_data: Processed data from reconstruction
78
+
79
+ Returns:
80
+ Status message
81
+ """
82
+ if not target_dir or target_dir == "None" or not os.path.isdir(target_dir):
83
+ return "No reconstruction available. Please run 'Reconstruct' first."
84
+
85
+ if processed_data is None:
86
+ return "No processed data available. Please run 'Reconstruct' first."
87
+
88
+ try:
89
+ # Add debug information
90
+ print("[DEBUG] save_current_visualization called with:")
91
+ print(f" target_dir: {target_dir}")
92
+ print(f" save_percentage: {save_percentage}")
93
+ print(f" show_cam: {show_cam}")
94
+ print(f" filter_black_bg: {filter_black_bg}")
95
+ print(f" filter_white_bg: {filter_white_bg}")
96
+ print(f" processed_data: {processed_data is not None}")
97
+
98
+ # Import the gallery save function
99
+ # Create gallery name with user input or auto-generated
100
+ import datetime
101
+
102
+ from .utils import save_to_gallery_func
103
+
104
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
105
+ if scene_name and scene_name.strip():
106
+ gallery_name = f"{scene_name.strip()}_{timestamp}_pct{save_percentage:.0f}"
107
+ else:
108
+ gallery_name = f"save_{timestamp}_pct{save_percentage:.0f}"
109
+
110
+ print(f"[DEBUG] Saving to gallery with name: {gallery_name}")
111
+
112
+ # Save entire process folder to gallery
113
+ success, message = save_to_gallery_func(
114
+ target_dir=target_dir, processed_data=processed_data, gallery_name=gallery_name
115
+ )
116
+
117
+ if success:
118
+ print(f"[DEBUG] Gallery save completed successfully: {message}")
119
+ return (
120
+ "Successfully saved to gallery!\n"
121
+ f"Gallery name: {gallery_name}\n"
122
+ f"Save percentage: {save_percentage}%\n"
123
+ f"Show cameras: {show_cam}\n"
124
+ f"Filter black bg: {filter_black_bg}\n"
125
+ f"Filter white bg: {filter_white_bg}\n\n"
126
+ f"{message}"
127
+ )
128
+ else:
129
+ print(f"[DEBUG] Gallery save failed: {message}")
130
+ return f"Failed to save to gallery: {message}"
131
+
132
+ except Exception as e:
133
+ return f"Error saving visualization: {str(e)}"
134
+
135
+ def gradio_demo(
136
+ self,
137
+ target_dir: str,
138
+ show_cam: bool = True,
139
+ filter_black_bg: bool = False,
140
+ filter_white_bg: bool = False,
141
+ process_res_method: str = "upper_bound_resize",
142
+ save_percentage: float = 30.0,
143
+ num_max_points: int = 1_000_000,
144
+ infer_gs: bool = False,
145
+ ref_view_strategy: str = "saddle_balanced",
146
+ gs_trj_mode: str = "extend",
147
+ gs_video_quality: str = "high",
148
+ ) -> Tuple[
149
+ Optional[str],
150
+ str,
151
+ Optional[Dict],
152
+ Optional[np.ndarray],
153
+ Optional[np.ndarray],
154
+ str,
155
+ gr.Dropdown,
156
+ Optional[str], # gs video path
157
+ gr.update, # gs video visibility update
158
+ gr.update, # gs info visibility update
159
+ ]:
160
+ """
161
+ Perform reconstruction using the already-created target_dir/images.
162
+
163
+ Args:
164
+ target_dir: Directory containing images
165
+ show_cam: Whether to show camera
166
+ filter_black_bg: Whether to filter black background
167
+ filter_white_bg: Whether to filter white background
168
+ process_res_method: Method for resizing input images
169
+ save_percentage: Filter percentage for point cloud
170
+ num_max_points: Maximum number of points
171
+ infer_gs: Whether to infer 3D Gaussian Splatting
172
+ ref_view_strategy: Reference view selection strategy
173
+
174
+ Returns:
175
+ Tuple of reconstruction results
176
+ """
177
+ if not os.path.isdir(target_dir) or target_dir == "None":
178
+ return (
179
+ None,
180
+ "No valid target directory found. Please upload first.",
181
+ None,
182
+ None,
183
+ None,
184
+ "",
185
+ None,
186
+ None,
187
+ gr.update(visible=False), # gs_video
188
+ gr.update(visible=True), # gs_info
189
+ )
190
+
191
+ start_time = time.time()
192
+ cleanup_cuda_memory()
193
+
194
+ # Get image files for logging
195
+ target_dir_images = os.path.join(target_dir, "images")
196
+ all_files = (
197
+ sorted(os.listdir(target_dir_images)) if os.path.isdir(target_dir_images) else []
198
+ )
199
+
200
+ print("Running DepthAnything3 model...")
201
+ print(f"Reference view strategy: {ref_view_strategy}")
202
+
203
+ with torch.no_grad():
204
+ prediction, processed_data = self.model_inference.run_inference(
205
+ target_dir,
206
+ process_res_method=process_res_method,
207
+ show_camera=show_cam,
208
+ save_percentage=save_percentage,
209
+ num_max_points=int(num_max_points * 1000), # Convert K to actual count
210
+ infer_gs=infer_gs,
211
+ ref_view_strategy=ref_view_strategy,
212
+ gs_trj_mode=gs_trj_mode,
213
+ gs_video_quality=gs_video_quality,
214
+ )
215
+
216
+ # The GLB file is already generated by the API
217
+ glbfile = os.path.join(target_dir, "scene.glb")
218
+
219
+ # Handle 3DGS video based on infer_gs flag
220
+ gsvideo_path = None
221
+ gs_video_visible = False
222
+ gs_info_visible = True
223
+
224
+ if infer_gs:
225
+ try:
226
+ gsvideo_path = sorted(glob(os.path.join(target_dir, "gs_video", "*.mp4")))[-1]
227
+ gs_video_visible = True
228
+ gs_info_visible = False
229
+ except IndexError:
230
+ gsvideo_path = None
231
+ print("3DGS video not found, but infer_gs was enabled")
232
+
233
+ # Cleanup
234
+ cleanup_cuda_memory()
235
+
236
+ end_time = time.time()
237
+ print(f"Total time: {end_time - start_time:.2f} seconds")
238
+ log_msg = f"Reconstruction Success ({len(all_files)} frames). Waiting for visualization."
239
+
240
+ # Populate visualization tabs with processed data
241
+ depth_vis, measure_img, measure_depth_vis, measure_pts = (
242
+ self.visualization_handler.populate_visualization_tabs(processed_data)
243
+ )
244
+
245
+ # Update view selectors based on available views
246
+ depth_selector, measure_selector = self.visualization_handler.update_view_selectors(
247
+ processed_data
248
+ )
249
+
250
+ return (
251
+ glbfile,
252
+ log_msg,
253
+ processed_data,
254
+ measure_img, # measure_image
255
+ measure_depth_vis, # measure_depth_image
256
+ "", # measure_text (empty initially)
257
+ measure_selector, # measure_view_selector
258
+ gsvideo_path,
259
+ gr.update(visible=gs_video_visible), # gs_video visibility
260
+ gr.update(visible=gs_info_visible), # gs_info visibility
261
+ )
262
+
263
+ def update_visualization(
264
+ self,
265
+ target_dir: str,
266
+ show_cam: bool,
267
+ is_example: str,
268
+ filter_black_bg: bool = False,
269
+ filter_white_bg: bool = False,
270
+ process_res_method: str = "upper_bound_resize",
271
+ ) -> Tuple[gr.update, str]:
272
+ """
273
+ Reload saved predictions from npz, create (or reuse) the GLB for new parameters,
274
+ and return it for the 3D viewer.
275
+
276
+ Args:
277
+ target_dir: Directory containing results
278
+ show_cam: Whether to show camera
279
+ is_example: Whether this is an example scene
280
+ filter_black_bg: Whether to filter black background
281
+ filter_white_bg: Whether to filter white background
282
+ process_res_method: Method for resizing input images
283
+
284
+ Returns:
285
+ Tuple of (glb_file, log_message)
286
+ """
287
+ if not target_dir or target_dir == "None" or not os.path.isdir(target_dir):
288
+ return (
289
+ gr.update(),
290
+ "No reconstruction available. Please click the Reconstruct button first.",
291
+ )
292
+
293
+ # Check if GLB exists (could be cached example or reconstructed scene)
294
+ glbfile = os.path.join(target_dir, "scene.glb")
295
+ if os.path.exists(glbfile):
296
+ return (
297
+ glbfile,
298
+ (
299
+ "Visualization loaded from cache."
300
+ if is_example == "True"
301
+ else "Visualization updated."
302
+ ),
303
+ )
304
+
305
+ # If no GLB but it's an example that hasn't been reconstructed yet
306
+ if is_example == "True":
307
+ return (
308
+ gr.update(),
309
+ "No reconstruction available. Please click the Reconstruct button first.",
310
+ )
311
+
312
+ # For non-examples, check predictions.npz
313
+ predictions_path = os.path.join(target_dir, "predictions.npz")
314
+ if not os.path.exists(predictions_path):
315
+ error_message = (
316
+ f"No reconstruction available at {predictions_path}. "
317
+ "Please run 'Reconstruct' first."
318
+ )
319
+ return gr.update(), error_message
320
+
321
+ loaded = np.load(predictions_path, allow_pickle=True)
322
+ predictions = {key: loaded[key] for key in loaded.keys()} # noqa: F841
323
+
324
+ return (
325
+ glbfile,
326
+ "Visualization updated.",
327
+ )
328
+
329
+ def handle_uploads(
330
+ self,
331
+ input_video: Optional[str],
332
+ input_images: Optional[List],
333
+ s_time_interval: float = 10.0,
334
+ ) -> Tuple[Optional[str], Optional[str], Optional[List], Optional[str]]:
335
+ """
336
+ Handle file uploads and update gallery.
337
+
338
+ Args:
339
+ input_video: Path to input video file
340
+ input_images: List of input image files
341
+ s_time_interval: Sampling FPS (frames per second) for frame extraction
342
+
343
+ Returns:
344
+ Tuple of (reconstruction_output, target_dir, image_paths, log_message)
345
+ """
346
+ return self.file_handler.update_gallery_on_upload(
347
+ input_video, input_images, s_time_interval
348
+ )
349
+
350
+ def load_example_scene(self, scene_name: str, examples_dir: str = None) -> Tuple[
351
+ Optional[str],
352
+ Optional[str],
353
+ Optional[List],
354
+ str,
355
+ Optional[Dict],
356
+ gr.Dropdown,
357
+ Optional[str],
358
+ gr.update,
359
+ gr.update,
360
+ ]:
361
+ """
362
+ Load a scene from examples directory.
363
+
364
+ Args:
365
+ scene_name: Name of the scene to load
366
+ examples_dir: Path to examples directory (if None, uses workspace_dir/examples)
367
+
368
+ Returns:
369
+ Tuple of (reconstruction_output, target_dir, image_paths, log_message, processed_data, measure_view_selector, gs_video, gs_video_vis, gs_info_vis) # noqa: E501
370
+ """
371
+ if examples_dir is None:
372
+ # Get workspace directory from environment variable
373
+ workspace_dir = os.environ.get("DA3_WORKSPACE_DIR", "gradio_workspace")
374
+ examples_dir = os.path.join(workspace_dir, "examples")
375
+
376
+ reconstruction_output, target_dir, image_paths, log_message = (
377
+ self.file_handler.load_example_scene(scene_name, examples_dir)
378
+ )
379
+
380
+ # Try to load cached processed data if available
381
+ processed_data = None
382
+ measure_view_selector = gr.Dropdown(choices=["View 1"], value="View 1")
383
+ gs_video_path = None
384
+ gs_video_visible = False
385
+ gs_info_visible = True
386
+
387
+ if target_dir and target_dir != "None":
388
+ predictions_path = os.path.join(target_dir, "predictions.npz")
389
+ if os.path.exists(predictions_path):
390
+ try:
391
+ # Load predictions from cache
392
+ loaded = np.load(predictions_path, allow_pickle=True)
393
+ predictions = {key: loaded[key] for key in loaded.keys()}
394
+
395
+ # Reconstruct processed_data structure
396
+ num_images = len(predictions.get("images", []))
397
+ processed_data = {}
398
+
399
+ for i in range(num_images):
400
+ processed_data[i] = {
401
+ "image": predictions["images"][i] if "images" in predictions else None,
402
+ "depth": predictions["depths"][i] if "depths" in predictions else None,
403
+ "depth_image": os.path.join(
404
+ target_dir, "depth_vis", f"{i:04d}.jpg" # Fixed: use .jpg not .png
405
+ ),
406
+ "intrinsics": (
407
+ predictions["intrinsics"][i]
408
+ if "intrinsics" in predictions
409
+ and i < len(predictions["intrinsics"])
410
+ else None
411
+ ),
412
+ "mask": None,
413
+ }
414
+
415
+ # Update measure view selector
416
+ choices = [f"View {i + 1}" for i in range(num_images)]
417
+ measure_view_selector = gr.Dropdown(choices=choices, value=choices[0])
418
+
419
+ except Exception as e:
420
+ print(f"Error loading cached data: {e}")
421
+
422
+ # Check for cached 3DGS video
423
+ gs_video_dir = os.path.join(target_dir, "gs_video")
424
+ if os.path.exists(gs_video_dir):
425
+ try:
426
+ from glob import glob
427
+
428
+ gs_videos = sorted(glob(os.path.join(gs_video_dir, "*.mp4")))
429
+ if gs_videos:
430
+ gs_video_path = gs_videos[-1]
431
+ gs_video_visible = True
432
+ gs_info_visible = False
433
+ print(f"Loaded cached 3DGS video: {gs_video_path}")
434
+ except Exception as e:
435
+ print(f"Error loading cached 3DGS video: {e}")
436
+
437
+ return (
438
+ reconstruction_output,
439
+ target_dir,
440
+ image_paths,
441
+ log_message,
442
+ processed_data,
443
+ measure_view_selector,
444
+ gs_video_path,
445
+ gr.update(visible=gs_video_visible),
446
+ gr.update(visible=gs_info_visible),
447
+ )
448
+
449
+ def navigate_depth_view(
450
+ self,
451
+ processed_data: Optional[Dict[int, Dict[str, Any]]],
452
+ current_selector: str,
453
+ direction: int,
454
+ ) -> Tuple[str, Optional[str]]:
455
+ """
456
+ Navigate depth view.
457
+
458
+ Args:
459
+ processed_data: Processed data dictionary
460
+ current_selector: Current selector value
461
+ direction: Direction to navigate
462
+
463
+ Returns:
464
+ Tuple of (new_selector_value, depth_vis)
465
+ """
466
+ return self.visualization_handler.navigate_depth_view(
467
+ processed_data, current_selector, direction
468
+ )
469
+
470
+ def update_depth_view(
471
+ self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int
472
+ ) -> Optional[str]:
473
+ """
474
+ Update depth view for a specific view index.
475
+
476
+ Args:
477
+ processed_data: Processed data dictionary
478
+ view_index: Index of the view to update
479
+
480
+ Returns:
481
+ Path to depth visualization image or None
482
+ """
483
+ return self.visualization_handler.update_depth_view(processed_data, view_index)
484
+
485
+ def navigate_measure_view(
486
+ self,
487
+ processed_data: Optional[Dict[int, Dict[str, Any]]],
488
+ current_selector: str,
489
+ direction: int,
490
+ ) -> Tuple[str, Optional[np.ndarray], Optional[np.ndarray], List]:
491
+ """
492
+ Navigate measure view.
493
+
494
+ Args:
495
+ processed_data: Processed data dictionary
496
+ current_selector: Current selector value
497
+ direction: Direction to navigate
498
+
499
+ Returns:
500
+ Tuple of (new_selector_value, measure_image, depth_right_half, measure_points)
501
+ """
502
+ return self.visualization_handler.navigate_measure_view(
503
+ processed_data, current_selector, direction
504
+ )
505
+
506
+ def update_measure_view(
507
+ self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int
508
+ ) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], List]:
509
+ """
510
+ Update measure view for a specific view index.
511
+
512
+ Args:
513
+ processed_data: Processed data dictionary
514
+ view_index: Index of the view to update
515
+
516
+ Returns:
517
+ Tuple of (measure_image, depth_right_half, measure_points)
518
+ """
519
+ return self.visualization_handler.update_measure_view(processed_data, view_index)
520
+
521
+ def measure(
522
+ self,
523
+ processed_data: Optional[Dict[int, Dict[str, Any]]],
524
+ measure_points: List,
525
+ current_view_selector: str,
526
+ event: gr.SelectData,
527
+ ) -> List:
528
+ """
529
+ Handle measurement on images.
530
+
531
+ Args:
532
+ processed_data: Processed data dictionary
533
+ measure_points: List of current measure points
534
+ current_view_selector: Current view selector value
535
+ event: Gradio select event
536
+
537
+ Returns:
538
+ List of [image, depth_right_half, measure_points, text]
539
+ """
540
+ return self.visualization_handler.measure(
541
+ processed_data, measure_points, current_view_selector, event
542
+ )
543
+
544
+ def select_first_frame(
545
+ self, image_gallery: List, selected_index: int = 0
546
+ ) -> Tuple[List, str, str]:
547
+ """
548
+ Select the first frame from the image gallery.
549
+
550
+ Args:
551
+ image_gallery: List of images in the gallery
552
+ selected_index: Index of the selected image (default: 0)
553
+
554
+ Returns:
555
+ Tuple of (updated_image_gallery, log_message, selected_frame_path)
556
+ """
557
+ try:
558
+ if not image_gallery or len(image_gallery) == 0:
559
+ return image_gallery, "No images available to select as first frame.", ""
560
+
561
+ # Handle None or invalid selected_index
562
+ if (
563
+ selected_index is None
564
+ or selected_index < 0
565
+ or selected_index >= len(image_gallery)
566
+ ):
567
+ selected_index = 0
568
+ print(f"Invalid selected_index: {selected_index}, using default: 0")
569
+
570
+ # Get the selected image based on index
571
+ selected_image = image_gallery[selected_index]
572
+ print(f"Selected image index: {selected_index}")
573
+ print(f"Total images: {len(image_gallery)}")
574
+
575
+ # Extract the file path from the selected image
576
+ selected_frame_path = ""
577
+ print(f"Selected image type: {type(selected_image)}")
578
+ print(f"Selected image: {selected_image}")
579
+
580
+ if isinstance(selected_image, tuple):
581
+ # Gradio Gallery returns tuple (path, None)
582
+ selected_frame_path = selected_image[0]
583
+ elif isinstance(selected_image, str):
584
+ selected_frame_path = selected_image
585
+ elif hasattr(selected_image, "name"):
586
+ selected_frame_path = selected_image.name
587
+ elif isinstance(selected_image, dict):
588
+ if "name" in selected_image:
589
+ selected_frame_path = selected_image["name"]
590
+ elif "path" in selected_image:
591
+ selected_frame_path = selected_image["path"]
592
+ elif "src" in selected_image:
593
+ selected_frame_path = selected_image["src"]
594
+ else:
595
+ # Try to convert to string
596
+ selected_frame_path = str(selected_image)
597
+
598
+ print(f"Extracted path: {selected_frame_path}")
599
+
600
+ # Extract filename from the path for matching
601
+ import os
602
+
603
+ selected_filename = os.path.basename(selected_frame_path)
604
+ print(f"Selected filename: {selected_filename}")
605
+
606
+ # Move the selected image to the front
607
+ updated_gallery = [selected_image] + [
608
+ img for img in image_gallery if img != selected_image
609
+ ]
610
+
611
+ log_message = (
612
+ f"Selected frame: {selected_filename}. "
613
+ f"Moved to first position. Total frames: {len(updated_gallery)}"
614
+ )
615
+ return updated_gallery, log_message, selected_filename
616
+
617
+ except Exception as e:
618
+ print(f"Error selecting first frame: {e}")
619
+ return image_gallery, f"Error selecting first frame: {e}", ""
src/depth_anything_3/app/modules/file_handlers.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ File handling module for Depth Anything 3 Gradio app.
17
+
18
+ This module handles file uploads, video processing, and file operations.
19
+ """
20
+
21
+ import os
22
+ import shutil
23
+ import time
24
+ from datetime import datetime
25
+ from typing import List, Optional, Tuple
26
+ import cv2
27
+ from PIL import Image
28
+ from pillow_heif import register_heif_opener
29
+
30
+ register_heif_opener()
31
+
32
+
33
+ class FileHandler:
34
+ """
35
+ Handles file uploads and processing for the Gradio app.
36
+ """
37
+
38
+ def __init__(self):
39
+ """Initialize the file handler."""
40
+
41
+ def handle_uploads(
42
+ self,
43
+ input_video: Optional[str],
44
+ input_images: Optional[List],
45
+ s_time_interval: float = 10.0,
46
+ ) -> Tuple[str, List[str]]:
47
+ """
48
+ Create a new 'target_dir' + 'images' subfolder, and place user-uploaded
49
+ images or extracted frames from video into it.
50
+
51
+ Args:
52
+ input_video: Path to input video file
53
+ input_images: List of input image files
54
+ s_time_interval: Sampling FPS (frames per second) for frame extraction
55
+
56
+ Returns:
57
+ Tuple of (target_dir, image_paths)
58
+ """
59
+ start_time = time.time()
60
+
61
+ # Get workspace directory from environment variable or use default
62
+ workspace_dir = os.environ.get("DA3_WORKSPACE_DIR", "gradio_workspace")
63
+ if not os.path.exists(workspace_dir):
64
+ os.makedirs(workspace_dir)
65
+
66
+ # Create input_images subdirectory
67
+ input_images_dir = os.path.join(workspace_dir, "input_images")
68
+ if not os.path.exists(input_images_dir):
69
+ os.makedirs(input_images_dir)
70
+
71
+ # Create a unique folder name within input_images
72
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
73
+ target_dir = os.path.join(input_images_dir, f"session_{timestamp}")
74
+ target_dir_images = os.path.join(target_dir, "images")
75
+
76
+ # Clean up if somehow that folder already exists
77
+ if os.path.exists(target_dir):
78
+ shutil.rmtree(target_dir)
79
+ os.makedirs(target_dir)
80
+ os.makedirs(target_dir_images)
81
+
82
+ image_paths = []
83
+
84
+ # Handle images
85
+ if input_images is not None:
86
+ image_paths.extend(self._process_images(input_images, target_dir_images))
87
+
88
+ # Handle video
89
+ if input_video is not None:
90
+ image_paths.extend(
91
+ self._process_video(input_video, target_dir_images, s_time_interval)
92
+ )
93
+
94
+ # Sort final images for gallery
95
+ image_paths = sorted(image_paths)
96
+
97
+ end_time = time.time()
98
+ print(f"Files copied to {target_dir_images}; took {end_time - start_time:.3f} seconds")
99
+ return target_dir, image_paths
100
+
101
+ def _process_images(self, input_images: List, target_dir_images: str) -> List[str]:
102
+ """
103
+ Process uploaded images.
104
+
105
+ Args:
106
+ input_images: List of input image files
107
+ target_dir_images: Target directory for images
108
+
109
+ Returns:
110
+ List of processed image paths
111
+ """
112
+ image_paths = []
113
+
114
+ for file_data in input_images:
115
+ if isinstance(file_data, dict) and "name" in file_data:
116
+ file_path = file_data["name"]
117
+ else:
118
+ file_path = file_data
119
+
120
+ # Check if the file is a HEIC image
121
+ file_ext = os.path.splitext(file_path)[1].lower()
122
+ if file_ext in [".heic", ".heif"]:
123
+ # Convert HEIC to JPEG for better gallery compatibility
124
+ try:
125
+ with Image.open(file_path) as img:
126
+ # Convert to RGB if necessary (HEIC can have different color modes)
127
+ if img.mode not in ("RGB", "L"):
128
+ img = img.convert("RGB")
129
+
130
+ # Create JPEG filename
131
+ base_name = os.path.splitext(os.path.basename(file_path))[0]
132
+ dst_path = os.path.join(target_dir_images, f"{base_name}.jpg")
133
+
134
+ # Save as JPEG with high quality
135
+ img.save(dst_path, "JPEG", quality=95)
136
+ image_paths.append(dst_path)
137
+ print(
138
+ f"Converted HEIC to JPEG: {os.path.basename(file_path)} -> "
139
+ f"{os.path.basename(dst_path)}"
140
+ )
141
+ except Exception as e:
142
+ print(f"Error converting HEIC file {file_path}: {e}")
143
+ # Fall back to copying as is
144
+ dst_path = os.path.join(target_dir_images, os.path.basename(file_path))
145
+ shutil.copy(file_path, dst_path)
146
+ image_paths.append(dst_path)
147
+ else:
148
+ # Regular image files - copy as is
149
+ dst_path = os.path.join(target_dir_images, os.path.basename(file_path))
150
+ shutil.copy(file_path, dst_path)
151
+ image_paths.append(dst_path)
152
+
153
+ return image_paths
154
+
155
+ def _process_video(
156
+ self, input_video: str, target_dir_images: str, s_time_interval: float
157
+ ) -> List[str]:
158
+ """
159
+ Process video file and extract frames.
160
+
161
+ Args:
162
+ input_video: Path to input video file
163
+ target_dir_images: Target directory for extracted frames
164
+ s_time_interval: Sampling FPS (frames per second) for frame extraction
165
+
166
+ Returns:
167
+ List of extracted frame paths
168
+ """
169
+ image_paths = []
170
+
171
+ if isinstance(input_video, dict) and "name" in input_video:
172
+ video_path = input_video["name"]
173
+ else:
174
+ video_path = input_video
175
+
176
+ vs = cv2.VideoCapture(video_path)
177
+ fps = vs.get(cv2.CAP_PROP_FPS)
178
+ frame_interval = max(1, int(fps / s_time_interval)) # Convert FPS to frame interval
179
+
180
+ count = 0
181
+ video_frame_num = 0
182
+ while True:
183
+ gotit, frame = vs.read()
184
+ if not gotit:
185
+ break
186
+ count += 1
187
+ if count % frame_interval == 0:
188
+ image_path = os.path.join(target_dir_images, f"{video_frame_num:06}.png")
189
+ cv2.imwrite(image_path, frame)
190
+ image_paths.append(image_path)
191
+ video_frame_num += 1
192
+
193
+ return image_paths
194
+
195
+ def update_gallery_on_upload(
196
+ self,
197
+ input_video: Optional[str],
198
+ input_images: Optional[List],
199
+ s_time_interval: float = 10.0,
200
+ ) -> Tuple[Optional[str], Optional[str], Optional[List], Optional[str]]:
201
+ """
202
+ Handle file uploads and update gallery.
203
+
204
+ Args:
205
+ input_video: Path to input video file
206
+ input_images: List of input image files
207
+ s_time_interval: Sampling FPS (frames per second) for frame extraction
208
+
209
+ Returns:
210
+ Tuple of (reconstruction_output, target_dir, image_paths, log_message)
211
+ """
212
+ if not input_video and not input_images:
213
+ return None, None, None, None
214
+
215
+ target_dir, image_paths = self.handle_uploads(input_video, input_images, s_time_interval)
216
+ return (
217
+ None,
218
+ target_dir,
219
+ image_paths,
220
+ "Upload complete. Click 'Reconstruct' to begin 3D processing.",
221
+ )
222
+
223
+ def load_example_scene(
224
+ self, scene_name: str, examples_dir: str = "examples"
225
+ ) -> Tuple[Optional[str], Optional[str], Optional[List], str]:
226
+ """
227
+ Load a scene from examples directory.
228
+
229
+ Args:
230
+ scene_name: Name of the scene to load
231
+ examples_dir: Path to examples directory
232
+
233
+ Returns:
234
+ Tuple of (reconstruction_output, target_dir, image_paths, log_message)
235
+ """
236
+ from depth_anything_3.app.modules.utils import get_scene_info
237
+
238
+ scenes = get_scene_info(examples_dir)
239
+
240
+ # Find the selected scene
241
+ selected_scene = None
242
+ for scene in scenes:
243
+ if scene["name"] == scene_name:
244
+ selected_scene = scene
245
+ break
246
+
247
+ if selected_scene is None:
248
+ return None, None, None, "Scene not found"
249
+
250
+ # Use fixed directory name for examples (not timestamp-based)
251
+ workspace_dir = os.environ.get("DA3_WORKSPACE_DIR", "gradio_workspace")
252
+ input_images_dir = os.path.join(workspace_dir, "input_images")
253
+ if not os.path.exists(input_images_dir):
254
+ os.makedirs(input_images_dir)
255
+
256
+ # Create a fixed folder name based on scene name
257
+ target_dir = os.path.join(input_images_dir, f"example_{scene_name}")
258
+ target_dir_images = os.path.join(target_dir, "images")
259
+
260
+ # Check if already cached (GLB file exists)
261
+ glb_path = os.path.join(target_dir, "scene.glb")
262
+ is_cached = os.path.exists(glb_path)
263
+
264
+ # Create directory if it doesn't exist
265
+ if not os.path.exists(target_dir):
266
+ os.makedirs(target_dir)
267
+ os.makedirs(target_dir_images)
268
+
269
+ # Copy images if directory is new or empty
270
+ if not os.path.exists(target_dir_images) or len(os.listdir(target_dir_images)) == 0:
271
+ os.makedirs(target_dir_images, exist_ok=True)
272
+ image_paths = []
273
+ for file_path in selected_scene["image_files"]:
274
+ dst_path = os.path.join(target_dir_images, os.path.basename(file_path))
275
+ shutil.copy(file_path, dst_path)
276
+ image_paths.append(dst_path)
277
+ else:
278
+ # Use existing images
279
+ image_paths = sorted(
280
+ [
281
+ os.path.join(target_dir_images, f)
282
+ for f in os.listdir(target_dir_images)
283
+ if f.lower().endswith((".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".tif"))
284
+ ]
285
+ )
286
+
287
+ # Return cached GLB if available
288
+ if is_cached:
289
+ return (
290
+ glb_path, # Return cached reconstruction
291
+ target_dir, # Set target directory
292
+ image_paths, # Set gallery
293
+ f"Loaded cached scene '{scene_name}' with {selected_scene['num_images']} images.",
294
+ )
295
+ else:
296
+ return (
297
+ None, # No cached reconstruction
298
+ target_dir, # Set target directory
299
+ image_paths, # Set gallery
300
+ (
301
+ f"Loaded scene '{scene_name}' with {selected_scene['num_images']} images. "
302
+ "Click 'Reconstruct' to begin 3D processing."
303
+ ),
304
+ )
src/depth_anything_3/app/modules/model_inference.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Model inference module for Depth Anything 3 Gradio app.
17
+
18
+ This module handles all model-related operations including inference,
19
+ data processing, and result preparation.
20
+ """
21
+
22
+ import glob
23
+ import os
24
+ from typing import Any, Dict, Optional, Tuple
25
+ import numpy as np
26
+ import torch
27
+
28
+ from depth_anything_3.api import DepthAnything3
29
+ from depth_anything_3.utils.memory import cleanup_cuda_memory
30
+ from depth_anything_3.utils.export.glb import export_to_glb
31
+ from depth_anything_3.utils.export.gs import export_to_gs_video
32
+
33
+
34
+ class ModelInference:
35
+ """
36
+ Handles model inference and data processing for Depth Anything 3.
37
+ """
38
+
39
+ def __init__(self):
40
+ """Initialize the model inference handler."""
41
+ self.model = None
42
+
43
+ def initialize_model(self, device: str = "cuda") -> None:
44
+ """
45
+ Initialize the DepthAnything3 model.
46
+
47
+ Args:
48
+ device: Device to load the model on
49
+ """
50
+ if self.model is None:
51
+ # Get model directory from environment variable or use default
52
+ model_dir = os.environ.get(
53
+ "DA3_MODEL_DIR", "/dev/shm/da3_models/DA3HF-VITG-METRIC_VITL"
54
+ )
55
+ self.model = DepthAnything3.from_pretrained(model_dir)
56
+ self.model = self.model.to(device)
57
+ else:
58
+ self.model = self.model.to(device)
59
+
60
+ self.model.eval()
61
+
62
+ def run_inference(
63
+ self,
64
+ target_dir: str,
65
+ filter_black_bg: bool = False,
66
+ filter_white_bg: bool = False,
67
+ process_res_method: str = "upper_bound_resize",
68
+ show_camera: bool = True,
69
+ save_percentage: float = 30.0,
70
+ num_max_points: int = 1_000_000,
71
+ infer_gs: bool = False,
72
+ ref_view_strategy: str = "saddle_balanced",
73
+ gs_trj_mode: str = "extend",
74
+ gs_video_quality: str = "high",
75
+ ) -> Tuple[Any, Dict[int, Dict[str, Any]]]:
76
+ """
77
+ Run DepthAnything3 model inference on images.
78
+
79
+ Args:
80
+ target_dir: Directory containing images
81
+ filter_black_bg: Whether to filter black background
82
+ filter_white_bg: Whether to filter white background
83
+ process_res_method: Method for resizing input images
84
+ show_camera: Whether to show camera in 3D view
85
+ save_percentage: Percentage of points to save (0-100)
86
+ num_max_points: Maximum number of points in point cloud
87
+ infer_gs: Whether to infer 3D Gaussian Splatting
88
+ ref_view_strategy: Reference view selection strategy
89
+ gs_trj_mode: Trajectory mode for 3DGS
90
+ gs_video_quality: Video quality for 3DGS
91
+
92
+ Returns:
93
+ Tuple of (prediction, processed_data)
94
+ """
95
+ print(f"Processing images from {target_dir}")
96
+
97
+ # Device check
98
+ device = "cuda" if torch.cuda.is_available() else "cpu"
99
+ device = torch.device(device)
100
+
101
+ # Initialize model if needed
102
+ self.initialize_model(device)
103
+
104
+ # Get image paths
105
+ print("Loading images...")
106
+ image_folder_path = os.path.join(target_dir, "images")
107
+ all_image_paths = sorted(glob.glob(os.path.join(image_folder_path, "*")))
108
+
109
+ # Filter for image files
110
+ image_extensions = [".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif"]
111
+ all_image_paths = [
112
+ path
113
+ for path in all_image_paths
114
+ if any(path.lower().endswith(ext) for ext in image_extensions)
115
+ ]
116
+
117
+ print(f"Found {len(all_image_paths)} images")
118
+ print(f"All image paths: {all_image_paths}")
119
+
120
+ # Use sorted image order (reference view will be selected automatically)
121
+ image_paths = all_image_paths
122
+ print(f"Reference view selection strategy: {ref_view_strategy}")
123
+
124
+ if len(image_paths) == 0:
125
+ raise ValueError("No images found. Check your upload.")
126
+
127
+ # Map UI options to actual method names
128
+ method_mapping = {"high_res": "lower_bound_resize", "low_res": "upper_bound_resize"}
129
+ actual_method = method_mapping.get(process_res_method, "upper_bound_crop")
130
+
131
+ # Run model inference
132
+ print(f"Running inference with method: {actual_method}")
133
+ with torch.no_grad():
134
+ prediction = self.model.inference(
135
+ image_paths,
136
+ export_dir=None,
137
+ process_res_method=actual_method,
138
+ infer_gs=infer_gs,
139
+ ref_view_strategy=ref_view_strategy,
140
+ )
141
+ # num_max_points: int = 1_000_000,
142
+ export_to_glb(
143
+ prediction,
144
+ filter_black_bg=filter_black_bg,
145
+ filter_white_bg=filter_white_bg,
146
+ export_dir=target_dir,
147
+ show_cameras=show_camera,
148
+ conf_thresh_percentile=save_percentage,
149
+ num_max_points=int(num_max_points),
150
+ )
151
+
152
+ # export to gs video if needed
153
+ if infer_gs:
154
+ mode_mapping = {"extend": "extend", "smooth": "interpolate_smooth"}
155
+ print(f"GS mode: {gs_trj_mode}; Backend mode: {mode_mapping[gs_trj_mode]}")
156
+ export_to_gs_video(
157
+ prediction,
158
+ export_dir=target_dir,
159
+ chunk_size=4,
160
+ trj_mode=mode_mapping.get(gs_trj_mode, "extend"),
161
+ enable_tqdm=True,
162
+ vis_depth="hcat",
163
+ video_quality=gs_video_quality,
164
+ )
165
+
166
+ # Save predictions.npz for caching metric depth data
167
+ self._save_predictions_cache(target_dir, prediction)
168
+
169
+ # Process results
170
+ processed_data = self._process_results(target_dir, prediction, image_paths)
171
+
172
+ # Clean up using centralized memory utilities for consistency with backend
173
+ cleanup_cuda_memory()
174
+
175
+ return prediction, processed_data
176
+
177
+ def _save_predictions_cache(self, target_dir: str, prediction: Any) -> None:
178
+ """
179
+ Save predictions data to predictions.npz for caching.
180
+
181
+ Args:
182
+ target_dir: Directory to save the cache
183
+ prediction: Model prediction object
184
+ """
185
+ try:
186
+ output_file = os.path.join(target_dir, "predictions.npz")
187
+
188
+ # Build save dict with prediction data
189
+ save_dict = {}
190
+
191
+ # Save processed images if available
192
+ if prediction.processed_images is not None:
193
+ save_dict["images"] = prediction.processed_images
194
+
195
+ # Save depth data
196
+ if prediction.depth is not None:
197
+ save_dict["depths"] = np.round(prediction.depth, 6)
198
+
199
+ # Save confidence if available
200
+ if prediction.conf is not None:
201
+ save_dict["conf"] = np.round(prediction.conf, 2)
202
+
203
+ # Save camera parameters
204
+ if prediction.extrinsics is not None:
205
+ save_dict["extrinsics"] = prediction.extrinsics
206
+ if prediction.intrinsics is not None:
207
+ save_dict["intrinsics"] = prediction.intrinsics
208
+
209
+ # Save to file
210
+ np.savez_compressed(output_file, **save_dict)
211
+ print(f"Saved predictions cache to: {output_file}")
212
+
213
+ except Exception as e:
214
+ print(f"Warning: Failed to save predictions cache: {e}")
215
+
216
+ def _process_results(
217
+ self, target_dir: str, prediction: Any, image_paths: list
218
+ ) -> Dict[int, Dict[str, Any]]:
219
+ """
220
+ Process model results into structured data.
221
+
222
+ Args:
223
+ target_dir: Directory containing results
224
+ prediction: Model prediction object
225
+ image_paths: List of input image paths
226
+
227
+ Returns:
228
+ Dictionary containing processed data for each view
229
+ """
230
+ processed_data = {}
231
+
232
+ # Read generated depth visualization files
233
+ depth_vis_dir = os.path.join(target_dir, "depth_vis")
234
+
235
+ if os.path.exists(depth_vis_dir):
236
+ depth_files = sorted(glob.glob(os.path.join(depth_vis_dir, "*.jpg")))
237
+ for i, depth_file in enumerate(depth_files):
238
+ # Use processed images directly from API
239
+ processed_image = None
240
+ if prediction.processed_images is not None and i < len(
241
+ prediction.processed_images
242
+ ):
243
+ processed_image = prediction.processed_images[i]
244
+
245
+ processed_data[i] = {
246
+ "depth_image": depth_file,
247
+ "image": processed_image,
248
+ "original_image_path": image_paths[i] if i < len(image_paths) else None,
249
+ "depth": prediction.depth[i] if i < len(prediction.depth) else None,
250
+ "intrinsics": (
251
+ prediction.intrinsics[i]
252
+ if prediction.intrinsics is not None and i < len(prediction.intrinsics)
253
+ else None
254
+ ),
255
+ "mask": None, # No mask information available
256
+ }
257
+
258
+ return processed_data
259
+
260
+ # cleanup() removed: call cleanup_cuda_memory() directly where needed.
src/depth_anything_3/app/modules/ui_components.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ UI components module for Depth Anything 3 Gradio app.
17
+
18
+ This module contains UI component definitions and layout functions.
19
+ """
20
+
21
+ import os
22
+ from typing import Any, Dict, List, Tuple
23
+ import gradio as gr
24
+
25
+ from depth_anything_3.app.modules.utils import get_logo_base64, get_scene_info
26
+
27
+
28
+ class UIComponents:
29
+ """
30
+ Handles UI component creation and layout for the Gradio app.
31
+ """
32
+
33
+ def __init__(self):
34
+ """Initialize the UI components handler."""
35
+
36
+ def create_upload_section(self) -> Tuple[gr.Video, gr.Slider, gr.File, gr.Gallery]:
37
+ """
38
+ Create the upload section with video, images, and gallery components.
39
+
40
+ Returns:
41
+ A tuple of Gradio components: (input_video, s_time_interval, input_images, image_gallery).
42
+ """
43
+ input_video = gr.Video(label="Upload Video", interactive=True)
44
+ s_time_interval = gr.Slider(
45
+ minimum=0.1,
46
+ maximum=60,
47
+ value=10,
48
+ step=0.1,
49
+ label="Sampling FPS (Frames Per Second)",
50
+ interactive=True,
51
+ visible=True,
52
+ )
53
+ input_images = gr.File(file_count="multiple", label="Upload Images", interactive=True)
54
+ image_gallery = gr.Gallery(
55
+ label="Preview",
56
+ columns=4,
57
+ height="300px",
58
+ show_download_button=True,
59
+ object_fit="contain",
60
+ preview=True,
61
+ interactive=False,
62
+ )
63
+
64
+ return input_video, s_time_interval, input_images, image_gallery
65
+
66
+ def create_3d_viewer_section(self) -> gr.Model3D:
67
+ """
68
+ Create the 3D viewer component.
69
+
70
+ Returns:
71
+ 3D model viewer component
72
+ """
73
+ return gr.Model3D(
74
+ height=520,
75
+ zoom_speed=0.5,
76
+ pan_speed=0.5,
77
+ clear_color=[0.0, 0.0, 0.0, 0.0],
78
+ key="persistent_3d_viewer",
79
+ elem_id="reconstruction_3d_viewer",
80
+ )
81
+
82
+ def create_nvs_video(self) -> Tuple[gr.Video, gr.Markdown]:
83
+ """
84
+ Create the 3DGS rendered video display component and info message.
85
+
86
+ Returns:
87
+ Tuple of (video component, info message component)
88
+ """
89
+ with gr.Column():
90
+ gs_info = gr.Markdown(
91
+ (
92
+ "‼️ **3D Gaussian Splatting rendering is currently DISABLED.** <br><br><br>"
93
+ "To render novel views from 3DGS, "
94
+ "enable **Infer 3D Gaussian Splatting** below. <br>"
95
+ "Next, in **Visualization Options**, "
96
+ "*optionally* configure the **rendering trajectory** (default: smooth) "
97
+ "and **video quality** (default: low), "
98
+ "then click **Reconstruct**."
99
+ ),
100
+ visible=True,
101
+ height=520,
102
+ )
103
+ gs_video = gr.Video(
104
+ height=520,
105
+ label="3DGS Rendered NVS Video (depth shown for reference only)",
106
+ interactive=False,
107
+ visible=False,
108
+ )
109
+ return gs_video, gs_info
110
+
111
+ def create_depth_section(self) -> Tuple[gr.Button, gr.Dropdown, gr.Button, gr.Image]:
112
+ """
113
+ Create the depth visualization section.
114
+
115
+ Returns:
116
+ A tuple of (prev_depth_btn, depth_view_selector, next_depth_btn, depth_map)
117
+ """
118
+ with gr.Row(elem_classes=["navigation-row"]):
119
+ prev_depth_btn = gr.Button("◀ Previous", size="sm", scale=1)
120
+ depth_view_selector = gr.Dropdown(
121
+ choices=["View 1"],
122
+ value="View 1",
123
+ label="Select View",
124
+ scale=2,
125
+ interactive=True,
126
+ allow_custom_value=True,
127
+ )
128
+ next_depth_btn = gr.Button("Next ▶", size="sm", scale=1)
129
+ depth_map = gr.Image(
130
+ type="numpy",
131
+ label="Colorized Depth Map",
132
+ format="png",
133
+ interactive=False,
134
+ )
135
+
136
+ return prev_depth_btn, depth_view_selector, next_depth_btn, depth_map
137
+
138
+ def create_measure_section(
139
+ self,
140
+ ) -> Tuple[gr.Button, gr.Dropdown, gr.Button, gr.Image, gr.Image, gr.Markdown]:
141
+ """
142
+ Create the measurement section.
143
+
144
+ Returns:
145
+ A tuple of (prev_measure_btn, measure_view_selector, next_measure_btn, measure_image,
146
+ measure_depth_image, measure_text)
147
+ """
148
+ from depth_anything_3.app.css_and_html import MEASURE_INSTRUCTIONS_HTML
149
+
150
+ gr.Markdown(MEASURE_INSTRUCTIONS_HTML)
151
+ with gr.Row(elem_classes=["navigation-row"]):
152
+ prev_measure_btn = gr.Button("◀ Previous", size="sm", scale=1)
153
+ measure_view_selector = gr.Dropdown(
154
+ choices=["View 1"],
155
+ value="View 1",
156
+ label="Select View",
157
+ scale=2,
158
+ interactive=True,
159
+ allow_custom_value=True,
160
+ )
161
+ next_measure_btn = gr.Button("Next ▶", size="sm", scale=1)
162
+ with gr.Row():
163
+ measure_image = gr.Image(
164
+ type="numpy",
165
+ show_label=False,
166
+ format="webp",
167
+ interactive=False,
168
+ sources=[],
169
+ label="RGB Image",
170
+ scale=1,
171
+ height=275,
172
+ )
173
+ measure_depth_image = gr.Image(
174
+ type="numpy",
175
+ show_label=False,
176
+ format="webp",
177
+ interactive=False,
178
+ sources=[],
179
+ label="Depth Visualization (Right Half)",
180
+ scale=1,
181
+ height=275,
182
+ )
183
+ gr.Markdown(
184
+ "**Note:** Images have been adjusted to model processing size. "
185
+ "Click two points on the RGB image to measure distance."
186
+ )
187
+ measure_text = gr.Markdown("")
188
+
189
+ return (
190
+ prev_measure_btn,
191
+ measure_view_selector,
192
+ next_measure_btn,
193
+ measure_image,
194
+ measure_depth_image,
195
+ measure_text,
196
+ )
197
+
198
+ def create_inference_control_section(self) -> Tuple[gr.Dropdown, gr.Checkbox, gr.Dropdown]:
199
+ """
200
+ Create the inference control section (before inference).
201
+
202
+ Returns:
203
+ Tuple of (process_res_method_dropdown, infer_gs, ref_view_strategy)
204
+ """
205
+ with gr.Row():
206
+ process_res_method_dropdown = gr.Dropdown(
207
+ choices=["high_res", "low_res"],
208
+ value="low_res",
209
+ label="Image Processing Method",
210
+ info="low_res for much more images",
211
+ scale=1,
212
+ )
213
+ # Modify line 220, add color class
214
+ infer_gs = gr.Checkbox(
215
+ label="Infer 3D Gaussian Splatting",
216
+ value=False,
217
+ info=(
218
+ 'Enable novel view rendering from 3DGS (<i class="fas fa-triangle-exclamation '
219
+ 'fa-color-red"></i> requires extra processing time)'
220
+ ),
221
+ scale=1,
222
+ )
223
+ ref_view_strategy = gr.Dropdown(
224
+ choices=["saddle_balanced", "saddle_sim_range", "first", "middle"],
225
+ value="saddle_balanced",
226
+ label="Reference View Strategy",
227
+ info="Strategy for selecting reference view from multiple inputs",
228
+ scale=1,
229
+ )
230
+
231
+ return (process_res_method_dropdown, infer_gs, ref_view_strategy)
232
+
233
+ def create_display_control_section(
234
+ self,
235
+ ) -> Tuple[
236
+ gr.Checkbox,
237
+ gr.Checkbox,
238
+ gr.Checkbox,
239
+ gr.Slider,
240
+ gr.Slider,
241
+ gr.Dropdown,
242
+ gr.Dropdown,
243
+ gr.Button,
244
+ gr.ClearButton,
245
+ ]:
246
+ """
247
+ Create the display control section (options for visualization).
248
+
249
+ Returns:
250
+ Tuple of display control components including buttons
251
+ """
252
+ with gr.Column():
253
+ # 3DGS options at the top
254
+ with gr.Row():
255
+ gs_trj_mode = gr.Dropdown(
256
+ choices=["smooth", "extend"],
257
+ value="smooth",
258
+ label=("Rendering trajectory for 3DGS viewpoints (requires n_views ≥ 2)"),
259
+ info=("'smooth' for view interpolation; 'extend' for longer trajectory"),
260
+ visible=False, # initially hidden
261
+ )
262
+ gs_video_quality = gr.Dropdown(
263
+ choices=["low", "medium", "high"],
264
+ value="low",
265
+ label=("Video quality for 3DGS rendered outputs"),
266
+ info=("'low' for faster loading speed; 'high' for better visual quality"),
267
+ visible=False, # initially hidden
268
+ )
269
+
270
+ # Reconstruct and Clear buttons (before Visualization Options)
271
+ with gr.Row():
272
+ submit_btn = gr.Button("Reconstruct", scale=1, variant="primary")
273
+ clear_btn = gr.ClearButton(scale=1)
274
+
275
+ gr.Markdown("### Visualization Options: (Click Reconstruct to update)")
276
+ show_cam = gr.Checkbox(label="Show Camera", value=True)
277
+ filter_black_bg = gr.Checkbox(label="Filter Black Background", value=False)
278
+ filter_white_bg = gr.Checkbox(label="Filter White Background", value=False)
279
+ save_percentage = gr.Slider(
280
+ minimum=0,
281
+ maximum=100,
282
+ value=10,
283
+ step=1,
284
+ label="Filter Percentage",
285
+ info="Confidence Threshold (%): Higher values filter more points.",
286
+ )
287
+ num_max_points = gr.Slider(
288
+ minimum=1000,
289
+ maximum=100000,
290
+ value=1000,
291
+ step=1000,
292
+ label="Max Points (K points)",
293
+ info="Maximum number of points to export to GLB (in thousands)",
294
+ )
295
+
296
+ return (
297
+ show_cam,
298
+ filter_black_bg,
299
+ filter_white_bg,
300
+ save_percentage,
301
+ num_max_points,
302
+ gs_trj_mode,
303
+ gs_video_quality,
304
+ submit_btn,
305
+ clear_btn,
306
+ )
307
+
308
+ def create_control_section(
309
+ self,
310
+ ) -> Tuple[
311
+ gr.Button,
312
+ gr.ClearButton,
313
+ gr.Dropdown,
314
+ gr.Checkbox,
315
+ gr.Checkbox,
316
+ gr.Checkbox,
317
+ gr.Checkbox,
318
+ gr.Checkbox,
319
+ gr.Dropdown,
320
+ gr.Checkbox,
321
+ gr.Textbox,
322
+ ]:
323
+ """
324
+ Create the control section with buttons and options.
325
+
326
+ Returns:
327
+ Tuple of control components
328
+ """
329
+ with gr.Row():
330
+ submit_btn = gr.Button("Reconstruct", scale=1, variant="primary")
331
+ clear_btn = gr.ClearButton(
332
+ scale=1,
333
+ )
334
+
335
+ with gr.Row():
336
+ frame_filter = gr.Dropdown(
337
+ choices=["All"], value="All", label="Show Points from Frame"
338
+ )
339
+ with gr.Column():
340
+ gr.Markdown("### Visualization Option: (Click Reconstruct to update)")
341
+ show_cam = gr.Checkbox(label="Show Camera", value=True)
342
+ show_mesh = gr.Checkbox(label="Show Mesh", value=True)
343
+ filter_black_bg = gr.Checkbox(label="Filter Black Background", value=False)
344
+ filter_white_bg = gr.Checkbox(label="Filter White Background", value=False)
345
+ gr.Markdown("### Reconstruction Options: (updated on next run)")
346
+ apply_mask_checkbox = gr.Checkbox(
347
+ label="Apply mask for predicted ambiguous depth classes & edges",
348
+ value=True,
349
+ )
350
+ process_res_method_dropdown = gr.Dropdown(
351
+ choices=[
352
+ "upper_bound_resize",
353
+ "upper_bound_crop",
354
+ "lower_bound_resize",
355
+ "lower_bound_crop",
356
+ ],
357
+ value="upper_bound_resize",
358
+ label="Image Processing Method",
359
+ info="Method for resizing input images",
360
+ )
361
+ save_to_gallery_checkbox = gr.Checkbox(
362
+ label="Save to Gallery",
363
+ value=False,
364
+ info="Save current reconstruction results to gallery directory",
365
+ )
366
+ gallery_name_input = gr.Textbox(
367
+ label="Gallery Name",
368
+ placeholder="Enter a name for the gallery folder",
369
+ value="",
370
+ info="Leave empty for auto-generated name with timestamp",
371
+ )
372
+
373
+ return (
374
+ submit_btn,
375
+ clear_btn,
376
+ frame_filter,
377
+ show_cam,
378
+ show_mesh,
379
+ filter_black_bg,
380
+ filter_white_bg,
381
+ apply_mask_checkbox,
382
+ process_res_method_dropdown,
383
+ save_to_gallery_checkbox,
384
+ gallery_name_input,
385
+ )
386
+
387
+ def create_example_scenes_section(self) -> List[Dict[str, Any]]:
388
+ """
389
+ Create the example scenes section.
390
+
391
+ Returns:
392
+ List of scene information dictionaries
393
+ """
394
+ # Get workspace directory from environment variable
395
+ workspace_dir = os.environ.get("DA3_WORKSPACE_DIR", "gradio_workspace")
396
+ examples_dir = os.path.join(workspace_dir, "examples")
397
+
398
+ # Get scene information
399
+ scenes = get_scene_info(examples_dir)
400
+
401
+ return scenes
402
+
403
+ def create_example_scene_grid(self, scenes: List[Dict[str, Any]]) -> List[gr.Image]:
404
+ """
405
+ Create the example scene grid.
406
+
407
+ Args:
408
+ scenes: List of scene information dictionaries
409
+
410
+ Returns:
411
+ List of scene image components
412
+ """
413
+ scene_components = []
414
+
415
+ if scenes:
416
+ for i in range(0, len(scenes), 4): # Process 4 scenes per row
417
+ with gr.Row():
418
+ for j in range(4):
419
+ scene_idx = i + j
420
+ if scene_idx < len(scenes):
421
+ scene = scenes[scene_idx]
422
+ with gr.Column(scale=1, elem_classes=["clickable-thumbnail"]):
423
+ # Clickable thumbnail
424
+ scene_img = gr.Image(
425
+ value=scene["thumbnail"],
426
+ height=150,
427
+ interactive=False,
428
+ show_label=False,
429
+ elem_id=f"scene_thumb_{scene['name']}",
430
+ sources=[],
431
+ )
432
+ scene_components.append(scene_img)
433
+
434
+ # Scene name and image count as text below thumbnail
435
+ gr.Markdown(
436
+ f"**{scene['name']}** \n {scene['num_images']} images",
437
+ elem_classes=["scene-info"],
438
+ )
439
+ else:
440
+ # Empty column to maintain grid structure
441
+ with gr.Column(scale=1):
442
+ pass
443
+
444
+ return scene_components
445
+
446
+ def create_header_section(self) -> gr.HTML:
447
+ """
448
+ Create the header section with logo and title.
449
+
450
+ Returns:
451
+ Header HTML component
452
+ """
453
+ from depth_anything_3.app.css_and_html import get_header_html
454
+
455
+ return gr.HTML(get_header_html(get_logo_base64()))
456
+
457
+ def create_description_section(self) -> gr.HTML:
458
+ """
459
+ Create the description section.
460
+
461
+ Returns:
462
+ Description HTML component
463
+ """
464
+ from depth_anything_3.app.css_and_html import get_description_html
465
+
466
+ return gr.HTML(get_description_html())
467
+
468
+ def create_acknowledgements_section(self) -> gr.HTML:
469
+ """
470
+ Create the acknowledgements section.
471
+
472
+ Returns:
473
+ Acknowledgements HTML component
474
+ """
475
+ from depth_anything_3.app.css_and_html import get_acknowledgements_html
476
+
477
+ return gr.HTML(get_acknowledgements_html())
src/depth_anything_3/app/modules/utils.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Utility functions for Depth Anything 3 Gradio app.
17
+
18
+ This module contains helper functions for data processing, visualization,
19
+ and file operations.
20
+ """
21
+
22
+
23
+ import json
24
+ import os
25
+ import shutil
26
+ from datetime import datetime
27
+ from typing import Any, Dict, List, Optional, Tuple
28
+ import numpy as np
29
+
30
+ def create_depth_visualization(depth: np.ndarray) -> Optional[np.ndarray]:
31
+ """
32
+ Create a colored depth visualization.
33
+
34
+ Args:
35
+ depth: Depth array
36
+
37
+ Returns:
38
+ Colored depth visualization or None
39
+ """
40
+ if depth is None:
41
+ return None
42
+
43
+ # Normalize depth to 0-1 range
44
+ depth_min = depth[depth > 0].min() if (depth > 0).any() else 0
45
+ depth_max = depth.max()
46
+
47
+ if depth_max <= depth_min:
48
+ return None
49
+
50
+ # Normalize depth
51
+ depth_norm = (depth - depth_min) / (depth_max - depth_min)
52
+ depth_norm = np.clip(depth_norm, 0, 1)
53
+
54
+ # Apply colormap (using matplotlib's viridis colormap)
55
+ import matplotlib.cm as cm
56
+
57
+ # Convert to colored image
58
+ depth_colored = cm.viridis(depth_norm)[:, :, :3] # Remove alpha channel
59
+ depth_colored = (depth_colored * 255).astype(np.uint8)
60
+
61
+ return depth_colored
62
+
63
+
64
+ def save_to_gallery_func(
65
+ target_dir: str, processed_data: Dict[int, Dict[str, Any]], gallery_name: Optional[str] = None
66
+ ) -> Tuple[bool, str]:
67
+ """
68
+ Save the current reconstruction results to the gallery directory.
69
+
70
+ Args:
71
+ target_dir: Source directory containing reconstruction results
72
+ processed_data: Processed data dictionary
73
+ gallery_name: Name for the gallery folder
74
+
75
+ Returns:
76
+ Tuple of (success, message)
77
+ """
78
+ try:
79
+ # Get gallery directory from environment variable or use default
80
+ gallery_dir = os.environ.get(
81
+ "DA3_GALLERY_DIR",
82
+ "workspace/gallery",
83
+ )
84
+ if not os.path.exists(gallery_dir):
85
+ os.makedirs(gallery_dir)
86
+
87
+ # Use provided name or create a unique name
88
+ if gallery_name is None or gallery_name.strip() == "":
89
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
90
+ gallery_name = f"reconstruction_{timestamp}"
91
+
92
+ gallery_path = os.path.join(gallery_dir, gallery_name)
93
+
94
+ # Check if directory already exists
95
+ if os.path.exists(gallery_path):
96
+ return False, f"Save failed: folder '{gallery_name}' already exists"
97
+
98
+ # Create the gallery directory
99
+ os.makedirs(gallery_path, exist_ok=True)
100
+
101
+ # Copy GLB file
102
+ glb_source = os.path.join(target_dir, "scene.glb")
103
+ glb_dest = os.path.join(gallery_path, "scene.glb")
104
+ if os.path.exists(glb_source):
105
+ shutil.copy2(glb_source, glb_dest)
106
+
107
+ # Copy depth visualization images
108
+ depth_vis_dir = os.path.join(target_dir, "depth_vis")
109
+ if os.path.exists(depth_vis_dir):
110
+ gallery_depth_vis = os.path.join(gallery_path, "depth_vis")
111
+ shutil.copytree(depth_vis_dir, gallery_depth_vis)
112
+
113
+ # Copy original images
114
+ images_source = os.path.join(target_dir, "images")
115
+ if os.path.exists(images_source):
116
+ gallery_images = os.path.join(gallery_path, "images")
117
+ shutil.copytree(images_source, gallery_images)
118
+
119
+ scene_preview_source = os.path.join(target_dir, "scene.jpg")
120
+ scene_preview_dest = os.path.join(gallery_path, "scene.jpg")
121
+ shutil.copy2(scene_preview_source, scene_preview_dest)
122
+
123
+ # Save metadata
124
+ metadata = {
125
+ "timestamp": datetime.now().strftime("%Y%m%d_%H%M%S"),
126
+ "num_images": len(processed_data) if processed_data else 0,
127
+ "gallery_name": gallery_name,
128
+ }
129
+
130
+ with open(os.path.join(gallery_path, "metadata.json"), "w") as f:
131
+ json.dump(metadata, f, indent=2)
132
+
133
+ print(f"Saved reconstruction to gallery: {gallery_path}")
134
+ return True, f"Save successful: saved to {gallery_path}"
135
+
136
+ except Exception as e:
137
+ print(f"Error saving to gallery: {e}")
138
+ return False, f"Save failed: {str(e)}"
139
+
140
+
141
+ def get_scene_info(examples_dir: str) -> List[Dict[str, Any]]:
142
+ """
143
+ Get information about scenes in the examples directory.
144
+
145
+ Args:
146
+ examples_dir: Path to examples directory
147
+
148
+ Returns:
149
+ List of scene information dictionaries
150
+ """
151
+ import glob
152
+
153
+ scenes = []
154
+ if not os.path.exists(examples_dir):
155
+ return scenes
156
+
157
+ for scene_folder in sorted(os.listdir(examples_dir)):
158
+ scene_path = os.path.join(examples_dir, scene_folder)
159
+ if os.path.isdir(scene_path):
160
+ # Find all image files in the scene folder
161
+ image_extensions = ["*.jpg", "*.jpeg", "*.png", "*.bmp", "*.tiff", "*.tif"]
162
+ image_files = []
163
+ for ext in image_extensions:
164
+ image_files.extend(glob.glob(os.path.join(scene_path, ext)))
165
+ image_files.extend(glob.glob(os.path.join(scene_path, ext.upper())))
166
+
167
+ if image_files:
168
+ # Sort images and get the first one for thumbnail
169
+ image_files = sorted(image_files)
170
+ first_image = image_files[0]
171
+ num_images = len(image_files)
172
+
173
+ scenes.append(
174
+ {
175
+ "name": scene_folder,
176
+ "path": scene_path,
177
+ "thumbnail": first_image,
178
+ "num_images": num_images,
179
+ "image_files": image_files,
180
+ }
181
+ )
182
+
183
+ return scenes
184
+
185
+
186
+ # NOTE: cleanup was moved to a single canonical helper in
187
+ # `depth_anything_3.utils.memory.cleanup_cuda_memory`.
188
+ # Callers should import and call that directly instead of using this module.
189
+
190
+
191
+ def get_logo_base64() -> Optional[str]:
192
+ """
193
+ Convert WAI logo to base64 for embedding in HTML.
194
+
195
+ Returns:
196
+ Base64 encoded logo string or None
197
+ """
198
+ import base64
199
+
200
+ logo_path = "examples/WAI-Logo/wai_logo.png"
201
+ try:
202
+ with open(logo_path, "rb") as img_file:
203
+ img_data = img_file.read()
204
+ base64_str = base64.b64encode(img_data).decode()
205
+ return f"data:image/png;base64,{base64_str}"
206
+ except FileNotFoundError:
207
+ return None
src/depth_anything_3/app/modules/visualization.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Visualization module for Depth Anything 3 Gradio app.
17
+
18
+ This module handles visualization updates, navigation, and measurement functionality.
19
+ """
20
+
21
+ import os
22
+ from typing import Any, Dict, List, Optional, Tuple
23
+ import cv2
24
+ import gradio as gr
25
+ import numpy as np
26
+
27
+
28
+ class VisualizationHandler:
29
+ """
30
+ Handles visualization updates and navigation for the Gradio app.
31
+ """
32
+
33
+ def __init__(self):
34
+ """Initialize the visualization handler."""
35
+
36
+ def update_view_selectors(
37
+ self, processed_data: Optional[Dict[int, Dict[str, Any]]]
38
+ ) -> Tuple[gr.Dropdown, gr.Dropdown]:
39
+ """
40
+ Update view selector dropdowns based on available views.
41
+
42
+ Args:
43
+ processed_data: Processed data dictionary
44
+
45
+ Returns:
46
+ Tuple of (depth_view_selector, measure_view_selector)
47
+ """
48
+ if processed_data is None or len(processed_data) == 0:
49
+ choices = ["View 1"]
50
+ else:
51
+ num_views = len(processed_data)
52
+ choices = [f"View {i + 1}" for i in range(num_views)]
53
+
54
+ return (
55
+ gr.Dropdown(choices=choices, value=choices[0]), # depth_view_selector
56
+ gr.Dropdown(choices=choices, value=choices[0]), # measure_view_selector
57
+ )
58
+
59
+ def get_view_data_by_index(
60
+ self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int
61
+ ) -> Optional[Dict[str, Any]]:
62
+ """
63
+ Get view data by index, handling bounds.
64
+
65
+ Args:
66
+ processed_data: Processed data dictionary
67
+ view_index: Index of the view to get
68
+
69
+ Returns:
70
+ View data dictionary or None
71
+ """
72
+ if processed_data is None or len(processed_data) == 0:
73
+ return None
74
+
75
+ view_keys = list(processed_data.keys())
76
+ if view_index < 0 or view_index >= len(view_keys):
77
+ view_index = 0
78
+
79
+ return processed_data[view_keys[view_index]]
80
+
81
+ def update_depth_view(
82
+ self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int
83
+ ) -> Optional[str]:
84
+ """
85
+ Update depth view for a specific view index.
86
+
87
+ Args:
88
+ processed_data: Processed data dictionary
89
+ view_index: Index of the view to update
90
+
91
+ Returns:
92
+ Path to depth visualization image or None
93
+ """
94
+ view_data = self.get_view_data_by_index(processed_data, view_index)
95
+ if view_data is None or view_data.get("depth_image") is None:
96
+ return None
97
+
98
+ # Return the depth visualization image directly
99
+ return view_data["depth_image"]
100
+
101
+ def navigate_depth_view(
102
+ self,
103
+ processed_data: Optional[Dict[int, Dict[str, Any]]],
104
+ current_selector_value: str,
105
+ direction: int,
106
+ ) -> Tuple[str, Optional[str]]:
107
+ """
108
+ Navigate depth view (direction: -1 for previous, +1 for next).
109
+
110
+ Args:
111
+ processed_data: Processed data dictionary
112
+ current_selector_value: Current selector value
113
+ direction: Direction to navigate (-1 for previous, +1 for next)
114
+
115
+ Returns:
116
+ Tuple of (new_selector_value, depth_vis)
117
+ """
118
+ if processed_data is None or len(processed_data) == 0:
119
+ return "View 1", None
120
+
121
+ # Parse current view number
122
+ try:
123
+ current_view = int(current_selector_value.split()[1]) - 1
124
+ except: # noqa
125
+ current_view = 0
126
+
127
+ num_views = len(processed_data)
128
+ new_view = (current_view + direction) % num_views
129
+
130
+ new_selector_value = f"View {new_view + 1}"
131
+ depth_vis = self.update_depth_view(processed_data, new_view)
132
+
133
+ return new_selector_value, depth_vis
134
+
135
+ def update_measure_view(
136
+ self, processed_data: Optional[Dict[int, Dict[str, Any]]], view_index: int
137
+ ) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], List]:
138
+ """
139
+ Update measure view for a specific view index.
140
+
141
+ Args:
142
+ processed_data: Processed data dictionary
143
+ view_index: Index of the view to update
144
+
145
+ Returns:
146
+ Tuple of (measure_image, depth_right_half, measure_points)
147
+ """
148
+ view_data = self.get_view_data_by_index(processed_data, view_index)
149
+ if view_data is None:
150
+ return None, None, [] # image, depth_right_half, measure_points
151
+
152
+ # Get the processed (resized) image
153
+ if "image" in view_data and view_data["image"] is not None:
154
+ image = view_data["image"].copy()
155
+ else:
156
+ return None, None, []
157
+
158
+ # Ensure image is in uint8 format
159
+ if image.dtype != np.uint8:
160
+ if image.max() <= 1.0:
161
+ image = (image * 255).astype(np.uint8)
162
+ else:
163
+ image = image.astype(np.uint8)
164
+
165
+ # Extract right half of the depth visualization (pure depth part)
166
+ depth_image_path = view_data.get("depth_image", None)
167
+ depth_right_half = None
168
+
169
+ if depth_image_path and os.path.exists(depth_image_path):
170
+ try:
171
+ # Load the combined depth visualization image
172
+ depth_combined = cv2.imread(depth_image_path)
173
+ depth_combined = cv2.cvtColor(depth_combined, cv2.COLOR_BGR2RGB)
174
+ if depth_combined is not None:
175
+ height, width = depth_combined.shape[:2]
176
+ # Extract right half (depth visualization part)
177
+ depth_right_half = depth_combined[:, width // 2 :]
178
+ except Exception as e:
179
+ print(f"Error extracting depth right half: {e}")
180
+
181
+ return image, depth_right_half, []
182
+
183
+ def navigate_measure_view(
184
+ self,
185
+ processed_data: Optional[Dict[int, Dict[str, Any]]],
186
+ current_selector_value: str,
187
+ direction: int,
188
+ ) -> Tuple[str, Optional[np.ndarray], Optional[str], List]:
189
+ """
190
+ Navigate measure view (direction: -1 for previous, +1 for next).
191
+
192
+ Args:
193
+ processed_data: Processed data dictionary
194
+ current_selector_value: Current selector value
195
+ direction: Direction to navigate (-1 for previous, +1 for next)
196
+
197
+ Returns:
198
+ Tuple of (new_selector_value, measure_image, depth_image_path, measure_points)
199
+ """
200
+ if processed_data is None or len(processed_data) == 0:
201
+ return "View 1", None, None, []
202
+
203
+ # Parse current view number
204
+ try:
205
+ current_view = int(current_selector_value.split()[1]) - 1
206
+ except: # noqa
207
+ current_view = 0
208
+
209
+ num_views = len(processed_data)
210
+ new_view = (current_view + direction) % num_views
211
+
212
+ new_selector_value = f"View {new_view + 1}"
213
+ measure_image, depth_right_half, measure_points = self.update_measure_view(
214
+ processed_data, new_view
215
+ )
216
+
217
+ return new_selector_value, measure_image, depth_right_half, measure_points
218
+
219
+ def populate_visualization_tabs(
220
+ self, processed_data: Optional[Dict[int, Dict[str, Any]]]
221
+ ) -> Tuple[Optional[str], Optional[np.ndarray], Optional[str], List]:
222
+ """
223
+ Populate the depth and measure tabs with processed data.
224
+
225
+ Args:
226
+ processed_data: Processed data dictionary
227
+
228
+ Returns:
229
+ Tuple of (depth_vis, measure_img, depth_image_path, measure_points)
230
+ """
231
+ if processed_data is None or len(processed_data) == 0:
232
+ return None, None, None, []
233
+
234
+ # Use update function to get depth visualization
235
+ depth_vis = self.update_depth_view(processed_data, 0)
236
+ measure_img, depth_right_half, _ = self.update_measure_view(processed_data, 0)
237
+
238
+ return depth_vis, measure_img, depth_right_half, []
239
+
240
+ def reset_measure(
241
+ self, processed_data: Optional[Dict[int, Dict[str, Any]]]
242
+ ) -> Tuple[Optional[np.ndarray], List, str]:
243
+ """
244
+ Reset measure points.
245
+
246
+ Args:
247
+ processed_data: Processed data dictionary
248
+
249
+ Returns:
250
+ Tuple of (image, measure_points, text)
251
+ """
252
+ if processed_data is None or len(processed_data) == 0:
253
+ return None, [], ""
254
+
255
+ # Return the first view image
256
+ first_view = list(processed_data.values())[0]
257
+ return first_view["image"], [], ""
258
+
259
+ def measure(
260
+ self,
261
+ processed_data: Optional[Dict[int, Dict[str, Any]]],
262
+ measure_points: List,
263
+ current_view_selector: str,
264
+ event: gr.SelectData,
265
+ ) -> List:
266
+ """
267
+ Handle measurement on images.
268
+
269
+ Args:
270
+ processed_data: Processed data dictionary
271
+ measure_points: List of current measure points
272
+ current_view_selector: Current view selector value
273
+ event: Gradio select event
274
+
275
+ Returns:
276
+ List of [image, depth_right_half, measure_points, text]
277
+ """
278
+ try:
279
+ print(f"Measure function called with selector: {current_view_selector}")
280
+
281
+ if processed_data is None or len(processed_data) == 0:
282
+ return [None, [], "No data available"]
283
+
284
+ # Use the currently selected view instead of always using the first view
285
+ try:
286
+ current_view_index = int(current_view_selector.split()[1]) - 1
287
+ except: # noqa
288
+ current_view_index = 0
289
+
290
+ print(f"Using view index: {current_view_index}")
291
+
292
+ # Get view data safely
293
+ if current_view_index < 0 or current_view_index >= len(processed_data):
294
+ current_view_index = 0
295
+
296
+ view_keys = list(processed_data.keys())
297
+ current_view = processed_data[view_keys[current_view_index]]
298
+
299
+ if current_view is None:
300
+ return [None, [], "No view data available"]
301
+
302
+ point2d = event.index[0], event.index[1]
303
+ print(f"Clicked point: {point2d}")
304
+
305
+ measure_points.append(point2d)
306
+
307
+ # Get image and depth visualization
308
+ image, depth_right_half, _ = self.update_measure_view(
309
+ processed_data, current_view_index
310
+ )
311
+ if image is None:
312
+ return [None, [], "No image available"]
313
+
314
+ image = image.copy()
315
+
316
+ # Ensure image is in uint8 format for proper cv2 operations
317
+ try:
318
+ if image.dtype != np.uint8:
319
+ if image.max() <= 1.0:
320
+ # Image is in [0, 1] range, convert to [0, 255]
321
+ image = (image * 255).astype(np.uint8)
322
+ else:
323
+ # Image is already in [0, 255] range
324
+ image = image.astype(np.uint8)
325
+ except Exception as e:
326
+ print(f"Image conversion error: {e}")
327
+ return [None, [], f"Image conversion error: {e}"]
328
+
329
+ # Draw circles for points
330
+ try:
331
+ for p in measure_points:
332
+ if 0 <= p[0] < image.shape[1] and 0 <= p[1] < image.shape[0]:
333
+ image = cv2.circle(image, p, radius=5, color=(255, 0, 0), thickness=2)
334
+ except Exception as e:
335
+ print(f"Drawing error: {e}")
336
+ return [None, [], f"Drawing error: {e}"]
337
+
338
+ # Get depth information from processed_data
339
+ depth_text = ""
340
+ try:
341
+ for i, p in enumerate(measure_points):
342
+ if (
343
+ current_view["depth"] is not None
344
+ and 0 <= p[1] < current_view["depth"].shape[0]
345
+ and 0 <= p[0] < current_view["depth"].shape[1]
346
+ ):
347
+ d = current_view["depth"][p[1], p[0]]
348
+ depth_text += f"- **P{i + 1} depth: {d:.2f}m**\n"
349
+ else:
350
+ depth_text += f"- **P{i + 1}: Click position ({p[0]}, {p[1]}) - No depth information**\n" # noqa: E501
351
+ except Exception as e:
352
+ print(f"Depth text error: {e}")
353
+ depth_text = f"Error computing depth: {e}\n"
354
+
355
+ if len(measure_points) == 2:
356
+ try:
357
+ point1, point2 = measure_points
358
+ # Draw line
359
+ if (
360
+ 0 <= point1[0] < image.shape[1]
361
+ and 0 <= point1[1] < image.shape[0]
362
+ and 0 <= point2[0] < image.shape[1]
363
+ and 0 <= point2[1] < image.shape[0]
364
+ ):
365
+ image = cv2.line(image, point1, point2, color=(255, 0, 0), thickness=2)
366
+
367
+ # Compute 3D distance using depth information and camera intrinsics
368
+ distance_text = "- **Distance: Unable to calculate 3D distance**"
369
+ if (
370
+ current_view["depth"] is not None
371
+ and 0 <= point1[1] < current_view["depth"].shape[0]
372
+ and 0 <= point1[0] < current_view["depth"].shape[1]
373
+ and 0 <= point2[1] < current_view["depth"].shape[0]
374
+ and 0 <= point2[0] < current_view["depth"].shape[1]
375
+ ):
376
+ try:
377
+ # Get depth values at the two points
378
+ d1 = current_view["depth"][point1[1], point1[0]]
379
+ d2 = current_view["depth"][point2[1], point2[0]]
380
+
381
+ # Convert 2D pixel coordinates to 3D world coordinates
382
+ if current_view["intrinsics"] is not None:
383
+ # Get camera intrinsics
384
+ K = current_view["intrinsics"] # 3x3 intrinsic matrix
385
+ fx, fy = K[0, 0], K[1, 1] # focal lengths
386
+ cx, cy = K[0, 2], K[1, 2] # principal point
387
+
388
+ # Convert pixel coordinates to normalized camera coordinates
389
+ # Point 1: (u1, v1) -> (x1, y1, z1)
390
+ u1, v1 = point1[0], point1[1]
391
+ x1 = (u1 - cx) * d1 / fx
392
+ y1 = (v1 - cy) * d1 / fy
393
+ z1 = d1
394
+
395
+ # Point 2: (u2, v2) -> (x2, y2, z2)
396
+ u2, v2 = point2[0], point2[1]
397
+ x2 = (u2 - cx) * d2 / fx
398
+ y2 = (v2 - cy) * d2 / fy
399
+ z2 = d2
400
+
401
+ # Calculate 3D Euclidean distance
402
+ p1_3d = np.array([x1, y1, z1])
403
+ p2_3d = np.array([x2, y2, z2])
404
+ distance_3d = np.linalg.norm(p1_3d - p2_3d)
405
+
406
+ distance_text = f"- **Distance: {distance_3d:.2f}m**"
407
+ else:
408
+ # Fallback to simplified calculation if no intrinsics
409
+ pixel_distance = np.sqrt(
410
+ (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
411
+ )
412
+ avg_depth = (d1 + d2) / 2
413
+ scale_factor = avg_depth / 1000 # Rough scaling factor
414
+ estimated_3d_distance = pixel_distance * scale_factor
415
+ distance_text = f"- **Distance: {estimated_3d_distance:.2f}m (estimated, no intrinsics)**" # noqa: E501
416
+
417
+ except Exception as e:
418
+ print(f"Distance computation error: {e}")
419
+ distance_text = f"- **Distance computation error: {e}**"
420
+
421
+ measure_points = []
422
+ text = depth_text + distance_text
423
+ print(f"Measurement complete: {text}")
424
+ return [image, depth_right_half, measure_points, text]
425
+ except Exception as e:
426
+ print(f"Final measurement error: {e}")
427
+ return [None, [], f"Measurement error: {e}"]
428
+ else:
429
+ print(f"Single point measurement: {depth_text}")
430
+ return [image, depth_right_half, measure_points, depth_text]
431
+
432
+ except Exception as e:
433
+ print(f"Overall measure function error: {e}")
434
+ return [None, [], f"Measure function error: {e}"]
src/depth_anything_3/cfg.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Configuration utility functions
17
+ """
18
+
19
+ import importlib
20
+ from pathlib import Path
21
+ from typing import Any, Callable, List, Union
22
+ from omegaconf import DictConfig, ListConfig, OmegaConf
23
+
24
+ try:
25
+ OmegaConf.register_new_resolver("eval", eval)
26
+ except Exception as e:
27
+ # if eval is not available, we can just pass
28
+ print(f"Error registering eval resolver: {e}")
29
+
30
+
31
+ def load_config(path: str, argv: List[str] = None) -> Union[DictConfig, ListConfig]:
32
+ """
33
+ Load a configuration. Will resolve inheritance.
34
+ Supports both file paths and module paths (e.g., depth_anything_3.configs.giant).
35
+ """
36
+ # Check if path is a module path (contains dots but no slashes and doesn't end with .yaml)
37
+ if "." in path and "/" not in path and not path.endswith(".yaml"):
38
+ # It's a module path, load from package resources
39
+ path_parts = path.split(".")[1:]
40
+ config_path = Path(__file__).resolve().parent
41
+ for part in path_parts:
42
+ config_path = config_path.joinpath(part)
43
+ config_path = config_path.with_suffix(".yaml")
44
+ config = OmegaConf.load(str(config_path))
45
+ else:
46
+ # It's a file path (absolute, relative, or with .yaml extension)
47
+ config = OmegaConf.load(path)
48
+
49
+ if argv is not None:
50
+ config_argv = OmegaConf.from_dotlist(argv)
51
+ config = OmegaConf.merge(config, config_argv)
52
+ config = resolve_recursive(config, resolve_inheritance)
53
+ return config
54
+
55
+
56
+ def resolve_recursive(
57
+ config: Any,
58
+ resolver: Callable[[Union[DictConfig, ListConfig]], Union[DictConfig, ListConfig]],
59
+ ) -> Any:
60
+ config = resolver(config)
61
+ if isinstance(config, DictConfig):
62
+ for k in config.keys():
63
+ v = config.get(k)
64
+ if isinstance(v, (DictConfig, ListConfig)):
65
+ config[k] = resolve_recursive(v, resolver)
66
+ if isinstance(config, ListConfig):
67
+ for i in range(len(config)):
68
+ v = config.get(i)
69
+ if isinstance(v, (DictConfig, ListConfig)):
70
+ config[i] = resolve_recursive(v, resolver)
71
+ return config
72
+
73
+
74
+ def resolve_inheritance(config: Union[DictConfig, ListConfig]) -> Any:
75
+ """
76
+ Recursively resolve inheritance if the config contains:
77
+ __inherit__: path/to/parent.yaml or a ListConfig of such paths.
78
+ """
79
+ if isinstance(config, DictConfig):
80
+ inherit = config.pop("__inherit__", None)
81
+
82
+ if inherit:
83
+ inherit_list = inherit if isinstance(inherit, ListConfig) else [inherit]
84
+
85
+ parent_config = None
86
+ for parent_path in inherit_list:
87
+ assert isinstance(parent_path, str)
88
+ parent_config = (
89
+ load_config(parent_path)
90
+ if parent_config is None
91
+ else OmegaConf.merge(parent_config, load_config(parent_path))
92
+ )
93
+
94
+ if len(config.keys()) > 0:
95
+ config = OmegaConf.merge(parent_config, config)
96
+ else:
97
+ config = parent_config
98
+ return config
99
+
100
+
101
+ def import_item(path: str, name: str) -> Any:
102
+ """
103
+ Import a python item. Example: import_item("path.to.file", "MyClass") -> MyClass
104
+ """
105
+ return getattr(importlib.import_module(path), name)
106
+
107
+
108
+ def create_object(config: DictConfig) -> Any:
109
+ """
110
+ Create an object from config.
111
+ The config is expected to contains the following:
112
+ __object__:
113
+ path: path.to.module
114
+ name: MyClass
115
+ args: as_config | as_params (default to as_config)
116
+ """
117
+ config = DictConfig(config)
118
+ item = import_item(
119
+ path=config.__object__.path,
120
+ name=config.__object__.name,
121
+ )
122
+ args = config.__object__.get("args", "as_config")
123
+ if args == "as_config":
124
+ return item(config)
125
+ if args == "as_params":
126
+ config = OmegaConf.to_object(config)
127
+ config.pop("__object__")
128
+ return item(**config)
129
+ raise NotImplementedError(f"Unknown args type: {args}")
130
+
131
+
132
+ def create_dataset(path: str, *args, **kwargs) -> Any:
133
+ """
134
+ Create a dataset. Requires the file to contain a "create_dataset" function.
135
+ """
136
+ return import_item(path, "create_dataset")(*args, **kwargs)
137
+
138
+
139
+ def to_dict_recursive(config_obj):
140
+ if isinstance(config_obj, DictConfig):
141
+ return {k: to_dict_recursive(v) for k, v in config_obj.items()}
142
+ elif isinstance(config_obj, ListConfig):
143
+ return [to_dict_recursive(item) for item in config_obj]
144
+ return config_obj
src/depth_anything_3/cli.py ADDED
@@ -0,0 +1,803 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: E402
2
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Refactored Depth Anything 3 CLI
17
+ Clean, modular command-line interface
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import typer
24
+
25
+ from depth_anything_3.services import start_server
26
+ from depth_anything_3.services.gallery import gallery as gallery_main
27
+ from depth_anything_3.services.inference_service import run_inference
28
+ from depth_anything_3.services.input_handlers import (
29
+ ColmapHandler,
30
+ ImageHandler,
31
+ ImagesHandler,
32
+ InputHandler,
33
+ VideoHandler,
34
+ parse_export_feat,
35
+ )
36
+ from depth_anything_3.utils.constants import (
37
+ DEFAULT_EXPORT_DIR,
38
+ DEFAULT_GALLERY_DIR,
39
+ DEFAULT_GRADIO_DIR,
40
+ DEFAULT_MODEL,
41
+ )
42
+
43
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
44
+
45
+ app = typer.Typer(help="Depth Anything 3 - Video depth estimation CLI", add_completion=False)
46
+
47
+
48
+ # ============================================================================
49
+ # Input type detection utilities
50
+ # ============================================================================
51
+
52
+ # Supported file extensions
53
+ IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tiff", ".tif"}
54
+ VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".flv", ".wmv", ".webm", ".m4v"}
55
+
56
+
57
+ def detect_input_type(input_path: str) -> str:
58
+ """
59
+ Detect input type from path.
60
+
61
+ Returns:
62
+ - "image": Single image file
63
+ - "images": Directory containing images
64
+ - "video": Video file
65
+ - "colmap": COLMAP directory structure
66
+ - "unknown": Cannot determine type
67
+ """
68
+ if not os.path.exists(input_path):
69
+ return "unknown"
70
+
71
+ # Check if it's a file
72
+ if os.path.isfile(input_path):
73
+ ext = os.path.splitext(input_path)[1].lower()
74
+ if ext in IMAGE_EXTENSIONS:
75
+ return "image"
76
+ elif ext in VIDEO_EXTENSIONS:
77
+ return "video"
78
+ return "unknown"
79
+
80
+ # Check if it's a directory
81
+ if os.path.isdir(input_path):
82
+ # Check for COLMAP structure
83
+ images_dir = os.path.join(input_path, "images")
84
+ sparse_dir = os.path.join(input_path, "sparse")
85
+
86
+ if os.path.isdir(images_dir) and os.path.isdir(sparse_dir):
87
+ return "colmap"
88
+
89
+ # Check if directory contains image files
90
+ for item in os.listdir(input_path):
91
+ item_path = os.path.join(input_path, item)
92
+ if os.path.isfile(item_path):
93
+ ext = os.path.splitext(item)[1].lower()
94
+ if ext in IMAGE_EXTENSIONS:
95
+ return "images"
96
+
97
+ return "unknown"
98
+
99
+ return "unknown"
100
+
101
+
102
+ # ============================================================================
103
+ # Common parameters and configuration
104
+ # ============================================================================
105
+
106
+ # ============================================================================
107
+ # Inference commands
108
+ # ============================================================================
109
+
110
+
111
+ @app.command()
112
+ def auto(
113
+ input_path: str = typer.Argument(
114
+ ..., help="Path to input (image, directory, video, or COLMAP)"
115
+ ),
116
+ model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"),
117
+ export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"),
118
+ export_format: str = typer.Option("glb", help="Export format"),
119
+ device: str = typer.Option("cuda", help="Device to use"),
120
+ use_backend: bool = typer.Option(False, help="Use backend service for inference"),
121
+ backend_url: str = typer.Option(
122
+ "http://localhost:8008", help="Backend URL (default: http://localhost:8008)"
123
+ ),
124
+ process_res: int = typer.Option(504, help="Processing resolution"),
125
+ process_res_method: str = typer.Option(
126
+ "upper_bound_resize", help="Processing resolution method"
127
+ ),
128
+ export_feat: str = typer.Option(
129
+ "",
130
+ help="[FEAT_VIS]Export features from specified layers using comma-separated indices (e.g., '0,1,2').",
131
+ ),
132
+ auto_cleanup: bool = typer.Option(
133
+ False, help="Automatically clean export directory if it exists (no prompt)"
134
+ ),
135
+ # Video-specific options
136
+ fps: float = typer.Option(1.0, help="[Video] Sampling FPS for frame extraction"),
137
+ # COLMAP-specific options
138
+ sparse_subdir: str = typer.Option(
139
+ "", help="[COLMAP] Sparse reconstruction subdirectory (e.g., '0' for sparse/0/)"
140
+ ),
141
+ align_to_input_ext_scale: bool = typer.Option(
142
+ True, help="[COLMAP] Align prediction to input extrinsics scale"
143
+ ),
144
+ # Pose estimation options
145
+ use_ray_pose: bool = typer.Option(
146
+ False, help="Use ray-based pose estimation instead of camera decoder"
147
+ ),
148
+ ref_view_strategy: str = typer.Option(
149
+ "saddle_balanced",
150
+ help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range",
151
+ ),
152
+ # GLB export options
153
+ conf_thresh_percentile: float = typer.Option(
154
+ 40.0, help="[GLB] Lower percentile for adaptive confidence threshold"
155
+ ),
156
+ num_max_points: int = typer.Option(
157
+ 1_000_000, help="[GLB] Maximum number of points in the point cloud"
158
+ ),
159
+ show_cameras: bool = typer.Option(
160
+ True, help="[GLB] Show camera wireframes in the exported scene"
161
+ ),
162
+ # Feat_vis export options
163
+ feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"),
164
+ ):
165
+ """
166
+ Automatically detect input type and run appropriate processing.
167
+
168
+ Supports:
169
+ - Single image file (.jpg, .png, etc.)
170
+ - Directory of images
171
+ - Video file (.mp4, .avi, etc.)
172
+ - COLMAP directory (with 'images' and 'sparse' subdirectories)
173
+ """
174
+ # Detect input type
175
+ input_type = detect_input_type(input_path)
176
+
177
+ if input_type == "unknown":
178
+ typer.echo(f"❌ Error: Cannot determine input type for: {input_path}", err=True)
179
+ typer.echo("Supported inputs:", err=True)
180
+ typer.echo(" - Single image file (.jpg, .png, etc.)", err=True)
181
+ typer.echo(" - Directory containing images", err=True)
182
+ typer.echo(" - Video file (.mp4, .avi, etc.)", err=True)
183
+ typer.echo(" - COLMAP directory (with 'images/' and 'sparse/' subdirectories)", err=True)
184
+ raise typer.Exit(1)
185
+
186
+ # Display detected type
187
+ typer.echo(f"🔍 Detected input type: {input_type.upper()}")
188
+ typer.echo(f"📁 Input path: {input_path}")
189
+ typer.echo()
190
+
191
+ # Determine backend URL based on use_backend flag
192
+ final_backend_url = backend_url if use_backend else None
193
+
194
+ # Parse export_feat parameter
195
+ export_feat_layers = parse_export_feat(export_feat)
196
+
197
+ # Route to appropriate handler
198
+ if input_type == "image":
199
+ typer.echo("Processing single image...")
200
+ # Process input
201
+ image_files = ImageHandler.process(input_path)
202
+
203
+ # Handle export directory
204
+ export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup)
205
+
206
+ # Run inference
207
+ run_inference(
208
+ image_paths=image_files,
209
+ export_dir=export_dir,
210
+ model_dir=model_dir,
211
+ device=device,
212
+ backend_url=final_backend_url,
213
+ export_format=export_format,
214
+ process_res=process_res,
215
+ process_res_method=process_res_method,
216
+ export_feat_layers=export_feat_layers,
217
+ use_ray_pose=use_ray_pose,
218
+ ref_view_strategy=ref_view_strategy,
219
+ conf_thresh_percentile=conf_thresh_percentile,
220
+ num_max_points=num_max_points,
221
+ show_cameras=show_cameras,
222
+ feat_vis_fps=feat_vis_fps,
223
+ )
224
+
225
+ elif input_type == "images":
226
+ typer.echo("Processing directory of images...")
227
+ # Process input - use default extensions
228
+ image_files = ImagesHandler.process(input_path, "png,jpg,jpeg")
229
+
230
+ # Handle export directory
231
+ export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup)
232
+
233
+ # Run inference
234
+ run_inference(
235
+ image_paths=image_files,
236
+ export_dir=export_dir,
237
+ model_dir=model_dir,
238
+ device=device,
239
+ backend_url=final_backend_url,
240
+ export_format=export_format,
241
+ process_res=process_res,
242
+ process_res_method=process_res_method,
243
+ export_feat_layers=export_feat_layers,
244
+ use_ray_pose=use_ray_pose,
245
+ ref_view_strategy=ref_view_strategy,
246
+ conf_thresh_percentile=conf_thresh_percentile,
247
+ num_max_points=num_max_points,
248
+ show_cameras=show_cameras,
249
+ feat_vis_fps=feat_vis_fps,
250
+ )
251
+
252
+ elif input_type == "video":
253
+ typer.echo(f"Processing video with FPS={fps}...")
254
+ # Handle export directory
255
+ export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup)
256
+
257
+ # Process input
258
+ image_files = VideoHandler.process(input_path, export_dir, fps)
259
+
260
+ # Run inference
261
+ run_inference(
262
+ image_paths=image_files,
263
+ export_dir=export_dir,
264
+ model_dir=model_dir,
265
+ device=device,
266
+ backend_url=final_backend_url,
267
+ export_format=export_format,
268
+ process_res=process_res,
269
+ process_res_method=process_res_method,
270
+ export_feat_layers=export_feat_layers,
271
+ use_ray_pose=use_ray_pose,
272
+ ref_view_strategy=ref_view_strategy,
273
+ conf_thresh_percentile=conf_thresh_percentile,
274
+ num_max_points=num_max_points,
275
+ show_cameras=show_cameras,
276
+ feat_vis_fps=feat_vis_fps,
277
+ )
278
+
279
+ elif input_type == "colmap":
280
+ typer.echo(
281
+ f"Processing COLMAP directory (sparse subdirectory: '{sparse_subdir or 'default'}')..."
282
+ )
283
+ # Process input
284
+ image_files, extrinsics, intrinsics = ColmapHandler.process(input_path, sparse_subdir)
285
+
286
+ # Handle export directory
287
+ export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup)
288
+
289
+ # Run inference
290
+ run_inference(
291
+ image_paths=image_files,
292
+ export_dir=export_dir,
293
+ model_dir=model_dir,
294
+ device=device,
295
+ backend_url=final_backend_url,
296
+ export_format=export_format,
297
+ process_res=process_res,
298
+ process_res_method=process_res_method,
299
+ export_feat_layers=export_feat_layers,
300
+ extrinsics=extrinsics,
301
+ intrinsics=intrinsics,
302
+ align_to_input_ext_scale=align_to_input_ext_scale,
303
+ use_ray_pose=use_ray_pose,
304
+ ref_view_strategy=ref_view_strategy,
305
+ conf_thresh_percentile=conf_thresh_percentile,
306
+ num_max_points=num_max_points,
307
+ show_cameras=show_cameras,
308
+ feat_vis_fps=feat_vis_fps,
309
+ )
310
+
311
+ typer.echo()
312
+ typer.echo("✅ Processing completed successfully!")
313
+
314
+
315
+ @app.command()
316
+ def image(
317
+ image_path: str = typer.Argument(..., help="Path to input image file"),
318
+ model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"),
319
+ export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"),
320
+ export_format: str = typer.Option("glb", help="Export format"),
321
+ device: str = typer.Option("cuda", help="Device to use"),
322
+ use_backend: bool = typer.Option(False, help="Use backend service for inference"),
323
+ backend_url: str = typer.Option(
324
+ "http://localhost:8008", help="Backend URL (default: http://localhost:8008)"
325
+ ),
326
+ process_res: int = typer.Option(504, help="Processing resolution"),
327
+ process_res_method: str = typer.Option(
328
+ "upper_bound_resize", help="Processing resolution method"
329
+ ),
330
+ export_feat: str = typer.Option(
331
+ "",
332
+ help="[FEAT_VIS] Export features from specified layers using comma-separated indices (e.g., '0,1,2').",
333
+ ),
334
+ auto_cleanup: bool = typer.Option(
335
+ False, help="Automatically clean export directory if it exists (no prompt)"
336
+ ),
337
+ # Pose estimation options
338
+ use_ray_pose: bool = typer.Option(
339
+ False, help="Use ray-based pose estimation instead of camera decoder"
340
+ ),
341
+ ref_view_strategy: str = typer.Option(
342
+ "saddle_balanced",
343
+ help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range",
344
+ ),
345
+ # GLB export options
346
+ conf_thresh_percentile: float = typer.Option(
347
+ 40.0, help="[GLB] Lower percentile for adaptive confidence threshold"
348
+ ),
349
+ num_max_points: int = typer.Option(
350
+ 1_000_000, help="[GLB] Maximum number of points in the point cloud"
351
+ ),
352
+ show_cameras: bool = typer.Option(
353
+ True, help="[GLB] Show camera wireframes in the exported scene"
354
+ ),
355
+ # Feat_vis export options
356
+ feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"),
357
+ ):
358
+ """Run camera pose and depth estimation on a single image."""
359
+ # Process input
360
+ image_files = ImageHandler.process(image_path)
361
+
362
+ # Handle export directory
363
+ export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup)
364
+
365
+ # Parse export_feat parameter
366
+ export_feat_layers = parse_export_feat(export_feat)
367
+
368
+ # Determine backend URL based on use_backend flag
369
+ final_backend_url = backend_url if use_backend else None
370
+
371
+ # Run inference
372
+ run_inference(
373
+ image_paths=image_files,
374
+ export_dir=export_dir,
375
+ model_dir=model_dir,
376
+ device=device,
377
+ backend_url=final_backend_url,
378
+ export_format=export_format,
379
+ process_res=process_res,
380
+ process_res_method=process_res_method,
381
+ export_feat_layers=export_feat_layers,
382
+ use_ray_pose=use_ray_pose,
383
+ reference_view_strategy=reference_view_strategy,
384
+ conf_thresh_percentile=conf_thresh_percentile,
385
+ num_max_points=num_max_points,
386
+ show_cameras=show_cameras,
387
+ feat_vis_fps=feat_vis_fps,
388
+ )
389
+
390
+
391
+ @app.command()
392
+ def images(
393
+ images_dir: str = typer.Argument(..., help="Path to directory containing input images"),
394
+ image_extensions: str = typer.Option(
395
+ "png,jpg,jpeg", help="Comma-separated image file extensions to process"
396
+ ),
397
+ model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"),
398
+ export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"),
399
+ export_format: str = typer.Option("glb", help="Export format"),
400
+ device: str = typer.Option("cuda", help="Device to use"),
401
+ use_backend: bool = typer.Option(False, help="Use backend service for inference"),
402
+ backend_url: str = typer.Option(
403
+ "http://localhost:8008", help="Backend URL (default: http://localhost:8008)"
404
+ ),
405
+ process_res: int = typer.Option(504, help="Processing resolution"),
406
+ process_res_method: str = typer.Option(
407
+ "upper_bound_resize", help="Processing resolution method"
408
+ ),
409
+ export_feat: str = typer.Option(
410
+ "",
411
+ help="[FEAT_VIS] Export features from specified layers using comma-separated indices (e.g., '0,1,2').",
412
+ ),
413
+ auto_cleanup: bool = typer.Option(
414
+ False, help="Automatically clean export directory if it exists (no prompt)"
415
+ ),
416
+ # Pose estimation options
417
+ use_ray_pose: bool = typer.Option(
418
+ False, help="Use ray-based pose estimation instead of camera decoder"
419
+ ),
420
+ ref_view_strategy: str = typer.Option(
421
+ "saddle_balanced",
422
+ help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range",
423
+ ),
424
+ # GLB export options
425
+ conf_thresh_percentile: float = typer.Option(
426
+ 40.0, help="[GLB] Lower percentile for adaptive confidence threshold"
427
+ ),
428
+ num_max_points: int = typer.Option(
429
+ 1_000_000, help="[GLB] Maximum number of points in the point cloud"
430
+ ),
431
+ show_cameras: bool = typer.Option(
432
+ True, help="[GLB] Show camera wireframes in the exported scene"
433
+ ),
434
+ # Feat_vis export options
435
+ feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"),
436
+ ):
437
+ """Run camera pose and depth estimation on a directory of images."""
438
+ # Process input
439
+ image_files = ImagesHandler.process(images_dir, image_extensions)
440
+
441
+ # Handle export directory
442
+ export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup)
443
+
444
+ # Parse export_feat parameter
445
+ export_feat_layers = parse_export_feat(export_feat)
446
+
447
+ # Determine backend URL based on use_backend flag
448
+ final_backend_url = backend_url if use_backend else None
449
+
450
+ # Run inference
451
+ run_inference(
452
+ image_paths=image_files,
453
+ export_dir=export_dir,
454
+ model_dir=model_dir,
455
+ device=device,
456
+ backend_url=final_backend_url,
457
+ export_format=export_format,
458
+ process_res=process_res,
459
+ process_res_method=process_res_method,
460
+ export_feat_layers=export_feat_layers,
461
+ use_ray_pose=use_ray_pose,
462
+ reference_view_strategy=reference_view_strategy,
463
+ conf_thresh_percentile=conf_thresh_percentile,
464
+ num_max_points=num_max_points,
465
+ show_cameras=show_cameras,
466
+ feat_vis_fps=feat_vis_fps,
467
+ )
468
+
469
+
470
+ @app.command()
471
+ def colmap(
472
+ colmap_dir: str = typer.Argument(
473
+ ..., help="Path to COLMAP directory containing 'images' and 'sparse' subdirectories"
474
+ ),
475
+ sparse_subdir: str = typer.Option(
476
+ "", help="Sparse reconstruction subdirectory (e.g., '0' for sparse/0/, empty for sparse/)"
477
+ ),
478
+ align_to_input_ext_scale: bool = typer.Option(
479
+ True, help="Align prediction to input extrinsics scale"
480
+ ),
481
+ model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"),
482
+ export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"),
483
+ export_format: str = typer.Option("glb", help="Export format"),
484
+ device: str = typer.Option("cuda", help="Device to use"),
485
+ use_backend: bool = typer.Option(False, help="Use backend service for inference"),
486
+ backend_url: str = typer.Option(
487
+ "http://localhost:8008", help="Backend URL (default: http://localhost:8008)"
488
+ ),
489
+ process_res: int = typer.Option(504, help="Processing resolution"),
490
+ process_res_method: str = typer.Option(
491
+ "upper_bound_resize", help="Processing resolution method"
492
+ ),
493
+ export_feat: str = typer.Option(
494
+ "",
495
+ help="Export features from specified layers using comma-separated indices (e.g., '0,1,2').",
496
+ ),
497
+ auto_cleanup: bool = typer.Option(
498
+ False, help="Automatically clean export directory if it exists (no prompt)"
499
+ ),
500
+ # Pose estimation options
501
+ use_ray_pose: bool = typer.Option(
502
+ False, help="Use ray-based pose estimation instead of camera decoder"
503
+ ),
504
+ ref_view_strategy: str = typer.Option(
505
+ "saddle_balanced",
506
+ help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range",
507
+ ),
508
+ # GLB export options
509
+ conf_thresh_percentile: float = typer.Option(
510
+ 40.0, help="[GLB] Lower percentile for adaptive confidence threshold"
511
+ ),
512
+ num_max_points: int = typer.Option(
513
+ 1_000_000, help="[GLB] Maximum number of points in the point cloud"
514
+ ),
515
+ show_cameras: bool = typer.Option(
516
+ True, help="[GLB] Show camera wireframes in the exported scene"
517
+ ),
518
+ # Feat_vis export options
519
+ feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"),
520
+ ):
521
+ """Run pose conditioned depth estimation on COLMAP data."""
522
+ # Process input
523
+ image_files, extrinsics, intrinsics = ColmapHandler.process(colmap_dir, sparse_subdir)
524
+
525
+ # Handle export directory
526
+ export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup)
527
+
528
+ # Parse export_feat parameter
529
+ export_feat_layers = parse_export_feat(export_feat)
530
+
531
+ # Determine backend URL based on use_backend flag
532
+ final_backend_url = backend_url if use_backend else None
533
+
534
+ # Run inference
535
+ run_inference(
536
+ image_paths=image_files,
537
+ export_dir=export_dir,
538
+ model_dir=model_dir,
539
+ device=device,
540
+ backend_url=final_backend_url,
541
+ export_format=export_format,
542
+ process_res=process_res,
543
+ process_res_method=process_res_method,
544
+ export_feat_layers=export_feat_layers,
545
+ extrinsics=extrinsics,
546
+ intrinsics=intrinsics,
547
+ align_to_input_ext_scale=align_to_input_ext_scale,
548
+ use_ray_pose=use_ray_pose,
549
+ reference_view_strategy=reference_view_strategy,
550
+ conf_thresh_percentile=conf_thresh_percentile,
551
+ num_max_points=num_max_points,
552
+ show_cameras=show_cameras,
553
+ feat_vis_fps=feat_vis_fps,
554
+ )
555
+
556
+
557
+ @app.command()
558
+ def video(
559
+ video_path: str = typer.Argument(..., help="Path to input video file"),
560
+ fps: float = typer.Option(1.0, help="Sampling FPS for frame extraction"),
561
+ model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"),
562
+ export_dir: str = typer.Option(DEFAULT_EXPORT_DIR, help="Export directory"),
563
+ export_format: str = typer.Option("glb", help="Export format"),
564
+ device: str = typer.Option("cuda", help="Device to use"),
565
+ use_backend: bool = typer.Option(False, help="Use backend service for inference"),
566
+ backend_url: str = typer.Option(
567
+ "http://localhost:8008", help="Backend URL (default: http://localhost:8008)"
568
+ ),
569
+ process_res: int = typer.Option(504, help="Processing resolution"),
570
+ process_res_method: str = typer.Option(
571
+ "upper_bound_resize", help="Processing resolution method"
572
+ ),
573
+ export_feat: str = typer.Option(
574
+ "",
575
+ help="[FEAT_VIS] Export features from specified layers using comma-separated indices (e.g., '0,1,2').",
576
+ ),
577
+ auto_cleanup: bool = typer.Option(
578
+ False, help="Automatically clean export directory if it exists (no prompt)"
579
+ ),
580
+ # Pose estimation options
581
+ use_ray_pose: bool = typer.Option(
582
+ False, help="Use ray-based pose estimation instead of camera decoder"
583
+ ),
584
+ ref_view_strategy: str = typer.Option(
585
+ "saddle_balanced",
586
+ help="Reference view selection strategy: empty, first, middle, saddle_balanced, saddle_sim_range",
587
+ ),
588
+ # GLB export options
589
+ conf_thresh_percentile: float = typer.Option(
590
+ 40.0, help="[GLB] Lower percentile for adaptive confidence threshold"
591
+ ),
592
+ num_max_points: int = typer.Option(
593
+ 1_000_000, help="[GLB] Maximum number of points in the point cloud"
594
+ ),
595
+ show_cameras: bool = typer.Option(
596
+ True, help="[GLB] Show camera wireframes in the exported scene"
597
+ ),
598
+ # Feat_vis export options
599
+ feat_vis_fps: int = typer.Option(15, help="[FEAT_VIS] Frame rate for output video"),
600
+ ):
601
+ """Run depth estimation on video by extracting frames and processing them."""
602
+ # Handle export directory
603
+ export_dir = InputHandler.handle_export_dir(export_dir, auto_cleanup)
604
+
605
+ # Process input
606
+ image_files = VideoHandler.process(video_path, export_dir, fps)
607
+
608
+ # Parse export_feat parameter
609
+ export_feat_layers = parse_export_feat(export_feat)
610
+
611
+ # Determine backend URL based on use_backend flag
612
+ final_backend_url = backend_url if use_backend else None
613
+
614
+ # Run inference
615
+ run_inference(
616
+ image_paths=image_files,
617
+ export_dir=export_dir,
618
+ model_dir=model_dir,
619
+ device=device,
620
+ backend_url=final_backend_url,
621
+ export_format=export_format,
622
+ process_res=process_res,
623
+ process_res_method=process_res_method,
624
+ export_feat_layers=export_feat_layers,
625
+ use_ray_pose=use_ray_pose,
626
+ reference_view_strategy=reference_view_strategy,
627
+ conf_thresh_percentile=conf_thresh_percentile,
628
+ num_max_points=num_max_points,
629
+ show_cameras=show_cameras,
630
+ feat_vis_fps=feat_vis_fps,
631
+ )
632
+
633
+
634
+ # ============================================================================
635
+ # Service management commands
636
+ # ============================================================================
637
+
638
+
639
+ @app.command()
640
+ def backend(
641
+ model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"),
642
+ device: str = typer.Option("cuda", help="Device to use"),
643
+ host: str = typer.Option("127.0.0.1", help="Host to bind to"),
644
+ port: int = typer.Option(8008, help="Port to bind to"),
645
+ gallery_dir: str = typer.Option(DEFAULT_GALLERY_DIR, help="Gallery directory path (optional)"),
646
+ ):
647
+ """Start model backend service with integrated gallery."""
648
+ typer.echo("=" * 60)
649
+ typer.echo("🚀 Starting Depth Anything 3 Backend Server")
650
+ typer.echo("=" * 60)
651
+ typer.echo(f"Model directory: {model_dir}")
652
+ typer.echo(f"Device: {device}")
653
+
654
+ # Check if gallery directory exists
655
+ if gallery_dir and os.path.exists(gallery_dir):
656
+ typer.echo(f"Gallery directory: {gallery_dir}")
657
+ else:
658
+ gallery_dir = None # Disable gallery if directory doesn't exist
659
+
660
+ typer.echo()
661
+ typer.echo("📡 Server URLs (Ctrl/CMD+Click to open):")
662
+ typer.echo(f" 🏠 Home: http://{host}:{port}")
663
+ typer.echo(f" 📊 Dashboard: http://{host}:{port}/dashboard")
664
+ typer.echo(f" 📈 API Status: http://{host}:{port}/status")
665
+
666
+ if gallery_dir:
667
+ typer.echo(f" 🎨 Gallery: http://{host}:{port}/gallery/")
668
+
669
+ typer.echo("=" * 60)
670
+
671
+ try:
672
+ start_server(model_dir, device, host, port, gallery_dir)
673
+ except KeyboardInterrupt:
674
+ typer.echo("\n👋 Backend server stopped.")
675
+ except Exception as e:
676
+ typer.echo(f"❌ Failed to start backend: {e}")
677
+ raise typer.Exit(1)
678
+
679
+
680
+ # ============================================================================
681
+ # Application launch commands
682
+ # ============================================================================
683
+
684
+
685
+ @app.command()
686
+ def gradio(
687
+ model_dir: str = typer.Option(DEFAULT_MODEL, help="Model directory path"),
688
+ workspace_dir: str = typer.Option(DEFAULT_GRADIO_DIR, help="Workspace directory path"),
689
+ gallery_dir: str = typer.Option(DEFAULT_GALLERY_DIR, help="Gallery directory path"),
690
+ host: str = typer.Option("127.0.0.1", help="Host address to bind to"),
691
+ port: int = typer.Option(7860, help="Port number to bind to"),
692
+ share: bool = typer.Option(False, help="Create a public link for the app"),
693
+ debug: bool = typer.Option(False, help="Enable debug mode"),
694
+ cache_examples: bool = typer.Option(
695
+ False, help="Pre-cache all example scenes at startup for faster loading"
696
+ ),
697
+ cache_gs_tag: str = typer.Option(
698
+ "",
699
+ help="Tag to match scene names for high-res+3DGS caching (e.g., 'dl3dv'). Scenes containing this tag will use high_res and infer_gs=True; others will use low_res only.",
700
+ ),
701
+ ):
702
+ """Launch Depth Anything 3 Gradio interactive web application"""
703
+ from depth_anything_3.app.gradio_app import DepthAnything3App
704
+
705
+ # Create necessary directories
706
+ os.makedirs(workspace_dir, exist_ok=True)
707
+ os.makedirs(gallery_dir, exist_ok=True)
708
+
709
+ typer.echo("Launching Depth Anything 3 Gradio application...")
710
+ typer.echo(f"Model directory: {model_dir}")
711
+ typer.echo(f"Workspace directory: {workspace_dir}")
712
+ typer.echo(f"Gallery directory: {gallery_dir}")
713
+ typer.echo(f"Host: {host}")
714
+ typer.echo(f"Port: {port}")
715
+ typer.echo(f"Share: {share}")
716
+ typer.echo(f"Debug mode: {debug}")
717
+ typer.echo(f"Cache examples: {cache_examples}")
718
+ if cache_examples:
719
+ if cache_gs_tag:
720
+ typer.echo(
721
+ f"Cache GS Tag: '{cache_gs_tag}' (scenes matching this tag will use high-res + 3DGS)"
722
+ )
723
+ else:
724
+ typer.echo(f"Cache GS Tag: None (all scenes will use low-res only)")
725
+
726
+ try:
727
+ # Initialize and launch application
728
+ app = DepthAnything3App(
729
+ model_dir=model_dir, workspace_dir=workspace_dir, gallery_dir=gallery_dir
730
+ )
731
+
732
+ # Pre-cache examples if requested
733
+ if cache_examples:
734
+ typer.echo("\n" + "=" * 60)
735
+ typer.echo("Pre-caching mode enabled")
736
+ if cache_gs_tag:
737
+ typer.echo(f"Scenes containing '{cache_gs_tag}' will use HIGH-RES + 3DGS")
738
+ typer.echo(f"Other scenes will use LOW-RES only")
739
+ else:
740
+ typer.echo(f"All scenes will use LOW-RES only")
741
+ typer.echo("=" * 60)
742
+ app.cache_examples(
743
+ show_cam=True,
744
+ filter_black_bg=False,
745
+ filter_white_bg=False,
746
+ save_percentage=20.0,
747
+ num_max_points=1000,
748
+ cache_gs_tag=cache_gs_tag,
749
+ gs_trj_mode="smooth",
750
+ gs_video_quality="low",
751
+ )
752
+
753
+ # Prepare launch arguments
754
+ launch_kwargs = {"share": share, "debug": debug}
755
+
756
+ app.launch(host=host, port=port, **launch_kwargs)
757
+
758
+ except KeyboardInterrupt:
759
+ typer.echo("\nGradio application stopped.")
760
+ except Exception as e:
761
+ typer.echo(f"Failed to launch Gradio application: {e}")
762
+ raise typer.Exit(1)
763
+
764
+
765
+ @app.command()
766
+ def gallery(
767
+ gallery_dir: str = typer.Option(DEFAULT_GALLERY_DIR, help="Gallery root directory"),
768
+ host: str = typer.Option("127.0.0.1", help="Host address to bind to"),
769
+ port: int = typer.Option(8007, help="Port number to bind to"),
770
+ open_browser: bool = typer.Option(False, help="Open browser after launch"),
771
+ ):
772
+ """Launch Depth Anything 3 Gallery server"""
773
+
774
+ # Validate gallery directory
775
+ if not os.path.exists(gallery_dir):
776
+ raise typer.BadParameter(f"Gallery directory not found: {gallery_dir}")
777
+
778
+ typer.echo("Launching Depth Anything 3 Gallery server...")
779
+ typer.echo(f"Gallery directory: {gallery_dir}")
780
+ typer.echo(f"Host: {host}")
781
+ typer.echo(f"Port: {port}")
782
+ typer.echo(f"Auto-open browser: {open_browser}")
783
+
784
+ try:
785
+ # Set command line arguments
786
+ import sys
787
+
788
+ sys.argv = ["gallery", "--dir", gallery_dir, "--host", host, "--port", str(port)]
789
+ if open_browser:
790
+ sys.argv.append("--open")
791
+
792
+ # Launch gallery server
793
+ gallery_main()
794
+
795
+ except KeyboardInterrupt:
796
+ typer.echo("\nGallery server stopped.")
797
+ except Exception as e:
798
+ typer.echo(f"Failed to launch Gallery server: {e}")
799
+ raise typer.Exit(1)
800
+
801
+
802
+ if __name__ == "__main__":
803
+ app()
src/depth_anything_3/configs/da3-base.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __object__:
2
+ path: depth_anything_3.model.da3
3
+ name: DepthAnything3Net
4
+ args: as_params
5
+
6
+ net:
7
+ __object__:
8
+ path: depth_anything_3.model.dinov2.dinov2
9
+ name: DinoV2
10
+ args: as_params
11
+
12
+ name: vitb
13
+ out_layers: [5, 7, 9, 11]
14
+ alt_start: 4
15
+ qknorm_start: 4
16
+ rope_start: 4
17
+ cat_token: True
18
+
19
+ head:
20
+ __object__:
21
+ path: depth_anything_3.model.dualdpt
22
+ name: DualDPT
23
+ args: as_params
24
+
25
+ dim_in: &head_dim_in 1536
26
+ output_dim: 2
27
+ features: &head_features 128
28
+ out_channels: &head_out_channels [96, 192, 384, 768]
29
+
30
+
31
+ cam_enc:
32
+ __object__:
33
+ path: depth_anything_3.model.cam_enc
34
+ name: CameraEnc
35
+ args: as_params
36
+
37
+ dim_out: 768
38
+
39
+ cam_dec:
40
+ __object__:
41
+ path: depth_anything_3.model.cam_dec
42
+ name: CameraDec
43
+ args: as_params
44
+
45
+ dim_in: 1536
src/depth_anything_3/configs/da3-giant.yaml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __object__:
2
+ path: depth_anything_3.model.da3
3
+ name: DepthAnything3Net
4
+ args: as_params
5
+
6
+ net:
7
+ __object__:
8
+ path: depth_anything_3.model.dinov2.dinov2
9
+ name: DinoV2
10
+ args: as_params
11
+
12
+ name: vitg
13
+ out_layers: [19, 27, 33, 39]
14
+ alt_start: 13
15
+ qknorm_start: 13
16
+ rope_start: 13
17
+ cat_token: True
18
+
19
+ head:
20
+ __object__:
21
+ path: depth_anything_3.model.dualdpt
22
+ name: DualDPT
23
+ args: as_params
24
+
25
+ dim_in: &head_dim_in 3072
26
+ output_dim: 2
27
+ features: &head_features 256
28
+ out_channels: &head_out_channels [256, 512, 1024, 1024]
29
+
30
+
31
+ cam_enc:
32
+ __object__:
33
+ path: depth_anything_3.model.cam_enc
34
+ name: CameraEnc
35
+ args: as_params
36
+
37
+ dim_out: 1536
38
+
39
+ cam_dec:
40
+ __object__:
41
+ path: depth_anything_3.model.cam_dec
42
+ name: CameraDec
43
+ args: as_params
44
+
45
+ dim_in: 3072
46
+
47
+
48
+ gs_head:
49
+ __object__:
50
+ path: depth_anything_3.model.gsdpt
51
+ name: GSDPT
52
+ args: as_params
53
+
54
+ dim_in: *head_dim_in
55
+ output_dim: 38 # should align with gs_adapter's setting, for gs params
56
+ features: *head_features
57
+ out_channels: *head_out_channels
58
+
59
+
60
+ gs_adapter:
61
+ __object__:
62
+ path: depth_anything_3.model.gs_adapter
63
+ name: GaussianAdapter
64
+ args: as_params
65
+
66
+ sh_degree: 2
67
+ pred_color: false # predict SH coefficient if false
68
+ pred_offset_depth: true
69
+ pred_offset_xy: true
70
+ gaussian_scale_min: 1e-5
71
+ gaussian_scale_max: 30.0
src/depth_anything_3/configs/da3-large.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __object__:
2
+ path: depth_anything_3.model.da3
3
+ name: DepthAnything3Net
4
+ args: as_params
5
+
6
+ net:
7
+ __object__:
8
+ path: depth_anything_3.model.dinov2.dinov2
9
+ name: DinoV2
10
+ args: as_params
11
+
12
+ name: vitl
13
+ out_layers: [11, 15, 19, 23]
14
+ alt_start: 8
15
+ qknorm_start: 8
16
+ rope_start: 8
17
+ cat_token: True
18
+
19
+ head:
20
+ __object__:
21
+ path: depth_anything_3.model.dualdpt
22
+ name: DualDPT
23
+ args: as_params
24
+
25
+ dim_in: &head_dim_in 2048
26
+ output_dim: 2
27
+ features: &head_features 256
28
+ out_channels: &head_out_channels [256, 512, 1024, 1024]
29
+
30
+
31
+ cam_enc:
32
+ __object__:
33
+ path: depth_anything_3.model.cam_enc
34
+ name: CameraEnc
35
+ args: as_params
36
+
37
+ dim_out: 1024
38
+
39
+ cam_dec:
40
+ __object__:
41
+ path: depth_anything_3.model.cam_dec
42
+ name: CameraDec
43
+ args: as_params
44
+
45
+ dim_in: 2048
src/depth_anything_3/configs/da3-small.yaml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __object__:
2
+ path: depth_anything_3.model.da3
3
+ name: DepthAnything3Net
4
+ args: as_params
5
+
6
+ net:
7
+ __object__:
8
+ path: depth_anything_3.model.dinov2.dinov2
9
+ name: DinoV2
10
+ args: as_params
11
+
12
+ name: vits
13
+ out_layers: [5, 7, 9, 11]
14
+ alt_start: 4
15
+ qknorm_start: 4
16
+ rope_start: 4
17
+ cat_token: True
18
+
19
+ head:
20
+ __object__:
21
+ path: depth_anything_3.model.dualdpt
22
+ name: DualDPT
23
+ args: as_params
24
+
25
+ dim_in: &head_dim_in 768
26
+ output_dim: 2
27
+ features: &head_features 64
28
+ out_channels: &head_out_channels [48, 96, 192, 384]
29
+
30
+
31
+ cam_enc:
32
+ __object__:
33
+ path: depth_anything_3.model.cam_enc
34
+ name: CameraEnc
35
+ args: as_params
36
+
37
+ dim_out: 384
38
+
39
+ cam_dec:
40
+ __object__:
41
+ path: depth_anything_3.model.cam_dec
42
+ name: CameraDec
43
+ args: as_params
44
+
45
+ dim_in: 768
src/depth_anything_3/configs/da3metric-large.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __object__:
2
+ path: depth_anything_3.model.da3
3
+ name: DepthAnything3Net
4
+ args: as_params
5
+
6
+ net:
7
+ __object__:
8
+ path: depth_anything_3.model.dinov2.dinov2
9
+ name: DinoV2
10
+ args: as_params
11
+
12
+ name: vitl
13
+ out_layers: [4, 11, 17, 23]
14
+ alt_start: -1 # -1 means disable
15
+ qknorm_start: -1
16
+ rope_start: -1
17
+ cat_token: False
18
+
19
+ head:
20
+ __object__:
21
+ path: depth_anything_3.model.dpt
22
+ name: DPT
23
+ args: as_params
24
+
25
+ dim_in: 1024
26
+ output_dim: 1
27
+ features: 256
28
+ out_channels: [256, 512, 1024, 1024]
src/depth_anything_3/configs/da3mono-large.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __object__:
2
+ path: depth_anything_3.model.da3
3
+ name: DepthAnything3Net
4
+ args: as_params
5
+
6
+ net:
7
+ __object__:
8
+ path: depth_anything_3.model.dinov2.dinov2
9
+ name: DinoV2
10
+ args: as_params
11
+
12
+ name: vitl
13
+ out_layers: [4, 11, 17, 23]
14
+ alt_start: -1 # -1 means disable
15
+ qknorm_start: -1
16
+ rope_start: -1
17
+ cat_token: False
18
+
19
+ head:
20
+ __object__:
21
+ path: depth_anything_3.model.dpt
22
+ name: DPT
23
+ args: as_params
24
+
25
+ dim_in: 1024
26
+ output_dim: 1
27
+ features: 256
28
+ out_channels: [256, 512, 1024, 1024]
src/depth_anything_3/configs/da3nested-giant-large.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __object__:
2
+ path: depth_anything_3.model.da3
3
+ name: NestedDepthAnything3Net
4
+ args: as_params
5
+
6
+ anyview:
7
+ __inherit__: depth_anything_3.configs.da3-giant
8
+
9
+ metric:
10
+ __inherit__: depth_anything_3.configs.da3metric-large
src/depth_anything_3/model/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from depth_anything_3.model.da3 import DepthAnything3Net, NestedDepthAnything3Net
16
+
17
+ __export__ = [
18
+ NestedDepthAnything3Net,
19
+ DepthAnything3Net,
20
+ ]
src/depth_anything_3/model/cam_dec.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+
18
+
19
+ class CameraDec(nn.Module):
20
+ def __init__(self, dim_in=1536):
21
+ super().__init__()
22
+ output_dim = dim_in
23
+ self.backbone = nn.Sequential(
24
+ nn.Linear(output_dim, output_dim),
25
+ nn.ReLU(),
26
+ nn.Linear(output_dim, output_dim),
27
+ nn.ReLU(),
28
+ )
29
+ self.fc_t = nn.Linear(output_dim, 3)
30
+ self.fc_qvec = nn.Linear(output_dim, 4)
31
+ self.fc_fov = nn.Sequential(nn.Linear(output_dim, 2), nn.ReLU())
32
+
33
+ def forward(self, feat, camera_encoding=None, *args, **kwargs):
34
+ B, N = feat.shape[:2]
35
+ feat = feat.reshape(B * N, -1)
36
+ feat = self.backbone(feat)
37
+ out_t = self.fc_t(feat.float()).reshape(B, N, 3)
38
+ if camera_encoding is None:
39
+ out_qvec = self.fc_qvec(feat.float()).reshape(B, N, 4)
40
+ out_fov = self.fc_fov(feat.float()).reshape(B, N, 2)
41
+ else:
42
+ out_qvec = camera_encoding[..., 3:7]
43
+ out_fov = camera_encoding[..., -2:]
44
+ pose_enc = torch.cat([out_t, out_qvec, out_fov], dim=-1)
45
+ return pose_enc
src/depth_anything_3/model/cam_enc.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch.nn as nn
16
+
17
+ from depth_anything_3.model.utils.attention import Mlp
18
+ from depth_anything_3.model.utils.block import Block
19
+ from depth_anything_3.model.utils.transform import extri_intri_to_pose_encoding
20
+ from depth_anything_3.utils.geometry import affine_inverse
21
+ from torch.utils.checkpoint import checkpoint
22
+
23
+ class CameraEnc(nn.Module):
24
+ """
25
+ CameraHead predicts camera parameters from token representations using iterative refinement.
26
+
27
+ It applies a series of transformer blocks (the "trunk") to dedicated camera tokens.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ dim_out: int = 1024,
33
+ dim_in: int = 9,
34
+ trunk_depth: int = 4,
35
+ target_dim: int = 9,
36
+ num_heads: int = 16,
37
+ mlp_ratio: int = 4,
38
+ init_values: float = 0.01,
39
+ **kwargs,
40
+ ):
41
+ super().__init__()
42
+ self.target_dim = target_dim
43
+ self.trunk_depth = trunk_depth
44
+ self.trunk = nn.Sequential(
45
+ *[
46
+ Block(
47
+ dim=dim_out,
48
+ num_heads=num_heads,
49
+ mlp_ratio=mlp_ratio,
50
+ init_values=init_values,
51
+ )
52
+ for _ in range(trunk_depth)
53
+ ]
54
+ )
55
+ self.token_norm = nn.LayerNorm(dim_out)
56
+ self.trunk_norm = nn.LayerNorm(dim_out)
57
+ self.pose_branch = Mlp(
58
+ in_features=dim_in,
59
+ hidden_features=dim_out // 2,
60
+ out_features=dim_out,
61
+ drop=0,
62
+ )
63
+
64
+ def forward(
65
+ self,
66
+ ext,
67
+ ixt,
68
+ image_size,
69
+ ) -> tuple:
70
+ c2ws = affine_inverse(ext)
71
+ pose_encoding = extri_intri_to_pose_encoding(
72
+ c2ws,
73
+ ixt,
74
+ image_size,
75
+ )
76
+
77
+ #pose_tokens = self.pose_branch(pose_encoding)
78
+ #pose_tokens = self.token_norm(pose_tokens)
79
+ #pose_tokens = self.trunk(pose_tokens)
80
+ #pose_tokens = self.trunk_norm(pose_tokens)
81
+
82
+ pose_tokens = checkpoint(self.pose_branch, pose_encoding, use_reentrant=False)
83
+ pose_tokens = checkpoint(self.token_norm, pose_tokens, use_reentrant=False)
84
+ pose_tokens = checkpoint(self.trunk, pose_tokens, use_reentrant=False)
85
+ pose_tokens = checkpoint(self.trunk_norm, pose_tokens, use_reentrant=False)
86
+ return pose_tokens
src/depth_anything_3/model/da3.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ from addict import Dict
20
+ from omegaconf import DictConfig, OmegaConf
21
+
22
+ from depth_anything_3.cfg import create_object
23
+ from depth_anything_3.model.utils.transform import pose_encoding_to_extri_intri
24
+ from depth_anything_3.utils.alignment import (
25
+ apply_metric_scaling,
26
+ compute_alignment_mask,
27
+ compute_sky_mask,
28
+ least_squares_scale_scalar,
29
+ sample_tensor_for_quantile,
30
+ set_sky_regions_to_max_depth,
31
+ )
32
+ from depth_anything_3.utils.geometry import affine_inverse, as_homogeneous, map_pdf_to_opacity
33
+ from depth_anything_3.utils.ray_utils import get_extrinsic_from_camray
34
+
35
+
36
+ def _wrap_cfg(cfg_obj):
37
+ return OmegaConf.create(cfg_obj)
38
+
39
+
40
+ class DepthAnything3Net(nn.Module):
41
+ """
42
+ Depth Anything 3 network for depth estimation and camera pose estimation.
43
+
44
+ This network consists of:
45
+ - Backbone: DinoV2 feature extractor
46
+ - Head: DPT or DualDPT for depth prediction
47
+ - Optional camera decoders for pose estimation
48
+ - Optional GSDPT for 3DGS prediction
49
+
50
+ Args:
51
+ preset: Configuration preset containing network dimensions and settings
52
+
53
+ Returns:
54
+ Dictionary containing:
55
+ - depth: Predicted depth map (B, H, W)
56
+ - depth_conf: Depth confidence map (B, H, W)
57
+ - extrinsics: Camera extrinsics (B, N, 4, 4)
58
+ - intrinsics: Camera intrinsics (B, N, 3, 3)
59
+ - gaussians: 3D Gaussian Splats (world space), type: model.gs_adapter.Gaussians
60
+ - aux: Auxiliary features for specified layers
61
+ """
62
+
63
+ # Patch size for feature extraction
64
+ PATCH_SIZE = 14
65
+
66
+ def __init__(self, net, head, cam_dec=None, cam_enc=None, gs_head=None, gs_adapter=None):
67
+ """
68
+ Initialize DepthAnything3Net with given yaml-initialized configuration.
69
+ """
70
+ super().__init__()
71
+ self.backbone = net if isinstance(net, nn.Module) else create_object(_wrap_cfg(net))
72
+ self.head = head if isinstance(head, nn.Module) else create_object(_wrap_cfg(head))
73
+ self.cam_dec, self.cam_enc = None, None
74
+ self.deformation_head = None
75
+ self.canonical_head = None
76
+ if cam_dec is not None:
77
+ self.cam_dec = (
78
+ cam_dec if isinstance(cam_dec, nn.Module) else create_object(_wrap_cfg(cam_dec))
79
+ )
80
+ self.cam_enc = (
81
+ cam_enc if isinstance(cam_enc, nn.Module) else create_object(_wrap_cfg(cam_enc))
82
+ )
83
+ self.gs_adapter, self.gs_head = None, None
84
+ if gs_head is not None and gs_adapter is not None:
85
+ self.gs_adapter = (
86
+ gs_adapter
87
+ if isinstance(gs_adapter, nn.Module)
88
+ else create_object(_wrap_cfg(gs_adapter))
89
+ )
90
+ gs_out_dim = self.gs_adapter.d_in + 1
91
+ if isinstance(gs_head, nn.Module):
92
+ assert (
93
+ gs_head.out_dim == gs_out_dim
94
+ ), f"gs_head.out_dim should be {gs_out_dim}, got {gs_head.out_dim}"
95
+ self.gs_head = gs_head
96
+ else:
97
+ assert (
98
+ gs_head["output_dim"] == gs_out_dim
99
+ ), f"gs_head output_dim should set to {gs_out_dim}, got {gs_head['output_dim']}"
100
+ self.gs_head = create_object(_wrap_cfg(gs_head))
101
+
102
+ def forward(
103
+ self,
104
+ x: torch.Tensor,
105
+ extrinsics: torch.Tensor | None = None,
106
+ intrinsics: torch.Tensor | None = None,
107
+ export_feat_layers: list[int] | None = [],
108
+ infer_gs: bool = False,
109
+ use_ray_pose: bool = False,
110
+ ref_view_strategy: str = "saddle_balanced",
111
+ ) -> Dict[str, torch.Tensor]:
112
+ """
113
+ Forward pass through the network.
114
+
115
+ Args:
116
+ x: Input images (B, N, 3, H, W)
117
+ extrinsics: Camera extrinsics (B, N, 4, 4)
118
+ intrinsics: Camera intrinsics (B, N, 3, 3)
119
+ feat_layers: List of layer indices to extract features from
120
+ infer_gs: Enable Gaussian Splatting branch
121
+ use_ray_pose: Use ray-based pose estimation
122
+ ref_view_strategy: Strategy for selecting reference view
123
+
124
+ Returns:
125
+ Dictionary containing predictions and auxiliary features
126
+ """
127
+ # Extract features using backbone
128
+ if extrinsics is not None:
129
+ with torch.autocast(device_type=x.device.type, enabled=False):
130
+ cam_token = self.cam_enc(extrinsics, intrinsics, x.shape[-2:])
131
+ else:
132
+ cam_token = None
133
+ all_grad = all(p.requires_grad for p in self.backbone.parameters())
134
+ x.requires_grad_(True)
135
+
136
+ feats, aux_feats = self.backbone(
137
+ x, cam_token=cam_token, export_feat_layers=export_feat_layers, ref_view_strategy=ref_view_strategy
138
+ )
139
+ # feats = [[item for item in feat] for feat in feats]
140
+ H, W = x.shape[-2], x.shape[-1]
141
+
142
+
143
+ # Process features through depth head
144
+ with torch.autocast(device_type=x.device.type, enabled=False):
145
+ output = self._process_depth_head(feats, H, W)
146
+ if self.deformation_head is not None:
147
+ deformation = self.deformation_head(feats, H, W, patch_start_idx=0)
148
+ output["deformation"] = deformation["deformation"]
149
+ output["deformation_conf"] = deformation["deformation_conf"]
150
+ if self.canonical_head is not None:
151
+ #print("Processing canonical head...")
152
+ canonical = self.canonical_head(feats, H, W, patch_start_idx=0)
153
+ output["canonical_depth"] = canonical["canonical_depth"]
154
+ output["canonical_depth_conf"] = canonical["canonical_depth_conf"]
155
+ output["canonical_ray"] = canonical["canonical_ray"]
156
+ output["canonical_ray_conf"] = canonical["canonical_ray_conf"]
157
+ #print("forward pass shapes", output["canonical_depth"].shape, output["canonical_depth_conf"].shape, output["canonical_ray"].shape, output["canonical_ray_conf"].shape)
158
+
159
+ if use_ray_pose:
160
+ output = self._process_ray_pose_estimation(output, H, W)
161
+ else:
162
+ output = self._process_camera_estimation(feats, H, W, output)
163
+ if infer_gs:
164
+ output = self._process_gs_head(feats, H, W, output, x, extrinsics, intrinsics)
165
+
166
+ output = self._process_mono_sky_estimation(output)
167
+
168
+ # Extract auxiliary features if requested
169
+ output.aux = self._extract_auxiliary_features(aux_feats, export_feat_layers, H, W)
170
+
171
+ return output
172
+
173
+ def _process_mono_sky_estimation(
174
+ self, output: Dict[str, torch.Tensor]
175
+ ) -> Dict[str, torch.Tensor]:
176
+ """Process mono sky estimation."""
177
+ if "sky" not in output:
178
+ return output
179
+ non_sky_mask = compute_sky_mask(output.sky, threshold=0.3)
180
+ if non_sky_mask.sum() <= 10:
181
+ return output
182
+ if (~non_sky_mask).sum() <= 10:
183
+ return output
184
+
185
+ non_sky_depth = output.depth[non_sky_mask]
186
+ if non_sky_depth.numel() > 100000:
187
+ idx = torch.randint(0, non_sky_depth.numel(), (100000,), device=non_sky_depth.device)
188
+ sampled_depth = non_sky_depth[idx]
189
+ else:
190
+ sampled_depth = non_sky_depth
191
+ non_sky_max = torch.quantile(sampled_depth, 0.99)
192
+
193
+ # Set sky regions to maximum depth and high confidence
194
+ output.depth, _ = set_sky_regions_to_max_depth(
195
+ output.depth, None, non_sky_mask, max_depth=non_sky_max
196
+ )
197
+ return output
198
+
199
+ def _process_ray_pose_estimation(
200
+ self, output: Dict[str, torch.Tensor], height: int, width: int
201
+ ) -> Dict[str, torch.Tensor]:
202
+ """Process ray pose estimation if ray pose decoder is available."""
203
+ if "ray" in output and "ray_conf" in output:
204
+ pred_extrinsic, pred_focal_lengths, pred_principal_points = get_extrinsic_from_camray(
205
+ output.ray,
206
+ output.ray_conf,
207
+ output.ray.shape[-3],
208
+ output.ray.shape[-2],
209
+ )
210
+ pred_extrinsic = affine_inverse(pred_extrinsic) # w2c -> c2w
211
+ pred_extrinsic = pred_extrinsic[:, :, :3, :]
212
+ pred_intrinsic = torch.eye(3, 3)[None, None].repeat(pred_extrinsic.shape[0], pred_extrinsic.shape[1], 1, 1).clone().to(pred_extrinsic.device)
213
+ pred_intrinsic[:, :, 0, 0] = pred_focal_lengths[:, :, 0] / 2 * width
214
+ pred_intrinsic[:, :, 1, 1] = pred_focal_lengths[:, :, 1] / 2 * height
215
+ pred_intrinsic[:, :, 0, 2] = pred_principal_points[:, :, 0] * width * 0.5
216
+ pred_intrinsic[:, :, 1, 2] = pred_principal_points[:, :, 1] * height * 0.5
217
+ del output.ray
218
+ del output.ray_conf
219
+ output.extrinsics = pred_extrinsic
220
+ output.intrinsics = pred_intrinsic
221
+ return output
222
+
223
+ def _process_depth_head(
224
+ self, feats: list[torch.Tensor], H: int, W: int
225
+ ) -> Dict[str, torch.Tensor]:
226
+ """Process features through the depth prediction head."""
227
+ return self.head(feats, H, W, patch_start_idx=0)
228
+
229
+ def _process_camera_estimation(
230
+ self, feats: list[torch.Tensor], H: int, W: int, output: Dict[str, torch.Tensor]
231
+ ) -> Dict[str, torch.Tensor]:
232
+ """Process camera pose estimation if camera decoder is available."""
233
+ if self.cam_dec is not None:
234
+ pose_enc = self.cam_dec(feats[-1][1])
235
+ output.pose_enc = pose_enc
236
+ # Remove ray information as it's not needed for pose estimation
237
+ #if "ray" in output:
238
+ # del output.ray
239
+ #if "ray_conf" in output:
240
+ # del output.ray_conf
241
+
242
+ # Convert pose encoding to extrinsics and intrinsics
243
+ c2w, ixt = pose_encoding_to_extri_intri(pose_enc, (H, W))
244
+ output.extrinsics = affine_inverse(c2w)
245
+ output.intrinsics = ixt
246
+
247
+ return output
248
+
249
+ def _process_gs_head(
250
+ self,
251
+ feats: list[torch.Tensor],
252
+ H: int,
253
+ W: int,
254
+ output: Dict[str, torch.Tensor],
255
+ in_images: torch.Tensor,
256
+ extrinsics: torch.Tensor | None = None,
257
+ intrinsics: torch.Tensor | None = None,
258
+ ) -> Dict[str, torch.Tensor]:
259
+ """Process 3DGS parameters estimation if 3DGS head is available."""
260
+ if self.gs_head is None or self.gs_adapter is None:
261
+ return output
262
+ assert output.get("depth", None) is not None, "must provide MV depth for the GS head."
263
+
264
+ # The depth is defined in the DA3 model's camera space,
265
+ # so even with provided GT camera poses,
266
+ # we instead use the predicted camera poses for better alignment.
267
+ ctx_extr = output.get("extrinsics", None)
268
+ ctx_intr = output.get("intrinsics", None)
269
+ assert (
270
+ ctx_extr is not None and ctx_intr is not None
271
+ ), "must process camera info first if GT is not available"
272
+
273
+ gt_extr = extrinsics
274
+ # homo the extr if needed
275
+ ctx_extr = as_homogeneous(ctx_extr)
276
+ if gt_extr is not None:
277
+ gt_extr = as_homogeneous(gt_extr)
278
+
279
+ # forward through the gs_dpt head to get 'camera space' parameters
280
+ gs_outs = self.gs_head(
281
+ feats=feats,
282
+ H=H,
283
+ W=W,
284
+ patch_start_idx=0,
285
+ images=in_images,
286
+ )
287
+ raw_gaussians = gs_outs.raw_gs
288
+ densities = gs_outs.raw_gs_conf
289
+
290
+ # convert to 'world space' 3DGS parameters; ready to export and render
291
+ # gt_extr could be None, and will be used to align the pose scale if available
292
+ gs_world = self.gs_adapter(
293
+ extrinsics=ctx_extr,
294
+ intrinsics=ctx_intr,
295
+ depths=output.depth,
296
+ opacities=map_pdf_to_opacity(densities),
297
+ raw_gaussians=raw_gaussians,
298
+ image_shape=(H, W),
299
+ gt_extrinsics=gt_extr,
300
+ )
301
+ output.gaussians = gs_world
302
+
303
+ return output
304
+
305
+ def _extract_auxiliary_features(
306
+ self, feats: list[torch.Tensor], feat_layers: list[int], H: int, W: int
307
+ ) -> Dict[str, torch.Tensor]:
308
+ """Extract auxiliary features from specified layers."""
309
+ aux_features = Dict()
310
+ assert len(feats) == len(feat_layers)
311
+ for feat, feat_layer in zip(feats, feat_layers):
312
+ # Reshape features to spatial dimensions
313
+ feat_reshaped = feat.reshape(
314
+ [
315
+ feat.shape[0],
316
+ feat.shape[1],
317
+ H // self.PATCH_SIZE,
318
+ W // self.PATCH_SIZE,
319
+ feat.shape[-1],
320
+ ]
321
+ )
322
+ aux_features[f"feat_layer_{feat_layer}"] = feat_reshaped
323
+
324
+ return aux_features
325
+
326
+
327
+ class NestedDepthAnything3Net(nn.Module):
328
+ """
329
+ Nested Depth Anything 3 network with metric scaling capabilities.
330
+
331
+ This network combines two DepthAnything3Net branches:
332
+ - Main branch: Standard depth estimation
333
+ - Metric branch: Metric depth estimation for scaling alignment
334
+
335
+ The network performs depth alignment using least squares scaling
336
+ and handles sky region masking for improved depth estimation.
337
+
338
+ Args:
339
+ preset: Configuration for the main depth estimation branch
340
+ second_preset: Configuration for the metric depth branch
341
+ """
342
+
343
+ def __init__(self, anyview: DictConfig, metric: DictConfig):
344
+ """
345
+ Initialize NestedDepthAnything3Net with two branches.
346
+
347
+ Args:
348
+ preset: Configuration for main depth estimation branch
349
+ second_preset: Configuration for metric depth branch
350
+ """
351
+ super().__init__()
352
+ self.da3 = create_object(anyview)
353
+ self.da3_metric = create_object(metric)
354
+
355
+ def forward(
356
+ self,
357
+ x: torch.Tensor,
358
+ extrinsics: torch.Tensor | None = None,
359
+ intrinsics: torch.Tensor | None = None,
360
+ export_feat_layers: list[int] | None = [],
361
+ infer_gs: bool = False,
362
+ use_ray_pose: bool = False,
363
+ ref_view_strategy: str = "saddle_balanced",
364
+ ) -> Dict[str, torch.Tensor]:
365
+ """
366
+ Forward pass through both branches with metric scaling alignment.
367
+
368
+ Args:
369
+ x: Input images (B, N, 3, H, W)
370
+ extrinsics: Camera extrinsics (B, N, 4, 4) - unused
371
+ intrinsics: Camera intrinsics (B, N, 3, 3) - unused
372
+ feat_layers: List of layer indices to extract features from
373
+ infer_gs: Enable Gaussian Splatting branch
374
+ use_ray_pose: Use ray-based pose estimation
375
+ ref_view_strategy: Strategy for selecting reference view
376
+
377
+ Returns:
378
+ Dictionary containing aligned depth predictions and camera parameters
379
+ """
380
+ # Get predictions from both branches
381
+ output = self.da3(
382
+ x, extrinsics, intrinsics, export_feat_layers=export_feat_layers, infer_gs=infer_gs, use_ray_pose=use_ray_pose, ref_view_strategy=ref_view_strategy
383
+ )
384
+ metric_output = self.da3_metric(x)
385
+
386
+ # Apply metric scaling and alignment
387
+ output = self._apply_metric_scaling(output, metric_output)
388
+ output = self._apply_depth_alignment(output, metric_output)
389
+ output = self._handle_sky_regions(output, metric_output)
390
+
391
+ return output
392
+
393
+ def _apply_metric_scaling(
394
+ self, output: Dict[str, torch.Tensor], metric_output: Dict[str, torch.Tensor]
395
+ ) -> Dict[str, torch.Tensor]:
396
+ """Apply metric scaling to the metric depth output."""
397
+ # Scale metric depth based on camera intrinsics
398
+ metric_output.depth = apply_metric_scaling(
399
+ metric_output.depth,
400
+ output.intrinsics,
401
+ )
402
+ return output
403
+
404
+ def _apply_depth_alignment(
405
+ self, output: Dict[str, torch.Tensor], metric_output: Dict[str, torch.Tensor]
406
+ ) -> Dict[str, torch.Tensor]:
407
+ """Apply depth alignment using least squares scaling."""
408
+ # Compute non-sky mask
409
+ non_sky_mask = compute_sky_mask(metric_output.sky, threshold=0.3)
410
+
411
+ # Ensure we have enough non-sky pixels
412
+ assert non_sky_mask.sum() > 10, "Insufficient non-sky pixels for alignment"
413
+
414
+ # Sample depth confidence for quantile computation
415
+ depth_conf_ns = output.depth_conf[non_sky_mask]
416
+ depth_conf_sampled = sample_tensor_for_quantile(depth_conf_ns, max_samples=100000)
417
+ median_conf = torch.quantile(depth_conf_sampled, 0.5)
418
+
419
+ # Compute alignment mask
420
+ align_mask = compute_alignment_mask(
421
+ output.depth_conf, non_sky_mask, output.depth, metric_output.depth, median_conf
422
+ )
423
+
424
+ # Compute scale factor using least squares
425
+ valid_depth = output.depth[align_mask]
426
+ valid_metric_depth = metric_output.depth[align_mask]
427
+ scale_factor = least_squares_scale_scalar(valid_metric_depth, valid_depth)
428
+
429
+ # Apply scaling to depth and extrinsics
430
+ output.depth *= scale_factor
431
+ output.extrinsics[:, :, :3, 3] *= scale_factor
432
+ output.is_metric = 1
433
+ output.scale_factor = scale_factor.item()
434
+
435
+ return output
436
+
437
+ def _handle_sky_regions(
438
+ self,
439
+ output: Dict[str, torch.Tensor],
440
+ metric_output: Dict[str, torch.Tensor],
441
+ sky_depth_def: float = 200.0,
442
+ ) -> Dict[str, torch.Tensor]:
443
+ """Handle sky regions by setting them to maximum depth."""
444
+ non_sky_mask = compute_sky_mask(metric_output.sky, threshold=0.3)
445
+
446
+ # Compute maximum depth for non-sky regions
447
+ # Use sampling to safely compute quantile on large tensors
448
+ non_sky_depth = output.depth[non_sky_mask]
449
+ if non_sky_depth.numel() > 100000:
450
+ idx = torch.randint(0, non_sky_depth.numel(), (100000,), device=non_sky_depth.device)
451
+ sampled_depth = non_sky_depth[idx]
452
+ else:
453
+ sampled_depth = non_sky_depth
454
+ non_sky_max = min(torch.quantile(sampled_depth, 0.99), sky_depth_def)
455
+
456
+ # Set sky regions to maximum depth and high confidence
457
+ output.depth, output.depth_conf = set_sky_regions_to_max_depth(
458
+ output.depth, output.depth_conf, non_sky_mask, max_depth=non_sky_max
459
+ )
460
+
461
+ return output
src/depth_anything_3/model/dinov2/dinov2.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
9
+
10
+
11
+ from typing import List
12
+ import torch.nn as nn
13
+
14
+ from depth_anything_3.model.dinov2.vision_transformer import (
15
+ vit_base,
16
+ vit_giant2,
17
+ vit_large,
18
+ vit_small,
19
+ )
20
+
21
+
22
+ class DinoV2(nn.Module):
23
+ def __init__(
24
+ self,
25
+ name: str,
26
+ out_layers: List[int],
27
+ alt_start: int = -1,
28
+ qknorm_start: int = -1,
29
+ rope_start: int = -1,
30
+ cat_token: bool = True,
31
+ **kwargs,
32
+ ):
33
+ super().__init__()
34
+ assert name in {"vits", "vitb", "vitl", "vitg"}
35
+ self.name = name
36
+ self.out_layers = out_layers
37
+ self.alt_start = alt_start
38
+ self.qknorm_start = qknorm_start
39
+ self.rope_start = rope_start
40
+ self.cat_token = cat_token
41
+ encoder_map = {
42
+ "vits": vit_small,
43
+ "vitb": vit_base,
44
+ "vitl": vit_large,
45
+ "vitg": vit_giant2,
46
+ }
47
+ encoder_fn = encoder_map[self.name]
48
+ ffn_layer = "swiglufused" if self.name == "vitg" else "mlp"
49
+ self.pretrained = encoder_fn(
50
+ img_size=518,
51
+ patch_size=14,
52
+ ffn_layer=ffn_layer,
53
+ alt_start=alt_start,
54
+ qknorm_start=qknorm_start,
55
+ rope_start=rope_start,
56
+ cat_token=cat_token,
57
+ )
58
+
59
+ def forward(self, x, **kwargs):
60
+ return self.pretrained.get_intermediate_layers(
61
+ x,
62
+ self.out_layers,
63
+ **kwargs,
64
+ )
src/depth_anything_3/model/dinov2/layers/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # from .attention import MemEffAttention
8
+ from .block import Block
9
+ from .layer_scale import LayerScale
10
+ from .mlp import Mlp
11
+ from .patch_embed import PatchEmbed
12
+ from .rope import PositionGetter, RotaryPositionEmbedding2D
13
+ from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused
14
+
15
+ __all__ = [
16
+ Mlp,
17
+ PatchEmbed,
18
+ SwiGLUFFN,
19
+ SwiGLUFFNFused,
20
+ Block,
21
+ # MemEffAttention,
22
+ LayerScale,
23
+ PositionGetter,
24
+ RotaryPositionEmbedding2D,
25
+ ]
src/depth_anything_3/model/dinov2/layers/attention.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
10
+
11
+ import logging
12
+ import torch.nn.functional as F
13
+ from torch import Tensor, nn
14
+
15
+ logger = logging.getLogger("dinov2")
16
+
17
+
18
+ class Attention(nn.Module):
19
+ def __init__(
20
+ self,
21
+ dim: int,
22
+ num_heads: int = 8,
23
+ qkv_bias: bool = False,
24
+ proj_bias: bool = True,
25
+ attn_drop: float = 0.0,
26
+ proj_drop: float = 0.0,
27
+ norm_layer: nn.Module = nn.LayerNorm,
28
+ qk_norm: bool = False,
29
+ fused_attn: bool = True, # use F.scaled_dot_product_attention or not
30
+ rope=None,
31
+ ) -> None:
32
+ super().__init__()
33
+ assert dim % num_heads == 0, "dim should be divisible by num_heads"
34
+ self.num_heads = num_heads
35
+ head_dim = dim // num_heads
36
+ self.scale = head_dim**-0.5
37
+ self.fused_attn = fused_attn
38
+
39
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
40
+ self.q_norm = norm_layer(head_dim) if qk_norm else nn.Identity()
41
+ self.k_norm = norm_layer(head_dim) if qk_norm else nn.Identity()
42
+ self.attn_drop = nn.Dropout(attn_drop)
43
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
44
+ self.proj_drop = nn.Dropout(proj_drop)
45
+ self.rope = rope
46
+
47
+ def forward(self, x: Tensor, pos=None, attn_mask=None) -> Tensor:
48
+ B, N, C = x.shape
49
+ qkv = (
50
+ self.qkv(x)
51
+ .reshape(B, N, 3, self.num_heads, C // self.num_heads)
52
+ .permute(2, 0, 3, 1, 4)
53
+ )
54
+ q, k, v = qkv[0], qkv[1], qkv[2]
55
+ q, k = self.q_norm(q), self.k_norm(k)
56
+ if self.rope is not None and pos is not None:
57
+ q = self.rope(q, pos)
58
+ k = self.rope(k, pos)
59
+ if self.fused_attn:
60
+ x = F.scaled_dot_product_attention(
61
+ q,
62
+ k,
63
+ v,
64
+ dropout_p=self.attn_drop.p if self.training else 0.0,
65
+ attn_mask=(
66
+ (attn_mask)[:, None].repeat(1, self.num_heads, 1, 1)
67
+ if attn_mask is not None
68
+ else None
69
+ ),
70
+ )
71
+ else:
72
+ q = q * self.scale
73
+ attn = q @ k.transpose(-2, -1)
74
+ attn = attn.softmax(dim=-1)
75
+ attn = self.attn_drop(attn)
76
+ x = attn @ v
77
+
78
+ x = x.transpose(1, 2).reshape(B, N, C)
79
+ x = self.proj(x)
80
+ x = self.proj_drop(x)
81
+ return x
82
+
83
+ def _forward(self, x: Tensor) -> Tensor:
84
+ B, N, C = x.shape
85
+ qkv = (
86
+ self.qkv(x)
87
+ .reshape(B, N, 3, self.num_heads, C // self.num_heads)
88
+ .permute(2, 0, 3, 1, 4)
89
+ )
90
+
91
+ q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
92
+ attn = q @ k.transpose(-2, -1)
93
+
94
+ attn = attn.softmax(dim=-1)
95
+ attn = self.attn_drop(attn)
96
+
97
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
98
+ x = self.proj(x)
99
+ x = self.proj_drop(x)
100
+ return x
src/depth_anything_3/model/dinov2/layers/block.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F821
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ # References:
9
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
10
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
11
+
12
+ import logging
13
+ from typing import Callable, Optional
14
+ import torch
15
+ from torch import Tensor, nn
16
+
17
+ from .attention import Attention
18
+ from .drop_path import DropPath
19
+ from .layer_scale import LayerScale
20
+ from .mlp import Mlp
21
+
22
+ logger = logging.getLogger("dinov2")
23
+ XFORMERS_AVAILABLE = True
24
+
25
+
26
+ class Block(nn.Module):
27
+ def __init__(
28
+ self,
29
+ dim: int,
30
+ num_heads: int,
31
+ mlp_ratio: float = 4.0,
32
+ qkv_bias: bool = False,
33
+ proj_bias: bool = True,
34
+ ffn_bias: bool = True,
35
+ drop: float = 0.0,
36
+ attn_drop: float = 0.0,
37
+ init_values=None,
38
+ drop_path: float = 0.0,
39
+ act_layer: Callable[..., nn.Module] = nn.GELU,
40
+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
41
+ attn_class: Callable[..., nn.Module] = Attention,
42
+ ffn_layer: Callable[..., nn.Module] = Mlp,
43
+ qk_norm: bool = False,
44
+ rope=None,
45
+ ln_eps: float = 1e-6,
46
+ ) -> None:
47
+ super().__init__()
48
+ # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
49
+ self.norm1 = norm_layer(dim, eps=ln_eps)
50
+ self.attn = attn_class(
51
+ dim,
52
+ num_heads=num_heads,
53
+ qkv_bias=qkv_bias,
54
+ proj_bias=proj_bias,
55
+ attn_drop=attn_drop,
56
+ proj_drop=drop,
57
+ qk_norm=qk_norm,
58
+ rope=rope,
59
+ )
60
+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
61
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
62
+
63
+ self.norm2 = norm_layer(dim, eps=ln_eps)
64
+ mlp_hidden_dim = int(dim * mlp_ratio)
65
+ self.mlp = ffn_layer(
66
+ in_features=dim,
67
+ hidden_features=mlp_hidden_dim,
68
+ act_layer=act_layer,
69
+ drop=drop,
70
+ bias=ffn_bias,
71
+ )
72
+ self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
73
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
74
+
75
+ self.sample_drop_ratio = drop_path
76
+
77
+ def forward(self, x: Tensor, pos=None, attn_mask=None) -> Tensor:
78
+ def attn_residual_func(x: Tensor, pos=None, attn_mask=None) -> Tensor:
79
+ return self.ls1(self.attn(self.norm1(x), pos=pos, attn_mask=attn_mask))
80
+
81
+ def ffn_residual_func(x: Tensor) -> Tensor:
82
+ return self.ls2(self.mlp(self.norm2(x)))
83
+
84
+ if self.training and self.sample_drop_ratio > 0.1:
85
+ # the overhead is compensated only for a drop path rate larger than 0.1
86
+ x = drop_add_residual_stochastic_depth(
87
+ x,
88
+ residual_func=attn_residual_func,
89
+ sample_drop_ratio=self.sample_drop_ratio,
90
+ pos=pos,
91
+ )
92
+ x = drop_add_residual_stochastic_depth(
93
+ x,
94
+ residual_func=ffn_residual_func,
95
+ sample_drop_ratio=self.sample_drop_ratio,
96
+ )
97
+ elif self.training and self.sample_drop_ratio > 0.0:
98
+ x = x + self.drop_path1(attn_residual_func(x, pos=pos, attn_mask=attn_mask))
99
+ x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
100
+ else:
101
+ x = x + attn_residual_func(x, pos=pos, attn_mask=attn_mask)
102
+ x = x + ffn_residual_func(x)
103
+ return x
104
+
105
+
106
+ def drop_add_residual_stochastic_depth(
107
+ x: Tensor,
108
+ residual_func: Callable[[Tensor], Tensor],
109
+ sample_drop_ratio: float = 0.0,
110
+ pos: Optional[Tensor] = None,
111
+ ) -> Tensor:
112
+ # 1) extract subset using permutation
113
+ b, n, d = x.shape
114
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
115
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
116
+ x_subset = x[brange]
117
+
118
+ # 2) apply residual_func to get residual
119
+ if pos is not None:
120
+ # if necessary, apply rope to the subset
121
+ pos = pos[brange]
122
+ residual = residual_func(x_subset, pos=pos)
123
+ else:
124
+ residual = residual_func(x_subset)
125
+
126
+ x_flat = x.flatten(1)
127
+ residual = residual.flatten(1)
128
+
129
+ residual_scale_factor = b / sample_subset_size
130
+
131
+ # 3) add the residual
132
+ x_plus_residual = torch.index_add(
133
+ x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor
134
+ )
135
+ return x_plus_residual.view_as(x)
136
+
137
+
138
+ def get_branges_scales(x, sample_drop_ratio=0.0):
139
+ b, n, d = x.shape
140
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
141
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
142
+ residual_scale_factor = b / sample_subset_size
143
+ return brange, residual_scale_factor
src/depth_anything_3/model/dinov2/layers/drop_path.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
10
+
11
+
12
+ from torch import nn
13
+
14
+
15
+ def drop_path(x, drop_prob: float = 0.0, training: bool = False):
16
+ if drop_prob == 0.0 or not training:
17
+ return x
18
+ keep_prob = 1 - drop_prob
19
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
20
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
21
+ if keep_prob > 0.0:
22
+ random_tensor.div_(keep_prob)
23
+ output = x * random_tensor
24
+ return output
25
+
26
+
27
+ class DropPath(nn.Module):
28
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
29
+
30
+ def __init__(self, drop_prob=None):
31
+ super().__init__()
32
+ self.drop_prob = drop_prob
33
+
34
+ def forward(self, x):
35
+ return drop_path(x, self.drop_prob, self.training)
src/depth_anything_3/model/dinov2/layers/layer_scale.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110 # noqa: E501
8
+
9
+ from typing import Union
10
+ import torch
11
+ from torch import Tensor, nn
12
+
13
+
14
+ class LayerScale(nn.Module):
15
+ def __init__(
16
+ self,
17
+ dim: int,
18
+ init_values: Union[float, Tensor] = 1e-5,
19
+ inplace: bool = False,
20
+ ) -> None:
21
+ super().__init__()
22
+ self.dim = dim
23
+ self.inplace = inplace
24
+ self.init_values = init_values
25
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
26
+
27
+ def forward(self, x: Tensor) -> Tensor:
28
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
29
+
30
+ def extra_repr(self) -> str:
31
+ return f"{self.dim}, init_values={self.init_values}, inplace={self.inplace}"
src/depth_anything_3/model/dinov2/layers/mlp.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
10
+
11
+
12
+ from typing import Callable, Optional
13
+ from torch import Tensor, nn
14
+
15
+
16
+ class Mlp(nn.Module):
17
+ def __init__(
18
+ self,
19
+ in_features: int,
20
+ hidden_features: Optional[int] = None,
21
+ out_features: Optional[int] = None,
22
+ act_layer: Callable[..., nn.Module] = nn.GELU,
23
+ drop: float = 0.0,
24
+ bias: bool = True,
25
+ ) -> None:
26
+ super().__init__()
27
+ out_features = out_features or in_features
28
+ hidden_features = hidden_features or in_features
29
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
30
+ self.act = act_layer()
31
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
32
+ self.drop = nn.Dropout(drop)
33
+
34
+ def forward(self, x: Tensor) -> Tensor:
35
+ x = self.fc1(x)
36
+ x = self.act(x)
37
+ x = self.drop(x)
38
+ x = self.fc2(x)
39
+ x = self.drop(x)
40
+ return x
src/depth_anything_3/model/dinov2/layers/patch_embed.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
10
+
11
+ from typing import Callable, Optional, Tuple, Union
12
+ import torch.nn as nn
13
+ from torch import Tensor
14
+
15
+
16
+ def make_2tuple(x):
17
+ if isinstance(x, tuple):
18
+ assert len(x) == 2
19
+ return x
20
+
21
+ assert isinstance(x, int)
22
+ return (x, x)
23
+
24
+
25
+ class PatchEmbed(nn.Module):
26
+ """
27
+ 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
28
+
29
+ Args:
30
+ img_size: Image size.
31
+ patch_size: Patch token size.
32
+ in_chans: Number of input image channels.
33
+ embed_dim: Number of linear projection output channels.
34
+ norm_layer: Normalization layer.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ img_size: Union[int, Tuple[int, int]] = 224,
40
+ patch_size: Union[int, Tuple[int, int]] = 16,
41
+ in_chans: int = 3,
42
+ embed_dim: int = 768,
43
+ norm_layer: Optional[Callable] = None,
44
+ flatten_embedding: bool = True,
45
+ ) -> None:
46
+ super().__init__()
47
+
48
+ image_HW = make_2tuple(img_size)
49
+ patch_HW = make_2tuple(patch_size)
50
+ patch_grid_size = (
51
+ image_HW[0] // patch_HW[0],
52
+ image_HW[1] // patch_HW[1],
53
+ )
54
+
55
+ self.img_size = image_HW
56
+ self.patch_size = patch_HW
57
+ self.patches_resolution = patch_grid_size
58
+ self.num_patches = patch_grid_size[0] * patch_grid_size[1]
59
+
60
+ self.in_chans = in_chans
61
+ self.embed_dim = embed_dim
62
+
63
+ self.flatten_embedding = flatten_embedding
64
+
65
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
66
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
67
+
68
+ def forward(self, x: Tensor) -> Tensor:
69
+ _, _, H, W = x.shape
70
+ patch_H, patch_W = self.patch_size
71
+
72
+ assert (
73
+ H % patch_H == 0
74
+ ), f"Input image height {H} is not a multiple of patch height {patch_H}"
75
+ assert (
76
+ W % patch_W == 0
77
+ ), f"Input image width {W} is not a multiple of patch width: {patch_W}"
78
+
79
+ x = self.proj(x) # B C H W
80
+ H, W = x.size(2), x.size(3)
81
+ x = x.flatten(2).transpose(1, 2) # B HW C
82
+ x = self.norm(x)
83
+ if not self.flatten_embedding:
84
+ x = x.reshape(-1, H, W, self.embed_dim) # B H W C
85
+ return x
86
+
87
+ def flops(self) -> float:
88
+ Ho, Wo = self.patches_resolution
89
+ flops = (
90
+ Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
91
+ )
92
+ if self.norm is not None:
93
+ flops += Ho * Wo * self.embed_dim
94
+ return flops
src/depth_anything_3/model/dinov2/layers/rope.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+
7
+ # Implementation of 2D Rotary Position Embeddings (RoPE).
8
+
9
+ # This module provides a clean implementation of 2D Rotary Position Embeddings,
10
+ # which extends the original RoPE concept to handle 2D spatial positions.
11
+
12
+ # Inspired by:
13
+ # https://github.com/meta-llama/codellama/blob/main/llama/model.py
14
+ # https://github.com/naver-ai/rope-vit
15
+
16
+
17
+ from typing import Dict, Tuple
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+
23
+ class PositionGetter:
24
+ """Generates and caches 2D spatial positions for patches in a grid.
25
+
26
+ This class efficiently manages the generation of spatial coordinates for patches
27
+ in a 2D grid, caching results to avoid redundant computations.
28
+
29
+ Attributes:
30
+ position_cache: Dictionary storing precomputed position tensors for different
31
+ grid dimensions.
32
+ """
33
+
34
+ def __init__(self):
35
+ """Initializes the position generator with an empty cache."""
36
+ self.position_cache: Dict[Tuple[int, int], torch.Tensor] = {}
37
+
38
+ def __call__(
39
+ self, batch_size: int, height: int, width: int, device: torch.device
40
+ ) -> torch.Tensor:
41
+ """Generates spatial positions for a batch of patches.
42
+
43
+ Args:
44
+ batch_size: Number of samples in the batch.
45
+ height: Height of the grid in patches.
46
+ width: Width of the grid in patches.
47
+ device: Target device for the position tensor.
48
+
49
+ Returns:
50
+ Tensor of shape (batch_size, height*width, 2) containing y,x coordinates
51
+ for each position in the grid, repeated for each batch item.
52
+ """
53
+ if (height, width) not in self.position_cache:
54
+ y_coords = torch.arange(height, device=device)
55
+ x_coords = torch.arange(width, device=device)
56
+ positions = torch.cartesian_prod(y_coords, x_coords)
57
+ self.position_cache[height, width] = positions
58
+
59
+ cached_positions = self.position_cache[height, width]
60
+ return cached_positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone()
61
+
62
+
63
+ class RotaryPositionEmbedding2D(nn.Module):
64
+ """2D Rotary Position Embedding implementation.
65
+
66
+ This module applies rotary position embeddings to input tokens based on their
67
+ 2D spatial positions. It handles the position-dependent rotation of features
68
+ separately for vertical and horizontal dimensions.
69
+
70
+ Args:
71
+ frequency: Base frequency for the position embeddings. Default: 100.0
72
+ scaling_factor: Scaling factor for frequency computation. Default: 1.0
73
+
74
+ Attributes:
75
+ base_frequency: Base frequency for computing position embeddings.
76
+ scaling_factor: Factor to scale the computed frequencies.
77
+ frequency_cache: Cache for storing precomputed frequency components.
78
+ """
79
+
80
+ def __init__(self, frequency: float = 100.0, scaling_factor: float = 1.0):
81
+ """Initializes the 2D RoPE module."""
82
+ super().__init__()
83
+ self.base_frequency = frequency
84
+ self.scaling_factor = scaling_factor
85
+ self.frequency_cache: Dict[Tuple, Tuple[torch.Tensor, torch.Tensor]] = {}
86
+
87
+ def _compute_frequency_components(
88
+ self, dim: int, seq_len: int, device: torch.device, dtype: torch.dtype
89
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
90
+ """Computes frequency components for rotary embeddings.
91
+
92
+ Args:
93
+ dim: Feature dimension (must be even).
94
+ seq_len: Maximum sequence length.
95
+ device: Target device for computations.
96
+ dtype: Data type for the computed tensors.
97
+
98
+ Returns:
99
+ Tuple of (cosine, sine) tensors for frequency components.
100
+ """
101
+ cache_key = (dim, seq_len, device, dtype)
102
+ if cache_key not in self.frequency_cache:
103
+ # Compute frequency bands
104
+ exponents = torch.arange(0, dim, 2, device=device).float() / dim
105
+ inv_freq = 1.0 / (self.base_frequency**exponents)
106
+
107
+ # Generate position-dependent frequencies
108
+ positions = torch.arange(seq_len, device=device, dtype=inv_freq.dtype)
109
+ angles = torch.einsum("i,j->ij", positions, inv_freq)
110
+
111
+ # Compute and cache frequency components
112
+ angles = angles.to(dtype)
113
+ angles = torch.cat((angles, angles), dim=-1)
114
+ cos_components = angles.cos().to(dtype)
115
+ sin_components = angles.sin().to(dtype)
116
+ self.frequency_cache[cache_key] = (cos_components, sin_components)
117
+
118
+ return self.frequency_cache[cache_key]
119
+
120
+ @staticmethod
121
+ def _rotate_features(x: torch.Tensor) -> torch.Tensor:
122
+ """Performs feature rotation by splitting and recombining feature dimensions.
123
+
124
+ Args:
125
+ x: Input tensor to rotate.
126
+
127
+ Returns:
128
+ Rotated feature tensor.
129
+ """
130
+ feature_dim = x.shape[-1]
131
+ x1, x2 = x[..., : feature_dim // 2], x[..., feature_dim // 2 :]
132
+ return torch.cat((-x2, x1), dim=-1)
133
+
134
+ def _apply_1d_rope(
135
+ self,
136
+ tokens: torch.Tensor,
137
+ positions: torch.Tensor,
138
+ cos_comp: torch.Tensor,
139
+ sin_comp: torch.Tensor,
140
+ ) -> torch.Tensor:
141
+ """Applies 1D rotary position embeddings along one dimension.
142
+
143
+ Args:
144
+ tokens: Input token features.
145
+ positions: Position indices.
146
+ cos_comp: Cosine components for rotation.
147
+ sin_comp: Sine components for rotation.
148
+
149
+ Returns:
150
+ Tokens with applied rotary position embeddings.
151
+ """
152
+ # Embed positions with frequency components
153
+ cos = F.embedding(positions, cos_comp)[:, None, :, :]
154
+ sin = F.embedding(positions, sin_comp)[:, None, :, :]
155
+ # Apply rotation
156
+ return (tokens * cos) + (self._rotate_features(tokens) * sin)
157
+
158
+ def forward(self, tokens: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
159
+ """Applies 2D rotary position embeddings to input tokens.
160
+
161
+ Args:
162
+ tokens: Input tensor of shape (batch_size, n_heads, n_tokens, dim).
163
+ The feature dimension (dim) must be divisible by 4.
164
+ positions: Position tensor of shape (batch_size, n_tokens, 2) containing
165
+ the y and x coordinates for each token.
166
+
167
+ Returns:
168
+ Tensor of same shape as input with applied 2D rotary position embeddings.
169
+
170
+ Raises:
171
+ AssertionError: If input dimensions are invalid or positions are malformed.
172
+ """
173
+ # Validate inputs
174
+ assert tokens.size(-1) % 2 == 0, "Feature dimension must be even"
175
+ assert (
176
+ positions.ndim == 3 and positions.shape[-1] == 2
177
+ ), "Positions must have shape (batch_size, n_tokens, 2)"
178
+
179
+ # Compute feature dimension for each spatial direction
180
+ feature_dim = tokens.size(-1) // 2
181
+
182
+ # Get frequency components
183
+ max_position = int(positions.max()) + 1
184
+ cos_comp, sin_comp = self._compute_frequency_components(
185
+ feature_dim, max_position, tokens.device, tokens.dtype
186
+ )
187
+
188
+ # Split features for vertical and horizontal processing
189
+ vertical_features, horizontal_features = tokens.chunk(2, dim=-1)
190
+
191
+ # Apply RoPE separately for each dimension
192
+ vertical_features = self._apply_1d_rope(
193
+ vertical_features, positions[..., 0], cos_comp, sin_comp
194
+ )
195
+ horizontal_features = self._apply_1d_rope(
196
+ horizontal_features, positions[..., 1], cos_comp, sin_comp
197
+ )
198
+
199
+ # Combine processed features
200
+ return torch.cat((vertical_features, horizontal_features), dim=-1)
src/depth_anything_3/model/dinov2/layers/swiglu_ffn.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Callable, Optional
8
+ import torch.nn.functional as F
9
+ from torch import Tensor, nn
10
+
11
+
12
+ class SwiGLUFFN(nn.Module):
13
+ def __init__(
14
+ self,
15
+ in_features: int,
16
+ hidden_features: Optional[int] = None,
17
+ out_features: Optional[int] = None,
18
+ act_layer: Callable[..., nn.Module] = None,
19
+ drop: float = 0.0,
20
+ bias: bool = True,
21
+ ) -> None:
22
+ super().__init__()
23
+ out_features = out_features or in_features
24
+ hidden_features = hidden_features or in_features
25
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
26
+ self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
27
+
28
+ def forward(self, x: Tensor) -> Tensor:
29
+ x12 = self.w12(x)
30
+ x1, x2 = x12.chunk(2, dim=-1)
31
+ hidden = F.silu(x1) * x2
32
+ return self.w3(hidden)
33
+
34
+
35
+ try:
36
+ from xformers.ops import SwiGLU
37
+
38
+ XFORMERS_AVAILABLE = True
39
+ except ImportError:
40
+ SwiGLU = SwiGLUFFN
41
+ XFORMERS_AVAILABLE = False
42
+
43
+
44
+ class SwiGLUFFNFused(SwiGLU):
45
+ def __init__(
46
+ self,
47
+ in_features: int,
48
+ hidden_features: Optional[int] = None,
49
+ out_features: Optional[int] = None,
50
+ act_layer: Callable[..., nn.Module] = None,
51
+ drop: float = 0.0,
52
+ bias: bool = True,
53
+ ) -> None:
54
+ out_features = out_features or in_features
55
+ hidden_features = hidden_features or in_features
56
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
57
+ super().__init__(
58
+ in_features=in_features,
59
+ hidden_features=hidden_features,
60
+ out_features=out_features,
61
+ bias=bias,
62
+ )
src/depth_anything_3/model/dinov2/vision_transformer.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
9
+
10
+ import math
11
+ from typing import Callable, List, Sequence, Tuple, Union
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.utils.checkpoint
16
+ from einops import rearrange
17
+ from torch.utils.checkpoint import checkpoint
18
+
19
+ from depth_anything_3.utils.logger import logger
20
+
21
+ from .layers import LayerScale # noqa: F401
22
+ from .layers import Mlp # noqa: F401
23
+ from .layers import ( # noqa: F401
24
+ Block,
25
+ PatchEmbed,
26
+ PositionGetter,
27
+ RotaryPositionEmbedding2D,
28
+ SwiGLUFFNFused,
29
+ )
30
+ from depth_anything_3.model.reference_view_selector import (
31
+ RefViewStrategy,
32
+ select_reference_view,
33
+ reorder_by_reference,
34
+ restore_original_order,
35
+ )
36
+ from depth_anything_3.utils.constants import THRESH_FOR_REF_SELECTION
37
+
38
+ # logger = logging.getLogger("dinov2")
39
+
40
+
41
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
42
+ """
43
+ embed_dim: output dimension for each position
44
+ pos: a list of positions to be encoded: size (M,)
45
+ out: (M, D)
46
+ """
47
+ assert embed_dim % 2 == 0
48
+ omega = np.arange(embed_dim // 2, dtype=float)
49
+ omega /= embed_dim / 2.0
50
+ omega = 1.0 / 10000**omega # (D/2,)
51
+
52
+ pos = pos.reshape(-1) # (M,)
53
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
54
+
55
+ emb_sin = np.sin(out) # (M, D/2)
56
+ emb_cos = np.cos(out) # (M, D/2)
57
+
58
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
59
+ return emb
60
+
61
+
62
+ def named_apply(
63
+ fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False
64
+ ) -> nn.Module:
65
+ if not depth_first and include_root:
66
+ fn(module=module, name=name)
67
+ for child_name, child_module in module.named_children():
68
+ child_name = ".".join((name, child_name)) if name else child_name
69
+ named_apply(
70
+ fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True
71
+ )
72
+ if depth_first and include_root:
73
+ fn(module=module, name=name)
74
+ return module
75
+
76
+
77
+ class BlockChunk(nn.ModuleList):
78
+ def forward(self, x):
79
+ for b in self:
80
+ x = b(x)
81
+ return x
82
+
83
+
84
+ class DinoVisionTransformer(nn.Module):
85
+ def __init__(
86
+ self,
87
+ img_size=224,
88
+ patch_size=16,
89
+ in_chans=3,
90
+ embed_dim=768,
91
+ depth=12,
92
+ num_heads=12,
93
+ mlp_ratio=4.0,
94
+ qkv_bias=True,
95
+ ffn_bias=True,
96
+ proj_bias=True,
97
+ drop_path_rate=0.0,
98
+ drop_path_uniform=False,
99
+ init_values=1.0, # for layerscale: None or 0 => no layerscale
100
+ embed_layer=PatchEmbed,
101
+ act_layer=nn.GELU,
102
+ block_fn=Block,
103
+ ffn_layer="mlp",
104
+ block_chunks=1,
105
+ num_register_tokens=0,
106
+ interpolate_antialias=False,
107
+ interpolate_offset=0.1,
108
+ alt_start=-1,
109
+ qknorm_start=-1,
110
+ rope_start=-1,
111
+ rope_freq=100,
112
+ plus_cam_token=False,
113
+ cat_token=True,
114
+ ):
115
+ """
116
+ Args:
117
+ img_size (int, tuple): input image size
118
+ patch_size (int, tuple): patch size
119
+ in_chans (int): number of input channels
120
+ embed_dim (int): embedding dimension
121
+ depth (int): depth of transformer
122
+ num_heads (int): number of attention heads
123
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
124
+ qkv_bias (bool): enable bias for qkv if True
125
+ proj_bias (bool): enable bias for proj in attn if True
126
+ ffn_bias (bool): enable bias for ffn if True
127
+ weight_init (str): weight init scheme
128
+ init_values (float): layer-scale init values
129
+ embed_layer (nn.Module): patch embedding layer
130
+ act_layer (nn.Module): MLP activation layer
131
+ block_fn (nn.Module): transformer block class
132
+ ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
133
+ block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
134
+ num_register_tokens: (int) number of extra cls tokens (so-called "registers")
135
+ interpolate_antialias: (str) flag to apply anti-aliasing when interpolating
136
+ positional embeddings
137
+ interpolate_offset: (float) work-around offset to apply when interpolating
138
+ positional embeddings
139
+ """
140
+ super().__init__()
141
+ self.patch_start_idx = 1
142
+ norm_layer = nn.LayerNorm
143
+ self.num_features = self.embed_dim = (
144
+ embed_dim # num_features for consistency with other models
145
+ )
146
+ self.alt_start = alt_start
147
+ self.qknorm_start = qknorm_start
148
+ self.rope_start = rope_start
149
+ self.cat_token = cat_token
150
+ self.num_tokens = 1
151
+ self.n_blocks = depth
152
+ self.num_heads = num_heads
153
+ self.patch_size = patch_size
154
+ self.num_register_tokens = num_register_tokens
155
+ self.interpolate_antialias = interpolate_antialias
156
+ self.interpolate_offset = interpolate_offset
157
+
158
+ self.patch_embed = embed_layer(
159
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim
160
+ )
161
+ num_patches = self.patch_embed.num_patches
162
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
163
+ if self.alt_start != -1:
164
+ self.camera_token = nn.Parameter(torch.randn(1, 2, embed_dim))
165
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
166
+ assert num_register_tokens >= 0
167
+ self.register_tokens = (
168
+ nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim))
169
+ if num_register_tokens
170
+ else None
171
+ )
172
+
173
+ if drop_path_uniform is True:
174
+ dpr = [drop_path_rate] * depth
175
+ else:
176
+ dpr = [
177
+ x.item() for x in torch.linspace(0, drop_path_rate, depth)
178
+ ] # stochastic depth decay rule
179
+ if ffn_layer == "mlp":
180
+ logger.info("using MLP layer as FFN")
181
+ ffn_layer = Mlp
182
+ elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
183
+ logger.info("using SwiGLU layer as FFN")
184
+ ffn_layer = SwiGLUFFNFused
185
+ elif ffn_layer == "identity":
186
+ logger.info("using Identity layer as FFN")
187
+
188
+ def f(*args, **kwargs):
189
+ return nn.Identity()
190
+
191
+ ffn_layer = f
192
+ else:
193
+ raise NotImplementedError
194
+
195
+ if self.rope_start != -1:
196
+ self.rope = RotaryPositionEmbedding2D(frequency=rope_freq) if rope_freq > 0 else None
197
+ self.position_getter = PositionGetter() if self.rope is not None else None
198
+ else:
199
+ self.rope = None
200
+ blocks_list = [
201
+ block_fn(
202
+ dim=embed_dim,
203
+ num_heads=num_heads,
204
+ mlp_ratio=mlp_ratio,
205
+ qkv_bias=qkv_bias,
206
+ proj_bias=proj_bias,
207
+ ffn_bias=ffn_bias,
208
+ drop_path=dpr[i],
209
+ norm_layer=norm_layer,
210
+ act_layer=act_layer,
211
+ ffn_layer=ffn_layer,
212
+ init_values=init_values,
213
+ qk_norm=i >= qknorm_start if qknorm_start != -1 else False,
214
+ rope=self.rope if i >= rope_start and rope_start != -1 else None,
215
+ )
216
+ for i in range(depth)
217
+ ]
218
+ self.blocks = nn.ModuleList(blocks_list)
219
+ self.norm = norm_layer(embed_dim)
220
+
221
+ def interpolate_pos_encoding(self, x, w, h):
222
+ previous_dtype = x.dtype
223
+ npatch = x.shape[1] - 1
224
+ N = self.pos_embed.shape[1] - 1
225
+ if npatch == N and w == h:
226
+ return self.pos_embed
227
+ pos_embed = self.pos_embed.float()
228
+ class_pos_embed = pos_embed[:, 0]
229
+ patch_pos_embed = pos_embed[:, 1:]
230
+ dim = x.shape[-1]
231
+ w0 = w // self.patch_size
232
+ h0 = h // self.patch_size
233
+ M = int(math.sqrt(N)) # Recover the number of patches in each dimension
234
+ assert N == M * M
235
+ kwargs = {}
236
+ if self.interpolate_offset:
237
+ # Historical kludge: add a small number to avoid floating point error in the
238
+ # interpolation, see https://github.com/facebookresearch/dino/issues/8
239
+ # Note: still needed for backward-compatibility, the underlying operators are using
240
+ # both output size and scale factors
241
+ sx = float(w0 + self.interpolate_offset) / M
242
+ sy = float(h0 + self.interpolate_offset) / M
243
+ kwargs["scale_factor"] = (sx, sy)
244
+ else:
245
+ # Simply specify an output size instead of a scale factor
246
+ kwargs["size"] = (w0, h0)
247
+ patch_pos_embed = nn.functional.interpolate(
248
+ patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2),
249
+ mode="bicubic",
250
+ antialias=self.interpolate_antialias,
251
+ **kwargs,
252
+ )
253
+ assert (w0, h0) == patch_pos_embed.shape[-2:]
254
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
255
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
256
+
257
+ def prepare_cls_token(self, B, S):
258
+ cls_token = self.cls_token.expand(B, S, -1)
259
+ cls_token = cls_token.reshape(B * S, -1, self.embed_dim)
260
+ return cls_token
261
+
262
+ def prepare_tokens_with_masks(self, x, masks=None, cls_token=None, **kwargs):
263
+ B, S, nc, w, h = x.shape
264
+ x = rearrange(x, "b s c h w -> (b s) c h w")
265
+ x = self.patch_embed(x)
266
+ if masks is not None:
267
+ x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
268
+ cls_token = self.prepare_cls_token(B, S)
269
+ x = torch.cat((cls_token, x), dim=1)
270
+ x = x + self.interpolate_pos_encoding(x, w, h)
271
+ if self.register_tokens is not None:
272
+ x = torch.cat(
273
+ (
274
+ x[:, :1],
275
+ self.register_tokens.expand(x.shape[0], -1, -1),
276
+ x[:, 1:],
277
+ ),
278
+ dim=1,
279
+ )
280
+ x = rearrange(x, "(b s) n c -> b s n c", b=B, s=S)
281
+ return x
282
+
283
+ def _prepare_rope(self, B, S, H, W, device):
284
+ pos = None
285
+ pos_nodiff = None
286
+ if self.rope is not None:
287
+ pos = self.position_getter(
288
+ B * S, H // self.patch_size, W // self.patch_size, device=device
289
+ )
290
+ pos = rearrange(pos, "(b s) n c -> b s n c", b=B)
291
+ pos_nodiff = torch.zeros_like(pos).to(pos.dtype)
292
+ if self.patch_start_idx > 0:
293
+ pos = pos + 1
294
+ pos_special = torch.zeros(B * S, self.patch_start_idx, 2).to(device).to(pos.dtype)
295
+ pos_special = rearrange(pos_special, "(b s) n c -> b s n c", b=B)
296
+ pos = torch.cat([pos_special, pos], dim=2)
297
+ pos_nodiff = pos_nodiff + 1
298
+ pos_nodiff = torch.cat([pos_special, pos_nodiff], dim=2)
299
+ return pos, pos_nodiff
300
+
301
+ def _get_intermediate_layers_not_chunked(self, x, n=1, export_feat_layers=[], **kwargs):
302
+ B, S, _, H, W = x.shape
303
+ x = self.prepare_tokens_with_masks(x)
304
+ output, total_block_len, aux_output = [], len(self.blocks), []
305
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
306
+ pos, pos_nodiff = self._prepare_rope(B, S, H, W, x.device)
307
+
308
+ for i, blk in enumerate(self.blocks):
309
+ if i < self.rope_start or self.rope is None:
310
+ g_pos, l_pos = None, None
311
+ else:
312
+ g_pos = pos_nodiff
313
+ l_pos = pos
314
+
315
+ if self.alt_start != -1 and (i == self.alt_start - 1) and x.shape[1] >= THRESH_FOR_REF_SELECTION:
316
+ # Select reference view using configured strategy
317
+ strategy = kwargs.get("ref_view_strategy", "saddle_balanced")
318
+ logger.info(f"Selecting reference view using strategy: {strategy}")
319
+ b_idx = select_reference_view(x, strategy=strategy)
320
+ # Reorder views to place reference view first
321
+ x = reorder_by_reference(x, b_idx)
322
+ local_x = reorder_by_reference(local_x, b_idx)
323
+
324
+ if self.alt_start != -1 and i == self.alt_start:
325
+ if kwargs.get("cam_token", None) is not None:
326
+ logger.info("Using camera conditions provided by the user")
327
+ cam_token = kwargs.get("cam_token")
328
+ else:
329
+ ref_token = self.camera_token[:, :1].expand(B, -1, -1)
330
+ src_token = self.camera_token[:, 1:].expand(B, S - 1, -1)
331
+ cam_token = torch.cat([ref_token, src_token], dim=1)
332
+ x[:, :, 0] = cam_token
333
+
334
+ if self.alt_start != -1 and i >= self.alt_start and i % 2 == 1:
335
+ x = self.process_attention(
336
+ x, blk, "global", pos=g_pos, attn_mask=kwargs.get("attn_mask", None)
337
+ )
338
+ else:
339
+ x = self.process_attention(x, blk, "local", pos=l_pos)
340
+ local_x = x
341
+
342
+ if i in blocks_to_take:
343
+ out_x = torch.cat([local_x, x], dim=-1) if self.cat_token else x
344
+ # Restore original view order if reordering was applied
345
+ if x.shape[1] >= THRESH_FOR_REF_SELECTION and self.alt_start != -1 and 'b_idx' in locals():
346
+ out_x = restore_original_order(out_x, b_idx)
347
+ output.append((out_x[:, :, 0], out_x))
348
+ if i in export_feat_layers:
349
+ aux_output.append(x)
350
+ return output, aux_output
351
+
352
+ def process_attention(self, x, block, attn_type="global", pos=None, attn_mask=None):
353
+ b, s, n = x.shape[:3]
354
+ if attn_type == "local":
355
+ x = rearrange(x, "b s n c -> (b s) n c")
356
+ if pos is not None:
357
+ pos = rearrange(pos, "b s n c -> (b s) n c")
358
+ elif attn_type == "global":
359
+ x = rearrange(x, "b s n c -> b (s n) c")
360
+ if pos is not None:
361
+ pos = rearrange(pos, "b s n c -> b (s n) c")
362
+ else:
363
+ raise ValueError(f"Invalid attention type: {attn_type}")
364
+
365
+ def forward_block(x, pos, attn_mask, block=block):
366
+ return block(x, pos=pos, attn_mask=attn_mask)
367
+
368
+ x = checkpoint(forward_block, x, pos, attn_mask, use_reentrant=False)
369
+ #x = checkpoint(block, x, pos, attn_mask, use_reentrant=False)
370
+ #x = block(x, pos=pos, attn_mask=attn_mask)
371
+
372
+ if attn_type == "local":
373
+ x = rearrange(x, "(b s) n c -> b s n c", b=b, s=s)
374
+ elif attn_type == "global":
375
+ x = rearrange(x, "b (s n) c -> b s n c", b=b, s=s)
376
+ return x
377
+
378
+ def get_intermediate_layers(
379
+ self,
380
+ x: torch.Tensor,
381
+ n: Union[int, Sequence] = 1, # Layers or n last layers to take
382
+ export_feat_layers: List[int] = [],
383
+ **kwargs,
384
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
385
+ outputs, aux_outputs = self._get_intermediate_layers_not_chunked(
386
+ x, n, export_feat_layers=export_feat_layers, **kwargs
387
+ )
388
+ camera_tokens = [out[0] for out in outputs]
389
+ if outputs[0][1].shape[-1] == self.embed_dim:
390
+ outputs = [self.norm(out[1]) for out in outputs]
391
+ elif outputs[0][1].shape[-1] == (self.embed_dim * 2):
392
+ outputs = [
393
+ torch.cat(
394
+ [out[1][..., : self.embed_dim], self.norm(out[1][..., self.embed_dim :])],
395
+ dim=-1,
396
+ )
397
+ for out in outputs
398
+ ]
399
+ else:
400
+ raise ValueError(f"Invalid output shape: {outputs[0][1].shape}")
401
+ aux_outputs = [self.norm(out) for out in aux_outputs]
402
+ outputs = [out[..., 1 + self.num_register_tokens :, :] for out in outputs]
403
+ aux_outputs = [out[..., 1 + self.num_register_tokens :, :] for out in aux_outputs]
404
+ return tuple(zip(outputs, camera_tokens)), aux_outputs
405
+
406
+
407
+ def vit_small(patch_size=16, num_register_tokens=0, depth=12, **kwargs):
408
+ model = DinoVisionTransformer(
409
+ patch_size=patch_size,
410
+ embed_dim=384,
411
+ depth=depth,
412
+ num_heads=6,
413
+ mlp_ratio=4,
414
+ # block_fn=partial(Block, attn_class=MemEffAttention),
415
+ num_register_tokens=num_register_tokens,
416
+ **kwargs,
417
+ )
418
+ return model
419
+
420
+
421
+ def vit_base(patch_size=16, num_register_tokens=0, depth=12, **kwargs):
422
+ model = DinoVisionTransformer(
423
+ patch_size=patch_size,
424
+ embed_dim=768,
425
+ depth=depth,
426
+ num_heads=12,
427
+ mlp_ratio=4,
428
+ # block_fn=partial(Block, attn_class=MemEffAttention),
429
+ num_register_tokens=num_register_tokens,
430
+ **kwargs,
431
+ )
432
+ return model
433
+
434
+
435
+ def vit_large(patch_size=16, num_register_tokens=0, depth=24, **kwargs):
436
+ model = DinoVisionTransformer(
437
+ patch_size=patch_size,
438
+ embed_dim=1024,
439
+ depth=depth,
440
+ num_heads=16,
441
+ mlp_ratio=4,
442
+ # block_fn=partial(Block, attn_class=MemEffAttention),
443
+ num_register_tokens=num_register_tokens,
444
+ **kwargs,
445
+ )
446
+ return model
447
+
448
+
449
+ def vit_giant2(patch_size=16, num_register_tokens=0, depth=40, **kwargs):
450
+ """
451
+ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
452
+ """
453
+ model = DinoVisionTransformer(
454
+ patch_size=patch_size,
455
+ embed_dim=1536,
456
+ depth=depth,
457
+ num_heads=24,
458
+ mlp_ratio=4,
459
+ num_register_tokens=num_register_tokens,
460
+ **kwargs,
461
+ )
462
+ return model
src/depth_anything_3/model/dpt.py ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa E501
2
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Dict as TyDict
17
+ from typing import List, Sequence, Tuple
18
+ import torch
19
+ import torch.nn as nn
20
+ from addict import Dict
21
+ from einops import rearrange
22
+
23
+ from depth_anything_3.model.utils.head_utils import (
24
+ Permute,
25
+ create_uv_grid,
26
+ custom_interpolate,
27
+ position_grid_to_embed,
28
+ )
29
+
30
+
31
+ class DPT(nn.Module):
32
+ """
33
+ DPT for dense prediction (main head + optional sky head, sky always 1 channel).
34
+
35
+ Returns:
36
+ - Main head:
37
+ * If output_dim>1: { head_name, f"{head_name}_conf" }
38
+ * If output_dim==1: { head_name }
39
+ - Sky head (if use_sky_head=True): { sky_name } # [B, S, 1, H/down_ratio, W/down_ratio]
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ dim_in: int,
45
+ *,
46
+ patch_size: int = 14,
47
+ output_dim: int = 1,
48
+ activation: str = "exp",
49
+ conf_activation: str = "expp1",
50
+ features: int = 256,
51
+ out_channels: Sequence[int] = (256, 512, 1024, 1024),
52
+ pos_embed: bool = False,
53
+ down_ratio: int = 1,
54
+ head_name: str = "depth",
55
+ # ---- sky head (fixed 1 channel) ----
56
+ use_sky_head: bool = True,
57
+ sky_name: str = "sky",
58
+ sky_activation: str = "relu", # 'sigmoid' / 'relu' / 'linear'
59
+ use_ln_for_heads: bool = False, # If needed, apply LayerNorm on intermediate features of both heads
60
+ norm_type: str = "idt", # use to match legacy GS-DPT head, "idt" / "layer"
61
+ fusion_block_inplace: bool = False,
62
+ ) -> None:
63
+ super().__init__()
64
+
65
+ # -------------------- configuration --------------------
66
+ self.patch_size = patch_size
67
+ self.activation = activation
68
+ self.conf_activation = conf_activation
69
+ self.pos_embed = pos_embed
70
+ self.down_ratio = down_ratio
71
+
72
+ # Names
73
+ self.head_main = head_name
74
+ self.sky_name = sky_name
75
+
76
+ # Main head: output dimension and confidence switch
77
+ self.out_dim = output_dim
78
+ self.has_conf = output_dim > 1
79
+
80
+ # Sky head parameters (always 1 channel)
81
+ self.use_sky_head = use_sky_head
82
+ self.sky_activation = sky_activation
83
+
84
+ # Fixed 4 intermediate outputs
85
+ self.intermediate_layer_idx: Tuple[int, int, int, int] = (0, 1, 2, 3)
86
+
87
+ # -------------------- token pre-norm + per-stage projection --------------------
88
+ if norm_type == "layer":
89
+ self.norm = nn.LayerNorm(dim_in)
90
+ elif norm_type == "idt":
91
+ self.norm = nn.Identity()
92
+ else:
93
+ raise Exception(f"Unknown norm_type {norm_type}, should be 'layer' or 'idt'.")
94
+ self.projects = nn.ModuleList(
95
+ [nn.Conv2d(dim_in, oc, kernel_size=1, stride=1, padding=0) for oc in out_channels]
96
+ )
97
+
98
+ # -------------------- Spatial re-size (align to common scale before fusion) --------------------
99
+ # Design consistent with original: relative to patch grid (x4, x2, x1, /2)
100
+ self.resize_layers = nn.ModuleList(
101
+ [
102
+ nn.ConvTranspose2d(
103
+ out_channels[0], out_channels[0], kernel_size=4, stride=4, padding=0
104
+ ),
105
+ nn.ConvTranspose2d(
106
+ out_channels[1], out_channels[1], kernel_size=2, stride=2, padding=0
107
+ ),
108
+ nn.Identity(),
109
+ nn.Conv2d(out_channels[3], out_channels[3], kernel_size=3, stride=2, padding=1),
110
+ ]
111
+ )
112
+
113
+ # -------------------- scratch: stage adapters + main fusion chain --------------------
114
+ self.scratch = _make_scratch(list(out_channels), features, expand=False)
115
+
116
+ # Main fusion chain
117
+ self.scratch.refinenet1 = _make_fusion_block(features, inplace=fusion_block_inplace)
118
+ self.scratch.refinenet2 = _make_fusion_block(features, inplace=fusion_block_inplace)
119
+ self.scratch.refinenet3 = _make_fusion_block(features, inplace=fusion_block_inplace)
120
+ self.scratch.refinenet4 = _make_fusion_block(
121
+ features, has_residual=False, inplace=fusion_block_inplace
122
+ )
123
+
124
+ # Heads (shared neck1; then split into two heads)
125
+ head_features_1 = features
126
+ head_features_2 = 32
127
+ self.scratch.output_conv1 = nn.Conv2d(
128
+ head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1
129
+ )
130
+
131
+ ln_seq = (
132
+ [Permute((0, 2, 3, 1)), nn.LayerNorm(head_features_2), Permute((0, 3, 1, 2))]
133
+ if use_ln_for_heads
134
+ else []
135
+ )
136
+
137
+ # Main head
138
+ self.scratch.output_conv2 = nn.Sequential(
139
+ nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
140
+ *ln_seq,
141
+ nn.ReLU(inplace=True),
142
+ nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0),
143
+ )
144
+
145
+ # Sky head (fixed 1 channel)
146
+ if self.use_sky_head:
147
+ self.scratch.sky_output_conv2 = nn.Sequential(
148
+ nn.Conv2d(
149
+ head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1
150
+ ),
151
+ *ln_seq,
152
+ nn.ReLU(inplace=True),
153
+ nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
154
+ )
155
+
156
+ # -------------------------------------------------------------------------
157
+ # Public forward (supports frame chunking to save memory)
158
+ # -------------------------------------------------------------------------
159
+ def forward(
160
+ self,
161
+ feats: List[torch.Tensor],
162
+ H: int,
163
+ W: int,
164
+ patch_start_idx: int,
165
+ chunk_size: int = 8,
166
+ **kwargs,
167
+ ) -> Dict:
168
+ """
169
+ Args:
170
+ feats: List of 4 entries, each entry is a tensor like [B, S, T, C] (or the 0th element of tuple/list is that tensor).
171
+ H, W: Original image dimensions
172
+ patch_start_idx: Starting index of patch tokens in sequence (for cropping non-patch tokens)
173
+ chunk_size: Chunk size along time dimension S
174
+
175
+ Returns:
176
+ Dict[str, Tensor]
177
+ """
178
+ B, S, N, C = feats[0][0].shape
179
+ feats = [feat[0].reshape(B * S, N, C) for feat in feats]
180
+
181
+ # update image info, used by the GS-DPT head
182
+ extra_kwargs = {}
183
+ if "images" in kwargs:
184
+ extra_kwargs.update({"images": rearrange(kwargs["images"], "B S ... -> (B S) ...")})
185
+
186
+ if chunk_size is None or chunk_size >= S:
187
+ out_dict = self._forward_impl(feats, H, W, patch_start_idx, **extra_kwargs)
188
+ out_dict = {k: v.view(B, S, *v.shape[1:]) for k, v in out_dict.items()}
189
+ return Dict(out_dict)
190
+
191
+ out_dicts: List[TyDict[str, torch.Tensor]] = []
192
+ for s0 in range(0, S, chunk_size):
193
+ s1 = min(s0 + chunk_size, S)
194
+ kw = {}
195
+ if "images" in extra_kwargs:
196
+ kw.update({"images": extra_kwargs["images"][s0:s1]})
197
+ out_dicts.append(
198
+ self._forward_impl([f[s0:s1] for f in feats], H, W, patch_start_idx, **kw)
199
+ )
200
+ out_dict = {k: torch.cat([od[k] for od in out_dicts], dim=0) for k in out_dicts[0].keys()}
201
+ out_dict = {k: v.view(B, S, *v.shape[1:]) for k, v in out_dict.items()}
202
+ return Dict(out_dict)
203
+
204
+ # -------------------------------------------------------------------------
205
+ # Internal forward (single chunk)
206
+ # -------------------------------------------------------------------------
207
+ def _forward_impl(
208
+ self,
209
+ feats: List[torch.Tensor],
210
+ H: int,
211
+ W: int,
212
+ patch_start_idx: int,
213
+ ) -> TyDict[str, torch.Tensor]:
214
+ B, _, C = feats[0].shape
215
+ ph, pw = H // self.patch_size, W // self.patch_size
216
+ resized_feats = []
217
+ for stage_idx, take_idx in enumerate(self.intermediate_layer_idx):
218
+ x = feats[take_idx][:, patch_start_idx:] # [B*S, N_patch, C]
219
+ x = self.norm(x)
220
+ # permute -> contiguous before reshape to keep conv input contiguous
221
+ x = x.permute(0, 2, 1).contiguous().reshape(B, C, ph, pw) # [B*S, C, ph, pw]
222
+
223
+ x = self.projects[stage_idx](x)
224
+ if self.pos_embed:
225
+ x = self._add_pos_embed(x, W, H)
226
+ x = self.resize_layers[stage_idx](x) # Align scale
227
+ resized_feats.append(x)
228
+
229
+ # 2) Fusion pyramid (main branch only)
230
+ fused = self._fuse(resized_feats)
231
+
232
+ # 3) Upsample to target resolution, optionally add position encoding again
233
+ h_out = int(ph * self.patch_size / self.down_ratio)
234
+ w_out = int(pw * self.patch_size / self.down_ratio)
235
+
236
+ fused = self.scratch.output_conv1(fused)
237
+ fused = custom_interpolate(fused, (h_out, w_out), mode="bilinear", align_corners=True)
238
+ if self.pos_embed:
239
+ fused = self._add_pos_embed(fused, W, H)
240
+
241
+ # 4) Shared neck1
242
+ feat = fused
243
+
244
+ # 5) Main head: logits -> activation
245
+ main_logits = self.scratch.output_conv2(feat)
246
+ outs: TyDict[str, torch.Tensor] = {}
247
+ if self.has_conf:
248
+ fmap = main_logits.permute(0, 2, 3, 1)
249
+ pred = self._apply_activation_single(fmap[..., :-1], self.activation)
250
+ conf = self._apply_activation_single(fmap[..., -1], self.conf_activation)
251
+ outs[self.head_main] = pred.squeeze(1)
252
+ outs[f"{self.head_main}_conf"] = conf.squeeze(1)
253
+ else:
254
+ outs[self.head_main] = self._apply_activation_single(
255
+ main_logits, self.activation
256
+ ).squeeze(1)
257
+
258
+ # 6) Sky head (fixed 1 channel)
259
+ if self.use_sky_head:
260
+ sky_logits = self.scratch.sky_output_conv2(feat)
261
+ outs[self.sky_name] = self._apply_sky_activation(sky_logits).squeeze(1)
262
+
263
+ return outs
264
+
265
+ # -------------------------------------------------------------------------
266
+ # Subroutines
267
+ # -------------------------------------------------------------------------
268
+ def _fuse(self, feats: List[torch.Tensor]) -> torch.Tensor:
269
+ """
270
+ 4-layer top-down fusion, returns finest scale features (after fusion, before neck1).
271
+ """
272
+ l1, l2, l3, l4 = feats
273
+
274
+ l1_rn = self.scratch.layer1_rn(l1)
275
+ l2_rn = self.scratch.layer2_rn(l2)
276
+ l3_rn = self.scratch.layer3_rn(l3)
277
+ l4_rn = self.scratch.layer4_rn(l4)
278
+
279
+ # 4 -> 3 -> 2 -> 1
280
+ out = self.scratch.refinenet4(l4_rn, size=l3_rn.shape[2:])
281
+ out = self.scratch.refinenet3(out, l3_rn, size=l2_rn.shape[2:])
282
+ out = self.scratch.refinenet2(out, l2_rn, size=l1_rn.shape[2:])
283
+ out = self.scratch.refinenet1(out, l1_rn)
284
+ return out
285
+
286
+ def _apply_activation_single(
287
+ self, x: torch.Tensor, activation: str = "linear"
288
+ ) -> torch.Tensor:
289
+ """
290
+ Apply activation to single channel output, maintaining semantic consistency with value branch in multi-channel case.
291
+ Supports: exp / relu / sigmoid / softplus / tanh / linear / expp1
292
+ """
293
+ act = activation.lower() if isinstance(activation, str) else activation
294
+ if act == "exp":
295
+ return torch.exp(x)
296
+ if act == "expp1":
297
+ return torch.exp(x) + 1
298
+ if act == "expm1":
299
+ return torch.expm1(x)
300
+ if act == "relu":
301
+ return torch.relu(x)
302
+ if act == "sigmoid":
303
+ return torch.sigmoid(x)
304
+ if act == "softplus":
305
+ return torch.nn.functional.softplus(x)
306
+ if act == "tanh":
307
+ return torch.tanh(x)
308
+ # Default linear
309
+ return x
310
+
311
+ def _apply_sky_activation(self, x: torch.Tensor) -> torch.Tensor:
312
+ """
313
+ Sky head activation (fixed 1 channel):
314
+ * 'sigmoid' -> Sigmoid probability map
315
+ * 'relu' -> ReLU positive domain output
316
+ * 'linear' -> Original value (logits)
317
+ """
318
+ act = (
319
+ self.sky_activation.lower()
320
+ if isinstance(self.sky_activation, str)
321
+ else self.sky_activation
322
+ )
323
+ if act == "sigmoid":
324
+ return torch.sigmoid(x)
325
+ if act == "relu":
326
+ return torch.relu(x)
327
+ # 'linear'
328
+ return x
329
+
330
+ def _add_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor:
331
+ """Simple UV position encoding directly added to feature map."""
332
+ pw, ph = x.shape[-1], x.shape[-2]
333
+ pe = create_uv_grid(pw, ph, aspect_ratio=W / H, dtype=x.dtype, device=x.device)
334
+ pe = position_grid_to_embed(pe, x.shape[1]) * ratio
335
+ pe = pe.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1)
336
+ return x + pe
337
+
338
+
339
+ # -----------------------------------------------------------------------------
340
+ # Building blocks (preserved, consistent with original)
341
+ # -----------------------------------------------------------------------------
342
+ def _make_fusion_block(
343
+ features: int,
344
+ size: Tuple[int, int] = None,
345
+ has_residual: bool = True,
346
+ groups: int = 1,
347
+ inplace: bool = False,
348
+ ) -> nn.Module:
349
+ return FeatureFusionBlock(
350
+ features=features,
351
+ activation=nn.ReLU(inplace=inplace),
352
+ deconv=False,
353
+ bn=False,
354
+ expand=False,
355
+ align_corners=True,
356
+ size=size,
357
+ has_residual=has_residual,
358
+ groups=groups,
359
+ )
360
+
361
+
362
+ def _make_scratch(
363
+ in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False
364
+ ) -> nn.Module:
365
+ scratch = nn.Module()
366
+ # Optional expansion by stage
367
+ c1 = out_shape
368
+ c2 = out_shape * (2 if expand else 1)
369
+ c3 = out_shape * (4 if expand else 1)
370
+ c4 = out_shape * (8 if expand else 1)
371
+
372
+ scratch.layer1_rn = nn.Conv2d(in_shape[0], c1, 3, 1, 1, bias=False, groups=groups)
373
+ scratch.layer2_rn = nn.Conv2d(in_shape[1], c2, 3, 1, 1, bias=False, groups=groups)
374
+ scratch.layer3_rn = nn.Conv2d(in_shape[2], c3, 3, 1, 1, bias=False, groups=groups)
375
+ scratch.layer4_rn = nn.Conv2d(in_shape[3], c4, 3, 1, 1, bias=False, groups=groups)
376
+ return scratch
377
+
378
+
379
+ class ResidualConvUnit(nn.Module):
380
+ """Lightweight residual convolution block for fusion"""
381
+
382
+ def __init__(self, features: int, activation: nn.Module, bn: bool, groups: int = 1) -> None:
383
+ super().__init__()
384
+ self.bn = bn
385
+ self.groups = groups
386
+ self.conv1 = nn.Conv2d(features, features, 3, 1, 1, bias=True, groups=groups)
387
+ self.conv2 = nn.Conv2d(features, features, 3, 1, 1, bias=True, groups=groups)
388
+ self.norm1 = None
389
+ self.norm2 = None
390
+ self.activation = activation
391
+ self.skip_add = nn.quantized.FloatFunctional()
392
+
393
+ def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore[override]
394
+ out = self.activation(x)
395
+ out = self.conv1(out)
396
+ if self.norm1 is not None:
397
+ out = self.norm1(out)
398
+
399
+ out = self.activation(out)
400
+ out = self.conv2(out)
401
+ if self.norm2 is not None:
402
+ out = self.norm2(out)
403
+
404
+ return self.skip_add.add(out, x)
405
+
406
+
407
+ class FeatureFusionBlock(nn.Module):
408
+ """Top-down fusion block: (optional) residual merge + upsampling + 1x1 contraction"""
409
+
410
+ def __init__(
411
+ self,
412
+ features: int,
413
+ activation: nn.Module,
414
+ deconv: bool = False,
415
+ bn: bool = False,
416
+ expand: bool = False,
417
+ align_corners: bool = True,
418
+ size: Tuple[int, int] = None,
419
+ has_residual: bool = True,
420
+ groups: int = 1,
421
+ ) -> None:
422
+ super().__init__()
423
+ self.align_corners = align_corners
424
+ self.size = size
425
+ self.has_residual = has_residual
426
+
427
+ self.resConfUnit1 = (
428
+ ResidualConvUnit(features, activation, bn, groups=groups) if has_residual else None
429
+ )
430
+ self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=groups)
431
+
432
+ out_features = (features // 2) if expand else features
433
+ self.out_conv = nn.Conv2d(features, out_features, 1, 1, 0, bias=True, groups=groups)
434
+ self.skip_add = nn.quantized.FloatFunctional()
435
+
436
+ def forward(self, *xs: torch.Tensor, size: Tuple[int, int] = None) -> torch.Tensor: # type: ignore[override]
437
+ """
438
+ xs:
439
+ - xs[0]: Top branch input
440
+ - xs[1]: Lateral input (can do residual addition with top branch)
441
+ """
442
+ y = xs[0]
443
+ if self.has_residual and len(xs) > 1 and self.resConfUnit1 is not None:
444
+ y = self.skip_add.add(y, self.resConfUnit1(xs[1]))
445
+
446
+ y = self.resConfUnit2(y)
447
+
448
+ # Upsampling
449
+ if (size is None) and (self.size is None):
450
+ up_kwargs = {"scale_factor": 2}
451
+ elif size is None:
452
+ up_kwargs = {"size": self.size}
453
+ else:
454
+ up_kwargs = {"size": size}
455
+
456
+ y = custom_interpolate(y, **up_kwargs, mode="bilinear", align_corners=self.align_corners)
457
+ y = self.out_conv(y)
458
+ return y
src/depth_anything_3/model/dualdpt.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa E501
2
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import List, Sequence, Tuple
17
+ import torch
18
+ import torch.nn as nn
19
+ from addict import Dict
20
+
21
+ from depth_anything_3.model.dpt import _make_fusion_block, _make_scratch
22
+ from depth_anything_3.model.utils.head_utils import (
23
+ Permute,
24
+ create_uv_grid,
25
+ custom_interpolate,
26
+ position_grid_to_embed,
27
+ )
28
+ from torch.utils.checkpoint import checkpoint
29
+
30
+ class DualDPT(nn.Module):
31
+ """
32
+ Dual-head DPT for dense prediction with an always-on auxiliary head.
33
+
34
+ Architectural notes:
35
+ - Sky/object branches are removed.
36
+ - `intermediate_layer_idx` is fixed to (0, 1, 2, 3).
37
+ - Auxiliary head has its **own** fusion blocks (no fusion_inplace / no sharing).
38
+ - Auxiliary head is internally multi-level; **only the final level** is returned.
39
+ - Returns a **dict** with keys from `head_names`, e.g.:
40
+ { main_name, f"{main_name}_conf", aux_name, f"{aux_name}_conf" }
41
+ - `feature_only` is fixed to False.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ dim_in: int,
47
+ *,
48
+ patch_size: int = 14,
49
+ output_dim: int = 2,
50
+ activation: str = "exp",
51
+ conf_activation: str = "expp1",
52
+ features: int = 256,
53
+ out_channels: Sequence[int] = (256, 512, 1024, 1024),
54
+ pos_embed: bool = True,
55
+ down_ratio: int = 1,
56
+ aux_pyramid_levels: int = 4,
57
+ aux_out1_conv_num: int = 5,
58
+ head_names: Tuple[str, str] = ("depth", "ray"),
59
+ ) -> None:
60
+ super().__init__()
61
+
62
+ # -------------------- configuration --------------------
63
+ self.patch_size = patch_size
64
+ self.activation = activation
65
+ self.conf_activation = conf_activation
66
+ self.pos_embed = pos_embed
67
+ self.down_ratio = down_ratio
68
+
69
+ self.aux_levels = aux_pyramid_levels
70
+ self.aux_out1_conv_num = aux_out1_conv_num
71
+
72
+ # names ONLY come from config (no hard-coded strings elsewhere)
73
+ self.head_main, self.head_aux = head_names
74
+
75
+ # Always expect 4 scales; enforce intermediate idx = (0, 1, 2, 3)
76
+ self.intermediate_layer_idx: Tuple[int, int, int, int] = (0, 1, 2, 3)
77
+
78
+ # -------------------- token pre-norm + per-stage projection --------------------
79
+ self.norm = nn.LayerNorm(dim_in)
80
+ self.projects = nn.ModuleList(
81
+ [nn.Conv2d(dim_in, oc, kernel_size=1, stride=1, padding=0) for oc in out_channels]
82
+ )
83
+
84
+ # -------------------- spatial re-sizers (align to common scale before fusion) --------------------
85
+ # design: stage strides (x4, x2, x1, /2) relative to patch grid to align to a common pivot scale
86
+ self.resize_layers = nn.ModuleList(
87
+ [
88
+ nn.ConvTranspose2d(
89
+ out_channels[0], out_channels[0], kernel_size=4, stride=4, padding=0
90
+ ),
91
+ nn.ConvTranspose2d(
92
+ out_channels[1], out_channels[1], kernel_size=2, stride=2, padding=0
93
+ ),
94
+ nn.Identity(),
95
+ nn.Conv2d(out_channels[3], out_channels[3], kernel_size=3, stride=2, padding=1),
96
+ ]
97
+ )
98
+
99
+ # -------------------- scratch: stage adapters + fusion (main & aux are separate) --------------------
100
+ self.scratch = _make_scratch(list(out_channels), features, expand=False)
101
+
102
+ # Main fusion chain (independent)
103
+ self.scratch.refinenet1 = _make_fusion_block(features)
104
+ self.scratch.refinenet2 = _make_fusion_block(features)
105
+ self.scratch.refinenet3 = _make_fusion_block(features)
106
+ self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False)
107
+
108
+ # Primary head neck + head (independent)
109
+ head_features_1 = features
110
+ head_features_2 = 32
111
+ self.scratch.output_conv1 = nn.Conv2d(
112
+ head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1
113
+ )
114
+ self.scratch.output_conv2 = nn.Sequential(
115
+ nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
116
+ nn.ReLU(inplace=True),
117
+ nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0),
118
+ )
119
+
120
+ # Auxiliary fusion chain (completely separate; no sharing, i.e., "fusion_inplace=False")
121
+ self.scratch.refinenet1_aux = _make_fusion_block(features)
122
+ self.scratch.refinenet2_aux = _make_fusion_block(features)
123
+ self.scratch.refinenet3_aux = _make_fusion_block(features)
124
+ self.scratch.refinenet4_aux = _make_fusion_block(features, has_residual=False)
125
+
126
+ # Aux pre-head per level (we will only *return final level*)
127
+ self.scratch.output_conv1_aux = nn.ModuleList(
128
+ [self._make_aux_out1_block(head_features_1) for _ in range(self.aux_levels)]
129
+ )
130
+
131
+ # Aux final projection per level
132
+ use_ln = True
133
+ ln_seq = (
134
+ [Permute((0, 2, 3, 1)), nn.LayerNorm(head_features_2), Permute((0, 3, 1, 2))]
135
+ if use_ln
136
+ else []
137
+ )
138
+ self.scratch.output_conv2_aux = nn.ModuleList(
139
+ [
140
+ nn.Sequential(
141
+ nn.Conv2d(
142
+ head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1
143
+ ),
144
+ *ln_seq,
145
+ nn.ReLU(inplace=True),
146
+ nn.Conv2d(head_features_2, 7, kernel_size=1, stride=1, padding=0),
147
+ )
148
+ for _ in range(self.aux_levels)
149
+ ]
150
+ )
151
+
152
+ # -------------------------------------------------------------------------
153
+ # Public forward (supports frame chunking for memory)
154
+ # -------------------------------------------------------------------------
155
+
156
+ def forward(
157
+ self,
158
+ feats: List[torch.Tensor],
159
+ H: int,
160
+ W: int,
161
+ patch_start_idx: int,
162
+ chunk_size: int = 16,
163
+ ) -> Dict[str, torch.Tensor]:
164
+ """
165
+ Args:
166
+ aggregated_tokens_list: List of 4 tensors [B, S, T, C] from transformer.
167
+ images: [B, S, 3, H, W], in [0, 1].
168
+ patch_start_idx: Patch-token start in the token sequence (to drop non-patch tokens).
169
+ frames_chunk_size: Optional chunking along S for memory.
170
+
171
+ Returns:
172
+ Dict[str, Tensor] with keys based on `head_names`, e.g.:
173
+ self.head_main, f"{self.head_main}_conf",
174
+ self.head_aux, f"{self.head_aux}_conf"
175
+ Shapes:
176
+ main: [B, S, out_dim, H/down_ratio, W/down_ratio]
177
+ main_cf: [B, S, 1, H/down_ratio, W/down_ratio]
178
+ aux: [B, S, 7, H/down_ratio, W/down_ratio]
179
+ aux_cf: [B, S, 1, H/down_ratio, W/down_ratio]
180
+ """
181
+ B, S, N, C = feats[0][0].shape
182
+ feats = [feat[0].reshape(B * S, N, C) for feat in feats]
183
+ if chunk_size is None or chunk_size >= S:
184
+ out_dict = self._forward_impl(feats, H, W, patch_start_idx)
185
+ out_dict = {k: v.reshape(B, S, *v.shape[1:]) for k, v in out_dict.items()}
186
+ return Dict(out_dict)
187
+ out_dicts = []
188
+ for s0 in range(0, S, chunk_size):
189
+ s1 = min(s0 + chunk_size, S)
190
+ out_dict = self._forward_impl(
191
+ [feat[s0:s1] for feat in feats],
192
+ H,
193
+ W,
194
+ patch_start_idx,
195
+ )
196
+ out_dicts.append(out_dict)
197
+ out_dict = {
198
+ k: torch.cat([out_dict[k] for out_dict in out_dicts], dim=0)
199
+ for k in out_dicts[0].keys()
200
+ }
201
+ out_dict = {k: v.view(B, S, *v.shape[1:]) for k, v in out_dict.items()}
202
+ return Dict(out_dict)
203
+
204
+ # -------------------------------------------------------------------------
205
+ # Internal forward (single chunk)
206
+ # -------------------------------------------------------------------------
207
+
208
+ def _forward_impl(
209
+ self,
210
+ feats: List[torch.Tensor],
211
+ H: int,
212
+ W: int,
213
+ patch_start_idx: int,
214
+ ) -> Dict[str, torch.Tensor]:
215
+ B, _, C = feats[0].shape
216
+ ph, pw = H // self.patch_size, W // self.patch_size
217
+ resized_feats = []
218
+ for stage_idx, take_idx in enumerate(self.intermediate_layer_idx):
219
+ x = feats[take_idx][:, patch_start_idx:]
220
+ #x = self.norm(x)
221
+ x = checkpoint(self.norm, x, use_reentrant=False)
222
+ x = x.permute(0, 2, 1).reshape(B, C, ph, pw) # [B*S, C, ph, pw]
223
+
224
+ #x = self.projects[stage_idx](x)
225
+ x = checkpoint(self.projects[stage_idx], x, use_reentrant=False)
226
+ if self.pos_embed:
227
+ x = self._add_pos_embed(x, W, H)
228
+ #x = self.resize_layers[stage_idx](x) # align scales
229
+ x = checkpoint(self.resize_layers[stage_idx], x, use_reentrant=False) # align scales
230
+ resized_feats.append(x)
231
+
232
+ # 2) Fuse pyramid (main & aux are completely independent)
233
+ #fused_main, fused_aux_pyr = self._fuse(resized_feats)
234
+ fused_main, fused_aux_pyr = checkpoint(self._fuse, resized_feats, use_reentrant=False)
235
+
236
+ # 3) Upsample to target resolution and (optional) add pos-embed again
237
+ h_out = int(ph * self.patch_size / self.down_ratio)
238
+ w_out = int(pw * self.patch_size / self.down_ratio)
239
+
240
+ fused_main = custom_interpolate(
241
+ fused_main, (h_out, w_out), mode="bilinear", align_corners=True
242
+ )
243
+ if self.pos_embed:
244
+ fused_main = self._add_pos_embed(fused_main, W, H)
245
+
246
+ # Primary head: conv1 -> conv2 -> activate
247
+ # fused_main = self.scratch.output_conv1(fused_main)
248
+ #main_logits = self.scratch.output_conv2(fused_main)
249
+ main_logits = checkpoint(self.scratch.output_conv2, fused_main, use_reentrant=False) # align scales
250
+ fmap = main_logits.permute(0, 2, 3, 1)
251
+ main_pred = self._apply_activation_single(fmap[..., :-1], self.activation)
252
+ main_conf = self._apply_activation_single(fmap[..., -1], self.conf_activation)
253
+
254
+ # Auxiliary head (multi-level inside) -> only last level returned (after activation)
255
+ last_aux = fused_aux_pyr[-1]
256
+ if self.pos_embed:
257
+ last_aux = self._add_pos_embed(last_aux, W, H)
258
+ # neck (per-level pre-conv) then final projection (only for last level)
259
+ # last_aux = self.scratch.output_conv1_aux[-1](last_aux)
260
+ #last_aux_logits = self.scratch.output_conv2_aux[-1](last_aux)
261
+ last_aux_logits = checkpoint(self.scratch.output_conv2_aux[-1], last_aux, use_reentrant=False) # align scales
262
+ fmap_last = last_aux_logits.permute(0, 2, 3, 1)
263
+ aux_pred = self._apply_activation_single(fmap_last[..., :-1], "linear")
264
+ aux_conf = self._apply_activation_single(fmap_last[..., -1], self.conf_activation)
265
+ return {
266
+ self.head_main: main_pred.squeeze(-1),
267
+ f"{self.head_main}_conf": main_conf,
268
+ self.head_aux: aux_pred,
269
+ f"{self.head_aux}_conf": aux_conf,
270
+ }
271
+
272
+ # -------------------------------------------------------------------------
273
+ # Subroutines
274
+ # -------------------------------------------------------------------------
275
+
276
+ def _fuse(self, feats: List[torch.Tensor]) -> Tuple[torch.Tensor, List[torch.Tensor]]:
277
+ """
278
+ Feature pyramid fusion.
279
+ Returns:
280
+ fused_main: Tensor at finest scale (after refinenet1)
281
+ aux_pyr: List of aux tensors at each level (pre out_conv1_aux)
282
+ """
283
+ l1, l2, l3, l4 = feats
284
+
285
+ l1_rn = self.scratch.layer1_rn(l1)
286
+ l2_rn = self.scratch.layer2_rn(l2)
287
+ l3_rn = self.scratch.layer3_rn(l3)
288
+ l4_rn = self.scratch.layer4_rn(l4)
289
+
290
+
291
+ #l1_rn = checkpoint(self.scratch.layer1_rn, l1, use_reentrant=False)
292
+ #l2_rn = checkpoint(self.scratch.layer2_rn, l2, use_reentrant=False)
293
+ #l3_rn = checkpoint(self.scratch.layer3_rn, l3, use_reentrant=False)
294
+ #l4_rn = checkpoint(self.scratch.layer4_rn, l4, use_reentrant=False)
295
+
296
+ # level 4 -> 3
297
+ out = self.scratch.refinenet4(l4_rn, size=l3_rn.shape[2:])
298
+ aux_out = self.scratch.refinenet4_aux(l4_rn, size=l3_rn.shape[2:])
299
+ aux_list: List[torch.Tensor] = []
300
+ if self.aux_levels >= 4:
301
+ aux_list.append(aux_out)
302
+
303
+ # level 3 -> 2
304
+ out = self.scratch.refinenet3(out, l3_rn, size=l2_rn.shape[2:])
305
+ aux_out = self.scratch.refinenet3_aux(aux_out, l3_rn, size=l2_rn.shape[2:])
306
+ if self.aux_levels >= 3:
307
+ aux_list.append(aux_out)
308
+
309
+ # level 2 -> 1
310
+ out = self.scratch.refinenet2(out, l2_rn, size=l1_rn.shape[2:])
311
+ aux_out = self.scratch.refinenet2_aux(aux_out, l2_rn, size=l1_rn.shape[2:])
312
+ if self.aux_levels >= 2:
313
+ aux_list.append(aux_out)
314
+
315
+ # level 1 (final)
316
+ out = self.scratch.refinenet1(out, l1_rn)
317
+ aux_out = self.scratch.refinenet1_aux(aux_out, l1_rn)
318
+ aux_list.append(aux_out)
319
+
320
+ out = self.scratch.output_conv1(out)
321
+ aux_list = [self.scratch.output_conv1_aux[i](aux) for i, aux in enumerate(aux_list)]
322
+
323
+ return out, aux_list
324
+
325
+ def _add_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor:
326
+ """Simple UV positional embedding added to feature maps."""
327
+ pw, ph = x.shape[-1], x.shape[-2]
328
+ pe = create_uv_grid(pw, ph, aspect_ratio=W / H, dtype=x.dtype, device=x.device)
329
+ pe = position_grid_to_embed(pe, x.shape[1]) * ratio
330
+ pe = pe.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1)
331
+ return x + pe
332
+
333
+ def _make_aux_out1_block(self, in_ch: int) -> nn.Sequential:
334
+ """Factory for the aux pre-head stack before the final 1x1 projection."""
335
+ if self.aux_out1_conv_num == 5:
336
+ return nn.Sequential(
337
+ nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1),
338
+ nn.Conv2d(in_ch // 2, in_ch, 3, 1, 1),
339
+ nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1),
340
+ nn.Conv2d(in_ch // 2, in_ch, 3, 1, 1),
341
+ nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1),
342
+ )
343
+ if self.aux_out1_conv_num == 3:
344
+ return nn.Sequential(
345
+ nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1),
346
+ nn.Conv2d(in_ch // 2, in_ch, 3, 1, 1),
347
+ nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1),
348
+ )
349
+ if self.aux_out1_conv_num == 1:
350
+ return nn.Sequential(nn.Conv2d(in_ch, in_ch // 2, 3, 1, 1))
351
+ raise ValueError(f"aux_out1_conv_num {self.aux_out1_conv_num} not supported")
352
+
353
+ def _apply_activation_single(
354
+ self, x: torch.Tensor, activation: str = "linear"
355
+ ) -> torch.Tensor:
356
+ """
357
+ Apply activation to single channel output, maintaining semantic consistency with value branch in multi-channel case.
358
+ Supports: exp / relu / sigmoid / softplus / tanh / linear / expp1
359
+ """
360
+ act = activation.lower() if isinstance(activation, str) else activation
361
+ if act == "exp":
362
+ return torch.exp(x)
363
+ if act == "expm1":
364
+ return torch.expm1(x)
365
+ if act == "expp1":
366
+ return torch.exp(x) + 1
367
+ if act == "relu":
368
+ return torch.relu(x)
369
+ if act == "sigmoid":
370
+ return torch.sigmoid(x)
371
+ if act == "softplus":
372
+ return torch.nn.functional.softplus(x)
373
+ if act == "tanh":
374
+ return torch.tanh(x)
375
+ # Default linear
376
+ return x
377
+
378
+
379
+ # # -----------------------------------------------------------------------------
380
+ # # Building blocks (tidy)
381
+ # # -----------------------------------------------------------------------------
382
+
383
+
384
+ # def _make_fusion_block(
385
+ # features: int,
386
+ # size: Tuple[int, int] = None,
387
+ # has_residual: bool = True,
388
+ # groups: int = 1,
389
+ # inplace: bool = False, # <- activation uses inplace=True by default; not related to "fusion_inplace"
390
+ # ) -> nn.Module:
391
+ # return FeatureFusionBlock(
392
+ # features=features,
393
+ # activation=nn.ReLU(inplace=inplace),
394
+ # deconv=False,
395
+ # bn=False,
396
+ # expand=False,
397
+ # align_corners=True,
398
+ # size=size,
399
+ # has_residual=has_residual,
400
+ # groups=groups,
401
+ # )
402
+
403
+
404
+ # def _make_scratch(
405
+ # in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False
406
+ # ) -> nn.Module:
407
+ # scratch = nn.Module()
408
+ # # optionally expand widths by stage
409
+ # c1 = out_shape
410
+ # c2 = out_shape * (2 if expand else 1)
411
+ # c3 = out_shape * (4 if expand else 1)
412
+ # c4 = out_shape * (8 if expand else 1)
413
+
414
+ # scratch.layer1_rn = nn.Conv2d(in_shape[0], c1, 3, 1, 1, bias=False, groups=groups)
415
+ # scratch.layer2_rn = nn.Conv2d(in_shape[1], c2, 3, 1, 1, bias=False, groups=groups)
416
+ # scratch.layer3_rn = nn.Conv2d(in_shape[2], c3, 3, 1, 1, bias=False, groups=groups)
417
+ # scratch.layer4_rn = nn.Conv2d(in_shape[3], c4, 3, 1, 1, bias=False, groups=groups)
418
+ # return scratch
419
+
420
+
421
+ # class ResidualConvUnit(nn.Module):
422
+ # """Lightweight residual conv block used within fusion."""
423
+
424
+ # def __init__(self, features: int, activation: nn.Module, bn: bool, groups: int = 1) -> None:
425
+ # super().__init__()
426
+ # self.bn = bn
427
+ # self.groups = groups
428
+ # self.conv1 = nn.Conv2d(features, features, 3, 1, 1, bias=True, groups=groups)
429
+ # self.conv2 = nn.Conv2d(features, features, 3, 1, 1, bias=True, groups=groups)
430
+ # self.norm1 = None
431
+ # self.norm2 = None
432
+ # self.activation = activation
433
+ # self.skip_add = nn.quantized.FloatFunctional()
434
+
435
+ # def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore[override]
436
+ # out = self.activation(x)
437
+ # out = self.conv1(out)
438
+ # if self.norm1 is not None:
439
+ # out = self.norm1(out)
440
+
441
+ # out = self.activation(out)
442
+ # out = self.conv2(out)
443
+ # if self.norm2 is not None:
444
+ # out = self.norm2(out)
445
+
446
+ # return self.skip_add.add(out, x)
447
+
448
+
449
+ # class FeatureFusionBlock(nn.Module):
450
+ # """Top-down fusion block: (optional) residual merge + upsample + 1x1 shrink."""
451
+
452
+ # def __init__(
453
+ # self,
454
+ # features: int,
455
+ # activation: nn.Module,
456
+ # deconv: bool = False,
457
+ # bn: bool = False,
458
+ # expand: bool = False,
459
+ # align_corners: bool = True,
460
+ # size: Tuple[int, int] = None,
461
+ # has_residual: bool = True,
462
+ # groups: int = 1,
463
+ # ) -> None:
464
+ # super().__init__()
465
+ # self.align_corners = align_corners
466
+ # self.size = size
467
+ # self.has_residual = has_residual
468
+
469
+ # self.resConfUnit1 = (
470
+ # ResidualConvUnit(features, activation, bn, groups=groups) if has_residual else None
471
+ # )
472
+ # self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=groups)
473
+
474
+ # out_features = (features // 2) if expand else features
475
+ # self.out_conv = nn.Conv2d(features, out_features, 1, 1, 0, bias=True, groups=groups)
476
+ # self.skip_add = nn.quantized.FloatFunctional()
477
+
478
+ # def forward(self, *xs: torch.Tensor, size: Tuple[int, int] = None) -> torch.Tensor: # type: ignore[override]
479
+ # """
480
+ # xs:
481
+ # - xs[0]: top input
482
+ # - xs[1]: (optional) lateral (to be added with residual)
483
+ # """
484
+ # y = xs[0]
485
+ # if self.has_residual and len(xs) > 1 and self.resConfUnit1 is not None:
486
+ # y = self.skip_add.add(y, self.resConfUnit1(xs[1]))
487
+
488
+ # y = self.resConfUnit2(y)
489
+
490
+ # # upsample
491
+ # if (size is None) and (self.size is None):
492
+ # up_kwargs = {"scale_factor": 2}
493
+ # elif size is None:
494
+ # up_kwargs = {"size": self.size}
495
+ # else:
496
+ # up_kwargs = {"size": size}
497
+
498
+ # y = custom_interpolate(y, **up_kwargs, mode="bilinear", align_corners=self.align_corners)
499
+ # y = self.out_conv(y)
500
+ # return y
src/depth_anything_3/model/gs_adapter.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional
16
+ import torch
17
+ from einops import einsum, rearrange, repeat
18
+ from torch import nn
19
+
20
+ from depth_anything_3.model.utils.transform import cam_quat_xyzw_to_world_quat_wxyz
21
+ from depth_anything_3.specs import Gaussians
22
+ from depth_anything_3.utils.geometry import affine_inverse, get_world_rays, sample_image_grid
23
+ from depth_anything_3.utils.pose_align import batch_align_poses_umeyama
24
+ from depth_anything_3.utils.sh_helpers import rotate_sh
25
+
26
+
27
+ class GaussianAdapter(nn.Module):
28
+
29
+ def __init__(
30
+ self,
31
+ sh_degree: int = 0,
32
+ pred_color: bool = False,
33
+ pred_offset_depth: bool = False,
34
+ pred_offset_xy: bool = True,
35
+ gaussian_scale_min: float = 1e-5,
36
+ gaussian_scale_max: float = 30.0,
37
+ ):
38
+ super().__init__()
39
+ self.sh_degree = sh_degree
40
+ self.pred_color = pred_color
41
+ self.pred_offset_depth = pred_offset_depth
42
+ self.pred_offset_xy = pred_offset_xy
43
+ self.gaussian_scale_min = gaussian_scale_min
44
+ self.gaussian_scale_max = gaussian_scale_max
45
+
46
+ # Create a mask for the spherical harmonics coefficients. This ensures that at
47
+ # initialization, the coefficients are biased towards having a large DC
48
+ # component and small view-dependent components.
49
+ if not pred_color:
50
+ self.register_buffer(
51
+ "sh_mask",
52
+ torch.ones((self.d_sh,), dtype=torch.float32),
53
+ persistent=False,
54
+ )
55
+ for degree in range(1, sh_degree + 1):
56
+ self.sh_mask[degree**2 : (degree + 1) ** 2] = 0.1 * 0.25**degree
57
+
58
+ def forward(
59
+ self,
60
+ extrinsics: torch.Tensor, # "*#batch 4 4"
61
+ intrinsics: torch.Tensor, # "*#batch 3 3"
62
+ depths: torch.Tensor, # "*#batch"
63
+ opacities: torch.Tensor, # "*#batch" | "*#batch _"
64
+ raw_gaussians: torch.Tensor, # "*#batch _"
65
+ image_shape: tuple[int, int],
66
+ eps: float = 1e-8,
67
+ gt_extrinsics: Optional[torch.Tensor] = None, # "*#batch 4 4"
68
+ **kwargs,
69
+ ) -> Gaussians:
70
+ device = extrinsics.device
71
+ dtype = raw_gaussians.dtype
72
+ H, W = image_shape
73
+ b, v = raw_gaussians.shape[:2]
74
+
75
+ # get cam2worlds and intr_normed to adapt to 3DGS codebase
76
+ cam2worlds = affine_inverse(extrinsics)
77
+ intr_normed = intrinsics.clone().detach()
78
+ intr_normed[..., 0, :] /= W
79
+ intr_normed[..., 1, :] /= H
80
+
81
+ # 1. compute 3DGS means
82
+ # 1.1) offset the predicted depth if needed
83
+ if self.pred_offset_depth:
84
+ gs_depths = depths + raw_gaussians[..., -1]
85
+ raw_gaussians = raw_gaussians[..., :-1]
86
+ else:
87
+ gs_depths = depths
88
+ # 1.2) align predicted poses with GT if needed
89
+ if gt_extrinsics is not None and not torch.equal(extrinsics, gt_extrinsics):
90
+ try:
91
+ _, _, pose_scales = batch_align_poses_umeyama(
92
+ gt_extrinsics.detach().float(),
93
+ extrinsics.detach().float(),
94
+ )
95
+ except Exception:
96
+ pose_scales = torch.ones_like(extrinsics[:, 0, 0, 0])
97
+ pose_scales = torch.clamp(pose_scales, min=1 / 3.0, max=3.0)
98
+ cam2worlds[:, :, :3, 3] = cam2worlds[:, :, :3, 3] * rearrange(
99
+ pose_scales, "b -> b () ()"
100
+ ) # [b, i, j]
101
+ gs_depths = gs_depths * rearrange(pose_scales, "b -> b () () ()") # [b, v, h, w]
102
+ # 1.3) casting xy in image space
103
+ xy_ray, _ = sample_image_grid((H, W), device)
104
+ xy_ray = xy_ray[None, None, ...].expand(b, v, -1, -1, -1) # b v h w xy
105
+ # offset xy if needed
106
+ if self.pred_offset_xy:
107
+ pixel_size = 1 / torch.tensor((W, H), dtype=xy_ray.dtype, device=device)
108
+ offset_xy = raw_gaussians[..., :2]
109
+ xy_ray = xy_ray + offset_xy * pixel_size
110
+ raw_gaussians = raw_gaussians[..., 2:] # skip the offset_xy
111
+ # 1.4) unproject depth + xy to world ray
112
+ origins, directions = get_world_rays(
113
+ xy_ray,
114
+ repeat(cam2worlds, "b v i j -> b v h w i j", h=H, w=W),
115
+ repeat(intr_normed, "b v i j -> b v h w i j", h=H, w=W),
116
+ )
117
+ gs_means_world = origins + directions * gs_depths[..., None]
118
+ gs_means_world = rearrange(gs_means_world, "b v h w d -> b (v h w) d")
119
+
120
+ # 2. compute other GS attributes
121
+ scales, rotations, sh = raw_gaussians.split((3, 4, 3 * self.d_sh), dim=-1)
122
+
123
+ # 2.1) 3DGS scales
124
+ # make the scale invarient to resolution
125
+ scale_min = self.gaussian_scale_min
126
+ scale_max = self.gaussian_scale_max
127
+ scales = scale_min + (scale_max - scale_min) * scales.sigmoid()
128
+ pixel_size = 1 / torch.tensor((W, H), dtype=dtype, device=device)
129
+ multiplier = self.get_scale_multiplier(intr_normed, pixel_size)
130
+ gs_scales = scales * gs_depths[..., None] * multiplier[..., None, None, None]
131
+ gs_scales = rearrange(gs_scales, "b v h w d -> b (v h w) d")
132
+
133
+ # 2.2) 3DGS quaternion (world space)
134
+ # due to historical issue, assume quaternion in order xyzw, not wxyz
135
+ # Normalize the quaternion features to yield a valid quaternion.
136
+ rotations = rotations / (rotations.norm(dim=-1, keepdim=True) + eps)
137
+ # rotate them to world space
138
+ cam_quat_xyzw = rearrange(rotations, "b v h w c -> b (v h w) c")
139
+ c2w_mat = repeat(
140
+ cam2worlds,
141
+ "b v i j -> b (v h w) i j",
142
+ h=H,
143
+ w=W,
144
+ )
145
+ world_quat_wxyz = cam_quat_xyzw_to_world_quat_wxyz(cam_quat_xyzw, c2w_mat)
146
+ gs_rotations_world = world_quat_wxyz # b (v h w) c
147
+
148
+ # 2.3) 3DGS color / SH coefficient (world space)
149
+ sh = rearrange(sh, "... (xyz d_sh) -> ... xyz d_sh", xyz=3)
150
+ if not self.pred_color:
151
+ sh = sh * self.sh_mask
152
+
153
+ if self.pred_color or self.sh_degree == 0:
154
+ # predict pre-computed color or predict only DC band, no need to transform
155
+ gs_sh_world = sh
156
+ else:
157
+ gs_sh_world = rotate_sh(sh, cam2worlds[:, :, None, None, None, :3, :3])
158
+ gs_sh_world = rearrange(gs_sh_world, "b v h w xyz d_sh -> b (v h w) xyz d_sh")
159
+
160
+ # 2.4) 3DGS opacity
161
+ gs_opacities = rearrange(opacities, "b v h w ... -> b (v h w) ...")
162
+
163
+ return Gaussians(
164
+ means=gs_means_world,
165
+ harmonics=gs_sh_world,
166
+ opacities=gs_opacities,
167
+ scales=gs_scales,
168
+ rotations=gs_rotations_world,
169
+ )
170
+
171
+ def get_scale_multiplier(
172
+ self,
173
+ intrinsics: torch.Tensor, # "*#batch 3 3"
174
+ pixel_size: torch.Tensor, # "*#batch 2"
175
+ multiplier: float = 0.1,
176
+ ) -> torch.Tensor: # " *batch"
177
+ xy_multipliers = multiplier * einsum(
178
+ intrinsics[..., :2, :2].float().inverse().to(intrinsics),
179
+ pixel_size,
180
+ "... i j, j -> ... i",
181
+ )
182
+ return xy_multipliers.sum(dim=-1)
183
+
184
+ @property
185
+ def d_sh(self) -> int:
186
+ return 1 if self.pred_color else (self.sh_degree + 1) ** 2
187
+
188
+ @property
189
+ def d_in(self) -> int:
190
+ # provided as reference to the gs_dpt output dim
191
+ raw_gs_dim = 0
192
+ if self.pred_offset_xy:
193
+ raw_gs_dim += 2
194
+ raw_gs_dim += 3 # scales
195
+ raw_gs_dim += 4 # quaternion
196
+ raw_gs_dim += 3 * self.d_sh # color
197
+ if self.pred_offset_depth:
198
+ raw_gs_dim += 1
199
+
200
+ return raw_gs_dim
src/depth_anything_3/model/gsdpt.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Dict as TyDict
16
+ from typing import List, Sequence
17
+ import torch
18
+ import torch.nn as nn
19
+
20
+ from depth_anything_3.model.dpt import DPT
21
+ from depth_anything_3.model.utils.head_utils import activate_head_gs, custom_interpolate
22
+ from torch.utils.checkpoint import checkpoint
23
+
24
+ class GSDPT(DPT):
25
+
26
+ def __init__(
27
+ self,
28
+ dim_in: int,
29
+ patch_size: int = 14,
30
+ output_dim: int = 4,
31
+ activation: str = "linear",
32
+ conf_activation: str = "sigmoid",
33
+ features: int = 256,
34
+ out_channels: Sequence[int] = (256, 512, 1024, 1024),
35
+ pos_embed: bool = True,
36
+ feature_only: bool = False,
37
+ down_ratio: int = 1,
38
+ conf_dim: int = 1,
39
+ norm_type: str = "idt", # use to match legacy GS-DPT head, "idt" / "layer"
40
+ fusion_block_inplace: bool = False,
41
+ ) -> None:
42
+ super().__init__(
43
+ dim_in=dim_in,
44
+ patch_size=patch_size,
45
+ output_dim=output_dim,
46
+ activation=activation,
47
+ conf_activation=conf_activation,
48
+ features=features,
49
+ out_channels=out_channels,
50
+ pos_embed=pos_embed,
51
+ down_ratio=down_ratio,
52
+ head_name="raw_gs",
53
+ use_sky_head=False,
54
+ norm_type=norm_type,
55
+ fusion_block_inplace=fusion_block_inplace,
56
+ )
57
+ self.conf_dim = conf_dim
58
+ if conf_dim and conf_dim > 1:
59
+ assert (
60
+ conf_activation == "linear"
61
+ ), "use linear prediction when using view-dependent opacity"
62
+
63
+ merger_out_dim = features if feature_only else features // 2
64
+ self.images_merger = nn.Sequential(
65
+ nn.Conv2d(3, merger_out_dim // 4, 3, 1, 1), # fewer channels first
66
+ nn.GELU(),
67
+ nn.Conv2d(merger_out_dim // 4, merger_out_dim // 2, 3, 1, 1),
68
+ nn.GELU(),
69
+ nn.Conv2d(merger_out_dim // 2, merger_out_dim, 3, 1, 1),
70
+ nn.GELU(),
71
+ )
72
+
73
+ # -------------------------------------------------------------------------
74
+ # Internal forward (single chunk)
75
+ # -------------------------------------------------------------------------
76
+ def _forward_impl(
77
+ self,
78
+ feats: List[torch.Tensor],
79
+ H: int,
80
+ W: int,
81
+ patch_start_idx: int,
82
+ images: torch.Tensor,
83
+ ) -> TyDict[str, torch.Tensor]:
84
+ B, _, C = feats[0].shape
85
+ ph, pw = H // self.patch_size, W // self.patch_size
86
+ resized_feats = []
87
+ for stage_idx, take_idx in enumerate(self.intermediate_layer_idx):
88
+ x = feats[take_idx][:, patch_start_idx:] # [B*S, N_patch, C]
89
+ x = self.norm(x)
90
+ x = x.permute(0, 2, 1).reshape(B, C, ph, pw) # [B*S, C, ph, pw]
91
+
92
+ #x = self.projects[stage_idx](x)
93
+ x = checkpoint(self.projects[stage_idx], x, use_reentrant=False)
94
+ if self.pos_embed:
95
+ x = self._add_pos_embed(x, W, H)
96
+ #x = self.resize_layers[stage_idx](x) # Align scale
97
+ x = checkpoint(self.resize_layers[stage_idx], x, use_reentrant=False) # align scales
98
+ resized_feats.append(x)
99
+
100
+ # 2) Fusion pyramid (main branch only)
101
+ #fused = self._fuse(resized_feats)
102
+ fused = checkpoint(self._fuse, resized_feats, use_reentrant=False)
103
+ #fused = self.scratch.output_conv1(fused)
104
+ fused = checkpoint(self.scratch.output_conv1, fused, use_reentrant=False)
105
+
106
+ # 3) Upsample to target resolution, optionally add position encoding again
107
+ h_out = int(ph * self.patch_size / self.down_ratio)
108
+ w_out = int(pw * self.patch_size / self.down_ratio)
109
+
110
+ fused = custom_interpolate(fused, (h_out, w_out), mode="bilinear", align_corners=True)
111
+
112
+ # inject the image information here
113
+ fused = fused + self.images_merger(images)
114
+
115
+ if self.pos_embed:
116
+ fused = self._add_pos_embed(fused, W, H)
117
+
118
+ # 4) Shared neck1
119
+ # feat = self.scratch.output_conv1(fused)
120
+ feat = fused
121
+
122
+ # 5) Main head: logits -> activate_head or single channel activation
123
+ #main_logits = self.scratch.output_conv2(feat)
124
+ main_logits = checkpoint(self.scratch.output_conv2, feat, use_reentrant=False)
125
+
126
+ outs: TyDict[str, torch.Tensor] = {}
127
+ if self.has_conf:
128
+ pred, conf = activate_head_gs(
129
+ main_logits,
130
+ activation=self.activation,
131
+ conf_activation=self.conf_activation,
132
+ conf_dim=self.conf_dim,
133
+ )
134
+ outs[self.head_main] = pred.squeeze(1)
135
+ outs[f"{self.head_main}_conf"] = conf.squeeze(1)
136
+ else:
137
+ outs[self.head_main] = self._apply_activation_single(main_logits).squeeze(1)
138
+
139
+ return outs
src/depth_anything_3/model/reference_view_selector.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Reference View Selection Strategies
17
+
18
+ This module provides different strategies for selecting a reference view
19
+ from multiple input views in multi-view depth estimation.
20
+ """
21
+
22
+ import torch
23
+ from typing import Literal
24
+
25
+
26
+ RefViewStrategy = Literal["first", "middle", "saddle_balanced", "saddle_sim_range"]
27
+
28
+
29
+ def select_reference_view(
30
+ x: torch.Tensor,
31
+ strategy: RefViewStrategy = "saddle_balanced",
32
+ ) -> torch.Tensor:
33
+ """
34
+ Select a reference view from multiple views using the specified strategy.
35
+
36
+ Args:
37
+ x: Input tensor of shape (B, S, N, C) where
38
+ B = batch size
39
+ S = number of views
40
+ N = number of tokens
41
+ C = channel dimension
42
+ strategy: Selection strategy, one of:
43
+ - "first": Always select the first view
44
+ - "middle": Select the middle view
45
+ - "saddle_balanced": Select view with balanced features across multiple metrics
46
+ - "saddle_sim_range": Select view with largest similarity range
47
+
48
+ Returns:
49
+ b_idx: Tensor of shape (B,) containing the selected view index for each batch
50
+ """
51
+ B, S, N, C = x.shape
52
+
53
+ # For single view, no reordering needed
54
+ if S <= 1:
55
+ return torch.zeros(B, dtype=torch.long, device=x.device)
56
+
57
+ # Simple position-based strategies
58
+ if strategy == "first":
59
+ return torch.zeros(B, dtype=torch.long, device=x.device)
60
+
61
+ elif strategy == "middle":
62
+ return torch.full((B,), S // 2, dtype=torch.long, device=x.device)
63
+
64
+ # Feature-based strategies require normalized class tokens
65
+ # Extract and normalize class tokens (first token of each view)
66
+ img_class_feat = x[:, :, 0] / x[:, :, 0].norm(dim=-1, keepdim=True) # B S C
67
+
68
+ if strategy == "saddle_balanced":
69
+ # Select view with balanced features across multiple metrics
70
+ # Compute similarity matrix
71
+ sim = torch.matmul(img_class_feat, img_class_feat.transpose(1, 2)) # B S S
72
+ sim_no_diag = sim - torch.eye(S, device=sim.device).unsqueeze(0)
73
+ sim_score = sim_no_diag.sum(dim=-1) / (S - 1) # B S
74
+
75
+ feat_norm = x[:, :, 0].norm(dim=-1) # B S
76
+ feat_var = img_class_feat.var(dim=-1) # B S
77
+
78
+ # Normalize all metrics to [0, 1]
79
+ def normalize_metric(metric):
80
+ min_val = metric.min(dim=1, keepdim=True).values
81
+ max_val = metric.max(dim=1, keepdim=True).values
82
+ return (metric - min_val) / (max_val - min_val + 1e-8)
83
+
84
+ sim_score_norm = normalize_metric(sim_score)
85
+ norm_norm = normalize_metric(feat_norm)
86
+ var_norm = normalize_metric(feat_var)
87
+
88
+ # Select view closest to the median (0.5) across all metrics
89
+ balance_score = (
90
+ (sim_score_norm - 0.5).abs() +
91
+ (norm_norm - 0.5).abs() +
92
+ (var_norm - 0.5).abs()
93
+ )
94
+ b_idx = balance_score.argmin(dim=1)
95
+
96
+ elif strategy == "saddle_sim_range":
97
+ # Select view with largest similarity range (max - min)
98
+ sim = torch.matmul(img_class_feat, img_class_feat.transpose(1, 2)) # B S S
99
+ sim_no_diag = sim - torch.eye(S, device=sim.device).unsqueeze(0)
100
+
101
+ sim_max = sim_no_diag.max(dim=-1).values # B S
102
+ sim_min = sim_no_diag.min(dim=-1).values # B S
103
+ sim_range = sim_max - sim_min
104
+ b_idx = sim_range.argmax(dim=1)
105
+
106
+ else:
107
+ raise ValueError(
108
+ f"Unknown reference view selection strategy: {strategy}. "
109
+ f"Must be one of: 'first', 'middle', 'saddle_balanced', 'saddle_sim_range'"
110
+ )
111
+
112
+ return b_idx
113
+
114
+
115
+ def reorder_by_reference(
116
+ x: torch.Tensor,
117
+ b_idx: torch.Tensor,
118
+ ) -> torch.Tensor:
119
+ """
120
+ Reorder views to place the selected reference view first.
121
+
122
+ Args:
123
+ x: Input tensor of shape (B, S, N, C)
124
+ b_idx: Reference view indices of shape (B,)
125
+
126
+ Returns:
127
+ Reordered tensor with reference view at position 0
128
+
129
+ Example:
130
+ If b_idx = [2] and S = 5 (views [0,1,2,3,4]),
131
+ result order is [2,0,1,3,4] (ref_idx first, then others in order)
132
+ """
133
+ B, S = x.shape[0], x.shape[1]
134
+
135
+ # For single view, no reordering needed
136
+ if S <= 1:
137
+ return x
138
+
139
+ # Create position indices: (B, S) where each row is [0, 1, 2, ..., S-1]
140
+ positions = torch.arange(S, device=x.device).unsqueeze(0).expand(B, -1) # B S
141
+
142
+ # For each position, determine which original index it should take
143
+ # Position 0 gets ref_idx
144
+ # Position 1 to ref_idx gets indices 0 to ref_idx-1
145
+ # Position ref_idx+1 to S-1 gets indices ref_idx+1 to S-1
146
+
147
+ b_idx_expanded = b_idx.unsqueeze(1) # B 1
148
+
149
+ # Create the reordering indices
150
+ # For positions 1 to ref_idx: map to indices 0 to ref_idx-1 (shift by -1)
151
+ # For positions > ref_idx: keep the same
152
+ reorder_indices = positions.clone()
153
+ reorder_indices = torch.where(
154
+ (positions > 0) & (positions <= b_idx_expanded),
155
+ positions - 1,
156
+ positions
157
+ )
158
+ # Set position 0 to ref_idx
159
+ reorder_indices[:, 0] = b_idx
160
+
161
+ # Gather using advanced indexing
162
+ batch_indices = torch.arange(B, device=x.device).unsqueeze(1) # B 1
163
+ x_reordered = x[batch_indices, reorder_indices]
164
+
165
+ return x_reordered
166
+
167
+
168
+ def restore_original_order(
169
+ x: torch.Tensor,
170
+ b_idx: torch.Tensor,
171
+ ) -> torch.Tensor:
172
+ """
173
+ Restore original view order after processing.
174
+
175
+ Args:
176
+ x: Reordered tensor of shape (B, S, ...)
177
+ b_idx: Original reference view indices of shape (B,)
178
+
179
+ Returns:
180
+ Tensor with original view order restored
181
+
182
+ Example:
183
+ If original order was [0, 1, 2, 3, 4] and b_idx=2,
184
+ reordered becomes [2, 0, 1, 3, 4] (reference at position 0),
185
+ restore should return [0, 1, 2, 3, 4] (original order).
186
+ """
187
+ B, S = x.shape[0], x.shape[1]
188
+
189
+ # For single view, no restoration needed
190
+ if S <= 1:
191
+ return x
192
+
193
+ # Create target position indices: (B, S) where each row is [0, 1, 2, ..., S-1]
194
+ target_positions = torch.arange(S, device=x.device).unsqueeze(0).expand(B, -1) # B S
195
+
196
+ # For each target position, determine which current position it comes from
197
+ # Target position 0 to ref_idx-1 <- Current position 1 to ref_idx (shift by +1)
198
+ # Target position ref_idx <- Current position 0
199
+ # Target position ref_idx+1 to S-1 <- Current position ref_idx+1 to S-1 (no change)
200
+
201
+ b_idx_expanded = b_idx.unsqueeze(1) # B 1
202
+
203
+ # Create the restore indices
204
+ restore_indices = torch.where(
205
+ target_positions < b_idx_expanded,
206
+ target_positions + 1, # Positions before ref_idx come from current position + 1
207
+ target_positions # Positions after ref_idx stay the same
208
+ )
209
+ # Target position = ref_idx comes from current position 0
210
+ # Use scatter to set specific positions
211
+ restore_indices = torch.scatter(
212
+ restore_indices,
213
+ dim=1,
214
+ index=b_idx_expanded,
215
+ src=torch.zeros_like(b_idx_expanded)
216
+ )
217
+
218
+ # Gather using advanced indexing
219
+ batch_indices = torch.arange(B, device=x.device).unsqueeze(1) # B 1
220
+ x_restored = x[batch_indices, restore_indices]
221
+
222
+ return x_restored
223
+
src/depth_anything_3/model/utils/attention.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110 # noqa
16
+
17
+ from typing import Callable, Optional, Union
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch import Tensor, nn
21
+
22
+
23
+ class Attention(nn.Module):
24
+ def __init__(
25
+ self,
26
+ dim: int,
27
+ num_heads: int = 8,
28
+ qkv_bias: bool = True,
29
+ proj_bias: bool = True,
30
+ attn_drop: float = 0.0,
31
+ proj_drop: float = 0.0,
32
+ norm_layer: nn.Module = nn.LayerNorm,
33
+ qk_norm: bool = False,
34
+ rope=None,
35
+ ) -> None:
36
+ super().__init__()
37
+ assert dim % num_heads == 0, "dim should be divisible by num_heads"
38
+ self.num_heads = num_heads
39
+ self.head_dim = dim // num_heads
40
+ self.scale = self.head_dim**-0.5
41
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
42
+ self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
43
+ self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
44
+ self.attn_drop = nn.Dropout(attn_drop)
45
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
46
+ self.proj_drop = nn.Dropout(proj_drop)
47
+ self.rope = rope
48
+
49
+ def forward(self, x: Tensor, pos=None, attn_mask=None) -> Tensor:
50
+ # Debug breakpoint removed for production
51
+ B, N, C = x.shape
52
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
53
+ q, k, v = qkv.unbind(0)
54
+ q, k = self.q_norm(q), self.k_norm(k)
55
+ q = self.rope(q, pos) if self.rope is not None else q
56
+ k = self.rope(k, pos) if self.rope is not None else k
57
+ x = F.scaled_dot_product_attention(
58
+ q,
59
+ k,
60
+ v,
61
+ dropout_p=self.attn_drop.p if self.training else 0.0,
62
+ attn_mask=attn_mask,
63
+ )
64
+ x = x.transpose(1, 2).reshape(B, N, C)
65
+ x = self.proj(x)
66
+ x = self.proj_drop(x)
67
+ return x
68
+
69
+
70
+ class LayerScale(nn.Module):
71
+ def __init__(
72
+ self,
73
+ dim: int,
74
+ init_values: Union[float, Tensor] = 1e-5,
75
+ inplace: bool = False,
76
+ ) -> None:
77
+ super().__init__()
78
+ self.inplace = inplace
79
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
80
+
81
+ def forward(self, x: Tensor) -> Tensor:
82
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
83
+
84
+
85
+ class Mlp(nn.Module):
86
+ def __init__(
87
+ self,
88
+ in_features: int,
89
+ hidden_features: Optional[int] = None,
90
+ out_features: Optional[int] = None,
91
+ act_layer: Callable[..., nn.Module] = nn.GELU,
92
+ drop: float = 0.0,
93
+ bias: bool = True,
94
+ ) -> None:
95
+ super().__init__()
96
+ out_features = out_features or in_features
97
+ hidden_features = hidden_features or in_features
98
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
99
+ self.act = act_layer()
100
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
101
+ self.drop = nn.Dropout(drop)
102
+
103
+ def forward(self, x: Tensor) -> Tensor:
104
+ x = self.fc1(x)
105
+ x = self.act(x)
106
+ x = self.drop(x)
107
+ x = self.fc2(x)
108
+ x = self.drop(x)
109
+ return x
src/depth_anything_3/model/utils/block.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import Callable
17
+ from torch import Tensor, nn
18
+
19
+ from .attention import Attention, LayerScale, Mlp
20
+
21
+
22
+ class Block(nn.Module):
23
+ def __init__(
24
+ self,
25
+ dim: int,
26
+ num_heads: int,
27
+ mlp_ratio: float = 4.0,
28
+ qkv_bias: bool = True,
29
+ proj_bias: bool = True,
30
+ ffn_bias: bool = True,
31
+ drop: float = 0.0,
32
+ attn_drop: float = 0.0,
33
+ init_values=None,
34
+ drop_path: float = 0.0,
35
+ act_layer: Callable[..., nn.Module] = nn.GELU,
36
+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
37
+ attn_class: Callable[..., nn.Module] = Attention,
38
+ ffn_layer: Callable[..., nn.Module] = Mlp,
39
+ qk_norm: bool = False,
40
+ rope=None,
41
+ ) -> None:
42
+ super().__init__()
43
+
44
+ self.norm1 = norm_layer(dim)
45
+
46
+ self.attn = attn_class(
47
+ dim,
48
+ num_heads=num_heads,
49
+ qkv_bias=qkv_bias,
50
+ proj_bias=proj_bias,
51
+ attn_drop=attn_drop,
52
+ proj_drop=drop,
53
+ qk_norm=qk_norm,
54
+ rope=rope,
55
+ )
56
+
57
+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
58
+ self.norm2 = norm_layer(dim)
59
+ mlp_hidden_dim = int(dim * mlp_ratio)
60
+ self.mlp = ffn_layer(
61
+ in_features=dim,
62
+ hidden_features=mlp_hidden_dim,
63
+ act_layer=act_layer,
64
+ drop=drop,
65
+ bias=ffn_bias,
66
+ )
67
+ self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
68
+
69
+ self.sample_drop_ratio = 0.0 # Equivalent to always having drop_path=0
70
+
71
+ def forward(self, x: Tensor, pos=None, attn_mask=None) -> Tensor:
72
+ def attn_residual_func(x: Tensor, pos=None, attn_mask=None) -> Tensor:
73
+ return self.ls1(self.attn(self.norm1(x), pos=pos, attn_mask=attn_mask))
74
+
75
+ def ffn_residual_func(x: Tensor) -> Tensor:
76
+ return self.ls2(self.mlp(self.norm2(x)))
77
+
78
+ # drop_path is always 0, so always take the else branch
79
+ x = x + attn_residual_func(x, pos=pos, attn_mask=attn_mask)
80
+ x = x + ffn_residual_func(x)
81
+ return x
src/depth_anything_3/model/utils/gs_renderer.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from math import isqrt
17
+ from typing import Literal, Optional
18
+ import torch
19
+ from einops import rearrange, repeat
20
+ from tqdm import tqdm
21
+
22
+ from depth_anything_3.specs import Gaussians
23
+ from depth_anything_3.utils.camera_trj_helpers import (
24
+ interpolate_extrinsics,
25
+ interpolate_intrinsics,
26
+ render_dolly_zoom_path,
27
+ render_stabilization_path,
28
+ render_wander_path,
29
+ render_wobble_inter_path,
30
+ )
31
+ from depth_anything_3.utils.geometry import affine_inverse, as_homogeneous, get_fov
32
+ from depth_anything_3.utils.logger import logger
33
+
34
+ try:
35
+ from gsplat import rasterization
36
+ except ImportError:
37
+ logger.warn(
38
+ "Dependency `gsplat` is required for rendering 3DGS. "
39
+ "Install via: pip install git+https://github.com/nerfstudio-project/"
40
+ "gsplat.git@0b4dddf04cb687367602c01196913cde6a743d70"
41
+ )
42
+
43
+
44
+ def render_3dgs(
45
+ extrinsics: torch.Tensor, # "batch_views 4 4", w2c
46
+ intrinsics: torch.Tensor, # "batch_views 3 3", normalized
47
+ image_shape: tuple[int, int],
48
+ gaussian: Gaussians,
49
+ background_color: Optional[torch.Tensor] = None, # "batch_views 3"
50
+ use_sh: bool = True,
51
+ num_view: int = 1,
52
+ color_mode: Literal["RGB+D", "RGB+ED"] = "RGB+D",
53
+ **kwargs,
54
+ ) -> tuple[
55
+ torch.Tensor, # "batch_views 3 height width"
56
+ torch.Tensor, # "batch_views height width"
57
+ ]:
58
+ # extract gaussian params
59
+ gaussian_means = gaussian.means
60
+ gaussian_scales = gaussian.scales
61
+ gaussian_quats = gaussian.rotations
62
+ gaussian_opacities = gaussian.opacities
63
+ gaussian_sh_coefficients = gaussian.harmonics
64
+ b, _, _ = extrinsics.shape
65
+
66
+ if background_color is None:
67
+ background_color = repeat(torch.tensor([0.0, 0.0, 0.0]), "c -> b c", b=b).to(
68
+ gaussian_sh_coefficients
69
+ )
70
+
71
+ if use_sh:
72
+ _, _, _, n = gaussian_sh_coefficients.shape
73
+ degree = isqrt(n) - 1
74
+ shs = rearrange(gaussian_sh_coefficients, "b g xyz n -> b g n xyz").contiguous()
75
+ else: # use color
76
+ shs = (
77
+ gaussian_sh_coefficients.squeeze(-1).sigmoid().contiguous()
78
+ ) # (b, g, c), normed to (0, 1)
79
+
80
+ h, w = image_shape
81
+
82
+ fov_x, fov_y = get_fov(intrinsics).unbind(dim=-1)
83
+ tan_fov_x = (0.5 * fov_x).tan()
84
+ tan_fov_y = (0.5 * fov_y).tan()
85
+ focal_length_x = w / (2 * tan_fov_x)
86
+ focal_length_y = h / (2 * tan_fov_y)
87
+
88
+ view_matrix = extrinsics.float()
89
+
90
+ all_images = []
91
+ all_radii = []
92
+ all_depths = []
93
+ # render view in a batch based, each batch contains one scene
94
+ # assume the Gaussian parameters are originally repeated along the view dim
95
+ batch_scene = b // num_view
96
+
97
+ def index_i_gs_attr(full_attr, idx):
98
+ # return rearrange(full_attr, "(b v) ... -> b v ...", v=num_view)[idx, 0]
99
+ return full_attr[idx]
100
+
101
+ for i in range(batch_scene):
102
+ K = repeat(
103
+ torch.tensor(
104
+ [
105
+ [0, 0, w / 2.0],
106
+ [0, 0, h / 2.0],
107
+ [0, 0, 1],
108
+ ]
109
+ ),
110
+ "i j -> v i j",
111
+ v=num_view,
112
+ ).to(gaussian_means)
113
+ K[:, 0, 0] = focal_length_x.reshape(batch_scene, num_view)[i]
114
+ K[:, 1, 1] = focal_length_y.reshape(batch_scene, num_view)[i]
115
+
116
+ i_means = index_i_gs_attr(gaussian_means, i) # [N, 3]
117
+ i_scales = index_i_gs_attr(gaussian_scales, i)
118
+ i_quats = index_i_gs_attr(gaussian_quats, i)
119
+ i_opacities = index_i_gs_attr(gaussian_opacities, i) # [N,]
120
+ i_colors = index_i_gs_attr(shs, i) # [N, K, 3]
121
+ i_viewmats = rearrange(view_matrix, "(b v) ... -> b v ...", v=num_view)[i] # [v, 4, 4]
122
+ i_backgrounds = rearrange(background_color, "(b v) ... -> b v ...", v=num_view)[
123
+ i
124
+ ] # [v, 3]
125
+
126
+ render_colors, render_alphas, info = rasterization(
127
+ means=i_means,
128
+ quats=i_quats, # [N, 4]
129
+ scales=i_scales, # [N, 3]
130
+ opacities=i_opacities,
131
+ colors=i_colors,
132
+ viewmats=i_viewmats, # [v, 4, 4]
133
+ Ks=K, # [v, 3, 3]
134
+ backgrounds=i_backgrounds,
135
+ render_mode=color_mode,
136
+ width=w,
137
+ height=h,
138
+ packed=False,
139
+ sh_degree=degree if use_sh else None,
140
+ )
141
+ depth = render_colors[..., -1].unbind(dim=0)
142
+
143
+ image = rearrange(render_colors[..., :3], "v h w c -> v c h w").unbind(dim=0)
144
+ radii = info["radii"].unbind(dim=0)
145
+ try:
146
+ info["means2d"].retain_grad() # [1, N, 2]
147
+ except Exception:
148
+ pass
149
+ all_images.extend(image)
150
+ all_depths.extend(depth)
151
+ all_radii.extend(radii)
152
+
153
+ return torch.stack(all_images), torch.stack(all_depths)
154
+
155
+
156
+ def run_renderer_in_chunk_w_trj_mode(
157
+ gaussians: Gaussians,
158
+ extrinsics: torch.Tensor, # world2cam, "batch view 4 4" | "batch view 3 4"
159
+ intrinsics: torch.Tensor, # unnormed intrinsics, "batch view 3 3"
160
+ image_shape: tuple[int, int],
161
+ chunk_size: Optional[int] = 8,
162
+ trj_mode: Literal[
163
+ "original",
164
+ "smooth",
165
+ "interpolate",
166
+ "interpolate_smooth",
167
+ "wander",
168
+ "dolly_zoom",
169
+ "extend",
170
+ "wobble_inter",
171
+ ] = "smooth",
172
+ input_shape: Optional[tuple[int, int]] = None,
173
+ enable_tqdm: Optional[bool] = False,
174
+ **kwargs,
175
+ ) -> tuple[
176
+ torch.Tensor, # color, "batch view 3 height width"
177
+ torch.Tensor, # depth, "batch view height width"
178
+ ]:
179
+ cam2world = affine_inverse(as_homogeneous(extrinsics))
180
+ if input_shape is not None:
181
+ in_h, in_w = input_shape
182
+ else:
183
+ in_h, in_w = image_shape
184
+ intr_normed = intrinsics.clone().detach()
185
+ intr_normed[..., 0, :] /= in_w
186
+ intr_normed[..., 1, :] /= in_h
187
+ if extrinsics.shape[1] <= 1:
188
+ assert trj_mode in [
189
+ "wander",
190
+ "dolly_zoom",
191
+ ], "Please set trj_mode to 'wander' or 'dolly_zoom' when n_views=1"
192
+
193
+ def _smooth_trj_fn_batch(raw_c2ws, k_size=50):
194
+ try:
195
+ smooth_c2ws = torch.stack(
196
+ [render_stabilization_path(c2w_i, k_size) for c2w_i in raw_c2ws],
197
+ dim=0,
198
+ )
199
+ except Exception as e:
200
+ print(f"[DEBUG] Path smoothing failed with error: {e}.")
201
+ smooth_c2ws = raw_c2ws
202
+ return smooth_c2ws
203
+
204
+ # get rendered trj
205
+ if trj_mode == "original":
206
+ tgt_c2w = cam2world
207
+ tgt_intr = intr_normed
208
+ elif trj_mode == "smooth":
209
+ tgt_c2w = _smooth_trj_fn_batch(cam2world)
210
+ tgt_intr = intr_normed
211
+ elif trj_mode in ["interpolate", "interpolate_smooth", "extend"]:
212
+ inter_len = 8
213
+ total_len = (cam2world.shape[1] - 1) * inter_len
214
+ if total_len > 24 * 18: # no more than 18s
215
+ inter_len = max(1, 24 * 10 // (cam2world.shape[1] - 1))
216
+ if total_len < 24 * 2: # no less than 2s
217
+ inter_len = max(1, 24 * 2 // (cam2world.shape[1] - 1))
218
+
219
+ if inter_len > 2:
220
+ t = torch.linspace(0, 1, inter_len, dtype=torch.float32, device=cam2world.device)
221
+ t = (torch.cos(torch.pi * (t + 1)) + 1) / 2
222
+ tgt_c2w_b = []
223
+ tgt_intr_b = []
224
+ for b_idx in range(cam2world.shape[0]):
225
+ tgt_c2w = []
226
+ tgt_intr = []
227
+ for cur_idx in range(cam2world.shape[1] - 1):
228
+ tgt_c2w.append(
229
+ interpolate_extrinsics(
230
+ cam2world[b_idx, cur_idx], cam2world[b_idx, cur_idx + 1], t
231
+ )[(0 if cur_idx == 0 else 1) :]
232
+ )
233
+ tgt_intr.append(
234
+ interpolate_intrinsics(
235
+ intr_normed[b_idx, cur_idx], intr_normed[b_idx, cur_idx + 1], t
236
+ )[(0 if cur_idx == 0 else 1) :]
237
+ )
238
+ tgt_c2w_b.append(torch.cat(tgt_c2w))
239
+ tgt_intr_b.append(torch.cat(tgt_intr))
240
+ tgt_c2w = torch.stack(tgt_c2w_b) # b v 4 4
241
+ tgt_intr = torch.stack(tgt_intr_b) # b v 3 3
242
+ else:
243
+ tgt_c2w = cam2world
244
+ tgt_intr = intr_normed
245
+ if trj_mode in ["interpolate_smooth", "extend"]:
246
+ tgt_c2w = _smooth_trj_fn_batch(tgt_c2w)
247
+ if trj_mode == "extend":
248
+ # apply dolly_zoom and wander in the middle frame
249
+ assert cam2world.shape[0] == 1, "extend only supports for batch_size=1 currently."
250
+ mid_idx = tgt_c2w.shape[1] // 2
251
+ c2w_wd, intr_wd = render_wander_path(
252
+ tgt_c2w[0, mid_idx],
253
+ tgt_intr[0, mid_idx],
254
+ h=in_h,
255
+ w=in_w,
256
+ num_frames=max(36, min(60, mid_idx // 2)),
257
+ max_disp=24.0,
258
+ )
259
+ c2w_dz, intr_dz = render_dolly_zoom_path(
260
+ tgt_c2w[0, mid_idx],
261
+ tgt_intr[0, mid_idx],
262
+ h=in_h,
263
+ w=in_w,
264
+ num_frames=max(36, min(60, mid_idx // 2)),
265
+ )
266
+ tgt_c2w = torch.cat(
267
+ [
268
+ tgt_c2w[:, :mid_idx],
269
+ c2w_wd.unsqueeze(0),
270
+ c2w_dz.unsqueeze(0),
271
+ tgt_c2w[:, mid_idx:],
272
+ ],
273
+ dim=1,
274
+ )
275
+ tgt_intr = torch.cat(
276
+ [
277
+ tgt_intr[:, :mid_idx],
278
+ intr_wd.unsqueeze(0),
279
+ intr_dz.unsqueeze(0),
280
+ tgt_intr[:, mid_idx:],
281
+ ],
282
+ dim=1,
283
+ )
284
+ elif trj_mode in ["wander", "dolly_zoom"]:
285
+ if trj_mode == "wander":
286
+ render_fn = render_wander_path
287
+ extra_kwargs = {"max_disp": 24.0}
288
+ else:
289
+ render_fn = render_dolly_zoom_path
290
+ extra_kwargs = {"D_focus": 30.0, "max_disp": 2.0}
291
+ tgt_c2w = []
292
+ tgt_intr = []
293
+ for b_idx in range(cam2world.shape[0]):
294
+ c2w_i, intr_i = render_fn(
295
+ cam2world[b_idx, 0], intr_normed[b_idx, 0], h=in_h, w=in_w, **extra_kwargs
296
+ )
297
+ tgt_c2w.append(c2w_i)
298
+ tgt_intr.append(intr_i)
299
+ tgt_c2w = torch.stack(tgt_c2w)
300
+ tgt_intr = torch.stack(tgt_intr)
301
+ elif trj_mode == "wobble_inter":
302
+ tgt_c2w, tgt_intr = render_wobble_inter_path(
303
+ cam2world=cam2world,
304
+ intr_normed=intr_normed,
305
+ inter_len=10,
306
+ n_skip=3,
307
+ )
308
+ else:
309
+ raise Exception(f"trj mode [{trj_mode}] is not implemented.")
310
+
311
+ _, v = tgt_c2w.shape[:2]
312
+ tgt_extr = affine_inverse(tgt_c2w)
313
+ if chunk_size is None:
314
+ chunk_size = v
315
+ chunk_size = min(v, chunk_size)
316
+ all_colors = []
317
+ all_depths = []
318
+ for chunk_idx in tqdm(
319
+ range(math.ceil(v / chunk_size)),
320
+ desc="Rendering novel views",
321
+ disable=(not enable_tqdm),
322
+ leave=False,
323
+ ):
324
+ s = int(chunk_idx * chunk_size)
325
+ e = int((chunk_idx + 1) * chunk_size)
326
+ cur_n_view = tgt_extr[:, s:e].shape[1]
327
+ color, depth = render_3dgs(
328
+ extrinsics=rearrange(tgt_extr[:, s:e], "b v ... -> (b v) ..."), # w2c
329
+ intrinsics=rearrange(tgt_intr[:, s:e], "b v ... -> (b v) ..."), # normed
330
+ image_shape=image_shape,
331
+ gaussian=gaussians,
332
+ num_view=cur_n_view,
333
+ **kwargs,
334
+ )
335
+ all_colors.append(rearrange(color, "(b v) ... -> b v ...", v=cur_n_view))
336
+ all_depths.append(rearrange(depth, "(b v) ... -> b v ...", v=cur_n_view))
337
+ all_colors = torch.cat(all_colors, dim=1)
338
+ all_depths = torch.cat(all_depths, dim=1)
339
+
340
+ return all_colors, all_depths
src/depth_anything_3/model/utils/head_utils.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Tuple, Union
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+
20
+ # -----------------------------------------------------------------------------
21
+ # Activation functions
22
+ # -----------------------------------------------------------------------------
23
+
24
+
25
+ def activate_head_gs(out, activation="norm_exp", conf_activation="expp1", conf_dim=None):
26
+ """
27
+ Process network output to extract GS params and density values.
28
+ Density could be view-dependent as SH coefficient
29
+
30
+
31
+ Args:
32
+ out: Network output tensor (B, C, H, W)
33
+ activation: Activation type for 3D points
34
+ conf_activation: Activation type for confidence values
35
+
36
+ Returns:
37
+ Tuple of (3D points tensor, confidence tensor)
38
+ """
39
+ # Move channels from last dim to the 4th dimension => (B, H, W, C)
40
+ fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected
41
+
42
+ # Split into xyz (first C-1 channels) and confidence (last channel)
43
+ conf_dim = 1 if conf_dim is None else conf_dim
44
+ xyz = fmap[:, :, :, :-conf_dim]
45
+ conf = fmap[:, :, :, -1] if conf_dim == 1 else fmap[:, :, :, -conf_dim:]
46
+
47
+ if activation == "norm_exp":
48
+ d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8)
49
+ xyz_normed = xyz / d
50
+ pts3d = xyz_normed * torch.expm1(d)
51
+ elif activation == "norm":
52
+ pts3d = xyz / xyz.norm(dim=-1, keepdim=True)
53
+ elif activation == "exp":
54
+ pts3d = torch.exp(xyz)
55
+ elif activation == "relu":
56
+ pts3d = F.relu(xyz)
57
+ elif activation == "sigmoid":
58
+ pts3d = torch.sigmoid(xyz)
59
+ elif activation == "linear":
60
+ pts3d = xyz
61
+ else:
62
+ raise ValueError(f"Unknown activation: {activation}")
63
+
64
+ if conf_activation == "expp1":
65
+ conf_out = 1 + conf.exp()
66
+ elif conf_activation == "expp0":
67
+ conf_out = conf.exp()
68
+ elif conf_activation == "sigmoid":
69
+ conf_out = torch.sigmoid(conf)
70
+ elif conf_activation == "linear":
71
+ conf_out = conf
72
+ else:
73
+ raise ValueError(f"Unknown conf_activation: {conf_activation}")
74
+
75
+ return pts3d, conf_out
76
+
77
+
78
+ # -----------------------------------------------------------------------------
79
+ # Other utilities
80
+ # -----------------------------------------------------------------------------
81
+
82
+
83
+ class Permute(nn.Module):
84
+ """nn.Module wrapper around Tensor.permute for cleaner nn.Sequential usage."""
85
+
86
+ dims: Tuple[int, ...]
87
+
88
+ def __init__(self, dims: Tuple[int, ...]) -> None:
89
+ super().__init__()
90
+ self.dims = dims
91
+
92
+ def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore[override]
93
+ return x.permute(*self.dims)
94
+
95
+
96
+ def position_grid_to_embed(
97
+ pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100
98
+ ) -> torch.Tensor:
99
+ """
100
+ Convert 2D position grid (HxWx2) to sinusoidal embeddings (HxWxC)
101
+
102
+ Args:
103
+ pos_grid: Tensor of shape (H, W, 2) containing 2D coordinates
104
+ embed_dim: Output channel dimension for embeddings
105
+
106
+ Returns:
107
+ Tensor of shape (H, W, embed_dim) with positional embeddings
108
+ """
109
+ H, W, grid_dim = pos_grid.shape
110
+ assert grid_dim == 2
111
+ pos_flat = pos_grid.reshape(-1, grid_dim) # Flatten to (H*W, 2)
112
+
113
+ # Process x and y coordinates separately
114
+ emb_x = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0) # [1, H*W, D/2]
115
+ emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0) # [1, H*W, D/2]
116
+
117
+ # Combine and reshape
118
+ emb = torch.cat([emb_x, emb_y], dim=-1) # [1, H*W, D]
119
+
120
+ return emb.view(H, W, embed_dim) # [H, W, D]
121
+
122
+
123
+ def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor:
124
+ """
125
+ This function generates a 1D positional embedding from a given grid using sine and cosine functions. # noqa
126
+
127
+ Args:
128
+ - embed_dim: The embedding dimension.
129
+ - pos: The position to generate the embedding from.
130
+
131
+ Returns:
132
+ - emb: The generated 1D positional embedding.
133
+ """
134
+ assert embed_dim % 2 == 0
135
+ omega = torch.arange(embed_dim // 2, dtype=torch.float32, device=pos.device)
136
+ omega /= embed_dim / 2.0
137
+ omega = 1.0 / omega_0**omega # (D/2,)
138
+
139
+ pos = pos.reshape(-1) # (M,)
140
+ out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product
141
+
142
+ emb_sin = torch.sin(out) # (M, D/2)
143
+ emb_cos = torch.cos(out) # (M, D/2)
144
+
145
+ emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D)
146
+ return emb.float()
147
+
148
+
149
+ # Inspired by https://github.com/microsoft/moge
150
+
151
+
152
+ def create_uv_grid(
153
+ width: int,
154
+ height: int,
155
+ aspect_ratio: float = None,
156
+ dtype: torch.dtype = None,
157
+ device: torch.device = None,
158
+ ) -> torch.Tensor:
159
+ """
160
+ Create a normalized UV grid of shape (width, height, 2).
161
+
162
+ The grid spans horizontally and vertically according to an aspect ratio,
163
+ ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right
164
+ corner is at (x_span, y_span), normalized by the diagonal of the plane.
165
+
166
+ Args:
167
+ width (int): Number of points horizontally.
168
+ height (int): Number of points vertically.
169
+ aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height.
170
+ dtype (torch.dtype, optional): Data type of the resulting tensor.
171
+ device (torch.device, optional): Device on which the tensor is created.
172
+
173
+ Returns:
174
+ torch.Tensor: A (width, height, 2) tensor of UV coordinates.
175
+ """
176
+ # Derive aspect ratio if not explicitly provided
177
+ if aspect_ratio is None:
178
+ aspect_ratio = float(width) / float(height)
179
+
180
+ # Compute normalized spans for X and Y
181
+ diag_factor = (aspect_ratio**2 + 1.0) ** 0.5
182
+ span_x = aspect_ratio / diag_factor
183
+ span_y = 1.0 / diag_factor
184
+
185
+ # Establish the linspace boundaries
186
+ left_x = -span_x * (width - 1) / width
187
+ right_x = span_x * (width - 1) / width
188
+ top_y = -span_y * (height - 1) / height
189
+ bottom_y = span_y * (height - 1) / height
190
+
191
+ # Generate 1D coordinates
192
+ x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device)
193
+ y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device)
194
+
195
+ # Create 2D meshgrid (width x height) and stack into UV
196
+ uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy")
197
+ uv_grid = torch.stack((uu, vv), dim=-1)
198
+
199
+ return uv_grid
200
+
201
+
202
+ # -----------------------------------------------------------------------------
203
+ # Interpolation (safe interpolation, avoid INT_MAX overflow)
204
+ # -----------------------------------------------------------------------------
205
+ def custom_interpolate(
206
+ x: torch.Tensor,
207
+ size: Union[Tuple[int, int], None] = None,
208
+ scale_factor: Union[float, None] = None,
209
+ mode: str = "bilinear",
210
+ align_corners: bool = True,
211
+ ) -> torch.Tensor:
212
+ """
213
+ Safe interpolation implementation to avoid INT_MAX overflow in torch.nn.functional.interpolate.
214
+ """
215
+ if size is None:
216
+ assert scale_factor is not None, "Either size or scale_factor must be provided."
217
+ size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor))
218
+
219
+ INT_MAX = 1610612736
220
+ total = size[0] * size[1] * x.shape[0] * x.shape[1]
221
+
222
+ if total > INT_MAX:
223
+ chunks = torch.chunk(x, chunks=(total // INT_MAX) + 1, dim=0)
224
+ outs = [
225
+ nn.functional.interpolate(c, size=size, mode=mode, align_corners=align_corners)
226
+ for c in chunks
227
+ ]
228
+ return torch.cat(outs, dim=0).contiguous()
229
+
230
+ return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners)
src/depth_anything_3/model/utils/transform.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ import torch.nn.functional as F
17
+
18
+
19
+ def extri_intri_to_pose_encoding(
20
+ extrinsics,
21
+ intrinsics,
22
+ image_size_hw=None,
23
+ ):
24
+ """Convert camera extrinsics and intrinsics to a compact pose encoding."""
25
+
26
+ # extrinsics: BxSx3x4
27
+ # intrinsics: BxSx3x3
28
+ R = extrinsics[:, :, :3, :3] # BxSx3x3
29
+ T = extrinsics[:, :, :3, 3] # BxSx3
30
+
31
+ quat = mat_to_quat(R)
32
+ # Note the order of h and w here
33
+ H, W = image_size_hw
34
+ fov_h = 2 * torch.atan((H / 2) / intrinsics[..., 1, 1])
35
+ fov_w = 2 * torch.atan((W / 2) / intrinsics[..., 0, 0])
36
+ pose_encoding = torch.cat([T, quat, fov_h[..., None], fov_w[..., None]], dim=-1).float()
37
+
38
+ return pose_encoding
39
+
40
+
41
+ def pose_encoding_to_extri_intri(
42
+ pose_encoding,
43
+ image_size_hw=None,
44
+ ):
45
+ """Convert a pose encoding back to camera extrinsics and intrinsics."""
46
+
47
+ T = pose_encoding[..., :3]
48
+ quat = pose_encoding[..., 3:7]
49
+ fov_h = pose_encoding[..., 7]
50
+ fov_w = pose_encoding[..., 8]
51
+
52
+ R = quat_to_mat(quat)
53
+ extrinsics = torch.cat([R, T[..., None]], dim=-1)
54
+
55
+ H, W = image_size_hw
56
+ fy = (H / 2.0) / torch.clamp(torch.tan(fov_h / 2.0), 1e-6)
57
+ fx = (W / 2.0) / torch.clamp(torch.tan(fov_w / 2.0), 1e-6)
58
+ intrinsics = torch.zeros(pose_encoding.shape[:2] + (3, 3), device=pose_encoding.device)
59
+ intrinsics[..., 0, 0] = fx
60
+ intrinsics[..., 1, 1] = fy
61
+ intrinsics[..., 0, 2] = W / 2
62
+ intrinsics[..., 1, 2] = H / 2
63
+ intrinsics[..., 2, 2] = 1.0 # Set the homogeneous coordinate to 1
64
+
65
+ return extrinsics, intrinsics
66
+
67
+
68
+ def quat_to_mat(quaternions: torch.Tensor) -> torch.Tensor:
69
+ """
70
+ Quaternion Order: XYZW or say ijkr, scalar-last
71
+
72
+ Convert rotations given as quaternions to rotation matrices.
73
+ Args:
74
+ quaternions: quaternions with real part last,
75
+ as tensor of shape (..., 4).
76
+
77
+ Returns:
78
+ Rotation matrices as tensor of shape (..., 3, 3).
79
+ """
80
+ i, j, k, r = torch.unbind(quaternions, -1)
81
+ two_s = 2.0 / (quaternions * quaternions).sum(-1)
82
+
83
+ o = torch.stack(
84
+ (
85
+ 1 - two_s * (j * j + k * k),
86
+ two_s * (i * j - k * r),
87
+ two_s * (i * k + j * r),
88
+ two_s * (i * j + k * r),
89
+ 1 - two_s * (i * i + k * k),
90
+ two_s * (j * k - i * r),
91
+ two_s * (i * k - j * r),
92
+ two_s * (j * k + i * r),
93
+ 1 - two_s * (i * i + j * j),
94
+ ),
95
+ -1,
96
+ )
97
+ return o.reshape(quaternions.shape[:-1] + (3, 3))
98
+
99
+
100
+ def mat_to_quat(matrix: torch.Tensor) -> torch.Tensor:
101
+ """
102
+ Convert rotations given as rotation matrices to quaternions.
103
+
104
+ Args:
105
+ matrix: Rotation matrices as tensor of shape (..., 3, 3).
106
+
107
+ Returns:
108
+ quaternions with real part last, as tensor of shape (..., 4).
109
+ Quaternion Order: XYZW or say ijkr, scalar-last
110
+ """
111
+ if matrix.size(-1) != 3 or matrix.size(-2) != 3:
112
+ raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.")
113
+
114
+ batch_dim = matrix.shape[:-2]
115
+ m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(
116
+ matrix.reshape(batch_dim + (9,)), dim=-1
117
+ )
118
+
119
+ q_abs = _sqrt_positive_part(
120
+ torch.stack(
121
+ [
122
+ 1.0 + m00 + m11 + m22,
123
+ 1.0 + m00 - m11 - m22,
124
+ 1.0 - m00 + m11 - m22,
125
+ 1.0 - m00 - m11 + m22,
126
+ ],
127
+ dim=-1,
128
+ )
129
+ )
130
+
131
+ quat_by_rijk = torch.stack(
132
+ [
133
+ torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1),
134
+ torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1),
135
+ torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1),
136
+ torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1),
137
+ ],
138
+ dim=-2,
139
+ )
140
+
141
+ flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device)
142
+ quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr))
143
+
144
+ out = quat_candidates[F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :].reshape(
145
+ batch_dim + (4,)
146
+ )
147
+
148
+ out = out[..., [1, 2, 3, 0]]
149
+
150
+ out = standardize_quaternion(out)
151
+
152
+ return out
153
+
154
+
155
+ def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor:
156
+ """
157
+ Returns torch.sqrt(torch.max(0, x))
158
+ but with a zero subgradient where x is 0.
159
+ """
160
+ ret = torch.zeros_like(x)
161
+ positive_mask = x > 0
162
+ if torch.is_grad_enabled():
163
+ ret[positive_mask] = torch.sqrt(x[positive_mask])
164
+ else:
165
+ ret = torch.where(positive_mask, torch.sqrt(x), ret)
166
+ return ret
167
+
168
+
169
+ def standardize_quaternion(quaternions: torch.Tensor) -> torch.Tensor:
170
+ """
171
+ Convert a unit quaternion to a standard form: one in which the real
172
+ part is non negative.
173
+
174
+ Args:
175
+ quaternions: Quaternions with real part last,
176
+ as tensor of shape (..., 4).
177
+
178
+ Returns:
179
+ Standardized quaternions as tensor of shape (..., 4).
180
+ """
181
+ return torch.where(quaternions[..., 3:4] < 0, -quaternions, quaternions)
182
+
183
+
184
+ def cam_quat_xyzw_to_world_quat_wxyz(cam_quat_xyzw, c2w):
185
+ # cam_quat_xyzw: (b, n, 4) in xyzw
186
+ # c2w: (b, n, 4, 4)
187
+ b, n = cam_quat_xyzw.shape[:2]
188
+ # 1. xyzw -> wxyz
189
+ cam_quat_wxyz = torch.cat(
190
+ [
191
+ cam_quat_xyzw[..., 3:4], # w
192
+ cam_quat_xyzw[..., 0:1], # x
193
+ cam_quat_xyzw[..., 1:2], # y
194
+ cam_quat_xyzw[..., 2:3], # z
195
+ ],
196
+ dim=-1,
197
+ )
198
+ # 2. Quaternion to matrix
199
+ cam_quat_wxyz_flat = cam_quat_wxyz.reshape(-1, 4)
200
+ rotmat_cam = quat_to_mat(cam_quat_wxyz_flat).reshape(b, n, 3, 3)
201
+ # 3. Transform to world space
202
+ rotmat_c2w = c2w[..., :3, :3]
203
+ rotmat_world = torch.matmul(rotmat_c2w, rotmat_cam)
204
+ # 4. Matrix to quaternion (wxyz)
205
+ rotmat_world_flat = rotmat_world.reshape(-1, 3, 3)
206
+ world_quat_wxyz_flat = mat_to_quat(rotmat_world_flat)
207
+ world_quat_wxyz = world_quat_wxyz_flat.reshape(b, n, 4)
208
+ return world_quat_wxyz
src/depth_anything_3/registry.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from collections import OrderedDict
16
+ from pathlib import Path
17
+
18
+
19
+ def get_all_models() -> OrderedDict:
20
+ """
21
+ Scans all YAML files in the configs directory and returns a sorted dictionary where:
22
+ - Keys are model names (YAML filenames without the .yaml extension)
23
+ - Values are absolute paths to the corresponding YAML files
24
+ """
25
+ # Get path to the configs directory within the da3 package
26
+ # Works both in development and after pip installation
27
+ # configs_dir = files("depth_anything_3").joinpath("configs")
28
+ configs_dir = Path(__file__).resolve().parent / "configs"
29
+
30
+ # Ensure path is a Path object for consistent cross-platform handling
31
+ configs_dir = Path(configs_dir)
32
+
33
+ model_entries = []
34
+ # Iterate through all items in the configs directory
35
+ for item in configs_dir.iterdir():
36
+ # Filter for YAML files (excluding directories)
37
+ if item.is_file() and item.suffix == ".yaml":
38
+ # Extract model name (filename without .yaml extension)
39
+ model_name = item.stem
40
+ # Get absolute path (resolve() handles symlinks)
41
+ file_abs_path = str(item.resolve())
42
+ model_entries.append((model_name, file_abs_path))
43
+
44
+ # Sort entries by model name and convert to OrderedDict
45
+ sorted_entries = sorted(model_entries, key=lambda x: x[0])
46
+ return OrderedDict(sorted_entries)
47
+
48
+
49
+ # Global registry for external imports
50
+ MODEL_REGISTRY = get_all_models()