from __future__ import annotations import json import os import subprocess import time from collections import defaultdict from pathlib import Path from statistics import median from typing import Any from packages.asset_registry.admission import ( canonical_category, classify_and_deduplicate, content_hash, infer_asset_kind, normalize_category, ) from packages.asset_registry.basisu import normalize_basisu_glb from packages.asset_registry.embeddings import EmbeddingProvider from packages.asset_registry.index import ( build_faiss_index, build_sqlite_index, write_index_manifest, ) from packages.asset_registry.models import ( AssetCatalog, AssetKind, AssetRecord, DimensionSource, GeometryMetadata, JointSummary, RuntimeCompatibility, ) from packages.asset_registry.proxy_sdf import repair_proxy_sdf DEFAULT_DIMENSIONS_M: dict[str, tuple[float, float, float]] = { "bottle": (0.08, 0.08, 0.25), "chair": (0.55, 0.55, 0.9), "desk": (1.2, 0.7, 0.75), "door": (0.9, 0.1, 2.05), "sofa": (2.0, 0.9, 0.85), "stair": (1.2, 3.0, 1.8), "table": (1.2, 0.75, 0.75), "trash can": (0.35, 0.35, 0.65), "object": (0.5, 0.5, 0.5), } def _usd_metadata(path: Path) -> dict[str, Any] | None: if path.suffix.casefold() not in {".usd", ".usda", ".usdc", ".usdz"}: return None try: from pxr import Usd, UsdGeom, UsdPhysics # type: ignore[import-not-found] except ImportError: return None stage = Usd.Stage.Open(str(path)) if stage is None: return None default_prim = stage.GetDefaultPrim() target = default_prim if default_prim else stage.GetPseudoRoot() bbox = UsdGeom.BBoxCache(Usd.TimeCode.Default(), [UsdGeom.Tokens.default_]).ComputeWorldBound( target ) aligned = bbox.ComputeAlignedBox() minimum = tuple(float(value) for value in aligned.GetMin()) maximum = tuple(float(value) for value in aligned.GetMax()) meters_per_unit = float(UsdGeom.GetStageMetersPerUnit(stage)) minimum_m = tuple(value * meters_per_unit for value in minimum) maximum_m = tuple(value * meters_per_unit for value in maximum) joints: list[tuple[str, str]] = [] articulation = False collision = False for prim in stage.Traverse(): if prim.HasAPI(UsdPhysics.ArticulationRootAPI): articulation = True if prim.HasAPI(UsdPhysics.CollisionAPI): collision = True if prim.IsA(UsdPhysics.Joint): joints.append((prim.GetName(), prim.GetTypeName())) return { "bbox_min_m": minimum_m, "bbox_max_m": maximum_m, "dimensions_m": tuple(high - low for low, high in zip(minimum_m, maximum_m, strict=True)), "meters_per_unit": meters_per_unit, "up_axis": str(UsdGeom.GetStageUpAxis(stage)).upper(), "default_prim": default_prim.GetPath().pathString if default_prim else None, "articulation": articulation, "collision": collision, "joints": joints, } def _mesh_metadata(path: Path) -> dict[str, Any] | None: if path.suffix.casefold() not in {".glb", ".gltf", ".obj", ".fbx"}: return None try: import numpy as np # type: ignore[import-not-found] import trimesh # type: ignore[import-not-found] except ImportError: return None loaded = trimesh.load(str(path), force="scene") bounds = np.asarray(loaded.bounds, dtype=float) if bounds.shape != (2, 3) or not np.isfinite(bounds).all(): return None minimum = tuple(float(value) for value in bounds[0]) maximum = tuple(float(value) for value in bounds[1]) if path.suffix.casefold() in {".glb", ".gltf"}: # glTF is Y-up. AssetRecord geometry uses the Z-up runtime convention. minimum = (minimum[0], minimum[2], minimum[1]) maximum = (maximum[0], maximum[2], maximum[1]) up_axis = "Y" else: up_axis = "Z" return { "bbox_min_m": minimum, "bbox_max_m": maximum, "dimensions_m": tuple( high - low for low, high in zip(minimum, maximum, strict=True) ), "meters_per_unit": 1.0, "up_axis": up_axis, "default_prim": None, "articulation": False, "collision": False, "joints": [], } def _default_dimensions(category: str) -> tuple[float, float, float]: normalized = normalize_category(category) for key, dimensions in DEFAULT_DIMENSIONS_M.items(): if key in normalized: return dimensions return DEFAULT_DIMENSIONS_M["object"] def _load_measurement_cache(path: Path | None) -> dict[str, dict[str, Any]]: if path is None or not path.is_file(): return {} payload = json.loads(path.read_text(encoding="utf-8")) if payload.get("schema_version") != "1.0": return {} return { str(key): value for key, value in payload.get("measurements", {}).items() if isinstance(value, dict) } def _write_measurement_cache(path: Path, records: list[AssetRecord]) -> None: measurements = {} for record in records: if record.content_hash is None or record.dimension_source not in { DimensionSource.MEASURED, DimensionSource.UPSTREAM, }: continue measurements[record.content_hash] = { "dimensions_m": record.dimensions_m, "dimension_source": record.dimension_source.value, "dimension_confidence": record.dimension_confidence, "geometry_metadata": ( record.geometry_metadata.model_dump(mode="json") if record.geometry_metadata else None ), "runtime_measurement": ( { "canonical_usd_path": record.runtime_compatibility.canonical_usd_path, "articulation": record.runtime_compatibility.articulation, "joint_summary": record.runtime_compatibility.joint_summary.model_dump( mode="json" ), "has_collision": record.runtime_compatibility.has_collision, } if record.runtime_compatibility else None ), } path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text( json.dumps( {"schema_version": "1.0", "measurements": measurements}, separators=(",", ":"), ), encoding="utf-8", ) temporary.replace(path) def measure_records( records: list[AssetRecord], *, cache_path: Path | None = None, asset_ids: frozenset[str] = frozenset(), ) -> list[AssetRecord]: measured: list[AssetRecord] = [] cache = _load_measurement_cache(cache_path) category_values: dict[str, list[tuple[float, float, float]]] = defaultdict(list) pending: list[int] = [] for record in records: path = Path(record.usd_path) fingerprint = record.content_hash or content_hash(record) cached = cache.get(fingerprint) selected = not asset_ids or record.asset_id in asset_ids metadata = ( (_usd_metadata(path) or _mesh_metadata(path)) if selected and cached is None and path.is_file() else None ) normalized = canonical_category(record) kind = infer_asset_kind(record) dimensions = record.dimensions_m source = record.dimension_source confidence = record.dimension_confidence geometry = record.geometry_metadata runtime = record.runtime_compatibility if cached is not None: dimensions_value = cached.get("dimensions_m") dimensions = ( ( float(dimensions_value[0]), float(dimensions_value[1]), float(dimensions_value[2]), ) if dimensions_value is not None else None ) source = DimensionSource(cached["dimension_source"]) confidence = cached.get("dimension_confidence") geometry = ( GeometryMetadata.model_validate(cached["geometry_metadata"]) if cached.get("geometry_metadata") else None ) runtime_measurement = cached.get("runtime_measurement") if runtime_measurement: runtime = (runtime or RuntimeCompatibility()).model_copy( update={ "canonical_usd_path": runtime_measurement["canonical_usd_path"], "articulation": runtime_measurement["articulation"], "joint_summary": JointSummary.model_validate( runtime_measurement["joint_summary"] ), "has_collision": runtime_measurement["has_collision"], } ) elif metadata is not None and all(value > 1e-6 for value in metadata["dimensions_m"]): raw_dimensions = metadata["dimensions_m"] dimensions = (raw_dimensions[0], raw_dimensions[1], raw_dimensions[2]) source = DimensionSource.MEASURED confidence = 1.0 geometry = GeometryMetadata( bbox_min_m=metadata["bbox_min_m"], bbox_max_m=metadata["bbox_max_m"], footprint_m=(dimensions[0], dimensions[1]), ground_offset_m=-metadata["bbox_min_m"][2], meters_per_unit=metadata["meters_per_unit"], up_axis=metadata["up_axis"], ) runtime = (runtime or RuntimeCompatibility()).model_copy( update={ "canonical_usd_path": str(path.resolve()), "articulation": metadata["articulation"], "has_collision": metadata["collision"], "joint_summary": JointSummary( joint_count=len(metadata["joints"]), joint_names=[item[0] for item in metadata["joints"]], joint_types=[item[1] for item in metadata["joints"]], ), } ) elif dimensions is not None: source = source or DimensionSource.UPSTREAM confidence = confidence if confidence is not None else 0.9 updated = record.model_copy( update={ "schema_version": "1.1", "asset_kind": kind, "normalized_category": normalized, "dimensions_m": dimensions, "dimension_source": source, "dimension_confidence": confidence, "geometry_metadata": geometry, "runtime_compatibility": runtime, "content_hash": fingerprint, } ) measured.append(updated) if dimensions is None: pending.append(len(measured) - 1) elif confidence is not None and confidence >= 0.9: category_values[normalized].append(dimensions) medians: dict[str, tuple[float, float, float]] = { category: ( median(values[0] for values in category_values[category]), median(values[1] for values in category_values[category]), median(values[2] for values in category_values[category]), ) for category, values in category_values.items() } for index in pending: record = measured[index] category = record.normalized_category or "object" dimensions = medians.get(category) if dimensions is not None: source = DimensionSource.CATEGORY_MEDIAN confidence = 0.4 else: dimensions = _default_dimensions(category) source = DimensionSource.DEFAULT confidence = 0.2 measured[index] = record.model_copy( update={ "dimensions_m": dimensions, "dimension_source": source, "dimension_confidence": confidence, } ) if cache_path is not None: _write_measurement_cache(cache_path, measured) return measured def write_catalog(records: list[AssetRecord], path: Path, *, source: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text( AssetCatalog(source=source, assets=records).model_dump_json(indent=2), encoding="utf-8", ) temporary.replace(path) def _blender_compatible_source(source: Path, proxy_root: Path, digest: str) -> Path: """Decode BasisU textures before Blender import without discarding materials.""" if source.suffix.casefold() != ".glb" or b"KHR_texture_basisu" not in source.read_bytes(): return source normalized_dir = proxy_root / ".normalized" / digest normalized = normalized_dir / "asset.gltf" if normalized.is_file(): return normalized ktx_value = os.environ.get("RHG_KTX_TOOL", "").strip() if not ktx_value: raise RuntimeError("RHG_KTX_TOOL is required to preserve BasisU proxy textures") return normalize_basisu_glb(source, normalized_dir, ktx_tool=Path(ktx_value)) def prepare_proxies( records: list[AssetRecord], output_dir: Path, *, blender: str, batch_size: int = 64, query_terms: tuple[str, ...] = (), asset_ids: frozenset[str] = frozenset(), limit: int | None = None, ) -> list[AssetRecord]: proxy_root = output_dir / "proxy" proxy_root.mkdir(parents=True, exist_ok=True) jobs: list[dict[str, Any]] = [] record_jobs: dict[str, tuple[Path, Path]] = {} for record in records: if asset_ids and record.asset_id not in asset_ids: continue if infer_asset_kind(record) != AssetKind.OBJECT: continue path_text = record.usd_path.casefold() if record.source == "ArtVIP" and "/resource/" in path_text: continue if record.source == "InteriorAgent": continue searchable = normalize_category( f"{record.asset_id} {record.display_name} {record.category} {' '.join(record.tags)}" ) if query_terms and not any(normalize_category(term) in searchable for term in query_terms): continue if limit is not None and len(record_jobs) >= limit: break source = Path(record.usd_path) if not source.is_file() or source.suffix.casefold() not in { ".usd", ".usda", ".usdc", ".usdz", ".glb", ".gltf", ".obj", ".fbx", }: continue digest = (record.content_hash or content_hash(record)).split(":", 1)[-1] safe_id = "".join( char if char.isalnum() or char in "-_" else "_" for char in record.asset_id ) destination = proxy_root / digest[:2] / f"{safe_id}.glb" sdf = destination.with_suffix(".sdf") record_jobs[record.asset_id] = (destination, sdf) compatible_source = _blender_compatible_source(source, proxy_root, digest) dimensions = record.dimensions_m or (0.5, 0.5, 0.5) geometry = record.geometry_metadata bbox_min = ( geometry.bbox_min_m if geometry is not None and geometry.bbox_min_m is not None else (-dimensions[0] / 2, -dimensions[1] / 2, 0.0) ) bbox_max = ( geometry.bbox_max_m if geometry is not None and geometry.bbox_max_m is not None else (dimensions[0] / 2, dimensions[1] / 2, dimensions[2]) ) if destination.is_file() and sdf.is_file(): repair_proxy_sdf(sdf, bbox_min, bbox_max) continue jobs.append( { "asset_id": record.asset_id, "source": str(compatible_source.resolve()), "gltf": str(destination.resolve()), "sdf": str(sdf.resolve()), "bbox_min_m": bbox_min, "bbox_max_m": bbox_max, "articulation": bool( record.runtime_compatibility and record.runtime_compatibility.articulation ), } ) worker = Path(__file__).resolve().parents[2] / "scripts" / "blender_prepare_asset_proxies.py" for offset in range(0, len(jobs), batch_size): batch = jobs[offset : offset + batch_size] manifest = proxy_root / f"jobs-{offset // batch_size:05d}.json" manifest.write_text(json.dumps(batch, indent=2) + "\n", encoding="utf-8") result = subprocess.run( [blender, "--background", "--python", str(worker), "--", str(manifest)], check=False, capture_output=True, text=True, ) if result.returncode: details = (result.stdout + result.stderr)[-4000:] raise RuntimeError(f"Blender proxy batch failed: {details}") missing_outputs = [ path for job in batch for path in (Path(job["gltf"]), Path(job["sdf"])) if not path.is_file() ] if missing_outputs: details = (result.stdout + result.stderr)[-4000:] raise RuntimeError( f"Blender reported success but proxy outputs are missing: " f"{missing_outputs}; {details}" ) updated = [] for record in records: paths = record_jobs.get(record.asset_id) if paths is None or not all(path.is_file() for path in paths): updated.append(record) continue runtime = record.runtime_compatibility or RuntimeCompatibility() compatible = sorted(set([*runtime.compatible_backends, "scenesmith", "isaac-sim"])) updated.append( record.model_copy( update={ "runtime_compatibility": runtime.model_copy( update={ "canonical_usd_path": runtime.canonical_usd_path or ( str(Path(record.usd_path).resolve()) if Path(record.usd_path).suffix.casefold() in {".usd", ".usda", ".usdc", ".usdz"} else None ), "proxy_gltf_path": str(paths[0].resolve()), "proxy_sdf_path": str(paths[1].resolve()), "compatible_backends": compatible, } ) } ) ) return updated def build_indexes( records: list[AssetRecord], output_dir: Path, embedding_provider: EmbeddingProvider ) -> Path: started = time.perf_counter() records = classify_and_deduplicate(records) write_catalog(records, output_dir / "enriched_catalog.json", source="RoboHouseGen indexed") active = build_sqlite_index(records, output_dir / "asset_index.sqlite3") build_faiss_index( active, output_dir / "asset_vectors.faiss", embedding_provider, sqlite_path=output_dir / "asset_index.sqlite3", ) return write_index_manifest( output_dir, records=records, active_records=active, embedding_provider=embedding_provider, build_duration_s=time.perf_counter() - started, )