File size: 14,255 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
from __future__ import annotations

import json
import os
import shlex
import shutil
import signal
import subprocess
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal

from pydantic import BaseModel, ConfigDict, Field, model_validator

from packages.adapters.protocols import NotConfiguredError
from packages.core.files import atomic_write_text

SCENESMITH_COMMIT = "67cc408fd38334b4a926efef45e284302ed5055b"
DEFAULT_ASSET_CATALOG = Path(
    os.environ.get("SCENESMITH_ASSET_CATALOG", Path.home() / ".cache/robohomegen/assets/retrieval_catalog.json")
)


def _terminate_process_group(process: subprocess.Popen[str], grace_s: float = 10.0) -> None:
    if process.poll() is not None:
        return
    try:
        os.killpg(process.pid, signal.SIGTERM)
    except ProcessLookupError:
        return
    try:
        process.wait(timeout=grace_s)
    except subprocess.TimeoutExpired:
        try:
            os.killpg(process.pid, signal.SIGKILL)
        except ProcessLookupError:
            pass
        process.wait()


def _run_isolated(command: list[str], timeout_s: int) -> subprocess.CompletedProcess[str]:
    """Run a backend in its own process group and reap it on interruption."""

    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        start_new_session=True,
    )
    previous_handlers: dict[int, Any] = {}
    install_handlers = threading.current_thread() is threading.main_thread()

    def interrupt(signum: int, _frame: object) -> None:
        if signum == signal.SIGINT:
            raise KeyboardInterrupt
        raise SystemExit(128 + signum)

    if install_handlers:
        for signum in (signal.SIGINT, signal.SIGTERM):
            previous_handlers[signum] = signal.signal(signum, interrupt)
    try:
        stdout, stderr = process.communicate(timeout=timeout_s)
    except BaseException:
        _terminate_process_group(process)
        raise
    finally:
        for signum, handler in previous_handlers.items():
            signal.signal(signum, handler)
    return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)

RoboLabPredicateType = Literal[
    "place-on-base",
    "left-of",
    "right-of",
    "front-of",
    "back-of",
    "random-rot",
    "facing-left",
    "facing-right",
    "facing-front",
    "facing-back",
    "align-left",
    "align-right",
    "align-front",
    "align-back",
    "align-center-lr",
    "align-center-fb",
    "place-on",
    "place-in",
    "place-anywhere",
]


class RoboLabSceneObject(BaseModel):
    model_config = ConfigDict(extra="forbid")
    name: str = Field(min_length=1)


class RoboLabScenePredicate(BaseModel):
    """Wire-compatible predicate accepted by RoboLab robolab-scenegen."""

    model_config = ConfigDict(extra="forbid")
    type: RoboLabPredicateType
    object: str | None = None
    objects: list[str] | None = None
    reference: str | None = None
    support: str | None = None
    container: str | None = None
    x: float | None = None
    y: float | None = None
    yaw: float | None = None
    distance: float | None = Field(default=None, gt=0)
    support_ratio: float | None = Field(default=None, gt=0, le=1)
    stability: Literal["stable", "unstable", "neutral"] | None = None
    position: str | None = None
    shelf_level: int | None = Field(default=None, ge=0)

    @model_validator(mode="after")
    def validate_shape(self) -> RoboLabScenePredicate:
        if self.type == "place-in":
            if not self.objects or not self.container:
                raise ValueError("place-in requires objects and container")
        elif not self.object:
            raise ValueError(f"{self.type} requires object")
        if (
            self.type
            in {
                "left-of",
                "right-of",
                "front-of",
                "back-of",
                "align-left",
                "align-right",
                "align-front",
                "align-back",
                "align-center-lr",
                "align-center-fb",
            }
            and not self.reference
        ):
            raise ValueError(f"{self.type} requires reference")
        if self.type == "place-on" and not self.support:
            raise ValueError("place-on requires support")
        return self

    def referenced_objects(self) -> set[str]:
        values = [self.object, self.reference, self.support, self.container, *(self.objects or [])]
        return {value for value in values if value}

    def target_objects(self) -> set[str]:
        return set(self.objects or []) if self.type == "place-in" else {self.object or ""}


