junaid-simamdigital commited on
Commit
5b86c13
·
verified ·
1 Parent(s): eb8b43e

Initial What’s Behind the Image prototype

Browse files
README.md CHANGED
@@ -1,13 +1,32 @@
1
  ---
2
- title: SimamBehindImage
3
- emoji: ⚡
4
- colorFrom: purple
5
  colorTo: blue
6
  sdk: gradio
7
- sdk_version: 6.28.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: What’s Behind the Image?
3
+ emoji: 🕳️
4
+ colorFrom: indigo
5
  colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 5.0.0
 
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
+ suggested_hardware: cpu-basic
12
  ---
13
 
14
+ # What’s Behind the Image?
15
+
16
+ A hypothesis-led spatial reveal experiment from Simam AI Lab. Upload an image,
17
+ write what you think is behind it, and inspect depth, lighting and uncertainty
18
+ before viewing a shareable reveal card.
19
+
20
+ This is not an oracle: unseen content is labelled as a hypothesis, not ground
21
+ truth. The app inherits the evidence-first export path from Simam RealityGap 3D
22
+ and includes an explicit no-model smoke mode for deployment testing.
23
+
24
+ ## Run locally
25
+
26
+ ```bash
27
+ pip install -r requirements.txt
28
+ python app.py
29
+ ```
30
+
31
+ Use `examples/sample_scene.png` to test the complete pipeline without uploading
32
+ personal media.
__pycache__/app.cpython-313.pyc ADDED
Binary file (63.6 kB). View file
 
__pycache__/simam3d_core.cpython-313.pyc ADDED
Binary file (53.1 kB). View file
 
