| """ProcTHOR/AI2-THOR rollout wrapper — generate one episode end-to-end. |
| |
| Lifecycle: |
| eng = ProcTHOREngine(width=512, height=512, fov=90, device=3) |
| eng.start() # spins up CloudRendering controller |
| for ep_idx in range(N): |
| ep = eng.run_one(seed=ep_idx) # returns EpisodeRecord (schema.EpisodeRecord) |
| write_episode(ep, ...) |
| eng.stop() |
| |
| `run_one` does: |
| 1) Generate procthor house |
| 2) Pick start position + a reachable goal object |
| 3) GetShortestPath → list of waypoints |
| 4) Walk the path. At each step: |
| a) Take an action (forward / left / right) chosen to follow the path |
| b) Record RGB + depth + agent pose |
| c) Record visible objects with projected (u, v) |
| d) Compute waypoint_uv (path[t + lookahead] projected to FOV) |
| e) Compute goal_uv (goal centroid projected) |
| f) Generate QA pairs |
| g) Sample an action chunk (next K poses → body-frame vels) |
| 5) Segment actions → phases |
| 6) Build PhaseFacts per phase → render subcommands |
| 7) Return EpisodeRecord |
| """ |
| from __future__ import annotations |
| import math |
| import random |
| import time |
| from pathlib import Path |
| from typing import Dict, List, Optional, Tuple |
|
|
| import numpy as np |
|
|
| from .schema import StepRecord, EpisodeRecord |
| from .projection import CameraIntrinsics, CameraPose, project_point, project_points_batch |
| from .phase_segment import segment_actions, FORWARD, LEFT, RIGHT, STOP |
| from .subcommands import PhaseFacts, render_episode, stitch_instruction |
| from .descriptions import pick_canonical, _type_to_noun |
| from . import qa as qa_mod |
|
|
|
|
| |
| |
| |
|
|
| class ProcTHOREngine: |
| def __init__(self, |
| width: int = 512, height: int = 512, |
| fov_vertical_deg: float = 90, |
| device_id: int = 0, |
| quality: str = "Low", |
| grid_size: float = 0.25, |
| horizon: float = 0.0, |
| split: str = "train", |
| frames_root: Optional[str] = None, |
| save_depth: bool = False): |
| self.width = width |
| self.height = height |
| self.fov = fov_vertical_deg |
| self.device_id = device_id |
| self.quality = quality |
| self.grid_size = grid_size |
| self.horizon = horizon |
| self.split = split |
| self.frames_root = frames_root |
| self.save_depth = save_depth |
| self.controller = None |
| self.intr = CameraIntrinsics(width, height, fov_vertical_deg) |
| self._hg = None |
|
|
| |
| def start(self): |
| from ai2thor.controller import Controller |
| from procthor.generation import HouseGenerator, PROCTHOR10K_ROOM_SPEC_SAMPLER |
| from procthor.constants import PROCTHOR_INITIALIZATION |
| |
| |
| |
| |
| self.controller = Controller( |
| platform="CloudRendering", |
| width=self.width, height=self.height, |
| fieldOfView=self.fov, |
| quality=self.quality, |
| renderDepthImage=True, |
| renderInstanceSegmentation=True, |
| gridSize=self.grid_size, |
| visibilityDistance=10, |
| **PROCTHOR_INITIALIZATION, |
| ) |
| self._hg = HouseGenerator(split=self.split, seed=0, controller=self.controller, |
| room_spec_sampler=PROCTHOR10K_ROOM_SPEC_SAMPLER) |
|
|
| def stop(self): |
| if self.controller is not None: |
| try: self.controller.stop() |
| except Exception: pass |
| self.controller = None |
|
|
| |
| def run_one(self, |
| episode_idx: int, |
| house_seed: int, |
| max_steps: int = 60, |
| lookahead: int = 5, |
| k_chunk: int = 10, |
| action_chunk_dt_s: float = 0.1, |
| rng_seed: Optional[int] = None |
| ) -> Optional[EpisodeRecord]: |
| """One episode end-to-end. Returns None if the rollout fails (e.g. no path).""" |
| c = self.controller |
| rng = random.Random(rng_seed if rng_seed is not None else episode_idx) |
| self._current_episode_id = f"procthor_{episode_idx:07d}" |
|
|
| |
| c.reset(scene="Procedural") |
| house, _ = self._hg.sample() |
| if hasattr(house, "data"): |
| house_dict = house.data |
| elif hasattr(house, "to_house_dict"): |
| house_dict = house.to_house_dict() |
| else: |
| house_dict = house |
| ev = c.step(action="CreateHouse", house=house_dict) |
| if not ev.metadata.get("lastActionSuccess", False): |
| print(f" [run_one ep{episode_idx}] CreateHouse failed: " |
| f"{ev.metadata.get('errorMessage', '')[:120]}", flush=True) |
| return None |
|
|
| |
| agent_meta = house_dict.get("metadata", {}).get("agent", {}) |
| spawn_pos = agent_meta.get("position", {"x": 0, "y": 0.9, "z": 0}) |
| c.step(action="Teleport", |
| position=spawn_pos, |
| rotation=agent_meta.get("rotation", dict(x=0, y=0, z=0)), |
| horizon=agent_meta.get("horizon", self.horizon)) |
| positions = c.step(action="GetReachablePositions").metadata.get("actionReturn", []) |
| if not positions: |
| self._diag = "no_reachable"; return None |
|
|
| |
| |
| |
| |
| start_pos = None |
| goal_obj = None |
| path = [] |
| for attempt in range(12): |
| sp = rng.choice(positions) |
| c.step(action="Teleport", |
| position=sp, |
| rotation=dict(x=0, y=rng.choice([0, 90, 180, 270]), z=0), |
| horizon=self.horizon) |
| ev = c.step(action="Pass") |
| cand_goal = self._pick_goal_object( |
| ev.metadata.get("objects", []), sp, rng, min_dist=2.5) |
| if cand_goal is None: continue |
| cand_path = self._get_path(sp, cand_goal["position"], cand_goal["objectId"]) |
| if cand_path and len(cand_path) >= 3: |
| start_pos = sp; goal_obj = cand_goal; path = cand_path |
| break |
| if start_pos is None: |
| self._diag = "no_pathable_start_goal_pair"; return None |
| goal_pos = goal_obj["position"] |
|
|
| |
| steps: List[StepRecord] = [] |
| actions: List[int] = [] |
| path_idx = 1 |
| for t in range(max_steps): |
| ev = c.step(action="Pass") |
| agent = ev.metadata["agent"] |
| pose_xyz = [agent["position"]["x"], agent["position"]["y"], agent["position"]["z"]] |
| yaw = agent["rotation"]["y"] |
| pitch = ev.metadata.get("cameraHorizon", self.horizon) |
|
|
| |
| if path_idx >= len(path): |
| action_id = STOP |
| else: |
| tgt = path[path_idx] |
| action_id = self._next_action_toward(pose_xyz, yaw, tgt) |
|
|
| actions.append(action_id) |
|
|
| |
| self._record_step(t, action_id, ev, pose_xyz, yaw, pitch, |
| goal_obj, path, path_idx, lookahead, steps, rng) |
|
|
| |
| if action_id == STOP: break |
| cmd = {1: "MoveAhead", 2: "RotateLeft", 3: "RotateRight"}[action_id] |
| c.step(action=cmd) |
|
|
| |
| if path_idx < len(path): |
| tgt = path[path_idx] |
| d = math.hypot(tgt[0] - pose_xyz[0], tgt[2] - pose_xyz[2]) |
| if d < self.grid_size * 1.5: |
| path_idx += 1 |
|
|
| |
| if actions and actions[-1] != STOP: |
| actions.append(STOP) |
|
|
| |
| spans, kinds = segment_actions(actions) |
|
|
| |
| phase_facts = self._build_phase_facts( |
| spans, kinds, actions, steps, goal_obj, path, rng) |
| subs = render_episode(phase_facts, rng) |
| instruction = stitch_instruction(subs) |
|
|
| |
| self._fill_action_chunks(steps, k_chunk, action_chunk_dt_s) |
|
|
| |
| return EpisodeRecord( |
| episode_id=f"procthor_{episode_idx:07d}", |
| house_seed=house_seed, |
| goal_object=goal_obj["objectId"], |
| instruction=instruction, |
| subcommands=subs, |
| phase_spans=[list(s) for s in spans], |
| phase_kinds=kinds, |
| actions=actions, |
| steps=steps, |
| camera_intrinsics=self.intr.as_dict(), |
| video_dir="", |
| meta={ |
| "goal_object_type": goal_obj.get("objectType", ""), |
| "goal_pos": goal_pos, |
| "start_pos": [start_pos["x"], start_pos["y"], start_pos["z"]], |
| "path_len_m": self._path_len(path), |
| "n_steps": len(actions), |
| }, |
| ) |
|
|
| |
| |
| |
| def _pick_goal_object(self, objects: List[Dict], start_pos, rng, min_dist: float = 1.0): |
| """Pick a reasonable goal: salient object at least `min_dist` m from start.""" |
| SKIP = {"Floor", "Wall", "Ceiling", "Window", "Door", "Doorway", |
| "Doorframe", "RoomDecal", ""} |
| cand = [] |
| for o in objects: |
| if not o.get("position"): continue |
| d = math.hypot(o["position"]["x"] - start_pos["x"], |
| o["position"]["z"] - start_pos["z"]) |
| if d < min_dist: continue |
| ty = o.get("objectType", "") |
| if ty in SKIP: continue |
| cand.append(o) |
| if not cand: return None |
| return rng.choice(cand) |
|
|
| def _get_path(self, start_pos, goal_pos, goal_object_id) -> List[Tuple[float, float, float]]: |
| """Use AI2-THOR's GetShortestPath to find a discrete path. Returns list of (x,y,z).""" |
| try: |
| ev = self.controller.step( |
| action="GetShortestPath", |
| objectId=goal_object_id, |
| position=start_pos, |
| ) |
| corners = ev.metadata.get("actionReturn", {}).get("corners", []) |
| except Exception: |
| corners = [] |
| out = [] |
| for c in corners: |
| out.append((c["x"], c["y"], c["z"])) |
| return out |
|
|
| def _path_len(self, path): |
| d = 0.0 |
| for i in range(1, len(path)): |
| dx = path[i][0] - path[i-1][0] |
| dz = path[i][2] - path[i-1][2] |
| d += math.hypot(dx, dz) |
| return d |
|
|
| def _next_action_toward(self, pose_xyz, yaw_deg, tgt) -> int: |
| """Choose between MoveAhead / RotateLeft / RotateRight to head toward `tgt`.""" |
| dx = tgt[0] - pose_xyz[0] |
| dz = tgt[2] - pose_xyz[2] |
| |
| target_yaw = (math.degrees(math.atan2(dx, dz)) + 360) % 360 |
| |
| delta = ((target_yaw - yaw_deg + 540) % 360) - 180 |
| if abs(delta) < 15: return FORWARD |
| return RIGHT if delta > 0 else LEFT |
|
|
| def _record_step(self, t, action_id, ev, pose_xyz, yaw, pitch, |
| goal_obj, path, path_idx, lookahead, steps, rng): |
| |
| |
| |
| cam = CameraPose(x=pose_xyz[0], y=pose_xyz[1] + 0.675, z=pose_xyz[2], |
| yaw_deg=yaw + 180.0, pitch_deg=pitch) |
| |
| wp_idx = min(path_idx + max(0, lookahead - 1), len(path) - 1) |
| wp = path[wp_idx] |
| wu, wv, wd = project_point(np.array(wp), cam, self.intr) |
| waypoint_uv = [wu, wv] if wu is not None else None |
|
|
| |
| gpos = goal_obj["position"] |
| gu, gv, gd = project_point( |
| np.array([gpos["x"], gpos["y"], gpos["z"]]), cam, self.intr) |
| goal_uv = [gu, gv] if gu is not None else None |
|
|
| |
| SKIP_TYPES = {"Floor", "Wall", "Ceiling", "Window", "Door", "Doorway", |
| "Doorframe", "RoomDecal", ""} |
| vis_objs = [] |
| for o in ev.metadata.get("objects", []): |
| if not o.get("visible", False): continue |
| ty = o.get("objectType", "") |
| if ty in SKIP_TYPES: continue |
| p = o["position"] |
| u, v, d = project_point(np.array([p["x"], p["y"], p["z"]]), cam, self.intr) |
| if u is None: continue |
| vis_objs.append({ |
| "name": o.get("name", ""), |
| "object_type": ty, |
| "uv": [u, v], |
| "depth_m": d, |
| "pos_3d": [p["x"], p["y"], p["z"]], |
| "salientMaterials": o.get("salientMaterials", []), |
| "mainColor": o.get("color", o.get("mainColor", None)), |
| "roomType": o.get("roomType", None), |
| }) |
|
|
| |
| if self.frames_root is not None: |
| from PIL import Image |
| from pathlib import Path |
| ep_dir = Path(self.frames_root) / self._current_episode_id / "rgb" |
| ep_dir.mkdir(parents=True, exist_ok=True) |
| frame = ev.frame |
| if frame is not None: |
| Image.fromarray(frame).save(ep_dir / f"{t:05d}.jpg", quality=85) |
| if self.save_depth and ev.depth_frame is not None: |
| d_dir = Path(self.frames_root) / self._current_episode_id / "depth" |
| d_dir.mkdir(parents=True, exist_ok=True) |
| np.save(d_dir / f"{t:05d}.npy", ev.depth_frame.astype(np.float32)) |
|
|
| |
| qa_pairs = qa_mod.for_step( |
| visible_objects=vis_objs, |
| goal_object=goal_obj, |
| goal_uv=goal_uv, |
| intrinsics_w=self.intr.width, |
| intrinsics_h=self.intr.height, |
| next_action=action_id, |
| rng=rng, |
| ) |
|
|
| steps.append(StepRecord( |
| t=t, action=action_id, pose=[*pose_xyz, 0.0, yaw, pitch], |
| visible_objects=vis_objs, |
| waypoint_uv=waypoint_uv, |
| goal_uv=goal_uv, |
| qa_pairs=qa_pairs, |
| )) |
|
|
| def _fill_action_chunks(self, steps: List[StepRecord], k: int, dt_s: float): |
| """For each step t, compute body-frame [vx, vy, ωz] chunks over t..t+k. |
| |
| Currently writes the chunks into a sibling list (returned via the EpisodeRecord |
| wrap by the caller); attached here as a `.chunk` attribute for convenience. |
| """ |
| N = len(steps) |
| for t in range(N): |
| chunk = [] |
| for j in range(k): |
| tj = t + j; tj_next = t + j + 1 |
| if tj_next >= N: |
| chunk.append([0.0, 0.0, 0.0]) |
| continue |
| p0 = steps[tj].pose; p1 = steps[tj_next].pose |
| dx_w = p1[0] - p0[0]; dz_w = p1[2] - p0[2] |
| yaw_rad = math.radians(p0[4]) |
| |
| vx_body = (dx_w * math.sin(yaw_rad) + dz_w * math.cos(yaw_rad)) / dt_s |
| vy_body = (dx_w * math.cos(yaw_rad) - dz_w * math.sin(yaw_rad)) / dt_s |
| dyaw = (p1[4] - p0[4] + 540) % 360 - 180 |
| wz = math.radians(dyaw) / dt_s |
| chunk.append([vx_body, vy_body, wz]) |
| steps[t].__dict__["action_chunk"] = chunk |
|
|
| def _build_phase_facts(self, spans, kinds, actions, steps, goal_obj, |
| path, rng) -> List[PhaseFacts]: |
| facts: List[PhaseFacts] = [] |
| for i, ((s, e), k) in enumerate(zip(spans, kinds)): |
| is_final = (i == len(spans) - 1) |
| |
| seen = {} |
| for t in range(s, min(e, len(steps))): |
| for o in steps[t].visible_objects: |
| ty = o.get("object_type", "") |
| if ty in ("Floor", "Wall", "Ceiling", "Window", ""): continue |
| nm = o["name"] |
| if nm not in seen: seen[nm] = o |
| |
| seen_l = sorted(seen.values(), key=lambda o: o.get("depth_m", 1e9)) |
| landmarks_passed = [pick_canonical(o) for o in seen_l[:3]] |
|
|
| landmark_at_turn = None |
| if k in ("left", "right") and seen_l: |
| landmark_at_turn = pick_canonical(seen_l[0]) |
|
|
| target_desc = None |
| next_room = None |
| if is_final: |
| target_desc = pick_canonical(goal_obj) |
| next_room = (goal_obj.get("roomType", "") or "").replace("_", " ").lower() or None |
|
|
| facts.append(PhaseFacts( |
| kind=k, |
| n_steps=e - s, |
| length_m=0.0, |
| landmarks_passed=landmarks_passed, |
| landmark_at_turn=landmark_at_turn, |
| is_final_phase=is_final, |
| target_description=target_desc, |
| next_room=next_room, |
| actions=actions[s:e], |
| )) |
| return facts |
|
|