class RoboLabSceneRequest(BaseModel):
    """Exact top-level RoboLab scene-gen request: objects plus predicates."""

    model_config = ConfigDict(extra="forbid")
    objects: list[RoboLabSceneObject] = Field(min_length=1)
    predicates: list[RoboLabScenePredicate] = Field(min_length=1)

    @model_validator(mode="after")
    def validate_references(self) -> RoboLabSceneRequest:
        names = [item.name for item in self.objects]
        if len(names) != len(set(names)):
            raise ValueError("scene object names must be unique")
        known = set(names)
        referenced = set().union(*(item.referenced_objects() for item in self.predicates))
        if unknown := referenced - known:
            raise ValueError(f"predicates reference unknown objects: {sorted(unknown)}")
        targeted = set().union(*(item.target_objects() for item in self.predicates))
        if missing := known - targeted:
            raise ValueError(f"objects have no placement predicate: {sorted(missing)}")
        return self

    @classmethod
    def model_validate_robolab(cls, value: dict[str, Any]) -> RoboLabSceneRequest:
        return cls.model_validate(value)


@dataclass(frozen=True, slots=True)
class SceneSmithSettings:
    command: tuple[str, ...]
    asset_catalog: Path = DEFAULT_ASSET_CATALOG
    asset_index: Path | None = None
    timeout_s: int = 14_400
    required: bool = False

    @classmethod
    def from_env(cls) -> SceneSmithSettings:
        command = tuple(shlex.split(os.environ.get("SCENESMITH_COMMAND", "")))
        timeout_s = int(os.environ.get("SCENESMITH_TIMEOUT_S", "14400"))
        if timeout_s <= 0:
            raise ValueError("SCENESMITH_TIMEOUT_S must be positive")
        return cls(
            command=command,
            asset_catalog=Path(
                os.environ.get("SCENESMITH_ASSET_CATALOG", str(DEFAULT_ASSET_CATALOG))
            ),
            asset_index=(
                Path(os.environ["RHG_ASSET_INDEX"]) if os.environ.get("RHG_ASSET_INDEX") else None
            ),
            timeout_s=timeout_s,
            required=os.environ.get("SCENESMITH_REQUIRED", "0").casefold() in {"1", "true", "yes"},
        )


def probe_scenesmith(settings: SceneSmithSettings | None = None) -> dict[str, object]:
    settings = settings or SceneSmithSettings.from_env()
    executable = settings.command[0] if settings.command else ""
    executable_ready = bool(executable) and (
        Path(executable).is_file() or shutil.which(executable) is not None
    )
    runtime_assets: dict[str, bool] = {}
    if "--upstream-root" in settings.command:
        index = settings.command.index("--upstream-root")
        if index + 1 < len(settings.command):
            root = Path(settings.command[index + 1])
            runtime_assets = {
                "hssd_models": (root / "data" / "hssd-models" / "objects").is_dir(),
                "hssd_support_surfaces": (
                    root / "data" / "hssd-models" / "support-surfaces"
                ).is_dir(),
                "hssd_index": (
                    root / "data" / "preprocessed" / "hssd_wnsynsetkey_index.json"
                ).is_file(),
                "hssd_embeddings": (
                    root / "data" / "preprocessed" / "clip_hssd_embeddings.npy"
                ).is_file(),
                "material_embeddings": (
                    root / "data" / "materials" / "embeddings" / "clip_embeddings.npy"
                ).is_file(),
                "material_index": (
                    root / "data" / "materials" / "embeddings" / "embedding_index.yaml"
                ).is_file(),
                "material_metadata": (
                    root / "data" / "materials" / "embeddings" / "metadata_index.yaml"
                ).is_file(),
            }
    runtime_ready = all(runtime_assets.values()) if runtime_assets else True
    return {
        "configured": bool(settings.command),
        "ready": executable_ready
        and (
            settings.asset_index is not None
            and settings.asset_index.is_file()
            or settings.asset_catalog.is_file()
        )
        and runtime_ready,
        "command": list(settings.command),
        "command_ready": executable_ready,
        "asset_catalog": str(settings.asset_catalog),
        "asset_catalog_ready": settings.asset_catalog.is_file(),
        "asset_index": str(settings.asset_index) if settings.asset_index else None,
        "asset_index_ready": bool(settings.asset_index and settings.asset_index.is_file()),
        "runtime_assets": runtime_assets,
        "runtime_assets_ready": runtime_ready,
        "required": settings.required,
        "timeout_s": settings.timeout_s,
        "commit": SCENESMITH_COMMIT,
    }


