#!/usr/bin/env python3 from __future__ import annotations import argparse import hashlib import importlib.util import json import pickle import re import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable import cv2 import numpy as np from PIL import Image from scipy.optimize import linear_sum_assignment SCENE_EXTS = (".blend", ".glb", ".gltf") IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".bmp") DEPTH_NAMES = ("depth.npy", "depth.npz", "depth.png", "depth.exr") CAMERA_NAMES = ( "camera.json", "cameras.json", "poses.json", "camera_poses.json", "transforms.json", "extrinsics.npy", "extrinsics.npz", "poses.npy", "poses.npz", "cameras.npz", ) EPS = 1e-9 OBJECT_NAME_STOPWORDS = { "object", "geometry", "mesh", "model", "shape", "textured", "scene", "gt", "pred", } def lower_is_better_to_score(value: float, bad_value: float = 1.0) -> float: if bad_value <= 0: raise ValueError("bad_value must be > 0") normalized = max(0.0, min(1.0, value / bad_value)) return 100.0 * (1.0 - normalized) @dataclass(frozen=True) class AssetBundle: key: str base: Path scene: Path images: tuple[Path, ...] text: Path | None depth: Path | None camera: Path | None generated_meta: Path | None def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="Run full eval for one sample id across multiple models") p.add_argument("--sample_id", required=True) p.add_argument("--data_root", default="data") p.add_argument("--gt_key", default="gt") p.add_argument( "--models", required=True, help="Comma-separated model keys under data_root", ) p.add_argument("--blender_bin", required=True) p.add_argument("--clip_model_path", required=True) p.add_argument("--clip_batch_size", type=int, default=32) p.add_argument("--out_json", required=True) p.add_argument( "--alignment", choices=["identity", "bbox", "object_bbox", "depth_bbox", "depth_camera"], default="bbox", help=( "Transform pred geometry into GT coordinates before IoU. " "object_bbox anchors on the best first-frame object IoU match; " "depth_camera uses depth median scale plus first-camera canonicalization." ), ) p.add_argument( "--ground_policy", choices=["exclude", "include"], default="exclude", help=( "Whether to exclude detected ground/floor/large planes from bbox alignment " "and scene/object IoU. Use include to benchmark with ground from alignment onward." ), ) p.add_argument( "--camera_convention", choices=["auto", "world_to_camera", "camera_to_world"], default="auto", help="Convention for camera matrices used by --alignment depth_camera.", ) p.add_argument( "--camera_rotation_only", action="store_true", help="For --alignment depth_camera, use only first-frame camera rotation and ignore camera translation.", ) p.add_argument( "--auto_scene_meta", action=argparse.BooleanOptionalAction, default=True, help="Auto-extract camera.json/depth.npy from scene.blend/glb when missing.", ) p.add_argument( "--scene_meta_dir", default=None, help="Cache directory for auto-extracted scene camera/depth metadata.", ) p.add_argument( "--alignment_dir", default=None, help="Directory for per-model alignment_transform.json files (default: out_json parent/alignments)", ) p.add_argument( "--geometry_frame_mode", default="first_mid_last", help="Geometry frames used for IoU-B extraction: first_only, first_mid_last, last_only, or exact:.", ) p.add_argument( "--image_glob", default="frames/*,selected_frames/*,eval_frames/*,scene.png", help="Comma-separated image globs relative to each asset directory", ) p.add_argument( "--scene_filename", default=None, help="Optional fixed scene filename, e.g. scene.glb. Otherwise auto-detect scene.*", ) p.add_argument( "--allow_missing_images", action="store_true", help="Skip PL/N-CLIP for models without selected images instead of failing", ) p.add_argument( "--skip_selected_image_metrics", action="store_true", help="Skip selected-frame PL/N-CLIP in this stage. Useful when rendered metrics are computed later.", ) args = p.parse_args() _validate_frame_mode(args.geometry_frame_mode) return args def _validate_frame_mode(mode: str) -> None: if mode in {"first_only", "first_mid_last", "last_only"}: return if mode.startswith("exact:"): raw = mode.split(":", 1)[1].strip() if raw and raw.lstrip("-").isdigit(): return raise ValueError( f"Unsupported --geometry_frame_mode {mode!r}; expected first_only, " "first_mid_last, last_only, or exact:." ) def _project_root() -> Path: return Path(__file__).resolve().parents[1] def _resolve_data_root(project_root: Path, raw: str) -> Path: path = Path(raw) if path.is_absolute(): return path return (project_root / path).resolve() def _first_existing(paths: Iterable[Path]) -> Path | None: for path in paths: if path.exists(): return path return None def _find_scene(base: Path, scene_filename: str | None) -> Path: if scene_filename: scene = base / scene_filename if scene.exists(): return scene raise FileNotFoundError(f"Missing scene asset: {scene}") for ext in SCENE_EXTS: scene = base / f"scene{ext}" if scene.exists(): return scene candidates: list[Path] = [] for ext in SCENE_EXTS: candidates.extend(sorted(base.glob(f"*{ext}"))) if candidates: return candidates[0] raise FileNotFoundError(f"No scene asset found under {base} ({', '.join(SCENE_EXTS)})") def _find_images(base: Path, image_glob: str) -> tuple[Path, ...]: out: list[Path] = [] seen: set[Path] = set() patterns = [x.strip() for x in image_glob.split(",") if x.strip()] for pattern in patterns: for path in sorted(base.glob(pattern)): if not path.is_file(): continue if path.suffix.lower() not in IMAGE_EXTS: continue resolved = path.resolve() if resolved in seen: continue seen.add(resolved) out.append(resolved) return tuple(out) def _find_depth(base: Path) -> Path | None: direct = _first_existing(base / name for name in DEPTH_NAMES) if direct is not None: return direct depth_dir = base / "depth" if depth_dir.is_dir(): for ext in (".npy", ".npz", ".png", ".exr"): cands = sorted(depth_dir.glob(f"*{ext}")) if cands: return cands[0] return None def _find_camera(base: Path) -> Path | None: direct = _first_existing(base / name for name in CAMERA_NAMES) if direct is not None: return direct camera_dir = base / "camera" if camera_dir.is_dir(): for name in CAMERA_NAMES: candidate = camera_dir / name if candidate.exists(): return candidate for pattern in ("*.json", "*.npy", "*.npz", "*.txt"): cands = sorted(camera_dir.glob(pattern)) if cands: return cands[0] cameras_dir = base / "cameras" if cameras_dir.is_dir(): for pattern in ("*.json", "*.npy", "*.npz", "*.txt"): cands = sorted(cameras_dir.glob(pattern)) if cands: return cands[0] return None def _scene_meta_script_path(project_root: Path) -> Path: script = project_root / "scripts" / "extract_scene_camera_depth.py" if not script.exists(): raise FileNotFoundError(f"Missing scene meta extraction script: {script}") return script def _scene_meta_cache_dir(root: Path, asset: AssetBundle) -> Path: stat = asset.scene.stat() key = f"{asset.scene.resolve()}::{stat.st_mtime_ns}::scene_meta_v1" digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:12] return root / asset.key / asset.scene.stem / digest def ensure_scene_meta( asset: AssetBundle, *, project_root: Path, blender_bin: str, scene_meta_dir: Path, force: bool = False, ) -> AssetBundle: if asset.depth is not None and asset.camera is not None: return asset out_dir = _scene_meta_cache_dir(scene_meta_dir, asset) camera_path = out_dir / "camera.json" depth_path = out_dir / "depth.npy" if force or not camera_path.exists() or not depth_path.exists(): out_dir.mkdir(parents=True, exist_ok=True) cmd = [ blender_bin, "--factory-startup", "--background", "--python", str(_scene_meta_script_path(project_root)), "--", "--input", str(asset.scene), "--output_dir", str(out_dir), ] proc = subprocess.run(cmd, capture_output=True, text=True) if proc.returncode != 0 or not camera_path.exists() or not depth_path.exists(): raise RuntimeError( "Scene camera/depth metadata extraction failed\n" f"scene={asset.scene}\n" f"code={proc.returncode}\n" f"stdout_tail={proc.stdout[-1000:]}\n" f"stderr_tail={proc.stderr[-1000:]}" ) return AssetBundle( key=asset.key, base=asset.base, scene=asset.scene, images=asset.images, text=asset.text, depth=asset.depth or depth_path, camera=asset.camera or camera_path, generated_meta=out_dir, ) def load_assets( data_root: Path, model_key: str, sample_id: str, *, image_glob: str, scene_filename: str | None, ) -> AssetBundle: base = data_root / model_key / sample_id scene = _find_scene(base, scene_filename) text = _first_existing([base / "description.txt", base / "prompt.txt", base / "text.txt"]) return AssetBundle( key=model_key, base=base, scene=scene.resolve(), images=_find_images(base, image_glob), text=text.resolve() if text is not None else None, depth=_find_depth(base), camera=_find_camera(base), generated_meta=None, ) def import_bbox_helpers(project_root: Path): bbox_script = project_root / "scripts" / "eval_bbox_iou_blend.py" spec = importlib.util.spec_from_file_location("eval_bbox_iou_blend", bbox_script) if spec is None or spec.loader is None: raise RuntimeError(f"Unable to import {bbox_script}") mod = importlib.util.module_from_spec(spec) import sys sys.modules[spec.name] = mod spec.loader.exec_module(mod) return mod def run_extract( blender_bin: str, extract_script: Path, scene_path: Path, out_path: Path, *, frame_mode: str, ) -> None: cmd = [ blender_bin, "--factory-startup", "--background", "--python", str(extract_script), "--", "--input", str(scene_path), "--output", str(out_path), "--frame_mode", frame_mode, ] proc = subprocess.run(cmd, capture_output=True, text=True) if proc.returncode != 0 or not out_path.exists(): raise RuntimeError( "Scene extraction failed\n" f"scene={scene_path}\n" f"code={proc.returncode}\n" f"stdout_tail={proc.stdout[-1000:]}\n" f"stderr_tail={proc.stderr[-1000:]}" ) def _load_payload( scene_path: Path, *, blender_bin: str, extract_script: Path, frame_mode: str, payload_cache: dict[str, dict[str, Any]], ) -> dict[str, Any]: k = f"{scene_path.resolve()}::{frame_mode}" if k in payload_cache: return payload_cache[k] with tempfile.TemporaryDirectory(prefix="big_eval_extract_") as td: p = Path(td) / "mesh.pkl" run_extract(blender_bin, extract_script, scene_path, p, frame_mode=frame_mode) payload = pickle.loads(p.read_bytes()) payload_cache[k] = payload return payload def _aligned_indices(total: int, target: int) -> list[int]: if total <= 0 or target <= 0: return [] if target >= total: return list(range(total)) return np.linspace(0, total - 1, num=target, dtype=int).tolist() def _stack_frame_vertices(bbox_mod: Any, frame: dict[str, Any]) -> np.ndarray: return bbox_mod._stack_vertices(bbox_mod._to_mesh_map(frame)) _GROUND_NAME_TOKENS = ("ground", "floor", "plane", "table_plane", "backdrop", "wall") def _is_ground_object(name: str, vertices: np.ndarray, scene_diag: float) -> bool: low = name.lower() if any(tok in low for tok in _GROUND_NAME_TOKENS): return True if vertices.size == 0: return False ext = vertices.max(axis=0) - vertices.min(axis=0) xy = float(np.hypot(ext[0], ext[1])) z = float(ext[2]) if scene_diag > 0 and xy >= 0.55 * scene_diag and z <= 0.06 * max(xy, EPS): return True return False def _stack_frame_vertices_no_ground(bbox_mod: Any, frame: dict[str, Any]) -> np.ndarray: mesh_map = bbox_mod._to_mesh_map(frame) full = bbox_mod._stack_vertices(mesh_map) if full.size == 0: return full scene_diag = float(np.linalg.norm(full.max(axis=0) - full.min(axis=0))) kept = { name: md for name, md in mesh_map.items() if not _is_ground_object(name, md.vertices, scene_diag) } if not kept: return full stacked = bbox_mod._stack_vertices(kept) return stacked if stacked.size else full def _drop_ground_from_map(mesh_map: dict[str, Any]) -> dict[str, Any]: if not mesh_map: return mesh_map full = _stack_mesh_map_safe(mesh_map) scene_diag = float(np.linalg.norm(full.max(axis=0) - full.min(axis=0))) if full.size else 0.0 kept = { name: md for name, md in mesh_map.items() if not _is_ground_object(name, md.vertices, scene_diag) } return kept if kept else mesh_map def _stack_mesh_map_safe(mesh_map: dict[str, Any]) -> np.ndarray: chunks = [md.vertices for md in mesh_map.values() if getattr(md, "vertices", None) is not None and md.vertices.size] if not chunks: return np.zeros((0, 3), dtype=np.float64) return np.concatenate(chunks, axis=0) def _aabb_bounds(vertices: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None: if vertices.size == 0: return None return np.min(vertices, axis=0), np.max(vertices, axis=0) def _center(bounds: tuple[np.ndarray, np.ndarray] | None) -> np.ndarray: if bounds is None: return np.zeros(3, dtype=np.float64) return 0.5 * (bounds[0] + bounds[1]) def _diag(bounds: tuple[np.ndarray, np.ndarray] | None) -> float: if bounds is None: return 1.0 return float(np.linalg.norm(bounds[1] - bounds[0])) def _first_frame_mesh_map(bbox_mod: Any, payload: dict[str, Any]) -> dict[str, Any]: frame = payload["objects_per_frame"][0] if payload.get("objects_per_frame") else {} return bbox_mod._to_mesh_map(frame) def _name_tokens(name: str) -> set[str]: tokens = set(re.findall(r"[a-zA-Z]+", name.lower())) return {tok for tok in tokens if tok not in OBJECT_NAME_STOPWORDS and len(tok) > 1} def _best_object_anchor_bounds( bbox_mod: Any, gt_payload: dict[str, Any], pred_payload: dict[str, Any], ) -> tuple[tuple[np.ndarray, np.ndarray] | None, tuple[np.ndarray, np.ndarray] | None, dict[str, Any] | None]: gt_map = _first_frame_mesh_map(bbox_mod, gt_payload) pred_map = _first_frame_mesh_map(bbox_mod, pred_payload) best: tuple[tuple[int, float], str, str, float, tuple[np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray]] | None = None for gt_name, gt_mesh in gt_map.items(): gt_bounds = _aabb_bounds(gt_mesh.vertices) if gt_bounds is None: continue gt_tokens = _name_tokens(gt_name) for pred_name, pred_mesh in pred_map.items(): pred_bounds = _aabb_bounds(pred_mesh.vertices) if pred_bounds is None: continue aabb, obb = _bbox_iou_for_meshes(bbox_mod, gt_mesh.vertices, pred_mesh.vertices) token_overlap = len(gt_tokens & _name_tokens(pred_name)) score = (token_overlap, float(aabb)) if best is None or score > best[0]: best = (score, gt_name, pred_name, float(obb), gt_bounds, pred_bounds) if best is None: return None, None, None score, gt_name, pred_name, obb, gt_bounds, pred_bounds = best return gt_bounds, pred_bounds, { "gt_name": gt_name, "pred_name": pred_name, "name_token_overlap": score[0], "first_frame_aabb_iou_before_alignment": score[1], "first_frame_obb_iou_before_alignment": obb, } def _read_depth_values(depth_path: Path | None) -> np.ndarray: if depth_path is None or not depth_path.exists(): return np.zeros((0,), dtype=np.float64) ext = depth_path.suffix.lower() if ext == ".npy": arr = np.load(depth_path) elif ext == ".npz": data = np.load(depth_path) key = "depth" if "depth" in data else data.files[0] arr = data[key] else: arr = cv2.imread(str(depth_path), cv2.IMREAD_UNCHANGED) if arr is None: return np.zeros((0,), dtype=np.float64) if arr.dtype == np.uint16: arr = arr.astype(np.float32) / 1000.0 arr = np.asarray(arr, dtype=np.float64) vals = arr[np.isfinite(arr) & (arr > 1e-8)] return vals.reshape(-1) def _depth_median(depth_path: Path | None) -> float | None: vals = _read_depth_values(depth_path) if vals.size == 0: return None return float(np.median(vals)) def _as_4x4(matrix_like: Any) -> np.ndarray | None: arr = np.asarray(matrix_like, dtype=np.float64) if arr.shape == (4, 4): return arr if arr.shape == (3, 4): out = np.eye(4, dtype=np.float64) out[:3, :4] = arr return out if arr.ndim == 3 and arr.shape[-2:] == (4, 4) and arr.shape[0] > 0: return arr[0] if arr.ndim == 3 and arr.shape[-2:] == (3, 4) and arr.shape[0] > 0: out = np.eye(4, dtype=np.float64) out[:3, :4] = arr[0] return out return None def _matrix_from_json_obj(obj: Any) -> tuple[np.ndarray | None, str | None]: if isinstance(obj, list): matrix = _as_4x4(obj) if matrix is not None: return matrix, None if obj: return _matrix_from_json_obj(obj[0]) if not isinstance(obj, dict): return None, None for key in ("world_to_camera", "w2c", "extrinsic", "extrinsics", "T_world_to_camera"): if key in obj: matrix = _as_4x4(obj[key]) if matrix is not None: return matrix, "world_to_camera" for key in ("camera_to_world", "c2w", "pose", "poses", "transform_matrix", "T_camera_to_world"): if key in obj: matrix = _as_4x4(obj[key]) if matrix is not None: return matrix, "camera_to_world" for key in ("frames", "cameras"): value = obj.get(key) if isinstance(value, list) and value: return _matrix_from_json_obj(value[0]) numeric_values = [v for v in obj.values() if isinstance(v, (list, tuple, dict))] for value in numeric_values: matrix, convention = _matrix_from_json_obj(value) if matrix is not None: return matrix, convention return None, None def _load_camera_matrix(camera_path: Path | None) -> tuple[np.ndarray | None, str | None]: if camera_path is None or not camera_path.exists(): return None, None ext = camera_path.suffix.lower() if ext == ".json": data = json.loads(camera_path.read_text(encoding="utf-8")) return _matrix_from_json_obj(data) if ext == ".npy": return _as_4x4(np.load(camera_path)), None if ext == ".npz": data = np.load(camera_path) priority = ( "world_to_camera", "w2c", "extrinsics", "extrinsic", "camera_to_world", "c2w", "poses", "pose", ) for key in priority: if key in data: matrix = _as_4x4(data[key]) if matrix is not None: if key in {"world_to_camera", "w2c", "extrinsics", "extrinsic"}: return matrix, "world_to_camera" if key in {"camera_to_world", "c2w", "poses", "pose"}: return matrix, "camera_to_world" for key in data.files: matrix = _as_4x4(data[key]) if matrix is not None: return matrix, None if ext == ".txt": arr = np.loadtxt(camera_path) return _as_4x4(arr), None return None, None def _orthonormalize_rotation(rot: np.ndarray) -> np.ndarray: u, _, vt = np.linalg.svd(rot) out = u @ vt if np.linalg.det(out) < 0: u[:, -1] *= -1.0 out = u @ vt return out def _camera_world_to_camera( camera_path: Path | None, *, convention: str, ) -> tuple[np.ndarray | None, str | None]: matrix, inferred = _load_camera_matrix(camera_path) if matrix is None: return None, None use_convention = inferred if convention == "auto" else convention if use_convention is None: use_convention = "world_to_camera" matrix = np.asarray(matrix, dtype=np.float64) if use_convention == "camera_to_world": matrix = np.linalg.inv(matrix) elif use_convention != "world_to_camera": raise ValueError(f"Unsupported camera convention: {use_convention}") matrix[:3, :3] = _orthonormalize_rotation(matrix[:3, :3]) return matrix, use_convention def _camera_canonical_matrix( camera_path: Path | None, *, convention: str, rotation_only: bool, ) -> tuple[np.ndarray | None, str | None]: w2c, used_convention = _camera_world_to_camera(camera_path, convention=convention) if w2c is None: return None, None matrix = np.eye(4, dtype=np.float64) matrix[:3, :3] = w2c[:3, :3] if not rotation_only: matrix[:3, 3] = w2c[:3, 3] return matrix, used_convention def _compose_similarity( canonical: np.ndarray, scale: float, *, center_after: np.ndarray | None = None, ) -> np.ndarray: matrix = canonical.copy() matrix[:3, :3] *= float(scale) matrix[:3, 3] *= float(scale) if center_after is not None: matrix[:3, 3] += center_after return matrix def build_alignment_transform( gt_payload: dict[str, Any], pred_payload: dict[str, Any], *, gt_depth: Path | None, pred_depth: Path | None, gt_camera: Path | None = None, pred_camera: Path | None = None, mode: str, bbox_mod: Any, camera_convention: str = "auto", camera_rotation_only: bool = False, ground_policy: str = "exclude", ) -> dict[str, Any]: gt_frame = gt_payload["objects_per_frame"][0] if gt_payload["objects_per_frame"] else {} pred_frame = pred_payload["objects_per_frame"][0] if pred_payload["objects_per_frame"] else {} gt_vertices = _stack_frame_vertices(bbox_mod, gt_frame) pred_vertices = _stack_frame_vertices(bbox_mod, pred_frame) gt_bounds = _aabb_bounds(gt_vertices) pred_bounds = _aabb_bounds(pred_vertices) scale = 1.0 scale_source = "identity" gt_matrix = np.eye(4, dtype=np.float64) pred_matrix = np.eye(4, dtype=np.float64) gt_camera_convention = None pred_camera_convention = None uses_camera = False alignment_anchor: dict[str, Any] | None = None if mode == "bbox": if ground_policy == "exclude": gt_align_bounds = _aabb_bounds(_stack_frame_vertices_no_ground(bbox_mod, gt_frame)) pred_align_bounds = _aabb_bounds(_stack_frame_vertices_no_ground(bbox_mod, pred_frame)) if gt_align_bounds is not None: gt_bounds = gt_align_bounds if pred_align_bounds is not None: pred_bounds = pred_align_bounds scale_source = "scene_bbox_diag_no_ground" else: scale_source = "scene_bbox_diag_with_ground" scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS) elif mode == "object_bbox": anchor_gt_bounds, anchor_pred_bounds, alignment_anchor = _best_object_anchor_bounds( bbox_mod, gt_payload, pred_payload, ) if anchor_gt_bounds is not None and anchor_pred_bounds is not None: gt_bounds = anchor_gt_bounds pred_bounds = anchor_pred_bounds scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS) scale_source = "best_object_bbox_diag" else: scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS) scale_source = "scene_bbox_diag_fallback_no_object_anchor" elif mode == "depth_bbox": gt_med = _depth_median(gt_depth) pred_med = _depth_median(pred_depth) if gt_med is not None and pred_med is not None: scale = gt_med / max(pred_med, EPS) scale_source = "depth_median_ratio" else: scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS) scale_source = "scene_bbox_diag_fallback" elif mode == "identity": scale = 1.0 elif mode == "depth_camera": gt_med = _depth_median(gt_depth) pred_med = _depth_median(pred_depth) if gt_med is not None and pred_med is not None: scale = gt_med / max(pred_med, EPS) scale_source = "depth_median_ratio" else: scale = _diag(gt_bounds) / max(_diag(pred_bounds), EPS) scale_source = "scene_bbox_diag_fallback_no_depth" gt_canon, gt_camera_convention = _camera_canonical_matrix( gt_camera, convention=camera_convention, rotation_only=camera_rotation_only, ) pred_canon, pred_camera_convention = _camera_canonical_matrix( pred_camera, convention=camera_convention, rotation_only=camera_rotation_only, ) if gt_canon is None or pred_canon is None: raise FileNotFoundError( "depth_camera alignment requires readable first-frame camera matrices for both GT and Pred. " f"gt_camera={gt_camera} pred_camera={pred_camera}" ) gt_matrix = gt_canon pred_matrix = _compose_similarity(pred_canon, scale) uses_camera = True else: raise ValueError(f"Unsupported alignment mode: {mode}") if not uses_camera: gt_center = _center(gt_bounds) pred_center = _center(pred_bounds) translation = gt_center - scale * pred_center pred_matrix = np.eye(4, dtype=np.float64) pred_matrix[:3, :3] *= scale pred_matrix[:3, 3] = translation if mode == "identity": pred_matrix[:3, 3] = 0.0 return { "mode": mode, "transform_direction": "gt_to_eval_and_pred_to_eval", "matrix": pred_matrix.tolist(), "gt_matrix": gt_matrix.tolist(), "pred_matrix": pred_matrix.tolist(), "scale": float(scale), "translation": pred_matrix[:3, 3].astype(float).tolist(), "rotation": pred_matrix[:3, :3].astype(float).tolist(), "scale_source": scale_source, "gt_depth": str(gt_depth) if gt_depth else None, "pred_depth": str(pred_depth) if pred_depth else None, "gt_camera": str(gt_camera) if gt_camera else None, "pred_camera": str(pred_camera) if pred_camera else None, "camera_convention": camera_convention, "gt_camera_convention_used": gt_camera_convention, "pred_camera_convention_used": pred_camera_convention, "camera_rotation_only": bool(camera_rotation_only), "ground_policy": ground_policy, "alignment_anchor": alignment_anchor, "note": ( "This transform is generated before geometry metrics. depth_camera maps " "GT and Pred into first-camera canonical coordinates and applies depth " "median scale to Pred; bbox/depth_bbox/object_bbox keep pred-to-GT " "uniform scale + translation behavior." ), } def _transform_vertices(vertices: np.ndarray, matrix: np.ndarray) -> np.ndarray: if vertices.size == 0: return vertices.astype(np.float64, copy=False) rot_scale = matrix[:3, :3] trans = matrix[:3, 3] return (vertices.astype(np.float64) @ rot_scale.T + trans).astype(np.float64, copy=False) def _transformed_mesh_map(bbox_mod: Any, raw_frame: dict[str, Any], matrix: np.ndarray) -> dict[str, Any]: mesh_map = bbox_mod._to_mesh_map(raw_frame) for mesh in mesh_map.values(): mesh.vertices = _transform_vertices(mesh.vertices, matrix) return mesh_map def _bbox_iou_for_meshes(bbox_mod: Any, gt_vertices: np.ndarray, pred_vertices: np.ndarray) -> tuple[float, float]: aabb = bbox_mod._aabb_iou( bbox_mod._aabb_from_vertices(gt_vertices), bbox_mod._aabb_from_vertices(pred_vertices), ) obb = bbox_mod._obb_iou( bbox_mod._obb_from_vertices(gt_vertices), bbox_mod._obb_from_vertices(pred_vertices), ) return float(aabb), float(obb) def _match_objects_by_iou( bbox_mod: Any, gt_map: dict[str, Any], pred_map: dict[str, Any], ) -> dict[str, Any]: gt_names = sorted(gt_map.keys()) pred_names = sorted(pred_map.keys()) if not gt_names and not pred_names: return { "aabb_penalized": 1.0, "obb_penalized": 1.0, "aabb_matched_mean": 1.0, "obb_matched_mean": 1.0, "matches": [], "unmatched_gt": [], "unmatched_pred": [], } if not gt_names or not pred_names: return { "aabb_penalized": 0.0, "obb_penalized": 0.0, "aabb_matched_mean": 0.0, "obb_matched_mean": 0.0, "matches": [], "unmatched_gt": gt_names, "unmatched_pred": pred_names, } aabb_matrix = np.zeros((len(gt_names), len(pred_names)), dtype=np.float64) obb_matrix = np.zeros_like(aabb_matrix) for gi, gt_name in enumerate(gt_names): for pi, pred_name in enumerate(pred_names): aabb, obb = _bbox_iou_for_meshes( bbox_mod, gt_map[gt_name].vertices, pred_map[pred_name].vertices, ) aabb_matrix[gi, pi] = aabb obb_matrix[gi, pi] = obb rows, cols = linear_sum_assignment(-aabb_matrix) matches: list[dict[str, Any]] = [] matched_aabb: list[float] = [] matched_obb: list[float] = [] used_gt: set[str] = set() used_pred: set[str] = set() for row, col in zip(rows, cols): aabb = float(aabb_matrix[row, col]) obb = float(obb_matrix[row, col]) if aabb <= 0.0 and obb <= 0.0: continue gt_name = gt_names[row] pred_name = pred_names[col] used_gt.add(gt_name) used_pred.add(pred_name) matched_aabb.append(aabb) matched_obb.append(obb) matches.append( { "gt_name": gt_name, "pred_name": pred_name, "aabb_iou": aabb, "obb_iou": obb, } ) denom = max(len(gt_names), len(pred_names), 1) return { "aabb_penalized": float(np.sum(matched_aabb) / denom), "obb_penalized": float(np.sum(matched_obb) / denom), "aabb_matched_mean": float(np.mean(matched_aabb)) if matched_aabb else 0.0, "obb_matched_mean": float(np.mean(matched_obb)) if matched_obb else 0.0, "matches": matches, "unmatched_gt": sorted(set(gt_names) - used_gt), "unmatched_pred": sorted(set(pred_names) - used_pred), } def ioub_aligned( bbox_mod: Any, gt_payload: dict[str, Any], pred_payload: dict[str, Any], transform: dict[str, Any], *, ground_policy: str = "exclude", ) -> dict[str, Any]: gt_frames = gt_payload["objects_per_frame"] pred_frames = pred_payload["objects_per_frame"] target = min(len(gt_frames), len(pred_frames)) gt_idx = _aligned_indices(len(gt_frames), target) pred_idx = _aligned_indices(len(pred_frames), target) gt_matrix = np.asarray(transform.get("gt_matrix", np.eye(4)), dtype=np.float64) pred_matrix = np.asarray(transform.get("pred_matrix", transform["matrix"]), dtype=np.float64) scene_aabb_frames: list[float] = [] scene_obb_frames: list[float] = [] obj_aabb_pen_frames: list[float] = [] obj_obb_pen_frames: list[float] = [] frame_details: list[dict[str, Any]] = [] for gi, pi in zip(gt_idx, pred_idx): gt_map = _transformed_mesh_map(bbox_mod, gt_frames[gi], gt_matrix) pred_map = _transformed_mesh_map(bbox_mod, pred_frames[pi], pred_matrix) if ground_policy == "exclude": gt_map = _drop_ground_from_map(gt_map) pred_map = _drop_ground_from_map(pred_map) gt_scene_vertices = bbox_mod._stack_vertices(gt_map) pred_scene_vertices = bbox_mod._stack_vertices(pred_map) scene_aabb, scene_obb = _bbox_iou_for_meshes(bbox_mod, gt_scene_vertices, pred_scene_vertices) scene_aabb_frames.append(scene_aabb) scene_obb_frames.append(scene_obb) obj_match = _match_objects_by_iou(bbox_mod, gt_map, pred_map) obj_aabb_pen_frames.append(float(obj_match["aabb_penalized"])) obj_obb_pen_frames.append(float(obj_match["obb_penalized"])) frame_details.append( { "gt_frame_no": int(gt_payload["frame_indices"][gi]), "pred_frame_no": int(pred_payload["frame_indices"][pi]), "scene_aabb_iou": scene_aabb, "scene_obb_iou": scene_obb, "gt_object_count": len(gt_map), "pred_object_count": len(pred_map), "matched_object_count": len(obj_match["matches"]), "object_match_mode": "hungarian_aabb_iou", "ground_policy": ground_policy, "object_aabb_iou_penalized": obj_match["aabb_penalized"], "object_obb_iou_penalized": obj_match["obb_penalized"], "matched_object_mean_aabb": obj_match["aabb_matched_mean"], "matched_object_mean_obb": obj_match["obb_matched_mean"], "unmatched_gt": obj_match["unmatched_gt"], "unmatched_pred": obj_match["unmatched_pred"], "per_object_matched": obj_match["matches"], } ) return { "scene_aabb_iou_frames": scene_aabb_frames, "scene_obb_iou_frames": scene_obb_frames, "object_aabb_iou_penalized_frames": obj_aabb_pen_frames, "object_obb_iou_penalized_frames": obj_obb_pen_frames, "scene_aabb_iou_mean": float(np.mean(scene_aabb_frames)) if scene_aabb_frames else 0.0, "scene_obb_iou_mean": float(np.mean(scene_obb_frames)) if scene_obb_frames else 0.0, "object_aabb_iou_penalized_mean": float(np.mean(obj_aabb_pen_frames)) if obj_aabb_pen_frames else 0.0, "object_obb_iou_penalized_mean": float(np.mean(obj_obb_pen_frames)) if obj_obb_pen_frames else 0.0, "frame_details": frame_details, } def read_image_rgb(path: Path) -> np.ndarray: bgr = cv2.imread(str(path), cv2.IMREAD_COLOR) if bgr is None: raise ValueError(f"Unable to decode image: {path}") return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) def _align_image_paths(gt_images: tuple[Path, ...], pred_images: tuple[Path, ...]) -> list[tuple[Path, Path]]: if not gt_images or not pred_images: return [] target = min(len(gt_images), len(pred_images)) gt_idx = _aligned_indices(len(gt_images), target) pred_idx = _aligned_indices(len(pred_images), target) return [(gt_images[g], pred_images[p]) for g, p in zip(gt_idx, pred_idx)] def photometric_loss_image(gt_frame: np.ndarray, pred_frame: np.ndarray) -> float: if pred_frame.shape[:2] != gt_frame.shape[:2]: h, w = gt_frame.shape[:2] pred_frame = cv2.resize(pred_frame, (w, h), interpolation=cv2.INTER_AREA) gt = gt_frame[..., :3].astype(np.float32) / 255.0 pred = pred_frame[..., :3].astype(np.float32) / 255.0 return float(np.mean(np.square(gt - pred))) def pl_images(gt_images: tuple[Path, ...], pred_images: tuple[Path, ...]) -> dict[str, Any]: pairs = _align_image_paths(gt_images, pred_images) if not pairs: raise FileNotFoundError("PL requires at least one GT image and one prediction image") losses = [photometric_loss_image(read_image_rgb(g), read_image_rgb(p)) for g, p in pairs] raw = float(np.mean(losses)) return { "metric": "PhotometricLoss_SelectedImages", "pl_raw": raw, "score_100": float(lower_is_better_to_score(raw, bad_value=1.0)), "frame_count": len(pairs), "mode": "selected_images", "gt_frame_count": len(gt_images), "pred_frame_count": len(pred_images), "pairs": [{"gt": str(g), "pred": str(p)} for g, p in pairs], "frame_losses": losses, "direction": "lower_is_better", } def _encode_image_features( images: list[Image.Image], model: Any, processor: Any, device: str, batch_size: int, ) -> Any: import torch feats: list[torch.Tensor] = [] with torch.no_grad(): for start in range(0, len(images), batch_size): chunk = images[start : start + batch_size] inputs = processor(images=chunk, return_tensors="pt") inputs = {k: v.to(device) for k, v in inputs.items()} image_features = model.get_image_features(**inputs) image_features = image_features / image_features.norm(dim=-1, keepdim=True) feats.append(image_features) return torch.cat(feats, dim=0) def nclip_images( gt_images: tuple[Path, ...], pred_images: tuple[Path, ...], model: Any, processor: Any, device: str, batch_size: int, ) -> dict[str, Any]: import torch pairs = _align_image_paths(gt_images, pred_images) if not pairs: raise FileNotFoundError("N-CLIP requires at least one GT image and one prediction image") gt_pil = [Image.fromarray(read_image_rgb(g)) for g, _ in pairs] pred_pil = [Image.fromarray(read_image_rgb(p)) for _, p in pairs] gt_feat = _encode_image_features(gt_pil, model, processor, device, batch_size) pred_feat = _encode_image_features(pred_pil, model, processor, device, batch_size) sims = torch.nn.functional.cosine_similarity(pred_feat, gt_feat, dim=-1) sim_values = sims.detach().cpu().numpy().astype(float).tolist() nclip_values = [float(1.0 - x) for x in sim_values] raw = float(np.mean(nclip_values)) return { "metric": "VIGA_N_CLIP_SelectedImages", "n_clip_raw": raw, "clip_similarity_mean": float(np.mean(sim_values)), "score_100": float(100.0 * max(0.0, min(1.0, 1.0 - raw))), "frame_count": len(pairs), "mode": "selected_images_image_image", "pairs": [{"gt": str(g), "pred": str(p)} for g, p in pairs], "frame_clip_similarity": sim_values, "frame_n_clip": nclip_values, "formula": "mean_i(1 - CLIPSim(pred_image_i, gt_image_i))", "direction": "lower_is_better", } def _missing_visual_metric( name: str, gt_images: tuple[Path, ...], pred_images: tuple[Path, ...], *, reason: str = "missing selected images", ) -> dict[str, Any]: return { "metric": name, "skipped": True, "reason": reason, "gt_frame_count": len(gt_images), "pred_frame_count": len(pred_images), "score_100": 0.0, } def main() -> None: args = parse_args() project_root = _project_root() data_root = _resolve_data_root(project_root, args.data_root) out_json = Path(args.out_json).resolve() out_json.parent.mkdir(parents=True, exist_ok=True) alignment_dir = Path(args.alignment_dir).resolve() if args.alignment_dir else out_json.parent / "alignments" alignment_dir.mkdir(parents=True, exist_ok=True) scene_meta_dir = Path(args.scene_meta_dir).resolve() if args.scene_meta_dir else out_json.parent / "scene_meta" if args.scene_meta_dir and not scene_meta_dir.is_absolute(): scene_meta_dir = (project_root / scene_meta_dir).resolve() gt_key = args.gt_key models = [x.strip() for x in args.models.split(",") if x.strip()] if not models: raise ValueError("models list is empty") all_assets = { k: load_assets( data_root, k, args.sample_id, image_glob=args.image_glob, scene_filename=args.scene_filename, ) for k in [gt_key] + models } if args.auto_scene_meta and args.alignment == "depth_camera": all_assets = { k: ensure_scene_meta( v, project_root=project_root, blender_bin=args.blender_bin, scene_meta_dir=scene_meta_dir, ) for k, v in all_assets.items() } bbox_mod = import_bbox_helpers(project_root) extract_script = project_root / "scripts" / "extract_blend_meshes.py" payload_cache: dict[str, dict[str, Any]] = {} gt_payload = _load_payload( all_assets[gt_key].scene, blender_bin=args.blender_bin, extract_script=extract_script, frame_mode=args.geometry_frame_mode, payload_cache=payload_cache, ) ious: dict[str, Any] = {} alignments: dict[str, Any] = {} for key in models: pred_payload = _load_payload( all_assets[key].scene, blender_bin=args.blender_bin, extract_script=extract_script, frame_mode=args.geometry_frame_mode, payload_cache=payload_cache, ) transform = build_alignment_transform( gt_payload, pred_payload, gt_depth=all_assets[gt_key].depth, pred_depth=all_assets[key].depth, gt_camera=all_assets[gt_key].camera, pred_camera=all_assets[key].camera, mode=args.alignment, bbox_mod=bbox_mod, camera_convention=args.camera_convention, camera_rotation_only=args.camera_rotation_only, ground_policy=args.ground_policy, ) align_path = alignment_dir / args.sample_id / key / "alignment_transform.json" align_path.parent.mkdir(parents=True, exist_ok=True) transform_with_paths = { **transform, "gt_scene": str(all_assets[gt_key].scene), "pred_scene": str(all_assets[key].scene), } align_path.write_text(json.dumps(transform_with_paths, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") alignments[key] = {**transform_with_paths, "path": str(align_path)} ious[key] = ioub_aligned( bbox_mod, gt_payload, pred_payload, transform, ground_policy=args.ground_policy, ) pl_nclip: dict[str, Any] = {} if args.skip_selected_image_metrics: device = "skipped" for key in models: gt_images = all_assets[gt_key].images pred_images = all_assets[key].images pl_nclip[key] = { "media_type": "selected_images", "gt_images": [str(x) for x in gt_images], "pred_images": [str(x) for x in pred_images], "pl": _missing_visual_metric( "PhotometricLoss_SelectedImages", gt_images, pred_images, reason="disabled by --skip_selected_image_metrics", ), "n_clip": _missing_visual_metric( "VIGA_N_CLIP_SelectedImages", gt_images, pred_images, reason="disabled by --skip_selected_image_metrics", ), } else: import torch from transformers import CLIPModel, CLIPProcessor clip_model = CLIPModel.from_pretrained(args.clip_model_path, local_files_only=True) clip_processor = CLIPProcessor.from_pretrained(args.clip_model_path, local_files_only=True) device = "cuda" if torch.cuda.is_available() else "cpu" clip_model = clip_model.to(device) clip_model.eval() for key in models: gt_images = all_assets[gt_key].images pred_images = all_assets[key].images if not gt_images or not pred_images: if not args.allow_missing_images: raise FileNotFoundError( f"Missing selected images for model={key}: " f"gt_count={len(gt_images)} pred_count={len(pred_images)}" ) pl = _missing_visual_metric("PhotometricLoss_SelectedImages", gt_images, pred_images) n_clip = _missing_visual_metric("VIGA_N_CLIP_SelectedImages", gt_images, pred_images) else: pl = pl_images(gt_images, pred_images) n_clip = nclip_images( gt_images, pred_images, clip_model, clip_processor, device, args.clip_batch_size, ) pl_nclip[key] = { "media_type": "selected_images", "gt_images": [str(x) for x in gt_images], "pred_images": [str(x) for x in pred_images], "pl": pl, "n_clip": n_clip, } summary = [] for key in models: summary.append( { "model": key, "scene_aabb_iou_mean": ious[key]["scene_aabb_iou_mean"], "scene_obb_iou_mean": ious[key]["scene_obb_iou_mean"], "object_aabb_iou_penalized_mean": ious[key]["object_aabb_iou_penalized_mean"], "object_obb_iou_penalized_mean": ious[key]["object_obb_iou_penalized_mean"], "pl_score_100": pl_nclip[key]["pl"]["score_100"], "n_clip_score_100": pl_nclip[key]["n_clip"]["score_100"], "pl_raw": pl_nclip[key]["pl"].get("pl_raw"), "n_clip_raw": pl_nclip[key]["n_clip"].get("n_clip_raw"), "alignment_mode": alignments[key]["mode"], "alignment_scale": alignments[key]["scale"], } ) output = { "sample_id": args.sample_id, "paths": { k: { "base": str(v.base), "scene": str(v.scene), "images": [str(x) for x in v.images], "text": str(v.text) if v.text else None, "depth": str(v.depth) if v.depth else None, "camera": str(v.camera) if v.camera else None, "generated_meta": str(v.generated_meta) if v.generated_meta else None, } for k, v in all_assets.items() }, "runtime": { "blender_bin": args.blender_bin, "clip_model_path": args.clip_model_path, "clip_device": device, }, "rules": { "asset_loader": "auto-detect scene.blend/scene.glb/scene.gltf and selected images", "auto_scene_meta": bool(args.auto_scene_meta), "scene_meta_dir": str(scene_meta_dir), "iou_b_frames": args.geometry_frame_mode, "alignment": args.alignment, "ground_policy": args.ground_policy, "alignment_transform": "saved per model before IoU under alignment_dir", "iou_b_object_matching": "Hungarian matching on object AABB IoU; penalty denominator=max(gt_count,pred_count)", "selected_image_metrics_skipped": bool(args.skip_selected_image_metrics), "pl_definition": "MSE on user-selected image frames only", "n_clip_definition": "VIGA-style mean(1 - CLIPSim(pred_selected_image, gt_selected_image))", }, "alignments": alignments, "iou_b": ious, "pl_nclip": pl_nclip, "summary": summary, "rankings": { "scene_aabb_desc": sorted(summary, key=lambda x: x["scene_aabb_iou_mean"], reverse=True), "scene_obb_desc": sorted(summary, key=lambda x: x["scene_obb_iou_mean"], reverse=True), "object_aabb_pen_desc": sorted(summary, key=lambda x: x["object_aabb_iou_penalized_mean"], reverse=True), "object_obb_pen_desc": sorted(summary, key=lambda x: x["object_obb_iou_penalized_mean"], reverse=True), "pl_score_desc": sorted(summary, key=lambda x: x["pl_score_100"], reverse=True), "nclip_score_desc": sorted(summary, key=lambda x: x["n_clip_score_100"], reverse=True), }, } out_json.write_text(json.dumps(output, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print(json.dumps(output, indent=2, ensure_ascii=False)) print(f"SAVED {out_json}") if __name__ == "__main__": main()