File size: 9,098 Bytes
231562a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import os
import json
import math
import sys
import collections
import argparse
from tqdm import tqdm

# Import visualize_blender_zones (must be in the same directory)
try:
    import visualize_blender_zones as viz
except ImportError:
    print("Error: visualize_blender_zones.py not found in current directory.")
    sys.exit(1)

def prepare_task_assets(task, asset_dir):
    """
    Prepare assets metadata (Simplified version from end_to_end_pipeline.py)
    Does not depend on torch/clip.
    """
    if "layout_criteria" not in task:
        task["layout_criteria"] = "the layout should follow the task description and adhere to common sense"

    all_data = collections.defaultdict(list)
    # task["assets"] keys are like "uid-index" or just "uid"
    # We need to handle both cases or assume raw scene_config format
    
    for original_uid in task["assets"].keys():
        # Handle potential suffix like "-0" if it exists in raw config
        # But usually raw config keys are just UIDs or "UID-0"
        parts = original_uid.split('-')
        if len(parts) > 1 and parts[-1].isdigit():
             uid = '-'.join(parts[:-1])
        else:
             uid = original_uid
        
        # Try to find data.json
        data_path = os.path.join(asset_dir, uid, "data.json")
        if not os.path.exists(data_path):
            # Try without stripping suffix if it failed (maybe uid has dashes)
            if os.path.exists(os.path.join(asset_dir, original_uid, "data.json")):
                uid = original_uid
                data_path = os.path.join(asset_dir, uid, "data.json")
            else:
                # print(f"⚠️  Warning: Asset data not found for {uid}")
                continue
            
        with open(data_path, "r") as f:
            data = json.load(f)
        data['path'] = os.path.join(asset_dir, uid, f"{uid}.glb")
        all_data[uid].append(data)

    category_count = collections.defaultdict(int)
    for uid, duplicated_assets in all_data.items():
        if not duplicated_assets: continue
        category_var_name = duplicated_assets[0]['annotations']['category']
        category_var_name = category_var_name.replace('-', "_").replace(" ", "_").replace("'", "_").replace("/", "_").replace(",", "_").lower()
        category_count[category_var_name] += 1

    new_assets = {}
    category_idx = collections.defaultdict(int)
    
    for uid, duplicated_assets in all_data.items():
        if not duplicated_assets: continue
        category_var_name = duplicated_assets[0]['annotations']['category']
        category_var_name = category_var_name.replace('-', "_").replace(" ", "_").replace("'", "_").replace("/", "_").replace(",", "_").lower()
        category_idx[category_var_name] += 1
        
        for instance_idx, data in enumerate(duplicated_assets):
            category_var_name_final = f"{category_var_name}_{chr(ord('A') + category_idx[category_var_name]-1)}" if category_count[category_var_name] > 1 else category_var_name
            var_name = f"{category_var_name_final}_{instance_idx}" if len(duplicated_assets) > 1 else category_var_name_final
            
            # Key format: category-index (e.g., table-0)
            key = f"{category_var_name_final}-{instance_idx}"
            
            new_assets[key] = {
                "uid": uid,
                "count": len(duplicated_assets),
                "instance_var_name": var_name,
                "asset_var_name": category_var_name_final,
                "instance_idx": instance_idx,
                "annotations": data["annotations"],
                "category": data["annotations"]["category"],
                'description': data['annotations']['description'],
                'path': data['path'],
                'assetMetadata': {
                    "boundingBox": {
                        "x": float(data['assetMetadata']['boundingBox']['y']),
                        "y": float(data['assetMetadata']['boundingBox']['x']),
                        "z": float(data['assetMetadata']['boundingBox']['z'])
                    },
                }
            }

    task["assets"] = new_assets
    return task

def process_dataset(results_dir, asset_dir, views=['topdown', 'diagonal']):
    """Process all samples in a results directory"""
    print(f"Processing dataset: {results_dir}")
    
    samples = sorted([d for d in os.listdir(results_dir) if d.startswith('sample_')])
    
    for sample_name in tqdm(samples):
        sample_dir = os.path.join(results_dir, sample_name)
        scene_config_path = os.path.join(sample_dir, 'scene_config.json')
        layout_path = os.path.join(sample_dir, 'layout.json')
        
        # Skip if layout doesn't exist
        if not os.path.exists(layout_path):
            continue
            
        # Skip if already rendered (check one view)
        if os.path.exists(os.path.join(sample_dir, f'render_{views[0]}.png')):
            # print(f"Skipping {sample_name}, already rendered.")
            continue

        try:
            # 1. Load scene config
            with open(scene_config_path, 'r') as f:
                scene_config = json.load(f)
            
            # 2. Prepare assets (map UIDs to category-index keys)
            scene_config = prepare_task_assets(scene_config, asset_dir)
            
            # 3. Load layout
            with open(layout_path, 'r') as f:
                layout = json.load(f)
            
            # 4. Construct scene object for visualizer
            scene_objects = []
            
            for key, transform in layout.items():
                if key not in scene_config['assets']:
                    # print(f"Warning: Asset {key} in layout but not in scene config")
                    continue
                
                asset_info = scene_config['assets'][key]
                
                # Convert rotation from radians to degrees
                rot_rad = transform.get('rotation', [0, 0, 0])
                rot_deg = [math.degrees(r) for r in rot_rad]
                
                # Get size from bounding box
                bbox = asset_info['assetMetadata']['boundingBox']
                size = [bbox['x'], bbox['y'], bbox['z']]
                
                obj_data = {
                    'id': key,
                    'model_id': asset_info['uid'],
                    'category': asset_info['category'],
                    'position': transform.get('position', [0, 0, 0]),
                    'rotation': rot_deg,
                    'size': size
                }
                scene_objects.append(obj_data)
            
            scene_for_viz = {
                'boundary': scene_config.get('boundary', {}).get('floor_vertices', []),
                'assets': scene_objects
            }
            
            # Handle boundary format differences
            if not scene_for_viz['boundary'] and 'boundary' in scene_config:
                 # Try to find vertices
                 if isinstance(scene_config['boundary'], dict):
                     scene_for_viz['boundary'] = scene_config['boundary'].get('floor_vertices', [])
            
            # 5. Render views
            for view in views:
                output_path = os.path.join(sample_dir, f'render_{view}.png')
                
                # Map view names to what visualize_blender_zones expects
                # visualize_blender_zones supports: 'top', 'diagonal', 'front'
                # We need to adapt setup_camera if we want more views
                
                viz_view = view
                if view == 'topdown': viz_view = 'top'
                elif view == 'side_front': viz_view = 'front'
                # For other views, we might need to hack visualize_blender_zones or just use diagonal
                
                # Since visualize_blender_zones only supports top, diagonal, front
                # We will stick to what it supports for now, or extend it.
                # The user asked for "diagonal and topdown".
                
                if viz_view not in ['top', 'diagonal', 'front']:
                    # print(f"Warning: View {view} not supported by visualizer, skipping")
                    continue
                
                viz.visualize_scene(
                    scene_for_viz, 
                    output_path=output_path, 
                    render=True, 
                    asset_dir=asset_dir, 
                    view=viz_view
                )
                
        except Exception as e:
            print(f"Error processing {sample_name}: {e}")
            # import traceback
            # traceback.print_exc()

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--asset_dir', required=True)
    args = parser.parse_args()
    
    # Zones Test 1000
    process_dataset('results/zones_test_1000', args.asset_dir, views=['topdown', 'diagonal'])
    
    # Bench Test 700
    process_dataset('results/bench_test_700', args.asset_dir, views=['topdown', 'diagonal'])

if __name__ == "__main__":
    main()