"""Public scene input contract for the portable whole-house generator. This module is deliberately dependency-free. It turns a small, stable scene description into the manifest/request pair consumed by the existing native pipeline. Asset IDs are provenance supplied by the caller; this layer never invents an asset to make a request appear ready. """ from __future__ import annotations import copy import json import math import re from pathlib import Path from typing import Any SCHEMA = "rhg.scene-spec.v1" class SceneSpecError(ValueError): """Raised when a public scene description cannot be compiled safely.""" _ROOM_ALIASES = { "living": ("living_room", "客厅", "起居室", "living room", "family room"), "kitchen": ("kitchen", "厨房"), "dining": ("dining_room", "餐厅", "dining room"), "bedroom": ("bedroom", "卧室", "主卧", "次卧"), "bathroom": ("bathroom", "卫生间", "厕所", "浴室", "bath room"), "study": ("study", "书房", "office", "办公室"), "hallway": ("hallway", "走廊", "过道", "hall"), "balcony": ("balcony", "阳台"), } _ENTITY_ALIASES = { "sofa": ("sofa", "couch", "沙发"), "television": ("television", "tv", "电视", "电视机"), "coffee_table": ("coffee table", "茶几"), "dining_table": ("dining table", "餐桌", "饭桌"), "kitchen_counter": ("kitchen counter", "counter", "料理台", "厨房台面"), "bed": ("bed", "床"), "desk": ("desk", "书桌", "办公桌"), "toilet": ("toilet", "马桶"), "sink": ("sink", "水槽", "洗手池"), "refrigerator": ("refrigerator", "fridge", "冰箱"), "plant": ("plant", "盆栽", "植物"), "lamp": ("lamp", "台灯", "落地灯"), "apple": ("apple", "苹果"), "bottle": ("bottle", "瓶子", "水瓶"), "cup": ("cup", "杯子", "水杯"), "plate": ("plate", "盘子"), "bowl": ("bowl", "碗"), } _DEFAULT_DIMENSIONS = { "sofa": [2.0, 0.9, 0.85], "television": [1.4, 0.15, 0.85], "coffee_table": [1.1, 0.6, 0.42], "dining_table": [1.6, 0.9, 0.75], "kitchen_counter": [2.0, 0.65, 0.9], "bed": [2.0, 1.6, 0.65], "desk": [1.2, 0.65, 0.75], "toilet": [0.7, 0.7, 0.8], "sink": [0.7, 0.55, 0.85], "refrigerator": [0.8, 0.75, 1.8], "plant": [0.35, 0.35, 1.0], "lamp": [0.3, 0.3, 1.2], "apple": [0.08, 0.08, 0.08], "bottle": [0.08, 0.08, 0.28], "cup": [0.09, 0.09, 0.12], "plate": [0.25, 0.25, 0.03], "bowl": [0.2, 0.2, 0.1], } _ROOM_DEFAULT_SIZE = { "living_room": [5.0, 4.0, 2.8], "kitchen": [3.5, 3.0, 2.8], "dining_room": [3.5, 3.0, 2.8], "bedroom": [4.0, 3.5, 2.8], "bathroom": [2.4, 2.2, 2.8], "study": [3.5, 3.0, 2.8], "hallway": [2.5, 1.8, 2.8], "balcony": [3.0, 1.8, 2.8], "indoor_room": [5.0, 4.0, 2.8], } def _text(value: Any, name: str) -> str: if not isinstance(value, str) or not value.strip(): raise SceneSpecError(f"{name} must be a non-empty string") return value.strip() def _finite(value: Any, name: str) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): raise SceneSpecError(f"{name} must be a finite number") return float(value) def _vector(value: Any, count: int, name: str, *, positive: bool = False) -> list[float]: if not isinstance(value, (list, tuple)) or len(value) != count: raise SceneSpecError(f"{name} must contain {count} numbers") result = [_finite(item, name) for item in value] if positive and any(item <= 0 for item in result): raise SceneSpecError(f"{name} must be positive") return result def _slug(value: str) -> str: value = re.sub(r"[^a-z0-9]+", "_", value.casefold()).strip("_") return value or "room" def _first_alias(text: str, aliases: dict[str, tuple[str, ...]]) -> str | None: lowered = text.casefold() matches = [] for key, values in aliases.items(): for value in values: index = lowered.find(value.casefold()) if index >= 0: matches.append((index, -len(value), key)) return min(matches)[2] if matches else None def _room_type(value: str) -> str: direct = { "living": "living_room", "dining": "dining_room", "bedroom": "bedroom", "bathroom": "bathroom", "study": "study", "kitchen": "kitchen", "hallway": "hallway", "balcony": "balcony", } if value.casefold() in direct: return direct[value.casefold()] key = _first_alias(value, _ROOM_ALIASES) if key is None: return _slug(value) return { "living": "living_room", "dining": "dining_room", }.get(key, key) def _entity_category(value: str) -> str | None: return _first_alias(value, _ENTITY_ALIASES) def _pack_rooms(rooms: list[dict[str, Any]]) -> list[dict[str, Any]]: cursor_x = 0.0 result = [] for row in rooms: item = copy.deepcopy(row) dimensions = item.get("dimensions_m") or _ROOM_DEFAULT_SIZE.get( item["room_type"], _ROOM_DEFAULT_SIZE["indoor_room"] ) dimensions = _vector(dimensions, 3, f"rooms[{item['room_id']}].dimensions_m", positive=True) item["dimensions_m"] = dimensions if item.get("bounds_m") is None: item["bounds_m"] = [cursor_x, 0.0, cursor_x + dimensions[0], dimensions[1]] else: item["bounds_m"] = _vector(item["bounds_m"], 4, f"rooms[{item['room_id']}].bounds_m") x0, y0, x1, y1 = item["bounds_m"] if x1 <= x0 or y1 <= y0: raise SceneSpecError(f"room {item['room_id']} has invalid bounds_m") # Adjacent generated rooms share a boundary so a declared connection # can become a real portal. A caller can provide explicit bounds when # a gap or a non-linear floor plan is required. cursor_x = max(cursor_x, x1) result.append(item) return result def _shared_door(room_a: dict[str, Any], room_b: dict[str, Any], connection: dict[str, Any], index: int) -> dict[str, Any]: ax0, ay0, ax1, ay1 = room_a["bounds_m"] bx0, by0, bx1, by1 = room_b["bounds_m"] width = float(connection.get("clear_width_m", 0.9)) if abs(ax1 - bx0) <= 1e-6 or abs(bx1 - ax0) <= 1e-6: line = ax1 if abs(ax1 - bx0) <= 1e-6 else bx1 low, high = max(ay0, by0), min(ay1, by1) if high <= low: raise SceneSpecError(f"rooms {room_a['room_id']} and {room_b['room_id']} do not share a boundary") mid = (low + high) / 2.0 interval = [max(low, mid - width / 2.0), min(high, mid + width / 2.0)] orientation = "V" elif abs(ay1 - by0) <= 1e-6 or abs(by1 - ay0) <= 1e-6: line = ay1 if abs(ay1 - by0) <= 1e-6 else by1 low, high = max(ax0, bx0), min(ax1, bx1) if high <= low: raise SceneSpecError(f"rooms {room_a['room_id']} and {room_b['room_id']} do not share a boundary") mid = (low + high) / 2.0 interval = [max(low, mid - width / 2.0), min(high, mid + width / 2.0)] orientation = "H" else: raise SceneSpecError(f"rooms {room_a['room_id']} and {room_b['room_id']} are not adjacent") return { "door_id": connection.get("portal_id", f"portal_{index + 1}"), "room_ids": [room_a["room_id"], room_b["room_id"]], "wall_orientation": orientation, "wall_line_m": line, "door_interval_m": interval, "clear_width_m": width, "clear_height_m": float(connection.get("clear_height_m", 2.1)), "hinge_side": connection.get("hinge_side", "left"), "swing_room_id": connection.get("swing_room_id", room_a["room_id"]), "initial_open_fraction": float(connection.get("initial_open_fraction", 1.0)), } def normalize_scene_spec(raw: dict[str, Any]) -> dict[str, Any]: if not isinstance(raw, dict): raise SceneSpecError("scene input must be an object") data = copy.deepcopy(raw) data.setdefault("schema", SCHEMA) if data["schema"] != SCHEMA: raise SceneSpecError(f"unsupported scene schema: {data['schema']}") seed = data.get("seed", 0) if isinstance(seed, bool) or not isinstance(seed, int): raise SceneSpecError("seed must be an integer") room_rows = data.get("rooms") if not isinstance(room_rows, list) or not room_rows: raise SceneSpecError("rooms must be a non-empty list") rooms = [] room_ids = set() for index, row in enumerate(room_rows): if not isinstance(row, dict): raise SceneSpecError(f"rooms[{index}] must be an object") room_id = _text(row.get("room_id"), f"rooms[{index}].room_id") if room_id in room_ids: raise SceneSpecError(f"duplicate room_id: {room_id}") room_ids.add(room_id) rooms.append({ "room_id": room_id, "room_type": _room_type(_text(row.get("room_type", room_id), f"rooms[{index}].room_type")), "dimensions_m": row.get("dimensions_m"), "bounds_m": row.get("bounds_m"), }) rooms = _pack_rooms(rooms) room_by_id = {row["room_id"]: row for row in rooms} connections = [] for index, row in enumerate(data.get("connections", [])): if not isinstance(row, dict): raise SceneSpecError(f"connections[{index}] must be an object") room_ids = row.get("room_ids") or [] room_a = _text(row.get("room_a_id", room_ids[0] if len(room_ids) > 0 else None), f"connections[{index}].room_a_id") room_b = _text(row.get("room_b_id", room_ids[1] if len(room_ids) > 1 else None), f"connections[{index}].room_b_id") if room_a not in room_by_id or room_b not in room_by_id or room_a == room_b: raise SceneSpecError(f"connection {index} references invalid rooms") connections.append(_shared_door(room_by_id[room_a], room_by_id[room_b], row, index)) entity_rows = data.get("entities", []) if not isinstance(entity_rows, list): raise SceneSpecError("entities must be a list") task_text = data.get("task_text", "") if not isinstance(task_text, str): raise SceneSpecError("task_text must be a string") entities = [] entity_ids = set() for index, row in enumerate(entity_rows): if not isinstance(row, dict): raise SceneSpecError(f"entities[{index}] must be an object") entity_id = _text(row.get("entity_id"), f"entities[{index}].entity_id") room_id = _text(row.get("room_id"), f"entities[{index}].room_id") category = _slug(_text(row.get("category"), f"entities[{index}].category")) if entity_id in entity_ids: raise SceneSpecError(f"duplicate entity_id: {entity_id}") if room_id not in room_by_id: raise SceneSpecError(f"entity {entity_id} references unknown room {room_id}") entity_ids.add(entity_id) parent = row.get("support_entity_id", row.get("supported_by_entity_id")) candidates = row.get("candidate_asset_ids", []) if not isinstance(candidates, list) or any( not isinstance(item, str) or not item.strip() for item in candidates ): raise SceneSpecError(f"entities[{index}].candidate_asset_ids must be a string list") item = { "entity_id": entity_id, "room_id": room_id, "category": category, "role": row.get("role", category), "dimensions_m": _vector( row.get("dimensions_m", _DEFAULT_DIMENSIONS.get(category, [0.5, 0.5, 0.5])), 3, f"entities[{index}].dimensions_m", positive=True, ), "candidate_asset_ids": list(dict.fromkeys(item.strip() for item in candidates)), } if row.get("asset_id") is not None: item["asset_id"] = _text(row["asset_id"], f"entities[{index}].asset_id") if parent is not None: item["support_entity_id"] = _text(parent, f"entities[{index}].support_entity_id") for key in ("center_xy_m", "yaw_deg", "base_z_m", "asset_query", "placement_hint", "requirements"): if key in row: item[key] = copy.deepcopy(row[key]) entities.append(item) by_id = {row["entity_id"]: row for row in entities} for row in entities: parent = row.get("support_entity_id") if parent is not None: if parent not in by_id: raise SceneSpecError(f"unknown support entity: {parent}") if by_id[parent]["room_id"] != row["room_id"]: raise SceneSpecError(f"cross-room support is not allowed: {row['entity_id']}") tasks = [] for index, row in enumerate(data.get("tasks", [])): if not isinstance(row, dict): raise SceneSpecError(f"tasks[{index}] must be an object") kind = _text(row.get("kind"), f"tasks[{index}].kind") subject = _text(row.get("subject_entity_id"), f"tasks[{index}].subject_entity_id") target = row.get("target_entity_id") if subject not in by_id: raise SceneSpecError(f"unknown task subject: {subject}") if target is not None and target not in by_id: raise SceneSpecError(f"unknown task target: {target}") # Validate known references, but keep caller predicates, parameters, # ordering, provenance and future task fields intact. item = copy.deepcopy(row) item.update({ "kind": kind, "subject_entity_id": subject, "target_entity_id": target, "text": row.get("text"), }) tasks.append(item) return { "schema": SCHEMA, "scene_id": _slug(str(data.get("scene_id", "scene"))), "seed": seed, "source": copy.deepcopy(data.get("source", {})), "description": data.get("description", ""), "task_text": task_text, "rooms": rooms, "connections": connections, "entities": entities, "tasks": tasks, "style": copy.deepcopy(data.get("style", {})), "constraints": copy.deepcopy(data.get("constraints", {})), } def _find_entity(category: str, entities: list[dict[str, Any]]) -> dict[str, Any] | None: return next((row for row in entities if row["category"] == category), None) _RESIDENTIAL_FURNISHING = { "living_room": ("sofa", "coffee_table", "television", "lamp"), "bedroom": ("bed", "wardrobe", "nightstand", "lamp"), "kitchen": ("kitchen_counter", "sink", "refrigerator", "stove", "dining_table", "dining_chair"), "bathroom": ("toilet", "sink", "shower"), } def _entity_mentions(text: str) -> list[tuple[int, int, str]]: aliases = {alias: category for category, values in _ENTITY_ALIASES.items() for alias in values} pattern = "|".join( (r"(? list[str]: # A decimal point belongs to its number, not a sentence boundary. boundary = r"[。!!??;;]|\.(?!\d)" if split_commas: boundary += r"|[,,]" return [part.strip() for part in re.split(boundary, text) if part.strip()] def _initial_support(text: str, entities: list[dict[str, Any]]) -> set[str]: """Read local stative relations; action destinations never set initial support.""" initial_clauses = set() for clause in _text_segments(text, split_commas=True): mentions = _entity_mentions(clause) for index, mention in enumerate(mentions): prefix = clause[mentions[index - 1][1] if index else 0:mention[0]] # In "cup upright on table", upright describes the previous noun. prefix = re.split(r"放在|位于|\bon(?:\s+top\s+of)?\b", prefix, flags=re.IGNORECASE)[-1] suffix = clause[mention[1]:] entity = _find_entity(mention[2], entities) if entity is None: continue for key, pattern in (("upright", r"直立|竖直|\bupright\b"), ("graspable", r"可抓取|可抓握|\bgraspable\b")): if (re.search(pattern, prefix, re.IGNORECASE) or re.match(r"\s*(?:is\s+)?(?:" + pattern + ")", suffix, re.IGNORECASE)): entity.setdefault("requirements", {})[key] = True if re.search(r"把|将|机器人|\brobot\b|\b(?:place|put)\b|放到|放入", clause, re.IGNORECASE): continue for first, second in zip(mentions, mentions[1:]): between = clause[first[1]:second[0]] suffix = clause[second[1]:] if re.match(r"(?:上面?|顶部)", between): parent_category, child_category = first[2], second[2] elif (re.search(r"\bon(?:\s+top\s+of)?\b", between, re.IGNORECASE) or (re.search(r"在|位于", between) and re.match(r"上", suffix))): child_category, parent_category = first[2], second[2] else: continue child, parent = _find_entity(child_category, entities), _find_entity(parent_category, entities) if child is None or parent is None or child is parent: continue child["room_id"] = parent["room_id"] child["support_entity_id"] = parent["entity_id"] initial_clauses.add(clause.strip()) return initial_clauses def _task_measurement(text: str, action: str, units: dict[str, float], name: str) -> float | None: """Read a literal action measurement; missing values remain unresolved.""" match = re.search(r"(?:" + action + r")\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*", text, re.IGNORECASE) if match is None: return None unit_pattern = "|".join(re.escape(unit) for unit in sorted(units, key=len, reverse=True)) unit = re.match(r"(?:" + unit_pattern + r")(?![a-z])", text[match.end():], re.IGNORECASE) if unit is None: raise SceneSpecError(f"{name} requires a supported unit") value = _finite(float(match.group(1)), name) * units[unit.group().casefold()] if value <= 0: raise SceneSpecError(f"{name} must be positive") return value def _robot_task_contract(text: str, entities: list[dict[str, Any]], rooms: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any], str]: """Compile a grasp/lift instruction without inventing execution qualification.""" for segment in _text_segments(text): grasp = re.search(r"抓住|抓取|抓握|\bgrasp\b", segment, re.IGNORECASE) lift = re.search(r"举起|抬起|\blift\b", segment, re.IGNORECASE) if not grasp or not lift: continue subject = _find_entity(_entity_category(segment[grasp.end():]) or "", entities) if subject is None: continue navigation = re.search(r"到达|走到|移动到|\bnavigate\s+to\b|\bapproach\b", segment, re.IGNORECASE) target = (_find_entity(_entity_category(segment[navigation.end():]) or "", entities) if navigation else None) if target is None and subject.get("support_entity_id"): target = next(row for row in entities if row["entity_id"] == subject["support_entity_id"]) start_match = re.search(r"从(.+?)(?:出发|起点)|\bfrom\s+(.+?)(?:,|\bto\b|$)", segment, re.IGNORECASE) start_type = _first_alias(start_match.group() if start_match else "", _ROOM_ALIASES) start_room = next((row["room_id"] for row in rooms if start_type and row["room_type"] == _room_type(start_type)), None) parameters = { "lift_height_m": _task_measurement(segment, r"举起|抬起|\blift\b", { "毫米": 0.001, "mm": 0.001, "厘米": 0.01, "公分": 0.01, "cm": 0.01, "米": 1.0, "m": 1.0, }, "lift_height_m"), "hold_duration_s": _task_measurement(segment, r"保持|维持|\bhold(?:\s+for)?\b", { "秒": 1.0, "s": 1.0, "second": 1.0, "seconds": 1.0, }, "hold_duration_s"), } robot = { "model": None, "footprint_m": None, "reach_m": None, **parameters, "start": {"room_id": start_room, "position_xy_m": None, "yaw_deg": None, "status": "unresolved_until_layout"}, } subject_id = subject["entity_id"] held = {"predicate": "held_by", "subject_entity_id": subject_id, "agent_id": "robot"} near = {"predicate": "near", "agent_id": "robot", "target_entity_id": target["entity_id"] if target else subject_id} initial = [{"predicate": key, "subject_entity_id": subject_id} for key, required in subject.get("requirements", {}).items() if required is True] if subject.get("support_entity_id"): initial.append({"predicate": "supported_by", "subject_entity_id": subject_id, "target_entity_id": subject["support_entity_id"]}) if not any(row["predicate"] == "graspable" for row in initial): initial.append({"predicate": "graspable", "subject_entity_id": subject_id}) steps = [] if navigation: steps.append(("navigate", [{"predicate": "at_start", "agent_id": "robot"}], [near])) steps.extend([ ("grasp", ([near] if navigation else []) + initial, [held]), ("lift", [held], [held, {"predicate": "above_initial_height", "subject_entity_id": subject_id, "min_height_m": parameters["lift_height_m"], "hold_duration_s": parameters["hold_duration_s"]}]), ]) tasks = [] for order, (kind, preconditions, success) in enumerate(steps, 1): tasks.append({ "task_id": f"{kind}_{order}", "kind": kind, "order": order, "agent_id": "robot", "subject_entity_id": subject_id, "target_entity_id": target["entity_id"] if kind == "navigate" and target else None, "depends_on": [tasks[-1]["task_id"]] if tasks else [], "preconditions": copy.deepcopy(preconditions), "success_predicates": copy.deepcopy(success), "parameters": copy.deepcopy(parameters) if kind == "lift" else {}, "text": segment.strip(), }) space = { "navigation": {"required": True, "clearance_m": None}, "docking": {"required": True, "clearance_m": None, "target_entity_id": target["entity_id"] if target else subject_id}, "manipulation": {"required": True, "clearance_m": None, "target_entity_id": subject_id}, } return tasks, {"robot": robot, "robot_space": space}, segment.strip() return [], {}, "" def _furnish_residence(rooms: list[dict[str, Any]], entities: list[dict[str, Any]]) -> dict[str, Any]: required_by_room = {} for room in rooms: categories = _RESIDENTIAL_FURNISHING.get(room["room_type"], ()) required_by_room[room["room_id"]] = list(categories) for category in categories: if any(row["room_id"] == room["room_id"] and row["category"] == category for row in entities): continue entity_id = category if _find_entity(category, entities) is None else f"{room['room_id']}_{category}" entities.append({"entity_id": entity_id, "room_id": room["room_id"], "category": category, "requirements": {"best_effort_furnishing": True}}) return {"profile": "complete_residential", "required_by_room": required_by_room} def parse_text_scene(description: str, *, seed: int = 0, room_inventory: list[dict[str, Any]] | None = None) -> dict[str, Any]: """Parse unchanged text, optionally binding furniture to selected rooms. The caller validates explicit topology constraints before supplying the inventory. Only IDs/types are used here; align_to_shell owns real geometry. """ text = _text(description, "description") room_types = [] for key, aliases in _ROOM_ALIASES.items(): if any(alias.casefold() in text.casefold() for alias in aliases): room_types.append({"room_id": {"living": "living", "dining": "dining"}.get(key, key), "room_type": _room_type(key)}) count_match = re.search(r"([一二两三四五六七八九十]|\d+)\s*室", text) if count_match: # An explicit count replaces the unnumbered bedroom alias. room_types = [row for row in room_types if row["room_type"] != "bedroom"] count_token = count_match.group(1) count = {"一": 1, "二": 2, "两": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9, "十": 10}.get(count_token, int(count_token) if count_token.isdigit() else 1) for index in range(1, count + 1): if not any(row["room_type"] == "bedroom" and row["room_id"] == f"bedroom_{index}" for row in room_types): room_types.append({"room_id": f"bedroom_{index}", "room_type": "bedroom"}) if "厅" in text and not any(row["room_type"] == "living_room" for row in room_types): room_types.append({"room_id": "living", "room_type": "living_room"}) unique_rooms = [] seen_room_ids = set() for room in room_types: if room["room_id"] not in seen_room_ids: unique_rooms.append(room) seen_room_ids.add(room["room_id"]) room_types = unique_rooms if not room_types: room_types = [{"room_id": "room_1", "room_type": "indoor_room"}] entity_rooms = room_types if room_inventory is not None: if not isinstance(room_inventory, list) or not room_inventory: raise SceneSpecError('room_inventory must be a non-empty list') selected_rooms = [] for index, room in enumerate(room_inventory): if not isinstance(room, dict): raise SceneSpecError(f'room_inventory[{index}] must be an object') selected_rooms.append({ 'room_id': _text(room.get('room_id'), f'room_inventory[{index}].room_id'), 'room_type': _room_type(_text(room.get('room_type'), f'room_inventory[{index}].room_type')), }) by_id = {room['room_id']:room for room in selected_rooms} if len(by_id) != len(selected_rooms): raise SceneSpecError('room_inventory contains duplicate room IDs') # This flat parser has no clause-to-bedroom-role binding. Inventory # expansion must not make an explicit secondary/child room silently # refer to the first bedroom. Structured room IDs/purposes bypass this # text-only path and retain their existing alignment semantics. target = re.search( r'主卧|次卧|客卧|儿童房|儿童卧室|' r'第\s*[一二两三四五六七八九十\d]+\s*(?:间)?卧室|' r'(? dict[str, Any]: normalized = normalize_scene_spec(spec) room_by_id = {row["room_id"]: row for row in normalized["rooms"]} doors = [] for index, connection in enumerate(normalized["connections"]): room_a = room_by_id[connection["room_ids"][0]] room_b = room_by_id[connection["room_ids"][1]] doors.append(_shared_door(room_a, room_b, connection, index)) manifest_entities = [] request_entities = [] furniture = [] unresolved = [] all_locked = True for row in normalized["entities"]: entity = { "entity_id": row["entity_id"], "room_id": row["room_id"], "role": row["role"], "category": row["category"], "dimensions_m": row["dimensions_m"], "center_xy_m": row.get("center_xy_m", [ sum(room_by_id[row["room_id"]]["bounds_m"][::2]) / 2.0, sum(room_by_id[row["room_id"]]["bounds_m"][1::2]) / 2.0, ]), "yaw_deg": row.get("yaw_deg", 0.0), "base_z_m": row.get("base_z_m", 0.0), } if row.get("support_entity_id") is not None: entity["support_entity_id"] = row["support_entity_id"] if "requirements" in row: entity["requirements"] = copy.deepcopy(row["requirements"]) if row.get("asset_id") is not None: entity["asset_id"] = row["asset_id"] furniture.append({"entity_id": row["entity_id"], "asset_id": row["asset_id"]}) else: candidates = list(row.get("candidate_asset_ids", [])) all_locked = False if not candidates: unresolved.append(row["entity_id"]) furniture.append({"entity_id": row["entity_id"], "candidate_asset_ids": candidates}) manifest_entities.append(entity) # requested_shell projects real asset geometry. Nominal dimensions and # asset identity belong to the manifest/furniture map, not definitions. definition = {key: copy.deepcopy(entity[key]) for key in ("entity_id", "room_id", "role", "category", "requirements") if key in entity} for source_key, preferred_key in (("center_xy_m", "preferred_center_xy_m"), ("yaw_deg", "preferred_yaw_deg")): if source_key in row: definition[preferred_key] = copy.deepcopy(row[source_key]) if row.get("support_entity_id") is not None: definition.update(supported_by_entity_id=row["support_entity_id"], support_relation="on_top", layout_relation="on_top") request_entities.append(definition) manifest = { "schema": "rhg.scene-manifest.v1", "scene_id": normalized["scene_id"], "seed": normalized["seed"], "source": normalized["source"], "floor_plan": {"rooms": normalized["rooms"], "doors": doors}, "entities": manifest_entities, "style": normalized["style"], } request = { "schema": "rhg.scene_request.v1", "mode": "locked" if all_locked and not unresolved else "pool", "task_kind": "scene_generation", "task_text": normalized["task_text"] or normalized["description"] or normalized["scene_id"], "seed": normalized["seed"], "entities": request_entities, "furniture": furniture, "tasks": copy.deepcopy(normalized["tasks"]), "constraints": copy.deepcopy(normalized["constraints"]), } return { "schema": "rhg.scene-compile-result.v1", "scene_spec": normalized, "manifest": manifest, "request": request, "unresolved_assets": sorted(unresolved), "ready_for_native_generation": not unresolved, } def write_scene_bundle(spec: dict[str, Any], output: str | Path) -> dict[str, Path]: """Write the portable input bundle used by the existing whole-house runner.""" output = Path(output) output.mkdir(parents=True, exist_ok=True) compiled = compile_native_inputs(spec) payloads = { "scene_spec": compiled["scene_spec"], "manifest": compiled["manifest"], "request": compiled["request"], "asset_requirements": { "schema": "rhg.asset-requirements.v1", "ready_for_native_generation": compiled["ready_for_native_generation"], "unresolved_assets": compiled["unresolved_assets"], "entities": [ { "entity_id": row["entity_id"], "category": row["category"], "candidate_asset_ids": list(row.get("candidate_asset_ids", [])), "asset_id": row.get("asset_id"), } for row in compiled["scene_spec"]["entities"] ], }, "compile_result": compiled, "run_config": { "schema": "rhg.frontier-chain-config.v1", "manifest": "manifest.json", "request": "request.json", "geometry_validation": {"enabled": True}, }, } paths = {} for name, payload in payloads.items(): path = output / (name + ".json") path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") paths[name] = path return paths