File size: 11,409 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
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