from __future__ import annotations import hashlib import re from collections import defaultdict from pathlib import Path from packages.asset_registry.models import ( AdmissionStatus, AssetKind, AssetRecord, ) GENERIC_NAMES = {"link 0 0", "material", "mesh", "node", "object", "root"} OBJECT_SOURCES = { "ArtVIP", "HSSD", "Lightwheel SimReady", "ReplicaCAD", "Google Scanned Objects", "GoogleResearch on Gazebo Fuel", "YCB", } OBJECT_CATEGORIES = { "book", "bookcase", "bottle", "bowl", "cabinet", "chair", "computer", "cup", "desk", "faucet", "floor lamp", "lamp", "monitor", "mug", "oven", "plant", "potted plant", "refrigerator", "shelf", "sink", "sofa", "table", "television", "trash can", } def normalize_category(value: str) -> str: tokens = re.findall(r"[a-z0-9]+", value.casefold().replace("_", "-")) terms = set(tokens) if "bottle" in terms or any( token.startswith("bottle") or token.endswith("bottle") for token in tokens ): return "bottle" if "trash" in terms and terms & {"bin", "can", "dustbin"}: return "trash can" if "dustbin" in terms: return "trash can" if "countertop" in terms or "worktop" in terms: return "kitchen counter" if "kitchen" in terms or "countertop" in terms else "worktop" # Catalogs such as ArtVIP and the H20 qualified overlay often expose a # useful class only in the filename/tags while their upstream category is # the generic ``articulated object``. Collapse those records to the same # compact taxonomy used by task specifications. if "pottedplant" in terms or ("potted" in terms and "plant" in terms): return "potted plant" if "floorlamp" in terms or ("floor" in terms and "lamp" in terms): return "floor lamp" if terms & {"television", "television003", "tv"}: return "television" if terms & {"refrigerator", "fridge", "freezer"}: return "refrigerator" if terms & {"faucet", "spigot"} or "tap" in terms: return "faucet" if terms & {"oven", "cooktop", "stovetop", "stove", "cooker"}: return "oven" if terms & {"sink", "basin"}: return "sink" if terms & {"cabinet", "cabinets", "cupboard", "cupboards"}: return "cabinet" if "bookcase" in terms or "bookshelf" in terms: return "bookcase" if ( "computer" in terms or "workstation" in terms or any(token.startswith("computer") for token in tokens) ): return "computer" if "monitor" in terms or "display" in terms: return "monitor" if "books" in terms or "book" in terms or any(token.startswith("book") for token in tokens): return "book" if "shelf" in terms or "shelving" in terms: return "shelf" if "mug" in terms: return "mug" if "cup" in terms: return "cup" if "bowl" in terms: return "bowl" if "plant" in terms: return "plant" if "lamp" in terms: return "lamp" if "desk" in terms or any(token.endswith("desk") for token in tokens): return "desk" if "chair" in terms or any(token.endswith("chair") for token in tokens): return "chair" if "sofa" in terms or "couch" in terms: return "sofa" if "table" in terms: return "table" return " ".join(tokens) def canonical_category(record: AssetRecord) -> str: return normalize_category( " ".join( [record.display_name, record.category, *record.tags, *record.synonyms] ) ) def infer_asset_kind(record: AssetRecord) -> AssetKind: category = canonical_category(record) path = Path(record.usd_path) path_text = path.as_posix().casefold() source = record.source.casefold() h20_namespace = source.split("h20 qualified/", 1)[1] if source.startswith("h20 qualified/") else "" # ArtVIP Interactive_scene stores individual props under an explicit item # directory. A path such as childrenroom/item/pottedplant is an object; # substring matching "room" in childrenroom previously misclassified it as # a complete ROOM and incorrectly bypassed proxy preparation. artvip_source = record.source == "ArtVIP" or record.source.casefold().endswith("/artvip") if artvip_source: parts = [part.casefold() for part in path.parts] if "/articulated_objects/" in path_text or "/item/" in path_text or "/itm/" in path_text: return AssetKind.OBJECT for marker in ("interactive_scene", "scenes"): if marker in parts and len(parts) - parts.index(marker) >= 4: return AssetKind.OBJECT if (record.source == "Lightwheel SimReady" or h20_namespace == "lightwheel") and ( "/props/" in path_text or category in OBJECT_CATEGORIES ): return AssetKind.OBJECT if h20_namespace in { "artvip", "assets_isaac", "molmospaces_thor", "roboparty_20260803", } and category in OBJECT_CATEGORIES: return AssetKind.OBJECT if record.source in OBJECT_SOURCES and category in OBJECT_CATEGORIES: return AssetKind.OBJECT if record.source.casefold() in {"poly haven", "ambientcg"} and ( "material" in category or path.suffix.casefold() in {".jpg", ".jpeg", ".png", ".exr"} ): return AssetKind.MATERIAL if "hdri" in category or path.suffix.casefold() in {".hdr", ".exr"}: return AssetKind.LIGHTING category_terms = set(category.split()) if "interior scene" in category or category_terms & {"room", "stage"}: return AssetKind.ROOM return record.asset_kind def _path_exists(record: AssetRecord) -> bool: return bool(record.usd_path) and Path(record.usd_path).exists() def content_hash(record: AssetRecord) -> str: existing = next((item.md5 for item in record.files if item.md5), None) if existing: return f"md5:{existing.casefold()}" path = Path(record.usd_path) if path.is_file(): digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): digest.update(chunk) return f"sha256:{digest.hexdigest()}" return "metadata:" + hashlib.sha256( f"{record.source}\0{record.asset_id}\0{record.usd_path}".encode() ).hexdigest() def classify(record: AssetRecord, *, check_paths: bool = True) -> AssetRecord: kind = infer_asset_kind(record) reasons: list[str] = [] display = record.display_name.strip().casefold() path_text = record.usd_path.casefold() category = canonical_category(record) if record.quality_tier == "REJECTED" or record.qa_status == "REJECTED": return record.model_copy( update={ "schema_version": "1.1", "asset_kind": kind, "normalized_category": category, "admission_status": AdmissionStatus.REJECTED, "exclusion_reasons": ["upstream_rejected"], "content_hash": content_hash(record), } ) if record.quality_tier == "C": reasons.append("quality_tier_c") if check_paths and not _path_exists(record): reasons.append("missing_runtime_path") if display in GENERIC_NAMES: reasons.append("generic_node_name") if record.source == "MolmoSpaces" and any( marker in path_text for marker in ("virtual", "placeholder", "package") ): reasons.append("molmospaces_virtual_package") if record.source == "InteriorAgent" and kind == AssetKind.OBJECT: reasons.append("interioragent_internal_mesh") if record.source == "ArtVIP" and "/resource/" in path_text: reasons.append("artvip_internal_resource") if record.source == "HSSD" and (kind == AssetKind.ROOM or "/stages/" in path_text): reasons.append("hssd_stage_not_object") if kind == AssetKind.OBJECT: runtime = record.runtime_compatibility if ( runtime is None or not runtime.canonical_usd_path or not runtime.proxy_gltf_path or not runtime.proxy_sdf_path or not Path(runtime.canonical_usd_path).is_file() or not Path(runtime.proxy_gltf_path).is_file() or not Path(runtime.proxy_sdf_path).is_file() ): reasons.append("proxy_not_prepared") if kind == AssetKind.OBJECT and record.source not in OBJECT_SOURCES | {"Poly Haven"}: if record.source == "MolmoSpaces": reasons.append("source_not_runtime_instantiable") status = AdmissionStatus.COLD if reasons else AdmissionStatus.ACTIVE return record.model_copy( update={ "schema_version": "1.1", "asset_kind": kind, "normalized_category": category, "admission_status": status, "exclusion_reasons": sorted(set(reasons)), "content_hash": content_hash(record), # Canonical aliases are recomputed by the following deduplication # pass; a formerly cold alias can become the prepared canonical. "canonical_asset_id": None, } ) def _canonical_score(record: AssetRecord) -> tuple[int, int, int, int, int, str]: qa = {"ISAAC_VALIDATED": 3, "CONVERTED": 2, "DOWNLOADED": 1, "REJECTED": 0} quality = {"A": 3, "B": 2, "C": 1, "REJECTED": 0} provenance = sum(bool(item.source_url and item.md5) for item in record.files) runtime = record.runtime_compatibility compatibility = int(bool(runtime and runtime.canonical_usd_path)) # Deduplication must never nominate a cold, uninstantiable record when the # same content already has a fully prepared ACTIVE representation. The # previous ordering let provenance/quality beat runtime readiness, leaving # every alias of some H20 assets cold despite a valid proxy being present. active = int(record.admission_status == AdmissionStatus.ACTIVE) return ( active, qa[record.qa_status], quality[record.quality_tier], provenance, compatibility, record.asset_id, ) def classify_and_deduplicate( records: list[AssetRecord], *, check_paths: bool = True ) -> list[AssetRecord]: classified = [classify(record, check_paths=check_paths) for record in records] groups: dict[str, list[int]] = defaultdict(list) for index, record in enumerate(classified): assert record.content_hash is not None groups[record.content_hash].append(index) for indices in groups.values(): if len(indices) < 2: continue canonical_index = max(indices, key=lambda index: _canonical_score(classified[index])) canonical_id = classified[canonical_index].asset_id for index in indices: if index == canonical_index: continue record = classified[index] reasons = sorted(set([*record.exclusion_reasons, "duplicate_content"])) classified[index] = record.model_copy( update={ "admission_status": AdmissionStatus.COLD, "exclusion_reasons": reasons, "canonical_asset_id": canonical_id, } ) return classified