app.py ADDED
@@ -0,0 +1,949 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import json
5
+ import hashlib
6
+ import io
7
+ import platform
8
+ import sys
9
+ import threading
10
+ import time
11
+ import traceback
12
+ import uuid
13
+ from pathlib import Path
14
+
15
+ for _stream in (sys.stdout, sys.stderr):
16
+ if hasattr(_stream, "reconfigure"):
17
+ _stream.reconfigure(encoding="utf-8", errors="replace")
18
+
19
+ import gradio as gr
20
+ from matplotlib import colormaps
21
+ import numpy as np
22
+ import trimesh
23
+ from PIL import Image, ImageDraw, ImageOps
24
+
25
+ try:
26
+ import torch
27
+ TORCH_AVAILABLE = True
28
+ except ImportError:
29
+ from contextlib import nullcontext
30
+ class _CudaStub:
31
+ @staticmethod
32
+ def is_available(): return False
33
+ @staticmethod
34
+ def empty_cache(): return None
35
+ class _TorchStub:
36
+ __version__ = "unavailable (CPU-safe export mode)"
37
+ cuda = _CudaStub()
38
+ @staticmethod
39
+ def inference_mode(): return nullcontext()
40
+ torch = _TorchStub()
41
+ TORCH_AVAILABLE = False
42
+
43
+ try:
44
+ from transformers import pipeline
45
+ except ImportError:
46
+ pipeline = None
47
+
48
+ GPU_DURATION_SECONDS = int(os.getenv("SIMAM3D_GPU_DURATION_SECONDS", "60"))
49
+ try:
50
+ import spaces
51
+ GPU_FUNCTION = spaces.GPU(duration=GPU_DURATION_SECONDS)
52
+ except (ImportError, AttributeError, TypeError):
53
+ def GPU_FUNCTION(function):
54
+ return function
55
+ from simam3d_core import (
56
+ analyze_light_field,
57
+ classify_scene_hypothesis,
58
+ deterministic_demo_depth,
59
+ classify_fusion_support,
60
+ estimate_depth_light,
61
+ filter_fusion_by_support,
62
+ fuse_point_views,
63
+ fusion_metrics,
64
+ input_diversity_metrics,
65
+ next_view_plan,
66
+ normalize_prediction_contract,
67
+ orbit_project_points,
68
+ project_world_points,
69
+ reprojection_consistency,
70
+ reveal_uncertainty,
71
+ synthetic_orbit_poses,
72
+ write_confidence_ply,
73
+ write_gaussian_ply,
74
+ )
75
+ from da3_compat import resolve_da3_class
76
+ from validate_manifest import validate_manifest
77
+
78
+
79
+ MODEL_ID = os.getenv("SIMAM3D_DEPTH_MODEL", "depth-anything/Depth-Anything-V2-Small-hf")
80
+ DA3_MODEL_ID = os.getenv("SIMAM3D_DA3_MODEL", "depth-anything/DA3NESTED-GIANT-LARGE-1.1")
81
+ SIMAM3D_VERSION = "0.1.0"
82
+ MANIFEST_SCHEMA_VERSION = 3
83
+ OUTPUT_DIR = Path("output")
84
+ MAX_VIEWS = int(os.getenv("SIMAM3D_MAX_VIEWS", "8"))
85
+ MAX_INPUT_SIDE = int(os.getenv("SIMAM3D_MAX_INPUT_SIDE", "1536"))
86
+ FUSION_VOXEL_SIZE = float(os.getenv("SIMAM3D_FUSION_VOXEL_SIZE", "0.02"))
87
+ FUSION_MAX_POINTS = int(os.getenv("SIMAM3D_FUSION_MAX_POINTS", "10000"))
88
+ MIN_FUSION_SUPPORT_VIEWS = int(os.getenv("SIMAM3D_MIN_FUSION_SUPPORT_VIEWS", "1"))
89
+ GAUSSIAN_MAX_POINTS = int(os.getenv("SIMAM3D_GAUSSIAN_MAX_POINTS", "2048"))
90
+ DA3_PROCESS_RES = int(os.getenv("SIMAM3D_DA3_PROCESS_RES", "256"))
91
+ DEPTH_PIPELINE = None
92
+ DA3_MODEL = None
93
+ PIPELINE_LOCK = threading.Lock()
94
+ INFERENCE_LOCK = threading.Lock()
95
+
96
+
97
+ def runtime_label() -> str:
98
+ if torch.cuda.is_available():
99
+ return f"CUDA GPU ({torch.cuda.get_device_name(0)})"
100
+ return "CPU"
101
+
102
+
103
+ def get_depth_pipeline():
104
+ global DEPTH_PIPELINE
105
+ if DEPTH_PIPELINE is not None:
106
+ return DEPTH_PIPELINE
107
+ with PIPELINE_LOCK:
108
+ if DEPTH_PIPELINE is None:
109
+ # Keep only one heavyweight backend resident when users switch
110
+ # between DA3 and V2 in a long-lived Space process.
111
+ clear_da3_model()
112
+ if pipeline is None or not TORCH_AVAILABLE:
113
+ raise RuntimeError("Learned depth dependencies are not installed; use export smoke mode or deploy the optional GPU image.")
114
+ device = 0 if torch.cuda.is_available() else -1
115
+ DEPTH_PIPELINE = pipeline("depth-estimation", model=MODEL_ID, device=device)
116
+ return DEPTH_PIPELINE
117
+
118
+
119
+ def get_da3_model():
120
+ global DA3_MODEL
121
+ if DA3_MODEL is not None:
122
+ return DA3_MODEL
123
+ with PIPELINE_LOCK:
124
+ if DA3_MODEL is None:
125
+ clear_depth_pipeline()
126
+ DepthAnything3, _ = load_da3_class()
127
+
128
+ device = "cuda" if torch.cuda.is_available() else "cpu"
129
+ DA3_MODEL = DepthAnything3.from_pretrained(DA3_MODEL_ID).to(device)
130
+ DA3_MODEL.eval()
131
+ return DA3_MODEL
132
+
133
+
134
+ def clear_da3_model():
135
+ global DA3_MODEL
136
+ DA3_MODEL = None
137
+ if torch.cuda.is_available():
138
+ torch.cuda.empty_cache()
139
+
140
+
141
+ def clear_depth_pipeline():
142
+ """Release the Transformers V2 pipeline before loading another backend."""
143
+ global DEPTH_PIPELINE
144
+ DEPTH_PIPELINE = None
145
+ if torch.cuda.is_available():
146
+ torch.cuda.empty_cache()
147
+
148
+
149
+ def make_depth_preview(depth: np.ndarray) -> Image.Image:
150
+ depth = (depth - depth.min()) / max(float(depth.max() - depth.min()), 1e-6)
151
+ rgb = (colormaps.get_cmap("magma")(1.0 - depth)[..., :3] * 255).astype(np.uint8)
152
+ return Image.fromarray(rgb)
153
+
154
+
155
+ def make_confidence_preview(confidence: np.ndarray) -> Image.Image:
156
+ confidence = np.asarray(confidence, dtype=np.float32)
157
+ confidence = np.nan_to_num(confidence, nan=0.0, posinf=1.0, neginf=0.0)
158
+ confidence = (confidence - confidence.min()) / max(float(confidence.max() - confidence.min()), 1e-6)
159
+ rgb = (colormaps.get_cmap("viridis")(confidence)[..., :3] * 255).astype(np.uint8)
160
+ return Image.fromarray(rgb)
161
+
162
+
163
+ def make_uncertainty_preview(uncertainty: np.ndarray) -> Image.Image:
164
+ uncertainty = np.clip(np.nan_to_num(np.asarray(uncertainty, dtype=np.float32)), 0.0, 1.0)
165
+ rgb = (colormaps.get_cmap("inferno")(uncertainty)[..., :3] * 255).astype(np.uint8)
166
+ return Image.fromarray(rgb)
167
+
168
+
169
+ def make_evidence_card(image, depth, confidence, backend, view_count, fusion_stats, run_id):
170
+ """Create a compact, shareable diagnostic card for each reconstruction run."""
171
+ tile_size = (480, 300)
172
+ source = ImageOps.contain(image.convert("RGB"), tile_size)
173
+ depth_tile = ImageOps.contain(make_depth_preview(depth).convert("RGB"), tile_size)
174
+ confidence_tile = ImageOps.contain(make_confidence_preview(confidence).convert("RGB"), tile_size)
175
+ canvas = Image.new("RGB", (960, 700), (12, 16, 28))
176
+ draw = ImageDraw.Draw(canvas)
177
+ draw.text((24, 18), "SIMAM3D | EVIDENCE CARD", fill=(235, 240, 255))
178
+ draw.text(
179
+ (24, 46),
180
+ f"{backend} | {view_count} view(s) | {runtime_label()}",
181
+ fill=(164, 178, 205),
182
+ )
183
+ tiles = [(source, (0, 90), "SOURCE"), (depth_tile, (480, 90), "DEPTH"),
184
+ (confidence_tile, (0, 390), "CONFIDENCE")]
185
+ for tile, origin, label in tiles:
186
+ x, y = origin
187
+ canvas.paste(tile, (x, y))
188
+ draw.rectangle((x, y, x + tile.width, y + tile.height), outline=(76, 93, 126), width=2)
189
+ draw.text((x + 12, y + 12), label, fill=(255, 255, 255))
190
+ draw.text(
191
+ (500, 410),
192
+ f"FUSED POINTS\n{fusion_stats['point_count']:,}\n\n"
193
+ f"DOMINANT SOURCE VIEWS\n{fusion_stats['dominant_source_view_count']}\n\n"
194
+ f"SUPPORTED SOURCE VIEWS\n{fusion_stats['supported_source_view_count']}\n\n"
195
+ f"MULTI-VIEW VOXELS\n{fusion_stats['multi_view_voxel_fraction']:.1%}\n\n"
196
+ f"CONFIDENCE MEAN\n{fusion_stats['confidence_mean']:.3f}\n\n"
197
+ f"CONFIDENCE P95\n{fusion_stats['confidence_p95']:.3f}",
198
+ fill=(210, 220, 240),
199
+ spacing=8,
200
+ )
201
+ OUTPUT_DIR.mkdir(exist_ok=True)
202
+ path = OUTPUT_DIR / f"simam3d_{run_id}_evidence_card.png"
203
+ canvas.save(path, optimize=True)
204
+ return str(path)
205
+
206
+
207
+ def make_reveal_card(image, depth, guess, lighting, run_id: str) -> str:
208
+ """Create a social-friendly reveal card while clearly separating inference from fact."""
209
+ tile_size = (480, 300)
210
+ source = ImageOps.contain(image.convert("RGB"), tile_size)
211
+ depth_tile = ImageOps.contain(make_depth_preview(depth).convert("RGB"), tile_size)
212
+ canvas = Image.new("RGB", (960, 760), (12, 16, 28))
213
+ draw = ImageDraw.Draw(canvas)
214
+ draw.text((24, 18), "SIMAM3D | WHAT'S BEHIND THE IMAGE?", fill=(235, 240, 255))
215
+ draw.text((24, 48), "Depth and illumination reveal | hypothesis, not ground truth", fill=(164, 178, 205))
216
+ canvas.paste(source, (0, 90))
217
+ canvas.paste(depth_tile, (480, 90))
218
+ draw.rectangle((0, 90, 480, 390), outline=(76, 93, 126), width=2)
219
+ draw.rectangle((480, 90, 960, 390), outline=(76, 93, 126), width=2)
220
+ draw.text((14, 104), "ORIGINAL", fill=(255, 255, 255))
221
+ draw.text((494, 104), "DEPTH REVEAL", fill=(255, 255, 255))
222
+ guess_text = str(guess["user_guess"])
223
+ cues = ", ".join(str(item) for item in guess["semantic_cues"])
224
+ lighting_text = (
225
+ f"LIGHT FIELD: {lighting['lighting_label']}\n"
226
+ f"Direction estimate: azimuth {lighting['estimated_azimuth_deg']:.0f} deg, "
227
+ f"elevation {lighting['estimated_elevation_deg']:.0f} deg\n"
228
+ f"Detector confidence: {lighting['detector_confidence']:.2f}"
229
+ )
230
+ draw.text((24, 430), "YOUR GUESS", fill=(133, 214, 255))
231
+ draw.text((24, 456), guess_text[:110], fill=(235, 240, 255))
232
+ draw.text((24, 500), f"SEMANTIC CUES: {cues}", fill=(210, 220, 240))
233
+ draw.text((24, 560), lighting_text, fill=(210, 220, 240), spacing=8)
234
+ draw.text((24, 690), "The unseen side is a research hypothesis; add views for evidence.", fill=(255, 190, 120))
235
+ OUTPUT_DIR.mkdir(exist_ok=True)
236
+ path = OUTPUT_DIR / f"simam3d_{run_id}_reveal_card.png"
237
+ canvas.save(path, optimize=True)
238
+ return str(path)
239
+
240
+
241
+ def depth_to_glb(image: Image.Image, depth: np.ndarray, run_id: str) -> str:
242
+ image = image.convert("RGB")
243
+ max_side = 192
244
+ scale = min(1.0, max_side / max(image.size))
245
+ size = (max(8, int(image.width * scale)), max(8, int(image.height * scale)))
246
+ rgb = np.asarray(image.resize(size, Image.Resampling.LANCZOS))
247
+ d = Image.fromarray(depth).resize(size, Image.Resampling.BILINEAR)
248
+ d = np.asarray(d, dtype=np.float32)
249
+ d = (d - d.min()) / max(float(d.max() - d.min()), 1e-6)
250
+
251
+ h, w = d.shape
252
+ yy, xx = np.mgrid[0:h, 0:w]
253
+ x = (xx / max(w - 1, 1) - 0.5) * 2.0
254
+ y = (0.5 - yy / max(h - 1, 1)) * 2.0
255
+ z = (1.0 - d) * 0.9
256
+ vertices = np.stack([x, y, z], axis=-1).reshape(-1, 3)
257
+ faces = []
258
+ for row in range(h - 1):
259
+ for col in range(w - 1):
260
+ i = row * w + col
261
+ faces.extend([[i, i + 1, i + w], [i + 1, i + w + 1, i + w]])
262
+ mesh = trimesh.Trimesh(vertices=vertices, faces=np.asarray(faces), process=False)
263
+ mesh.visual.vertex_colors = np.concatenate(
264
+ [rgb.reshape(-1, 3), np.full((vertices.shape[0], 1), 255, dtype=np.uint8)], axis=1
265
+ )
266
+ OUTPUT_DIR.mkdir(exist_ok=True)
267
+ path = OUTPUT_DIR / f"simam3d_{run_id}.glb"
268
+ mesh.export(path)
269
+ return str(path)
270
+
271
+
272
+ def depth_to_pointcloud(image: Image.Image, depth: np.ndarray, confidence: np.ndarray, run_id: str) -> str:
273
+ """Export the current depth scaffold as a colored PLY point cloud."""
274
+ image = image.convert("RGB")
275
+ max_side = 384
276
+ scale = min(1.0, max_side / max(image.size))
277
+ size = (max(8, int(image.width * scale)), max(8, int(image.height * scale)))
278
+ rgb = np.asarray(image.resize(size, Image.Resampling.LANCZOS))
279
+ d = np.asarray(Image.fromarray(depth).resize(size, Image.Resampling.BILINEAR), dtype=np.float32)
280
+ d = (d - d.min()) / max(float(d.max() - d.min()), 1e-6)
281
+ h, w = d.shape
282
+ yy, xx = np.mgrid[0:h, 0:w]
283
+ points = np.stack(
284
+ [(xx / max(w - 1, 1) - 0.5) * 2.0, (0.5 - yy / max(h - 1, 1)) * 2.0, (1.0 - d) * 0.9],
285
+ axis=-1,
286
+ ).reshape(-1, 3)
287
+ confidence = np.asarray(
288
+ Image.fromarray(np.asarray(confidence, dtype=np.float32)).resize(size, Image.Resampling.BILINEAR),
289
+ dtype=np.float32,
290
+ )
291
+ confidence = np.nan_to_num(confidence, nan=0.0, posinf=0.0, neginf=0.0)
292
+ peak = float(max(confidence.max(), 0.0)) if confidence.size else 0.0
293
+ confidence = confidence / peak if peak > 1e-6 else np.ones_like(confidence)
294
+ OUTPUT_DIR.mkdir(exist_ok=True)
295
+ path = OUTPUT_DIR / f"simam3d_{run_id}.ply"
296
+ write_confidence_ply(path, points, rgb.reshape(-1, 3), confidence.reshape(-1))
297
+ return str(path)
298
+
299
+
300
+ def save_prediction_npz(depth, confidence, extrinsics, intrinsics, run_id: str) -> str:
301
+ OUTPUT_DIR.mkdir(exist_ok=True)
302
+ path = OUTPUT_DIR / f"simam3d_{run_id}.npz"
303
+ np.savez_compressed(
304
+ path,
305
+ depth=np.asarray(depth, dtype=np.float32),
306
+ confidence=np.asarray(confidence, dtype=np.float32),
307
+ extrinsics=np.asarray(extrinsics, dtype=np.float32),
308
+ intrinsics=np.asarray(intrinsics, dtype=np.float32),
309
+ )
310
+ return str(path)
311
+
312
+
313
+ def save_uncertainty_map(uncertainty: np.ndarray, run_id: str) -> str:
314
+ OUTPUT_DIR.mkdir(exist_ok=True)
315
+ path = OUTPUT_DIR / f"simam3d_{run_id}_reveal_uncertainty.png"
316
+ make_uncertainty_preview(uncertainty).save(path, optimize=True)
317
+ return str(path)
318
+
319
+
320
+ def save_turntable_gif(points: np.ndarray, colors: np.ndarray, run_id: str) -> str:
321
+ """Render a lightweight, dependency-free orbit preview from fused points."""
322
+ points = np.asarray(points, dtype=np.float32)
323
+ colors = np.asarray(colors, dtype=np.uint8)[..., :3]
324
+ if len(points) != len(colors):
325
+ raise ValueError("turntable points and colors must have matching lengths")
326
+ if len(points) > 12000:
327
+ keep = np.linspace(0, len(points) - 1, 12000, dtype=np.int64)
328
+ points, colors = points[keep], colors[keep]
329
+ frames = []
330
+ size = 512
331
+ for yaw in np.linspace(0.0, 330.0, 12):
332
+ xy, depth = orbit_project_points(points, float(yaw))
333
+ frame = Image.new("RGB", (size, size), (9, 12, 22))
334
+ draw = ImageDraw.Draw(frame)
335
+ order = np.argsort(depth)
336
+ for index in order:
337
+ x = int((float(xy[index, 0]) * 0.43 + 0.5) * size)
338
+ y = int((0.5 - float(xy[index, 1]) * 0.43) * size)
339
+ if 0 <= x < size and 0 <= y < size:
340
+ radius = 1 if len(points) > 4000 else 2
341
+ color = tuple(int(value) for value in colors[index])
342
+ draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=color)
343
+ draw.text((16, 16), f"SIMAM3D | {float(yaw):.0f} deg", fill=(235, 240, 255))
344
+ frames.append(frame)
345
+ OUTPUT_DIR.mkdir(exist_ok=True)
346
+ path = OUTPUT_DIR / f"simam3d_{run_id}_turntable.gif"
347
+ frames[0].save(path, save_all=True, append_images=frames[1:], duration=100, loop=0, optimize=True)
348
+ return str(path)
349
+
350
+
351
+ def save_run_manifest(run_id, backend, view_count, elapsed, outputs, metrics) -> str:
352
+ OUTPUT_DIR.mkdir(exist_ok=True)
353
+ path = OUTPUT_DIR / f"simam3d_{run_id}_run.json"
354
+ manifest = {
355
+ "project": "SimamRealityGap3D",
356
+ "version": SIMAM3D_VERSION,
357
+ "manifest_schema_version": MANIFEST_SCHEMA_VERSION,
358
+ "run_id": run_id,
359
+ "backend": backend,
360
+ "model": (
361
+ DA3_MODEL_ID if backend.startswith("Depth Anything 3")
362
+ else "none (deterministic export smoke test)" if backend.startswith("Deterministic")
363
+ else MODEL_ID
364
+ ),
365
+ "runtime": runtime_label(),
366
+ "claims": {
367
+ "observed_input_geometry": True,
368
+ "generated_novel_views": False,
369
+ "metric_scale_reconstruction": False,
370
+ "learned_gaussian_optimization": False,
371
+ "direct_gaussian_prediction": metrics.get("gaussian_source") == "da3_direct",
372
+ "depth_normal_light_is_heuristic": True,
373
+ "reveal_content_is_verified": False,
374
+ },
375
+ "software": {
376
+ "python": platform.python_version(),
377
+ "platform": platform.platform(),
378
+ "torch": getattr(torch, "__version__", "unknown"),
379
+ "gradio": getattr(gr, "__version__", "unknown"),
380
+ "numpy": np.__version__,
381
+ "python_implementation": sys.implementation.name,
382
+ },
383
+ "view_count": view_count,
384
+ "elapsed_seconds": round(elapsed, 3),
385
+ "metrics": metrics,
386
+ "outputs": outputs,
387
+ "output_sha256": {
388
+ Path(output).name: file_fingerprint(output)
389
+ for output in outputs
390
+ if Path(output).is_file()
391
+ },
392
+ }
393
+ path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
394
+ valid, errors = validate_manifest(path)
395
+ if not valid:
396
+ raise RuntimeError(
397
+ "Generated manifest failed self-validation: " + "; ".join(errors)
398
+ )
399
+ return str(path)
400
+
401
+
402
+ def predict_v2(images):
403
+ """Run the lightweight, widely compatible depth fallback for every view."""
404
+ depths = []
405
+ for view in images:
406
+ with torch.inference_mode():
407
+ result = get_depth_pipeline()(view)
408
+ predicted = result.get("predicted_depth")
409
+ if predicted is None:
410
+ raise RuntimeError(f"Depth model returned no predicted_depth field: {list(result)}")
411
+ depths.append(predicted.squeeze().detach().float().cpu().numpy().astype(np.float32))
412
+ return np.stack(depths, axis=0)
413
+
414
+
415
+ def fuse_views(images, depths, confidence, extrinsics, intrinsics, run_id: str):
416
+ """Fuse depth views into a confidence-weighted world-space PLY."""
417
+ views = []
418
+ for idx, (image, depth) in enumerate(zip(images, depths)):
419
+ depth = np.asarray(depth, dtype=np.float32)
420
+ h, w = depth.shape
421
+ colors = np.asarray(image.convert("RGB").resize((w, h), Image.Resampling.LANCZOS))
422
+ conf = np.asarray(confidence[idx], dtype=np.float32) if len(confidence) > idx else None
423
+ if conf is not None and conf.shape != depth.shape:
424
+ conf = np.asarray(Image.fromarray(conf).resize((w, h), Image.Resampling.BILINEAR))
425
+ camera_k = intrinsics[idx] if len(intrinsics) > idx else None
426
+ if camera_k is not None:
427
+ camera_k = np.asarray(camera_k, dtype=np.float32).copy()
428
+ source_w, source_h = image.size
429
+ if camera_k.shape == (3, 3) and source_w and source_h:
430
+ camera_k[0, :] *= w / source_w
431
+ camera_k[1, :] *= h / source_h
432
+ views.append((depth, conf, camera_k,
433
+ extrinsics[idx] if len(extrinsics) > idx else None, colors))
434
+ result = fuse_point_views(
435
+ views, voxel_size=FUSION_VOXEL_SIZE, max_points=FUSION_MAX_POINTS
436
+ )
437
+ result = filter_fusion_by_support(result, MIN_FUSION_SUPPORT_VIEWS)
438
+ OUTPUT_DIR.mkdir(exist_ok=True)
439
+ path = OUTPUT_DIR / f"simam3d_{run_id}_fused.ply"
440
+ write_confidence_ply(
441
+ path, result.points, result.colors, result.weights,
442
+ result.source_views, result.source_masks
443
+ )
444
+ return str(path), fusion_metrics(result), result.weights, result.source_views, result.source_masks
445
+
446
+
447
+ def pointcloud_to_gaussian_ply(pointcloud_path: str, run_id: str, weights=None, source_views=None, source_masks=None) -> str:
448
+ """Convert fused colored points to a confidence-initialized 3DGS PLY."""
449
+ cloud = trimesh.load(pointcloud_path, process=False)
450
+ points = np.asarray(cloud.vertices, dtype=np.float32)
451
+ colors = np.asarray(cloud.colors[:, :3], dtype=np.uint8)
452
+ OUTPUT_DIR.mkdir(exist_ok=True)
453
+ path = OUTPUT_DIR / f"simam3d_{run_id}_gaussians.ply"
454
+ write_gaussian_ply(path, points, colors, weights, source_views, source_masks)
455
+ return str(path)
456
+
457
+
458
+ def _prediction_array(value):
459
+ """Move an optional DA3 tensor to a CPU NumPy array without torch types."""
460
+ if hasattr(value, "detach"):
461
+ value = value.detach().cpu().numpy()
462
+ return np.asarray(value)
463
+
464
+
465
+ def direct_da3_gaussian_ply(prediction, run_id: str) -> tuple[str, int, int] | None:
466
+ """Export DA3's learned world-space Gaussian parameters when available."""
467
+ gaussians = getattr(prediction, "gaussians", None)
468
+ if gaussians is None:
469
+ return None
470
+ print("Simam3D direct Gaussian export: reading parameters", flush=True)
471
+ means = _prediction_array(getattr(gaussians, "means", None))
472
+ scales = _prediction_array(getattr(gaussians, "scales", None))
473
+ rotations = _prediction_array(getattr(gaussians, "rotations", None))
474
+ opacities = _prediction_array(getattr(gaussians, "opacities", None)).reshape(-1)
475
+ print(f"Simam3D direct Gaussian export: means={means.shape} scales={scales.shape}", flush=True)
476
+ if means.ndim == 3 and means.shape[0] == 1:
477
+ means = means[0]
478
+ if scales.ndim == 3 and scales.shape[0] == 1:
479
+ scales = scales[0]
480
+ if rotations.ndim == 3 and rotations.shape[0] == 1:
481
+ rotations = rotations[0]
482
+ if means.ndim != 2 or means.shape[1] != 3:
483
+ raise ValueError(f"DA3 Gaussian means must have shape Nx3, got {means.shape}")
484
+ if scales.shape != (len(means), 3) or rotations.shape != (len(means), 4) or len(opacities) != len(means):
485
+ raise ValueError("DA3 Gaussian parameter arrays do not have matching lengths")
486
+ original_count = len(means)
487
+ keep = None
488
+ if original_count > GAUSSIAN_MAX_POINTS:
489
+ # Preserve the most visible splats and restore source order for
490
+ # deterministic output. This bounds ASCII export time and file size.
491
+ keep = np.argsort(np.nan_to_num(opacities, nan=-np.inf))[-GAUSSIAN_MAX_POINTS:]
492
+ keep.sort()
493
+ means, scales, rotations, opacities = means[keep], scales[keep], rotations[keep], opacities[keep]
494
+ print(f"Simam3D direct Gaussian export: selecting {len(means)} of {original_count}", flush=True)
495
+ harmonics = getattr(gaussians, "harmonics", None)
496
+ if harmonics is not None:
497
+ # Only the DC coefficient is needed for the portable PLY color field;
498
+ # avoid transferring the complete SH basis from GPU memory.
499
+ if hasattr(harmonics, "detach") and harmonics.ndim >= 3:
500
+ harmonics = harmonics[..., 0]
501
+ harmonics = _prediction_array(harmonics)
502
+ if harmonics.ndim == 4 and harmonics.shape[0] == 1:
503
+ harmonics = harmonics[0]
504
+ if harmonics.ndim == 3 and harmonics.shape[0] == 1:
505
+ harmonics = harmonics[0]
506
+ if keep is not None and harmonics.shape[0] == original_count:
507
+ harmonics = harmonics[keep]
508
+ if harmonics.ndim == 2 and harmonics.shape[0] == len(means):
509
+ colors = np.clip((harmonics * 0.2820947918 + 0.5) * 255.0, 0, 255).astype(np.uint8)
510
+ else:
511
+ colors = np.full((len(means), 3), 180, dtype=np.uint8)
512
+ else:
513
+ colors = np.full((len(means), 3), 180, dtype=np.uint8)
514
+ path = OUTPUT_DIR / f"simam3d_{run_id}_gaussians_da3_direct.ply"
515
+ write_gaussian_ply(
516
+ path, means, colors, weights=np.clip(opacities, 0.0, 1.0),
517
+ scales=scales, rotations=rotations, opacities=opacities,
518
+ )
519
+ print(f"Simam3D direct Gaussian export: wrote {path}", flush=True)
520
+ return str(path), original_count, len(means)
521
+
522
+
523
+ def load_input_images(primary: Image.Image, extra_files) -> list[Image.Image]:
524
+ images = [primary.convert("RGB")]
525
+ for item in extra_files or []:
526
+ path = item if isinstance(item, str) else (
527
+ getattr(item, "path", None) or getattr(item, "name", None)
528
+ )
529
+ if path:
530
+ try:
531
+ with Image.open(path) as extra:
532
+ images.append(extra.convert("RGB").copy())
533
+ except (OSError, ValueError) as exc:
534
+ raise ValueError(f"Could not read additional view {path!r}: {exc}") from exc
535
+ if len(images) > MAX_VIEWS:
536
+ raise ValueError(f"At most {MAX_VIEWS} views are supported per run to protect hosted GPU memory.")
537
+ normalized = []
538
+ for current in images:
539
+ if max(current.size) > MAX_INPUT_SIDE:
540
+ scale = MAX_INPUT_SIDE / max(current.size)
541
+ size = (max(8, int(current.width * scale)), max(8, int(current.height * scale)))
542
+ current = current.resize(size, Image.Resampling.LANCZOS)
543
+ normalized.append(current)
544
+ return normalized
545
+
546
+
547
+ def image_fingerprint(image: Image.Image) -> str:
548
+ """Hash normalized RGB pixels so runs can be reproduced exactly."""
549
+ buffer = io.BytesIO()
550
+ image.convert("RGB").save(buffer, format="PNG", optimize=False)
551
+ return hashlib.sha256(buffer.getvalue()).hexdigest()
552
+
553
+
554
+ def near_duplicate_pair_count(images: list[Image.Image], threshold: float = 0.03) -> int:
555
+ """Count pairs with tiny normalized RGB distance for view-quality diagnostics."""
556
+ thumbnails = [
557
+ np.asarray(ImageOps.fit(image.convert("RGB"), (32, 32)), dtype=np.float32) / 255.0
558
+ for image in images
559
+ ]
560
+ return sum(
561
+ float(np.abs(thumbnails[left] - thumbnails[right]).mean()) <= threshold
562
+ for left in range(len(thumbnails))
563
+ for right in range(left + 1, len(thumbnails))
564
+ )
565
+
566
+
567
+ def file_fingerprint(path: str | Path) -> str:
568
+ """Hash an exported artifact in bounded chunks for manifest provenance."""
569
+ digest = hashlib.sha256()
570
+ with Path(path).open("rb") as handle:
571
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
572
+ digest.update(chunk)
573
+ return digest.hexdigest()
574
+
575
+
576
+ def da3_api_status() -> dict:
577
+ """Check the optional DA3 API without downloading weights or loading a model."""
578
+ try:
579
+ _, location = load_da3_class()
580
+ return {"installed": True, "importable": True, "api_location": location, "error": None}
581
+ except (ImportError, ModuleNotFoundError, AttributeError) as exc:
582
+ return {"installed": False, "importable": False, "api_location": None, "error": f"{type(exc).__name__}: {exc}"}
583
+ except Exception as exc:
584
+ return {"installed": True, "importable": False, "api_location": None, "error": f"{type(exc).__name__}: {exc}"}
585
+
586
+
587
+ def load_da3_class():
588
+ """Resolve the DA3 class across known upstream package layouts."""
589
+ return resolve_da3_class()
590
+
591
+
592
+ def save_failure_manifest(requested_backend: str, stage: str, exc: Exception, input_hashes=None) -> str:
593
+ """Persist actionable failure context without storing user media or secrets."""
594
+ OUTPUT_DIR.mkdir(exist_ok=True)
595
+ run_id = uuid.uuid4().hex
596
+ manifest = {
597
+ "project": "SimamRealityGap3D",
598
+ "version": SIMAM3D_VERSION,
599
+ "manifest_schema_version": MANIFEST_SCHEMA_VERSION,
600
+ "run_id": run_id,
601
+ "status": "failed",
602
+ "backend": requested_backend,
603
+ "runtime": runtime_label(),
604
+ "software": {
605
+ "python": platform.python_version(),
606
+ "torch": getattr(torch, "__version__", "unknown"),
607
+ "gradio": getattr(gr, "__version__", "unknown"),
608
+ },
609
+ "stage": stage,
610
+ "input_sha256": list(input_hashes or []),
611
+ "error": {"type": type(exc).__name__, "message": str(exc)},
612
+ "traceback_tail": traceback.format_exc().splitlines()[-8:],
613
+ "claims": {
614
+ "observed_input_geometry": False,
615
+ "generated_novel_views": False,
616
+ "metric_scale_reconstruction": False,
617
+ "learned_gaussian_optimization": False,
618
+ "failure_report_only": True,
619
+ },
620
+ }
621
+ path = OUTPUT_DIR / f"simam3d_{run_id}_failure.json"
622
+ path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
623
+ return str(path)
624
+
625
+
626
+ def diagnostics() -> str:
627
+ """Return actionable environment information without loading a model."""
628
+ OUTPUT_DIR.mkdir(exist_ok=True)
629
+ checks = {
630
+ "simam3d_version": SIMAM3D_VERSION,
631
+ "runtime": runtime_label(),
632
+ "cuda_available": bool(torch.cuda.is_available()),
633
+ "torch": getattr(torch, "__version__", "unknown"),
634
+ "gradio": getattr(gr, "__version__", "unknown"),
635
+ "v2_model": MODEL_ID,
636
+ "da3_api": da3_api_status(),
637
+ "da3_model": DA3_MODEL_ID,
638
+ "output_directory_writable": os.access(OUTPUT_DIR, os.W_OK),
639
+ "max_input_side": MAX_INPUT_SIDE,
640
+ "max_views": MAX_VIEWS,
641
+ "fusion_voxel_size": FUSION_VOXEL_SIZE,
642
+ "fusion_max_points": FUSION_MAX_POINTS,
643
+ "min_fusion_support_views": MIN_FUSION_SUPPORT_VIEWS,
644
+ "da3_process_res": DA3_PROCESS_RES,
645
+ "gpu_duration_seconds": GPU_DURATION_SECONDS,
646
+ }
647
+ if torch.cuda.is_available():
648
+ checks["cuda_device"] = torch.cuda.get_device_name(0)
649
+ checks["cuda_memory_gb"] = round(torch.cuda.get_device_properties(0).total_memory / 1024**3, 2)
650
+ return "```json\n" + json.dumps(checks, indent=2) + "\n```"
651
+
652
+
653
+ def recent_failure_reports():
654
+ """Return recent redacted failure manifests for download from the UI."""
655
+ OUTPUT_DIR.mkdir(exist_ok=True)
656
+ return [str(path) for path in sorted(OUTPUT_DIR.glob("*_failure.json"), key=lambda item: item.stat().st_mtime, reverse=True)[:10]]
657
+
658
+
659
+ def _generate_impl(image: Image.Image, extra_files, backend: str, guess: str, demo_mode: bool, progress=gr.Progress()):
660
+ if image is None:
661
+ raise gr.Error("Please add an input image first.")
662
+ started = time.perf_counter()
663
+ stage = "input_validation"
664
+ input_hashes = []
665
+ try:
666
+ if not TORCH_AVAILABLE and not demo_mode:
667
+ demo_mode = True
668
+ gr.Warning("Optional Torch depth dependencies are unavailable; running the deterministic evidence/export baseline.")
669
+ stage = "input_loading"
670
+ images = load_input_images(image, extra_files)
671
+ view_count = len(images)
672
+ input_hashes = [image_fingerprint(view) for view in images]
673
+ input_diversity = input_diversity_metrics(input_hashes, near_duplicate_pair_count(images))
674
+ scene_guess = classify_scene_hypothesis(guess)
675
+ lighting = analyze_light_field(np.asarray(images[0]))
676
+ backend_used = backend
677
+ fallback_note = ""
678
+ fallback_error = None
679
+ confidence_source = "baseline_uniform"
680
+ da3_prediction = None
681
+ progress(0.05, desc=f"Loading {backend} on {runtime_label()}")
682
+ confidence = np.ones((view_count, 1, 1), dtype=np.float32)
683
+ extrinsics = synthetic_orbit_poses(view_count)
684
+ intrinsics = np.repeat(np.eye(3, dtype=np.float32)[None, ...], view_count, axis=0)
685
+ pose_source = "synthetic_orbit_prior"
686
+ if demo_mode:
687
+ stage = "deterministic_depth"
688
+ depth = np.stack([deterministic_demo_depth(np.asarray(view)) for view in images], axis=0)
689
+ confidence = np.ones_like(depth, dtype=np.float32)
690
+ backend_used = "Deterministic export smoke test (no AI)"
691
+ pose_source = "synthetic_orbit_prior"
692
+ confidence_source = "uniform_demo"
693
+ progress(0.45, desc="Running deterministic export smoke test")
694
+ elif backend == "Depth Anything 3 (camera-aware)":
695
+ try:
696
+ stage = "da3_inference"
697
+ with INFERENCE_LOCK, torch.inference_mode():
698
+ prediction = get_da3_model().inference(
699
+ image=images, infer_gs=True, process_res=DA3_PROCESS_RES
700
+ )
701
+ da3_prediction = prediction
702
+ depth, confidence, extrinsics, intrinsics, confidence_source, pose_source = normalize_prediction_contract(
703
+ prediction, view_count
704
+ )
705
+ except (ImportError, ModuleNotFoundError, RuntimeError, TypeError, ValueError) as exc:
706
+ clear_da3_model()
707
+ fallback_error = f"{type(exc).__name__}: {exc}"
708
+ fallback_note = f" DA3 unavailable ({type(exc).__name__}); used the stable V2 fallback."
709
+ print(f"Simam3D DA3 unavailable; falling back to V2: {exc}", flush=True)
710
+ gr.Warning(fallback_note.strip())
711
+ backend_used = "Depth Anything V2 (stable baseline; DA3 fallback)"
712
+ stage = "v2_fallback_inference"
713
+ with INFERENCE_LOCK:
714
+ depth = predict_v2(images)
715
+ confidence = np.ones_like(depth, dtype=np.float32)
716
+ else:
717
+ stage = "v2_inference"
718
+ with INFERENCE_LOCK:
719
+ depth = predict_v2(images)
720
+ confidence = np.ones_like(depth, dtype=np.float32)
721
+ if depth.ndim != 3 or not np.isfinite(depth).all():
722
+ raise RuntimeError(f"Invalid depth tensor returned with shape {depth.shape}")
723
+ stage = "geometry_export"
724
+ progress(0.65, desc="Building depth geometry")
725
+ run_id = uuid.uuid4().hex
726
+ depth_image = make_depth_preview(depth[0])
727
+ confidence_image = make_confidence_preview(confidence[0])
728
+ glb_path = depth_to_glb(images[0], depth[0], run_id)
729
+ ply_path = depth_to_pointcloud(images[0], depth[0], confidence[0], run_id)
730
+ fused_path, fusion_stats, fused_weights, fused_source_views, fused_source_masks = fuse_views(
731
+ images, depth, confidence, extrinsics, intrinsics, run_id
732
+ )
733
+ fusion_stats["support_status"] = classify_fusion_support(
734
+ fusion_stats,
735
+ view_count,
736
+ input_diversity["unique_input_view_count"],
737
+ pose_source,
738
+ input_diversity["near_duplicate_pair_count"],
739
+ )
740
+ fused_cloud = trimesh.load(fused_path, process=False)
741
+ fused_points = np.asarray(fused_cloud.vertices, dtype=np.float32)
742
+ projection_coverage = []
743
+ reprojection_metrics = []
744
+ for idx in range(view_count):
745
+ _, _, inside = project_world_points(
746
+ fused_points, intrinsics[idx], extrinsics[idx], images[idx].width, images[idx].height
747
+ )
748
+ projection_coverage.append(float(inside.mean()) if len(inside) else 0.0)
749
+ reprojection_metrics.append(
750
+ reprojection_consistency(fused_points, depth[idx], intrinsics[idx], extrinsics[idx])
751
+ )
752
+ turntable_path = save_turntable_gif(
753
+ fused_points,
754
+ np.asarray(fused_cloud.colors[:, :3], dtype=np.uint8),
755
+ run_id,
756
+ )
757
+ gaussian_path = pointcloud_to_gaussian_ply(
758
+ fused_path, run_id, fused_weights, fused_source_views, fused_source_masks
759
+ )
760
+ gaussian_source = "fused_point_initialization"
761
+ direct_gaussian_error = None
762
+ direct_gaussian_count = 0
763
+ direct_gaussian_exported_count = 0
764
+ if da3_prediction is not None:
765
+ try:
766
+ direct_result = direct_da3_gaussian_ply(da3_prediction, run_id)
767
+ if direct_result is not None:
768
+ direct_path, direct_gaussian_count, direct_gaussian_exported_count = direct_result
769
+ gaussian_path = direct_path
770
+ gaussian_source = "da3_direct"
771
+ except (RuntimeError, TypeError, ValueError) as exc:
772
+ direct_gaussian_error = f"{type(exc).__name__}: {exc}"
773
+ print(
774
+ f"Simam3D native Gaussian export unavailable; using fused initialization: {exc}",
775
+ flush=True,
776
+ )
777
+ gr.Warning("Native DA3 Gaussian export was unavailable; exported fused Gaussian initialization instead.")
778
+ npz_path = save_prediction_npz(depth, confidence, extrinsics, intrinsics, run_id)
779
+ uncertainty = reveal_uncertainty(depth[0], confidence[0])
780
+ depth_lighting = estimate_depth_light(depth[0], np.asarray(images[0].resize(depth[0].shape[::-1], Image.Resampling.LANCZOS)))
781
+ uncertainty_path = save_uncertainty_map(uncertainty, run_id)
782
+ view_plan = next_view_plan(view_count, extrinsics)
783
+ evidence_card = make_evidence_card(
784
+ images[0], depth[0], confidence[0], backend_used, view_count, fusion_stats, run_id
785
+ )
786
+ reveal_card = make_reveal_card(images[0], depth[0], scene_guess, lighting, run_id)
787
+ analysis_report = (
788
+ "### Behind-the-image analysis\n"
789
+ f"**Your hypothesis:** {scene_guess['user_guess']} \n"
790
+ f"**Semantic cues:** {', '.join(scene_guess['semantic_cues'])} \n"
791
+ f"**Lighting:** {lighting['lighting_label']} \n"
792
+ f"**Estimated light direction:** azimuth {lighting['estimated_azimuth_deg']:.0f} deg, "
793
+ f"elevation {lighting['estimated_elevation_deg']:.0f} deg \n"
794
+ f"**3D light vector:** ({depth_lighting['light_direction_x']:.2f}, "
795
+ f"{depth_lighting['light_direction_y']:.2f}, {depth_lighting['light_direction_z']:.2f}) "
796
+ f"with confidence {depth_lighting['photometric_confidence']:.2f} \n"
797
+ f"**Detector confidence:** {lighting['detector_confidence']:.2f} \n"
798
+ f"**Reveal uncertainty:** {uncertainty.mean():.2f} mean visible-space uncertainty \n"
799
+ f"**Fused projection coverage:** {np.mean(projection_coverage):.1%} mean across input views \n"
800
+ f"**Depth reprojection MAE:** {np.mean([item['mean_absolute_error'] for item in reprojection_metrics]):.3f} "
801
+ "relative-depth diagnostic \n"
802
+ f"**Input diversity:** {input_diversity['input_diversity_status']} "
803
+ f"({input_diversity['unique_input_view_count']}/{input_diversity['input_view_count']} unique view(s)) \n"
804
+ f"**Fusion support:** {fusion_stats['support_status']} \n"
805
+ f"**Next view suggestion:** {view_plan[0]['yaw_deg']:.0f} deg yaw "
806
+ f"({view_plan[0]['gap_from_existing_deg']:.0f} deg gap) \n"
807
+ "*This is an image-space lighting estimate and a user-guided scene hypothesis, "
808
+ "not verified hidden content.*"
809
+ )
810
+ elapsed = time.perf_counter() - started
811
+ manifest_path = save_run_manifest(
812
+ run_id,
813
+ backend_used,
814
+ view_count,
815
+ elapsed,
816
+ [glb_path, ply_path, fused_path, gaussian_path, npz_path, uncertainty_path, turntable_path, evidence_card, reveal_card],
817
+ {
818
+ "depth_shape": list(depth.shape),
819
+ "depth_min": float(depth.min()),
820
+ "depth_max": float(depth.max()),
821
+ "confidence_mean": float(np.mean(confidence)),
822
+ # Preserve the full fusion evidence in the manifest. Keeping
823
+ # this nested record avoids reducing a multi-view run to only
824
+ # its point count and makes source support auditable.
825
+ "fusion": fusion_stats,
826
+ "gaussian_source": gaussian_source,
827
+ "direct_gaussian_count": direct_gaussian_count,
828
+ "direct_gaussian_exported_count": direct_gaussian_exported_count,
829
+ "direct_gaussian_error": direct_gaussian_error,
830
+ "gaussian_export_max_points": GAUSSIAN_MAX_POINTS,
831
+ "da3_process_res": DA3_PROCESS_RES,
832
+ "fused_point_count": fusion_stats["point_count"],
833
+ "fused_confidence_mean": fusion_stats["confidence_mean"],
834
+ "fused_confidence_p95": fusion_stats["confidence_p95"],
835
+ "pose_source": pose_source,
836
+ "confidence_source": confidence_source,
837
+ "requested_backend": backend,
838
+ "fallback_error": fallback_error,
839
+ "input_sha256": input_hashes,
840
+ "input_diversity": input_diversity,
841
+ "input_sizes": [list(view.size) for view in images],
842
+ "fusion_voxel_size": FUSION_VOXEL_SIZE,
843
+ "fusion_max_points": FUSION_MAX_POINTS,
844
+ "min_fusion_support_views": MIN_FUSION_SUPPORT_VIEWS,
845
+ "scene_hypothesis": scene_guess,
846
+ "lighting_analysis": lighting,
847
+ "depth_normal_lighting": depth_lighting,
848
+ "reveal_uncertainty_mean": float(uncertainty.mean()),
849
+ "next_view_plan": view_plan,
850
+ "projection_coverage": projection_coverage,
851
+ "reprojection_consistency": reprojection_metrics,
852
+ },
853
+ )
854
+ progress(1.0, desc="Done")
855
+ return depth_image, confidence_image, glb_path, ply_path, fused_path, gaussian_path, npz_path, uncertainty_path, turntable_path, evidence_card, reveal_card, manifest_path, analysis_report, (
856
+ f"Processed {view_count} view(s) on {runtime_label()} in {elapsed:.1f}s using {backend_used}. "
857
+ "Per-view and confidence-weighted fused point clouds are exported. "
858
+ f"Pose source: {pose_source}; confidence source: {confidence_source}." + fallback_note
859
+ )
860
+ except Exception as exc:
861
+ print(f"Simam3D generation failed: {type(exc).__name__}: {exc}", flush=True)
862
+ failure_path = save_failure_manifest(backend, stage, exc, input_hashes)
863
+ raise gr.Error(
864
+ f"Generation failed: {type(exc).__name__}: {exc}. Failure manifest: {failure_path}"
865
+ ) from exc
866
+
867
+
868
+ @GPU_FUNCTION
869
+ def _generate_gpu(image: Image.Image, extra_files, backend: str, guess: str, demo_mode: bool, progress=gr.Progress()):
870
+ return _generate_impl(image, extra_files, backend, guess, demo_mode, progress)
871
+
872
+
873
+ def generate(image: Image.Image, extra_files, backend: str, guess: str, demo_mode: bool, progress=gr.Progress()):
874
+ """Keep the deterministic export diagnostic independent of GPU quota."""
875
+ if demo_mode:
876
+ return _generate_impl(image, extra_files, backend, guess, demo_mode, progress)
877
+ return _generate_gpu(image, extra_files, backend, guess, demo_mode, progress)
878
+
879
+
880
+ with gr.Blocks(title="Simam What's Behind the Image?") as demo:
881
+ gr.Markdown("# What’s Behind the Image?\n### A hypothesis-led spatial reveal")
882
+ gr.Markdown(
883
+ "Start with an image and your own guess about what lies behind it. The original image is lifted using a depth model, "
884
+ "then exported as a textured GLB and Gaussian-style point cloud. The lab reports which "
885
+ "regions are observed, inferred, or uncertain instead of presenting hallucinated geometry as fact."
886
+ )
887
+ gr.Markdown(
888
+ "**First run:** keep **Depth Anything V2 (stable baseline)** selected. "
889
+ "Use **Depth Anything 3 (camera-aware)** when you want to test the heavier "
890
+ "multi-view research path; failed DA3 loads fall back to V2 with a warning."
891
+ )
892
+ with gr.Row():
893
+ with gr.Column():
894
+ image = gr.Image(type="pil", label="Input image")
895
+ extra_files = gr.Files(
896
+ label="Optional additional views",
897
+ file_types=["image"],
898
+ file_count="multiple",
899
+ type="filepath",
900
+ )
901
+ guess = gr.Textbox(
902
+ label="What do you think is behind this image?",
903
+ placeholder="e.g. I think there is a garden or a room behind it...",
904
+ )
905
+ backend = gr.Dropdown(
906
+ choices=["Depth Anything 3 (camera-aware)", "Depth Anything V2 (stable baseline)"],
907
+ value="Depth Anything V2 (stable baseline)",
908
+ label="Reconstruction backend",
909
+ )
910
+ demo_mode = gr.Checkbox(
911
+ label="Run export smoke test (no AI model; diagnostic only)",
912
+ value=False,
913
+ )
914
+ run = gr.Button("Generate depth + 3D", variant="primary")
915
+ gr.Examples([["examples/sample_scene.png"]], inputs=[image], label="Try the included synthetic fixture")
916
+ with gr.Column():
917
+ depth = gr.Image(label="Predicted depth")
918
+ confidence_view = gr.Image(label="Confidence diagnostic")
919
+ model = gr.File(label="Download depth geometry GLB", file_count="single")
920
+ pointcloud = gr.File(label="Download point cloud PLY", file_count="single")
921
+ fused = gr.File(label="Download fused point cloud PLY", file_count="single")
922
+ gaussians = gr.File(label="Download Gaussian-splat PLY", file_count="single")
923
+ metadata = gr.File(label="Download depth/camera metadata NPZ", file_count="single")
924
+ uncertainty_file = gr.File(label="Download reveal uncertainty map PNG", file_count="single")
925
+ turntable_file = gr.File(label="Download reconstructed turntable GIF", file_count="single")
926
+ evidence_card = gr.File(label="Download shareable evidence card PNG", file_count="single")
927
+ reveal_card = gr.File(label="Download What's Behind reveal card PNG", file_count="single")
928
+ manifest = gr.File(label="Download reproducibility manifest JSON", file_count="single")
929
+ analysis_report = gr.Markdown()
930
+ status = gr.Markdown(f"Ready. What’s Behind the Image? **v{SIMAM3D_VERSION}** | Runtime: **{runtime_label()}**")
931
+ with gr.Accordion("Diagnostics", open=False):
932
+ diagnose = gr.Button("Run environment diagnostics")
933
+ diagnostic_report = gr.Markdown()
934
+ diagnose.click(diagnostics, outputs=diagnostic_report)
935
+ refresh_failures = gr.Button("Refresh recent failure reports")
936
+ failure_reports = gr.Files(label="Download recent failure reports", file_count="multiple")
937
+ refresh_failures.click(recent_failure_reports, outputs=failure_reports)
938
+ run.click(
939
+ generate,
940
+ inputs=[image, extra_files, backend, guess, demo_mode],
941
+ outputs=[depth, confidence_view, model, pointcloud, fused, gaussians, metadata, uncertainty_file, turntable_file, evidence_card, reveal_card, manifest, analysis_report, status],
942
+ concurrency_limit=1,
943
+ concurrency_id="simam3d_heavy_inference",
944
+ )
945
+
946
+
947
+ if __name__ == "__main__":
948
+ print(f"What’s Behind the Image? v{SIMAM3D_VERSION} starting on {runtime_label()}", flush=True)
949
+ demo.launch(show_error=True)
da3_compat.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dependency-free resolver for known Depth Anything 3 package layouts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+
7
+
8
+ def resolve_da3_class(importer=importlib.import_module):
9
+ """Return ``(DepthAnything3, module_name)`` or a useful ImportError."""
10
+ errors = []
11
+ for location in ("depth_anything_3.api", "depth_anything_3"):
12
+ try:
13
+ module = importer(location)
14
+ candidate = getattr(module, "DepthAnything3", None)
15
+ if candidate is not None:
16
+ return candidate, location
17
+ errors.append(f"{location}: DepthAnything3 is missing")
18
+ except (ImportError, ModuleNotFoundError, AttributeError) as exc:
19
+ errors.append(f"{location}: {type(exc).__name__}: {exc}")
20
+ raise ImportError("; ".join(errors))
examples/sample_scene.png ADDED
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ gradio==5.0.0
2
+ pillow>=10,<12
3
+ numpy>=2,<3
4
+ matplotlib>=3.8,<4
5
+ trimesh>=4.5,<5
6
+ # Torch/Transformers/DA3 are optional and belong in a dedicated GPU image.
7
+ audioop-lts>=0.2.1; python_version >= "3.13"
8
+ huggingface_hub<1.0
simam3d_core.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure NumPy geometry utilities for Simam3D.
2
+
3
+ This module intentionally has no Torch, Gradio, or CUDA dependency. It is the
4
+ testable contract between model adapters and the export/UI layer.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class FusionResult:
17
+ points: np.ndarray
18
+ colors: np.ndarray
19
+ weights: np.ndarray
20
+ source_views: np.ndarray
21
+ source_masks: np.ndarray
22
+
23
+
24
+ def normalize_map(values: np.ndarray) -> np.ndarray:
25
+ values = np.asarray(values, dtype=np.float32)
26
+ finite = np.isfinite(values)
27
+ if not finite.any():
28
+ return np.zeros_like(values, dtype=np.float32)
29
+ lo = float(values[finite].min())
30
+ hi = float(values[finite].max())
31
+ return np.clip(np.nan_to_num((values - lo) / max(hi - lo, 1e-6)), 0.0, 1.0)
32
+
33
+
34
+ def analyze_light_field(colors: np.ndarray) -> dict[str, float | str]:
35
+ """Estimate image-space illumination cues from an RGB image.
36
+
37
+ This is an auditable cue detector, not physical inverse rendering. It uses
38
+ luminance, contrast, and the centroid of bright pixels to provide a stable
39
+ lighting hypothesis for the UI and future learned relighting work.
40
+ """
41
+ rgb = np.asarray(colors, dtype=np.float32)
42
+ if rgb.ndim != 3 or rgb.shape[2] < 3 or min(rgb.shape[:2]) < 2:
43
+ raise ValueError("colors must have shape HxWx3 or HxWx4")
44
+ rgb = np.clip(rgb[..., :3], 0.0, 255.0) / 255.0
45
+ luminance = 0.2126 * rgb[..., 0] + 0.7152 * rgb[..., 1] + 0.0722 * rgb[..., 2]
46
+ mean = float(luminance.mean())
47
+ contrast = float(luminance.std())
48
+ bright_threshold = float(np.percentile(luminance, 90))
49
+ bright = luminance >= max(bright_threshold, 0.65)
50
+ yy, xx = np.mgrid[0:luminance.shape[0], 0:luminance.shape[1]]
51
+ mass = luminance * bright
52
+ total = float(mass.sum())
53
+ if total > 1e-6:
54
+ cx = float((xx * mass).sum() / total / max(luminance.shape[1] - 1, 1) * 2.0 - 1.0)
55
+ cy = float(1.0 - (yy * mass).sum() / total / max(luminance.shape[0] - 1, 1) * 2.0)
56
+ else:
57
+ cx = cy = 0.0
58
+ highlight_fraction = float(bright.mean())
59
+ shadow_fraction = float((luminance <= np.percentile(luminance, 10)).mean())
60
+ azimuth = float(np.degrees(np.arctan2(cx, max(cy, 1e-6))))
61
+ elevation = float(np.clip(35.0 + 45.0 * cy, 5.0, 85.0))
62
+ if contrast < 0.08:
63
+ label = "soft / low-contrast light"
64
+ elif highlight_fraction < 0.03 and shadow_fraction > 0.18:
65
+ label = "directional light with strong shadow cues"
66
+ else:
67
+ label = "directional light with diffuse fill"
68
+ confidence = float(np.clip(contrast * 3.0 + min(highlight_fraction * 2.0, 0.25), 0.0, 1.0))
69
+ return {
70
+ "lighting_label": label,
71
+ "mean_luminance": mean,
72
+ "contrast": contrast,
73
+ "highlight_fraction": highlight_fraction,
74
+ "shadow_fraction": shadow_fraction,
75
+ "bright_centroid_x": cx,
76
+ "bright_centroid_y": cy,
77
+ "estimated_azimuth_deg": azimuth,
78
+ "estimated_elevation_deg": elevation,
79
+ "detector_confidence": confidence,
80
+ }
81
+
82
+
83
+ def estimate_depth_light(depth: np.ndarray, colors: np.ndarray) -> dict[str, float | str]:
84
+ """Estimate a camera-space light direction from depth-derived normals.
85
+
86
+ This is a low-cost photometric heuristic. It is useful for ranking light
87
+ hypotheses and checking generated views, but it is not physical inverse
88
+ rendering and cannot disambiguate albedo from illumination by itself.
89
+ """
90
+ depth = np.asarray(depth, dtype=np.float32)
91
+ rgb = np.asarray(colors, dtype=np.float32)
92
+ if depth.ndim != 2 or rgb.ndim != 3 or rgb.shape[:2] != depth.shape or rgb.shape[2] < 3:
93
+ raise ValueError("depth must be HxW and colors must be matching HxWx3")
94
+ h, w = depth.shape
95
+ z = 1.0 - normalize_map(depth)
96
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
97
+ x = (xx / max(w - 1, 1) - 0.5) * 2.0
98
+ y = (0.5 - yy / max(h - 1, 1)) * 2.0
99
+ points = np.stack([x, y, z], axis=-1)
100
+ dx = np.gradient(points, axis=1)
101
+ dy = np.gradient(points, axis=0)
102
+ normals = np.cross(dx, dy)
103
+ lengths = np.linalg.norm(normals, axis=-1, keepdims=True)
104
+ normals = normals / np.maximum(lengths, 1e-6)
105
+ normals = np.where(normals[..., 2:3] < 0.0, -normals, normals)
106
+ luminance = (0.2126 * rgb[..., 0] + 0.7152 * rgb[..., 1] + 0.0722 * rgb[..., 2]) / 255.0
107
+ signal = np.clip(luminance - float(luminance.mean()), 0.0, None)
108
+ total = float(signal.sum())
109
+ if total <= 1e-6:
110
+ direction = np.array([0.0, 0.0, 1.0], dtype=np.float32)
111
+ confidence = 0.0
112
+ else:
113
+ direction = (normals * signal[..., None]).sum(axis=(0, 1)) / total
114
+ direction = direction / max(float(np.linalg.norm(direction)), 1e-6)
115
+ confidence = float(np.clip(np.linalg.norm((normals * signal[..., None]).sum(axis=(0, 1))) / total, 0.0, 1.0))
116
+ azimuth = float(np.degrees(np.arctan2(float(direction[0]), float(direction[2]))))
117
+ elevation = float(np.degrees(np.arcsin(np.clip(float(direction[1]), -1.0, 1.0))))
118
+ return {
119
+ "light_direction_x": float(direction[0]),
120
+ "light_direction_y": float(direction[1]),
121
+ "light_direction_z": float(direction[2]),
122
+ "estimated_azimuth_deg": azimuth,
123
+ "estimated_elevation_deg": elevation,
124
+ "photometric_confidence": confidence,
125
+ "status": "depth-normal photometric heuristic; albedo and exposure are confounds",
126
+ }
127
+
128
+
129
+ def deterministic_demo_depth(colors: np.ndarray) -> np.ndarray:
130
+ """Create an explicitly non-AI depth-like map for export-pipeline smoke tests."""
131
+ rgb = np.asarray(colors, dtype=np.float32)
132
+ if rgb.ndim != 3 or rgb.shape[2] < 3:
133
+ raise ValueError("colors must have shape HxWx3 or HxWx4")
134
+ luminance = 0.2126 * rgb[..., 0] + 0.7152 * rgb[..., 1] + 0.0722 * rgb[..., 2]
135
+ # Invert brightness only to create stable synthetic geometry; this has no
136
+ # semantic or metric meaning and must remain labelled as demo output.
137
+ return (255.0 - luminance).astype(np.float32)
138
+
139
+
140
+ def classify_scene_hypothesis(text: str | None) -> dict[str, str | list[str]]:
141
+ """Turn the user's reveal guess into explicit, inspectable semantic cues."""
142
+ raw = (text or "").strip()
143
+ normalized = " ".join(raw.split())
144
+ lower = normalized.lower()
145
+ cue_groups = {
146
+ "outdoor": ("sky", "street", "garden", "forest", "mountain", "building", "road"),
147
+ "indoor": ("room", "wall", "kitchen", "office", "hallway", "inside"),
148
+ "person": ("person", "face", "body", "portrait", "human"),
149
+ "object": ("object", "chair", "car", "shoe", "bottle", "product", "box"),
150
+ "nature": ("tree", "plant", "garden", "water", "animal", "cloud", "rock"),
151
+ }
152
+ cues = [name for name, words in cue_groups.items() if any(word in lower for word in words)]
153
+ return {
154
+ "user_guess": normalized or "No prior guess supplied",
155
+ "semantic_cues": cues or ["unspecified"],
156
+ "status": "user hypothesis only; not verified hidden content",
157
+ }
158
+
159
+
160
+ def reveal_uncertainty(depth: np.ndarray, confidence: np.ndarray | None = None) -> np.ndarray:
161
+ """Build a visible-space uncertainty map for deciding where to inspect next.
162
+
163
+ Low confidence and strong depth discontinuities are useful acquisition cues,
164
+ but this map does not assert what exists outside the camera's field of view.
165
+ """
166
+ depth = np.asarray(depth, dtype=np.float32)
167
+ if depth.ndim != 2:
168
+ raise ValueError("depth must be a 2-D map")
169
+ normalized = normalize_map(depth)
170
+ gy, gx = np.gradient(normalized)
171
+ edges = np.sqrt(gx * gx + gy * gy)
172
+ edges = normalize_map(edges)
173
+ if confidence is None:
174
+ conf = np.ones_like(normalized)
175
+ else:
176
+ conf = np.asarray(confidence, dtype=np.float32)
177
+ if conf.shape != depth.shape:
178
+ conf = np.ones_like(normalized)
179
+ conf = np.nan_to_num(conf, nan=0.0, posinf=0.0, neginf=0.0)
180
+ conf = np.clip(conf, 0.0, None)
181
+ peak = float(conf.max()) if conf.size else 0.0
182
+ conf = conf / peak if peak > 1e-6 else np.zeros_like(normalized)
183
+ return np.clip(0.7 * (1.0 - conf) + 0.3 * edges, 0.0, 1.0).astype(np.float32)
184
+
185
+
186
+ def next_view_plan(view_count: int, poses: np.ndarray | None = None) -> list[dict[str, float | str]]:
187
+ """Suggest yaw targets that fill the largest observed camera gaps.
188
+
189
+ When camera poses are available, use their camera centers instead of
190
+ assuming that submitted views are evenly spaced. This remains a 2-D
191
+ azimuth heuristic and is not a full next-best-view optimizer.
192
+ """
193
+ if view_count < 1:
194
+ raise ValueError("view_count must be positive")
195
+ existing = None
196
+ if poses is not None:
197
+ raw_poses = np.asarray(poses, dtype=np.float32)
198
+ if raw_poses.ndim == 3 and raw_poses.shape[0] == view_count:
199
+ centers = []
200
+ for raw_pose in raw_poses:
201
+ pose = ensure_pose(raw_pose)
202
+ center = np.linalg.inv(pose)[:3, 3]
203
+ if float(np.linalg.norm(center[[0, 2]])) > 1e-6:
204
+ centers.append(float(np.degrees(np.arctan2(center[0], center[2])) % 360.0))
205
+ if centers:
206
+ existing = np.asarray(centers, dtype=np.float32)
207
+ if existing is None:
208
+ existing = np.linspace(0.0, 360.0, view_count, endpoint=False)
209
+ targets = [180.0, 90.0, 270.0, 45.0, 315.0]
210
+ suggestions = []
211
+ for yaw in targets:
212
+ distance = float(np.min(np.abs(((existing - yaw + 180.0) % 360.0) - 180.0)))
213
+ suggestions.append({"yaw_deg": yaw, "gap_from_existing_deg": distance, "reason": "largest observed azimuth gap"})
214
+ return sorted(suggestions, key=lambda item: (-float(item["gap_from_existing_deg"]), float(item["yaw_deg"])))
215
+
216
+
217
+ def orbit_project_points(points: np.ndarray, yaw_deg: float) -> tuple[np.ndarray, np.ndarray]:
218
+ """Project reconstructed points to a normalized orbit view for previews."""
219
+ points = np.asarray(points, dtype=np.float32)
220
+ if points.ndim != 2 or points.shape[1] != 3:
221
+ raise ValueError("points must have shape Nx3")
222
+ angle = np.deg2rad(float(yaw_deg))
223
+ cosine, sine = np.cos(angle), np.sin(angle)
224
+ rotation = np.array([[cosine, 0.0, -sine], [0.0, 1.0, 0.0], [sine, 0.0, cosine]], dtype=np.float32)
225
+ view = points @ rotation.T
226
+ extent = max(float(np.max(np.abs(view[:, :2]))) if len(view) else 0.0, 1e-6)
227
+ xy = np.clip(view[:, :2] / extent, -1.0, 1.0)
228
+ return xy.astype(np.float32), view[:, 2].astype(np.float32)
229
+
230
+
231
+ def default_intrinsics(width: int, height: int) -> np.ndarray:
232
+ focal = float(max(width, height))
233
+ return np.array(
234
+ [[focal, 0.0, width / 2.0], [0.0, focal, height / 2.0], [0.0, 0.0, 1.0]],
235
+ dtype=np.float32,
236
+ )
237
+
238
+
239
+ def prepare_intrinsics(matrix: np.ndarray | None, width: int, height: int) -> np.ndarray:
240
+ """Validate intrinsics and convert normalized matrices to pixel units."""
241
+ if matrix is None:
242
+ return default_intrinsics(width, height)
243
+ k = np.asarray(matrix, dtype=np.float32).copy()
244
+ if k.shape != (3, 3) or not np.isfinite(k).all() or abs(float(k[2, 2])) < 1e-6:
245
+ return default_intrinsics(width, height)
246
+ # The V2 placeholder is identity, which means unknown rather than a real
247
+ # camera. Normalized camera matrices commonly use fx/fy and cx/cy in [0, 1].
248
+ if np.allclose(k, np.eye(3, dtype=np.float32)):
249
+ return default_intrinsics(width, height)
250
+ if abs(float(k[0, 0])) <= 2.0 and abs(float(k[1, 1])) <= 2.0:
251
+ k[0, :] *= width
252
+ k[1, :] *= height
253
+ if abs(float(k[0, 0])) < 1e-6 or abs(float(k[1, 1])) < 1e-6:
254
+ return default_intrinsics(width, height)
255
+ return k
256
+
257
+
258
+ def ensure_pose(matrix: np.ndarray | None) -> np.ndarray:
259
+ if matrix is None:
260
+ return np.eye(4, dtype=np.float32)
261
+ pose = np.asarray(matrix, dtype=np.float32)
262
+ if pose.shape == (3, 4):
263
+ pose = np.vstack([pose, [0.0, 0.0, 0.0, 1.0]])
264
+ if pose.shape != (4, 4) or not np.isfinite(pose).all():
265
+ return np.eye(4, dtype=np.float32)
266
+ return pose
267
+
268
+
269
+ def synthetic_orbit_poses(view_count: int, radius: float = 0.35) -> np.ndarray:
270
+ """Return a deterministic orbit prior for views without camera metadata.
271
+
272
+ These are world-to-camera poses for visualization/fusion only. They are not
273
+ a substitute for calibrated camera poses and are labeled as synthetic by
274
+ the application manifest.
275
+ """
276
+ if view_count < 1:
277
+ return np.empty((0, 4, 4), dtype=np.float32)
278
+ if view_count == 1:
279
+ return np.eye(4, dtype=np.float32)[None, ...]
280
+ poses = []
281
+ up = np.array([0.0, 1.0, 0.0], dtype=np.float32)
282
+ for index in range(view_count):
283
+ angle = 2.0 * np.pi * index / max(view_count, 1)
284
+ position = np.array([radius * np.sin(angle), 0.0, radius * np.cos(angle)], dtype=np.float32)
285
+ forward = -position / max(float(np.linalg.norm(position)), 1e-6)
286
+ right = np.cross(up, forward)
287
+ right /= max(float(np.linalg.norm(right)), 1e-6)
288
+ true_up = np.cross(forward, right)
289
+ camera_to_world = np.eye(4, dtype=np.float32)
290
+ camera_to_world[:3, :3] = np.stack([right, true_up, forward], axis=1)
291
+ camera_to_world[:3, 3] = position
292
+ poses.append(np.linalg.inv(camera_to_world).astype(np.float32))
293
+ return np.stack(poses, axis=0)
294
+
295
+
296
+ def normalize_prediction_contract(prediction, view_count: int):
297
+ """Validate and normalize the official DA3 Prediction output contract."""
298
+ depth = np.asarray(getattr(prediction, "depth", None), dtype=np.float32)
299
+ if depth.ndim == 2 and view_count == 1:
300
+ depth = depth[None, ...]
301
+ if depth.ndim != 3 or depth.shape[0] != view_count or not np.isfinite(depth).all():
302
+ raise ValueError(f"DA3 depth must have shape ({view_count}, H, W), got {depth.shape}")
303
+ raw_confidence = getattr(prediction, "conf", None)
304
+ if raw_confidence is None:
305
+ confidence = np.ones_like(depth, dtype=np.float32)
306
+ confidence_source = "baseline_uniform"
307
+ else:
308
+ confidence = np.asarray(raw_confidence, dtype=np.float32)
309
+ if confidence.ndim == 2 and view_count == 1:
310
+ confidence = confidence[None, ...]
311
+ if confidence.shape != depth.shape or not np.isfinite(confidence).all():
312
+ raise ValueError(f"DA3 confidence must match depth shape {depth.shape}, got {confidence.shape}")
313
+ confidence_source = "depth_anything_3"
314
+ raw_extrinsics = getattr(prediction, "extrinsics", None)
315
+ if raw_extrinsics is not None:
316
+ extrinsics = np.asarray(raw_extrinsics, dtype=np.float32)
317
+ valid_pose_shapes = {(view_count, 3, 4), (view_count, 4, 4)}
318
+ if extrinsics.shape not in valid_pose_shapes or not np.isfinite(extrinsics).all():
319
+ raise ValueError(f"DA3 extrinsics have invalid shape {extrinsics.shape}")
320
+ try:
321
+ for pose in extrinsics:
322
+ np.linalg.inv(ensure_pose(pose))
323
+ except np.linalg.LinAlgError:
324
+ extrinsics = synthetic_orbit_poses(view_count)
325
+ pose_source = "synthetic_orbit_prior"
326
+ else:
327
+ pose_source = "depth_anything_3"
328
+ else:
329
+ extrinsics = synthetic_orbit_poses(view_count)
330
+ pose_source = "synthetic_orbit_prior"
331
+ raw_intrinsics = getattr(prediction, "intrinsics", None)
332
+ if raw_intrinsics is not None:
333
+ intrinsics = np.asarray(raw_intrinsics, dtype=np.float32)
334
+ if intrinsics.shape != (view_count, 3, 3) or not np.isfinite(intrinsics).all():
335
+ raise ValueError(f"DA3 intrinsics have invalid shape {intrinsics.shape}")
336
+ else:
337
+ intrinsics = np.repeat(np.eye(3, dtype=np.float32)[None, ...], view_count, axis=0)
338
+ return depth, confidence, extrinsics, intrinsics, confidence_source, pose_source
339
+
340
+
341
+ def project_world_points(
342
+ points: np.ndarray,
343
+ intrinsics: np.ndarray | None,
344
+ extrinsics: np.ndarray | None,
345
+ width: int,
346
+ height: int,
347
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
348
+ """Project world-space points into a view and return pixels, depth, validity."""
349
+ points = np.asarray(points, dtype=np.float32)
350
+ if points.ndim != 2 or points.shape[1] != 3:
351
+ raise ValueError("points must have shape Nx3")
352
+ pose = ensure_pose(extrinsics)
353
+ camera = (pose @ np.c_[points, np.ones(len(points), dtype=np.float32)].T).T[:, :3]
354
+ k = prepare_intrinsics(intrinsics, width, height)
355
+ positive = camera[:, 2] > 1e-6
356
+ pixels = np.full((len(points), 2), np.nan, dtype=np.float32)
357
+ pixels[positive, 0] = k[0, 0] * camera[positive, 0] / camera[positive, 2] + k[0, 2]
358
+ pixels[positive, 1] = k[1, 1] * camera[positive, 1] / camera[positive, 2] + k[1, 2]
359
+ inside = positive & (pixels[:, 0] >= 0.0) & (pixels[:, 0] < width) & (pixels[:, 1] >= 0.0) & (pixels[:, 1] < height)
360
+ return pixels, camera[:, 2].astype(np.float32), inside
361
+
362
+
363
+ def reprojection_consistency(
364
+ points: np.ndarray,
365
+ depth: np.ndarray,
366
+ intrinsics: np.ndarray | None,
367
+ extrinsics: np.ndarray | None,
368
+ ) -> dict[str, float]:
369
+ """Compare fused-point depth against a view's relative depth prediction."""
370
+ depth = np.asarray(depth, dtype=np.float32)
371
+ if depth.ndim != 2:
372
+ raise ValueError("depth must be a 2-D map")
373
+ height, width = depth.shape
374
+ pixels, point_depth, inside = project_world_points(
375
+ points, intrinsics, extrinsics, width, height
376
+ )
377
+ if not inside.any():
378
+ return {"coverage": 0.0, "mean_absolute_error": 0.0, "median_absolute_error": 0.0}
379
+ raster = np.full((height, width), np.nan, dtype=np.float32)
380
+ pixel_x = np.clip(np.rint(pixels[inside, 0]).astype(np.int64), 0, width - 1)
381
+ pixel_y = np.clip(np.rint(pixels[inside, 1]).astype(np.int64), 0, height - 1)
382
+ for x, y, value in zip(pixel_x, pixel_y, point_depth[inside]):
383
+ if not np.isfinite(raster[y, x]) or value < raster[y, x]:
384
+ raster[y, x] = value
385
+ valid = np.isfinite(raster)
386
+ if not valid.any():
387
+ return {"coverage": 0.0, "mean_absolute_error": 0.0, "median_absolute_error": 0.0}
388
+ target = 1.0 - normalize_map(depth)
389
+ error = np.abs(raster[valid] - target[valid])
390
+ return {
391
+ "coverage": float(valid.mean()),
392
+ "mean_absolute_error": float(error.mean()),
393
+ "median_absolute_error": float(np.median(error)),
394
+ }
395
+
396
+
397
+ def depth_to_camera_points(
398
+ depth: np.ndarray,
399
+ intrinsics: np.ndarray | None = None,
400
+ confidence: np.ndarray | None = None,
401
+ ) -> tuple[np.ndarray, np.ndarray]:
402
+ """Project a depth map into camera-space points and return point weights."""
403
+ depth = np.asarray(depth, dtype=np.float32)
404
+ if depth.ndim != 2:
405
+ raise ValueError(f"depth must be HxW, got {depth.shape}")
406
+ height, width = depth.shape
407
+ k = prepare_intrinsics(intrinsics, width, height)
408
+ yy, xx = np.mgrid[0:height, 0:width]
409
+ # Depth Anything outputs relative depth; the scaffold uses inverse-depth
410
+ # convention consistently with the GLB/PLY exporters (higher prediction
411
+ # values place a point closer to the camera). Metric scale is not claimed.
412
+ z = 1.0 - normalize_map(depth)
413
+ z = np.clip(z, 0.02, 1.0)
414
+ points = np.stack(
415
+ [(xx - k[0, 2]) / max(float(k[0, 0]), 1e-6) * z,
416
+ (yy - k[1, 2]) / max(float(k[1, 1]), 1e-6) * z,
417
+ z],
418
+ axis=-1,
419
+ ).reshape(-1, 3)
420
+ if confidence is None:
421
+ weights = np.ones((height, width), dtype=np.float32)
422
+ else:
423
+ weights = np.nan_to_num(np.asarray(confidence, dtype=np.float32), nan=0.0)
424
+ if weights.shape != (height, width):
425
+ weights = np.ones((height, width), dtype=np.float32)
426
+ weights = np.clip(weights, 0.0, None)
427
+ peak = float(weights.max()) if weights.size else 0.0
428
+ # Preserve absolute confidence ratios across views: min-max scaling
429
+ # would turn a valid 0.5 confidence into zero when it is the minimum.
430
+ weights = weights / peak if peak > 1e-6 else np.zeros_like(weights)
431
+ return points, weights.reshape(-1)
432
+
433
+
434
+ def fuse_point_views(
435
+ views: list[tuple[np.ndarray, np.ndarray, np.ndarray | None, np.ndarray | None, np.ndarray]],
436
+ voxel_size: float = 0.02,
437
+ max_points: int = 150_000,
438
+ ) -> FusionResult:
439
+ """Fuse `(depth, confidence, intrinsics, extrinsics, colors)` views.
440
+
441
+ Extrinsics are interpreted as world-to-camera, matching DA3's API. Fusion
442
+ is deterministic: points are grouped into voxels and confidence-weighted
443
+ centroids/colors are retained, then capped by voxel confidence.
444
+ """
445
+ points_all, colors_all, weights_all, sources_all, masks_all = [], [], [], [], []
446
+ for source_view, (depth, confidence, intrinsics, extrinsics, colors) in enumerate(views):
447
+ depth = np.asarray(depth, dtype=np.float32)
448
+ colors = np.asarray(colors, dtype=np.uint8)
449
+ if colors.shape[:2] != depth.shape or colors.shape[-1] < 3:
450
+ raise ValueError("colors must have shape HxWx3 or HxWx4 matching depth")
451
+ camera_points, weights = depth_to_camera_points(depth, intrinsics, confidence)
452
+ pose = ensure_pose(extrinsics)
453
+ world_points = (np.linalg.inv(pose) @ np.c_[camera_points, np.ones(len(camera_points))].T).T[:, :3]
454
+ colors_all.append(colors[..., :3].reshape(-1, 3))
455
+ points_all.append(world_points)
456
+ weights_all.append(weights)
457
+ sources_all.append(np.full(len(weights), source_view, dtype=np.int32))
458
+ masks_all.append(np.full(len(weights), 1 << source_view, dtype=np.int32))
459
+ if not points_all:
460
+ empty = np.empty((0, 3), dtype=np.float32)
461
+ return FusionResult(
462
+ empty, np.empty((0, 3), dtype=np.uint8), np.empty((0,), dtype=np.float32),
463
+ np.empty((0,), dtype=np.int32), np.empty((0,), dtype=np.int32)
464
+ )
465
+ if len(views) > 30:
466
+ raise ValueError("At most 30 views are supported by the signed int32 provenance bitmask")
467
+ points = np.concatenate(points_all).astype(np.float32)
468
+ colors = np.concatenate(colors_all).astype(np.uint8)
469
+ weights = np.concatenate(weights_all).astype(np.float32)
470
+ source_views = np.concatenate(sources_all).astype(np.int32)
471
+ source_masks = np.concatenate(masks_all).astype(np.int32)
472
+ valid = np.isfinite(points).all(axis=1) & np.isfinite(weights) & (weights > 0)
473
+ points, colors, weights = points[valid], colors[valid], weights[valid]
474
+ source_views, source_masks = source_views[valid], source_masks[valid]
475
+ if voxel_size > 0 and len(points):
476
+ voxels = np.floor(points / voxel_size).astype(np.int64)
477
+ unique_voxels, inverse = np.unique(voxels, axis=0, return_inverse=True)
478
+ grouped_points = np.zeros((len(unique_voxels), 3), dtype=np.float64)
479
+ grouped_colors = np.zeros((len(unique_voxels), 3), dtype=np.float64)
480
+ grouped_weight = np.zeros(len(unique_voxels), dtype=np.float64)
481
+ np.add.at(grouped_points, inverse, points * weights[:, None])
482
+ np.add.at(grouped_colors, inverse, colors * weights[:, None])
483
+ np.add.at(grouped_weight, inverse, weights)
484
+ counts = np.bincount(inverse, minlength=len(unique_voxels)).astype(np.float64)
485
+ # Pick the strongest individual observation as an auditable provenance
486
+ # pointer for each voxel; full multi-source lineage remains future work.
487
+ raw_order = np.argsort(-weights, kind="stable")
488
+ _, first_source = np.unique(inverse[raw_order], return_index=True)
489
+ source_by_voxel = np.zeros(len(unique_voxels), dtype=np.int32)
490
+ source_by_voxel[inverse[raw_order[first_source]]] = source_views[raw_order[first_source]]
491
+ mask_by_voxel = np.zeros(len(unique_voxels), dtype=np.int32)
492
+ np.bitwise_or.at(mask_by_voxel, inverse, source_masks)
493
+ points = (grouped_points / np.maximum(grouped_weight[:, None], 1e-6)).astype(np.float32)
494
+ colors = np.clip(
495
+ grouped_colors / np.maximum(grouped_weight[:, None], 1e-6), 0.0, 255.0
496
+ ).astype(np.uint8)
497
+ weights = (grouped_weight / np.maximum(counts, 1.0)).astype(np.float32)
498
+ source_views = source_by_voxel
499
+ source_masks = mask_by_voxel
500
+ if len(points) > max_points:
501
+ keep = np.argsort(-weights, kind="stable")[:max_points]
502
+ points, colors, weights = points[keep], colors[keep], weights[keep]
503
+ source_views, source_masks = source_views[keep], source_masks[keep]
504
+ return FusionResult(points, colors, weights, source_views, source_masks)
505
+
506
+
507
+ def fusion_metrics(result: FusionResult) -> dict[str, float | int]:
508
+ if not len(result.points):
509
+ return {
510
+ "point_count": 0,
511
+ "confidence_mean": 0.0,
512
+ "confidence_p95": 0.0,
513
+ "dominant_source_view_count": 0,
514
+ "supported_source_view_count": 0,
515
+ "multi_view_voxel_fraction": 0.0,
516
+ }
517
+ supported_mask = int(np.bitwise_or.reduce(result.source_masks))
518
+ multi_view = np.fromiter(
519
+ (int(mask).bit_count() > 1 for mask in result.source_masks),
520
+ dtype=bool,
521
+ count=len(result.source_masks),
522
+ )
523
+ return {
524
+ "point_count": int(len(result.points)),
525
+ "confidence_mean": float(result.weights.mean()),
526
+ "confidence_p95": float(np.percentile(result.weights, 95)),
527
+ "dominant_source_view_count": int(len(np.unique(result.source_views))),
528
+ "supported_source_view_count": supported_mask.bit_count(),
529
+ "multi_view_voxel_fraction": float(multi_view.mean()),
530
+ }
531
+
532
+
533
+ def classify_fusion_support(
534
+ metrics: dict[str, float | int],
535
+ view_count: int,
536
+ unique_view_count: int | None = None,
537
+ pose_source: str | None = None,
538
+ near_duplicate_pair_count: int = 0,
539
+ ) -> str:
540
+ """Classify support without overstating duplicate or synthetic-pose evidence."""
541
+ if int(view_count) < 2:
542
+ return "single_view_baseline"
543
+ if unique_view_count is not None and int(unique_view_count) < int(view_count):
544
+ return "duplicate_input_support"
545
+ if int(near_duplicate_pair_count) > 0:
546
+ return "near_duplicate_input_support"
547
+ if pose_source is not None and pose_source != "depth_anything_3":
548
+ return "synthetic_prior_support"
549
+ fraction = float(metrics.get("multi_view_voxel_fraction", 0.0))
550
+ if fraction >= 0.5:
551
+ return "strong_multi_view_support"
552
+ if fraction >= 0.1:
553
+ return "partial_multi_view_support"
554
+ return "low_multi_view_support"
555
+
556
+
557
+ def filter_fusion_by_support(result: FusionResult, minimum_views: int) -> FusionResult:
558
+ """Retain only voxels supported by at least ``minimum_views`` source views."""
559
+ minimum_views = int(minimum_views)
560
+ if minimum_views <= 1 or not len(result.points):
561
+ return result
562
+ keep = np.fromiter(
563
+ (int(mask).bit_count() >= minimum_views for mask in result.source_masks),
564
+ dtype=bool,
565
+ count=len(result.source_masks),
566
+ )
567
+ return FusionResult(
568
+ result.points[keep], result.colors[keep], result.weights[keep],
569
+ result.source_views[keep], result.source_masks[keep],
570
+ )
571
+
572
+
573
+ def input_diversity_metrics(
574
+ input_hashes: list[str] | tuple[str, ...], near_duplicate_pair_count: int = 0
575
+ ) -> dict[str, int | bool | str]:
576
+ """Describe whether submitted views contain duplicate normalized images.
577
+
578
+ A repeated image can still exercise batching and export code, but it is not
579
+ evidence of additional visual coverage. Keeping this diagnostic beside the
580
+ fusion metrics prevents a multi-view run from being over-interpreted.
581
+ """
582
+ hashes = [str(value) for value in input_hashes]
583
+ unique_count = len(set(hashes))
584
+ duplicate_count = max(0, len(hashes) - unique_count)
585
+ near_duplicate_pair_count = max(0, int(near_duplicate_pair_count))
586
+ if duplicate_count:
587
+ status = "duplicate_inputs"
588
+ elif near_duplicate_pair_count:
589
+ status = "near_duplicate_inputs"
590
+ else:
591
+ status = "distinct_inputs"
592
+ return {
593
+ "input_view_count": len(hashes),
594
+ "unique_input_view_count": unique_count,
595
+ "duplicate_input_view_count": duplicate_count,
596
+ "near_duplicate_pair_count": near_duplicate_pair_count,
597
+ "has_duplicate_input_views": duplicate_count > 0,
598
+ "input_diversity_status": status,
599
+ }
600
+
601
+
602
+ def gaussian_initialization(weights: np.ndarray | None, point_count: int) -> tuple[np.ndarray, np.ndarray]:
603
+ """Map confidence weights to initial opacity and isotropic log-scales.
604
+
605
+ This is deliberately a lightweight initialization heuristic. It does not
606
+ claim to replace a learned Gaussian optimizer.
607
+ """
608
+ if weights is None or len(weights) != point_count:
609
+ normalized = np.ones(point_count, dtype=np.float32)
610
+ else:
611
+ normalized = np.clip(np.asarray(weights, dtype=np.float32), 0.0, 1.0)
612
+ opacity = 0.05 + 0.90 * normalized
613
+ log_scale = -4.605 + 0.8 * (1.0 - normalized)
614
+ return opacity, log_scale
615
+
616
+
617
+ def write_confidence_ply(
618
+ path: str | Path,
619
+ points: np.ndarray,
620
+ colors: np.ndarray,
621
+ confidence: np.ndarray,
622
+ source_views: np.ndarray | None = None,
623
+ source_masks: np.ndarray | None = None,
624
+ ) -> None:
625
+ """Write an ASCII PLY retaining confidence and optional source provenance."""
626
+ points = np.asarray(points, dtype=np.float32)
627
+ colors = np.asarray(colors, dtype=np.uint8)[..., :3]
628
+ confidence = np.asarray(confidence, dtype=np.float32)
629
+ if points.ndim != 2 or points.shape[1] != 3 or colors.shape != (len(points), 3):
630
+ raise ValueError("points and colors must contain matching Nx3 arrays")
631
+ if confidence.shape != (len(points),):
632
+ raise ValueError("confidence must contain one value per point")
633
+ if source_views is None:
634
+ source_views = np.full(len(points), -1, dtype=np.int32)
635
+ source_views = np.asarray(source_views, dtype=np.int32)
636
+ if source_views.shape != (len(points),):
637
+ raise ValueError("source_views must contain one value per point")
638
+ if source_masks is None:
639
+ source_masks = np.where(source_views >= 0, 1 << source_views, 0).astype(np.int32)
640
+ source_masks = np.asarray(source_masks, dtype=np.int32)
641
+ if source_masks.shape != (len(points),):
642
+ raise ValueError("source_masks must contain one value per point")
643
+ header = [
644
+ "ply", "format ascii 1.0", f"element vertex {len(points)}",
645
+ "property float x", "property float y", "property float z",
646
+ "property uchar red", "property uchar green", "property uchar blue",
647
+ "property float confidence", "property int source_view", "property int source_mask", "end_header",
648
+ ]
649
+ with Path(path).open("w", encoding="utf-8") as handle:
650
+ handle.write("\n".join(header) + "\n")
651
+ for point, color, score, source_view, source_mask in zip(points, colors, confidence, source_views, source_masks):
652
+ handle.write(
653
+ "{:.7g} {:.7g} {:.7g} {} {} {} {:.7g} {} {}\n".format(
654
+ *point, *color, float(score), int(source_view), int(source_mask)
655
+ )
656
+ )
657
+
658
+
659
+ def write_gaussian_ply(
660
+ path: str | Path,
661
+ points: np.ndarray,
662
+ colors: np.ndarray,
663
+ weights: np.ndarray | None = None,
664
+ source_views: np.ndarray | None = None,
665
+ source_masks: np.ndarray | None = None,
666
+ scales: np.ndarray | None = None,
667
+ rotations: np.ndarray | None = None,
668
+ opacities: np.ndarray | None = None,
669
+ ) -> None:
670
+ """Write a 3DGS PLY with evidence fields.
671
+
672
+ When direct Gaussian parameters are supplied, preserve their scales,
673
+ rotations, and opacities. Otherwise initialize those fields from the
674
+ confidence weights for the portable depth-to-Gaussian baseline.
675
+ """
676
+ points = np.asarray(points, dtype=np.float32)
677
+ colors = np.asarray(colors, dtype=np.uint8)[..., :3]
678
+ if points.ndim != 2 or points.shape[1] != 3 or colors.shape != (len(points), 3):
679
+ raise ValueError("points and colors must contain matching Nx3 arrays")
680
+ if scales is None and rotations is None and opacities is None:
681
+ opacity, log_scale = gaussian_initialization(weights, len(points))
682
+ log_scale = np.repeat(log_scale[:, None], 3, axis=1)
683
+ rotations = np.zeros((len(points), 4), dtype=np.float32)
684
+ rotations[:, 0] = 1.0
685
+ else:
686
+ if scales is None or rotations is None or opacities is None:
687
+ raise ValueError("scales, rotations, and opacities must be supplied together")
688
+ scales = np.asarray(scales, dtype=np.float32)
689
+ rotations = np.asarray(rotations, dtype=np.float32)
690
+ opacity = np.asarray(opacities, dtype=np.float32)
691
+ if scales.shape != (len(points), 3) or rotations.shape != (len(points), 4) or opacity.shape != (len(points),):
692
+ raise ValueError("direct Gaussian parameters must have shapes Nx3, Nx4, and N")
693
+ if not np.isfinite(scales).all() or not np.isfinite(rotations).all() or not np.isfinite(opacity).all():
694
+ raise ValueError("direct Gaussian parameters must be finite")
695
+ # DA3 exposes standard deviations; the PLY convention stores log scales.
696
+ log_scale = np.log(np.clip(np.abs(scales), 1e-6, None))
697
+ opacity = np.clip(opacity, 0.0, 1.0)
698
+ rotation_norm = np.linalg.norm(rotations, axis=1, keepdims=True)
699
+ rotations = rotations / np.clip(rotation_norm, 1e-8, None)
700
+ if weights is None or len(weights) != len(points):
701
+ exported_confidence = np.ones(len(points), dtype=np.float32)
702
+ else:
703
+ exported_confidence = np.clip(np.asarray(weights, dtype=np.float32), 0.0, 1.0)
704
+ if source_views is None or len(source_views) != len(points):
705
+ source_views = np.full(len(points), -1, dtype=np.int32)
706
+ else:
707
+ source_views = np.asarray(source_views, dtype=np.int32)
708
+ if source_masks is None:
709
+ source_masks = np.where(source_views >= 0, 1 << source_views, 0).astype(np.int32)
710
+ source_masks = np.asarray(source_masks, dtype=np.int32)
711
+ if source_masks.shape != (len(points),):
712
+ raise ValueError("source_masks must contain one value per point")
713
+ dc = (colors.astype(np.float32) / 255.0 - 0.5) / 0.2820947918
714
+ header = [
715
+ "ply", "format ascii 1.0", f"element vertex {len(points)}",
716
+ "property float x", "property float y", "property float z",
717
+ "property float nx", "property float ny", "property float nz",
718
+ "property float f_dc_0", "property float f_dc_1", "property float f_dc_2",
719
+ "property float opacity", "property float scale_0", "property float scale_1",
720
+ "property float scale_2", "property float rot_0", "property float rot_1",
721
+ "property float rot_2", "property float rot_3",
722
+ "property float confidence", "property int source_view", "property int source_mask", "end_header",
723
+ ]
724
+ with Path(path).open("w", encoding="utf-8") as handle:
725
+ handle.write("\n".join(header) + "\n")
726
+ for point, color, alpha, scale, rotation, score, source_view, source_mask in zip(
727
+ points, dc, opacity, log_scale, rotations, exported_confidence, source_views, source_masks
728
+ ):
729
+ numeric = [*point, 0.0, 0.0, 0.0, *color, float(alpha), *scale, *rotation, float(score)]
730
+ fields = [f"{float(value):.7g}" for value in numeric]
731
+ fields.extend((str(int(source_view)), str(int(source_mask))))
732
+ handle.write(" ".join(fields) + "\n")
sitecustomize.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Keep hosted Space logs UTF-8 even when the base image advertises a charmap."""
2
+
3
+ import sys
4
+
5
+
6
+ for _stream in (sys.stdout, sys.stderr):
7
+ if hasattr(_stream, "reconfigure"):
8
+ _stream.reconfigure(encoding="utf-8", errors="replace")
validate_manifest.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate a Simam3D run manifest and its exported artifact fingerprints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+
11
+ def _version_at_least(version: object, required: tuple[int, int, int]) -> bool:
12
+ try:
13
+ parts = tuple(int(part) for part in str(version).split(".")[:3])
14
+ except (TypeError, ValueError):
15
+ return False
16
+ return parts >= required
17
+
18
+
19
+ def _safe_int(value: object, default: int | None = None) -> int | None:
20
+ try:
21
+ return int(value)
22
+ except (TypeError, ValueError, OverflowError):
23
+ return default
24
+
25
+
26
+ def file_sha256(path: Path) -> str:
27
+ digest = hashlib.sha256()
28
+ with path.open("rb") as handle:
29
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
30
+ digest.update(chunk)
31
+ return digest.hexdigest()
32
+
33
+
34
+ def validate_manifest(manifest_path: str | Path) -> tuple[bool, list[str]]:
35
+ manifest_path = Path(manifest_path)
36
+ errors: list[str] = []
37
+ try:
38
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
39
+ except (OSError, json.JSONDecodeError) as exc:
40
+ return False, [f"manifest unreadable: {exc}"]
41
+ if manifest.get("project") != "Simam3D":
42
+ errors.append("project is not Simam3D")
43
+ schema_version = _safe_int(manifest.get("manifest_schema_version", 0), 0)
44
+ if schema_version < 3:
45
+ errors.append("manifest schema is older than provenance-contract schema 3")
46
+ if manifest.get("status") == "failed":
47
+ required = {"run_id", "backend", "runtime", "stage", "error", "input_sha256"}
48
+ missing = sorted(key for key in required if key not in manifest)
49
+ if missing:
50
+ errors.append(f"failure manifest missing fields: {', '.join(missing)}")
51
+ if not isinstance(manifest.get("error"), dict):
52
+ errors.append("failure manifest error field is invalid")
53
+ elif not all(manifest["error"].get(key) for key in ("type", "message")):
54
+ errors.append("failure manifest error type/message is incomplete")
55
+ claims = manifest.get("claims")
56
+ if not isinstance(claims, dict) or claims.get("failure_report_only") is not True:
57
+ errors.append("failure manifest must declare failure_report_only")
58
+ return not errors, errors
59
+ claims = manifest.get("claims")
60
+ required_claims = {
61
+ "observed_input_geometry",
62
+ "generated_novel_views",
63
+ "metric_scale_reconstruction",
64
+ "learned_gaussian_optimization",
65
+ "reveal_content_is_verified",
66
+ }
67
+ if not isinstance(claims, dict) or not required_claims.issubset(claims):
68
+ errors.append("claims provenance contract is missing or incomplete")
69
+ if _version_at_least(manifest.get("version"), (0, 4, 1)):
70
+ metrics = manifest.get("metrics")
71
+ if not isinstance(metrics, dict):
72
+ errors.append("version 0.4.1+ manifest is missing metrics")
73
+ else:
74
+ if claims.get("generated_novel_views") is True and not metrics.get("novel_view_evidence"):
75
+ errors.append("novel-view claim has no novel_view_evidence record")
76
+ if claims.get("metric_scale_reconstruction") is True and not metrics.get("metric_scale_evidence"):
77
+ errors.append("metric-scale claim has no metric_scale_evidence record")
78
+ if claims.get("reveal_content_is_verified") is True and not metrics.get("reveal_verification"):
79
+ errors.append("verified reveal claim has no reveal_verification record")
80
+ diversity = metrics.get("input_diversity")
81
+ if not isinstance(diversity, dict):
82
+ errors.append("metrics.input_diversity is missing")
83
+ else:
84
+ expected_views = _safe_int(manifest.get("view_count", -1), -1)
85
+ if diversity.get("input_view_count") != expected_views:
86
+ errors.append("input diversity view count does not match manifest view_count")
87
+ unique = diversity.get("unique_input_view_count")
88
+ duplicates = diversity.get("duplicate_input_view_count")
89
+ near_duplicates = diversity.get("near_duplicate_pair_count")
90
+ if not isinstance(unique, int) or not isinstance(duplicates, int):
91
+ errors.append("input diversity counts are invalid")
92
+ elif unique + duplicates != expected_views:
93
+ errors.append("input diversity counts do not add up to view_count")
94
+ if not isinstance(near_duplicates, int) or near_duplicates < 0:
95
+ errors.append("near-duplicate pair count is invalid")
96
+ near_duplicate_value = near_duplicates if isinstance(near_duplicates, int) else 0
97
+ expected_status = (
98
+ "duplicate_inputs" if duplicates > 0
99
+ else "near_duplicate_inputs" if near_duplicate_value > 0
100
+ else "distinct_inputs"
101
+ )
102
+ if diversity.get("input_diversity_status") != expected_status:
103
+ errors.append("input diversity status is inconsistent with duplicate count")
104
+ fusion = metrics.get("fusion")
105
+ valid_support_statuses = {
106
+ "strong_multi_view_support", "partial_multi_view_support",
107
+ "low_multi_view_support", "duplicate_input_support",
108
+ "near_duplicate_input_support", "synthetic_prior_support",
109
+ "single_view_baseline",
110
+ }
111
+ if not isinstance(fusion, dict) or fusion.get("support_status") not in valid_support_statuses:
112
+ errors.append("metrics.fusion.support_status is missing or invalid")
113
+ elif isinstance(diversity, dict):
114
+ support_status = fusion["support_status"]
115
+ pose_source = metrics.get("pose_source")
116
+ if expected_views < 2:
117
+ expected_support = "single_view_baseline"
118
+ elif duplicates > 0:
119
+ expected_support = "duplicate_input_support"
120
+ elif near_duplicate_value > 0:
121
+ expected_support = "near_duplicate_input_support"
122
+ elif pose_source is not None and pose_source != "depth_anything_3":
123
+ expected_support = "synthetic_prior_support"
124
+ else:
125
+ expected_support = None
126
+ if expected_support is not None and support_status != expected_support:
127
+ errors.append("fusion support status is inconsistent with input or pose provenance")
128
+ gaussian_source = metrics.get("gaussian_source")
129
+ direct_gaussian_error = metrics.get("direct_gaussian_error")
130
+ if claims.get("direct_gaussian_prediction") is True:
131
+ if gaussian_source != "da3_direct":
132
+ errors.append("direct Gaussian claim does not match gaussian_source")
133
+ exported_count = _safe_int(metrics.get("direct_gaussian_exported_count", 0), 0)
134
+ if exported_count <= 0:
135
+ errors.append("direct Gaussian claim has no exported Gaussian count")
136
+ if direct_gaussian_error:
137
+ errors.append("direct Gaussian claim cannot include an export error")
138
+ elif gaussian_source == "da3_direct":
139
+ errors.append("gaussian_source is direct but direct Gaussian claim is false")
140
+ outputs = manifest.get("outputs")
141
+ hashes = manifest.get("output_sha256")
142
+ if not isinstance(outputs, list) or not isinstance(hashes, dict):
143
+ return False, errors + ["outputs/output_sha256 fields are missing or invalid"]
144
+ for raw_output in outputs:
145
+ output = Path(str(raw_output))
146
+ if not output.is_absolute() and not output.is_file():
147
+ sibling = manifest_path.parent / output
148
+ if sibling.is_file():
149
+ output = sibling
150
+ if not output.is_file():
151
+ errors.append(f"missing artifact: {raw_output}")
152
+ continue
153
+ expected = hashes.get(str(raw_output)) or hashes.get(output.name)
154
+ if not expected:
155
+ errors.append(f"missing hash: {output.name}")
156
+ continue
157
+ actual = file_sha256(output)
158
+ if actual != expected:
159
+ errors.append(f"hash mismatch: {output.name}")
160
+ return not errors, errors
161
+
162
+
163
+ def main(argv: list[str] | None = None) -> int:
164
+ argv = argv or sys.argv[1:]
165
+ if len(argv) != 1:
166
+ print("usage: python validate_manifest.py PATH_TO_RUN_JSON", file=sys.stderr)
167
+ return 2
168
+ valid, errors = validate_manifest(argv[0])
169
+ if valid:
170
+ print("VALID: all Simam3D artifacts match manifest fingerprints")
171
+ return 0
172
+ print("INVALID")
173
+ for error in errors:
174
+ print(f"- {error}")
175
+ return 1
176
+
177
+
178
+ if __name__ == "__main__":
179
+ raise SystemExit(main())