File size: 4,216 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
from __future__ import annotations

import os
from pathlib import Path

import yaml  # type: ignore[import-untyped]

from packages.adapters.scenesmith import (
    RoboLabSceneObject,
    RoboLabScenePredicate,
    RoboLabSceneRequest,
)
from packages.schemas.models import PredicateSpec, TaskEntity, TaskSpec


class SceneRequestCompiler:
    """Compile simulator-independent task entities into the RoboLab scene-gen wire format."""

    def __init__(self, policy_path: Path | None = None) -> None:
        declared = policy_path or Path(
            os.environ.get("RHG_SCENE_COMPILER_POLICY", "configs/scene_generation/compiler_v1.yaml")
        )
        if not declared.is_absolute() and not declared.is_file():
            declared = Path(__file__).resolve().parents[2] / declared
        payload = yaml.safe_load(declared.read_text(encoding="utf-8"))
        placement = payload["placement"]
        self.floor_mounted_categories = set(placement["floor_mounted_categories"])
        self.floor_mounted_category_markers = tuple(placement["floor_mounted_category_markers"])

    def compile(self, task: TaskSpec) -> RoboLabSceneRequest:
        physical_entities = [
            entity
            for entity in task.entities
            if entity.role not in {"REGION", "ROBOT"}
            and "procedural_geometry" not in entity.attributes
        ]
        if not physical_entities:
            raise ValueError("SceneSmith requires at least one physical task entity")
        objects = [RoboLabSceneObject(name=entity.entity_id) for entity in physical_entities]
        known = {entity.entity_id for entity in physical_entities}
        predicates: list[RoboLabScenePredicate] = []
        seen_predicates: set[str] = set()
        placed: set[str] = set()
        for predicate in task.initial_predicates:
            compiled = self._compile_predicate(predicate, known)
            if compiled is not None:
                key = compiled.model_dump_json(exclude_none=True)
                if key not in seen_predicates:
                    predicates.append(compiled)
                    seen_predicates.add(key)
                placed.update(compiled.target_objects())
        for entity in physical_entities:
            if entity.entity_id not in placed:
                predicates.append(self._default_placement(entity))
        return RoboLabSceneRequest(objects=objects, predicates=predicates)

    @staticmethod
    def _compile_predicate(
        predicate: PredicateSpec, known: set[str]
    ) -> RoboLabScenePredicate | None:
        if predicate.subject not in known:
            return None
        support_relation = str(predicate.params.get("support_relation", "")).casefold()
        if support_relation in {"false", "none", "not_supported", "unsupported"}:
            return None
        if predicate.name in {"on", "supported_by"} and predicate.object in known:
            return RoboLabScenePredicate(
                type="place-on", object=predicate.subject, support=predicate.object
            )
        if predicate.name == "inside" and predicate.object in known:
            return RoboLabScenePredicate(
                type="place-in", objects=[predicate.subject], container=predicate.object
            )
        if predicate.name == "near" and predicate.object in known:
            return RoboLabScenePredicate(
                type="front-of", object=predicate.subject, reference=predicate.object
            )
        return None

    def _default_placement(self, entity: TaskEntity) -> RoboLabScenePredicate:
        mount = str(entity.attributes.get("mount", "")).upper()
        floor_mounted = entity.attributes.get("floor_mounted") is True
        category = entity.category.casefold().replace("-", "_").replace(" ", "_")
        if (
            entity.role == "BACKGROUND"
            or mount == "FLOOR"
            or floor_mounted
            or category in self.floor_mounted_categories
            or any(marker in category for marker in self.floor_mounted_category_markers)
        ):
            return RoboLabScenePredicate(type="place-on-base", object=entity.entity_id)
        return RoboLabScenePredicate(type="place-anywhere", object=entity.entity_id)