Datasets:
Download code/robohome/src/engine/source/packages/asset_registry/release.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 75.1 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/asset_registry/release.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome/code/robohome/src/engine/source/packages/asset_registry/release.py
-
curl -L -o release.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/main/code/robohome/src/engine/source/packages/asset_registry/release.py
75.1 kB
from __future__ import annotations
import ast
import csv
import hashlib
import json
import math
import os
import re
import sqlite3
import struct
import threading
import time
import traceback
import urllib.parse
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from collections.abc import Iterable, Sequence
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal, cast
from PIL import Image, ImageDraw
from shapely.geometry import MultiPoint, Polygon, box # type: ignore[import-untyped]
from shapely.ops import unary_union # type: ignore[import-untyped]
from packages.asset_registry.admission import normalize_category
from packages.asset_registry.descriptors import (
AssetDescriptor,
AssetQuality,
OperationalClearance,
OrientedBoundingBox,
PbrChannels,
Point2,
)
from packages.asset_registry.models import AdmissionStatus, AssetCatalog, AssetKind, AssetRecord
from packages.core.files import atomic_write_text
# USD's resolver and stage caches are not safe to drive from several Python
# threads in the same process. GLB/GLTF inspection remains parallel, while
# USD loading is serialized through this narrow gate.
_USD_INSPECTION_LOCK = threading.Lock()
SUPPORTED_GEOMETRY_EXTENSIONS = {
".glb",
".gltf",
".obj",
".fbx",
".usd",
".usda",
".usdc",
".usdz",
".sdf",
}
NON_GEOMETRY_KINDS = {AssetKind.MATERIAL, AssetKind.LIGHTING}
STYLE_WORDS = {
"art deco",
"bohemian",
"classic",
"contemporary",
"industrial",
"japanese",
"mid century",
"minimal",
"modern",
"rustic",
"scandinavian",
"traditional",
"vintage",
}
COLOR_WORDS = {
"beige",
"black",
"blue",
"brass",
"bronze",
"brown",
"copper",
"cream",
"gold",
"gray",
"green",
"grey",
"orange",
"pink",
"purple",
"red",
"silver",
"teal",
"white",
"yellow",
}
MATERIAL_WORDS = {
"bamboo",
"ceramic",
"concrete",
"fabric",
"glass",
"leather",
"marble",
"metal",
"plastic",
"rattan",
"steel",
"stone",
"wood",
"wooden",
}
CATEGORY_SYNONYMS: dict[str, tuple[str, ...]] = {
"armchair": ("accent chair", "easy chair", "reading chair"),
"bookcase": ("bookshelf", "book shelf", "low bookcase"),
"cabinet": ("cupboard", "storage cabinet", "drawer cabinet"),
"chair": ("seat", "work chair", "office chair"),
"chest of drawers": ("drawer cabinet", "dresser", "storage cabinet"),
"desk": ("work desk", "worktable", "writing desk"),
"floor lamp": ("standing lamp", "floor light"),
"lamp": ("light", "lighting fixture"),
"picture": ("wall art", "artwork", "framed art"),
"plant": ("indoor plant", "potted plant", "greenery"),
"potted plant": ("indoor plant", "plant", "greenery"),
"shelf": ("shelving", "storage shelf"),
"side table": ("end table", "occasional table", "small table"),
"sofa": ("couch", "settee"),
"table": ("worktable", "dining table", "desk"),
"vase": ("flower vase", "decorative vessel"),
}
@dataclass(slots=True)
class HssdSemantic:
category: str = ""
articulated: bool = False
pickable: bool = False
name: str = ""
@dataclass(frozen=True, slots=True)
class FrontAxisOverride:
asset_id: str
asset_sha256: str
front_axis: Literal["+X", "-X", "+Y", "-Y"]
source: Literal["multiview_verified", "manual_override"]
confidence: float
evidence: tuple[str, ...]
note: str = ""
@dataclass(slots=True)
class ReleaseMetadata:
hssd_root: Path | None = None
hssd_semantics: dict[str, HssdSemantic] = field(default_factory=dict)
affordances_by_category: dict[str, list[str]] = field(default_factory=dict)
front_axis_overrides: dict[str, FrontAxisOverride] = field(default_factory=dict)
_PROCESS_OUTPUT_ROOT: Path | None = None
_PROCESS_METADATA: ReleaseMetadata | None = None
_PROCESS_RENDER_VIEWS = True
@dataclass(slots=True)
class GeometryEvidence:
vertices: Any
collision_vertices: Any | None
triangle_count: int
material_count: int
pbr_channels: PbrChannels
material_names: list[str]
texture_dependencies: list[str]
missing_dependencies: list[str]
format_extensions: list[str]
loader_compatibility: dict[str, str]
native_up: tuple[float, float, float]
native_front: tuple[float, float, float]
native_to_meter_scale: float
canonical_transform: tuple[float, ...]
source_bbox_min_m: tuple[float, float, float]
source_bbox_max_m: tuple[float, float, float]
articulated: bool = False
movable_parts: list[dict[str, Any]] = field(default_factory=list)
explicit_collision: bool = False
inferred: list[str] = field(default_factory=list)
class _MissingAssetDependencies(Exception):
def __init__(self, paths: Sequence[str]) -> None:
self.paths = list(paths)
super().__init__("|".join(self.paths))
def _sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _sha256_json(value: Any) -> str:
return hashlib.sha256(
json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
).hexdigest()
def _words(value: str) -> list[str]:
return re.findall(r"[a-z0-9]+", value.casefold().replace("_", " ").replace("-", " "))
def _clean_category(value: str) -> str:
normalized = normalize_category(value).strip()
aliases = {
"bin": "trash can",
"bookshelf": "bookcase",
"couch": "sofa",
"drawer": "chest of drawers",
"dresser": "chest of drawers",
"filing cabinet": "cabinet",
"fridge": "refrigerator",
"office chair": "chair",
"painting": "picture",
"picture frame": "picture",
"seat": "chair",
"standing lamp": "floor lamp",
"trashcan": "trash can",
"tv": "television",
"wardrobe": "wardrobe",
}
return aliases.get(normalized, normalized or "object")
_CATEGORY_HINTS: tuple[tuple[tuple[str, ...], str], ...] = (
(("floor lamp", "standing lamp"), "floor lamp"),
(("ceiling lamp", "ceiling light", "pendant light"), "ceiling lamp"),
(("desk lamp", "table lamp"), "table lamp"),
(("office chair", "desk chair", "task chair", "work chair"), "chair"),
(("armchair", "accent chair", "easy chair", "reading chair"), "armchair"),
(("side table", "bedside table", "nightstand", "end table"), "side table"),
(("chest of drawers", "drawer chest", "dresser"), "chest of drawers"),
(("bookcase", "bookshelf", "book shelf"), "bookcase"),
(("work desk", "writing desk", "computer desk", "desk"), "desk"),
(("dining table", "coffee table", "work table", "table"), "table"),
(("storage cabinet", "shoe cabinet", "sideboard", "cupboard", "cabinet"), "cabinet"),
(("wardrobe", "armoire"), "wardrobe"),
(("floor plant", "potted plant", "houseplant", "plant"), "potted plant"),
(("wall art", "painting", "picture", "poster", "artwork"), "picture"),
(("trash can", "trashcan", "waste bin", "pedal bin", "bin"), "trash can"),
(("sofa", "couch", "settee"), "sofa"),
(("stool",), "stool"),
(("bench",), "bench"),
(("shelf",), "shelf"),
(("chair",), "chair"),
(("lamp", "lightbox"), "lamp"),
(("bed",), "bed"),
(("basket",), "basket"),
(("carton", "cardboard box", "storage box"), "box"),
(("clock",), "clock"),
(("monitor", "display"), "monitor"),
(("vase",), "vase"),
(("mug", "cup"), "mug"),
(("bottle",), "bottle"),
(("medical", "surgical", "anesthesia", "incubator", "ultrasound"), "medical equipment"),
)
def _record_category(record: AssetRecord, semantic: HssdSemantic | None) -> str:
display = " ".join(_words(record.display_name))
# Prefer explicit object names for well-defined refinements when an
# upstream semantic class is broad (for example HSSD labels some open
# bookcases as cabinets, which would incorrectly invent door clearance).
refinements: tuple[tuple[tuple[str, ...], str], ...] = (
(("floor lamp", "standing lamp"), "floor lamp"),
(("bookcase", "bookshelf", "book shelf"), "bookcase"),
(("side table", "bedside table", "end table", "nightstand"), "side table"),
(("chest of drawers", "drawer chest", "dresser"), "chest of drawers"),
(("armchair", "accent chair", "easy chair", "reading chair"), "armchair"),
(("potted plant", "indoor plant"), "potted plant"),
(("wall art", "painting", "picture"), "picture"),
(("wardrobe", "armoire"), "wardrobe"),
)
for phrases, category in refinements:
if any(phrase in display for phrase in phrases):
return category
if semantic and semantic.category:
return _clean_category(semantic.category)
candidate = _clean_category(record.normalized_category or "")
candidate_words = _words(candidate)
# Earlier indexes sometimes stored the complete tokenized search document
# in normalized_category. It is useful for retrieval, but is not a class.
if candidate not in {"", "object"} and len(candidate_words) <= 5:
return candidate
text = " ".join(
_words(
" ".join(
[
record.display_name,
record.description,
record.category,
Path(record.usd_path).stem,
]
)
)
)
for phrases, category in _CATEGORY_HINTS:
if any(phrase in text for phrase in phrases):
return category
source_category = _clean_category(record.category.split("/")[-1])
return source_category if len(_words(source_category)) <= 4 else "object"
def _bool_cell(value: str) -> bool:
return value.strip().casefold() in {"1", "true", "yes", "y"}
def load_front_axis_overrides(path: Path | None) -> dict[str, FrontAxisOverride]:
if path is None:
return {}
payload = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(payload, dict) or payload.get("schema_version") != "1.0":
raise ValueError("front-axis override file must use schema_version 1.0")
entries = payload.get("overrides")
if not isinstance(entries, list):
raise ValueError("front-axis override file requires an overrides list")
output: dict[str, FrontAxisOverride] = {}
allowed_axes = {"+X", "-X", "+Y", "-Y"}
allowed_sources = {"multiview_verified", "manual_override"}
for index, raw in enumerate(entries):
if not isinstance(raw, dict):
raise ValueError(f"front-axis override {index} must be an object")
asset_id = str(raw.get("asset_id") or "").strip()
asset_sha256 = str(raw.get("asset_sha256") or "").casefold()
front_axis = str(raw.get("front_axis") or "")
source = str(raw.get("source") or "")
confidence = float(raw.get("confidence", 0.0))
evidence_raw = raw.get("evidence")
evidence = (
tuple(str(item).strip() for item in evidence_raw if str(item).strip())
if isinstance(evidence_raw, list)
else ()
)
if not asset_id:
raise ValueError(f"front-axis override {index} has no asset_id")
if asset_id in output:
raise ValueError(f"duplicate front-axis override: {asset_id}")
if not re.fullmatch(r"[0-9a-f]{64}", asset_sha256):
raise ValueError(f"invalid front-axis override sha256: {asset_id}")
if front_axis not in allowed_axes:
raise ValueError(f"invalid front-axis override direction: {asset_id}")
if source not in allowed_sources:
raise ValueError(f"invalid front-axis override source: {asset_id}")
if not 0.9 <= confidence <= 1.0:
raise ValueError(f"verified front-axis confidence must be in [0.9, 1]: {asset_id}")
if not evidence:
raise ValueError(f"verified front-axis override requires evidence: {asset_id}")
output[asset_id] = FrontAxisOverride(
asset_id=asset_id,
asset_sha256=asset_sha256,
front_axis=cast(Literal["+X", "-X", "+Y", "-Y"], front_axis),
source=cast(Literal["multiview_verified", "manual_override"], source),
confidence=confidence,
evidence=evidence,
note=str(raw.get("note") or "").strip(),
)
return output
def load_release_metadata(
hssd_root: Path | None,
front_axis_overrides_path: Path | None = None,
) -> ReleaseMetadata:
metadata = ReleaseMetadata(
hssd_root=hssd_root,
front_axis_overrides=load_front_axis_overrides(front_axis_overrides_path),
)
if hssd_root is None or not hssd_root.is_dir():
return metadata
semantics_path = hssd_root / "metadata" / "hssd_obj_semantics_condensed.csv"
if semantics_path.is_file():
with semantics_path.open("r", encoding="utf-8-sig", newline="") as handle:
rows = csv.reader(handle)
next(rows, None)
for row in rows:
if len(row) < 4 or not row[0].strip():
continue
metadata.hssd_semantics[row[0].strip()] = HssdSemantic(
category=_clean_category(row[3]),
articulated=_bool_cell(row[1]),
pickable=_bool_cell(row[2]),
)
objects_path = hssd_root / "metadata" / "objects.json"
if objects_path.is_file():
payload = json.loads(objects_path.read_text(encoding="utf-8"))
for asset_id, value in payload.items():
item = metadata.hssd_semantics.setdefault(str(asset_id), HssdSemantic())
item.name = str(value.get("name") or "")
affordance_path = hssd_root / "metadata" / "affordance_objects.csv"
if affordance_path.is_file():
with affordance_path.open("r", encoding="utf-8-sig", newline="") as handle:
for row in csv.reader(handle):
if len(row) < 3:
continue
try:
categories = ast.literal_eval(row[-1])
except (ValueError, SyntaxError):
continue
if not isinstance(categories, list):
continue
action = row[0].strip()
for category in categories:
key = _clean_category(str(category))
if action and action not in metadata.affordances_by_category.setdefault(
key, []
):
metadata.affordances_by_category[key].append(action)
return metadata
def _hssd_id(record: AssetRecord, path: Path) -> str | None:
if record.source == "HSSD" or record.asset_id.startswith("hssd:"):
stem = path.stem
for suffix in (".collider", ".filteredSupportSurface", ".supportSurface"):
stem = stem.removesuffix(suffix)
return stem
return None
def _gltf_document(path: Path) -> dict[str, Any] | None:
if path.suffix.casefold() == ".gltf":
document = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(document, dict):
raise ValueError("gltf_root_is_not_an_object")
return cast(dict[str, Any], document)
if path.suffix.casefold() != ".glb":
return None
with path.open("rb") as handle:
header = handle.read(12)
if len(header) != 12:
raise ValueError("truncated_glb_header")
magic, version, total_length = struct.unpack("<4sII", header)
if magic != b"glTF" or version != 2 or total_length > path.stat().st_size:
raise ValueError("invalid_glb_header")
while handle.tell() + 8 <= total_length:
length, chunk_type = struct.unpack("<II", handle.read(8))
payload = handle.read(length)
if len(payload) != length:
raise ValueError("truncated_glb_chunk")
if chunk_type == 0x4E4F534A:
document = json.loads(payload.rstrip(b"\x00 \t\r\n").decode("utf-8"))
if not isinstance(document, dict):
raise ValueError("glb_json_root_is_not_an_object")
return cast(dict[str, Any], document)
raise ValueError("glb_has_no_json_chunk")
def _gltf_material_evidence(
path: Path, document: dict[str, Any]
) -> tuple[PbrChannels, int, list[str], list[str], list[str], list[str]]:
dependencies: list[str] = []
missing: list[str] = []
for section in ("buffers", "images"):
for item in document.get(section) or []:
uri = str(item.get("uri") or "")
if not uri or uri.startswith("data:"):
continue
candidate = (path.parent / urllib.parse.unquote(uri)).resolve()
dependencies.append(str(candidate))
if not candidate.is_file():
missing.append(str(candidate))
materials = document.get("materials") or []
names = [str(item.get("name") or "") for item in materials if item.get("name")]
base = normal = roughness = metallic = occlusion = emissive = False
for material in materials:
pbr = material.get("pbrMetallicRoughness") or {}
base = base or bool(pbr.get("baseColorTexture") or pbr.get("baseColorFactor"))
roughness = roughness or bool(
pbr.get("metallicRoughnessTexture") or "roughnessFactor" in pbr
)
metallic = metallic or bool(pbr.get("metallicRoughnessTexture") or "metallicFactor" in pbr)
normal = normal or bool(material.get("normalTexture"))
occlusion = occlusion or bool(material.get("occlusionTexture"))
emissive = emissive or bool(
material.get("emissiveTexture") or material.get("emissiveFactor")
)
if materials and not base:
base = True
return (
PbrChannels(
base_color=base,
normal=normal,
roughness=roughness,
metallic=metallic,
occlusion=occlusion,
emissive=emissive,
),
len(materials),
names,
dependencies,
missing,
sorted(set(str(value) for value in document.get("extensionsRequired") or [])),
)
def _orientation_from_config(
path: Path, default_up: Sequence[float], default_front: Sequence[float]
) -> tuple[tuple[float, float, float], tuple[float, float, float], bool]:
stem = path.stem.split(".", 1)[0]
config = path.with_name(f"{stem}.object_config.json")
if config.is_file():
payload = json.loads(config.read_text(encoding="utf-8"))
up = payload.get("up")
front = payload.get("front")
if isinstance(up, list) and len(up) == 3 and isinstance(front, list) and len(front) == 3:
return (
(float(up[0]), float(up[1]), float(up[2])),
(float(front[0]), float(front[1]), float(front[2])),
True,
)
return (
(float(default_up[0]), float(default_up[1]), float(default_up[2])),
(float(default_front[0]), float(default_front[1]), float(default_front[2])),
False,
)
def _canonical_rotation(up: Sequence[float], front: Sequence[float]) -> Any:
import numpy as np
source_up = np.asarray(up, dtype=float)
source_front = np.asarray(front, dtype=float)
if not np.isfinite(source_up).all() or not np.isfinite(source_front).all():
raise ValueError("non_finite_orientation")
source_up /= np.linalg.norm(source_up)
source_front -= source_up * float(np.dot(source_front, source_up))
if np.linalg.norm(source_front) < 1.0e-8:
raise ValueError("parallel_up_and_front")
source_front /= np.linalg.norm(source_front)
source_right = np.cross(source_front, source_up)
source_right /= np.linalg.norm(source_right)
target_right = np.array([1.0, 0.0, 0.0])
target_up = np.array([0.0, 0.0, 1.0])
target_front = np.array([0.0, 1.0, 0.0])
source_basis = np.column_stack([source_right, source_up, source_front])
target_basis = np.column_stack([target_right, target_up, target_front])
return target_basis @ np.linalg.inv(source_basis)
def _transform_matrix(rotation: Any, scale: float) -> tuple[float, ...]:
import numpy as np
matrix = np.eye(4, dtype=float)
matrix[:3, :3] = rotation * scale
return tuple(float(value) for value in matrix.reshape(-1))
_CANONICAL_FRONT_VECTORS: dict[str, tuple[float, float, float]] = {
"+X": (1.0, 0.0, 0.0),
"-X": (-1.0, 0.0, 0.0),
"+Y": (0.0, 1.0, 0.0),
"-Y": (0.0, -1.0, 0.0),
}
def _native_front_for_canonical_axis(
canonical_transform: Sequence[float], front_axis: str
) -> tuple[float, float, float]:
import numpy as np
transform = np.asarray(canonical_transform, dtype=float).reshape(4, 4)
canonical = np.asarray(_CANONICAL_FRONT_VECTORS[front_axis], dtype=float)
native = np.linalg.solve(transform[:3, :3], canonical)
length = float(np.linalg.norm(native))
if not math.isfinite(length) or length <= 1.0e-9:
raise ValueError("front-axis override produced an invalid native direction")
native /= length
return (
round(float(native[0]), 9),
round(float(native[1]), 9),
round(float(native[2]), 9),
)
def certify_descriptor_front_axis(
descriptor: AssetDescriptor,
override: FrontAxisOverride | None = None,
) -> AssetDescriptor:
"""Attach truthful semantic-front provenance without changing asset geometry."""
if descriptor.status != "ACTIVE":
return descriptor
if override is None and descriptor.front_axis_source != "unknown":
return descriptor
value = descriptor.model_dump(mode="json")
observed = set(descriptor.observed_fields)
inferred = set(descriptor.inferred_fields)
confidence = dict(descriptor.confidence)
if override is None:
from_source_metadata = "native_front_vector" in observed
value["front_axis_source"] = (
"source_metadata" if from_source_metadata else "dataset_convention"
)
value["front_axis_evidence"] = [
(
"source orientation metadata; semantic front not yet verified by material views"
if from_source_metadata
else "format default orientation; semantic front not yet verified by material views"
)
]
confidence["front_axis"] = 0.75 if from_source_metadata else 0.55
if from_source_metadata:
observed.add("front_axis")
inferred.discard("front_axis")
else:
inferred.add("front_axis")
observed.discard("front_axis")
else:
if descriptor.asset_id != override.asset_id:
raise ValueError("front-axis override asset_id mismatch")
if descriptor.sha256 != override.asset_sha256:
raise ValueError(
f"front-axis override sha256 mismatch for {descriptor.asset_id}: "
f"expected {override.asset_sha256}, observed {descriptor.sha256}"
)
evidence = list(override.evidence)
if override.note:
evidence.append(f"note:{override.note}")
value.update(
front_axis=override.front_axis,
front_axis_source=override.source,
front_axis_evidence=evidence,
native_front_vector=_native_front_for_canonical_axis(
descriptor.canonical_transform, override.front_axis
),
)
confidence["front_axis"] = override.confidence
confidence["native_front_vector"] = override.confidence
observed.add("front_axis")
inferred.discard("front_axis")
# The semantic native vector is derived by applying the inverse of the
# measured canonical transform to the verified canonical direction.
inferred.add("native_front_vector")
observed.discard("native_front_vector")
value["observed_fields"] = sorted(observed - inferred)
value["inferred_fields"] = sorted(inferred)
value["confidence"] = confidence
return AssetDescriptor.model_validate(value)
def _mesh_geometry(path: Path, record: AssetRecord) -> GeometryEvidence:
import numpy as np
import trimesh # type: ignore[import-not-found]
document = _gltf_document(path)
if document is not None:
pbr, material_count, names, dependencies, missing, format_extensions = (
_gltf_material_evidence(path, document)
)
else:
pbr = PbrChannels(base_color=True)
material_count, names, dependencies, missing = 1, [], [], []
format_extensions = []
loaded = trimesh.load(str(path), force="scene", process=False)
mesh = loaded.to_geometry() if isinstance(loaded, trimesh.Scene) else loaded
vertices = np.asarray(mesh.vertices, dtype=float)
faces = np.asarray(mesh.faces)
if vertices.ndim != 2 or vertices.shape[1] != 3 or len(vertices) < 3:
raise ValueError("no_geometry_vertices")
if faces.ndim != 2 or len(faces) < 1:
raise ValueError("no_geometry_faces")
if not np.isfinite(vertices).all():
raise ValueError("non_finite_geometry")
default_up = (0.0, 1.0, 0.0) if path.suffix.casefold() in {".glb", ".gltf"} else (0.0, 0.0, 1.0)
default_front = (0.0, 0.0, -1.0) if default_up[1] else (0.0, 1.0, 0.0)
native_up, native_front, observed_orientation = _orientation_from_config(
path, default_up, default_front
)
rotation = _canonical_rotation(native_up, native_front)
source_min = vertices.min(axis=0)
source_max = vertices.max(axis=0)
scale = 1.0
canonical = (rotation @ (vertices * scale).T).T
collision_path = path.with_name(f"{path.stem}.collider{path.suffix}")
collision_vertices = None
explicit_collision = False
if collision_path.is_file():
collision_loaded = trimesh.load(str(collision_path), force="scene", process=False)
collision_mesh = (
collision_loaded.to_geometry()
if isinstance(collision_loaded, trimesh.Scene)
else collision_loaded
)
collision_raw = np.asarray(collision_mesh.vertices, dtype=float)
if collision_raw.ndim == 2 and collision_raw.shape[1] == 3 and len(collision_raw) >= 3:
collision_vertices = (rotation @ (collision_raw * scale).T).T
explicit_collision = bool(np.isfinite(collision_vertices).all())
inferred = [] if observed_orientation else ["native_orientation"]
return GeometryEvidence(
vertices=canonical,
collision_vertices=collision_vertices,
triangle_count=int(len(faces)),
material_count=material_count,
pbr_channels=pbr,
material_names=names,
texture_dependencies=dependencies,
missing_dependencies=missing,
format_extensions=format_extensions,
loader_compatibility={
"trimesh": "verified",
"blender_gltf": (
"unsupported" if "KHR_texture_basisu" in format_extensions else "compatible"
),
"blender_gltf_basisu_repair": (
"compatible" if "KHR_texture_basisu" in format_extensions else "not_tested"
),
},
native_up=native_up,
native_front=native_front,
native_to_meter_scale=scale,
canonical_transform=_transform_matrix(rotation, scale),
source_bbox_min_m=(
float(source_min[0] * scale),
float(source_min[1] * scale),
float(source_min[2] * scale),
),
source_bbox_max_m=(
float(source_max[0] * scale),
float(source_max[1] * scale),
float(source_max[2] * scale),
),
explicit_collision=explicit_collision,
inferred=inferred,
)
def _asset_paths(value: Any) -> Iterable[str]:
try:
from pxr import Sdf # type: ignore[import-not-found]
except ImportError:
return []
if isinstance(value, Sdf.AssetPath):
# Prefer USD's layer-aware resolved path. Referenced material layers
# (notably ArtVIP's resource/material.usd) author paths relative to
# their own layer, not relative to the root model layer.
return [value.resolvedPath or value.path]
if isinstance(value, (list, tuple)):
output: list[str] = []
for item in value:
output.extend(_asset_paths(item))
return output
return []
def _usd_composition_dependencies(path: Path) -> tuple[list[str], list[str]]:
from pxr import UsdUtils
layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(path))
dependencies: list[str] = []
for layer in layers:
layer_path = str(getattr(layer, "realPath", "") or getattr(layer, "identifier", ""))
if layer_path and not layer_path.startswith("anon:"):
dependencies.append(layer_path)
dependencies.extend(str(asset) for asset in assets if str(asset))
missing = [str(asset) for asset in unresolved if str(asset)]
return sorted(set(dependencies)), sorted(set(missing))
def _usd_geometry(path: Path, _record: AssetRecord) -> GeometryEvidence:
import numpy as np
from pxr import Gf, Usd, UsdGeom, UsdPhysics
dependencies, missing = _usd_composition_dependencies(path)
if missing:
raise _MissingAssetDependencies(missing)
stage = Usd.Stage.Open(str(path))
if stage is None:
raise ValueError("usd_stage_open_failed")
meters_per_unit = float(UsdGeom.GetStageMetersPerUnit(stage))
if not math.isfinite(meters_per_unit) or meters_per_unit <= 0:
raise ValueError("invalid_usd_meters_per_unit")
up_axis = str(UsdGeom.GetStageUpAxis(stage)).upper()
default_up = (0.0, 0.0, 1.0) if up_axis == "Z" else (0.0, 1.0, 0.0)
default_front = (0.0, 1.0, 0.0) if up_axis == "Z" else (0.0, 0.0, -1.0)
native_up, native_front, observed_orientation = _orientation_from_config(
path, default_up, default_front
)
rotation = _canonical_rotation(native_up, native_front)
xforms = UsdGeom.XformCache(Usd.TimeCode.Default())
vertices: list[tuple[float, float, float]] = []
collision_vertices: list[tuple[float, float, float]] = []
triangle_count = 0
material_names: list[str] = []
joints: list[dict[str, Any]] = []
articulated = False
channels = Counter[str]()
for prim in stage.Traverse():
if prim.IsA(UsdGeom.Mesh):
points = UsdGeom.Mesh(prim).GetPointsAttr().Get() or []
matrix = xforms.GetLocalToWorldTransform(prim)
transformed = [matrix.Transform(Gf.Vec3d(*point)) for point in points]
tuples = [(float(point[0]), float(point[1]), float(point[2])) for point in transformed]
vertices.extend(tuples)
if prim.HasAPI(UsdPhysics.CollisionAPI):
collision_vertices.extend(tuples)
counts = UsdGeom.Mesh(prim).GetFaceVertexCountsAttr().Get() or []
triangle_count += sum(max(int(count) - 2, 0) for count in counts)
if prim.GetTypeName() == "Material":
material_names.append(prim.GetName())
if prim.HasAPI(UsdPhysics.ArticulationRootAPI):
articulated = True
if prim.IsA(UsdPhysics.Joint):
articulated = True
joints.append({"name": prim.GetName(), "type": prim.GetTypeName()})
for attribute in prim.GetAttributes():
name = attribute.GetName().casefold()
if "diffuse" in name or "basecolor" in name:
channels["base_color"] += 1
if "normal" in name:
channels["normal"] += 1
if "roughness" in name:
channels["roughness"] += 1
if "metallic" in name:
channels["metallic"] += 1
try:
value = attribute.Get()
except Exception:
continue
for asset_path in _asset_paths(value):
if not asset_path or asset_path.startswith(("http://", "https://")):
continue
candidate = (path.parent / asset_path).resolve()
dependencies.append(str(candidate))
if not candidate.is_file():
missing.append(str(candidate))
raw = np.asarray(vertices, dtype=float)
if raw.ndim != 2 or raw.shape[1] != 3 or len(raw) < 3 or triangle_count < 1:
raise ValueError("usd_has_no_triangle_geometry")
if not np.isfinite(raw).all():
raise ValueError("non_finite_geometry")
source_min = raw.min(axis=0) * meters_per_unit
source_max = raw.max(axis=0) * meters_per_unit
canonical = (rotation @ (raw * meters_per_unit).T).T
collision = None
if collision_vertices:
collision_raw = np.asarray(collision_vertices, dtype=float)
collision = (rotation @ (collision_raw * meters_per_unit).T).T
inferred = [] if observed_orientation else ["native_orientation"]
if collision is None:
inferred.append("collision_footprint_polygon_m")
return GeometryEvidence(
vertices=canonical,
collision_vertices=collision,
triangle_count=triangle_count,
material_count=len(material_names),
pbr_channels=PbrChannels(
base_color=bool(channels["base_color"] or material_names),
normal=bool(channels["normal"]),
roughness=bool(channels["roughness"]),
metallic=bool(channels["metallic"]),
),
material_names=material_names,
texture_dependencies=sorted(set(dependencies)),
missing_dependencies=sorted(set(missing)),
format_extensions=[],
loader_compatibility={"pxr_usd": "verified"},
native_up=native_up,
native_front=native_front,
native_to_meter_scale=meters_per_unit,
canonical_transform=_transform_matrix(rotation, meters_per_unit),
source_bbox_min_m=(
float(source_min[0]),
float(source_min[1]),
float(source_min[2]),
),
source_bbox_max_m=(
float(source_max[0]),
float(source_max[1]),
float(source_max[2]),
),
articulated=articulated,
movable_parts=joints,
explicit_collision=collision is not None,
inferred=inferred,
)
def _sdf_geometry(path: Path, record: AssetRecord) -> GeometryEvidence:
root = ET.parse(path).getroot()
uri = root.findtext(".//mesh/uri")
if uri:
normalized = uri.removeprefix("file://")
candidate = Path(normalized)
if not candidate.is_absolute():
candidate = (path.parent / candidate).resolve()
if not candidate.is_file():
raise ValueError(f"sdf_missing_mesh:{candidate}")
if candidate.suffix.casefold() in {".usd", ".usda", ".usdc", ".usdz"}:
with _USD_INSPECTION_LOCK:
evidence = _usd_geometry(candidate, record)
else:
evidence = _mesh_geometry(candidate, record)
evidence.texture_dependencies = sorted(
set([*evidence.texture_dependencies, str(candidate)])
)
return evidence
raise ValueError("sdf_has_no_supported_mesh_geometry")
def load_geometry_evidence(path: Path, record: AssetRecord) -> GeometryEvidence:
suffix = path.suffix.casefold()
if suffix in {".glb", ".gltf", ".obj", ".fbx"}:
return _mesh_geometry(path, record)
if suffix in {".usd", ".usda", ".usdc", ".usdz"}:
with _USD_INSPECTION_LOCK:
return _usd_geometry(path, record)
if suffix == ".sdf":
return _sdf_geometry(path, record)
raise ValueError(f"unsupported_geometry_format:{suffix or 'none'}")
def _polygon(points: Any, *, minimum_thickness_m: float = 0.005) -> Polygon:
import numpy as np
values = np.asarray(points, dtype=float)
if values.ndim != 2 or values.shape[1] != 2 or len(values) < 1:
raise ValueError("footprint_has_no_points")
if len(values) > 100_000:
stride = max(1, len(values) // 100_000)
extrema = values[
np.unique(
np.concatenate(
[
np.argmin(values, axis=0),
np.argmax(values, axis=0),
np.arange(0, len(values), stride),
]
)
)
]
values = extrema
geometry = MultiPoint(values).convex_hull
if isinstance(geometry, Polygon) and geometry.area > 1.0e-10:
return geometry
return geometry.buffer(minimum_thickness_m / 2.0, cap_style="square").convex_hull
def _points(polygon: Polygon) -> list[Point2]:
return [(round(float(x), 6), round(float(y), 6)) for x, y in polygon.exterior.coords[:-1]]
def _clearances(category: str, visual: Polygon, height: float) -> list[OperationalClearance]:
min_x, min_y, max_x, max_y = visual.bounds
width = max_x - min_x
result: list[OperationalClearance] = []
if category in {"cabinet", "chest of drawers", "refrigerator", "wardrobe"}:
polygon = box(min_x - 0.05, max_y, max_x + 0.05, max_y + min(0.9, max(0.45, width)))
result.append(
OperationalClearance(
clearance_id="front_opening",
operation="open doors or drawers",
polygon_m=_points(polygon),
height_range_m=(0.0, max(height, 0.1)),
source="inferred",
confidence=0.72,
)
)
elif category in {"chair", "office chair"}:
polygon = box(min_x - 0.08, min_y - 0.75, max_x + 0.08, min_y)
result.append(
OperationalClearance(
clearance_id="chair_pull_out",
operation="pull chair out and sit",
polygon_m=_points(polygon),
height_range_m=(0.0, max(height, 0.1)),
source="inferred",
confidence=0.78,
)
)
elif category == "armchair":
polygon = box(min_x - 0.05, max_y, max_x + 0.05, max_y + 0.45)
result.append(
OperationalClearance(
clearance_id="reading_approach",
operation="approach and sit",
polygon_m=_points(polygon),
height_range_m=(0.0, max(height, 0.1)),
source="inferred",
confidence=0.70,
)
)
return result
def _support_semantics(category: str) -> tuple[str, str]:
if category in {"picture", "wall art", "mirror", "wall lamp"}:
return "wall", "required"
if category in {"ceiling lamp", "ceiling light"}:
return "ceiling", "none"
if category in {
"book",
"bottle",
"bowl",
"cup",
"mug",
"vase",
"target object",
}:
return "surface", "none"
if category in {"bookcase", "cabinet", "chest of drawers", "desk", "shelf", "television"}:
return "floor", "preferred"
return "floor", "none"
def _obb(visual: Polygon, minimum_z: float, maximum_z: float) -> OrientedBoundingBox:
rectangle = visual.minimum_rotated_rectangle
coordinates = list(rectangle.exterior.coords)[:-1]
lengths = [math.dist(coordinates[index], coordinates[(index + 1) % 4]) for index in range(4)]
longest = max(range(4), key=lengths.__getitem__)
first = coordinates[longest]
second = coordinates[(longest + 1) % 4]
yaw = math.degrees(math.atan2(second[1] - first[1], second[0] - first[0]))
width = lengths[longest]
depth = lengths[(longest + 1) % 4]
center = rectangle.centroid
return OrientedBoundingBox(
center_m=(float(center.x), float(center.y), (minimum_z + maximum_z) / 2.0),
size_m=(float(width), float(depth), float(maximum_z - minimum_z)),
yaw_deg=float(((yaw + 180.0) % 360.0) - 180.0),
footprint_polygon_m=_points(rectangle),
)
def _semantic_tags(record: AssetRecord, category: str, semantic: HssdSemantic | None) -> list[str]:
values = set(_words(" ".join([record.display_name, record.category, *record.tags])))
values.update(_words(category))
if semantic and semantic.pickable:
values.add("pickable")
if record.admission_status != AdmissionStatus.ACTIVE:
values.add("newly_released")
return sorted(values)
def _tag_subset(text: str, candidates: Iterable[str]) -> list[str]:
normalized = " ".join(_words(text))
return sorted(candidate for candidate in candidates if candidate in normalized)
def _quality(
evidence: GeometryEvidence,
*,
collision_explicit: bool,
support_observed: bool,
) -> AssetQuality:
geometry = 55 + min(25, int(math.log10(max(10, evidence.triangle_count)) * 8))
geometry += 10 if collision_explicit else 0
geometry += 5 if support_observed else 0
geometry = min(100, geometry)
material_channels = sum(bool(value) for value in evidence.pbr_channels.model_dump().values())
materials = min(100, 35 + material_channels * 10 + min(15, evidence.material_count * 3))
realism = min(100, round(0.55 * geometry + 0.45 * materials))
overall = round(0.45 * geometry + 0.35 * materials + 0.20 * realism)
return AssetQuality(
geometry=geometry,
materials=materials,
realism=realism,
overall=overall,
)
def _project(vertices: Any, view: str) -> Any:
import numpy as np
if view == "top":
return vertices[:, [0, 1]]
if view == "front":
return vertices[:, [0, 2]]
if view == "side":
return vertices[:, [1, 2]]
matrix = np.array([[0.86, -0.50, 0.0], [0.24, 0.42, 0.82]], dtype=float)
return vertices @ matrix.T
def _render_view(path: Path, vertices: Any, view: str, size: int, label: str) -> None:
import numpy as np
projected = _project(vertices, view)
polygon = _polygon(projected, minimum_thickness_m=0.001)
coordinates = np.asarray(polygon.exterior.coords[:-1], dtype=float)
minimum = coordinates.min(axis=0)
maximum = coordinates.max(axis=0)
span = np.maximum(maximum - minimum, 1.0e-6)
margin = max(12, size // 12)
usable = size - 2 * margin
scale = min(usable / span[0], usable / span[1])
pixels = [
(
margin + float((point[0] - minimum[0]) * scale),
size - margin - float((point[1] - minimum[1]) * scale),
)
for point in coordinates
]
image = Image.new("RGB", (size, size), (247, 244, 236))
draw = ImageDraw.Draw(image)
draw.rounded_rectangle((4, 4, size - 5, size - 5), radius=9, outline=(185, 177, 160), width=2)
draw.polygon(pixels, fill=(91, 121, 112), outline=(26, 55, 52))
draw.line([*pixels, pixels[0]], fill=(26, 55, 52), width=max(1, size // 96))
draw.text((margin, 7), f"{label[:22]} · {view}", fill=(39, 48, 45))
path.parent.mkdir(parents=True, exist_ok=True)
# Identical assets can be inspected concurrently before deduplication.
# A per-thread temporary name prevents the two renderers from racing on
# the same shared-content view path.
temporary = path.with_suffix(path.suffix + f".{os.getpid()}.{threading.get_ident()}.tmp")
image.save(temporary, format="PNG", optimize=True)
temporary.replace(path)
def render_multiviews(
output_root: Path, sha256: str, vertices: Any, label: str
) -> tuple[str, list[str]]:
directory = output_root / "views" / sha256[:2] / sha256
thumbnail = directory / "thumbnail.png"
view_paths = [directory / f"{view}.png" for view in ("front", "side", "top", "perspective")]
if not thumbnail.is_file():
_render_view(thumbnail, vertices, "perspective", 128, label)
for view_path, view in zip(view_paths, ("front", "side", "top", "perspective"), strict=True):
if not view_path.is_file():
_render_view(view_path, vertices, view, 256, label)
return str(thumbnail.resolve()), [str(path.resolve()) for path in view_paths]
def _minimal_quarantine(record: AssetRecord, path: Path, reason: str) -> AssetDescriptor:
synthetic_hash = hashlib.sha256(
(record.content_hash or f"{record.asset_id}\0{path}").encode("utf-8")
).hexdigest()
return AssetDescriptor(
asset_id=record.asset_id,
source=record.source or "unknown",
source_license=record.source_license or "unknown",
source_path=str(path),
canonical_path=str(path),
sha256=synthetic_hash,
category=_clean_category(record.normalized_category or record.category),
display_name=record.display_name or record.asset_id,
canonical_transform=(
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
),
native_bbox_m=(0.0, 0.0, 0.0),
source_bbox_min_m=(0.0, 0.0, 0.0),
source_bbox_max_m=(0.0, 0.0, 0.0),
quality=AssetQuality(geometry=0, materials=0, realism=0, overall=0),
geometry_format=path.suffix.casefold().lstrip("."),
loader_compatibility={},
status="QUARANTINED",
status_reason=reason[:1000],
inferred_fields=["sha256"] if not path.is_file() else [],
confidence={"status": 1.0},
)
def inspect_record(
record: AssetRecord,
*,
output_root: Path,
metadata: ReleaseMetadata,
render_views: bool,
) -> AssetDescriptor:
path = Path(record.usd_path)
normalized_path = path.as_posix().casefold()
if record.source.casefold().endswith("artvip") and "/resource/" in normalized_path:
return _minimal_quarantine(
record,
path,
"artvip_internal_resource_component:not_a_primary_scene_asset",
)
if record.asset_kind in NON_GEOMETRY_KINDS:
return _minimal_quarantine(record, path, "non_3d_asset_kind")
if not path.is_file():
return _minimal_quarantine(record, path, "missing_runtime_path")
if path.suffix.casefold() not in SUPPORTED_GEOMETRY_EXTENSIONS:
return _minimal_quarantine(record, path, f"unsupported_geometry_format:{path.suffix}")
if not record.source_license.strip() or record.source_license.casefold() in {
"unknown",
"not permitted",
"prohibited",
}:
return _minimal_quarantine(record, path, "source_license_not_permitted")
try:
evidence = load_geometry_evidence(path, record)
except _MissingAssetDependencies as error:
return _minimal_quarantine(
record,
path,
"missing_material_or_texture_dependencies:" + "|".join(error.paths[:8]),
)
except Exception as error:
reason = f"geometry_load_failed:{type(error).__name__}:{error}"
return _minimal_quarantine(record, path, reason)
import numpy as np
hssd_id = _hssd_id(record, path)
semantic = metadata.hssd_semantics.get(hssd_id or "")
category = _record_category(record, semantic)
if category == "chair" and any(
token in " ".join(_words(record.display_name))
for token in ("armchair", "accent chair", "easy chair")
):
category = "armchair"
if category == "table" and any(
phrase in " ".join(_words(record.display_name)) for phrase in ("side table", "end table")
):
category = "side table"
vertices = np.asarray(evidence.vertices, dtype=float)
# Thin wall-mounted art is frequently authored flat in HSSD even though
# its semantic mounting direction is vertical. Rotate the longest plane
# dimension into canonical Z while retaining a thin wall-normal footprint.
preliminary_dimensions = vertices.max(axis=0) - vertices.min(axis=0)
if category in {"picture", "painting", "wall art", "mirror"} and (
preliminary_dimensions[2] < max(preliminary_dimensions[0], preliminary_dimensions[1]) * 0.20
):
if preliminary_dimensions[1] >= preliminary_dimensions[0]:
repair = np.array(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.0)))
else:
repair = np.array(((0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0, 0.0)))
vertices = (repair @ vertices.T).T
if evidence.collision_vertices is not None:
evidence.collision_vertices = (
repair @ np.asarray(evidence.collision_vertices, dtype=float).T
).T
transform = np.asarray(evidence.canonical_transform, dtype=float).reshape(4, 4)
transform[:3, :3] = repair @ transform[:3, :3]
evidence.canonical_transform = tuple(float(value) for value in transform.reshape(-1))
evidence.inferred.append("semantic_wall_mount_orientation_repair")
minimum = vertices.min(axis=0)
maximum = vertices.max(axis=0)
dimensions = maximum - minimum
if not np.isfinite(dimensions).all() or any(float(value) <= 1.0e-5 for value in dimensions):
return _minimal_quarantine(record, path, f"invalid_dimensions:{dimensions.tolist()}")
if float(dimensions.max()) > 15.0 or float(dimensions.min()) < 1.0e-5:
return _minimal_quarantine(record, path, f"abnormal_dimensions_m:{dimensions.tolist()}")
if evidence.missing_dependencies:
return _minimal_quarantine(
record,
path,
"missing_material_or_texture_dependencies:"
+ "|".join(evidence.missing_dependencies[:8]),
)
visual = _polygon(vertices[:, :2])
if evidence.collision_vertices is not None:
collision = _polygon(np.asarray(evidence.collision_vertices)[:, :2])
collision_source = "explicit"
else:
collision = visual.buffer(0.002, join_style="mitre")
collision_source = "visual_conservative"
evidence.inferred.append("collision_footprint_polygon_m")
ground_band = max(0.004, min(0.03, float(dimensions[2]) * 0.025))
ground_points = vertices[vertices[:, 2] <= minimum[2] + ground_band, :2]
support_observed = len(ground_points) >= 3
if support_observed:
support = _polygon(ground_points)
else:
support = collision.buffer(-min(0.005, math.sqrt(collision.area) * 0.02))
if support.is_empty or not isinstance(support, Polygon):
support = collision
evidence.inferred.append("support_footprint_polygon_m")
clearances = _clearances(category, visual, float(dimensions[2]))
envelope_parts = [visual, collision, *[Polygon(item.polygon_m) for item in clearances]]
envelope = unary_union(envelope_parts).convex_hull
if not isinstance(envelope, Polygon):
envelope = collision
asset_sha = _sha256_file(path)
front_axis_override = metadata.front_axis_overrides.get(record.asset_id)
if front_axis_override and asset_sha != front_axis_override.asset_sha256:
return _minimal_quarantine(
record,
path,
"front_axis_override_sha256_mismatch:"
f"expected={front_axis_override.asset_sha256}:observed={asset_sha}",
)
if render_views:
thumbnail, multiview = render_multiviews(
output_root, asset_sha, vertices, record.display_name
)
else:
placeholder_dir = output_root / "views" / asset_sha[:2] / asset_sha
thumbnail = str((placeholder_dir / "thumbnail.png").resolve())
multiview = [
str((placeholder_dir / f"{view}.png").resolve())
for view in ("front", "side", "top", "perspective")
]
text = " ".join([record.display_name, record.description, record.category, *record.tags])
material_text = " ".join([text, *evidence.material_names])
support_type, wall_affinity = _support_semantics(category)
affordances = sorted(
set(
[*record.affordances, *metadata.affordances_by_category.get(category, [])]
+ (["pick up and carry"] if semantic and semantic.pickable else [])
)
)
synonyms = sorted(set([*record.synonyms, *CATEGORY_SYNONYMS.get(category, ())]))
articulated = bool(evidence.articulated or (semantic and semantic.articulated))
quality = _quality(
evidence,
collision_explicit=evidence.explicit_collision,
support_observed=support_observed,
)
geometry_signature = _sha256_json(
{
"category": category,
"dimensions_5cm": [round(float(value) / 0.05) for value in dimensions],
"triangles_log2": round(math.log2(max(1, evidence.triangle_count))),
"materials": min(8, evidence.material_count),
}
)[:24]
observed = {
"sha256",
"native_bbox_m",
"visual_footprint_polygon_m",
"pbr_channels",
"geometry_counts",
"texture_dependencies",
"format_extensions",
}
if evidence.explicit_collision:
observed.add("collision_footprint_polygon_m")
if support_observed:
observed.add("support_footprint_polygon_m")
if "native_orientation" not in evidence.inferred:
observed.update({"native_up_vector", "native_front_vector"})
inferred = set(evidence.inferred)
inferred.update(
{
"category",
"synonyms",
"style_tags",
"color_tags",
"material_tags",
"support_type",
"wall_affinity",
"operational_clearance",
"layout_reserve_envelope_polygon_m",
"quality",
"loader_compatibility",
}
)
confidence = {
"geometry": 1.0,
"units": 1.0 if hssd_id or path.suffix.casefold().startswith(".usd") else 0.9,
"orientation": 1.0 if "native_orientation" not in inferred else 0.65,
"category": 0.98 if semantic and semantic.category else 0.78,
"collision": 1.0 if evidence.explicit_collision else 0.72,
"support_footprint": 0.95 if support_observed else 0.65,
"operational_clearance": 0.72 if clearances else 0.60,
"quality": 0.85,
"loader_compatibility": 0.95,
}
descriptor = AssetDescriptor(
asset_id=record.asset_id,
source=record.source,
source_license=record.source_license,
source_path=str(path.resolve()),
canonical_path=str(path.resolve()),
sha256=asset_sha,
category=category,
subcategory=record.category,
display_name=semantic.name if semantic and semantic.name else record.display_name,
semantic_tags=_semantic_tags(record, category, semantic),
synonyms=synonyms,
style_tags=_tag_subset(text, STYLE_WORDS),
color_tags=_tag_subset(text, COLOR_WORDS),
material_tags=_tag_subset(material_text, MATERIAL_WORDS),
pbr_channels=evidence.pbr_channels,
native_units="meter",
native_to_meter_scale=evidence.native_to_meter_scale,
native_up_vector=evidence.native_up,
native_front_vector=evidence.native_front,
canonical_transform=evidence.canonical_transform,
native_bbox_m=(
round(float(dimensions[0]), 6),
round(float(dimensions[1]), 6),
round(float(dimensions[2]), 6),
),
source_bbox_min_m=evidence.source_bbox_min_m,
source_bbox_max_m=evidence.source_bbox_max_m,
visual_footprint_polygon_m=_points(visual),
collision_footprint_polygon_m=_points(collision),
support_footprint_polygon_m=_points(support),
layout_reserve_envelope_polygon_m=_points(envelope),
obb_m=_obb(visual, float(minimum[2]), float(maximum[2])),
height_m=round(float(dimensions[2]), 6),
support_type=support_type, # type: ignore[arg-type]
wall_affinity=wall_affinity, # type: ignore[arg-type]
articulated=articulated,
movable_parts=evidence.movable_parts,
operational_clearance=clearances,
affordances=affordances,
uniform_scale_range=(1.0, 1.0) if articulated else (0.9, 1.1),
quality=quality,
thumbnail=thumbnail,
multiview_images=multiview,
geometry_format=path.suffix.casefold().lstrip("."),
format_extensions=evidence.format_extensions,
loader_compatibility=evidence.loader_compatibility, # type: ignore[arg-type]
vertex_count=int(len(vertices)),
triangle_count=evidence.triangle_count,
material_count=evidence.material_count,
collision_source=collision_source, # type: ignore[arg-type]
texture_dependencies=evidence.texture_dependencies,
missing_dependencies=[],
geometry_signature=geometry_signature,
status="ACTIVE",
status_reason="",
observed_fields=sorted(observed - inferred),
inferred_fields=sorted(inferred),
confidence=confidence,
)
return certify_descriptor_front_axis(descriptor, front_axis_override)
def _resolve_duplicates(descriptors: list[AssetDescriptor]) -> list[AssetDescriptor]:
by_hash: dict[str, list[int]] = defaultdict(list)
for index, descriptor in enumerate(descriptors):
if descriptor.status == "ACTIVE":
by_hash[descriptor.sha256].append(index)
for indices in by_hash.values():
if len(indices) < 2:
continue
canonical_index = max(
indices,
key=lambda index: (
descriptors[index].quality.overall,
bool(descriptors[index].collision_source == "explicit"),
descriptors[index].asset_id,
),
)
canonical_id = descriptors[canonical_index].asset_id
for index in indices:
if index == canonical_index:
continue
value = descriptors[index].model_dump(mode="json")
value.update(
status="QUARANTINED",
status_reason=f"duplicate_content:{canonical_id}",
canonical_asset_id=canonical_id,
)
descriptors[index] = AssetDescriptor.model_validate(value)
by_signature: dict[str, list[int]] = defaultdict(list)
for index, descriptor in enumerate(descriptors):
if descriptor.status == "ACTIVE" and descriptor.geometry_signature:
by_signature[descriptor.geometry_signature].append(index)
for indices in by_signature.values():
if len(indices) < 2:
continue
ids = [descriptors[index].asset_id for index in indices]
for index in indices:
value = descriptors[index].model_dump(mode="json")
value["near_duplicate_asset_ids"] = [
asset_id for asset_id in ids if asset_id != descriptors[index].asset_id
][:64]
descriptors[index] = AssetDescriptor.model_validate(value)
return descriptors
def _write_descriptor_index(descriptors: Sequence[AssetDescriptor], path: Path) -> None:
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.unlink(missing_ok=True)
connection = sqlite3.connect(temporary)
try:
connection.executescript(
"""
PRAGMA journal_mode=OFF;
PRAGMA synchronous=OFF;
CREATE TABLE asset_descriptors (
asset_id TEXT PRIMARY KEY,
asset_sha256 TEXT NOT NULL,
source TEXT NOT NULL,
category TEXT NOT NULL,
support_type TEXT NOT NULL,
quality_overall INTEGER NOT NULL,
status TEXT NOT NULL,
status_reason TEXT NOT NULL,
canonical_path TEXT NOT NULL,
descriptor_json TEXT NOT NULL
);
CREATE INDEX descriptor_status_category ON asset_descriptors(status, category);
CREATE INDEX descriptor_sha256 ON asset_descriptors(asset_sha256);
CREATE VIRTUAL TABLE active_descriptor_fts USING fts5(
asset_id, display_name, category, semantic_tags, synonyms,
style_tags, color_tags, material_tags, affordances, content=''
);
"""
)
for row_id, descriptor in enumerate(descriptors, start=1):
connection.execute(
"INSERT INTO asset_descriptors VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
descriptor.asset_id,
descriptor.sha256,
descriptor.source,
descriptor.category,
descriptor.support_type,
descriptor.quality.overall,
descriptor.status,
descriptor.status_reason,
descriptor.canonical_path,
descriptor.model_dump_json(),
),
)
if descriptor.status == "ACTIVE":
connection.execute(
"INSERT INTO active_descriptor_fts("
"rowid, asset_id, display_name, category, semantic_tags, synonyms, "
"style_tags, color_tags, material_tags, affordances"
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
row_id,
descriptor.asset_id,
descriptor.display_name,
descriptor.category,
" ".join(descriptor.semantic_tags),
" ".join(descriptor.synonyms),
" ".join(descriptor.style_tags),
" ".join(descriptor.color_tags),
" ".join(descriptor.material_tags),
" ".join(descriptor.affordances),
),
)
connection.commit()
finally:
connection.close()
temporary.replace(path)
def _jsonl(path: Path, descriptors: Iterable[AssetDescriptor]) -> None:
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("w", encoding="utf-8") as handle:
for descriptor in descriptors:
handle.write(descriptor.model_dump_json() + "\n")
temporary.replace(path)
def _inventory_roots(roots: Sequence[Path], indexed_paths: set[Path]) -> dict[str, Any]:
output: dict[str, Any] = {}
for root in roots:
resolved = root.resolve()
if not resolved.exists():
output[str(resolved)] = {
"exists": False,
"geometry_files": 0,
"indexed_primary_files": 0,
}
continue
extensions = Counter[str]()
geometry_files = 0
indexed = 0
for path in resolved.rglob("*"):
if not path.is_file() or path.suffix.casefold() not in SUPPORTED_GEOMETRY_EXTENSIONS:
continue
geometry_files += 1
extensions[path.suffix.casefold()] += 1
try:
if path.resolve() in indexed_paths:
indexed += 1
except OSError:
pass
output[str(resolved)] = {
"exists": True,
"geometry_files": geometry_files,
"indexed_primary_files": indexed,
"unindexed_or_auxiliary_geometry_files": geometry_files - indexed,
"by_extension": dict(sorted(extensions.items())),
}
return output
def _inspect_record_safely(
record: AssetRecord,
*,
output_root: Path,
metadata: ReleaseMetadata,
render_views: bool,
) -> AssetDescriptor:
try:
return inspect_record(
record,
output_root=output_root,
metadata=metadata,
render_views=render_views,
)
except Exception as error: # defensive per-asset isolation
details = "".join(traceback.format_exception_only(type(error), error)).strip()
return _minimal_quarantine(
record,
Path(record.usd_path),
f"inspection_internal_error:{details}",
)
def _initialize_inspection_process(
output_root: Path,
metadata: ReleaseMetadata,
render_views: bool,
) -> None:
global _PROCESS_METADATA, _PROCESS_OUTPUT_ROOT, _PROCESS_RENDER_VIEWS
_PROCESS_OUTPUT_ROOT = output_root
_PROCESS_METADATA = metadata
_PROCESS_RENDER_VIEWS = render_views
def _inspect_record_in_process(record: AssetRecord) -> AssetDescriptor:
if _PROCESS_OUTPUT_ROOT is None or _PROCESS_METADATA is None:
raise RuntimeError("asset inspection process was not initialized")
return _inspect_record_safely(
record,
output_root=_PROCESS_OUTPUT_ROOT,
metadata=_PROCESS_METADATA,
render_views=_PROCESS_RENDER_VIEWS,
)
def release_catalog(
catalog_path: Path,
output_root: Path,
*,
hssd_root: Path | None = None,
front_axis_overrides_path: Path | None = None,
scan_roots: Sequence[Path] = (),
workers: int = 4,
inspection_backend: str = "process",
render_views: bool = True,
maximum_records: int | None = None,
) -> dict[str, Any]:
started = time.perf_counter()
output_root.mkdir(parents=True, exist_ok=False)
catalog = AssetCatalog.model_validate_json(catalog_path.read_text(encoding="utf-8"))
records = catalog.assets[:maximum_records] if maximum_records is not None else catalog.assets
metadata = load_release_metadata(hssd_root, front_axis_overrides_path)
stage_started = time.perf_counter()
if inspection_backend not in {"process", "thread"}:
raise ValueError("inspection_backend must be 'process' or 'thread'")
descriptors: list[AssetDescriptor] = []
worker_count = max(1, workers)
executor_context: ProcessPoolExecutor | ThreadPoolExecutor
if inspection_backend == "process":
executor_context = ProcessPoolExecutor(
max_workers=worker_count,
initializer=_initialize_inspection_process,
initargs=(output_root, metadata, render_views),
)
descriptor_iterator = executor_context.map(
_inspect_record_in_process,
records,
chunksize=1,
)
else:
executor_context = ThreadPoolExecutor(max_workers=worker_count)
descriptor_iterator = executor_context.map(
lambda record: _inspect_record_safely(
record,
output_root=output_root,
metadata=metadata,
render_views=render_views,
),
records,
)
with executor_context:
for index, descriptor in enumerate(descriptor_iterator, start=1):
descriptors.append(descriptor)
if index == len(records) or index % 250 == 0:
active_so_far = sum(item.status == "ACTIVE" for item in descriptors)
print(
f"asset-release progress={index}/{len(records)} "
f"loadable={active_so_far} quarantined={index - active_so_far}",
flush=True,
)
inspection_duration = time.perf_counter() - stage_started
dedupe_started = time.perf_counter()
descriptors = _resolve_duplicates(descriptors)
descriptors.sort(key=lambda descriptor: descriptor.asset_id)
dedupe_duration = time.perf_counter() - dedupe_started
active = [descriptor for descriptor in descriptors if descriptor.status == "ACTIVE"]
quarantined = [descriptor for descriptor in descriptors if descriptor.status == "QUARANTINED"]
_jsonl(output_root / "asset_descriptors.jsonl", descriptors)
_jsonl(output_root / "quarantine.jsonl", quarantined)
_write_descriptor_index(descriptors, output_root / "asset_descriptor_index.sqlite3")
before_active = [
record for record in records if record.admission_status == AdmissionStatus.ACTIVE
]
before_categories = Counter(
(record.normalized_category or normalize_category(record.category))
for record in before_active
)
after_categories = Counter(descriptor.category for descriptor in active)
reasons = Counter(descriptor.status_reason.split(":", 1)[0] for descriptor in quarantined)
indexed_paths = {
Path(record.usd_path).resolve() for record in records if Path(record.usd_path).is_file()
}
inventory_started = time.perf_counter()
inventory = _inventory_roots(scan_roots, indexed_paths)
inventory_duration = time.perf_counter() - inventory_started
report: dict[str, Any] = {
"schema_version": "2.0",
"truth_policy": (
"ACTIVE only after file, loader, triangle, units, orientation, dimensions, "
"dependency and footprint checks"
),
"source_catalog": str(catalog_path.resolve()),
"output_root": str(output_root.resolve()),
"inspection_backend": inspection_backend,
"inspection_workers": worker_count,
"front_axis_overrides": {
"path": (
str(front_axis_overrides_path.resolve()) if front_axis_overrides_path else None
),
"configured": len(metadata.front_axis_overrides),
"applied_active": sum(
descriptor.front_axis_source in {"multiview_verified", "manual_override"}
for descriptor in active
),
},
"before": {
"catalog_records": len(records),
"active_records": len(before_active),
"active_3d_records": sum(
record.asset_kind not in NON_GEOMETRY_KINDS for record in before_active
),
"active_category_count": len(before_categories),
"active_by_category": dict(before_categories.most_common()),
},
"after": {
"descriptor_records": len(descriptors),
"active_records": len(active),
"quarantined_records": len(quarantined),
"active_category_count": len(after_categories),
"active_by_category": dict(after_categories.most_common()),
"active_by_source": dict(Counter(item.source for item in active).most_common()),
"quarantine_reasons": dict(reasons.most_common()),
"exact_duplicate_quarantines": sum(
item.status_reason.startswith("duplicate_content:") for item in quarantined
),
"near_duplicate_members": sum(bool(item.near_duplicate_asset_ids) for item in active),
},
"source_inventory": inventory,
"durations_s": {
"inspection_and_views": round(inspection_duration, 3),
"deduplication": round(dedupe_duration, 3),
"source_inventory": round(inventory_duration, 3),
"total": round(time.perf_counter() - started, 3),
},
"files": {},
}
for path in (
output_root / "asset_descriptors.jsonl",
output_root / "quarantine.jsonl",
output_root / "asset_descriptor_index.sqlite3",
):
report["files"][path.name] = {"path": str(path.resolve()), "sha256": _sha256_file(path)}
atomic_write_text(
output_root / "asset_release_report.json",
json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
)
manifest: dict[str, Any] = {
"schema_version": "2.0",
"descriptor_schema": "packages.asset_registry.descriptors.AssetDescriptor/2.0",
"active_records": len(active),
"quarantined_records": len(quarantined),
"active_by_kind": {"OBJECT_OR_ROOM": len(active)},
"active_by_category": dict(after_categories.most_common()),
"files": {
**report["files"],
"asset_release_report.json": {
"path": str((output_root / "asset_release_report.json").resolve()),
"sha256": _sha256_file(output_root / "asset_release_report.json"),
},
},
"old_indexes_preserved": True,
}
atomic_write_text(
output_root / "asset_index_manifest.json",
json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
)
return report
def load_active_descriptors(
index_path: Path,
asset_ids: Sequence[str] = (),
*,
categories: Sequence[str] = (),
) -> list[AssetDescriptor]:
uri = f"file:{index_path.resolve()}?mode=ro&immutable=1"
connection = sqlite3.connect(uri, uri=True)
try:
clauses = ["status='ACTIVE'"]
parameters: list[str] = []
if asset_ids:
placeholders = ",".join("?" for _ in asset_ids)
clauses.append(f"asset_id IN ({placeholders})")
parameters.extend(asset_ids)
if categories:
normalized_categories = sorted({_clean_category(item) for item in categories})
placeholders = ",".join("?" for _ in normalized_categories)
clauses.append(f"category IN ({placeholders})")
parameters.extend(normalized_categories)
rows = connection.execute(
"SELECT descriptor_json FROM asset_descriptors WHERE "
+ " AND ".join(clauses)
+ " ORDER BY asset_id",
tuple(parameters),
).fetchall()
finally:
connection.close()
return [AssetDescriptor.model_validate_json(row[0]) for row in rows]
def search_active_descriptors(
index_path: Path,
*,
query: str,
category: str | None = None,
limit: int = 20,
) -> list[AssetDescriptor]:
uri = f"file:{index_path.resolve()}?mode=ro&immutable=1"
connection = sqlite3.connect(uri, uri=True)
connection.row_factory = sqlite3.Row
try:
terms = list(dict.fromkeys(_words(query)))
expression = " OR ".join(f'"{term}"' for term in terms)
if expression:
row_ids = [
int(row[0])
for row in connection.execute(
"SELECT rowid FROM active_descriptor_fts "
"WHERE active_descriptor_fts MATCH ? LIMIT ?",
(expression, max(limit * 10, 100)),
)
]
else:
row_ids = []
clauses = ["status='ACTIVE'"]
parameters: list[Any] = []
if category:
clauses.append("category=?")
parameters.append(_clean_category(category))
if row_ids:
clauses.append(f"rowid IN ({','.join('?' for _ in row_ids)})")
parameters.extend(row_ids)
rows = connection.execute(
"SELECT descriptor_json FROM asset_descriptors WHERE "
+ " AND ".join(clauses)
+ " ORDER BY quality_overall DESC, asset_id LIMIT ?",
(*parameters, limit),
).fetchall()
finally:
connection.close()
return [AssetDescriptor.model_validate_json(row[0]) for row in rows]
from __future__ import annotations
import ast
import csv
import hashlib
import json
import math
import os
import re
import sqlite3
import struct
import threading
import time
import traceback
import urllib.parse
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from collections.abc import Iterable, Sequence
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal, cast
from PIL import Image, ImageDraw
from shapely.geometry import MultiPoint, Polygon, box # type: ignore[import-untyped]
from shapely.ops import unary_union # type: ignore[import-untyped]
from packages.asset_registry.admission import normalize_category
from packages.asset_registry.descriptors import (
AssetDescriptor,
AssetQuality,
OperationalClearance,
OrientedBoundingBox,
PbrChannels,
Point2,
)
from packages.asset_registry.models import AdmissionStatus, AssetCatalog, AssetKind, AssetRecord
from packages.core.files import atomic_write_text
# USD's resolver and stage caches are not safe to drive from several Python
# threads in the same process. GLB/GLTF inspection remains parallel, while
# USD loading is serialized through this narrow gate.
_USD_INSPECTION_LOCK = threading.Lock()
SUPPORTED_GEOMETRY_EXTENSIONS = {
".glb",
".gltf",
".obj",
".fbx",
".usd",
".usda",
".usdc",
".usdz",
".sdf",
}
NON_GEOMETRY_KINDS = {AssetKind.MATERIAL, AssetKind.LIGHTING}
STYLE_WORDS = {
"art deco",
"bohemian",
"classic",
"contemporary",
"industrial",
"japanese",
"mid century",
"minimal",
"modern",
"rustic",
"scandinavian",
"traditional",
"vintage",
}
COLOR_WORDS = {
"beige",
"black",
"blue",
"brass",
"bronze",
"brown",
"copper",
"cream",
"gold",
"gray",
"green",
"grey",
"orange",
"pink",
"purple",
"red",
"silver",
"teal",
"white",
"yellow",
}
MATERIAL_WORDS = {
"bamboo",
"ceramic",
"concrete",
"fabric",
"glass",