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