RoboHome / code /robohome /src /tools /collection /package_scene.py
wentywenty's picture
Verify RoboHome source completeness and document portable workflows
75e20e2 verified
Raw History Blame Contribute Delete
13.2 kB
#!/usr/bin/env python3
import argparse
import hashlib
import json
import math
import re
import shutil
import time
from pathlib import Path
def actual_area_m2(floor_plan) -> float:
"""Sum generated room areas, using rectangular bounds only when absent."""
rooms = floor_plan.get("rooms")
if not isinstance(rooms, list) or not rooms:
raise ValueError("floor_plan.rooms must be a nonempty list")
areas = []
for index, room in enumerate(rooms):
try:
area = room.get("area_m2")
if area is None:
x0, y0, x1, y1 = map(float, room["bounds_m"])
if not all(math.isfinite(v) for v in (x0, y0, x1, y1)) or x1 < x0 or y1 < y0:
raise ValueError("invalid bounds_m")
area = (x1 - x0) * (y1 - y0)
area = float(area)
if not math.isfinite(area) or area < 0:
raise ValueError("area must be nonnegative and finite")
except (AttributeError, KeyError, TypeError, ValueError, OverflowError) as exc:
raise ValueError(f"invalid area for floor_plan.rooms[{index}]: {exc}") from exc
areas.append(area)
try:
return math.fsum(areas)
except OverflowError as exc:
raise ValueError("sum of room areas is not finite") from exc
def area_bin_name(area: float) -> str:
lo = int(area // 10) * 10
return f"{lo:03d}-{lo + 9:03d}m2"
def conversion_target_area_m2(floor_plan):
conversion = floor_plan.get("rplan_conversion") or {}
target = conversion.get("target_area_m2_before_clamp")
if target is None:
target = conversion.get("target_area_m2")
return float(target) if target is not None else None
def sha(p):
h = hashlib.sha256()
with open(p, "rb") as f:
for b in iter(lambda: f.read(1024 * 1024), b""):
h.update(b)
return h.hexdigest()
def _attempt_key(path: Path):
match = re.search(r"attempt_(\d+)", str(path))
return int(match.group(1)) if match else -1
def _resolve_reference(value, result_path, case):
if not isinstance(value, str) or not value:
return None
raw = Path(value).expanduser()
if raw.is_absolute():
return raw.resolve()
for base in (result_path.parent, case):
candidate = (base / raw).resolve()
if candidate.exists():
return candidate
return (result_path.parent / raw).resolve()
def _blend_for_manifest(manifest):
manifest = Path(manifest).resolve()
if not manifest.is_file():
return None
blends = sorted(
p for p in manifest.parent.glob("*.blend")
if p.is_file() and "original_template" not in p.name
)
return blends[0] if blends else None
def _manifest_from_target(target):
target = Path(target).resolve()
if target.is_file():
return target if target.name == "composition_manifest.runtime.json" else None
if not target.is_dir():
return None
exact = target / "generated/fullhome_asset_v16_000/composition_manifest.runtime.json"
if exact.is_file():
return exact
candidates = sorted(
p for p in target.rglob("composition_manifest.runtime.json")
if "generated" in p.parts
)
return candidates[0] if len(candidates) == 1 else None
def _verified_result_manifest(case, result_path):
try:
data = json.loads(result_path.read_text())
except Exception:
return None, None, False
target = _resolve_reference(data.get("generated_manifest"), result_path, case)
manifest = _manifest_from_target(target) if target is not None else None
if manifest is None:
return None, data, False
geometry_ok = data.get("full_geometry_passed") is True or data.get("geometry_passed") is True
if data.get("generation_executed") is False or not geometry_ok or data.get("output_contract_passed") is not True:
return None, data, True
return manifest, data, False
def _final_output_result_paths(final_output):
return (final_output / "chain" / "result.json", final_output / "result.json")
def _selected_scene(manifest, selected_by):
manifest = Path(manifest).resolve()
blend = _blend_for_manifest(manifest)
if blend is None:
return None
return manifest.parent, manifest, blend, selected_by
def find_scene(case, manifest=None):
case = Path(case).resolve()
if manifest is not None:
selected = _selected_scene(Path(manifest), "manifest_arg")
if selected is None:
raise FileNotFoundError("manifest argument has no non-template blend")
return selected
rejected_targets = []
final_output = None
summary = case / "execution_summary.json"
if summary.is_file():
try:
data = json.loads(summary.read_text())
except Exception:
data = {}
final_output = _resolve_reference(data.get("final_output"), summary, case)
summary_ok = data.get("geometry_passed") is True and data.get("output_contract_passed") is True
if summary_ok and final_output is not None:
rejected_result = False
for result_path in _final_output_result_paths(final_output):
if not result_path.is_file():
continue
candidate, _, rejected = _verified_result_manifest(case, result_path)
rejected_result = rejected_result or rejected
if candidate is not None:
selected = _selected_scene(candidate, "chain_result")
if selected is not None:
return selected
if not rejected_result:
candidate = _manifest_from_target(final_output)
if candidate is not None:
selected = _selected_scene(candidate, "execution_summary")
if selected is not None:
return selected
elif final_output is not None:
rejected_targets.append(final_output)
result_paths = []
if final_output is not None:
result_paths.extend(_final_output_result_paths(final_output))
result_paths.append(case / "execution/chain/result.json")
result_paths.extend(sorted(
case.glob("layout_recovery/attempt_*/execution/chain/result.json"),
key=lambda p: (_attempt_key(p), str(p)),
reverse=True,
))
result_paths.append(case / "execution/result.json")
for result_path in sorted(result_paths, key=lambda p: (_attempt_key(p), str(p)), reverse=True):
if not result_path.is_file():
continue
try:
data = json.loads(result_path.read_text())
except Exception:
continue
target = _resolve_reference(data.get("generated_manifest") or data.get("final_output"), result_path, case)
geometry_ok = data.get("full_geometry_passed") is True or data.get("geometry_passed") is True
if data.get("generation_executed") is False or not geometry_ok or data.get("output_contract_passed") is not True:
rejected_targets.append(result_path.parent)
if target is not None:
rejected_targets.append(target)
continue
if target is None:
continue
candidate = _manifest_from_target(target)
if candidate is None:
continue
if any(candidate == rejected or rejected in candidate.parents for rejected in rejected_targets):
continue
selected = _selected_scene(candidate, "chain_result")
if selected is not None:
return selected
roots = []
for pattern in (
"execution/chain/**/generated/fullhome_asset_v16_000/composition_manifest.runtime.json",
"layout_recovery/attempt_*/execution/chain/**/generated/fullhome_asset_v16_000/composition_manifest.runtime.json",
):
roots.extend(case.glob(pattern))
candidates = []
for candidate in roots:
candidate = candidate.resolve()
if any(candidate == rejected or rejected in candidate.parents for rejected in rejected_targets):
continue
selected = _selected_scene(candidate, "glob")
if selected is not None:
candidates.append(selected)
if candidates:
return max(candidates, key=lambda item: (_attempt_key(item[1]), str(item[1])))
raise FileNotFoundError("successful generated blend/manifest not found")
def plan_png(manifest, out):
from PIL import Image, ImageDraw
rooms = manifest.get("floor_plan", {}).get("rooms", [])
bounds = [r.get("bounds_m") for r in rooms if isinstance(r.get("bounds_m"), list) and len(r["bounds_m"]) == 4]
if not bounds:
return None
minx = min(b[0] for b in bounds)
miny = min(b[1] for b in bounds)
maxx = max(b[2] for b in bounds)
maxy = max(b[3] for b in bounds)
scale = min(1800 / max(maxx - minx, 1e-6), 1200 / max(maxy - miny, 1e-6))
pad = 80
im = Image.new("RGB", (int((maxx - minx) * scale) + 2 * pad, int((maxy - miny) * scale) + 2 * pad), (248, 248, 245))
dr = ImageDraw.Draw(im)
for i, room in enumerate(rooms):
b = room.get("bounds_m")
if not isinstance(b, list) or len(b) != 4:
continue
x0 = pad + int((b[0] - minx) * scale)
y0 = pad + int((maxy - b[3]) * scale)
x1 = pad + int((b[2] - minx) * scale)
y1 = pad + int((maxy - b[1]) * scale)
dr.rectangle((x0, y0, x1, y1), outline=(35, 35, 35), width=3,
fill=(235 + (i * 11) % 18, 240 - (i * 7) % 24, 230 - (i * 5) % 20))
dr.text(((x0 + x1) // 2 - 35, (y0 + y1) // 2 - 8), str(room.get("room_type", room.get("room_id", "room"))), fill=(20, 20, 20))
im.save(out)
return str(out)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--case", type=Path, required=True)
ap.add_argument("--dataset", type=Path, required=True)
ap.add_argument("--worker-meta", type=Path, required=True)
ap.add_argument("--manifest", type=Path)
args = ap.parse_args()
case = args.case.resolve()
scene_dir, mp, blend, selected_by = find_scene(case, manifest=args.manifest)
manifest = json.loads(mp.read_text())
fp = manifest.get("floor_plan", {})
try:
area, area_basis = actual_area_m2(fp), "sum_of_room_areas_m2"
except ValueError:
# Older/minimal manifests without a room list: fall back to the RPLAN conversion target and say so.
area, area_basis = conversion_target_area_m2(fp), "rplan_conversion_target_fallback"
if area is None:
raise ValueError("manifest has neither floor_plan.rooms nor a conversion target area")
area_bin = area_bin_name(area)
plan_id = fp.get("plan_id") or "plan_unknown"
sid = f"{plan_id}__{case.name}"
dest = (args.dataset / area_bin / sid).resolve()
dest.mkdir(parents=True, exist_ok=False)
copied = []
for p in [blend, mp, scene_dir / "SceneManifest.v16.json", scene_dir / "BenchmarkEpisode.v16.json", scene_dir / "generation_task_plan.json", scene_dir / "real_asset_import_audit.json", scene_dir / "saved_blend_verification.json"]:
if p.is_file():
shutil.copy2(p, dest / p.name)
copied.append(p.name)
for p in [case / "request.json", case / "runtime.json", case / "selection.json", case / "chain_config.json", case / "execute_result.json"]:
if p.is_file():
shutil.copy2(p, dest / p.name)
copied.append(p.name)
plan = plan_png(manifest, dest / "floorplan.png")
meta = json.loads(args.worker_meta.read_text())
info = {
"schema": "rhg.rp1_imported_scene_info.v1",
"scene_id": sid,
"area_m2": area,
"area_bin": area_bin,
"area_basis": area_basis,
"conversion_target_area_m2": conversion_target_area_m2(fp),
"source_plan_id": fp.get("plan_id"),
"source_rplan_id": fp.get("rplan_source_id"),
"scene_dir": str(scene_dir),
"selected_by": selected_by,
"copied_files": copied,
"blend_sha256": sha(dest / blend.name),
"manifest_sha256": sha(dest / mp.name),
"floorplan_png": plan,
"floor_plan": fp,
"rooms": manifest.get("floor_plan", {}).get("rooms", []),
"doors": manifest.get("floor_plan", {}).get("doors", []),
"windows": manifest.get("floor_plan", {}).get("windows", []),
"entities": manifest.get("entities", []),
"relations": manifest.get("relations", []),
"room_purposes": manifest.get("room_purposes", {}),
"floorplan_library": meta.get("floorplan_library"),
"worker": meta,
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
(dest / "source_manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
(dest / "rp1_scene_info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2) + "\n")
print(json.dumps({"ok": True, "scene_id": sid, "area_m2": area, "area_bin": area_bin,
"dest": str(dest), "scene_dir": str(scene_dir), "selected_by": selected_by}, ensure_ascii=False), flush=True)
if __name__ == "__main__":
main()