""" Render table and sofa from a scene layout separately. """ import os import json import argparse import subprocess import sys import tempfile import shutil from pathlib import Path from typing import List, Dict, Any, Optional # Add project root SCRIPT_DIR = Path(__file__).parent REPO_ROOT = SCRIPT_DIR.parent.parent sys.path.insert(0, str(REPO_ROOT)) # Keywords to identify tables and sofas TABLE_KEYWORDS = ['table', 'desk', 'dining', 'coffee_table', 'end_table', 'side_table', 'console'] SOFA_KEYWORDS = ['sofa', 'couch', 'loveseat', 'settee', 'sectional', 'armchair', 'chair'] def is_table(asset: Dict) -> bool: """Check if asset is a table.""" semantic = asset.get('semantic', '').lower() category = asset.get('category', '').lower() uid = asset.get('uid', '').lower() text = f"{semantic} {category} {uid}" return any(kw in text for kw in TABLE_KEYWORDS) def is_sofa(asset: Dict) -> bool: """Check if asset is a sofa/seating.""" semantic = asset.get('semantic', '').lower() category = asset.get('category', '').lower() uid = asset.get('uid', '').lower() text = f"{semantic} {category} {uid}" return any(kw in text for kw in SOFA_KEYWORDS) def find_tables_and_sofas(layout: Dict) -> Dict[str, List[Dict]]: """Find all tables and sofas in the layout.""" assets = layout.get('assets', []) tables = [] sofas = [] for asset in assets: if is_table(asset): tables.append(asset) elif is_sofa(asset): sofas.append(asset) return { 'tables': tables, 'sofas': sofas } def compose_assets_scene(assets: List[Dict], output_path: str): """ Compose a scene with only the specified assets. """ from tools.data_gen.compose_generated import compose_scene # Create a minimal layout with just these assets layout = { "meta": {"scene_type": "asset_vis"}, "architecture": {"boundary_polygon": []}, "assets": assets } compose_scene( layout=layout, output_path=output_path, add_floor=False, add_walls=False, add_ceiling=False, ) print(f" Composed scene: {output_path}") def run_command(cmd, env=None, quiet=False): """Run a shell command.""" print(f" Running: {cmd[:100]}...") try: if quiet: subprocess.check_call(cmd, shell=True, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) else: subprocess.check_call(cmd, shell=True, env=env) return True except subprocess.CalledProcessError as e: print(f" Command failed: {e}") return False def render_scene(glb_path: str, output_path: str, view_mode: str = "diagonal", width: int = 1200, height: int = 900): """Render a GLB scene using Blender.""" current_env = os.environ.copy() cmd = ( f"conda run -n blender python InternScenes/InternScenes_Real2Sim/blender_renderer.py " f"--input '{glb_path}' " f"--output '{output_path}' " f"--width {width} --height {height} " f"--engine BLENDER_EEVEE --samples 64 " f"--view-mode {view_mode} --auto-crop " f"--floor-material solid " f"--diagonal-distance 2.5 " f"--camera-factor 1.8 " ) run_command(cmd, env=current_env, quiet=True) def render_table_sofa( layout_path: str, output_dir: str, render_views: List[str] = None, ): """ Main function to render tables and sofas from a layout. """ if render_views is None: render_views = ["diagonal", "diagonal2"] print(f"\n{'='*60}") print(f"Table & Sofa Rendering") print(f"{'='*60}") print(f"Input: {layout_path}") print(f"Output: {output_dir}") print(f"{'='*60}\n") # Load layout with open(layout_path, 'r') as f: layout = json.load(f) # Create output directory os.makedirs(output_dir, exist_ok=True) # Find tables and sofas print("Finding tables and sofas...") found = find_tables_and_sofas(layout) tables = found['tables'] sofas = found['sofas'] print(f"Found {len(tables)} table(s):") for t in tables: print(f" - {t.get('semantic', 'unknown')} ({t.get('uid', 'no-uid')[:30]})") print(f"Found {len(sofas)} sofa(s):") for s in sofas: print(f" - {s.get('semantic', 'unknown')} ({s.get('uid', 'no-uid')[:30]})") if not tables and not sofas: print("No tables or sofas found in this layout!") return # Combine all found assets assets_to_render = tables + sofas print(f"\nRendering {len(assets_to_render)} asset(s) together...") # Create temporary directory for intermediate files with tempfile.TemporaryDirectory() as tmpdir: # Compose scene with tables and sofas scene_glb = os.path.join(tmpdir, "table_sofa_scene.glb") compose_assets_scene(assets_to_render, scene_glb) # Render from different views for view in render_views: print(f"\nRendering {view} view...") output_img = os.path.join(output_dir, f"table_sofa_{view}.png") render_scene(scene_glb, output_img, view_mode=view) if os.path.exists(output_img): print(f" Saved: {output_img}") # Save asset info info_path = os.path.join(output_dir, "asset_info.json") info = { 'tables': [{'semantic': t.get('semantic'), 'uid': t.get('uid')} for t in tables], 'sofas': [{'semantic': s.get('semantic'), 'uid': s.get('uid')} for s in sofas], } with open(info_path, 'w') as f: json.dump(info, f, indent=2) print(f"\n{'='*60}") print(f"Done! Outputs saved to {output_dir}") print(f"{'='*60}\n") def main(): parser = argparse.ArgumentParser(description='Render tables and sofas from a scene layout') parser.add_argument('--input', required=True, help='Path to layout JSON file') parser.add_argument('--output', default='table_sofa_output', help='Output directory') parser.add_argument('--all-views', action='store_true', help='Render from all standard views') args = parser.parse_args() views = ["diagonal", "diagonal2"] if args.all_views: views = ["diagonal", "diagonal2", "top", "front"] render_table_sofa( layout_path=args.input, output_dir=args.output, render_views=views, ) if __name__ == "__main__": main()