Update modular inference, encoder, tests, and cache layout (part 2)
Browse files- encoder/adapters.py +81 -32
- encoder/config.py +2 -3
- encoder/geometric.py +194 -148
- encoder/launch.py +4 -4
- encoder/render.py +2 -2
- encoder/run.py +6 -6
- inference/adapters.py +59 -70
- inference/run.py +2 -6
- symbolic/launch.py +2 -2
- symbolic/run.py +3 -5
- symbolic/solver.py +11 -9
- tests/test_encoder/conftest.py +13 -0
- tests/test_encoder/test_adapters.py +210 -0
- tests/test_encoder/test_config.py +49 -0
- tests/test_encoder/test_encoder.py +70 -0
- tests/test_encoder/test_geometric.py +160 -0
- tests/test_encoder/test_launch.py +49 -0
- tests/test_encoder/test_render.py +37 -0
- tests/test_encoder/test_run.py +39 -0
- tests/test_inference/conftest.py +13 -0
- tests/test_inference/test_adapters.py +198 -0
- tests/test_inference/test_inference.py +91 -0
- tests/test_inference/test_launch.py +130 -0
- tests/test_inference/test_run.py +41 -0
- tests/test_symbolic/conftest.py +78 -0
- tests/test_symbolic/test_launch.py +61 -0
- tests/test_symbolic/test_run.py +73 -0
- tests/test_symbolic/test_solver.py +121 -0
- tests/test_symbolic/test_symbolic.py +13 -0
encoder/adapters.py
CHANGED
|
@@ -20,6 +20,14 @@ import sys
|
|
| 20 |
import numpy as np
|
| 21 |
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# ==========================================================================================
|
| 24 |
# CANONICAL SHAPE -- validation only. Plain dicts on purpose: no schema/contract class layer.
|
| 25 |
# ==========================================================================================
|
|
@@ -114,7 +122,11 @@ def _load_native_sam3(path):
|
|
| 114 |
masks = response["outputs"].get("masks")
|
| 115 |
if masks is None:
|
| 116 |
raise ValueError(f"SAM3 response at frame {frame_index} has no masks")
|
| 117 |
-
masks =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
if masks.ndim == 2:
|
| 119 |
masks = masks[None]
|
| 120 |
if masks.ndim == 4 and masks.shape[1] == 1:
|
|
@@ -150,7 +162,9 @@ def _load_native_da3(path):
|
|
| 150 |
intr = np.asarray(field("intrinsics"), np.float32)
|
| 151 |
extr = np.asarray(field("extrinsics"), np.float32)
|
| 152 |
if extr.shape[-2:] == (3, 4):
|
| 153 |
-
homogeneous = np.broadcast_to(
|
|
|
|
|
|
|
| 154 |
homogeneous[..., :3, :] = extr
|
| 155 |
extr = homogeneous
|
| 156 |
if extr.shape[-2:] != (4, 4):
|
|
@@ -161,24 +175,29 @@ def _load_native_da3(path):
|
|
| 161 |
return depth, intr, c2w, conf
|
| 162 |
|
| 163 |
|
| 164 |
-
def _backproject(depth,
|
| 165 |
ys, xs = np.nonzero(mask)
|
| 166 |
z = depth[ys, xs]
|
| 167 |
ok = np.isfinite(z) & (z > 0)
|
| 168 |
ys, xs, z = ys[ok], xs[ok], z[ok]
|
| 169 |
if not len(z):
|
| 170 |
return np.zeros((0, 3), np.float32), None
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
cf = conf[ys, xs].astype(np.float32) if conf is not None else None
|
| 174 |
-
return
|
| 175 |
|
| 176 |
|
| 177 |
-
def
|
| 178 |
-
|
| 179 |
-
)
|
| 180 |
-
"""Fuse raw DA3 geometry and raw per-frame SAM3 masks into canonical geometry."""
|
| 181 |
-
if root and scene:
|
| 182 |
da3_path = da3_path or os.path.join(root, "depth-anything-3", f"{scene}.pkl")
|
| 183 |
sam3_path = sam3_path or os.path.join(root, "sam3", f"{scene}.pt")
|
| 184 |
if da3_path is None:
|
|
@@ -187,6 +206,10 @@ def adapt_sam3_depth_anything_3(
|
|
| 187 |
sam3_path = root
|
| 188 |
if not da3_path:
|
| 189 |
raise ValueError("da3_path is required")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
if str(da3_path).endswith(".pkl"):
|
| 191 |
depth, intr, c2w, conf = _load_native_da3(da3_path)
|
| 192 |
ft = np.arange(len(depth), dtype=np.float32)
|
|
@@ -194,8 +217,20 @@ def adapt_sam3_depth_anything_3(
|
|
| 194 |
d = np.load(da3_path)
|
| 195 |
depth, intr, c2w = d["depth"], d["intr"], d["c2w"]
|
| 196 |
conf = d["conf"] if "conf" in d and d["conf"].size else None
|
| 197 |
-
ft =
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
instances, stats = {}, {}
|
| 200 |
for cls, frames in per.items():
|
| 201 |
by_id = {}
|
|
@@ -217,7 +252,7 @@ def adapt_sam3_depth_anything_3(
|
|
| 217 |
"chunks": [],
|
| 218 |
"conf": [],
|
| 219 |
"frames": set(),
|
| 220 |
-
"first_time": float(
|
| 221 |
},
|
| 222 |
)
|
| 223 |
r["chunks"].append(pts)
|
|
@@ -241,25 +276,39 @@ def adapt_sam3_depth_anything_3(
|
|
| 241 |
if raw:
|
| 242 |
instances[cls] = raw
|
| 243 |
stats[cls] = {"raw": len(raw), "merged": len(raw), "peak": peak}
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
for fi in range(0, len(depth), 3):
|
| 246 |
m = np.zeros_like(depth[fi], bool)
|
| 247 |
m[::8, ::8] = True
|
| 248 |
pts, _ = _backproject(depth[fi], intr[fi], c2w[fi], m)
|
| 249 |
if len(pts):
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
return validate(
|
| 252 |
{
|
| 253 |
"instances": instances,
|
| 254 |
"stats": stats,
|
| 255 |
-
"scene_pts":
|
| 256 |
"cameras": c2w[:, :3, 3],
|
| 257 |
"raw_inputs": {
|
| 258 |
"depth": depth,
|
| 259 |
"intr": intr,
|
| 260 |
"c2w": c2w,
|
| 261 |
"conf": conf,
|
| 262 |
-
"ftimes":
|
| 263 |
"per": per,
|
| 264 |
},
|
| 265 |
}
|
|
@@ -272,7 +321,9 @@ def adapt_sam3_depth_anything_3(
|
|
| 272 |
# ==========================================================================================
|
| 273 |
|
| 274 |
|
| 275 |
-
SEGVGGT_CLASSES = """wall|floor|chair|table|door|couch|cabinet|shelf|desk|office chair|bed|pillow|sink|picture|window|toilet|bookshelf|monitor|curtain|book|armchair|coffee table|box|refrigerator|lamp|kitchen cabinet|towel|clothes|tv|nightstand|counter|dresser|stool|cushion|plant|ceiling|bathtub|end table|dining table|keyboard|bag|backpack|toilet paper|printer|tv stand|whiteboard|blanket|shower curtain|trash can|closet|stairs|microwave|stove|shoe|computer tower|bottle|bin|ottoman|bench|board|washing machine|mirror|copier|basket|sofa chair|file cabinet|fan|laptop|shower|paper|person|paper towel dispenser|oven|blinds|rack|plate|blackboard|piano|suitcase|rail|radiator|recycling bin|container|wardrobe|soap dispenser|telephone""".split(
|
|
|
|
|
|
|
| 276 |
|
| 277 |
|
| 278 |
def _decode_segvggt_raw(path):
|
|
@@ -299,7 +350,9 @@ def _decode_segvggt_raw(path):
|
|
| 299 |
raw = torch.load(path, map_location="cpu", weights_only=False)
|
| 300 |
required = {"world_points", "instance_maps", "instance_labels", "pose_enc"}
|
| 301 |
if not isinstance(raw, dict) or not required.issubset(raw):
|
| 302 |
-
missing =
|
|
|
|
|
|
|
| 303 |
raise ValueError(f"invalid SegVGGT raw cache {path}; missing keys: {missing}")
|
| 304 |
|
| 305 |
logits = raw["instance_maps"][0]
|
|
@@ -316,14 +369,11 @@ def _decode_segvggt_raw(path):
|
|
| 316 |
|
| 317 |
world = raw["world_points"][0].float()
|
| 318 |
if tuple(world.shape[1:3]) != (height, width):
|
| 319 |
-
world = (
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
)
|
| 325 |
-
.permute(0, 2, 3, 1)
|
| 326 |
-
)
|
| 327 |
world = world.cpu().numpy()
|
| 328 |
|
| 329 |
if "images" in raw:
|
|
@@ -332,9 +382,7 @@ def _decode_segvggt_raw(path):
|
|
| 332 |
image_size = raw["depth"].shape[2:4]
|
| 333 |
else:
|
| 334 |
image_size = (height, width)
|
| 335 |
-
extrinsics, _ = pose_encoding_to_extri_intri(
|
| 336 |
-
raw["pose_enc"].float(), image_size
|
| 337 |
-
)
|
| 338 |
extrinsics = extrinsics[0].cpu().numpy()
|
| 339 |
rotations = extrinsics[:, :3, :3]
|
| 340 |
translations = extrinsics[:, :3, 3]
|
|
@@ -358,7 +406,8 @@ def _decode_segvggt_raw(path):
|
|
| 358 |
|
| 359 |
def adapt_segvggt(root=None, path=None, scene=None, **_):
|
| 360 |
"""Translate a raw-preserving SegVGGT cache to canonical geometry."""
|
| 361 |
-
if path is None and
|
|
|
|
| 362 |
path = os.path.join(root, "segvggt", f"{scene}.pt")
|
| 363 |
else:
|
| 364 |
path = path or root
|
|
|
|
| 20 |
import numpy as np
|
| 21 |
|
| 22 |
|
| 23 |
+
RAW_CACHE_ROOT = "/root/data/caches"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _raw_cache_root(root=None):
|
| 27 |
+
"""Resolve the shared inference-output root without importing encoder config."""
|
| 28 |
+
return root or os.environ.get("VSI_CACHE_ROOT", RAW_CACHE_ROOT)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
# ==========================================================================================
|
| 32 |
# CANONICAL SHAPE -- validation only. Plain dicts on purpose: no schema/contract class layer.
|
| 33 |
# ==========================================================================================
|
|
|
|
| 122 |
masks = response["outputs"].get("masks")
|
| 123 |
if masks is None:
|
| 124 |
raise ValueError(f"SAM3 response at frame {frame_index} has no masks")
|
| 125 |
+
masks = (
|
| 126 |
+
masks.detach().cpu().numpy()
|
| 127 |
+
if hasattr(masks, "detach")
|
| 128 |
+
else np.asarray(masks)
|
| 129 |
+
)
|
| 130 |
if masks.ndim == 2:
|
| 131 |
masks = masks[None]
|
| 132 |
if masks.ndim == 4 and masks.shape[1] == 1:
|
|
|
|
| 162 |
intr = np.asarray(field("intrinsics"), np.float32)
|
| 163 |
extr = np.asarray(field("extrinsics"), np.float32)
|
| 164 |
if extr.shape[-2:] == (3, 4):
|
| 165 |
+
homogeneous = np.broadcast_to(
|
| 166 |
+
np.eye(4, dtype=np.float32), extr.shape[:-2] + (4, 4)
|
| 167 |
+
).copy()
|
| 168 |
homogeneous[..., :3, :] = extr
|
| 169 |
extr = homogeneous
|
| 170 |
if extr.shape[-2:] != (4, 4):
|
|
|
|
| 175 |
return depth, intr, c2w, conf
|
| 176 |
|
| 177 |
|
| 178 |
+
def _backproject(depth, intrinsics, c2w, mask, conf=None):
|
| 179 |
ys, xs = np.nonzero(mask)
|
| 180 |
z = depth[ys, xs]
|
| 181 |
ok = np.isfinite(z) & (z > 0)
|
| 182 |
ys, xs, z = ys[ok], xs[ok], z[ok]
|
| 183 |
if not len(z):
|
| 184 |
return np.zeros((0, 3), np.float32), None
|
| 185 |
+
camera_points = np.stack(
|
| 186 |
+
[
|
| 187 |
+
(xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
|
| 188 |
+
(ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
|
| 189 |
+
z,
|
| 190 |
+
],
|
| 191 |
+
1,
|
| 192 |
+
)
|
| 193 |
+
world_points = (c2w[:3, :3] @ camera_points.T).T + c2w[:3, 3]
|
| 194 |
cf = conf[ys, xs].astype(np.float32) if conf is not None else None
|
| 195 |
+
return world_points.astype(np.float32), cf
|
| 196 |
|
| 197 |
|
| 198 |
+
def _fusion_cache_paths(root, da3_path, sam3_path, scene):
|
| 199 |
+
if scene:
|
| 200 |
+
root = _raw_cache_root(root)
|
|
|
|
|
|
|
| 201 |
da3_path = da3_path or os.path.join(root, "depth-anything-3", f"{scene}.pkl")
|
| 202 |
sam3_path = sam3_path or os.path.join(root, "sam3", f"{scene}.pt")
|
| 203 |
if da3_path is None:
|
|
|
|
| 206 |
sam3_path = root
|
| 207 |
if not da3_path:
|
| 208 |
raise ValueError("da3_path is required")
|
| 209 |
+
return da3_path, sam3_path
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _load_fusion_inputs(da3_path, sam3_path):
|
| 213 |
if str(da3_path).endswith(".pkl"):
|
| 214 |
depth, intr, c2w, conf = _load_native_da3(da3_path)
|
| 215 |
ft = np.arange(len(depth), dtype=np.float32)
|
|
|
|
| 217 |
d = np.load(da3_path)
|
| 218 |
depth, intr, c2w = d["depth"], d["intr"], d["c2w"]
|
| 219 |
conf = d["conf"] if "conf" in d and d["conf"].size else None
|
| 220 |
+
ft = (
|
| 221 |
+
d["frame_times"]
|
| 222 |
+
if "frame_times" in d
|
| 223 |
+
else np.arange(len(depth), dtype=np.float32)
|
| 224 |
+
)
|
| 225 |
+
per = (
|
| 226 |
+
_load_native_sam3(sam3_path)
|
| 227 |
+
if str(sam3_path).endswith(".pt")
|
| 228 |
+
else _load_masks(sam3_path)
|
| 229 |
+
)
|
| 230 |
+
return depth, intr, c2w, conf, ft, per
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _fuse_mask_instances(per, depth, intr, c2w, conf, frame_times):
|
| 234 |
instances, stats = {}, {}
|
| 235 |
for cls, frames in per.items():
|
| 236 |
by_id = {}
|
|
|
|
| 252 |
"chunks": [],
|
| 253 |
"conf": [],
|
| 254 |
"frames": set(),
|
| 255 |
+
"first_time": float(frame_times[fi]),
|
| 256 |
},
|
| 257 |
)
|
| 258 |
r["chunks"].append(pts)
|
|
|
|
| 276 |
if raw:
|
| 277 |
instances[cls] = raw
|
| 278 |
stats[cls] = {"raw": len(raw), "merged": len(raw), "peak": peak}
|
| 279 |
+
return instances, stats
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _sample_scene_points(depth, intr, c2w):
|
| 283 |
+
scene_points = []
|
| 284 |
for fi in range(0, len(depth), 3):
|
| 285 |
m = np.zeros_like(depth[fi], bool)
|
| 286 |
m[::8, ::8] = True
|
| 287 |
pts, _ = _backproject(depth[fi], intr[fi], c2w[fi], m)
|
| 288 |
if len(pts):
|
| 289 |
+
scene_points.append(pts)
|
| 290 |
+
return np.concatenate(scene_points, 0)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def adapt_sam3_depth_anything_3(
|
| 294 |
+
root=None, da3_path=None, sam3_path=None, scene=None, **_
|
| 295 |
+
):
|
| 296 |
+
"""Fuse raw DA3 geometry and raw per-frame SAM3 masks into canonical geometry."""
|
| 297 |
+
da3_path, sam3_path = _fusion_cache_paths(root, da3_path, sam3_path, scene)
|
| 298 |
+
depth, intr, c2w, conf, frame_times, per = _load_fusion_inputs(da3_path, sam3_path)
|
| 299 |
+
instances, stats = _fuse_mask_instances(per, depth, intr, c2w, conf, frame_times)
|
| 300 |
return validate(
|
| 301 |
{
|
| 302 |
"instances": instances,
|
| 303 |
"stats": stats,
|
| 304 |
+
"scene_pts": _sample_scene_points(depth, intr, c2w),
|
| 305 |
"cameras": c2w[:, :3, 3],
|
| 306 |
"raw_inputs": {
|
| 307 |
"depth": depth,
|
| 308 |
"intr": intr,
|
| 309 |
"c2w": c2w,
|
| 310 |
"conf": conf,
|
| 311 |
+
"ftimes": frame_times,
|
| 312 |
"per": per,
|
| 313 |
},
|
| 314 |
}
|
|
|
|
| 321 |
# ==========================================================================================
|
| 322 |
|
| 323 |
|
| 324 |
+
SEGVGGT_CLASSES = """wall|floor|chair|table|door|couch|cabinet|shelf|desk|office chair|bed|pillow|sink|picture|window|toilet|bookshelf|monitor|curtain|book|armchair|coffee table|box|refrigerator|lamp|kitchen cabinet|towel|clothes|tv|nightstand|counter|dresser|stool|cushion|plant|ceiling|bathtub|end table|dining table|keyboard|bag|backpack|toilet paper|printer|tv stand|whiteboard|blanket|shower curtain|trash can|closet|stairs|microwave|stove|shoe|computer tower|bottle|bin|ottoman|bench|board|washing machine|mirror|copier|basket|sofa chair|file cabinet|fan|laptop|shower|paper|person|paper towel dispenser|oven|blinds|rack|plate|blackboard|piano|suitcase|rail|radiator|recycling bin|container|wardrobe|soap dispenser|telephone""".split(
|
| 325 |
+
"|"
|
| 326 |
+
)
|
| 327 |
|
| 328 |
|
| 329 |
def _decode_segvggt_raw(path):
|
|
|
|
| 350 |
raw = torch.load(path, map_location="cpu", weights_only=False)
|
| 351 |
required = {"world_points", "instance_maps", "instance_labels", "pose_enc"}
|
| 352 |
if not isinstance(raw, dict) or not required.issubset(raw):
|
| 353 |
+
missing = (
|
| 354 |
+
sorted(required - set(raw)) if isinstance(raw, dict) else sorted(required)
|
| 355 |
+
)
|
| 356 |
raise ValueError(f"invalid SegVGGT raw cache {path}; missing keys: {missing}")
|
| 357 |
|
| 358 |
logits = raw["instance_maps"][0]
|
|
|
|
| 369 |
|
| 370 |
world = raw["world_points"][0].float()
|
| 371 |
if tuple(world.shape[1:3]) != (height, width):
|
| 372 |
+
world = functional.interpolate(
|
| 373 |
+
world.permute(0, 3, 1, 2),
|
| 374 |
+
(height, width),
|
| 375 |
+
mode="nearest",
|
| 376 |
+
).permute(0, 2, 3, 1)
|
|
|
|
|
|
|
|
|
|
| 377 |
world = world.cpu().numpy()
|
| 378 |
|
| 379 |
if "images" in raw:
|
|
|
|
| 382 |
image_size = raw["depth"].shape[2:4]
|
| 383 |
else:
|
| 384 |
image_size = (height, width)
|
| 385 |
+
extrinsics, _ = pose_encoding_to_extri_intri(raw["pose_enc"].float(), image_size)
|
|
|
|
|
|
|
| 386 |
extrinsics = extrinsics[0].cpu().numpy()
|
| 387 |
rotations = extrinsics[:, :3, :3]
|
| 388 |
translations = extrinsics[:, :3, 3]
|
|
|
|
| 406 |
|
| 407 |
def adapt_segvggt(root=None, path=None, scene=None, **_):
|
| 408 |
"""Translate a raw-preserving SegVGGT cache to canonical geometry."""
|
| 409 |
+
if path is None and scene:
|
| 410 |
+
root = _raw_cache_root(root)
|
| 411 |
path = os.path.join(root, "segvggt", f"{scene}.pt")
|
| 412 |
else:
|
| 413 |
path = path or root
|
encoder/config.py
CHANGED
|
@@ -13,11 +13,10 @@ DATA_ROOT = Path(os.environ.get("VSI_DATA_ROOT", "/workspace/data"))
|
|
| 13 |
VSI_ROOT = Path(os.environ.get("VSI_ROOT", "/root/data/VSI-Bench"))
|
| 14 |
JSONL = Path(os.environ.get("VSI_JSONL", VSI_ROOT / "test.jsonl"))
|
| 15 |
CACHE_ROOT = Path(os.environ.get("VSI_CACHE_ROOT", "/root/data/caches"))
|
| 16 |
-
CODES_ROOT = Path(
|
| 17 |
-
os.environ.get("VSI_CODES", DATA_ROOT / "spatial codes")
|
| 18 |
-
)
|
| 19 |
VIDEO_DATASETS = ("scannet", "scannetpp", "arkitscenes")
|
| 20 |
|
|
|
|
| 21 |
def video_path(scene: str, dataset: str | None = None) -> str:
|
| 22 |
"""Return the unique MP4 for ``scene`` from the VSI-Bench dataset folders."""
|
| 23 |
scene = str(scene)
|
|
|
|
| 13 |
VSI_ROOT = Path(os.environ.get("VSI_ROOT", "/root/data/VSI-Bench"))
|
| 14 |
JSONL = Path(os.environ.get("VSI_JSONL", VSI_ROOT / "test.jsonl"))
|
| 15 |
CACHE_ROOT = Path(os.environ.get("VSI_CACHE_ROOT", "/root/data/caches"))
|
| 16 |
+
CODES_ROOT = Path(os.environ.get("VSI_CODES", "/root/workspace/spatial codes"))
|
|
|
|
|
|
|
| 17 |
VIDEO_DATASETS = ("scannet", "scannetpp", "arkitscenes")
|
| 18 |
|
| 19 |
+
|
| 20 |
def video_path(scene: str, dataset: str | None = None) -> str:
|
| 21 |
"""Return the unique MP4 for ``scene`` from the VSI-Bench dataset folders."""
|
| 22 |
scene = str(scene)
|
encoder/geometric.py
CHANGED
|
@@ -102,10 +102,10 @@ def room_up_axis(instances, c2w):
|
|
| 102 |
"""up axis = smallest-extent axis of all object points; sign from gravity (floor->camera).
|
| 103 |
Floor = densest horizontal slab; cameras are always above it, which fixes the sign.
|
| 104 |
Returns (axis_index, signed_unit_vector)."""
|
| 105 |
-
|
| 106 |
-
ext = np.percentile(
|
| 107 |
up = int(np.argmin(ext))
|
| 108 |
-
h, edges = np.histogram(
|
| 109 |
floor = 0.5 * (edges[h.argmax()] + edges[h.argmax() + 1]) # densest slab = floor
|
| 110 |
cam_up = c2w[:, :3, 3][:, up].mean()
|
| 111 |
e = np.zeros(3, np.float32)
|
|
@@ -119,10 +119,10 @@ def room_gravity(
|
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis)."""
|
| 122 |
-
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
-
|
| 125 |
-
ys, xs = np.mgrid[0:
|
| 126 |
ys = ys.ravel()
|
| 127 |
xs = xs.ravel()
|
| 128 |
z = depth[f][ys, xs]
|
|
@@ -132,15 +132,24 @@ def room_gravity(
|
|
| 132 |
ys, xs, z = ys[ok], xs[ok], z[ok]
|
| 133 |
if not len(z):
|
| 134 |
continue
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
)
|
| 139 |
-
|
| 140 |
-
|
| 141 |
cam = c2w[:, :3, 3].mean(0)
|
| 142 |
-
if len(
|
| 143 |
-
ext =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
ax = int(np.argmin(ext))
|
| 145 |
g = np.zeros(3)
|
| 146 |
g[ax] = 1.0
|
|
@@ -149,14 +158,14 @@ def room_gravity(
|
|
| 149 |
best = None
|
| 150 |
best_score = -1
|
| 151 |
for _ in range(iters):
|
| 152 |
-
a, b, c =
|
| 153 |
nrm = np.cross(b - a, c - a)
|
| 154 |
ln = np.linalg.norm(nrm)
|
| 155 |
if ln < 1e-6:
|
| 156 |
continue
|
| 157 |
nrm /= ln
|
| 158 |
d = -nrm @ a
|
| 159 |
-
side =
|
| 160 |
ninl = int((np.abs(side) < thr).sum())
|
| 161 |
if ninl < 50:
|
| 162 |
continue
|
|
@@ -167,7 +176,7 @@ def room_gravity(
|
|
| 167 |
best_score = score
|
| 168 |
best = (nrm, d)
|
| 169 |
if best is None:
|
| 170 |
-
ext = np.percentile(
|
| 171 |
ax = int(np.argmin(ext))
|
| 172 |
g = np.zeros(3)
|
| 173 |
g[ax] = 1.0
|
|
@@ -314,7 +323,7 @@ def _rep(insts):
|
|
| 314 |
return max(insts, key=lambda i: i["n"])
|
| 315 |
|
| 316 |
|
| 317 |
-
def answer_rel_direction(
|
| 318 |
"""Standing at A facing B, where is C? front/back=dot(C-A,fwd); left/right=dot(C-A, up x fwd).
|
| 319 |
Right-handed world (OpenCV cam frame + det+1 c2w) makes up x fwd = left a fixed identity.
|
| 320 |
Projection uses the gravity VECTOR (v-(v.g)g), so a tilted floor (ScanNet++) is handled; for an
|
|
@@ -326,14 +335,14 @@ def answer_rel_direction(pA, pB, pC, up_vec, up_ax, mode="hard"):
|
|
| 326 |
w = v.astype(np.float64)
|
| 327 |
return w - (w @ g) * g
|
| 328 |
|
| 329 |
-
fwd = fl(
|
| 330 |
n = np.linalg.norm(fwd)
|
| 331 |
if n < 1e-6:
|
| 332 |
return None
|
| 333 |
fwd /= n
|
| 334 |
left = np.cross(g, fwd)
|
| 335 |
left /= np.linalg.norm(left) + 1e-9
|
| 336 |
-
d = fl(
|
| 337 |
f = float(d @ fwd)
|
| 338 |
lateral = float(d @ left)
|
| 339 |
if mode == "medium":
|
|
@@ -431,10 +440,10 @@ def _sor(pts, k=16, std=2.0, cap=4000):
|
|
| 431 |
if len(pts) < k + 2:
|
| 432 |
return pts
|
| 433 |
rs = np.random.RandomState(0)
|
| 434 |
-
|
| 435 |
-
d, _ = cKDTree(
|
| 436 |
md = d[:, 1:].mean(1)
|
| 437 |
-
return
|
| 438 |
|
| 439 |
|
| 440 |
def _main_cluster(pts):
|
|
@@ -498,21 +507,21 @@ def _clean(inst, cap=4000):
|
|
| 498 |
return pts
|
| 499 |
|
| 500 |
|
| 501 |
-
def answer_closest_distance(
|
| 502 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 503 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 504 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 505 |
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring."""
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
if len(
|
| 509 |
return float("inf")
|
| 510 |
from scipy.spatial import cKDTree
|
| 511 |
|
| 512 |
-
if len(
|
| 513 |
-
d, _ = cKDTree(
|
| 514 |
else:
|
| 515 |
-
d, _ = cKDTree(
|
| 516 |
return float(d.min())
|
| 517 |
|
| 518 |
|
|
@@ -600,7 +609,7 @@ def refine_mask(mask, rgb):
|
|
| 600 |
|
| 601 |
def backproject_frame(
|
| 602 |
depth_f,
|
| 603 |
-
|
| 604 |
c2w_f,
|
| 605 |
mask_f,
|
| 606 |
conf_f=None,
|
|
@@ -614,15 +623,15 @@ def backproject_frame(
|
|
| 614 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 615 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 616 |
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection)."""
|
| 617 |
-
|
| 618 |
empty = (
|
| 619 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
| 620 |
if return_conf
|
| 621 |
else np.empty((0, 3), np.float32)
|
| 622 |
)
|
| 623 |
-
if mask_f.shape != (
|
| 624 |
mask_f = cv2.resize(
|
| 625 |
-
mask_f.astype(np.uint8), (
|
| 626 |
).astype(bool)
|
| 627 |
if valid_f is None:
|
| 628 |
valid_f = np.isfinite(depth_f) & (depth_f > 0)
|
|
@@ -655,17 +664,24 @@ def backproject_frame(
|
|
| 655 |
keep = (z >= q1 - 1.5 * iqr) & (z <= q3 + 1.5 * iqr)
|
| 656 |
if keep.sum() >= 1:
|
| 657 |
ys, xs, z = ys[keep], xs[keep], z[keep]
|
| 658 |
-
fx, fy, cx, cy =
|
| 659 |
-
|
| 660 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 661 |
if return_conf:
|
| 662 |
cw = (
|
| 663 |
conf_f[ys, xs].astype(np.float32)
|
| 664 |
if conf_f is not None
|
| 665 |
else np.ones(len(ys), np.float32)
|
| 666 |
)
|
| 667 |
-
return
|
| 668 |
-
return
|
| 669 |
|
| 670 |
|
| 671 |
# ==========================================================================================
|
|
@@ -686,25 +702,31 @@ def robust_centroid_extent(pts, up_axis=None):
|
|
| 686 |
If up_axis is None (unknown at the call site): falls back to unconstrained 3D PCA.
|
| 687 |
Either way: parameter-free, rotation-invariant in-plane, p2..p98 robust extent."""
|
| 688 |
c = np.median(pts, axis=0)
|
| 689 |
-
|
| 690 |
-
if len(
|
| 691 |
-
|
| 692 |
if up_axis is not None:
|
| 693 |
floor_axes = [i for i in range(3) if i != up_axis]
|
| 694 |
-
|
| 695 |
try:
|
| 696 |
-
_, _,
|
| 697 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 698 |
except np.linalg.LinAlgError:
|
| 699 |
-
proj_floor =
|
| 700 |
-
up_col =
|
| 701 |
proj = np.concatenate([proj_floor, up_col], axis=1)
|
| 702 |
else:
|
| 703 |
try:
|
| 704 |
-
_, _,
|
| 705 |
-
|
|
|
|
|
|
|
| 706 |
except np.linalg.LinAlgError:
|
| 707 |
-
proj =
|
| 708 |
lo = np.percentile(proj, 2, axis=0)
|
| 709 |
hi = np.percentile(proj, 98, axis=0)
|
| 710 |
ext = np.maximum(hi - lo, 0.0)
|
|
@@ -864,7 +886,7 @@ def build_instances(
|
|
| 864 |
if (conf_f is not None and CONF_PCT > 0)
|
| 865 |
else 0.0
|
| 866 |
)
|
| 867 |
-
|
| 868 |
depth[fidx],
|
| 869 |
intr[fidx],
|
| 870 |
c2w[fidx],
|
|
@@ -875,8 +897,8 @@ def build_instances(
|
|
| 875 |
return_conf=True,
|
| 876 |
edges_f=edges.get(fidx),
|
| 877 |
)
|
| 878 |
-
if len(
|
| 879 |
-
pts_by_id.setdefault(oid, []).append(
|
| 880 |
conf_by_id.setdefault(oid, []).append(
|
| 881 |
cw
|
| 882 |
) # per-point DA3 confidence (for _clean)
|
|
@@ -966,8 +988,8 @@ def class_spatial_code(insts, peak=0):
|
|
| 966 |
def compute_floor_area(depth, intr, c2w, conf, sky, stride=8, up_vec=None):
|
| 967 |
pts = []
|
| 968 |
for f in range(depth.shape[0]):
|
| 969 |
-
|
| 970 |
-
ys, xs = np.mgrid[0:
|
| 971 |
ys = ys.ravel()
|
| 972 |
xs = xs.ravel()
|
| 973 |
z = depth[f][ys, xs]
|
|
@@ -979,14 +1001,19 @@ def compute_floor_area(depth, intr, c2w, conf, sky, stride=8, up_vec=None):
|
|
| 979 |
ys, xs, z = ys[ok], xs[ok], z[ok]
|
| 980 |
if not len(z):
|
| 981 |
continue
|
| 982 |
-
|
| 983 |
-
fx, fy, cx, cy =
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 987 |
if not pts:
|
| 988 |
return 0.0
|
| 989 |
-
|
| 990 |
if up_vec is not None:
|
| 991 |
# VSI-faithful: area in the plane orthogonal to GRAVITY (RANSAC floor normal), like the
|
| 992 |
# benchmark's gravity-aligned GT meshes. Build an orthonormal in-plane basis (u, v).
|
|
@@ -996,43 +1023,45 @@ def compute_floor_area(depth, intr, c2w, conf, sky, stride=8, up_vec=None):
|
|
| 996 |
u = np.cross(g, a)
|
| 997 |
u /= np.linalg.norm(u)
|
| 998 |
v = np.cross(g, u)
|
| 999 |
-
|
| 1000 |
else:
|
| 1001 |
up = int(
|
| 1002 |
-
np.argmin(
|
| 1003 |
) # legacy: vertical = smallest-extent axis
|
| 1004 |
floor_axes = [i for i in range(3) if i != up]
|
| 1005 |
-
|
| 1006 |
# VSI-Bench room-size definition = alpha-shape of the floor-plane point cloud (confirmed in their
|
| 1007 |
# paper appendix). VSI does not publish the alpha value they use for their own GT mesh, so alpha=2
|
| 1008 |
# here is NOT a matched/verified constant -- it was chosen empirically for this pipeline's own
|
| 1009 |
# (sparser) reconstructed point density. This is the one disclosed benchmark-adjacent tuned constant
|
| 1010 |
# in the whole file; everything else is exact/derived or a generic, non-tuned statistical convention.
|
| 1011 |
# (Falls back to enclosed-fill below if the alphashape package isn't available.)
|
| 1012 |
-
|
| 1013 |
-
lo = np.percentile(
|
| 1014 |
-
hi = np.percentile(
|
| 1015 |
-
|
| 1016 |
-
(
|
| 1017 |
-
& (
|
| 1018 |
-
& (
|
| 1019 |
-
& (
|
| 1020 |
]
|
| 1021 |
-
if len(
|
| 1022 |
return 0.0
|
| 1023 |
try:
|
| 1024 |
import alphashape
|
| 1025 |
|
| 1026 |
-
idx = np.random.RandomState(0).choice(
|
|
|
|
|
|
|
| 1027 |
return round(
|
| 1028 |
-
float(alphashape.alphashape(
|
| 1029 |
) # alpha=2 tuned for recon density
|
| 1030 |
except Exception:
|
| 1031 |
from scipy import ndimage
|
| 1032 |
|
| 1033 |
res = 0.10
|
| 1034 |
-
ai = ((
|
| 1035 |
-
bi = ((
|
| 1036 |
grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
|
| 1037 |
grid[ai + 1, bi + 1] = 1
|
| 1038 |
grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
|
@@ -1063,8 +1092,8 @@ def _room_outline(depth, intr, c2w, conf, bu, bv):
|
|
| 1063 |
|
| 1064 |
pts, stride = [], 8
|
| 1065 |
for f in range(0, depth.shape[0], 3):
|
| 1066 |
-
|
| 1067 |
-
ys, xs = np.mgrid[0:
|
| 1068 |
ys = ys.ravel()
|
| 1069 |
xs = xs.ravel()
|
| 1070 |
z = depth[f][ys, xs]
|
|
@@ -1074,31 +1103,38 @@ def _room_outline(depth, intr, c2w, conf, bu, bv):
|
|
| 1074 |
ys, xs, z = ys[ok], xs[ok], z[ok]
|
| 1075 |
if not len(z):
|
| 1076 |
continue
|
| 1077 |
-
|
| 1078 |
-
|
| 1079 |
-
[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1080 |
)
|
| 1081 |
-
pts.append(((c2w[f][:3, :3] @ Xc.T).T + c2w[f][:3, 3]).astype(np.float32))
|
| 1082 |
if not pts:
|
| 1083 |
return []
|
| 1084 |
-
|
| 1085 |
-
|
| 1086 |
-
[
|
| 1087 |
) # gravity-plane projection (same bu,bv as objects/area)
|
| 1088 |
-
lo = np.percentile(
|
| 1089 |
-
hi = np.percentile(
|
| 1090 |
-
|
| 1091 |
-
(
|
| 1092 |
-
& (
|
| 1093 |
-
& (
|
| 1094 |
-
& (
|
| 1095 |
]
|
| 1096 |
-
if len(
|
| 1097 |
return []
|
| 1098 |
res = 0.10
|
| 1099 |
-
x0, y0 =
|
| 1100 |
-
ai = ((
|
| 1101 |
-
bi = ((
|
| 1102 |
grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
|
| 1103 |
grid[ai + 1, bi + 1] = 1
|
| 1104 |
grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
|
@@ -1131,8 +1167,8 @@ def build_spatial_code_raw(depth, intr, c2w, conf, ftimes, per):
|
|
| 1131 |
# emission-time class rename: VSI's questions say 'coat rack' while their annotations
|
| 1132 |
# (and hence the SAM3 prompt + caches) say 'coat hanger' -- same object, their naming
|
| 1133 |
# seam. The model sees questions, so emitted codes follow the question vocabulary.
|
| 1134 |
-
|
| 1135 |
-
per = {
|
| 1136 |
inst, stats = build_instances(per, depth, intr, c2w, conf, ftimes)
|
| 1137 |
up_vec, up_ax = room_gravity(
|
| 1138 |
depth, intr, c2w, conf
|
|
@@ -1140,8 +1176,8 @@ def build_spatial_code_raw(depth, intr, c2w, conf, ftimes, per):
|
|
| 1140 |
bu, bv, bg = _floor_basis(
|
| 1141 |
up_vec
|
| 1142 |
) # shared gravity floor frame (bu,bv horizontal, bg up)
|
| 1143 |
-
|
| 1144 |
-
floor_level = _floor_level(
|
| 1145 |
fa = compute_floor_area(depth, intr, c2w, conf, None, up_vec=up_vec)
|
| 1146 |
code = to_spatial_code(inst, stats, fa, up_ax, up_vec, floor_level)
|
| 1147 |
cls = list(inst.keys())
|
|
@@ -1192,19 +1228,23 @@ def dump_spatial_code(code, path):
|
|
| 1192 |
|
| 1193 |
|
| 1194 |
# Canonical world-space fallback used by SegVGGT and similar adapters.
|
| 1195 |
-
def _canonical_room_gravity(
|
| 1196 |
"""Robust UP vector = normal of the RANSAC floor plane, oriented toward the cameras."""
|
| 1197 |
-
|
| 1198 |
-
|
| 1199 |
-
if len(
|
| 1200 |
-
|
| 1201 |
cam = (
|
| 1202 |
np.asarray(cameras, np.float64).mean(0)
|
| 1203 |
if cameras is not None and len(cameras)
|
| 1204 |
else None
|
| 1205 |
)
|
| 1206 |
-
if len(
|
| 1207 |
-
ext =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1208 |
ax = int(np.argmin(ext))
|
| 1209 |
g = np.zeros(3)
|
| 1210 |
g[ax] = 1.0
|
|
@@ -1213,14 +1253,14 @@ def _canonical_room_gravity(P, cameras=None, iters=300, thr=0.05):
|
|
| 1213 |
best = None
|
| 1214 |
best_score = -1
|
| 1215 |
for _ in range(iters):
|
| 1216 |
-
a, b, c =
|
| 1217 |
nrm = np.cross(b - a, c - a)
|
| 1218 |
ln = np.linalg.norm(nrm)
|
| 1219 |
if ln < 1e-06:
|
| 1220 |
continue
|
| 1221 |
nrm /= ln
|
| 1222 |
d = -nrm @ a
|
| 1223 |
-
side =
|
| 1224 |
ninl = int((np.abs(side) < thr).sum())
|
| 1225 |
if ninl < 50:
|
| 1226 |
continue
|
|
@@ -1229,7 +1269,7 @@ def _canonical_room_gravity(P, cameras=None, iters=300, thr=0.05):
|
|
| 1229 |
best_score = score
|
| 1230 |
best = (nrm, d)
|
| 1231 |
if best is None:
|
| 1232 |
-
ext = np.percentile(
|
| 1233 |
ax = int(np.argmin(ext))
|
| 1234 |
g = np.zeros(3)
|
| 1235 |
g[ax] = 1.0
|
|
@@ -1258,24 +1298,28 @@ def _canonical_floor_basis(up_vec):
|
|
| 1258 |
|
| 1259 |
def _canonical_robust_centroid_extent(pts, up_axis=None):
|
| 1260 |
c = np.median(pts, axis=0)
|
| 1261 |
-
|
| 1262 |
-
if len(
|
| 1263 |
-
|
| 1264 |
if up_axis is not None:
|
| 1265 |
floor_axes = [i for i in range(3) if i != up_axis]
|
| 1266 |
-
|
| 1267 |
try:
|
| 1268 |
-
_, _,
|
| 1269 |
-
|
|
|
|
|
|
|
| 1270 |
except np.linalg.LinAlgError:
|
| 1271 |
-
proj_floor =
|
| 1272 |
-
proj = np.concatenate([proj_floor,
|
| 1273 |
else:
|
| 1274 |
try:
|
| 1275 |
-
_, _,
|
| 1276 |
-
|
|
|
|
|
|
|
| 1277 |
except np.linalg.LinAlgError:
|
| 1278 |
-
proj =
|
| 1279 |
ext = np.maximum(np.percentile(proj, 98, 0) - np.percentile(proj, 2, 0), 0.0)
|
| 1280 |
dims = np.sort(ext)[::-1]
|
| 1281 |
return (c.astype(np.float32), float(dims[0]), dims)
|
|
@@ -1348,14 +1392,14 @@ def _canonical_sor(pts, k=16, std=2.0, cap=4000):
|
|
| 1348 |
|
| 1349 |
if len(pts) < k + 2:
|
| 1350 |
return pts
|
| 1351 |
-
|
| 1352 |
pts
|
| 1353 |
if len(pts) <= cap
|
| 1354 |
else pts[np.random.RandomState(0).choice(len(pts), cap, False)]
|
| 1355 |
)
|
| 1356 |
-
d, _ = cKDTree(
|
| 1357 |
md = d[:, 1:].mean(1)
|
| 1358 |
-
return
|
| 1359 |
|
| 1360 |
|
| 1361 |
def _canonical_clean(inst, cap=4000):
|
|
@@ -1379,27 +1423,27 @@ def _canonical_rep(insts):
|
|
| 1379 |
return max(insts, key=lambda i: (i.get("n", len(i["pts"])), i.get("nframes", 0)))
|
| 1380 |
|
| 1381 |
|
| 1382 |
-
def _canonical_answer_closest_distance(
|
| 1383 |
from scipy.spatial import cKDTree
|
| 1384 |
|
| 1385 |
-
|
| 1386 |
-
_canonical_clean(_canonical_rep(
|
| 1387 |
-
_canonical_clean(_canonical_rep(
|
| 1388 |
)
|
| 1389 |
-
if not len(
|
| 1390 |
return float("inf")
|
| 1391 |
d, _ = (
|
| 1392 |
-
cKDTree(
|
| 1393 |
-
if len(
|
| 1394 |
-
else cKDTree(
|
| 1395 |
)
|
| 1396 |
return float(d.min())
|
| 1397 |
|
| 1398 |
|
| 1399 |
-
def _canonical_compute_floor_area(
|
| 1400 |
-
|
| 1401 |
-
|
| 1402 |
-
if not len(
|
| 1403 |
return 0.0
|
| 1404 |
g = np.asarray(up_vec, np.float64)
|
| 1405 |
g /= np.linalg.norm(g) + 1e-12
|
|
@@ -1407,27 +1451,29 @@ def _canonical_compute_floor_area(P, up_vec):
|
|
| 1407 |
u = np.cross(g, a)
|
| 1408 |
u /= np.linalg.norm(u)
|
| 1409 |
v = np.cross(g, u)
|
| 1410 |
-
|
| 1411 |
-
lo, hi = (np.percentile(
|
| 1412 |
-
|
| 1413 |
-
(
|
| 1414 |
-
& (
|
| 1415 |
-
& (
|
| 1416 |
-
& (
|
| 1417 |
]
|
| 1418 |
-
if len(
|
| 1419 |
return 0.0
|
| 1420 |
try:
|
| 1421 |
import alphashape
|
| 1422 |
|
| 1423 |
-
idx = np.random.RandomState(0).choice(
|
| 1424 |
-
|
|
|
|
|
|
|
| 1425 |
except Exception:
|
| 1426 |
from scipy import ndimage
|
| 1427 |
|
| 1428 |
res = 0.1
|
| 1429 |
-
ai = ((
|
| 1430 |
-
bi = ((
|
| 1431 |
grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
|
| 1432 |
grid[ai + 1, bi + 1] = 1
|
| 1433 |
grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
|
|
|
| 102 |
"""up axis = smallest-extent axis of all object points; sign from gravity (floor->camera).
|
| 103 |
Floor = densest horizontal slab; cameras are always above it, which fixes the sign.
|
| 104 |
Returns (axis_index, signed_unit_vector)."""
|
| 105 |
+
points = np.concatenate([i["pts"] for v in instances.values() for i in v], 0)
|
| 106 |
+
ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
|
| 107 |
up = int(np.argmin(ext))
|
| 108 |
+
h, edges = np.histogram(points[:, up], bins=80)
|
| 109 |
floor = 0.5 * (edges[h.argmax()] + edges[h.argmax() + 1]) # densest slab = floor
|
| 110 |
cam_up = c2w[:, :3, 3][:, up].mean()
|
| 111 |
e = np.zeros(3, np.float32)
|
|
|
|
| 119 |
"""Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
|
| 120 |
the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
|
| 121 |
Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis)."""
|
| 122 |
+
points = []
|
| 123 |
for f in range(0, len(depth), fstride):
|
| 124 |
+
height, width = depth[f].shape
|
| 125 |
+
ys, xs = np.mgrid[0:height:stride, 0:width:stride]
|
| 126 |
ys = ys.ravel()
|
| 127 |
xs = xs.ravel()
|
| 128 |
z = depth[f][ys, xs]
|
|
|
|
| 132 |
ys, xs, z = ys[ok], xs[ok], z[ok]
|
| 133 |
if not len(z):
|
| 134 |
continue
|
| 135 |
+
intrinsics = intr[f]
|
| 136 |
+
camera_points = np.stack(
|
| 137 |
+
[
|
| 138 |
+
(xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
|
| 139 |
+
(ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
|
| 140 |
+
z,
|
| 141 |
+
],
|
| 142 |
+
1,
|
| 143 |
)
|
| 144 |
+
points.append((c2w[f][:3, :3] @ camera_points.T).T + c2w[f][:3, 3])
|
| 145 |
+
points = np.concatenate(points).astype(np.float64) if points else np.zeros((0, 3))
|
| 146 |
cam = c2w[:, :3, 3].mean(0)
|
| 147 |
+
if len(points) < 100: # fallback to axis-extent
|
| 148 |
+
ext = (
|
| 149 |
+
np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
|
| 150 |
+
if len(points)
|
| 151 |
+
else np.ones(3)
|
| 152 |
+
)
|
| 153 |
ax = int(np.argmin(ext))
|
| 154 |
g = np.zeros(3)
|
| 155 |
g[ax] = 1.0
|
|
|
|
| 158 |
best = None
|
| 159 |
best_score = -1
|
| 160 |
for _ in range(iters):
|
| 161 |
+
a, b, c = points[rng.choice(len(points), 3, False)]
|
| 162 |
nrm = np.cross(b - a, c - a)
|
| 163 |
ln = np.linalg.norm(nrm)
|
| 164 |
if ln < 1e-6:
|
| 165 |
continue
|
| 166 |
nrm /= ln
|
| 167 |
d = -nrm @ a
|
| 168 |
+
side = points @ nrm + d
|
| 169 |
ninl = int((np.abs(side) < thr).sum())
|
| 170 |
if ninl < 50:
|
| 171 |
continue
|
|
|
|
| 176 |
best_score = score
|
| 177 |
best = (nrm, d)
|
| 178 |
if best is None:
|
| 179 |
+
ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
|
| 180 |
ax = int(np.argmin(ext))
|
| 181 |
g = np.zeros(3)
|
| 182 |
g[ax] = 1.0
|
|
|
|
| 323 |
return max(insts, key=lambda i: i["n"])
|
| 324 |
|
| 325 |
|
| 326 |
+
def answer_rel_direction(point_a, point_b, point_c, up_vec, up_ax, mode="hard"):
|
| 327 |
"""Standing at A facing B, where is C? front/back=dot(C-A,fwd); left/right=dot(C-A, up x fwd).
|
| 328 |
Right-handed world (OpenCV cam frame + det+1 c2w) makes up x fwd = left a fixed identity.
|
| 329 |
Projection uses the gravity VECTOR (v-(v.g)g), so a tilted floor (ScanNet++) is handled; for an
|
|
|
|
| 335 |
w = v.astype(np.float64)
|
| 336 |
return w - (w @ g) * g
|
| 337 |
|
| 338 |
+
fwd = fl(point_b - point_a)
|
| 339 |
n = np.linalg.norm(fwd)
|
| 340 |
if n < 1e-6:
|
| 341 |
return None
|
| 342 |
fwd /= n
|
| 343 |
left = np.cross(g, fwd)
|
| 344 |
left /= np.linalg.norm(left) + 1e-9
|
| 345 |
+
d = fl(point_c - point_a)
|
| 346 |
f = float(d @ fwd)
|
| 347 |
lateral = float(d @ left)
|
| 348 |
if mode == "medium":
|
|
|
|
| 440 |
if len(pts) < k + 2:
|
| 441 |
return pts
|
| 442 |
rs = np.random.RandomState(0)
|
| 443 |
+
points = pts if len(pts) <= cap else pts[rs.choice(len(pts), cap, False)]
|
| 444 |
+
d, _ = cKDTree(points).query(points, k=k + 1, workers=KD_WORKERS)
|
| 445 |
md = d[:, 1:].mean(1)
|
| 446 |
+
return points[md <= md.mean() + std * md.std()]
|
| 447 |
|
| 448 |
|
| 449 |
def _main_cluster(pts):
|
|
|
|
| 507 |
return pts
|
| 508 |
|
| 509 |
|
| 510 |
+
def answer_closest_distance(instances_a, instances_b, k=4000):
|
| 511 |
"""Closest distance between the two objects' point clouds ('closest point of each object'). Points are
|
| 512 |
cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
|
| 513 |
KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
|
| 514 |
boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring."""
|
| 515 |
+
points_a = _clean(_rep(instances_a), cap=k)
|
| 516 |
+
points_b = _clean(_rep(instances_b), cap=k)
|
| 517 |
+
if len(points_a) == 0 or len(points_b) == 0:
|
| 518 |
return float("inf")
|
| 519 |
from scipy.spatial import cKDTree
|
| 520 |
|
| 521 |
+
if len(points_a) <= len(points_b):
|
| 522 |
+
d, _ = cKDTree(points_a).query(points_b, k=1, workers=KD_WORKERS)
|
| 523 |
else:
|
| 524 |
+
d, _ = cKDTree(points_b).query(points_a, k=1, workers=KD_WORKERS)
|
| 525 |
return float(d.min())
|
| 526 |
|
| 527 |
|
|
|
|
| 609 |
|
| 610 |
def backproject_frame(
|
| 611 |
depth_f,
|
| 612 |
+
intrinsics,
|
| 613 |
c2w_f,
|
| 614 |
mask_f,
|
| 615 |
conf_f=None,
|
|
|
|
| 623 |
return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
|
| 624 |
edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
|
| 625 |
(cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection)."""
|
| 626 |
+
height, width = depth_f.shape
|
| 627 |
empty = (
|
| 628 |
(np.empty((0, 3), np.float32), np.empty((0,), np.float32))
|
| 629 |
if return_conf
|
| 630 |
else np.empty((0, 3), np.float32)
|
| 631 |
)
|
| 632 |
+
if mask_f.shape != (height, width):
|
| 633 |
mask_f = cv2.resize(
|
| 634 |
+
mask_f.astype(np.uint8), (width, height), interpolation=cv2.INTER_NEAREST
|
| 635 |
).astype(bool)
|
| 636 |
if valid_f is None:
|
| 637 |
valid_f = np.isfinite(depth_f) & (depth_f > 0)
|
|
|
|
| 664 |
keep = (z >= q1 - 1.5 * iqr) & (z <= q3 + 1.5 * iqr)
|
| 665 |
if keep.sum() >= 1:
|
| 666 |
ys, xs, z = ys[keep], xs[keep], z[keep]
|
| 667 |
+
fx, fy, cx, cy = (
|
| 668 |
+
intrinsics[0, 0],
|
| 669 |
+
intrinsics[1, 1],
|
| 670 |
+
intrinsics[0, 2],
|
| 671 |
+
intrinsics[1, 2],
|
| 672 |
+
)
|
| 673 |
+
camera_points = np.stack(
|
| 674 |
+
[(xs - cx) * z / fx, (ys - cy) * z / fy, z], axis=1
|
| 675 |
+
) # camera coords
|
| 676 |
+
world_points = (c2w_f[:3, :3] @ camera_points.T).T + c2w_f[:3, 3] # -> world
|
| 677 |
if return_conf:
|
| 678 |
cw = (
|
| 679 |
conf_f[ys, xs].astype(np.float32)
|
| 680 |
if conf_f is not None
|
| 681 |
else np.ones(len(ys), np.float32)
|
| 682 |
)
|
| 683 |
+
return world_points.astype(np.float32), cw
|
| 684 |
+
return world_points.astype(np.float32)
|
| 685 |
|
| 686 |
|
| 687 |
# ==========================================================================================
|
|
|
|
| 702 |
If up_axis is None (unknown at the call site): falls back to unconstrained 3D PCA.
|
| 703 |
Either way: parameter-free, rotation-invariant in-plane, p2..p98 robust extent."""
|
| 704 |
c = np.median(pts, axis=0)
|
| 705 |
+
centered = pts - c
|
| 706 |
+
if len(centered) > 5000: # PCA on a sample (deterministic)
|
| 707 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
| 708 |
if up_axis is not None:
|
| 709 |
floor_axes = [i for i in range(3) if i != up_axis]
|
| 710 |
+
floor_points = centered[:, floor_axes]
|
| 711 |
try:
|
| 712 |
+
_, _, floor_rotation = np.linalg.svd(
|
| 713 |
+
floor_points - floor_points.mean(0), full_matrices=False
|
| 714 |
+
)
|
| 715 |
+
proj_floor = (
|
| 716 |
+
floor_points @ floor_rotation.T
|
| 717 |
+
) # (N,2) along the object's own floor-plane axes
|
| 718 |
except np.linalg.LinAlgError:
|
| 719 |
+
proj_floor = floor_points
|
| 720 |
+
up_col = centered[:, up_axis : up_axis + 1] # up axis untouched (yaw-only)
|
| 721 |
proj = np.concatenate([proj_floor, up_col], axis=1)
|
| 722 |
else:
|
| 723 |
try:
|
| 724 |
+
_, _, rotation = np.linalg.svd(
|
| 725 |
+
centered - centered.mean(0), full_matrices=False
|
| 726 |
+
)
|
| 727 |
+
proj = centered @ rotation.T # coordinates along principal axes
|
| 728 |
except np.linalg.LinAlgError:
|
| 729 |
+
proj = centered
|
| 730 |
lo = np.percentile(proj, 2, axis=0)
|
| 731 |
hi = np.percentile(proj, 98, axis=0)
|
| 732 |
ext = np.maximum(hi - lo, 0.0)
|
|
|
|
| 886 |
if (conf_f is not None and CONF_PCT > 0)
|
| 887 |
else 0.0
|
| 888 |
)
|
| 889 |
+
world_points, cw = backproject_frame(
|
| 890 |
depth[fidx],
|
| 891 |
intr[fidx],
|
| 892 |
c2w[fidx],
|
|
|
|
| 897 |
return_conf=True,
|
| 898 |
edges_f=edges.get(fidx),
|
| 899 |
)
|
| 900 |
+
if len(world_points):
|
| 901 |
+
pts_by_id.setdefault(oid, []).append(world_points)
|
| 902 |
conf_by_id.setdefault(oid, []).append(
|
| 903 |
cw
|
| 904 |
) # per-point DA3 confidence (for _clean)
|
|
|
|
| 988 |
def compute_floor_area(depth, intr, c2w, conf, sky, stride=8, up_vec=None):
|
| 989 |
pts = []
|
| 990 |
for f in range(depth.shape[0]):
|
| 991 |
+
height, width = depth[f].shape
|
| 992 |
+
ys, xs = np.mgrid[0:height:stride, 0:width:stride]
|
| 993 |
ys = ys.ravel()
|
| 994 |
xs = xs.ravel()
|
| 995 |
z = depth[f][ys, xs]
|
|
|
|
| 1001 |
ys, xs, z = ys[ok], xs[ok], z[ok]
|
| 1002 |
if not len(z):
|
| 1003 |
continue
|
| 1004 |
+
intrinsics = intr[f]
|
| 1005 |
+
fx, fy, cx, cy = (
|
| 1006 |
+
intrinsics[0, 0],
|
| 1007 |
+
intrinsics[1, 1],
|
| 1008 |
+
intrinsics[0, 2],
|
| 1009 |
+
intrinsics[1, 2],
|
| 1010 |
+
)
|
| 1011 |
+
camera_points = np.stack([(xs - cx) * z / fx, (ys - cy) * z / fy, z], 1)
|
| 1012 |
+
world_points = (c2w[f][:3, :3] @ camera_points.T).T + c2w[f][:3, 3]
|
| 1013 |
+
pts.append(world_points.astype(np.float32))
|
| 1014 |
if not pts:
|
| 1015 |
return 0.0
|
| 1016 |
+
points = np.concatenate(pts, 0)
|
| 1017 |
if up_vec is not None:
|
| 1018 |
# VSI-faithful: area in the plane orthogonal to GRAVITY (RANSAC floor normal), like the
|
| 1019 |
# benchmark's gravity-aligned GT meshes. Build an orthonormal in-plane basis (u, v).
|
|
|
|
| 1023 |
u = np.cross(g, a)
|
| 1024 |
u /= np.linalg.norm(u)
|
| 1025 |
v = np.cross(g, u)
|
| 1026 |
+
all_floor_points = np.stack([points @ u, points @ v], 1)
|
| 1027 |
else:
|
| 1028 |
up = int(
|
| 1029 |
+
np.argmin(points.max(0) - points.min(0))
|
| 1030 |
) # legacy: vertical = smallest-extent axis
|
| 1031 |
floor_axes = [i for i in range(3) if i != up]
|
| 1032 |
+
all_floor_points = points[:, floor_axes]
|
| 1033 |
# VSI-Bench room-size definition = alpha-shape of the floor-plane point cloud (confirmed in their
|
| 1034 |
# paper appendix). VSI does not publish the alpha value they use for their own GT mesh, so alpha=2
|
| 1035 |
# here is NOT a matched/verified constant -- it was chosen empirically for this pipeline's own
|
| 1036 |
# (sparser) reconstructed point density. This is the one disclosed benchmark-adjacent tuned constant
|
| 1037 |
# in the whole file; everything else is exact/derived or a generic, non-tuned statistical convention.
|
| 1038 |
# (Falls back to enclosed-fill below if the alphashape package isn't available.)
|
| 1039 |
+
floor_points = all_floor_points
|
| 1040 |
+
lo = np.percentile(floor_points, 0.5, 0)
|
| 1041 |
+
hi = np.percentile(floor_points, 99.5, 0) # gentle clip (preserve room extent)
|
| 1042 |
+
floor_points = floor_points[
|
| 1043 |
+
(floor_points[:, 0] >= lo[0])
|
| 1044 |
+
& (floor_points[:, 0] <= hi[0])
|
| 1045 |
+
& (floor_points[:, 1] >= lo[1])
|
| 1046 |
+
& (floor_points[:, 1] <= hi[1])
|
| 1047 |
]
|
| 1048 |
+
if len(floor_points) < 10:
|
| 1049 |
return 0.0
|
| 1050 |
try:
|
| 1051 |
import alphashape
|
| 1052 |
|
| 1053 |
+
idx = np.random.RandomState(0).choice(
|
| 1054 |
+
len(floor_points), min(10000, len(floor_points))
|
| 1055 |
+
)
|
| 1056 |
return round(
|
| 1057 |
+
float(alphashape.alphashape(floor_points[idx], alpha=2).area), 1
|
| 1058 |
) # alpha=2 tuned for recon density
|
| 1059 |
except Exception:
|
| 1060 |
from scipy import ndimage
|
| 1061 |
|
| 1062 |
res = 0.10
|
| 1063 |
+
ai = ((floor_points[:, 0] - floor_points[:, 0].min()) / res).astype(int)
|
| 1064 |
+
bi = ((floor_points[:, 1] - floor_points[:, 1].min()) / res).astype(int)
|
| 1065 |
grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
|
| 1066 |
grid[ai + 1, bi + 1] = 1
|
| 1067 |
grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
|
|
|
| 1092 |
|
| 1093 |
pts, stride = [], 8
|
| 1094 |
for f in range(0, depth.shape[0], 3):
|
| 1095 |
+
height, width = depth[f].shape
|
| 1096 |
+
ys, xs = np.mgrid[0:height:stride, 0:width:stride]
|
| 1097 |
ys = ys.ravel()
|
| 1098 |
xs = xs.ravel()
|
| 1099 |
z = depth[f][ys, xs]
|
|
|
|
| 1103 |
ys, xs, z = ys[ok], xs[ok], z[ok]
|
| 1104 |
if not len(z):
|
| 1105 |
continue
|
| 1106 |
+
intrinsics = intr[f]
|
| 1107 |
+
camera_points = np.stack(
|
| 1108 |
+
[
|
| 1109 |
+
(xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
|
| 1110 |
+
(ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
|
| 1111 |
+
z,
|
| 1112 |
+
],
|
| 1113 |
+
1,
|
| 1114 |
+
)
|
| 1115 |
+
pts.append(
|
| 1116 |
+
((c2w[f][:3, :3] @ camera_points.T).T + c2w[f][:3, 3]).astype(np.float32)
|
| 1117 |
)
|
|
|
|
| 1118 |
if not pts:
|
| 1119 |
return []
|
| 1120 |
+
world_points = np.concatenate(pts, 0)
|
| 1121 |
+
points = np.stack(
|
| 1122 |
+
[world_points @ bu, world_points @ bv], 1
|
| 1123 |
) # gravity-plane projection (same bu,bv as objects/area)
|
| 1124 |
+
lo = np.percentile(points, 0.5, 0)
|
| 1125 |
+
hi = np.percentile(points, 99.5, 0)
|
| 1126 |
+
points = points[
|
| 1127 |
+
(points[:, 0] >= lo[0])
|
| 1128 |
+
& (points[:, 0] <= hi[0])
|
| 1129 |
+
& (points[:, 1] >= lo[1])
|
| 1130 |
+
& (points[:, 1] <= hi[1])
|
| 1131 |
]
|
| 1132 |
+
if len(points) < 10:
|
| 1133 |
return []
|
| 1134 |
res = 0.10
|
| 1135 |
+
x0, y0 = points[:, 0].min(), points[:, 1].min()
|
| 1136 |
+
ai = ((points[:, 0] - x0) / res).astype(int)
|
| 1137 |
+
bi = ((points[:, 1] - y0) / res).astype(int)
|
| 1138 |
grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
|
| 1139 |
grid[ai + 1, bi + 1] = 1
|
| 1140 |
grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
|
|
|
| 1167 |
# emission-time class rename: VSI's questions say 'coat rack' while their annotations
|
| 1168 |
# (and hence the SAM3 prompt + caches) say 'coat hanger' -- same object, their naming
|
| 1169 |
# seam. The model sees questions, so emitted codes follow the question vocabulary.
|
| 1170 |
+
class_aliases = {"coat hanger": "coat rack"}
|
| 1171 |
+
per = {class_aliases.get(k, k): v for k, v in per.items()}
|
| 1172 |
inst, stats = build_instances(per, depth, intr, c2w, conf, ftimes)
|
| 1173 |
up_vec, up_ax = room_gravity(
|
| 1174 |
depth, intr, c2w, conf
|
|
|
|
| 1176 |
bu, bv, bg = _floor_basis(
|
| 1177 |
up_vec
|
| 1178 |
) # shared gravity floor frame (bu,bv horizontal, bg up)
|
| 1179 |
+
points = np.concatenate([i["pts"] for cl in inst.values() for i in cl], 0)
|
| 1180 |
+
floor_level = _floor_level(points, bg)
|
| 1181 |
fa = compute_floor_area(depth, intr, c2w, conf, None, up_vec=up_vec)
|
| 1182 |
code = to_spatial_code(inst, stats, fa, up_ax, up_vec, floor_level)
|
| 1183 |
cls = list(inst.keys())
|
|
|
|
| 1228 |
|
| 1229 |
|
| 1230 |
# Canonical world-space fallback used by SegVGGT and similar adapters.
|
| 1231 |
+
def _canonical_room_gravity(points, cameras=None, iters=300, thr=0.05):
|
| 1232 |
"""Robust UP vector = normal of the RANSAC floor plane, oriented toward the cameras."""
|
| 1233 |
+
points = np.asarray(points, np.float64)
|
| 1234 |
+
points = points[np.isfinite(points).all(1)]
|
| 1235 |
+
if len(points) > 100000:
|
| 1236 |
+
points = points[np.random.RandomState(0).choice(len(points), 100000, False)]
|
| 1237 |
cam = (
|
| 1238 |
np.asarray(cameras, np.float64).mean(0)
|
| 1239 |
if cameras is not None and len(cameras)
|
| 1240 |
else None
|
| 1241 |
)
|
| 1242 |
+
if len(points) < 100:
|
| 1243 |
+
ext = (
|
| 1244 |
+
np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
|
| 1245 |
+
if len(points)
|
| 1246 |
+
else np.ones(3)
|
| 1247 |
+
)
|
| 1248 |
ax = int(np.argmin(ext))
|
| 1249 |
g = np.zeros(3)
|
| 1250 |
g[ax] = 1.0
|
|
|
|
| 1253 |
best = None
|
| 1254 |
best_score = -1
|
| 1255 |
for _ in range(iters):
|
| 1256 |
+
a, b, c = points[rng.choice(len(points), 3, False)]
|
| 1257 |
nrm = np.cross(b - a, c - a)
|
| 1258 |
ln = np.linalg.norm(nrm)
|
| 1259 |
if ln < 1e-06:
|
| 1260 |
continue
|
| 1261 |
nrm /= ln
|
| 1262 |
d = -nrm @ a
|
| 1263 |
+
side = points @ nrm + d
|
| 1264 |
ninl = int((np.abs(side) < thr).sum())
|
| 1265 |
if ninl < 50:
|
| 1266 |
continue
|
|
|
|
| 1269 |
best_score = score
|
| 1270 |
best = (nrm, d)
|
| 1271 |
if best is None:
|
| 1272 |
+
ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
|
| 1273 |
ax = int(np.argmin(ext))
|
| 1274 |
g = np.zeros(3)
|
| 1275 |
g[ax] = 1.0
|
|
|
|
| 1298 |
|
| 1299 |
def _canonical_robust_centroid_extent(pts, up_axis=None):
|
| 1300 |
c = np.median(pts, axis=0)
|
| 1301 |
+
centered = pts - c
|
| 1302 |
+
if len(centered) > 5000:
|
| 1303 |
+
centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
|
| 1304 |
if up_axis is not None:
|
| 1305 |
floor_axes = [i for i in range(3) if i != up_axis]
|
| 1306 |
+
floor_points = centered[:, floor_axes]
|
| 1307 |
try:
|
| 1308 |
+
_, _, floor_rotation = np.linalg.svd(
|
| 1309 |
+
floor_points - floor_points.mean(0), full_matrices=False
|
| 1310 |
+
)
|
| 1311 |
+
proj_floor = floor_points @ floor_rotation.T
|
| 1312 |
except np.linalg.LinAlgError:
|
| 1313 |
+
proj_floor = floor_points
|
| 1314 |
+
proj = np.concatenate([proj_floor, centered[:, up_axis : up_axis + 1]], 1)
|
| 1315 |
else:
|
| 1316 |
try:
|
| 1317 |
+
_, _, rotation = np.linalg.svd(
|
| 1318 |
+
centered - centered.mean(0), full_matrices=False
|
| 1319 |
+
)
|
| 1320 |
+
proj = centered @ rotation.T
|
| 1321 |
except np.linalg.LinAlgError:
|
| 1322 |
+
proj = centered
|
| 1323 |
ext = np.maximum(np.percentile(proj, 98, 0) - np.percentile(proj, 2, 0), 0.0)
|
| 1324 |
dims = np.sort(ext)[::-1]
|
| 1325 |
return (c.astype(np.float32), float(dims[0]), dims)
|
|
|
|
| 1392 |
|
| 1393 |
if len(pts) < k + 2:
|
| 1394 |
return pts
|
| 1395 |
+
points = (
|
| 1396 |
pts
|
| 1397 |
if len(pts) <= cap
|
| 1398 |
else pts[np.random.RandomState(0).choice(len(pts), cap, False)]
|
| 1399 |
)
|
| 1400 |
+
d, _ = cKDTree(points).query(points, k=k + 1, workers=KD_WORKERS)
|
| 1401 |
md = d[:, 1:].mean(1)
|
| 1402 |
+
return points[md <= md.mean() + std * md.std()]
|
| 1403 |
|
| 1404 |
|
| 1405 |
def _canonical_clean(inst, cap=4000):
|
|
|
|
| 1423 |
return max(insts, key=lambda i: (i.get("n", len(i["pts"])), i.get("nframes", 0)))
|
| 1424 |
|
| 1425 |
|
| 1426 |
+
def _canonical_answer_closest_distance(instances_a, instances_b, k=4000):
|
| 1427 |
from scipy.spatial import cKDTree
|
| 1428 |
|
| 1429 |
+
points_a, points_b = (
|
| 1430 |
+
_canonical_clean(_canonical_rep(instances_a), k),
|
| 1431 |
+
_canonical_clean(_canonical_rep(instances_b), k),
|
| 1432 |
)
|
| 1433 |
+
if not len(points_a) or not len(points_b):
|
| 1434 |
return float("inf")
|
| 1435 |
d, _ = (
|
| 1436 |
+
cKDTree(points_a).query(points_b, workers=KD_WORKERS)
|
| 1437 |
+
if len(points_a) <= len(points_b)
|
| 1438 |
+
else cKDTree(points_b).query(points_a, workers=KD_WORKERS)
|
| 1439 |
)
|
| 1440 |
return float(d.min())
|
| 1441 |
|
| 1442 |
|
| 1443 |
+
def _canonical_compute_floor_area(points, up_vec):
|
| 1444 |
+
points = np.asarray(points, np.float32)
|
| 1445 |
+
points = points[np.isfinite(points).all(1)]
|
| 1446 |
+
if not len(points):
|
| 1447 |
return 0.0
|
| 1448 |
g = np.asarray(up_vec, np.float64)
|
| 1449 |
g /= np.linalg.norm(g) + 1e-12
|
|
|
|
| 1451 |
u = np.cross(g, a)
|
| 1452 |
u /= np.linalg.norm(u)
|
| 1453 |
v = np.cross(g, u)
|
| 1454 |
+
floor_points = np.stack([points @ u, points @ v], 1)
|
| 1455 |
+
lo, hi = (np.percentile(floor_points, 0.5, 0), np.percentile(floor_points, 99.5, 0))
|
| 1456 |
+
floor_points = floor_points[
|
| 1457 |
+
(floor_points[:, 0] >= lo[0])
|
| 1458 |
+
& (floor_points[:, 0] <= hi[0])
|
| 1459 |
+
& (floor_points[:, 1] >= lo[1])
|
| 1460 |
+
& (floor_points[:, 1] <= hi[1])
|
| 1461 |
]
|
| 1462 |
+
if len(floor_points) < 10:
|
| 1463 |
return 0.0
|
| 1464 |
try:
|
| 1465 |
import alphashape
|
| 1466 |
|
| 1467 |
+
idx = np.random.RandomState(0).choice(
|
| 1468 |
+
len(floor_points), min(10000, len(floor_points))
|
| 1469 |
+
)
|
| 1470 |
+
return round(float(alphashape.alphashape(floor_points[idx], alpha=2).area), 1)
|
| 1471 |
except Exception:
|
| 1472 |
from scipy import ndimage
|
| 1473 |
|
| 1474 |
res = 0.1
|
| 1475 |
+
ai = ((floor_points[:, 0] - floor_points[:, 0].min()) / res).astype(int)
|
| 1476 |
+
bi = ((floor_points[:, 1] - floor_points[:, 1].min()) / res).astype(int)
|
| 1477 |
grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
|
| 1478 |
grid[ai + 1, bi + 1] = 1
|
| 1479 |
grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
encoder/launch.py
CHANGED
|
@@ -17,11 +17,11 @@ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
|
|
| 17 |
if str(WORKSPACE_ROOT) not in sys.path:
|
| 18 |
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 19 |
|
| 20 |
-
from encoder import config
|
| 21 |
|
| 22 |
|
| 23 |
def _scenes():
|
| 24 |
-
with open(
|
| 25 |
return list(dict.fromkeys(str(json.loads(line)["scene_name"]) for line in f))
|
| 26 |
|
| 27 |
|
|
@@ -62,7 +62,7 @@ def main():
|
|
| 62 |
p = argparse.ArgumentParser()
|
| 63 |
p.add_argument("scene", nargs="?")
|
| 64 |
p.add_argument("--all", action="store_true")
|
| 65 |
-
p.add_argument("--model", default=
|
| 66 |
p.add_argument(
|
| 67 |
"--workers",
|
| 68 |
type=int,
|
|
@@ -76,7 +76,7 @@ def main():
|
|
| 76 |
pending = []
|
| 77 |
completed = 0
|
| 78 |
for scene in scenes:
|
| 79 |
-
if os.path.exists(
|
| 80 |
completed += 1
|
| 81 |
print(f"[{completed}/{len(scenes)}] {scene}: skipped", flush=True)
|
| 82 |
else:
|
|
|
|
| 17 |
if str(WORKSPACE_ROOT) not in sys.path:
|
| 18 |
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 19 |
|
| 20 |
+
from encoder import config # noqa: E402
|
| 21 |
|
| 22 |
|
| 23 |
def _scenes():
|
| 24 |
+
with open(config.JSONL) as f:
|
| 25 |
return list(dict.fromkeys(str(json.loads(line)["scene_name"]) for line in f))
|
| 26 |
|
| 27 |
|
|
|
|
| 62 |
p = argparse.ArgumentParser()
|
| 63 |
p.add_argument("scene", nargs="?")
|
| 64 |
p.add_argument("--all", action="store_true")
|
| 65 |
+
p.add_argument("--model", default=config.MODEL)
|
| 66 |
p.add_argument(
|
| 67 |
"--workers",
|
| 68 |
type=int,
|
|
|
|
| 76 |
pending = []
|
| 77 |
completed = 0
|
| 78 |
for scene in scenes:
|
| 79 |
+
if os.path.exists(config.spatial_code_path(scene, a.model)) and not a.rebuild:
|
| 80 |
completed += 1
|
| 81 |
print(f"[{completed}/{len(scenes)}] {scene}: skipped", flush=True)
|
| 82 |
else:
|
encoder/render.py
CHANGED
|
@@ -4,7 +4,7 @@ from __future__ import annotations
|
|
| 4 |
|
| 5 |
import os
|
| 6 |
|
| 7 |
-
from encoder import config
|
| 8 |
from encoder import geometric as geometry_math
|
| 9 |
from encoder import run as perceive
|
| 10 |
|
|
@@ -17,7 +17,7 @@ def build_spatial_code_for(scene, model=None, rebuild=False):
|
|
| 17 |
|
| 18 |
def write_spatial_code_for(scene, model=None, rebuild=False):
|
| 19 |
code, how = build_spatial_code_for(scene, model, rebuild)
|
| 20 |
-
path =
|
| 21 |
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 22 |
geometry_math.dump_spatial_code(code, path)
|
| 23 |
return code, how, path
|
|
|
|
| 4 |
|
| 5 |
import os
|
| 6 |
|
| 7 |
+
from encoder import config
|
| 8 |
from encoder import geometric as geometry_math
|
| 9 |
from encoder import run as perceive
|
| 10 |
|
|
|
|
| 17 |
|
| 18 |
def write_spatial_code_for(scene, model=None, rebuild=False):
|
| 19 |
code, how = build_spatial_code_for(scene, model, rebuild)
|
| 20 |
+
path = config.spatial_code_path(scene, model)
|
| 21 |
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 22 |
geometry_math.dump_spatial_code(code, path)
|
| 23 |
return code, how, path
|
encoder/run.py
CHANGED
|
@@ -13,14 +13,14 @@ WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
|
|
| 13 |
if str(WORKSPACE_ROOT) not in sys.path:
|
| 14 |
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 15 |
|
| 16 |
-
from encoder import adapters
|
| 17 |
-
from encoder import config
|
| 18 |
|
| 19 |
|
| 20 |
def cache_or_load(scene: str, model: str | None = None, rebuild: bool = False):
|
| 21 |
"""Return canonical geometry, reusing ``<scene>.pkl.gz`` when available."""
|
| 22 |
-
model = model or
|
| 23 |
-
path =
|
| 24 |
if os.path.exists(path) and not rebuild:
|
| 25 |
with gzip.open(path, "rb") as f:
|
| 26 |
return adapters.validate(pickle.load(f)), "loaded"
|
|
@@ -28,7 +28,7 @@ def cache_or_load(scene: str, model: str | None = None, rebuild: bool = False):
|
|
| 28 |
geometry = adapters.adapt(
|
| 29 |
model,
|
| 30 |
scene=scene,
|
| 31 |
-
root=str(
|
| 32 |
rebuild=rebuild,
|
| 33 |
)
|
| 34 |
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
@@ -40,7 +40,7 @@ def cache_or_load(scene: str, model: str | None = None, rebuild: bool = False):
|
|
| 40 |
def main() -> None:
|
| 41 |
p = argparse.ArgumentParser()
|
| 42 |
p.add_argument("scene")
|
| 43 |
-
p.add_argument("--model", default=
|
| 44 |
p.add_argument("--rebuild", action="store_true")
|
| 45 |
a = p.parse_args()
|
| 46 |
geometry, how = cache_or_load(a.scene, a.model, a.rebuild)
|
|
|
|
| 13 |
if str(WORKSPACE_ROOT) not in sys.path:
|
| 14 |
sys.path.insert(0, str(WORKSPACE_ROOT))
|
| 15 |
|
| 16 |
+
from encoder import adapters # noqa: E402
|
| 17 |
+
from encoder import config # noqa: E402
|
| 18 |
|
| 19 |
|
| 20 |
def cache_or_load(scene: str, model: str | None = None, rebuild: bool = False):
|
| 21 |
"""Return canonical geometry, reusing ``<scene>.pkl.gz`` when available."""
|
| 22 |
+
model = model or config.MODEL
|
| 23 |
+
path = config.cache_file(scene, model)
|
| 24 |
if os.path.exists(path) and not rebuild:
|
| 25 |
with gzip.open(path, "rb") as f:
|
| 26 |
return adapters.validate(pickle.load(f)), "loaded"
|
|
|
|
| 28 |
geometry = adapters.adapt(
|
| 29 |
model,
|
| 30 |
scene=scene,
|
| 31 |
+
root=str(config.CACHE_ROOT),
|
| 32 |
rebuild=rebuild,
|
| 33 |
)
|
| 34 |
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
|
|
| 40 |
def main() -> None:
|
| 41 |
p = argparse.ArgumentParser()
|
| 42 |
p.add_argument("scene")
|
| 43 |
+
p.add_argument("--model", default=config.MODEL)
|
| 44 |
p.add_argument("--rebuild", action="store_true")
|
| 45 |
a = p.parse_args()
|
| 46 |
geometry, how = cache_or_load(a.scene, a.model, a.rebuild)
|
inference/adapters.py
CHANGED
|
@@ -11,6 +11,31 @@ import sys
|
|
| 11 |
import numpy as np
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
class InferenceAdapter(ABC):
|
| 15 |
"""Common interface implemented by every inference backend."""
|
| 16 |
|
|
@@ -76,9 +101,7 @@ class SegVGGTAdapter(InferenceAdapter):
|
|
| 76 |
config = compose(config_name="segvggt_scannet200")
|
| 77 |
model = instantiate(config.model, _recursive_=False)
|
| 78 |
state = torch.load(self.checkpoint, map_location="cpu")
|
| 79 |
-
model.load_state_dict(
|
| 80 |
-
state["model"] if "model" in state else state, strict=False
|
| 81 |
-
)
|
| 82 |
self.model = model.to(self.device).to(self.dtype).eval()
|
| 83 |
self.runtime = torch
|
| 84 |
|
|
@@ -86,36 +109,19 @@ class SegVGGTAdapter(InferenceAdapter):
|
|
| 86 |
def _read_video(path, frame_count):
|
| 87 |
import cv2
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
)
|
| 99 |
-
|
| 100 |
-
frames
|
| 101 |
-
|
| 102 |
-
capture.set(cv2.CAP_PROP_POS_FRAMES, int(index))
|
| 103 |
-
ok, frame = capture.read()
|
| 104 |
-
if not ok:
|
| 105 |
-
raise RuntimeError(f"failed reading frame {index} from {path}")
|
| 106 |
-
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 107 |
-
height, width = frame.shape[:2]
|
| 108 |
-
new_height = max(14, round(height * 518 / width / 14) * 14)
|
| 109 |
-
frame = cv2.resize(
|
| 110 |
-
frame, (518, new_height), interpolation=cv2.INTER_LANCZOS4
|
| 111 |
-
)
|
| 112 |
-
if new_height > 518:
|
| 113 |
-
offset = (new_height - 518) // 2
|
| 114 |
-
frame = frame[offset : offset + 518]
|
| 115 |
-
frames.append(frame)
|
| 116 |
-
finally:
|
| 117 |
-
capture.release()
|
| 118 |
-
return np.stack(frames), indices.astype(np.float32) / fps
|
| 119 |
|
| 120 |
def run_scene(self, video_path, output_path, frame_count):
|
| 121 |
if self.model is None or self.runtime is None:
|
|
@@ -164,9 +170,7 @@ class DepthAnything3Adapter(InferenceAdapter):
|
|
| 164 |
def __init__(self, model_root=None, checkpoint=None):
|
| 165 |
self.model_root = Path(
|
| 166 |
model_root
|
| 167 |
-
or os.environ.get(
|
| 168 |
-
"VSI_DA3_ROOT", "/root/models/depth-anything-3"
|
| 169 |
-
)
|
| 170 |
)
|
| 171 |
self.checkpoint = Path(
|
| 172 |
checkpoint
|
|
@@ -203,35 +207,13 @@ class DepthAnything3Adapter(InferenceAdapter):
|
|
| 203 |
|
| 204 |
@staticmethod
|
| 205 |
def _read_video(path, frame_count):
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
capture = cv2.VideoCapture(path)
|
| 209 |
-
if not capture.isOpened():
|
| 210 |
-
raise RuntimeError(f"cannot open video: {path}")
|
| 211 |
-
try:
|
| 212 |
-
total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 213 |
-
if total < frame_count:
|
| 214 |
-
raise ValueError(
|
| 215 |
-
f"{path} has {total} frames; {frame_count} are required"
|
| 216 |
-
)
|
| 217 |
-
frames = []
|
| 218 |
-
for index in np.linspace(0, total - 1, frame_count, dtype=int):
|
| 219 |
-
capture.set(cv2.CAP_PROP_POS_FRAMES, int(index))
|
| 220 |
-
ok, frame = capture.read()
|
| 221 |
-
if not ok:
|
| 222 |
-
raise RuntimeError(f"failed reading frame {index} from {path}")
|
| 223 |
-
frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
| 224 |
-
return frames
|
| 225 |
-
finally:
|
| 226 |
-
capture.release()
|
| 227 |
|
| 228 |
-
def
|
| 229 |
if self.model is None:
|
| 230 |
-
raise RuntimeError("load_model() must be called before
|
| 231 |
-
prediction = self.model.inference(
|
| 232 |
-
self._read_video(video_path, frame_count),
|
| 233 |
-
export_dir=None,
|
| 234 |
-
)
|
| 235 |
output = Path(output_path)
|
| 236 |
output.parent.mkdir(parents=True, exist_ok=True)
|
| 237 |
temporary = output.with_suffix(output.suffix + ".tmp")
|
|
@@ -239,6 +221,9 @@ class DepthAnything3Adapter(InferenceAdapter):
|
|
| 239 |
pickle.dump(prediction, stream, protocol=pickle.HIGHEST_PROTOCOL)
|
| 240 |
os.replace(temporary, output)
|
| 241 |
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
class SAM3Adapter(InferenceAdapter):
|
| 244 |
"""Run SAM3 independently on sampled images, with no video tracking."""
|
|
@@ -285,11 +270,14 @@ class SAM3Adapter(InferenceAdapter):
|
|
| 285 |
self.processor = Sam3Processor(self.model)
|
| 286 |
|
| 287 |
def run_scene(self, video_path, output_path, frame_count):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
if self.model is None or self.processor is None or self.runtime is None:
|
| 289 |
-
raise RuntimeError("load_model() must be called before
|
| 290 |
from PIL import Image
|
| 291 |
|
| 292 |
-
frames = DepthAnything3Adapter._read_video(video_path, frame_count)
|
| 293 |
raw_outputs = []
|
| 294 |
with self.runtime.inference_mode():
|
| 295 |
for frame in frames:
|
|
@@ -324,11 +312,12 @@ class SAM3DepthAnything3Adapter(InferenceAdapter):
|
|
| 324 |
|
| 325 |
def run_scene(self, video_path, output_path, frame_count):
|
| 326 |
if not isinstance(output_path, dict):
|
| 327 |
-
raise TypeError(
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
)
|
|
|
|
| 332 |
|
| 333 |
|
| 334 |
_ADAPTERS = {
|
|
|
|
| 11 |
import numpy as np
|
| 12 |
|
| 13 |
|
| 14 |
+
def _sample_video_frames(path, frame_count):
|
| 15 |
+
"""Decode one shared set of evenly spaced RGB frames for every model adapter."""
|
| 16 |
+
import cv2
|
| 17 |
+
|
| 18 |
+
capture = cv2.VideoCapture(path)
|
| 19 |
+
if not capture.isOpened():
|
| 20 |
+
raise RuntimeError(f"cannot open video: {path}")
|
| 21 |
+
try:
|
| 22 |
+
fps = capture.get(cv2.CAP_PROP_FPS) or 1.0
|
| 23 |
+
total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 24 |
+
if total < frame_count:
|
| 25 |
+
raise ValueError(f"{path} has {total} frames; {frame_count} are required")
|
| 26 |
+
indices = np.linspace(0, total - 1, frame_count, dtype=int)
|
| 27 |
+
frames = []
|
| 28 |
+
for index in indices:
|
| 29 |
+
capture.set(cv2.CAP_PROP_POS_FRAMES, int(index))
|
| 30 |
+
ok, frame = capture.read()
|
| 31 |
+
if not ok:
|
| 32 |
+
raise RuntimeError(f"failed reading frame {index} from {path}")
|
| 33 |
+
frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
| 34 |
+
finally:
|
| 35 |
+
capture.release()
|
| 36 |
+
return np.stack(frames), indices.astype(np.float32) / fps
|
| 37 |
+
|
| 38 |
+
|
| 39 |
class InferenceAdapter(ABC):
|
| 40 |
"""Common interface implemented by every inference backend."""
|
| 41 |
|
|
|
|
| 101 |
config = compose(config_name="segvggt_scannet200")
|
| 102 |
model = instantiate(config.model, _recursive_=False)
|
| 103 |
state = torch.load(self.checkpoint, map_location="cpu")
|
| 104 |
+
model.load_state_dict(state.get("model", state), strict=False)
|
|
|
|
|
|
|
| 105 |
self.model = model.to(self.device).to(self.dtype).eval()
|
| 106 |
self.runtime = torch
|
| 107 |
|
|
|
|
| 109 |
def _read_video(path, frame_count):
|
| 110 |
import cv2
|
| 111 |
|
| 112 |
+
raw_frames, frame_times = _sample_video_frames(path, frame_count)
|
| 113 |
+
frames = []
|
| 114 |
+
for frame in raw_frames:
|
| 115 |
+
height, width = frame.shape[:2]
|
| 116 |
+
new_height = max(14, round(height * 518 / width / 14) * 14)
|
| 117 |
+
frame = cv2.resize(
|
| 118 |
+
frame, (518, new_height), interpolation=cv2.INTER_LANCZOS4
|
| 119 |
+
)
|
| 120 |
+
if new_height > 518:
|
| 121 |
+
offset = (new_height - 518) // 2
|
| 122 |
+
frame = frame[offset : offset + 518]
|
| 123 |
+
frames.append(frame)
|
| 124 |
+
return np.stack(frames), frame_times
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
def run_scene(self, video_path, output_path, frame_count):
|
| 127 |
if self.model is None or self.runtime is None:
|
|
|
|
| 170 |
def __init__(self, model_root=None, checkpoint=None):
|
| 171 |
self.model_root = Path(
|
| 172 |
model_root
|
| 173 |
+
or os.environ.get("VSI_DA3_ROOT", "/root/models/depth-anything-3")
|
|
|
|
|
|
|
| 174 |
)
|
| 175 |
self.checkpoint = Path(
|
| 176 |
checkpoint
|
|
|
|
| 207 |
|
| 208 |
@staticmethod
|
| 209 |
def _read_video(path, frame_count):
|
| 210 |
+
frames, _ = _sample_video_frames(path, frame_count)
|
| 211 |
+
return list(frames)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
+
def run_frames(self, frames, output_path):
|
| 214 |
if self.model is None:
|
| 215 |
+
raise RuntimeError("load_model() must be called before run_frames()")
|
| 216 |
+
prediction = self.model.inference(list(frames), export_dir=None)
|
|
|
|
|
|
|
|
|
|
| 217 |
output = Path(output_path)
|
| 218 |
output.parent.mkdir(parents=True, exist_ok=True)
|
| 219 |
temporary = output.with_suffix(output.suffix + ".tmp")
|
|
|
|
| 221 |
pickle.dump(prediction, stream, protocol=pickle.HIGHEST_PROTOCOL)
|
| 222 |
os.replace(temporary, output)
|
| 223 |
|
| 224 |
+
def run_scene(self, video_path, output_path, frame_count):
|
| 225 |
+
self.run_frames(self._read_video(video_path, frame_count), output_path)
|
| 226 |
+
|
| 227 |
|
| 228 |
class SAM3Adapter(InferenceAdapter):
|
| 229 |
"""Run SAM3 independently on sampled images, with no video tracking."""
|
|
|
|
| 270 |
self.processor = Sam3Processor(self.model)
|
| 271 |
|
| 272 |
def run_scene(self, video_path, output_path, frame_count):
|
| 273 |
+
frames, _ = _sample_video_frames(video_path, frame_count)
|
| 274 |
+
self.run_frames(frames, output_path)
|
| 275 |
+
|
| 276 |
+
def run_frames(self, frames, output_path):
|
| 277 |
if self.model is None or self.processor is None or self.runtime is None:
|
| 278 |
+
raise RuntimeError("load_model() must be called before run_frames()")
|
| 279 |
from PIL import Image
|
| 280 |
|
|
|
|
| 281 |
raw_outputs = []
|
| 282 |
with self.runtime.inference_mode():
|
| 283 |
for frame in frames:
|
|
|
|
| 312 |
|
| 313 |
def run_scene(self, video_path, output_path, frame_count):
|
| 314 |
if not isinstance(output_path, dict):
|
| 315 |
+
raise TypeError(
|
| 316 |
+
"combined inference requires a model-to-output-path mapping"
|
| 317 |
+
)
|
| 318 |
+
frames, _ = _sample_video_frames(video_path, frame_count)
|
| 319 |
+
self.sam3.run_frames(frames, output_path["sam3"])
|
| 320 |
+
self.depth_anything_3.run_frames(frames, output_path["depth-anything-3"])
|
| 321 |
|
| 322 |
|
| 323 |
_ADAPTERS = {
|
inference/run.py
CHANGED
|
@@ -17,9 +17,7 @@ from inference import adapters # noqa: E402
|
|
| 17 |
def output_paths(scene, model):
|
| 18 |
"""Return every adapter-owned raw-cache path for one inference selection."""
|
| 19 |
return {
|
| 20 |
-
target: str(
|
| 21 |
-
Path(inference_config.model_cache_dir(target)) / f"{scene}{suffix}"
|
| 22 |
-
)
|
| 23 |
for target, suffix in adapters.output_targets(model).items()
|
| 24 |
}
|
| 25 |
|
|
@@ -44,9 +42,7 @@ def run_scene(
|
|
| 44 |
if owns_adapter:
|
| 45 |
adapter.load_model(device or "cuda")
|
| 46 |
adapter_output = (
|
| 47 |
-
next(iter(destinations.values()))
|
| 48 |
-
if len(destinations) == 1
|
| 49 |
-
else destinations
|
| 50 |
)
|
| 51 |
adapter.run_scene(inference_config.video_path(scene), adapter_output, frame_count)
|
| 52 |
return "built", output_path(scene, model)
|
|
|
|
| 17 |
def output_paths(scene, model):
|
| 18 |
"""Return every adapter-owned raw-cache path for one inference selection."""
|
| 19 |
return {
|
| 20 |
+
target: str(Path(inference_config.model_cache_dir(target)) / f"{scene}{suffix}")
|
|
|
|
|
|
|
| 21 |
for target, suffix in adapters.output_targets(model).items()
|
| 22 |
}
|
| 23 |
|
|
|
|
| 42 |
if owns_adapter:
|
| 43 |
adapter.load_model(device or "cuda")
|
| 44 |
adapter_output = (
|
| 45 |
+
next(iter(destinations.values())) if len(destinations) == 1 else destinations
|
|
|
|
|
|
|
| 46 |
)
|
| 47 |
adapter.run_scene(inference_config.video_path(scene), adapter_output, frame_count)
|
| 48 |
return "built", output_path(scene, model)
|
symbolic/launch.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""Runs the symbolic engine (via symbolic/run.py's score_scene()) across EVERY scene that has
|
| 2 |
-
a real spatial code
|
| 3 |
orchestrator, matching encoder/launch.py's and harness/launch.py's own single-scene-worker vs.
|
| 4 |
multi-scene-orchestrator split (symbolic/run.py stays single-scene only; this file is the only
|
| 5 |
one that loops over more than one scene). This file contains no scoring logic of its own --
|
|
@@ -8,7 +8,7 @@ unmodified vsi_official_eval.py) is symbolic/run.py's score_scene(), called once
|
|
| 8 |
|
| 9 |
Usage:
|
| 10 |
python symbolic/launch.py
|
| 11 |
-
Every scene under /workspace/
|
| 12 |
question in test.jsonl -- runs each one (delegating to symbolic/run.py's score_scene()
|
| 13 |
for the actual work), prints a per-scene report (including the appearance-order
|
| 14 |
diagnostic run.py builds), then one combined aggregate across every scene together.
|
|
|
|
| 1 |
"""Runs the symbolic engine (via symbolic/run.py's score_scene()) across EVERY scene that has
|
| 2 |
+
a real spatial code under /root/workspace/spatial codes/<MODEL>/ -- the multi-scene
|
| 3 |
orchestrator, matching encoder/launch.py's and harness/launch.py's own single-scene-worker vs.
|
| 4 |
multi-scene-orchestrator split (symbolic/run.py stays single-scene only; this file is the only
|
| 5 |
one that loops over more than one scene). This file contains no scoring logic of its own --
|
|
|
|
| 8 |
|
| 9 |
Usage:
|
| 10 |
python symbolic/launch.py
|
| 11 |
+
Every scene under /root/workspace/spatial codes/<MODEL>/*.json that also has at least one real
|
| 12 |
question in test.jsonl -- runs each one (delegating to symbolic/run.py's score_scene()
|
| 13 |
for the actual work), prints a per-scene report (including the appearance-order
|
| 14 |
diagnostic run.py builds), then one combined aggregate across every scene together.
|
symbolic/run.py
CHANGED
|
@@ -6,7 +6,7 @@ orchestrator (matches encoder/launch.py's and harness/launch.py's own single-sce
|
|
| 6 |
multi-scene-orchestrator split: this file never loops over more than one scene on its own).
|
| 7 |
|
| 8 |
FETCHES the spatial code from:
|
| 9 |
-
/workspace/
|
| 10 |
(the model-specific on-disk layout). This file does NOT
|
| 11 |
build spatial codes (that's encoder/render.py's job) and does NOT call any model -- it only
|
| 12 |
reads an already-built spatial_code.json and answers/scores against it.
|
|
@@ -87,9 +87,7 @@ _AUTO_WORKSPACE = _find_workspace_root(_HERE)
|
|
| 87 |
|
| 88 |
|
| 89 |
def _default_spatial_codes_root():
|
| 90 |
-
|
| 91 |
-
return os.path.join(_AUTO_WORKSPACE, "data", "spatial codes")
|
| 92 |
-
return "/workspace/data/spatial codes"
|
| 93 |
|
| 94 |
|
| 95 |
def _default_test_jsonl():
|
|
@@ -144,7 +142,7 @@ DEFAULT_TEST_JSONL = os.environ.get("SYMBOLIC_TEST_JSONL", _default_test_jsonl()
|
|
| 144 |
|
| 145 |
def spatial_code_path(scene_id):
|
| 146 |
"""The one place this file looks for a scene's spatial code:
|
| 147 |
-
/workspace/
|
| 148 |
return os.path.join(SPATIAL_CODES_DIR, f"{scene_id}.json")
|
| 149 |
|
| 150 |
|
|
|
|
| 6 |
multi-scene-orchestrator split: this file never loops over more than one scene on its own).
|
| 7 |
|
| 8 |
FETCHES the spatial code from:
|
| 9 |
+
/root/workspace/spatial codes/<MODEL>/<SCENE_ID>.json
|
| 10 |
(the model-specific on-disk layout). This file does NOT
|
| 11 |
build spatial codes (that's encoder/render.py's job) and does NOT call any model -- it only
|
| 12 |
reads an already-built spatial_code.json and answers/scores against it.
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
def _default_spatial_codes_root():
|
| 90 |
+
return "/root/workspace/spatial codes"
|
|
|
|
|
|
|
| 91 |
|
| 92 |
|
| 93 |
def _default_test_jsonl():
|
|
|
|
| 142 |
|
| 143 |
def spatial_code_path(scene_id):
|
| 144 |
"""The one place this file looks for a scene's spatial code:
|
| 145 |
+
/root/workspace/spatial codes/<MODEL>/<SCENE_ID>.json."""
|
| 146 |
return os.path.join(SPATIAL_CODES_DIR, f"{scene_id}.json")
|
| 147 |
|
| 148 |
|
symbolic/solver.py
CHANGED
|
@@ -92,16 +92,16 @@ def _instance_xy(code, cls_name, index=0):
|
|
| 92 |
return (_parse_meters(pos["x coordinate"]), _parse_meters(pos["y coordinate"]))
|
| 93 |
|
| 94 |
|
| 95 |
-
def _rel_direction(
|
| 96 |
"""Standing at A facing B, where is C? Same formula as
|
| 97 |
encoder/geometric.py's answer_rel_direction(), specialized to the 2D floor plane (the
|
| 98 |
spatial code's frame has no raw height needed for this -- direction is a floor-plane
|
| 99 |
question in every real VSI-Bench phrasing). front/back = dot(C-A, fwd);
|
| 100 |
left/right = dot(C-A, left), where left = fwd rotated +90 degrees (matches the
|
| 101 |
right-handed convention answer_rel_direction() documents)."""
|
| 102 |
-
ax, ay =
|
| 103 |
-
bx, by =
|
| 104 |
-
cx, cy =
|
| 105 |
fwd = (bx - ax, by - ay)
|
| 106 |
n = (fwd[0] ** 2 + fwd[1] ** 2) ** 0.5
|
| 107 |
if n < 1e-9:
|
|
@@ -374,14 +374,14 @@ def _answer_rel_direction_typed(question, options, code, mode):
|
|
| 374 |
c_cls = _find_class(m2.group(1), code)
|
| 375 |
if a_cls is None or b_cls is None or c_cls is None:
|
| 376 |
return None
|
| 377 |
-
|
| 378 |
_instance_xy(code, a_cls),
|
| 379 |
_instance_xy(code, b_cls),
|
| 380 |
_instance_xy(code, c_cls),
|
| 381 |
)
|
| 382 |
-
if
|
| 383 |
return None
|
| 384 |
-
result = _rel_direction(
|
| 385 |
if result is None:
|
| 386 |
return None
|
| 387 |
for opt in options:
|
|
@@ -527,7 +527,8 @@ def _demo_questions():
|
|
| 527 |
ground truth (this scene's own uploaded spatial_code.json doesn't carry official VSI-Bench
|
| 528 |
question/ground_truth pairs alongside it) -- see symbolic/test_symbolic.py for real
|
| 529 |
accuracy checks against actual test.jsonl rows."""
|
| 530 |
-
|
|
|
|
| 531 |
subset = [c for c in ["bed", "chair", "table", "tv"] if c in order]
|
| 532 |
subset_sorted = sorted(subset, key=lambda c: order.index(c))
|
| 533 |
ao_correct = ", ".join(subset_sorted)
|
|
@@ -627,7 +628,8 @@ def main():
|
|
| 627 |
f"\nNo spatial_code.json found at any of {candidates} -- nothing to demo against."
|
| 628 |
)
|
| 629 |
return
|
| 630 |
-
|
|
|
|
| 631 |
if "closest classes distance meters from" not in code:
|
| 632 |
print(
|
| 633 |
f"\n{path} is not in the final spatial code shape (no "
|
|
|
|
| 92 |
return (_parse_meters(pos["x coordinate"]), _parse_meters(pos["y coordinate"]))
|
| 93 |
|
| 94 |
|
| 95 |
+
def _rel_direction(point_a, point_b, point_c, mode="hard"):
|
| 96 |
"""Standing at A facing B, where is C? Same formula as
|
| 97 |
encoder/geometric.py's answer_rel_direction(), specialized to the 2D floor plane (the
|
| 98 |
spatial code's frame has no raw height needed for this -- direction is a floor-plane
|
| 99 |
question in every real VSI-Bench phrasing). front/back = dot(C-A, fwd);
|
| 100 |
left/right = dot(C-A, left), where left = fwd rotated +90 degrees (matches the
|
| 101 |
right-handed convention answer_rel_direction() documents)."""
|
| 102 |
+
ax, ay = point_a
|
| 103 |
+
bx, by = point_b
|
| 104 |
+
cx, cy = point_c
|
| 105 |
fwd = (bx - ax, by - ay)
|
| 106 |
n = (fwd[0] ** 2 + fwd[1] ** 2) ** 0.5
|
| 107 |
if n < 1e-9:
|
|
|
|
| 374 |
c_cls = _find_class(m2.group(1), code)
|
| 375 |
if a_cls is None or b_cls is None or c_cls is None:
|
| 376 |
return None
|
| 377 |
+
point_a, point_b, point_c = (
|
| 378 |
_instance_xy(code, a_cls),
|
| 379 |
_instance_xy(code, b_cls),
|
| 380 |
_instance_xy(code, c_cls),
|
| 381 |
)
|
| 382 |
+
if point_a is None or point_b is None or point_c is None:
|
| 383 |
return None
|
| 384 |
+
result = _rel_direction(point_a, point_b, point_c, mode=mode)
|
| 385 |
if result is None:
|
| 386 |
return None
|
| 387 |
for opt in options:
|
|
|
|
| 527 |
ground truth (this scene's own uploaded spatial_code.json doesn't carry official VSI-Bench
|
| 528 |
question/ground_truth pairs alongside it) -- see symbolic/test_symbolic.py for real
|
| 529 |
accuracy checks against actual test.jsonl rows."""
|
| 530 |
+
with open("/tmp/final_spatial_code.json") as stream:
|
| 531 |
+
order = json.load(stream).get("appearance order", [])
|
| 532 |
subset = [c for c in ["bed", "chair", "table", "tv"] if c in order]
|
| 533 |
subset_sorted = sorted(subset, key=lambda c: order.index(c))
|
| 534 |
ao_correct = ", ".join(subset_sorted)
|
|
|
|
| 628 |
f"\nNo spatial_code.json found at any of {candidates} -- nothing to demo against."
|
| 629 |
)
|
| 630 |
return
|
| 631 |
+
with open(path) as stream:
|
| 632 |
+
code = json.load(stream)
|
| 633 |
if "closest classes distance meters from" not in code:
|
| 634 |
print(
|
| 635 |
f"\n{path} is not in the final spatial code shape (no "
|
tests/test_encoder/conftest.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared import setup for encoder tests."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 7 |
+
for path in (ROOT, ROOT / "encoder"):
|
| 8 |
+
if str(path) not in sys.path:
|
| 9 |
+
sys.path.insert(0, str(path))
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def pytest_configure(config):
|
| 13 |
+
config.option.importmode = "importlib"
|
tests/test_encoder/test_adapters.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gzip
|
| 2 |
+
import pickle
|
| 3 |
+
import sys
|
| 4 |
+
import types
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from encoder import adapters
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_registry_decodes_native_segvggt_dictionary(tmp_path, monkeypatch):
|
| 13 |
+
torch = pytest.importorskip("torch")
|
| 14 |
+
evaluation = types.ModuleType("eval.instance_eval_common")
|
| 15 |
+
evaluation.predict_by_feat_instance = lambda *args, **kwargs: (
|
| 16 |
+
torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0]], dtype=torch.bool),
|
| 17 |
+
torch.tensor([0, 2]),
|
| 18 |
+
torch.ones(2),
|
| 19 |
+
)
|
| 20 |
+
pose = types.ModuleType("segvggt.utils.pose_enc")
|
| 21 |
+
pose.pose_encoding_to_extri_intri = lambda value, size: (
|
| 22 |
+
torch.cat(
|
| 23 |
+
[
|
| 24 |
+
torch.eye(3).reshape(1, 1, 3, 3),
|
| 25 |
+
torch.zeros(1, 1, 3, 1),
|
| 26 |
+
],
|
| 27 |
+
dim=-1,
|
| 28 |
+
),
|
| 29 |
+
torch.eye(3).reshape(1, 1, 3, 3),
|
| 30 |
+
)
|
| 31 |
+
monkeypatch.setitem(sys.modules, "eval.instance_eval_common", evaluation)
|
| 32 |
+
monkeypatch.setitem(sys.modules, "segvggt.utils.pose_enc", pose)
|
| 33 |
+
|
| 34 |
+
path = tmp_path / "scene.pt"
|
| 35 |
+
torch.save(
|
| 36 |
+
{
|
| 37 |
+
"world_points": torch.zeros(1, 1, 2, 2, 3),
|
| 38 |
+
"instance_maps": torch.zeros(1, 2, 1, 2, 2),
|
| 39 |
+
"instance_labels": torch.zeros(1, 2, 4),
|
| 40 |
+
"pose_enc": torch.zeros(1, 1, 9),
|
| 41 |
+
},
|
| 42 |
+
path,
|
| 43 |
+
)
|
| 44 |
+
result = adapters.adapt("segvggt", path=path)
|
| 45 |
+
assert list(result["instances"]) == ["chair"]
|
| 46 |
+
assert result["instances"]["chair"][0]["n"] == 1
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _scene():
|
| 50 |
+
return {
|
| 51 |
+
"instances": {"chair": [{"pts": [[0, 0, 0]], "best_pts": [[0, 0, 0]]}]},
|
| 52 |
+
"stats": {"chair": {"raw": 1, "merged": 1, "peak": 1}},
|
| 53 |
+
"scene_pts": [[0, 0, 0]],
|
| 54 |
+
"cameras": None,
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_validate_normalizes_canonical_geometry():
|
| 59 |
+
result = adapters.validate(_scene())
|
| 60 |
+
instance = result["instances"]["chair"][0]
|
| 61 |
+
assert instance["pts"].shape == (1, 3)
|
| 62 |
+
assert instance["frames"] == set()
|
| 63 |
+
assert instance["n"] == 1
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@pytest.mark.parametrize(
|
| 67 |
+
("scene", "error"),
|
| 68 |
+
[
|
| 69 |
+
([], TypeError),
|
| 70 |
+
({"instances": {}}, ValueError),
|
| 71 |
+
(
|
| 72 |
+
{"instances": {"chair": [{"pts": [1, 2, 3]}]}, "scene_pts": [[0, 0, 0]]},
|
| 73 |
+
ValueError,
|
| 74 |
+
),
|
| 75 |
+
],
|
| 76 |
+
)
|
| 77 |
+
def test_validate_rejects_invalid_geometry(scene, error):
|
| 78 |
+
with pytest.raises(error):
|
| 79 |
+
adapters.validate(scene)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_adapt_segvggt_reads_flat_npz(tmp_path):
|
| 83 |
+
path = tmp_path / "scene.npz"
|
| 84 |
+
world = np.array([[[[0, 0, 1], [1, 0, 1]]]], np.float32)
|
| 85 |
+
masks = np.array([[[[True, False]]]])
|
| 86 |
+
np.savez(
|
| 87 |
+
path,
|
| 88 |
+
world_points=world,
|
| 89 |
+
instance_masks=masks,
|
| 90 |
+
labels=np.array(["chair"], dtype=object),
|
| 91 |
+
frame_times=np.array([0], np.float32),
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
result = adapters.adapt_segvggt(path=str(path))
|
| 95 |
+
|
| 96 |
+
instance = result["instances"]["chair"][0]
|
| 97 |
+
assert list(result["instances"]) == ["chair"]
|
| 98 |
+
assert instance["frames"] == {0}
|
| 99 |
+
assert result["stats"]["chair"] == {"raw": 1, "merged": 1, "peak": 1}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_adapt_segvggt_requires_existing_cache(tmp_path):
|
| 103 |
+
with pytest.raises(FileNotFoundError, match="raw cache does not exist"):
|
| 104 |
+
adapters.adapt_segvggt(path=str(tmp_path / "missing.npz"))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_adapter_owned_raw_cache_locations(tmp_path, monkeypatch):
|
| 108 |
+
seen = {}
|
| 109 |
+
raw_path = tmp_path / "segvggt" / "scene1.pt"
|
| 110 |
+
raw_path.parent.mkdir()
|
| 111 |
+
raw_path.touch()
|
| 112 |
+
|
| 113 |
+
def fake_segvggt(path):
|
| 114 |
+
seen["segvggt"] = str(path)
|
| 115 |
+
return {
|
| 116 |
+
"world_points": np.zeros((1, 1, 1, 3), np.float32),
|
| 117 |
+
"instance_masks": np.ones((1, 1, 1, 1), bool),
|
| 118 |
+
"labels": np.array(["chair"], dtype=object),
|
| 119 |
+
"camera_positions": np.zeros((1, 3), np.float32),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
monkeypatch.setattr(adapters, "_decode_segvggt_raw", fake_segvggt)
|
| 123 |
+
adapters.adapt_segvggt(root=str(tmp_path), scene="scene1")
|
| 124 |
+
assert seen["segvggt"] == str(raw_path)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def test_fusion_adapter_resolves_two_native_model_directories(tmp_path, monkeypatch):
|
| 128 |
+
seen = {}
|
| 129 |
+
depth = np.ones((1, 1, 1), np.float32)
|
| 130 |
+
intr = np.eye(3, dtype=np.float32)[None]
|
| 131 |
+
c2w = np.eye(4, dtype=np.float32)[None]
|
| 132 |
+
|
| 133 |
+
def fake_da3(path):
|
| 134 |
+
seen["da3"] = str(path)
|
| 135 |
+
return depth, intr, c2w, None
|
| 136 |
+
|
| 137 |
+
def fake_sam3(path):
|
| 138 |
+
seen["sam3"] = str(path)
|
| 139 |
+
return {"object": {0: {0: np.ones((1, 1), bool)}}}
|
| 140 |
+
|
| 141 |
+
monkeypatch.setattr(adapters, "_load_native_da3", fake_da3)
|
| 142 |
+
monkeypatch.setattr(adapters, "_load_native_sam3", fake_sam3)
|
| 143 |
+
adapters.adapt_sam3_depth_anything_3(root=str(tmp_path), scene="scene1")
|
| 144 |
+
assert seen == {
|
| 145 |
+
"da3": str(tmp_path / "depth-anything-3" / "scene1.pkl"),
|
| 146 |
+
"sam3": str(tmp_path / "sam3" / "scene1.pt"),
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_adapters_default_to_root_data_caches(monkeypatch, tmp_path):
|
| 151 |
+
monkeypatch.delenv("VSI_CACHE_ROOT", raising=False)
|
| 152 |
+
seen = {}
|
| 153 |
+
|
| 154 |
+
def fake_da3(path):
|
| 155 |
+
seen["da3"] = str(path)
|
| 156 |
+
return (
|
| 157 |
+
np.ones((1, 1, 1), np.float32),
|
| 158 |
+
np.eye(3, dtype=np.float32)[None],
|
| 159 |
+
np.eye(4, dtype=np.float32)[None],
|
| 160 |
+
None,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
def fake_sam3(path):
|
| 164 |
+
seen["sam3"] = str(path)
|
| 165 |
+
return {"object": {0: {0: np.ones((1, 1), bool)}}}
|
| 166 |
+
|
| 167 |
+
monkeypatch.setattr(adapters, "_load_native_da3", fake_da3)
|
| 168 |
+
monkeypatch.setattr(adapters, "_load_native_sam3", fake_sam3)
|
| 169 |
+
adapters.adapt_sam3_depth_anything_3(scene="scene1")
|
| 170 |
+
assert seen == {
|
| 171 |
+
"da3": "/root/data/caches/depth-anything-3/scene1.pkl",
|
| 172 |
+
"sam3": "/root/data/caches/sam3/scene1.pt",
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_adapt_segvggt_rejects_missing_npz_fields(tmp_path):
|
| 177 |
+
path = tmp_path / "broken.npz"
|
| 178 |
+
np.savez(path, labels=np.array(["chair"], dtype=object))
|
| 179 |
+
with pytest.raises(KeyError):
|
| 180 |
+
adapters.adapt_segvggt(path=str(path))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_adapt_sam3_depth_anything_3_decodes_masks_and_backprojects(tmp_path):
|
| 184 |
+
da3_path = tmp_path / "scene.da3.npz"
|
| 185 |
+
depth = np.full((1, 2, 2), 2.0, np.float32)
|
| 186 |
+
intrinsics = np.eye(3, dtype=np.float32)[None]
|
| 187 |
+
poses = np.eye(4, dtype=np.float32)[None]
|
| 188 |
+
np.savez(
|
| 189 |
+
da3_path,
|
| 190 |
+
depth=depth,
|
| 191 |
+
intr=intrinsics,
|
| 192 |
+
c2w=poses,
|
| 193 |
+
frame_times=np.array([1.5], np.float32),
|
| 194 |
+
)
|
| 195 |
+
mask = np.array([[True, False], [False, True]])
|
| 196 |
+
packed = {"chair": {0: {7: (np.packbits(mask), mask.shape)}}}
|
| 197 |
+
mask_path = tmp_path / "scene.sam3.pkl.gz"
|
| 198 |
+
with gzip.open(mask_path, "wb") as cache:
|
| 199 |
+
pickle.dump(packed, cache)
|
| 200 |
+
|
| 201 |
+
result = adapters.adapt_sam3_depth_anything_3(
|
| 202 |
+
da3_path=str(da3_path), sam3_path=str(mask_path)
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
instance = result["instances"]["chair"][0]
|
| 206 |
+
assert instance["frames"] == {0}
|
| 207 |
+
assert instance["first_time"] == pytest.approx(1.5)
|
| 208 |
+
np.testing.assert_allclose(instance["pts"], [[0, 0, 2], [2, 2, 2]])
|
| 209 |
+
assert result["stats"]["chair"] == {"raw": 1, "merged": 1, "peak": 1}
|
| 210 |
+
assert result["raw_inputs"]["per"]["chair"][0][7].dtype == bool
|
tests/test_encoder/test_config.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from encoder import config
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_cache_and_code_paths_are_flat(tmp_path, monkeypatch):
|
| 7 |
+
monkeypatch.setattr(config, "CACHE_ROOT", tmp_path / "caches")
|
| 8 |
+
monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "spatial codes")
|
| 9 |
+
|
| 10 |
+
assert config.cache_file("scene1", "segvggt") == str(
|
| 11 |
+
tmp_path / "caches/segvggt/scene1.pkl.gz"
|
| 12 |
+
)
|
| 13 |
+
assert config.segvggt_cache_file("scene1") == str(
|
| 14 |
+
tmp_path / "caches/segvggt/scene1.pt"
|
| 15 |
+
)
|
| 16 |
+
assert config.da3_cache_file("scene1") == str(
|
| 17 |
+
tmp_path / "caches/depth-anything-3/scene1.pkl"
|
| 18 |
+
)
|
| 19 |
+
assert config.sam3_cache_file("scene1") == str(tmp_path / "caches/sam3/scene1.pt")
|
| 20 |
+
assert config.spatial_code_path("scene1") == str(
|
| 21 |
+
tmp_path / "spatial codes/segvggt/scene1.json"
|
| 22 |
+
)
|
| 23 |
+
assert config.spatial_code_path("scene1", "sam3+depth-anything-3") == str(
|
| 24 |
+
tmp_path / "spatial codes/sam3+depth-anything-3/scene1.json"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_video_path_searches_dataset_folders(tmp_path, monkeypatch):
|
| 29 |
+
monkeypatch.setattr(config, "VSI_ROOT", tmp_path)
|
| 30 |
+
path = tmp_path / "arkitscenes" / "41069025.mp4"
|
| 31 |
+
path.parent.mkdir(parents=True)
|
| 32 |
+
path.write_bytes(b"video")
|
| 33 |
+
assert config.video_path("41069025") == str(path)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_video_path_rejects_unknown_dataset(tmp_path, monkeypatch):
|
| 37 |
+
monkeypatch.setattr(config, "VSI_ROOT", tmp_path)
|
| 38 |
+
with pytest.raises(ValueError, match="unknown VSI dataset"):
|
| 39 |
+
config.video_path("scene1", "unknown")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_video_path_requires_unique_match(tmp_path, monkeypatch):
|
| 43 |
+
monkeypatch.setattr(config, "VSI_ROOT", tmp_path)
|
| 44 |
+
for dataset in ("scannet", "scannetpp"):
|
| 45 |
+
path = tmp_path / dataset / "scene1.mp4"
|
| 46 |
+
path.parent.mkdir(parents=True)
|
| 47 |
+
path.write_bytes(b"video")
|
| 48 |
+
with pytest.raises(RuntimeError, match="multiple datasets"):
|
| 49 |
+
config.video_path("scene1")
|
tests/test_encoder/test_encoder.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import geometric
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_backproject_frame_applies_intrinsics_pose_and_confidence():
|
| 8 |
+
depth = np.array([[2.0, 2.0], [2.0, np.nan]], np.float32)
|
| 9 |
+
mask = np.ones((2, 2), bool)
|
| 10 |
+
intrinsics = np.eye(3, dtype=np.float32)
|
| 11 |
+
pose = np.eye(4, dtype=np.float32)
|
| 12 |
+
pose[0, 3] = 1.0
|
| 13 |
+
confidence = np.array([[0.9, 0.8], [0.1, 1.0]], np.float32)
|
| 14 |
+
|
| 15 |
+
points, kept_confidence = geometric.backproject_frame(
|
| 16 |
+
depth, intrinsics, pose, mask, confidence, conf_thr=0.5, return_conf=True
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
np.testing.assert_allclose(points, [[1.0, 0.0, 2.0], [3.0, 0.0, 2.0]])
|
| 20 |
+
np.testing.assert_allclose(kept_confidence, [0.9, 0.8])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_backproject_frame_returns_typed_empty_array():
|
| 24 |
+
points = geometric.backproject_frame(
|
| 25 |
+
np.zeros((2, 2), np.float32), np.eye(3), np.eye(4), np.ones((2, 2), bool)
|
| 26 |
+
)
|
| 27 |
+
assert points.shape == (0, 3)
|
| 28 |
+
assert points.dtype == np.float32
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_relative_direction_modes():
|
| 32 |
+
origin = np.array([0.0, 0.0, 0.0])
|
| 33 |
+
forward = np.array([0.0, 1.0, 0.0])
|
| 34 |
+
front_left = np.array([-1.0, 1.0, 0.0])
|
| 35 |
+
up = np.array([0.0, 0.0, 1.0])
|
| 36 |
+
assert (
|
| 37 |
+
geometric.answer_rel_direction(origin, forward, front_left, up, 2)
|
| 38 |
+
== "front-left"
|
| 39 |
+
)
|
| 40 |
+
assert (
|
| 41 |
+
geometric.answer_rel_direction(origin, forward, front_left, up, 2, "medium")
|
| 42 |
+
== "left"
|
| 43 |
+
)
|
| 44 |
+
assert geometric.answer_rel_direction(origin, origin, front_left, up, 2) is None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_closest_distance_uses_point_cloud_distance():
|
| 48 |
+
first = [{"pts": np.array([[0.0, 0.0, 0.0]], np.float32), "n": 1}]
|
| 49 |
+
second = [{"pts": np.array([[0.0, 3.0, 4.0]], np.float32), "n": 1}]
|
| 50 |
+
assert geometric.answer_closest_distance(first, second) == pytest.approx(5.0)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_robust_centroid_extent_returns_sorted_dimensions():
|
| 54 |
+
points = np.array(
|
| 55 |
+
[[x, y, z] for x in (-2.0, 2.0) for y in (-1.0, 1.0) for z in (-0.5, 0.5)],
|
| 56 |
+
np.float32,
|
| 57 |
+
)
|
| 58 |
+
centroid, longest, dimensions = geometric.robust_centroid_extent(points, up_axis=2)
|
| 59 |
+
np.testing.assert_allclose(centroid, [0.0, 0.0, 0.0])
|
| 60 |
+
assert longest > 3.0
|
| 61 |
+
assert np.all(dimensions[:-1] >= dimensions[1:])
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_depth_edges_handles_small_and_discontinuous_frames():
|
| 65 |
+
small = np.ones((5, 5), np.float32)
|
| 66 |
+
assert not geometric.depth_edges(small, np.ones_like(small, bool)).any()
|
| 67 |
+
depth = np.ones((20, 20), np.float32)
|
| 68 |
+
depth[:, 10:] = 10.0
|
| 69 |
+
edges = geometric.depth_edges(depth, np.ones_like(depth, bool))
|
| 70 |
+
assert edges[:, 9:11].any()
|
tests/test_encoder/test_geometric.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
import geometric
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_dump_spatial_code(tmp_path):
|
| 10 |
+
path = tmp_path / "scene.json"
|
| 11 |
+
geometric.dump_spatial_code({"objects": {}, "appearance order": []}, path)
|
| 12 |
+
assert path.exists()
|
| 13 |
+
assert '"appearance order"' in path.read_text()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_raw_bundle_dispatches_to_integrated_exact_path(monkeypatch):
|
| 17 |
+
expected = (
|
| 18 |
+
{
|
| 19 |
+
"objects": {},
|
| 20 |
+
"room": {"floor area": "0.0 square meters"},
|
| 21 |
+
"closest classes distance meters from": {},
|
| 22 |
+
"appearance order": [],
|
| 23 |
+
},
|
| 24 |
+
{},
|
| 25 |
+
{},
|
| 26 |
+
1,
|
| 27 |
+
np.array([0, 1, 0], dtype=np.float32),
|
| 28 |
+
0.0,
|
| 29 |
+
)
|
| 30 |
+
seen = {}
|
| 31 |
+
|
| 32 |
+
def fake(depth, intr, c2w, conf, ftimes, per):
|
| 33 |
+
seen.update(depth=depth, intr=intr, c2w=c2w, conf=conf, ftimes=ftimes, per=per)
|
| 34 |
+
return expected
|
| 35 |
+
|
| 36 |
+
monkeypatch.setattr(geometric, "build_spatial_code_raw", fake)
|
| 37 |
+
raw = {
|
| 38 |
+
"depth": np.ones((1, 2, 2), np.float32),
|
| 39 |
+
"intr": np.eye(3, dtype=np.float32)[None],
|
| 40 |
+
"c2w": np.eye(4, dtype=np.float32)[None],
|
| 41 |
+
"conf": None,
|
| 42 |
+
"ftimes": np.array([0.0], np.float32),
|
| 43 |
+
"per": {"chair": {}},
|
| 44 |
+
}
|
| 45 |
+
scene = {"raw_inputs": raw}
|
| 46 |
+
assert geometric.build_spatial_code(scene) is expected
|
| 47 |
+
assert seen == raw
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_exact_math_is_integrated_into_geometric_module():
|
| 51 |
+
assert callable(geometric.build_spatial_code_raw)
|
| 52 |
+
assert callable(geometric.dump_spatial_code)
|
| 53 |
+
assert not hasattr(geometric, "_reference")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_position_reader_accepts_current_and_legacy_formatting():
|
| 57 |
+
assert geometric.pos3(
|
| 58 |
+
{
|
| 59 |
+
"position": {
|
| 60 |
+
"x coordinate": "1.25 meters",
|
| 61 |
+
"y coordinate": "-2.0 meters",
|
| 62 |
+
"height above floor": "0.5 meters",
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
) == [1.25, -2.0, 0.5]
|
| 66 |
+
assert geometric.pos3(
|
| 67 |
+
{
|
| 68 |
+
"position": {
|
| 69 |
+
"floor_x_meters": 1.25,
|
| 70 |
+
"floor_y_meters": -2.0,
|
| 71 |
+
"height_above_floor_meters": 0.5,
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
) == [1.25, -2.0, 0.5]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_floor_level_v1_v2_math_is_shared(monkeypatch):
|
| 78 |
+
points = np.array([[0, 0, z] for z in [0, 0, 0, 1, 10]], np.float32)
|
| 79 |
+
gravity = np.array([0, 0, 1], np.float32)
|
| 80 |
+
monkeypatch.delenv("VSI_CODE_V2", raising=False)
|
| 81 |
+
v1 = geometric._floor_level(points, gravity)
|
| 82 |
+
monkeypatch.setenv("VSI_CODE_V2", "1")
|
| 83 |
+
v2 = geometric._floor_level(points, gravity)
|
| 84 |
+
assert 0 <= v1 < 0.2
|
| 85 |
+
assert v2 == 0.0
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
METERS = re.compile(r"^-?\d+(?:\.\d+)? meters$")
|
| 89 |
+
SQUARE_METERS = re.compile(r"^\d+(?:\.\d+)? square meters$")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _schema_instance(x, y, z, size, first_time=0.0):
|
| 93 |
+
pts = np.array(
|
| 94 |
+
[
|
| 95 |
+
[x - size / 2, y, z],
|
| 96 |
+
[x + size / 2, y, z],
|
| 97 |
+
[x, y - size / 2, z],
|
| 98 |
+
[x, y + size / 2, z],
|
| 99 |
+
],
|
| 100 |
+
dtype=np.float32,
|
| 101 |
+
)
|
| 102 |
+
return {
|
| 103 |
+
"pts": pts,
|
| 104 |
+
"best_pts": pts,
|
| 105 |
+
"n": len(pts),
|
| 106 |
+
"nframes": 1,
|
| 107 |
+
"first_time": first_time,
|
| 108 |
+
"frames": {0},
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _schema_scene():
|
| 113 |
+
chair = _schema_instance(0.0, 0.0, 0.5, 0.8, first_time=0.0)
|
| 114 |
+
table = _schema_instance(1.0, 0.0, 0.7, 1.2, first_time=1.0)
|
| 115 |
+
floor = np.array(
|
| 116 |
+
[[x, y, 0.0] for x in np.linspace(-1, 2, 5) for y in np.linspace(-1, 1, 5)],
|
| 117 |
+
dtype=np.float32,
|
| 118 |
+
)
|
| 119 |
+
return {
|
| 120 |
+
"instances": {"chair": [chair], "table": [table]},
|
| 121 |
+
"stats": {"chair": {"peak": 1}, "table": {"peak": 3}},
|
| 122 |
+
"scene_pts": np.concatenate([chair["pts"], table["pts"], floor], axis=0),
|
| 123 |
+
"cameras": None,
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def test_spatial_code_matches_reference_schema():
|
| 128 |
+
code, *_ = geometric.build_spatial_code(_schema_scene())
|
| 129 |
+
assert list(code) == [
|
| 130 |
+
"objects",
|
| 131 |
+
"room",
|
| 132 |
+
"closest classes distance meters from",
|
| 133 |
+
"appearance order",
|
| 134 |
+
]
|
| 135 |
+
assert code["appearance order"] == ["chair", "table"]
|
| 136 |
+
assert SQUARE_METERS.match(code["room"]["floor area"])
|
| 137 |
+
for class_data in code["objects"].values():
|
| 138 |
+
assert set(class_data) == {"count", "instances"}
|
| 139 |
+
assert class_data["count"] == len(class_data["instances"])
|
| 140 |
+
for instance in class_data["instances"]:
|
| 141 |
+
assert set(instance) == {"position", "longest dimension"}
|
| 142 |
+
assert set(instance["position"]) == {
|
| 143 |
+
"x coordinate",
|
| 144 |
+
"y coordinate",
|
| 145 |
+
"height above floor",
|
| 146 |
+
}
|
| 147 |
+
assert all(METERS.match(value) for value in instance["position"].values())
|
| 148 |
+
assert METERS.match(instance["longest dimension"])
|
| 149 |
+
assert code["objects"]["table"]["count"] == 1
|
| 150 |
+
chair_to_table = code["closest classes distance meters from"]["chair"]["table"]
|
| 151 |
+
assert set(chair_to_table) == {"distance", "closeness rank"}
|
| 152 |
+
assert METERS.match(chair_to_table["distance"])
|
| 153 |
+
assert chair_to_table["closeness rank"] == 1
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_dumped_json_preserves_schema(tmp_path):
|
| 157 |
+
code, *_ = geometric.build_spatial_code(_schema_scene())
|
| 158 |
+
path = tmp_path / "scene.json"
|
| 159 |
+
geometric.dump_spatial_code(code, path)
|
| 160 |
+
assert json.loads(path.read_text()) == code
|
tests/test_encoder/test_launch.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from encoder import config
|
| 7 |
+
from encoder import launch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_scenes_deduplicates_manifest_in_order(tmp_path, monkeypatch):
|
| 11 |
+
manifest = tmp_path / "test.jsonl"
|
| 12 |
+
manifest.write_text(
|
| 13 |
+
"\n".join(json.dumps({"scene_name": scene}) for scene in ("s1", "s2", "s1"))
|
| 14 |
+
)
|
| 15 |
+
monkeypatch.setattr(config, "JSONL", manifest)
|
| 16 |
+
assert launch._scenes() == ["s1", "s2"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_visible_gpus_uses_environment(monkeypatch):
|
| 20 |
+
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "2, 4, -1")
|
| 21 |
+
assert launch._visible_gpus() == ["2", "4"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_visible_gpus_falls_back_to_nvidia_smi(monkeypatch):
|
| 25 |
+
monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
|
| 26 |
+
monkeypatch.setattr(
|
| 27 |
+
launch.subprocess, "check_output", lambda *args, **kwargs: "0\n1\n"
|
| 28 |
+
)
|
| 29 |
+
assert launch._visible_gpus() == ["0", "1"]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_main_skips_existing_spatial_codes(tmp_path, monkeypatch, capsys):
|
| 33 |
+
manifest = tmp_path / "test.jsonl"
|
| 34 |
+
manifest.write_text('{"scene_name": "s1"}\n')
|
| 35 |
+
codes = tmp_path / "codes"
|
| 36 |
+
(codes / "segvggt").mkdir(parents=True)
|
| 37 |
+
(codes / "segvggt" / "s1.json").write_text("{}")
|
| 38 |
+
monkeypatch.setattr(config, "JSONL", manifest)
|
| 39 |
+
monkeypatch.setattr(config, "CODES_ROOT", codes)
|
| 40 |
+
monkeypatch.setattr(sys, "argv", ["launch.py"])
|
| 41 |
+
monkeypatch.setattr(
|
| 42 |
+
launch.mp, "get_context", lambda *args: pytest.fail("workers should not start")
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
launch.main()
|
| 46 |
+
|
| 47 |
+
output = capsys.readouterr().out
|
| 48 |
+
assert "s1: skipped" in output
|
| 49 |
+
assert "DONE: 1 ok, 0 failed" in output
|
tests/test_encoder/test_render.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
from encoder import config
|
| 4 |
+
from encoder import render
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_build_spatial_code_uses_cached_geometry(monkeypatch):
|
| 8 |
+
geometry = {"instances": {}}
|
| 9 |
+
code = {"objects": {}}
|
| 10 |
+
monkeypatch.setattr(
|
| 11 |
+
render.perceive,
|
| 12 |
+
"cache_or_load",
|
| 13 |
+
lambda *args, **kwargs: (geometry, "loaded"),
|
| 14 |
+
)
|
| 15 |
+
monkeypatch.setattr(
|
| 16 |
+
render.geometry_math,
|
| 17 |
+
"build_spatial_code",
|
| 18 |
+
lambda value: (code, None),
|
| 19 |
+
)
|
| 20 |
+
assert render.build_spatial_code_for("abc", "segvggt") == (code, "loaded")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_write_spatial_code_uses_scene_json(tmp_path, monkeypatch):
|
| 24 |
+
monkeypatch.setattr(config, "CODES_ROOT", tmp_path / "spatial codes")
|
| 25 |
+
monkeypatch.setattr(
|
| 26 |
+
render,
|
| 27 |
+
"build_spatial_code_for",
|
| 28 |
+
lambda *args, **kwargs: ({"objects": {}}, "loaded"),
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
_, how, path = render.write_spatial_code_for("abc", "segvggt")
|
| 32 |
+
|
| 33 |
+
assert how == "loaded"
|
| 34 |
+
assert path == str(tmp_path / "spatial codes" / "segvggt" / "abc.json")
|
| 35 |
+
assert json.loads(
|
| 36 |
+
(tmp_path / "spatial codes" / "segvggt" / "abc.json").read_text()
|
| 37 |
+
) == {"objects": {}}
|
tests/test_encoder/test_run.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gzip
|
| 2 |
+
import pickle
|
| 3 |
+
|
| 4 |
+
from encoder import adapters
|
| 5 |
+
from encoder import config
|
| 6 |
+
from encoder import run
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _geometry():
|
| 10 |
+
return {
|
| 11 |
+
"instances": {"chair": [{"pts": [[0, 0, 0]], "best_pts": [[0, 0, 0]]}]},
|
| 12 |
+
"stats": {"chair": {"raw": 1, "merged": 1, "peak": 1}},
|
| 13 |
+
"scene_pts": [[0, 0, 0]],
|
| 14 |
+
"cameras": None,
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_cache_or_load_reads_flat_cache(tmp_path, monkeypatch):
|
| 19 |
+
path = tmp_path / "caches" / "segvggt" / "s1.pkl.gz"
|
| 20 |
+
path.parent.mkdir(parents=True)
|
| 21 |
+
with gzip.open(path, "wb") as cache:
|
| 22 |
+
pickle.dump(_geometry(), cache)
|
| 23 |
+
monkeypatch.setattr(config, "CACHE_ROOT", tmp_path / "caches")
|
| 24 |
+
|
| 25 |
+
result, how = run.cache_or_load("s1", "segvggt")
|
| 26 |
+
|
| 27 |
+
assert how == "loaded"
|
| 28 |
+
assert "chair" in result["instances"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_cache_or_load_builds_and_writes_cache(tmp_path, monkeypatch):
|
| 32 |
+
monkeypatch.setattr(config, "CACHE_ROOT", tmp_path / "caches")
|
| 33 |
+
monkeypatch.setitem(adapters.RAW_ADAPTERS, "fake", lambda **kwargs: _geometry())
|
| 34 |
+
|
| 35 |
+
result, how = run.cache_or_load("s1", "fake")
|
| 36 |
+
|
| 37 |
+
assert how == "built"
|
| 38 |
+
assert result["instances"]["chair"][0]["n"] == 1
|
| 39 |
+
assert (tmp_path / "caches" / "fake" / "s1.pkl.gz").is_file()
|
tests/test_inference/conftest.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared import setup for inference tests."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 7 |
+
for path in (ROOT, ROOT / "encoder"):
|
| 8 |
+
if str(path) not in sys.path:
|
| 9 |
+
sys.path.insert(0, str(path))
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def pytest_configure(config):
|
| 13 |
+
config.option.importmode = "importlib"
|
tests/test_inference/test_adapters.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
import sys
|
| 3 |
+
from types import SimpleNamespace
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from inference import adapters
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_load_model_validates_repository_and_checkpoint(tmp_path):
|
| 12 |
+
adapter = adapters.SegVGGTAdapter(model_root=tmp_path / "missing")
|
| 13 |
+
with pytest.raises(FileNotFoundError, match="repository not found"):
|
| 14 |
+
adapter.load_model("cpu")
|
| 15 |
+
model_root = tmp_path / "model"
|
| 16 |
+
model_root.mkdir()
|
| 17 |
+
adapter = adapters.SegVGGTAdapter(
|
| 18 |
+
model_root=model_root, checkpoint=tmp_path / "missing.pt"
|
| 19 |
+
)
|
| 20 |
+
with pytest.raises(FileNotFoundError, match="checkpoint not found"):
|
| 21 |
+
adapter.load_model("cpu")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_run_scene_requires_loaded_model(tmp_path):
|
| 25 |
+
adapter = adapters.SegVGGTAdapter()
|
| 26 |
+
with pytest.raises(RuntimeError, match=r"load_model\(\)"):
|
| 27 |
+
adapter.run_scene("video.mp4", tmp_path / "scene.pt", 1)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_read_video_rejects_unopenable_file():
|
| 31 |
+
with pytest.raises(RuntimeError, match="cannot open video"):
|
| 32 |
+
adapters.SegVGGTAdapter._read_video("/missing/video.mp4", 1)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_run_scene_preserves_raw_dtypes_and_encoder_geometry(tmp_path, monkeypatch):
|
| 36 |
+
torch = pytest.importorskip("torch")
|
| 37 |
+
adapter = adapters.SegVGGTAdapter()
|
| 38 |
+
adapter.device = torch.device("cpu")
|
| 39 |
+
adapter.dtype = torch.bfloat16
|
| 40 |
+
frames = np.zeros((1, 2, 2, 3), np.uint8)
|
| 41 |
+
monkeypatch.setattr(
|
| 42 |
+
adapter,
|
| 43 |
+
"_read_video",
|
| 44 |
+
lambda path, count: (frames, np.array([0.25], np.float32)),
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
class Model:
|
| 48 |
+
def __call__(self, images):
|
| 49 |
+
return {
|
| 50 |
+
"instance_maps": torch.zeros((1, 2, 1, 2, 2), dtype=torch.bfloat16),
|
| 51 |
+
"instance_labels": torch.zeros((1, 2, 3)),
|
| 52 |
+
"depth": torch.ones((1, 1, 2, 2)),
|
| 53 |
+
"pose_enc": torch.zeros((1, 1, 4)),
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
adapter.model = Model()
|
| 57 |
+
adapter.runtime = torch
|
| 58 |
+
output = tmp_path / "nested" / "scene.pt"
|
| 59 |
+
adapter.run_scene("video.mp4", output, 1)
|
| 60 |
+
|
| 61 |
+
assert output.is_file()
|
| 62 |
+
assert not output.with_suffix(".pt.tmp").exists()
|
| 63 |
+
cache = torch.load(output, map_location="cpu", weights_only=False)
|
| 64 |
+
assert set(cache) == {
|
| 65 |
+
"instance_maps",
|
| 66 |
+
"instance_labels",
|
| 67 |
+
"depth",
|
| 68 |
+
"pose_enc",
|
| 69 |
+
}
|
| 70 |
+
assert cache["instance_maps"].dtype == torch.bfloat16
|
| 71 |
+
assert cache["depth"].dtype == torch.float32
|
| 72 |
+
assert all(value.device.type == "cpu" for value in cache.values())
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_da3_preserves_native_prediction_object(tmp_path, monkeypatch):
|
| 76 |
+
adapter = adapters.DepthAnything3Adapter()
|
| 77 |
+
prediction = SimpleNamespace(
|
| 78 |
+
depth=np.ones((2, 3, 4), dtype=np.float32),
|
| 79 |
+
conf=np.ones((2, 3, 4), dtype=np.float16),
|
| 80 |
+
is_metric=True,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
class Model:
|
| 84 |
+
def inference(self, images, export_dir):
|
| 85 |
+
assert images == ["frame"]
|
| 86 |
+
assert export_dir is None
|
| 87 |
+
return prediction
|
| 88 |
+
|
| 89 |
+
adapter.model = Model()
|
| 90 |
+
monkeypatch.setattr(adapter, "_read_video", lambda path, count: ["frame"])
|
| 91 |
+
output = tmp_path / "depth-anything-3" / "scene.pkl"
|
| 92 |
+
adapter.run_scene("video.mp4", output, 1)
|
| 93 |
+
|
| 94 |
+
with output.open("rb") as stream:
|
| 95 |
+
restored = pickle.load(stream)
|
| 96 |
+
assert vars(restored).keys() == vars(prediction).keys()
|
| 97 |
+
assert restored.depth.dtype == np.float32
|
| 98 |
+
assert restored.conf.dtype == np.float16
|
| 99 |
+
assert restored.is_metric is True
|
| 100 |
+
assert not output.with_suffix(".pkl.tmp").exists()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_sam3_preserves_independent_image_responses_without_tracking(
|
| 104 |
+
tmp_path, monkeypatch
|
| 105 |
+
):
|
| 106 |
+
states = []
|
| 107 |
+
monkeypatch.setitem(
|
| 108 |
+
sys.modules,
|
| 109 |
+
"PIL",
|
| 110 |
+
SimpleNamespace(Image=SimpleNamespace(fromarray=lambda frame: frame)),
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
class Processor:
|
| 114 |
+
def set_image(self, image):
|
| 115 |
+
state = {"frame": len(states), "shape": image.shape}
|
| 116 |
+
states.append(state)
|
| 117 |
+
return state
|
| 118 |
+
|
| 119 |
+
def set_text_prompt(self, state, prompt):
|
| 120 |
+
assert prompt == "chair"
|
| 121 |
+
return {"state": state, "masks": np.ones((1, 2, 2), np.float32)}
|
| 122 |
+
|
| 123 |
+
class InferenceMode:
|
| 124 |
+
def __enter__(self):
|
| 125 |
+
return self
|
| 126 |
+
|
| 127 |
+
def __exit__(self, *args):
|
| 128 |
+
return False
|
| 129 |
+
|
| 130 |
+
class Runtime:
|
| 131 |
+
@staticmethod
|
| 132 |
+
def inference_mode():
|
| 133 |
+
return InferenceMode()
|
| 134 |
+
|
| 135 |
+
@staticmethod
|
| 136 |
+
def save(value, path):
|
| 137 |
+
with open(path, "wb") as stream:
|
| 138 |
+
pickle.dump(value, stream)
|
| 139 |
+
|
| 140 |
+
adapter = adapters.SAM3Adapter(prompt="chair")
|
| 141 |
+
adapter.model = object()
|
| 142 |
+
adapter.processor = Processor()
|
| 143 |
+
adapter.runtime = Runtime()
|
| 144 |
+
monkeypatch.setattr(
|
| 145 |
+
adapters,
|
| 146 |
+
"_sample_video_frames",
|
| 147 |
+
lambda path, count: (
|
| 148 |
+
np.stack(
|
| 149 |
+
[
|
| 150 |
+
np.zeros((2, 3, 3), np.uint8),
|
| 151 |
+
np.ones((2, 3, 3), np.uint8),
|
| 152 |
+
]
|
| 153 |
+
),
|
| 154 |
+
np.array([0.0, 1.0], np.float32),
|
| 155 |
+
),
|
| 156 |
+
)
|
| 157 |
+
output = tmp_path / "sam3" / "scene.pt"
|
| 158 |
+
adapter.run_scene("video.mp4", output, 2)
|
| 159 |
+
|
| 160 |
+
with output.open("rb") as stream:
|
| 161 |
+
restored = pickle.load(stream)
|
| 162 |
+
assert [response["state"]["frame"] for response in restored] == [0, 1]
|
| 163 |
+
assert all(response["masks"].dtype == np.float32 for response in restored)
|
| 164 |
+
assert len(states) == 2
|
| 165 |
+
assert not output.with_suffix(".pt.tmp").exists()
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_combined_adapter_gives_both_models_the_same_decoded_frames(monkeypatch):
|
| 169 |
+
calls = []
|
| 170 |
+
frames = np.arange(24, dtype=np.uint8).reshape(2, 2, 2, 3)
|
| 171 |
+
monkeypatch.setattr(
|
| 172 |
+
adapters,
|
| 173 |
+
"_sample_video_frames",
|
| 174 |
+
lambda path, count: (frames, np.array([0.0, 1.0], np.float32)),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
class Child:
|
| 178 |
+
def __init__(self, name):
|
| 179 |
+
self.name = name
|
| 180 |
+
|
| 181 |
+
def run_frames(self, received_frames, output_path):
|
| 182 |
+
calls.append((self.name, received_frames, output_path))
|
| 183 |
+
|
| 184 |
+
adapter = adapters.SAM3DepthAnything3Adapter()
|
| 185 |
+
adapter.sam3 = Child("sam3")
|
| 186 |
+
adapter.depth_anything_3 = Child("depth-anything-3")
|
| 187 |
+
outputs = {
|
| 188 |
+
"sam3": "/root/data/caches/sam3/scene.pt",
|
| 189 |
+
"depth-anything-3": "/root/data/caches/depth-anything-3/scene.pkl",
|
| 190 |
+
}
|
| 191 |
+
adapter.run_scene("/videos/scene.mp4", outputs, 32)
|
| 192 |
+
|
| 193 |
+
assert [(name, path) for name, _, path in calls] == [
|
| 194 |
+
("sam3", outputs["sam3"]),
|
| 195 |
+
("depth-anything-3", outputs["depth-anything-3"]),
|
| 196 |
+
]
|
| 197 |
+
assert calls[0][1] is calls[1][1]
|
| 198 |
+
assert calls[0][1] is frames
|
tests/test_inference/test_inference.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from inference import adapters
|
| 6 |
+
from inference import launch
|
| 7 |
+
from inference import run
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class FakeAdapter:
|
| 11 |
+
model = object()
|
| 12 |
+
|
| 13 |
+
def __init__(self):
|
| 14 |
+
self.calls = []
|
| 15 |
+
|
| 16 |
+
def run_scene(self, video_path, output_path, frame_count):
|
| 17 |
+
self.calls.append((video_path, output_path, frame_count))
|
| 18 |
+
path = Path(output_path)
|
| 19 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 20 |
+
path.touch()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_adapter_registry():
|
| 24 |
+
assert adapters.available_models() == (
|
| 25 |
+
"depth-anything-3",
|
| 26 |
+
"sam3",
|
| 27 |
+
"sam3+depth-anything-3",
|
| 28 |
+
"segvggt",
|
| 29 |
+
)
|
| 30 |
+
assert isinstance(
|
| 31 |
+
adapters.get_adapter("depth-anything-3"),
|
| 32 |
+
adapters.DepthAnything3Adapter,
|
| 33 |
+
)
|
| 34 |
+
assert isinstance(adapters.get_adapter("sam3"), adapters.SAM3Adapter)
|
| 35 |
+
assert isinstance(
|
| 36 |
+
adapters.get_adapter("sam3+depth-anything-3"),
|
| 37 |
+
adapters.SAM3DepthAnything3Adapter,
|
| 38 |
+
)
|
| 39 |
+
assert isinstance(adapters.get_adapter("segvggt"), adapters.SegVGGTAdapter)
|
| 40 |
+
with pytest.raises(KeyError, match="unknown inference model"):
|
| 41 |
+
adapters.get_adapter("unknown")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_local_model_roots_are_exact(monkeypatch):
|
| 45 |
+
for variable in ("VSI_SEGVGGT_ROOT", "VSI_SAM3_ROOT", "VSI_DA3_ROOT"):
|
| 46 |
+
monkeypatch.delenv(variable, raising=False)
|
| 47 |
+
assert adapters.SegVGGTAdapter().model_root == Path("/root/models/SegVGGT")
|
| 48 |
+
assert adapters.SAM3Adapter().model_root == Path("/root/models/sam3")
|
| 49 |
+
assert adapters.DepthAnything3Adapter().model_root == Path(
|
| 50 |
+
"/root/models/depth-anything-3"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_native_output_paths(tmp_path, monkeypatch):
|
| 55 |
+
monkeypatch.setattr(run.inference_config, "CACHE_ROOT", tmp_path)
|
| 56 |
+
assert run.output_path("scene1", "depth-anything-3") == str(
|
| 57 |
+
tmp_path / "depth-anything-3" / "scene1.pkl"
|
| 58 |
+
)
|
| 59 |
+
assert run.output_path("scene1", "sam3") == str(tmp_path / "sam3" / "scene1.pt")
|
| 60 |
+
assert run.output_path("scene1", "sam3+depth-anything-3") == {
|
| 61 |
+
"sam3": str(tmp_path / "sam3" / "scene1.pt"),
|
| 62 |
+
"depth-anything-3": str(tmp_path / "depth-anything-3" / "scene1.pkl"),
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_run_scene_builds_then_skips(tmp_path, monkeypatch):
|
| 67 |
+
monkeypatch.setattr(run.inference_config, "CACHE_ROOT", tmp_path)
|
| 68 |
+
monkeypatch.setattr(
|
| 69 |
+
run.inference_config, "video_path", lambda scene: f"/videos/{scene}.mp4"
|
| 70 |
+
)
|
| 71 |
+
adapter = FakeAdapter()
|
| 72 |
+
assert run.run_scene("scene1", adapter=adapter) == (
|
| 73 |
+
"built",
|
| 74 |
+
str(tmp_path / "segvggt" / "scene1.pt"),
|
| 75 |
+
)
|
| 76 |
+
assert run.run_scene("scene1", adapter=adapter)[0] == "skipped"
|
| 77 |
+
assert len(adapter.calls) == 1
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_scenes_deduplicates_manifest(tmp_path, monkeypatch):
|
| 81 |
+
manifest = tmp_path / "test.jsonl"
|
| 82 |
+
manifest.write_text(
|
| 83 |
+
'{"scene_name": "s1"}\n{"scene_name": "s2"}\n{"scene_name": "s1"}\n'
|
| 84 |
+
)
|
| 85 |
+
monkeypatch.setattr(launch.inference_config, "JSONL", manifest)
|
| 86 |
+
assert launch.scenes() == ["s1", "s2"]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_visible_gpus_uses_environment(monkeypatch):
|
| 90 |
+
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "2, 4, -1")
|
| 91 |
+
assert launch.visible_gpus() == ["2", "4"]
|
tests/test_inference/test_launch.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from queue import Queue
|
| 2 |
+
from types import SimpleNamespace
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from inference import launch
|
| 8 |
+
from inference import run
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class FakeAdapter:
|
| 12 |
+
def __init__(self, load_error=None):
|
| 13 |
+
self.load_error = load_error
|
| 14 |
+
self.load_calls = []
|
| 15 |
+
|
| 16 |
+
def load_model(self, device):
|
| 17 |
+
self.load_calls.append(device)
|
| 18 |
+
if self.load_error:
|
| 19 |
+
raise self.load_error
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _queues(*scenes):
|
| 23 |
+
tasks, results = Queue(), Queue()
|
| 24 |
+
for scene in scenes:
|
| 25 |
+
tasks.put(scene)
|
| 26 |
+
tasks.put(None)
|
| 27 |
+
return tasks, results
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_worker_loads_adapter_once_and_reuses_it(monkeypatch):
|
| 31 |
+
adapter = FakeAdapter()
|
| 32 |
+
calls = []
|
| 33 |
+
fake_run = SimpleNamespace(
|
| 34 |
+
run_scene=lambda scene, model, frames, rebuild, adapter: (
|
| 35 |
+
calls.append(scene) or ("built", f"/{scene}.npz")
|
| 36 |
+
)
|
| 37 |
+
)
|
| 38 |
+
monkeypatch.setattr(launch.adapters, "get_adapter", lambda model: adapter)
|
| 39 |
+
monkeypatch.setattr(launch, "_load_run_module", lambda: fake_run)
|
| 40 |
+
tasks, results = _queues("s1", "s2")
|
| 41 |
+
|
| 42 |
+
launch._worker(tasks, results, "segvggt", 32, False, "3", 2)
|
| 43 |
+
|
| 44 |
+
assert adapter.load_calls == ["cuda:0"]
|
| 45 |
+
assert calls == ["s1", "s2"]
|
| 46 |
+
assert results.get() == ("s1", True, "built -> /s1.npz")
|
| 47 |
+
assert results.get() == ("s2", True, "built -> /s2.npz")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_worker_reports_model_load_failure_for_every_scene(monkeypatch):
|
| 51 |
+
adapter = FakeAdapter(RuntimeError("load failed"))
|
| 52 |
+
monkeypatch.setattr(launch.adapters, "get_adapter", lambda model: adapter)
|
| 53 |
+
monkeypatch.setattr(launch, "_load_run_module", lambda: SimpleNamespace())
|
| 54 |
+
tasks, results = _queues("s1", "s2")
|
| 55 |
+
|
| 56 |
+
launch._worker(tasks, results, "segvggt", 32, False, None, 1)
|
| 57 |
+
|
| 58 |
+
for expected in ("s1", "s2"):
|
| 59 |
+
scene, ok, detail = results.get()
|
| 60 |
+
assert scene == expected and not ok
|
| 61 |
+
assert "load failed" in detail
|
| 62 |
+
assert adapter.load_calls == ["cpu"]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_worker_reports_scene_failure_and_continues(monkeypatch):
|
| 66 |
+
adapter = FakeAdapter()
|
| 67 |
+
|
| 68 |
+
def run_scene(scene, *args, **kwargs):
|
| 69 |
+
if scene == "bad":
|
| 70 |
+
raise ValueError("broken scene")
|
| 71 |
+
return "built", f"/{scene}.npz"
|
| 72 |
+
|
| 73 |
+
monkeypatch.setattr(launch.adapters, "get_adapter", lambda model: adapter)
|
| 74 |
+
monkeypatch.setattr(
|
| 75 |
+
launch, "_load_run_module", lambda: SimpleNamespace(run_scene=run_scene)
|
| 76 |
+
)
|
| 77 |
+
tasks, results = _queues("bad", "good")
|
| 78 |
+
|
| 79 |
+
launch._worker(tasks, results, "segvggt", 32, False, None, 1)
|
| 80 |
+
|
| 81 |
+
first, second = results.get(), results.get()
|
| 82 |
+
assert first[0:2] == ("bad", False) and "broken scene" in first[2]
|
| 83 |
+
assert second == ("good", True, "built -> /good.npz")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_run_scene_rebuild_overwrites_existing_cache(tmp_path, monkeypatch):
|
| 87 |
+
monkeypatch.setattr(run.inference_config, "CACHE_ROOT", tmp_path)
|
| 88 |
+
monkeypatch.setattr(
|
| 89 |
+
run.inference_config, "video_path", lambda scene: f"/{scene}.mp4"
|
| 90 |
+
)
|
| 91 |
+
destination = tmp_path / "segvggt" / "s1.pt"
|
| 92 |
+
destination.parent.mkdir()
|
| 93 |
+
destination.write_bytes(b"old")
|
| 94 |
+
calls = []
|
| 95 |
+
adapter = SimpleNamespace(
|
| 96 |
+
run_scene=lambda *args: calls.append(args) or destination.write_bytes(b"new")
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
status, _ = run.run_scene("s1", rebuild=True, adapter=adapter)
|
| 100 |
+
|
| 101 |
+
assert status == "built"
|
| 102 |
+
assert destination.read_bytes() == b"new"
|
| 103 |
+
assert len(calls) == 1
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_visible_gpus_falls_back_to_nvidia_smi(monkeypatch):
|
| 107 |
+
monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
|
| 108 |
+
monkeypatch.setattr(
|
| 109 |
+
launch.subprocess, "check_output", lambda *args, **kwargs: "0\n2\n"
|
| 110 |
+
)
|
| 111 |
+
assert launch.visible_gpus() == ["0", "2"]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_launch_main_skips_all_existing_caches(tmp_path, monkeypatch, capsys):
|
| 115 |
+
cache = tmp_path / "s1.npz"
|
| 116 |
+
cache.touch()
|
| 117 |
+
monkeypatch.setattr(launch, "scenes", lambda: ["s1"])
|
| 118 |
+
monkeypatch.setattr(
|
| 119 |
+
launch,
|
| 120 |
+
"_load_run_module",
|
| 121 |
+
lambda: SimpleNamespace(output_paths=lambda *args: {"segvggt": str(cache)}),
|
| 122 |
+
)
|
| 123 |
+
monkeypatch.setattr(sys, "argv", ["launch.py"])
|
| 124 |
+
monkeypatch.setattr(
|
| 125 |
+
launch.mp, "get_context", lambda *args: pytest.fail("workers should not start")
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
launch.main()
|
| 129 |
+
|
| 130 |
+
assert "DONE: 0 built, 1 skipped, 0 failed" in capsys.readouterr().out
|
tests/test_inference/test_run.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional real-model validation; enable with VSI_RUN_GPU_TESTS=1."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from inference import adapters
|
| 9 |
+
from inference import run
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@pytest.mark.skipif(
|
| 13 |
+
os.environ.get("VSI_RUN_GPU_TESTS") != "1",
|
| 14 |
+
reason="set VSI_RUN_GPU_TESTS=1 to run real SegVGGT inference",
|
| 15 |
+
)
|
| 16 |
+
def test_real_segvggt_scene_preserves_native_prediction_dictionary(tmp_path):
|
| 17 |
+
torch = pytest.importorskip("torch")
|
| 18 |
+
with open(run.inference_config.JSONL) as manifest:
|
| 19 |
+
scene = str(json.loads(next(manifest))["scene_name"])
|
| 20 |
+
adapter = adapters.get_adapter("segvggt")
|
| 21 |
+
adapter.load_model("cuda:0")
|
| 22 |
+
output = tmp_path / f"{scene}.pt"
|
| 23 |
+
adapter.run_scene(
|
| 24 |
+
run.inference_config.video_path(scene),
|
| 25 |
+
str(output),
|
| 26 |
+
run.inference_config.FRAMES_PER_VIDEO,
|
| 27 |
+
)
|
| 28 |
+
cache = torch.load(output, map_location="cpu", weights_only=False)
|
| 29 |
+
assert isinstance(cache, dict)
|
| 30 |
+
assert {
|
| 31 |
+
"pose_enc",
|
| 32 |
+
"depth",
|
| 33 |
+
"world_points",
|
| 34 |
+
"instance_maps",
|
| 35 |
+
"instance_labels",
|
| 36 |
+
}.issubset(cache)
|
| 37 |
+
assert all(
|
| 38 |
+
value.device.type == "cpu"
|
| 39 |
+
for value in cache.values()
|
| 40 |
+
if isinstance(value, torch.Tensor)
|
| 41 |
+
)
|
tests/test_symbolic/conftest.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared import setup and fixtures for symbolic tests."""
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from types import ModuleType
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 11 |
+
SYMBOLIC_ROOT = ROOT / "symbolic"
|
| 12 |
+
ENCODER_ROOT = ROOT / "encoder"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def pytest_configure(config):
|
| 16 |
+
config.option.importmode = "importlib"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if str(SYMBOLIC_ROOT) not in sys.path:
|
| 20 |
+
sys.path.insert(0, str(SYMBOLIC_ROOT))
|
| 21 |
+
sys.modules.setdefault("utils", ModuleType("utils"))
|
| 22 |
+
|
| 23 |
+
launch_spec = importlib.util.spec_from_file_location(
|
| 24 |
+
"symbolic_launch_tests", SYMBOLIC_ROOT / "launch.py"
|
| 25 |
+
)
|
| 26 |
+
symbolic_launch = importlib.util.module_from_spec(launch_spec)
|
| 27 |
+
sys.modules["symbolic_launch_tests"] = symbolic_launch
|
| 28 |
+
launch_spec.loader.exec_module(symbolic_launch)
|
| 29 |
+
sys.modules["symbolic_run_tests"] = symbolic_launch.symbolic_run
|
| 30 |
+
sys.modules["symbolic_solver_tests"] = symbolic_launch.symbolic_run.sym
|
| 31 |
+
|
| 32 |
+
if str(SYMBOLIC_ROOT) in sys.path:
|
| 33 |
+
sys.path.remove(str(SYMBOLIC_ROOT))
|
| 34 |
+
if str(ENCODER_ROOT) not in sys.path:
|
| 35 |
+
sys.path.insert(0, str(ENCODER_ROOT))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest.fixture
|
| 39 |
+
def spatial_code():
|
| 40 |
+
def object_record(x, y, size="1.0 meters", count=1):
|
| 41 |
+
return {
|
| 42 |
+
"count": count,
|
| 43 |
+
"instances": [
|
| 44 |
+
{
|
| 45 |
+
"position": {
|
| 46 |
+
"x coordinate": f"{x} meters",
|
| 47 |
+
"y coordinate": f"{y} meters",
|
| 48 |
+
"height above floor": "0.5 meters",
|
| 49 |
+
},
|
| 50 |
+
"longest dimension": size,
|
| 51 |
+
}
|
| 52 |
+
],
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
return {
|
| 56 |
+
"objects": {
|
| 57 |
+
"chair": object_record(0, 0, "0.8 meters", count=2),
|
| 58 |
+
"table": object_record(0, 1, "1.2 meters"),
|
| 59 |
+
"lamp": object_record(-1, 1, "0.4 meters"),
|
| 60 |
+
"sofa": object_record(1, 1, "2.0 meters"),
|
| 61 |
+
},
|
| 62 |
+
"room": {"floor area": "12.5 square meters"},
|
| 63 |
+
"appearance order": ["chair", "table", "lamp", "sofa"],
|
| 64 |
+
"closest classes distance meters from": {
|
| 65 |
+
"chair": {
|
| 66 |
+
"table": {"distance": "1.0 meters", "closeness rank": 1},
|
| 67 |
+
"lamp": {"distance": "1.4 meters", "closeness rank": 2},
|
| 68 |
+
"sofa": {"distance": "1.5 meters", "closeness rank": 3},
|
| 69 |
+
},
|
| 70 |
+
"table": {
|
| 71 |
+
"chair": {"distance": "1.0 meters", "closeness rank": 1},
|
| 72 |
+
"lamp": {"distance": "0.8 meters", "closeness rank": 2},
|
| 73 |
+
"sofa": {"distance": "0.9 meters", "closeness rank": 3},
|
| 74 |
+
},
|
| 75 |
+
"lamp": {"table": {"distance": "0.8 meters", "closeness rank": 1}},
|
| 76 |
+
"sofa": {"table": {"distance": "0.9 meters", "closeness rank": 1}},
|
| 77 |
+
},
|
| 78 |
+
}
|
tests/test_symbolic/test_launch.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import symbolic_launch_tests as launch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _question(question_type, answer, ground_truth, question, options=None):
|
| 9 |
+
return {
|
| 10 |
+
"question_type": question_type,
|
| 11 |
+
"engine_answer": answer,
|
| 12 |
+
"ground_truth": ground_truth,
|
| 13 |
+
"question": question,
|
| 14 |
+
"options": options,
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_scenes_with_spatial_codes_returns_sorted_stems(tmp_path, monkeypatch):
|
| 19 |
+
monkeypatch.setattr(launch.symbolic_run, "SPATIAL_CODES_DIR", str(tmp_path))
|
| 20 |
+
for name in ("scene2.json", "scene1.json"):
|
| 21 |
+
(tmp_path / name).write_text(json.dumps({}))
|
| 22 |
+
assert launch.scenes_with_spatial_codes() == ["scene1", "scene2"]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_error_analysis_summarizes_numeric_errors():
|
| 26 |
+
questions = [
|
| 27 |
+
_question("object_counting", 3, "2", "How many chair(s) are in this room?"),
|
| 28 |
+
_question("object_counting", 1, "2", "How many table(s) are in this room?"),
|
| 29 |
+
_question("object_counting", None, "1", "How many lamp(s) are in this room?"),
|
| 30 |
+
]
|
| 31 |
+
result = launch.error_analysis({"scene1": (questions, {})}, "object_counting")
|
| 32 |
+
assert result["n"] == 3
|
| 33 |
+
assert result["n_unanswered"] == 1
|
| 34 |
+
assert result["mean_absolute_error"] == 1.0
|
| 35 |
+
assert result["overcounts"] == 1
|
| 36 |
+
assert result["undercounts"] == 1
|
| 37 |
+
assert [item["class"] for item in result["by_class"]] == ["chair", "table"]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_error_analysis_rejects_non_numeric_question_type():
|
| 41 |
+
with pytest.raises(ValueError, match="only supports"):
|
| 42 |
+
launch.error_analysis({}, "route_planning")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_mca_answer_breakdown_distinguishes_outcomes():
|
| 46 |
+
options = ["A. chair, table, lamp", "B. table, chair, lamp"]
|
| 47 |
+
questions = [
|
| 48 |
+
_question("obj_appearance_order", "A", "A", "question", options),
|
| 49 |
+
_question("obj_appearance_order", "B", "A", "question", options),
|
| 50 |
+
_question("obj_appearance_order", None, "A", "question", options),
|
| 51 |
+
]
|
| 52 |
+
result = launch.mca_answer_breakdown(
|
| 53 |
+
{"scene1": (questions, {})}, "obj_appearance_order"
|
| 54 |
+
)
|
| 55 |
+
assert result == {
|
| 56 |
+
"n": 3,
|
| 57 |
+
"n_unanswered": 1,
|
| 58 |
+
"n_wrong": 1,
|
| 59 |
+
"n_correct": 1,
|
| 60 |
+
"mean_swap_distance": 1.0,
|
| 61 |
+
}
|
tests/test_symbolic/test_run.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import symbolic_run_tests as symbolic_run
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_find_workspace_root_uses_spatial_codes_folder(tmp_path):
|
| 9 |
+
start = tmp_path / "project" / "symbolic"
|
| 10 |
+
(tmp_path / "project" / "data" / "spatial codes" / "sam3+depth-anything-3").mkdir(
|
| 11 |
+
parents=True
|
| 12 |
+
)
|
| 13 |
+
start.mkdir()
|
| 14 |
+
assert symbolic_run._find_workspace_root(start) == str(tmp_path / "project")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_fetch_spatial_code_reads_flat_json(tmp_path, monkeypatch, spatial_code):
|
| 18 |
+
monkeypatch.setattr(symbolic_run, "SPATIAL_CODES_DIR", str(tmp_path))
|
| 19 |
+
(tmp_path / "scene1.json").write_text(json.dumps(spatial_code))
|
| 20 |
+
assert symbolic_run.spatial_code_path("scene1") == str(tmp_path / "scene1.json")
|
| 21 |
+
assert symbolic_run.fetch_spatial_code("scene1") == spatial_code
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_select_model_reads_fusion_subfolder(tmp_path, monkeypatch):
|
| 25 |
+
monkeypatch.setattr(symbolic_run, "SPATIAL_CODES_ROOT", str(tmp_path))
|
| 26 |
+
monkeypatch.setattr(symbolic_run, "SPATIAL_CODES_DIR_OVERRIDE", None)
|
| 27 |
+
assert symbolic_run.select_spatial_codes_model("sam3+depth-anything-3") == str(
|
| 28 |
+
tmp_path / "sam3+depth-anything-3"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_fetch_spatial_code_reports_missing_file(tmp_path, monkeypatch):
|
| 33 |
+
monkeypatch.setattr(symbolic_run, "SPATIAL_CODES_DIR", str(tmp_path))
|
| 34 |
+
with pytest.raises(FileNotFoundError, match="no spatial code found"):
|
| 35 |
+
symbolic_run.fetch_spatial_code("missing")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_real_questions_for_scene_filters_jsonl(tmp_path):
|
| 39 |
+
path = tmp_path / "test.jsonl"
|
| 40 |
+
rows = [
|
| 41 |
+
{"scene_name": "scene1", "id": "q1"},
|
| 42 |
+
{"scene_name": "scene2", "id": "q2"},
|
| 43 |
+
{"scene_name": "scene1", "id": "q3"},
|
| 44 |
+
]
|
| 45 |
+
path.write_text("\n".join(json.dumps(row) for row in rows))
|
| 46 |
+
assert [
|
| 47 |
+
row["id"] for row in symbolic_run.real_questions_for_scene("scene1", path)
|
| 48 |
+
] == [
|
| 49 |
+
"q1",
|
| 50 |
+
"q3",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_write_scene_results_uses_one_file_per_question(tmp_path, spatial_code):
|
| 55 |
+
question = {
|
| 56 |
+
"question_id": "q1",
|
| 57 |
+
"dataset": "scannet",
|
| 58 |
+
"question_type": "object_counting",
|
| 59 |
+
"question": "How many chair(s) are in this room?",
|
| 60 |
+
"options": None,
|
| 61 |
+
"engine_answer": 2,
|
| 62 |
+
"ground_truth": "2",
|
| 63 |
+
"score": 1.0,
|
| 64 |
+
}
|
| 65 |
+
paths = symbolic_run.write_scene_results(
|
| 66 |
+
"scene1", [question], {"accuracy": 1.0}, spatial_code, tmp_path
|
| 67 |
+
)
|
| 68 |
+
record = json.loads((tmp_path / "scene1" / "q1.json").read_text())
|
| 69 |
+
aggregate = json.loads((tmp_path / "scene1" / "_aggregate.json").read_text())
|
| 70 |
+
assert len(paths) == 2
|
| 71 |
+
assert record["answer_given"] == "2"
|
| 72 |
+
assert record["model"] == "symbolic"
|
| 73 |
+
assert aggregate == {"scene_id": "scene1", "aggregate": {"accuracy": 1.0}}
|
tests/test_symbolic/test_solver.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
import symbolic_solver_tests as solver
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_unit_parsers_accept_strings_and_numbers():
|
| 7 |
+
assert solver._parse_meters("-1.25 meters") == -1.25
|
| 8 |
+
assert solver._parse_square_meters("12.5 square meters") == 12.5
|
| 9 |
+
assert solver._parse_meters(3) == 3.0
|
| 10 |
+
with pytest.raises(ValueError, match="could not parse"):
|
| 11 |
+
solver._parse_meters("unknown")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_direct_numeric_answers(spatial_code):
|
| 15 |
+
assert (
|
| 16 |
+
solver.answer(
|
| 17 |
+
"object_counting", "How many chair(s) are in this room?", None, spatial_code
|
| 18 |
+
)
|
| 19 |
+
== 2
|
| 20 |
+
)
|
| 21 |
+
assert (
|
| 22 |
+
solver.answer(
|
| 23 |
+
"object_size_estimation",
|
| 24 |
+
"What is the longest dimension of the table, measured in centimeters?",
|
| 25 |
+
None,
|
| 26 |
+
spatial_code,
|
| 27 |
+
)
|
| 28 |
+
== 120.0
|
| 29 |
+
)
|
| 30 |
+
assert (
|
| 31 |
+
solver.answer(
|
| 32 |
+
"room_size_estimation", "What is the size of this room?", None, spatial_code
|
| 33 |
+
)
|
| 34 |
+
== 12.5
|
| 35 |
+
)
|
| 36 |
+
assert (
|
| 37 |
+
solver.answer(
|
| 38 |
+
"object_abs_distance",
|
| 39 |
+
"What is the distance between the chair and the table (in meters)?",
|
| 40 |
+
None,
|
| 41 |
+
spatial_code,
|
| 42 |
+
)
|
| 43 |
+
== 1.0
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_multiple_choice_distance_and_order_answers(spatial_code):
|
| 48 |
+
assert (
|
| 49 |
+
solver.answer(
|
| 50 |
+
"object_rel_distance",
|
| 51 |
+
"Which of these objects is closest to the table?",
|
| 52 |
+
["A. sofa", "B. lamp", "C. chair"],
|
| 53 |
+
spatial_code,
|
| 54 |
+
)
|
| 55 |
+
== "B"
|
| 56 |
+
)
|
| 57 |
+
assert (
|
| 58 |
+
solver.answer(
|
| 59 |
+
"obj_appearance_order",
|
| 60 |
+
"What is the first-time appearance order of the categories?",
|
| 61 |
+
["A. table, chair, lamp", "B. chair, table, lamp"],
|
| 62 |
+
spatial_code,
|
| 63 |
+
)
|
| 64 |
+
== "B"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_direction_answers_use_floor_coordinates(spatial_code):
|
| 69 |
+
question = (
|
| 70 |
+
"If I am standing by the chair and facing the table, is the lamp to my left?"
|
| 71 |
+
)
|
| 72 |
+
assert (
|
| 73 |
+
solver.answer(
|
| 74 |
+
"object_rel_direction_hard",
|
| 75 |
+
question,
|
| 76 |
+
["A. front-left", "B. front-right", "C. back-left", "D. back-right"],
|
| 77 |
+
spatial_code,
|
| 78 |
+
)
|
| 79 |
+
== "A"
|
| 80 |
+
)
|
| 81 |
+
assert (
|
| 82 |
+
solver.answer(
|
| 83 |
+
"object_rel_direction_easy",
|
| 84 |
+
question,
|
| 85 |
+
["A. left", "B. right"],
|
| 86 |
+
spatial_code,
|
| 87 |
+
)
|
| 88 |
+
== "A"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_route_planning_chains_turns(spatial_code):
|
| 93 |
+
question = (
|
| 94 |
+
"You are a robot beginning at the chair facing the table. Actions: "
|
| 95 |
+
"1. Go forward until the table 2. [please fill in] "
|
| 96 |
+
"3. Go forward until the lamp."
|
| 97 |
+
)
|
| 98 |
+
assert (
|
| 99 |
+
solver.answer(
|
| 100 |
+
"route_planning",
|
| 101 |
+
question,
|
| 102 |
+
["A. Turn Left", "B. Turn Right", "C. Turn Back"],
|
| 103 |
+
spatial_code,
|
| 104 |
+
)
|
| 105 |
+
== "A"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_dispatch_returns_none_for_unknown_or_missing_data(spatial_code):
|
| 110 |
+
assert solver.answer("unknown", "question", None, spatial_code) is None
|
| 111 |
+
assert (
|
| 112 |
+
solver.answer(
|
| 113 |
+
"object_counting",
|
| 114 |
+
"How many cabinet(s) are in this room?",
|
| 115 |
+
None,
|
| 116 |
+
spatial_code,
|
| 117 |
+
)
|
| 118 |
+
== 0
|
| 119 |
+
)
|
| 120 |
+
assert solver.pairwise_swap_distance(["a", "b", "c"], ["b", "a", "c"]) == 1
|
| 121 |
+
assert solver.pairwise_swap_distance(["a"], ["b"]) is None
|
tests/test_symbolic/test_symbolic.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Folder-level contract tests for the symbolic package."""
|
| 2 |
+
|
| 3 |
+
import symbolic_launch_tests as launch
|
| 4 |
+
import symbolic_run_tests as run
|
| 5 |
+
import symbolic_solver_tests as solver
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_symbolic_folder_modules_are_wired_together():
|
| 9 |
+
assert launch.symbolic_run is run
|
| 10 |
+
assert run.sym is solver
|
| 11 |
+
assert callable(run.score_scene)
|
| 12 |
+
assert callable(launch.run_all)
|
| 13 |
+
assert callable(solver.answer)
|