class SceneSmithAdapter:
    """RoboLab scene-gen compatible input adapter for isolated SceneSmith."""

    def __init__(
        self,
        command: list[str] | tuple[str, ...] | None = None,
        asset_catalog: Path | None = None,
        asset_index: Path | None = None,
        timeout_s: int | None = None,
    ) -> None:
        self.asset_catalog: Path | None
        if command is None:
            settings = SceneSmithSettings.from_env()
            self.command = list(settings.command)
            self.asset_catalog = asset_catalog or settings.asset_catalog
            self.asset_index = asset_index or settings.asset_index
            self.timeout_s = timeout_s or settings.timeout_s
        else:
            self.command = list(command)
            self.asset_catalog = asset_catalog
            self.asset_index = asset_index
            self.timeout_s = timeout_s or 14_400

    def version(self) -> str:
        return SCENESMITH_COMMIT

    def author(
        self,
        scene: RoboLabSceneRequest,
        output_dir: Path,
        *,
        context: dict[str, Any] | None = None,
    ) -> Path:
        if not self.command:
            raise NotConfiguredError("SceneSmith command is not configured")
        fresh_scene = os.environ.get("RHG_FRESH_SCENE", "0").casefold() in {
            "1",
            "true",
            "yes",
        }
        reuse_from = None if fresh_scene else os.environ.get("RHG_SCENESMITH_REUSE_FROM")
        if reuse_from:
            source = Path(reuse_from).resolve()
            if not source.is_dir():
                raise NotADirectoryError(source)
            # A private copy is required because deterministic post-processing
            # rewrites USD/state files.  Symlinks or hardlinks would mutate the
            # accepted parent checkpoint.  copytree preserves sparse metadata
            # and is local-I/O only (no API/model work).
            shutil.copytree(source, output_dir, dirs_exist_ok=True, symlinks=True)
        output_dir.mkdir(parents=True, exist_ok=True)
        request = output_dir / "scene_request.json"
        atomic_write_text(request, scene.model_dump_json(indent=2, exclude_none=True))
        command = [*self.command, "--request", str(request), "--output", str(output_dir)]
        if os.environ.get("RHG_COMPOSED_PREVIEW", "0").casefold() in {"1", "true", "yes"}:
            # The outer orchestrator renders root.usda after robot composition.
            # Rendering the worker-only scene here would be overwritten and
            # doubles the 96-frame preview cost.
            command.append("--no-preview")
        start_stage = os.environ.get("RHG_SCENESMITH_START_STAGE")
        resume_from = os.environ.get("RHG_SCENESMITH_RESUME_FROM")
        if start_stage:
            command.extend(["--start-stage", start_stage])
        if resume_from:
            command.extend(["--resume-from", resume_from])
        if not fresh_scene and (
            reuse_from or os.environ.get("RHG_SCENESMITH_REUSE_UPSTREAM", "0").casefold() in {
            "1",
            "true",
            "yes",
            }
        ):
            command.append("--reuse-upstream")
        if context is not None:
            context_path = output_dir / "scene_context.json"
            atomic_write_text(context_path, json.dumps(context, indent=2, sort_keys=True))
            command.extend(["--context", str(context_path)])
        if self.asset_index is not None:
            if not self.asset_index.is_file():
                raise FileNotFoundError(self.asset_index)
            command.extend(["--asset-index", str(self.asset_index.resolve())])
        elif self.asset_catalog is not None:
            if not self.asset_catalog.is_file():
                raise FileNotFoundError(self.asset_catalog)
            command.extend(["--asset-catalog", str(self.asset_catalog.resolve())])
        result = _run_isolated(command, self.timeout_s)
        if (
            result.returncode != 0
            and "--no-preview" in command
            and "unrecognized arguments: --no-preview" in result.stderr
        ):
            # ``RHG_COMPOSED_PREVIEW`` is an execution optimization, not part of
            # the public worker contract. Older/custom workers must remain valid.
            command.remove("--no-preview")
            result = _run_isolated(command, self.timeout_s)
        manifest = output_dir / "stage_manifest.json"
        if result.returncode != 0:
            raise RuntimeError(f"SceneSmith failed ({result.returncode}): {result.stderr[-2000:]}")
        if not manifest.exists():
            raise RuntimeError("SceneSmith did not produce stage_manifest.json")
        json.loads(manifest.read_text(encoding="utf-8"))
        return manifest