junaid-simamdigital commited on
Commit
10bfddb
·
verified ·
1 Parent(s): 0dc7ae1

Initial ZeroGPU Simam3D runtime

Browse files
Files changed (1) hide show
  1. app.py +765 -0
app.py ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import gradio as gr
16
+ import matplotlib.cm as cm
17
+ import numpy as np
18
+ import torch
19
+ import trimesh
20
+ from PIL import Image, ImageDraw, ImageOps
21
+ from transformers import pipeline
22
+
23
+ try:
24
+ import spaces
25
+ GPU_FUNCTION = spaces.GPU(duration=120)
26
+ except (ImportError, AttributeError, TypeError):
27
+ def GPU_FUNCTION(function):
28
+ return function
29
+ from simam3d_core import (
30
+ analyze_light_field,
31
+ classify_scene_hypothesis,
32
+ deterministic_demo_depth,
33
+ estimate_depth_light,
34
+ fuse_point_views,
35
+ fusion_metrics,
36
+ next_view_plan,
37
+ normalize_prediction_contract,
38
+ orbit_project_points,
39
+ project_world_points,
40
+ reprojection_consistency,
41
+ reveal_uncertainty,
42
+ synthetic_orbit_poses,
43
+ write_confidence_ply,
44
+ write_gaussian_ply,
45
+ )
46
+ from da3_compat import resolve_da3_class
47
+
48
+
49
+ MODEL_ID = os.getenv("SIMAM3D_DEPTH_MODEL", "depth-anything/Depth-Anything-V2-Small-hf")
50
+ DA3_MODEL_ID = os.getenv("SIMAM3D_DA3_MODEL", "depth-anything/DA3-LARGE")
51
+ SIMAM3D_VERSION = "0.3.0"
52
+ MANIFEST_SCHEMA_VERSION = 3
53
+ OUTPUT_DIR = Path("output")
54
+ MAX_VIEWS = int(os.getenv("SIMAM3D_MAX_VIEWS", "8"))
55
+ MAX_INPUT_SIDE = int(os.getenv("SIMAM3D_MAX_INPUT_SIDE", "1536"))
56
+ FUSION_VOXEL_SIZE = float(os.getenv("SIMAM3D_FUSION_VOXEL_SIZE", "0.02"))
57
+ FUSION_MAX_POINTS = int(os.getenv("SIMAM3D_FUSION_MAX_POINTS", "150000"))
58
+ DEPTH_PIPELINE = None
59
+ DA3_MODEL = None
60
+ PIPELINE_LOCK = threading.Lock()
61
+ INFERENCE_LOCK = threading.Lock()
62
+
63
+
64
+ def runtime_label() -> str:
65
+ if torch.cuda.is_available():
66
+ return f"CUDA GPU ({torch.cuda.get_device_name(0)})"
67
+ return "CPU"
68
+
69
+
70
+ def get_depth_pipeline():
71
+ global DEPTH_PIPELINE
72
+ if DEPTH_PIPELINE is not None:
73
+ return DEPTH_PIPELINE
74
+ with PIPELINE_LOCK:
75
+ if DEPTH_PIPELINE is None:
76
+ # Keep only one heavyweight backend resident when users switch
77
+ # between DA3 and V2 in a long-lived Space process.
78
+ clear_da3_model()
79
+ device = 0 if torch.cuda.is_available() else -1
80
+ DEPTH_PIPELINE = pipeline("depth-estimation", model=MODEL_ID, device=device)
81
+ return DEPTH_PIPELINE
82
+
83
+
84
+ def get_da3_model():
85
+ global DA3_MODEL
86
+ if DA3_MODEL is not None:
87
+ return DA3_MODEL
88
+ with PIPELINE_LOCK:
89
+ if DA3_MODEL is None:
90
+ clear_depth_pipeline()
91
+ DepthAnything3, _ = load_da3_class()
92
+
93
+ device = "cuda" if torch.cuda.is_available() else "cpu"
94
+ DA3_MODEL = DepthAnything3.from_pretrained(DA3_MODEL_ID).to(device)
95
+ DA3_MODEL.eval()
96
+ return DA3_MODEL
97
+
98
+
99
+ def clear_da3_model():
100
+ global DA3_MODEL
101
+ DA3_MODEL = None
102
+ if torch.cuda.is_available():
103
+ torch.cuda.empty_cache()
104
+
105
+
106
+ def clear_depth_pipeline():
107
+ """Release the Transformers V2 pipeline before loading another backend."""
108
+ global DEPTH_PIPELINE
109
+ DEPTH_PIPELINE = None
110
+ if torch.cuda.is_available():
111
+ torch.cuda.empty_cache()
112
+
113
+
114
+ def make_depth_preview(depth: np.ndarray) -> Image.Image:
115
+ depth = (depth - depth.min()) / max(float(depth.max() - depth.min()), 1e-6)
116
+ rgb = (cm.get_cmap("magma")(1.0 - depth)[..., :3] * 255).astype(np.uint8)
117
+ return Image.fromarray(rgb)
118
+
119
+
120
+ def make_confidence_preview(confidence: np.ndarray) -> Image.Image:
121
+ confidence = np.asarray(confidence, dtype=np.float32)
122
+ confidence = np.nan_to_num(confidence, nan=0.0, posinf=1.0, neginf=0.0)
123
+ confidence = (confidence - confidence.min()) / max(float(confidence.max() - confidence.min()), 1e-6)
124
+ rgb = (cm.get_cmap("viridis")(confidence)[..., :3] * 255).astype(np.uint8)
125
+ return Image.fromarray(rgb)
126
+
127
+
128
+ def make_uncertainty_preview(uncertainty: np.ndarray) -> Image.Image:
129
+ uncertainty = np.clip(np.nan_to_num(np.asarray(uncertainty, dtype=np.float32)), 0.0, 1.0)
130
+ rgb = (cm.get_cmap("inferno")(uncertainty)[..., :3] * 255).astype(np.uint8)
131
+ return Image.fromarray(rgb)
132
+
133
+
134
+ def make_evidence_card(image, depth, confidence, backend, view_count, fusion_stats, run_id):
135
+ """Create a compact, shareable diagnostic card for each reconstruction run."""
136
+ tile_size = (480, 300)
137
+ source = ImageOps.contain(image.convert("RGB"), tile_size)
138
+ depth_tile = ImageOps.contain(make_depth_preview(depth).convert("RGB"), tile_size)
139
+ confidence_tile = ImageOps.contain(make_confidence_preview(confidence).convert("RGB"), tile_size)
140
+ canvas = Image.new("RGB", (960, 700), (12, 16, 28))
141
+ draw = ImageDraw.Draw(canvas)
142
+ draw.text((24, 18), "SIMAM3D · EVIDENCE CARD", fill=(235, 240, 255))
143
+ draw.text(
144
+ (24, 46),
145
+ f"{backend} · {view_count} view(s) · {runtime_label()}",
146
+ fill=(164, 178, 205),
147
+ )
148
+ tiles = [(source, (0, 90), "SOURCE"), (depth_tile, (480, 90), "DEPTH"),
149
+ (confidence_tile, (0, 390), "CONFIDENCE")]
150
+ for tile, origin, label in tiles:
151
+ x, y = origin
152
+ canvas.paste(tile, (x, y))
153
+ draw.rectangle((x, y, x + tile.width, y + tile.height), outline=(76, 93, 126), width=2)
154
+ draw.text((x + 12, y + 12), label, fill=(255, 255, 255))
155
+ draw.text(
156
+ (500, 410),
157
+ f"FUSED POINTS\n{fusion_stats['point_count']:,}\n\n"
158
+ f"DOMINANT SOURCE VIEWS\n{fusion_stats['dominant_source_view_count']}\n\n"
159
+ f"SUPPORTED SOURCE VIEWS\n{fusion_stats['supported_source_view_count']}\n\n"
160
+ f"MULTI-VIEW VOXELS\n{fusion_stats['multi_view_voxel_fraction']:.1%}\n\n"
161
+ f"CONFIDENCE MEAN\n{fusion_stats['confidence_mean']:.3f}\n\n"
162
+ f"CONFIDENCE P95\n{fusion_stats['confidence_p95']:.3f}",
163
+ fill=(210, 220, 240),
164
+ spacing=8,
165
+ )
166
+ OUTPUT_DIR.mkdir(exist_ok=True)
167
+ path = OUTPUT_DIR / f"simam3d_{run_id}_evidence_card.png"
168
+ canvas.save(path, optimize=True)
169
+ return str(path)
170
+
171
+
172
+ def make_reveal_card(image, depth, guess, lighting, run_id: str) -> str:
173
+ """Create a social-friendly reveal card while clearly separating inference from fact."""
174
+ tile_size = (480, 300)
175
+ source = ImageOps.contain(image.convert("RGB"), tile_size)
176
+ depth_tile = ImageOps.contain(make_depth_preview(depth).convert("RGB"), tile_size)
177
+ canvas = Image.new("RGB", (960, 760), (12, 16, 28))
178
+ draw = ImageDraw.Draw(canvas)
179
+ draw.text((24, 18), "SIMAM3D · WHAT'S BEHIND THE IMAGE?", fill=(235, 240, 255))
180
+ draw.text((24, 48), "Depth and illumination reveal · hypothesis, not ground truth", fill=(164, 178, 205))
181
+ canvas.paste(source, (0, 90))
182
+ canvas.paste(depth_tile, (480, 90))
183
+ draw.rectangle((0, 90, 480, 390), outline=(76, 93, 126), width=2)
184
+ draw.rectangle((480, 90, 960, 390), outline=(76, 93, 126), width=2)
185
+ draw.text((14, 104), "ORIGINAL", fill=(255, 255, 255))
186
+ draw.text((494, 104), "DEPTH REVEAL", fill=(255, 255, 255))
187
+ guess_text = str(guess["user_guess"])
188
+ cues = ", ".join(str(item) for item in guess["semantic_cues"])
189
+ lighting_text = (
190
+ f"LIGHT FIELD: {lighting['lighting_label']}\n"
191
+ f"Direction estimate: azimuth {lighting['estimated_azimuth_deg']:.0f}°, "
192
+ f"elevation {lighting['estimated_elevation_deg']:.0f}°\n"
193
+ f"Detector confidence: {lighting['detector_confidence']:.2f}"
194
+ )
195
+ draw.text((24, 430), "YOUR GUESS", fill=(133, 214, 255))
196
+ draw.text((24, 456), guess_text[:110], fill=(235, 240, 255))
197
+ draw.text((24, 500), f"SEMANTIC CUES: {cues}", fill=(210, 220, 240))
198
+ draw.text((24, 560), lighting_text, fill=(210, 220, 240), spacing=8)
199
+ draw.text((24, 690), "The unseen side is a research hypothesis; add views for evidence.", fill=(255, 190, 120))
200
+ OUTPUT_DIR.mkdir(exist_ok=True)
201
+ path = OUTPUT_DIR / f"simam3d_{run_id}_reveal_card.png"
202
+ canvas.save(path, optimize=True)
203
+ return str(path)
204
+
205
+
206
+ def depth_to_glb(image: Image.Image, depth: np.ndarray, run_id: str) -> str:
207
+ image = image.convert("RGB")
208
+ max_side = 192
209
+ scale = min(1.0, max_side / max(image.size))
210
+ size = (max(8, int(image.width * scale)), max(8, int(image.height * scale)))
211
+ rgb = np.asarray(image.resize(size, Image.Resampling.LANCZOS))
212
+ d = Image.fromarray(depth).resize(size, Image.Resampling.BILINEAR)
213
+ d = np.asarray(d, dtype=np.float32)
214
+ d = (d - d.min()) / max(float(d.max() - d.min()), 1e-6)
215
+
216
+ h, w = d.shape
217
+ yy, xx = np.mgrid[0:h, 0:w]
218
+ x = (xx / max(w - 1, 1) - 0.5) * 2.0
219
+ y = (0.5 - yy / max(h - 1, 1)) * 2.0
220
+ z = (1.0 - d) * 0.9
221
+ vertices = np.stack([x, y, z], axis=-1).reshape(-1, 3)
222
+ faces = []
223
+ for row in range(h - 1):
224
+ for col in range(w - 1):
225
+ i = row * w + col
226
+ faces.extend([[i, i + 1, i + w], [i + 1, i + w + 1, i + w]])
227
+ mesh = trimesh.Trimesh(vertices=vertices, faces=np.asarray(faces), process=False)
228
+ mesh.visual.vertex_colors = np.concatenate(
229
+ [rgb.reshape(-1, 3), np.full((vertices.shape[0], 1), 255, dtype=np.uint8)], axis=1
230
+ )
231
+ OUTPUT_DIR.mkdir(exist_ok=True)
232
+ path = OUTPUT_DIR / f"simam3d_{run_id}.glb"
233
+ mesh.export(path)
234
+ return str(path)
235
+
236
+
237
+ def depth_to_pointcloud(image: Image.Image, depth: np.ndarray, confidence: np.ndarray, run_id: str) -> str:
238
+ """Export the current depth scaffold as a colored PLY point cloud."""
239
+ image = image.convert("RGB")
240
+ max_side = 384
241
+ scale = min(1.0, max_side / max(image.size))
242
+ size = (max(8, int(image.width * scale)), max(8, int(image.height * scale)))
243
+ rgb = np.asarray(image.resize(size, Image.Resampling.LANCZOS))
244
+ d = np.asarray(Image.fromarray(depth).resize(size, Image.Resampling.BILINEAR), dtype=np.float32)
245
+ d = (d - d.min()) / max(float(d.max() - d.min()), 1e-6)
246
+ h, w = d.shape
247
+ yy, xx = np.mgrid[0:h, 0:w]
248
+ points = np.stack(
249
+ [(xx / max(w - 1, 1) - 0.5) * 2.0, (0.5 - yy / max(h - 1, 1)) * 2.0, (1.0 - d) * 0.9],
250
+ axis=-1,
251
+ ).reshape(-1, 3)
252
+ confidence = np.asarray(
253
+ Image.fromarray(np.asarray(confidence, dtype=np.float32)).resize(size, Image.Resampling.BILINEAR),
254
+ dtype=np.float32,
255
+ )
256
+ confidence = np.nan_to_num(confidence, nan=0.0, posinf=0.0, neginf=0.0)
257
+ peak = float(max(confidence.max(), 0.0)) if confidence.size else 0.0
258
+ confidence = confidence / peak if peak > 1e-6 else np.ones_like(confidence)
259
+ OUTPUT_DIR.mkdir(exist_ok=True)
260
+ path = OUTPUT_DIR / f"simam3d_{run_id}.ply"
261
+ write_confidence_ply(path, points, rgb.reshape(-1, 3), confidence.reshape(-1))
262
+ return str(path)
263
+
264
+
265
+ def save_prediction_npz(depth, confidence, extrinsics, intrinsics, run_id: str) -> str:
266
+ OUTPUT_DIR.mkdir(exist_ok=True)
267
+ path = OUTPUT_DIR / f"simam3d_{run_id}.npz"
268
+ np.savez_compressed(
269
+ path,
270
+ depth=np.asarray(depth, dtype=np.float32),
271
+ confidence=np.asarray(confidence, dtype=np.float32),
272
+ extrinsics=np.asarray(extrinsics, dtype=np.float32),
273
+ intrinsics=np.asarray(intrinsics, dtype=np.float32),
274
+ )
275
+ return str(path)
276
+
277
+
278
+ def save_uncertainty_map(uncertainty: np.ndarray, run_id: str) -> str:
279
+ OUTPUT_DIR.mkdir(exist_ok=True)
280
+ path = OUTPUT_DIR / f"simam3d_{run_id}_reveal_uncertainty.png"
281
+ make_uncertainty_preview(uncertainty).save(path, optimize=True)
282
+ return str(path)
283
+
284
+
285
+ def save_turntable_gif(points: np.ndarray, colors: np.ndarray, run_id: str) -> str:
286
+ """Render a lightweight, dependency-free orbit preview from fused points."""
287
+ points = np.asarray(points, dtype=np.float32)
288
+ colors = np.asarray(colors, dtype=np.uint8)[..., :3]
289
+ if len(points) != len(colors):
290
+ raise ValueError("turntable points and colors must have matching lengths")
291
+ if len(points) > 12000:
292
+ keep = np.linspace(0, len(points) - 1, 12000, dtype=np.int64)
293
+ points, colors = points[keep], colors[keep]
294
+ frames = []
295
+ size = 512
296
+ for yaw in np.linspace(0.0, 330.0, 12):
297
+ xy, depth = orbit_project_points(points, float(yaw))
298
+ frame = Image.new("RGB", (size, size), (9, 12, 22))
299
+ draw = ImageDraw.Draw(frame)
300
+ order = np.argsort(depth)
301
+ for index in order:
302
+ x = int((float(xy[index, 0]) * 0.43 + 0.5) * size)
303
+ y = int((0.5 - float(xy[index, 1]) * 0.43) * size)
304
+ if 0 <= x < size and 0 <= y < size:
305
+ radius = 1 if len(points) > 4000 else 2
306
+ color = tuple(int(value) for value in colors[index])
307
+ draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=color)
308
+ draw.text((16, 16), f"SIMAM3D · {float(yaw):.0f}°", fill=(235, 240, 255))
309
+ frames.append(frame)
310
+ OUTPUT_DIR.mkdir(exist_ok=True)
311
+ path = OUTPUT_DIR / f"simam3d_{run_id}_turntable.gif"
312
+ frames[0].save(path, save_all=True, append_images=frames[1:], duration=100, loop=0, optimize=True)
313
+ return str(path)
314
+
315
+
316
+ def save_run_manifest(run_id, backend, view_count, elapsed, outputs, metrics) -> str:
317
+ OUTPUT_DIR.mkdir(exist_ok=True)
318
+ path = OUTPUT_DIR / f"simam3d_{run_id}_run.json"
319
+ manifest = {
320
+ "project": "Simam3D",
321
+ "version": SIMAM3D_VERSION,
322
+ "manifest_schema_version": MANIFEST_SCHEMA_VERSION,
323
+ "run_id": run_id,
324
+ "backend": backend,
325
+ "model": (
326
+ DA3_MODEL_ID if backend.startswith("Depth Anything 3")
327
+ else "none (deterministic export smoke test)" if backend.startswith("Deterministic")
328
+ else MODEL_ID
329
+ ),
330
+ "runtime": runtime_label(),
331
+ "claims": {
332
+ "observed_input_geometry": True,
333
+ "generated_novel_views": False,
334
+ "metric_scale_reconstruction": False,
335
+ "learned_gaussian_optimization": False,
336
+ "depth_normal_light_is_heuristic": True,
337
+ "reveal_content_is_verified": False,
338
+ },
339
+ "software": {
340
+ "python": platform.python_version(),
341
+ "platform": platform.platform(),
342
+ "torch": getattr(torch, "__version__", "unknown"),
343
+ "gradio": getattr(gr, "__version__", "unknown"),
344
+ "numpy": np.__version__,
345
+ "python_implementation": sys.implementation.name,
346
+ },
347
+ "view_count": view_count,
348
+ "elapsed_seconds": round(elapsed, 3),
349
+ "metrics": metrics,
350
+ "outputs": outputs,
351
+ "output_sha256": {
352
+ Path(output).name: file_fingerprint(output)
353
+ for output in outputs
354
+ if Path(output).is_file()
355
+ },
356
+ }
357
+ path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
358
+ return str(path)
359
+
360
+
361
+ def predict_v2(images):
362
+ """Run the lightweight, widely compatible depth fallback for every view."""
363
+ depths = []
364
+ for view in images:
365
+ with torch.inference_mode():
366
+ result = get_depth_pipeline()(view)
367
+ predicted = result.get("predicted_depth")
368
+ if predicted is None:
369
+ raise RuntimeError(f"Depth model returned no predicted_depth field: {list(result)}")
370
+ depths.append(predicted.squeeze().detach().float().cpu().numpy().astype(np.float32))
371
+ return np.stack(depths, axis=0)
372
+
373
+
374
+ def fuse_views(images, depths, confidence, extrinsics, intrinsics, run_id: str):
375
+ """Fuse depth views into a confidence-weighted world-space PLY."""
376
+ views = []
377
+ for idx, (image, depth) in enumerate(zip(images, depths)):
378
+ depth = np.asarray(depth, dtype=np.float32)
379
+ h, w = depth.shape
380
+ colors = np.asarray(image.convert("RGB").resize((w, h), Image.Resampling.LANCZOS))
381
+ conf = np.asarray(confidence[idx], dtype=np.float32) if len(confidence) > idx else None
382
+ if conf is not None and conf.shape != depth.shape:
383
+ conf = np.asarray(Image.fromarray(conf).resize((w, h), Image.Resampling.BILINEAR))
384
+ camera_k = intrinsics[idx] if len(intrinsics) > idx else None
385
+ if camera_k is not None:
386
+ camera_k = np.asarray(camera_k, dtype=np.float32).copy()
387
+ source_w, source_h = image.size
388
+ if camera_k.shape == (3, 3) and source_w and source_h:
389
+ camera_k[0, :] *= w / source_w
390
+ camera_k[1, :] *= h / source_h
391
+ views.append((depth, conf, camera_k,
392
+ extrinsics[idx] if len(extrinsics) > idx else None, colors))
393
+ result = fuse_point_views(
394
+ views, voxel_size=FUSION_VOXEL_SIZE, max_points=FUSION_MAX_POINTS
395
+ )
396
+ OUTPUT_DIR.mkdir(exist_ok=True)
397
+ path = OUTPUT_DIR / f"simam3d_{run_id}_fused.ply"
398
+ write_confidence_ply(
399
+ path, result.points, result.colors, result.weights,
400
+ result.source_views, result.source_masks
401
+ )
402
+ return str(path), fusion_metrics(result), result.weights, result.source_views, result.source_masks
403
+
404
+
405
+ def pointcloud_to_gaussian_ply(pointcloud_path: str, run_id: str, weights=None, source_views=None, source_masks=None) -> str:
406
+ """Convert fused colored points to a confidence-initialized 3DGS PLY."""
407
+ cloud = trimesh.load(pointcloud_path, process=False)
408
+ points = np.asarray(cloud.vertices, dtype=np.float32)
409
+ colors = np.asarray(cloud.colors[:, :3], dtype=np.uint8)
410
+ OUTPUT_DIR.mkdir(exist_ok=True)
411
+ path = OUTPUT_DIR / f"simam3d_{run_id}_gaussians.ply"
412
+ write_gaussian_ply(path, points, colors, weights, source_views, source_masks)
413
+ return str(path)
414
+
415
+
416
+ def load_input_images(primary: Image.Image, extra_files) -> list[Image.Image]:
417
+ images = [primary.convert("RGB")]
418
+ for item in extra_files or []:
419
+ path = item if isinstance(item, str) else (
420
+ getattr(item, "path", None) or getattr(item, "name", None)
421
+ )
422
+ if path:
423
+ try:
424
+ with Image.open(path) as extra:
425
+ images.append(extra.convert("RGB").copy())
426
+ except (OSError, ValueError) as exc:
427
+ raise ValueError(f"Could not read additional view {path!r}: {exc}") from exc
428
+ if len(images) > MAX_VIEWS:
429
+ raise ValueError(f"At most {MAX_VIEWS} views are supported per run to protect hosted GPU memory.")
430
+ normalized = []
431
+ for current in images:
432
+ if max(current.size) > MAX_INPUT_SIDE:
433
+ scale = MAX_INPUT_SIDE / max(current.size)
434
+ size = (max(8, int(current.width * scale)), max(8, int(current.height * scale)))
435
+ current = current.resize(size, Image.Resampling.LANCZOS)
436
+ normalized.append(current)
437
+ return normalized
438
+
439
+
440
+ def image_fingerprint(image: Image.Image) -> str:
441
+ """Hash normalized RGB pixels so runs can be reproduced exactly."""
442
+ buffer = io.BytesIO()
443
+ image.convert("RGB").save(buffer, format="PNG", optimize=False)
444
+ return hashlib.sha256(buffer.getvalue()).hexdigest()
445
+
446
+
447
+ def file_fingerprint(path: str | Path) -> str:
448
+ """Hash an exported artifact in bounded chunks for manifest provenance."""
449
+ digest = hashlib.sha256()
450
+ with Path(path).open("rb") as handle:
451
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
452
+ digest.update(chunk)
453
+ return digest.hexdigest()
454
+
455
+
456
+ def da3_api_status() -> dict:
457
+ """Check the optional DA3 API without downloading weights or loading a model."""
458
+ try:
459
+ _, location = load_da3_class()
460
+ return {"installed": True, "importable": True, "api_location": location, "error": None}
461
+ except (ImportError, ModuleNotFoundError, AttributeError) as exc:
462
+ return {"installed": False, "importable": False, "api_location": None, "error": f"{type(exc).__name__}: {exc}"}
463
+ except Exception as exc:
464
+ return {"installed": True, "importable": False, "api_location": None, "error": f"{type(exc).__name__}: {exc}"}
465
+
466
+
467
+ def load_da3_class():
468
+ """Resolve the DA3 class across known upstream package layouts."""
469
+ return resolve_da3_class()
470
+
471
+
472
+ def save_failure_manifest(requested_backend: str, stage: str, exc: Exception, input_hashes=None) -> str:
473
+ """Persist actionable failure context without storing user media or secrets."""
474
+ OUTPUT_DIR.mkdir(exist_ok=True)
475
+ run_id = uuid.uuid4().hex
476
+ manifest = {
477
+ "project": "Simam3D",
478
+ "version": SIMAM3D_VERSION,
479
+ "manifest_schema_version": MANIFEST_SCHEMA_VERSION,
480
+ "run_id": run_id,
481
+ "status": "failed",
482
+ "backend": requested_backend,
483
+ "runtime": runtime_label(),
484
+ "software": {
485
+ "python": platform.python_version(),
486
+ "torch": getattr(torch, "__version__", "unknown"),
487
+ "gradio": getattr(gr, "__version__", "unknown"),
488
+ },
489
+ "stage": stage,
490
+ "input_sha256": list(input_hashes or []),
491
+ "error": {"type": type(exc).__name__, "message": str(exc)},
492
+ "traceback_tail": traceback.format_exc().splitlines()[-8:],
493
+ "claims": {
494
+ "observed_input_geometry": False,
495
+ "generated_novel_views": False,
496
+ "metric_scale_reconstruction": False,
497
+ "learned_gaussian_optimization": False,
498
+ "failure_report_only": True,
499
+ },
500
+ }
501
+ path = OUTPUT_DIR / f"simam3d_{run_id}_failure.json"
502
+ path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
503
+ return str(path)
504
+
505
+
506
+ def diagnostics() -> str:
507
+ """Return actionable environment information without loading a model."""
508
+ OUTPUT_DIR.mkdir(exist_ok=True)
509
+ checks = {
510
+ "simam3d_version": SIMAM3D_VERSION,
511
+ "runtime": runtime_label(),
512
+ "cuda_available": bool(torch.cuda.is_available()),
513
+ "torch": getattr(torch, "__version__", "unknown"),
514
+ "gradio": getattr(gr, "__version__", "unknown"),
515
+ "v2_model": MODEL_ID,
516
+ "da3_api": da3_api_status(),
517
+ "da3_model": DA3_MODEL_ID,
518
+ "output_directory_writable": os.access(OUTPUT_DIR, os.W_OK),
519
+ "max_input_side": MAX_INPUT_SIDE,
520
+ "max_views": MAX_VIEWS,
521
+ "fusion_voxel_size": FUSION_VOXEL_SIZE,
522
+ }
523
+ if torch.cuda.is_available():
524
+ checks["cuda_device"] = torch.cuda.get_device_name(0)
525
+ checks["cuda_memory_gb"] = round(torch.cuda.get_device_properties(0).total_memory / 1024**3, 2)
526
+ return "```json\n" + json.dumps(checks, indent=2) + "\n```"
527
+
528
+
529
+ def recent_failure_reports():
530
+ """Return recent redacted failure manifests for download from the UI."""
531
+ OUTPUT_DIR.mkdir(exist_ok=True)
532
+ return [str(path) for path in sorted(OUTPUT_DIR.glob("*_failure.json"), key=lambda item: item.stat().st_mtime, reverse=True)[:10]]
533
+
534
+
535
+ @GPU_FUNCTION
536
+ def generate(image: Image.Image, extra_files, backend: str, guess: str, demo_mode: bool, progress=gr.Progress()):
537
+ if image is None:
538
+ raise gr.Error("Please add an input image first.")
539
+ started = time.perf_counter()
540
+ stage = "input_validation"
541
+ input_hashes = []
542
+ try:
543
+ stage = "input_loading"
544
+ images = load_input_images(image, extra_files)
545
+ view_count = len(images)
546
+ input_hashes = [image_fingerprint(view) for view in images]
547
+ scene_guess = classify_scene_hypothesis(guess)
548
+ lighting = analyze_light_field(np.asarray(images[0]))
549
+ backend_used = backend
550
+ fallback_note = ""
551
+ fallback_error = None
552
+ confidence_source = "baseline_uniform"
553
+ progress(0.05, desc=f"Loading {backend} on {runtime_label()}")
554
+ confidence = np.ones((view_count, 1, 1), dtype=np.float32)
555
+ extrinsics = synthetic_orbit_poses(view_count)
556
+ intrinsics = np.repeat(np.eye(3, dtype=np.float32)[None, ...], view_count, axis=0)
557
+ pose_source = "synthetic_orbit_prior"
558
+ if demo_mode:
559
+ stage = "deterministic_depth"
560
+ depth = np.stack([deterministic_demo_depth(np.asarray(view)) for view in images], axis=0)
561
+ confidence = np.ones_like(depth, dtype=np.float32)
562
+ backend_used = "Deterministic export smoke test (no AI)"
563
+ pose_source = "synthetic_orbit_prior"
564
+ confidence_source = "uniform_demo"
565
+ progress(0.45, desc="Running deterministic export smoke test")
566
+ elif backend == "Depth Anything 3 (camera-aware)":
567
+ try:
568
+ stage = "da3_inference"
569
+ with INFERENCE_LOCK, torch.inference_mode():
570
+ prediction = get_da3_model().inference(image=images)
571
+ depth, confidence, extrinsics, intrinsics, confidence_source, pose_source = normalize_prediction_contract(
572
+ prediction, view_count
573
+ )
574
+ except (ImportError, ModuleNotFoundError, RuntimeError, TypeError, ValueError) as exc:
575
+ clear_da3_model()
576
+ fallback_error = f"{type(exc).__name__}: {exc}"
577
+ fallback_note = f" DA3 unavailable ({type(exc).__name__}); used the stable V2 fallback."
578
+ print(f"Simam3D DA3 unavailable; falling back to V2: {exc}", flush=True)
579
+ gr.Warning(fallback_note.strip())
580
+ backend_used = "Depth Anything V2 (stable baseline; DA3 fallback)"
581
+ stage = "v2_fallback_inference"
582
+ with INFERENCE_LOCK:
583
+ depth = predict_v2(images)
584
+ confidence = np.ones_like(depth, dtype=np.float32)
585
+ else:
586
+ stage = "v2_inference"
587
+ with INFERENCE_LOCK:
588
+ depth = predict_v2(images)
589
+ confidence = np.ones_like(depth, dtype=np.float32)
590
+ if depth.ndim != 3 or not np.isfinite(depth).all():
591
+ raise RuntimeError(f"Invalid depth tensor returned with shape {depth.shape}")
592
+ stage = "geometry_export"
593
+ progress(0.65, desc="Building depth geometry")
594
+ run_id = uuid.uuid4().hex
595
+ depth_image = make_depth_preview(depth[0])
596
+ confidence_image = make_confidence_preview(confidence[0])
597
+ glb_path = depth_to_glb(images[0], depth[0], run_id)
598
+ ply_path = depth_to_pointcloud(images[0], depth[0], confidence[0], run_id)
599
+ fused_path, fusion_stats, fused_weights, fused_source_views, fused_source_masks = fuse_views(
600
+ images, depth, confidence, extrinsics, intrinsics, run_id
601
+ )
602
+ fused_cloud = trimesh.load(fused_path, process=False)
603
+ fused_points = np.asarray(fused_cloud.vertices, dtype=np.float32)
604
+ projection_coverage = []
605
+ reprojection_metrics = []
606
+ for idx in range(view_count):
607
+ _, _, inside = project_world_points(
608
+ fused_points, intrinsics[idx], extrinsics[idx], images[idx].width, images[idx].height
609
+ )
610
+ projection_coverage.append(float(inside.mean()) if len(inside) else 0.0)
611
+ reprojection_metrics.append(
612
+ reprojection_consistency(fused_points, depth[idx], intrinsics[idx], extrinsics[idx])
613
+ )
614
+ turntable_path = save_turntable_gif(
615
+ fused_points,
616
+ np.asarray(fused_cloud.colors[:, :3], dtype=np.uint8),
617
+ run_id,
618
+ )
619
+ gaussian_path = pointcloud_to_gaussian_ply(
620
+ fused_path, run_id, fused_weights, fused_source_views, fused_source_masks
621
+ )
622
+ npz_path = save_prediction_npz(depth, confidence, extrinsics, intrinsics, run_id)
623
+ uncertainty = reveal_uncertainty(depth[0], confidence[0])
624
+ depth_lighting = estimate_depth_light(depth[0], np.asarray(images[0].resize(depth[0].shape[::-1], Image.Resampling.LANCZOS)))
625
+ uncertainty_path = save_uncertainty_map(uncertainty, run_id)
626
+ view_plan = next_view_plan(view_count)
627
+ evidence_card = make_evidence_card(
628
+ images[0], depth[0], confidence[0], backend_used, view_count, fusion_stats, run_id
629
+ )
630
+ reveal_card = make_reveal_card(images[0], depth[0], scene_guess, lighting, run_id)
631
+ analysis_report = (
632
+ "### Behind-the-image analysis\n"
633
+ f"**Your hypothesis:** {scene_guess['user_guess']} \n"
634
+ f"**Semantic cues:** {', '.join(scene_guess['semantic_cues'])} \n"
635
+ f"**Lighting:** {lighting['lighting_label']} \n"
636
+ f"**Estimated light direction:** azimuth {lighting['estimated_azimuth_deg']:.0f}°, "
637
+ f"elevation {lighting['estimated_elevation_deg']:.0f}° \n"
638
+ f"**3D light vector:** ({depth_lighting['light_direction_x']:.2f}, "
639
+ f"{depth_lighting['light_direction_y']:.2f}, {depth_lighting['light_direction_z']:.2f}) "
640
+ f"with confidence {depth_lighting['photometric_confidence']:.2f} \n"
641
+ f"**Detector confidence:** {lighting['detector_confidence']:.2f} \n"
642
+ f"**Reveal uncertainty:** {uncertainty.mean():.2f} mean visible-space uncertainty \n"
643
+ f"**Fused projection coverage:** {np.mean(projection_coverage):.1%} mean across input views \n"
644
+ f"**Depth reprojection MAE:** {np.mean([item['mean_absolute_error'] for item in reprojection_metrics]):.3f} "
645
+ "relative-depth diagnostic \n"
646
+ f"**Next view suggestion:** {view_plan[0]['yaw_deg']:.0f}° yaw "
647
+ f"({view_plan[0]['gap_from_existing_deg']:.0f}° gap) \n"
648
+ "*This is an image-space lighting estimate and a user-guided scene hypothesis, "
649
+ "not verified hidden content.*"
650
+ )
651
+ elapsed = time.perf_counter() - started
652
+ manifest_path = save_run_manifest(
653
+ run_id,
654
+ backend_used,
655
+ view_count,
656
+ elapsed,
657
+ [glb_path, ply_path, fused_path, gaussian_path, npz_path, uncertainty_path, turntable_path, evidence_card, reveal_card],
658
+ {
659
+ "depth_shape": list(depth.shape),
660
+ "depth_min": float(depth.min()),
661
+ "depth_max": float(depth.max()),
662
+ "confidence_mean": float(np.mean(confidence)),
663
+ "fused_point_count": fusion_stats["point_count"],
664
+ "fused_confidence_mean": fusion_stats["confidence_mean"],
665
+ "fused_confidence_p95": fusion_stats["confidence_p95"],
666
+ "pose_source": pose_source,
667
+ "confidence_source": confidence_source,
668
+ "requested_backend": backend,
669
+ "fallback_error": fallback_error,
670
+ "input_sha256": input_hashes,
671
+ "input_sizes": [list(view.size) for view in images],
672
+ "fusion_voxel_size": FUSION_VOXEL_SIZE,
673
+ "fusion_max_points": FUSION_MAX_POINTS,
674
+ "scene_hypothesis": scene_guess,
675
+ "lighting_analysis": lighting,
676
+ "depth_normal_lighting": depth_lighting,
677
+ "reveal_uncertainty_mean": float(uncertainty.mean()),
678
+ "next_view_plan": view_plan,
679
+ "projection_coverage": projection_coverage,
680
+ "reprojection_consistency": reprojection_metrics,
681
+ },
682
+ )
683
+ progress(1.0, desc="Done")
684
+ 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, (
685
+ f"Processed {view_count} view(s) on {runtime_label()} in {elapsed:.1f}s using {backend_used}. "
686
+ "Per-view and confidence-weighted fused point clouds are exported. "
687
+ f"Pose source: {pose_source}; confidence source: {confidence_source}." + fallback_note
688
+ )
689
+ except Exception as exc:
690
+ print(f"Simam3D generation failed: {type(exc).__name__}: {exc}", flush=True)
691
+ failure_path = save_failure_manifest(backend, stage, exc, input_hashes)
692
+ raise gr.Error(
693
+ f"Generation failed: {type(exc).__name__}: {exc}. Failure manifest: {failure_path}"
694
+ ) from exc
695
+
696
+
697
+ with gr.Blocks(title="Simam3D") as demo:
698
+ gr.Markdown("# Simam3D\nSingle-image depth and 3D reconstruction workbench")
699
+ gr.Markdown(
700
+ "Phase 1 is deliberately transparent: the original image is lifted using a depth model, "
701
+ "then exported as a textured GLB. This gives us a known-good baseline before adding "
702
+ "multi-view generation and Gaussian splat fusion."
703
+ )
704
+ gr.Markdown(
705
+ "**First run:** keep **Depth Anything V2 (stable baseline)** selected. "
706
+ "Use **Depth Anything 3 (camera-aware)** when you want to test the heavier "
707
+ "multi-view research path; failed DA3 loads fall back to V2 with a warning."
708
+ )
709
+ with gr.Row():
710
+ with gr.Column():
711
+ image = gr.Image(type="pil", label="Input image")
712
+ extra_files = gr.Files(
713
+ label="Optional additional views",
714
+ file_types=["image"],
715
+ file_count="multiple",
716
+ type="filepath",
717
+ )
718
+ guess = gr.Textbox(
719
+ label="What do you think is behind this image?",
720
+ placeholder="e.g. I think there is a garden or a room behind it…",
721
+ )
722
+ backend = gr.Dropdown(
723
+ choices=["Depth Anything 3 (camera-aware)", "Depth Anything V2 (stable baseline)"],
724
+ value="Depth Anything V2 (stable baseline)",
725
+ label="Reconstruction backend",
726
+ )
727
+ demo_mode = gr.Checkbox(
728
+ label="Run export smoke test (no AI model; diagnostic only)",
729
+ value=False,
730
+ )
731
+ run = gr.Button("Generate depth + 3D", variant="primary")
732
+ with gr.Column():
733
+ depth = gr.Image(label="Predicted depth")
734
+ confidence_view = gr.Image(label="Confidence diagnostic")
735
+ model = gr.File(label="Download depth geometry GLB", file_count="single")
736
+ pointcloud = gr.File(label="Download point cloud PLY", file_count="single")
737
+ fused = gr.File(label="Download fused point cloud PLY", file_count="single")
738
+ gaussians = gr.File(label="Download Gaussian-splat PLY", file_count="single")
739
+ metadata = gr.File(label="Download depth/camera metadata NPZ", file_count="single")
740
+ uncertainty_file = gr.File(label="Download reveal uncertainty map PNG", file_count="single")
741
+ turntable_file = gr.File(label="Download reconstructed turntable GIF", file_count="single")
742
+ evidence_card = gr.File(label="Download shareable evidence card PNG", file_count="single")
743
+ reveal_card = gr.File(label="Download What's Behind reveal card PNG", file_count="single")
744
+ manifest = gr.File(label="Download reproducibility manifest JSON", file_count="single")
745
+ analysis_report = gr.Markdown()
746
+ status = gr.Markdown(f"Ready. Simam3D **v{SIMAM3D_VERSION}** · Runtime: **{runtime_label()}**")
747
+ with gr.Accordion("Diagnostics", open=False):
748
+ diagnose = gr.Button("Run environment diagnostics")
749
+ diagnostic_report = gr.Markdown()
750
+ diagnose.click(diagnostics, outputs=diagnostic_report)
751
+ refresh_failures = gr.Button("Refresh recent failure reports")
752
+ failure_reports = gr.Files(label="Download recent failure reports", file_count="multiple")
753
+ refresh_failures.click(recent_failure_reports, outputs=failure_reports)
754
+ run.click(
755
+ generate,
756
+ inputs=[image, extra_files, backend, guess, demo_mode],
757
+ outputs=[depth, confidence_view, model, pointcloud, fused, gaussians, metadata, uncertainty_file, turntable_file, evidence_card, reveal_card, manifest, analysis_report, status],
758
+ concurrency_limit=1,
759
+ concurrency_id="simam3d_heavy_inference",
760
+ )
761
+
762
+
763
+ if __name__ == "__main__":
764
+ print(f"Simam3D v{SIMAM3D_VERSION} starting on {runtime_label()}", flush=True)
765
+ demo.launch(show_error=True)