| """ |
| 测试 layout_instr_bench_test 数据集 (700 samples) |
| |
| 7 种房间类型,每种 100 个样本: |
| - bathroom, bedroom, dining_room, kitchen, living_room, office, study_room |
| |
| 使用 generated_prompt 作为输入,走完整的 end_to_end_pipeline 流程: |
| 1. 从 user_input 生成房间规格和物体列表 (在主进程使用 Azure OpenAI) |
| 2. 用 OpenShape 从 objaverse_processed 检索 3D 资产 (在主进程使用 CUDA) |
| 3. 用 LayoutVLM 优化布局 (单线程) |
| 4. 计算碰撞和出界指标 (使用 voxel, pitch=0.05) |
| |
| 架构说明: |
| - 第一阶段 (主进程): 对所有样本进行 LLM 调用和 CUDA 资产检索 |
| - 第二阶段 (单线程): 运行 LayoutVLM 优化 |
| """ |
|
|
| import os |
| import json |
| import argparse |
| import numpy as np |
| import collections |
| from typing import Dict, List, Any, Optional, Tuple |
| from dataclasses import dataclass |
| from tqdm import tqdm |
| import trimesh |
| from scipy.spatial import ConvexHull |
| from shapely.geometry import Polygon, Point |
| from multiprocessing import current_process |
| import traceback |
|
|
| |
| from end_to_end_pipeline import ( |
| setup_azure_client, |
| generate_room_specification, |
| generate_object_list, |
| retrieve_3d_assets, |
| generate_scene_json, |
| prepare_task_assets, |
| load_openclip_model, |
| load_openshape_embeddings, |
| ) |
|
|
| from src.layoutvlm.layoutvlm import LayoutVLM |
| from utils.blender_render import render_existing_scene |
| from utils.blender_utils import reset_blender |
|
|
|
|
| |
| |
| |
|
|
| def load_bench_test_data(data_dir: str) -> List[Dict]: |
| """加载 layout_instr_bench_test 中的数据""" |
| print(f"\n📂 加载数据: {data_dir}") |
| |
| room_types = [ |
| 'bathroom', 'bedroom', 'dining_room', 'kitchen', |
| 'living_room', 'office', 'study_room' |
| ] |
| |
| all_samples = [] |
| |
| for room_type in room_types: |
| jsonl_path = os.path.join(data_dir, room_type, 'instructions.jsonl') |
| if not os.path.exists(jsonl_path): |
| print(f" ⚠️ 文件不存在: {jsonl_path}") |
| continue |
| |
| with open(jsonl_path, 'r') as f: |
| for line_idx, line in enumerate(f): |
| try: |
| data = json.loads(line.strip()) |
| sample = { |
| 'id': f"{room_type}_{line_idx:03d}", |
| 'room_type': room_type, |
| 'user_input': data.get('generated_prompt', ''), |
| 'source': data.get('source', {}), |
| 'complexity': data.get('complexity', ''), |
| } |
| all_samples.append(sample) |
| except json.JSONDecodeError as e: |
| print(f" ⚠️ JSON 解析错误 {room_type}:{line_idx}: {e}") |
| |
| print(f" {room_type}: 加载完成") |
| |
| print(f" 总计 {len(all_samples)} 个样本") |
| return all_samples |
|
|
|
|
| |
| |
| |
|
|
| @dataclass |
| class CollisionResult: |
| total_assets: int |
| collision_pairs: List[Tuple[str, str]] |
| collision_count: int |
| collision_ratio: float |
| |
| collision_volume: float |
| collision_volume_per_pair: Dict[str, float] |
| |
| out_of_bounds_assets: List[str] |
| out_of_bounds_count: int |
| out_of_bounds_ratio: float |
| |
| out_of_bounds_volume: float |
| out_of_bounds_volume_per_asset: Dict[str, float] |
| |
| total_asset_volume: float |
|
|
|
|
| def load_mesh_from_glb(glb_path: str) -> Optional[trimesh.Trimesh]: |
| """从 glb 文件加载 mesh""" |
| if not os.path.exists(glb_path): |
| return None |
| try: |
| mesh = trimesh.load(glb_path) |
| if isinstance(mesh, trimesh.Scene): |
| meshes = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)] |
| if meshes: |
| mesh = trimesh.util.concatenate(meshes) |
| else: |
| return None |
| return mesh |
| except Exception as e: |
| print(f" ⚠️ 加载mesh失败: {e}") |
| return None |
|
|
|
|
| def transform_mesh(mesh: trimesh.Trimesh, position: List[float], |
| rotation: float, scale: List[float]) -> trimesh.Trimesh: |
| """变换 mesh 到世界坐标""" |
| mesh_copy = mesh.copy() |
| |
| |
| current_extents = mesh_copy.bounding_box.extents |
| if all(e > 0 for e in current_extents): |
| scale_factors = [s / e for s, e in zip(scale, current_extents)] |
| mesh_copy.apply_scale(scale_factors) |
| |
| |
| rotation_matrix = trimesh.transformations.rotation_matrix( |
| np.radians(rotation), [0, 0, 1] |
| ) |
| mesh_copy.apply_transform(rotation_matrix) |
| |
| |
| mesh_copy.apply_translation(position) |
| |
| return mesh_copy |
|
|
|
|
| def voxelize_mesh(mesh: trimesh.Trimesh, pitch: float = 0.05) -> Optional[set]: |
| """将 mesh 体素化,返回体素坐标集合""" |
| try: |
| voxels = mesh.voxelized(pitch=pitch) |
| |
| indices = voxels.sparse_indices |
| |
| world_coords = indices * pitch + voxels.transform[:3, 3] |
| |
| quantized = set(map(tuple, np.round(world_coords / pitch).astype(int))) |
| return quantized |
| except Exception as e: |
| return None |
|
|
|
|
| def check_voxel_collision(voxels1: set, voxels2: set, voxel_pitch: float = 0.05) -> Tuple[bool, int, float]: |
| """检测两个体素集合是否碰撞,返回碰撞体素数和碰撞体积""" |
| if voxels1 is None or voxels2 is None: |
| return False, 0, 0.0 |
| overlap = voxels1 & voxels2 |
| overlap_count = len(overlap) |
| |
| overlap_volume = overlap_count * (voxel_pitch ** 3) |
| return overlap_count > 0, overlap_count, overlap_volume |
|
|
|
|
| def check_out_of_bounds_voxel(voxels: set, boundary_polygon: List[List[float]], |
| height: float, voxel_pitch: float = 0.05) -> Tuple[bool, int, float]: |
| """ |
| 检测物体体素是否出界,返回出界体素数和出界体积 |
| """ |
| if voxels is None or len(voxels) == 0: |
| return False, 0, 0.0 |
| |
| try: |
| boundary = Polygon([(p[0], p[1]) for p in boundary_polygon]) |
| if not boundary.is_valid: |
| boundary = boundary.buffer(0) |
| |
| out_count = 0 |
| for voxel in voxels: |
| |
| x = voxel[0] * voxel_pitch |
| y = voxel[1] * voxel_pitch |
| z = voxel[2] * voxel_pitch if len(voxel) > 2 else 0 |
| |
| |
| point = Point(x, y) |
| if not boundary.contains(point): |
| out_count += 1 |
| |
| elif z < 0 or z > height: |
| out_count += 1 |
| |
| out_volume = out_count * (voxel_pitch ** 3) |
| return out_count > 0, out_count, out_volume |
| |
| except Exception as e: |
| return False, 0, 0.0 |
|
|
|
|
| def evaluate_layout_collisions(layout: Dict, scene_config: Dict, |
| voxel_pitch: float = 0.05) -> CollisionResult: |
| """ |
| 评估布局的碰撞和出界情况,计算碰撞体积和出界体积 |
| """ |
| print(" 📊 评估碰撞和出界...") |
| |
| |
| boundary = scene_config.get('boundary', {}) |
| floor_vertices = boundary.get('floor_vertices', [[0,0,0], [5,0,0], [5,5,0], [0,5,0]]) |
| boundary_polygon = [[v[0], v[1]] for v in floor_vertices] |
| room_height = boundary.get('ceiling_height', 2.7) |
| |
| |
| asset_voxels = {} |
| asset_positions = {} |
| asset_volumes = {} |
| |
| for asset_id, asset_info in layout.items(): |
| if asset_id not in scene_config.get('assets', {}): |
| continue |
| |
| asset_meta = scene_config['assets'][asset_id] |
| glb_path = asset_meta.get('path') |
| |
| position = asset_info.get('position', [0, 0, 0]) |
| if len(position) == 2: |
| bbox = asset_meta.get('assetMetadata', {}).get('boundingBox', {}) |
| z_height = bbox.get('z', 1.0) |
| position = [position[0], position[1], z_height / 2] |
| |
| rotation = asset_info.get('rotation', 0) |
| if isinstance(rotation, (list, tuple)): |
| rotation = rotation[2] if len(rotation) > 2 else rotation[0] |
| |
| scale_factor = asset_info.get('scale', 1.0) |
| bbox = asset_meta.get('assetMetadata', {}).get('boundingBox', {}) |
| size = [ |
| bbox.get('x', 1.0) * scale_factor, |
| bbox.get('y', 1.0) * scale_factor, |
| bbox.get('z', 1.0) * scale_factor |
| ] |
| |
| asset_positions[asset_id] = { |
| 'position': position, |
| 'rotation': rotation, |
| 'size': size, |
| } |
| |
| |
| if glb_path and os.path.exists(glb_path): |
| mesh = load_mesh_from_glb(glb_path) |
| if mesh: |
| transformed = transform_mesh(mesh, position, rotation, size) |
| voxels = voxelize_mesh(transformed, voxel_pitch) |
| if voxels: |
| asset_voxels[asset_id] = voxels |
| asset_volumes[asset_id] = len(voxels) * (voxel_pitch ** 3) |
| |
| |
| print(f" 检测碰撞 (voxel pitch={voxel_pitch})...") |
| collision_pairs = [] |
| collision_volume_per_pair = {} |
| total_collision_volume = 0.0 |
| |
| asset_ids = list(asset_voxels.keys()) |
| for i in range(len(asset_ids)): |
| for j in range(i + 1, len(asset_ids)): |
| id1, id2 = asset_ids[i], asset_ids[j] |
| is_collision, overlap_count, overlap_volume = check_voxel_collision( |
| asset_voxels[id1], asset_voxels[id2], voxel_pitch |
| ) |
| if is_collision: |
| pair_key = f"{id1}--{id2}" |
| collision_pairs.append((id1, id2)) |
| collision_volume_per_pair[pair_key] = overlap_volume |
| total_collision_volume += overlap_volume |
| |
| |
| print(" 检测出界...") |
| out_of_bounds = [] |
| out_of_bounds_volume_per_asset = {} |
| total_out_of_bounds_volume = 0.0 |
| |
| for asset_id in asset_voxels.keys(): |
| is_out, out_count, out_volume = check_out_of_bounds_voxel( |
| asset_voxels[asset_id], boundary_polygon, room_height, voxel_pitch |
| ) |
| if is_out: |
| out_of_bounds.append(asset_id) |
| out_of_bounds_volume_per_asset[asset_id] = out_volume |
| total_out_of_bounds_volume += out_volume |
| |
| |
| n = len(asset_positions) |
| max_pairs = n * (n - 1) // 2 if n > 1 else 1 |
| total_asset_volume = sum(asset_volumes.values()) |
| |
| print(f" 📊 碰撞: {len(collision_pairs)} 对, 碰撞体积: {total_collision_volume:.6f} m³") |
| print(f" 📊 出界: {len(out_of_bounds)} 个, 出界体积: {total_out_of_bounds_volume:.6f} m³") |
| print(f" 📊 总资产体积: {total_asset_volume:.6f} m³") |
| |
| return CollisionResult( |
| total_assets=n, |
| collision_pairs=collision_pairs, |
| collision_count=len(collision_pairs), |
| collision_ratio=len(collision_pairs) / max_pairs if max_pairs > 0 else 0, |
| collision_volume=total_collision_volume, |
| collision_volume_per_pair=collision_volume_per_pair, |
| out_of_bounds_assets=out_of_bounds, |
| out_of_bounds_count=len(out_of_bounds), |
| out_of_bounds_ratio=len(out_of_bounds) / n if n > 0 else 0, |
| out_of_bounds_volume=total_out_of_bounds_volume, |
| out_of_bounds_volume_per_asset=out_of_bounds_volume_per_asset, |
| total_asset_volume=total_asset_volume, |
| ) |
|
|
|
|
| |
| |
| |
|
|
| def render_scene(scene_config: Dict, layout: Dict, save_dir: str) -> List[str]: |
| """渲染场景 (diagonal + top 视角,无墙壁天花板)""" |
| print(" 🎨 渲染场景...") |
| |
| output_dir = os.path.join(save_dir, "renders") |
| os.makedirs(output_dir, exist_ok=True) |
| |
| render_paths = [] |
| |
| try: |
| print(" 渲染 top-down 视角...") |
| top_images, _ = render_existing_scene( |
| placed_assets=layout, |
| task=scene_config, |
| save_dir=output_dir, |
| high_res=True, |
| render_top_down=True, |
| add_coordinate_mark=False, |
| annotate_object=False, |
| annotate_wall=False, |
| combine_obj_components=True, |
| fov_multiplier=1.3, |
| topdown_save_file=os.path.join(output_dir, 'render_top.png'), |
| sideview_save_file=os.path.join(output_dir, 'render_diagonal.png'), |
| side_view_indices=[3], |
| ) |
| reset_blender() |
| render_paths.extend(top_images) |
| print(f" ✅ 渲染完成: {len(render_paths)} 张图片") |
| |
| except Exception as e: |
| print(f" ❌ 渲染失败: {e}") |
| traceback.print_exc() |
| |
| return render_paths |
|
|
|
|
| |
| |
| |
|
|
| def preprocess_sample(sample: Dict, asset_dir: str, client, use_openshape: bool = True) -> Dict: |
| """ |
| 在主进程中预处理单个样本: |
| 1. 调用 LLM 生成房间规格和物体列表 |
| 2. 使用 CUDA 进行 OpenShape 资产检索 |
| 3. 生成 scene_json |
| |
| 返回预处理结果,供后续 LayoutVLM 优化使用 |
| """ |
| sample_id = sample['id'] |
| user_input = sample['user_input'] |
| |
| result = { |
| 'sample_id': sample_id, |
| 'user_input': user_input, |
| 'room_type': sample.get('room_type', ''), |
| 'success': False, |
| 'scene_json': None, |
| 'room_spec': None, |
| 'object_list': None, |
| 'num_assets': 0, |
| 'error': None, |
| } |
| |
| try: |
| |
| room_spec = generate_room_specification(client, user_input) |
| result['room_spec'] = room_spec |
| |
| |
| object_list = generate_object_list( |
| client, |
| room_spec['task_description'], |
| room_spec['layout_criteria'], |
| room_spec['room_size'] |
| ) |
| result['object_list'] = object_list |
| |
| |
| assets = retrieve_3d_assets(object_list, asset_dir, use_openshape=use_openshape) |
| result['num_assets'] = len(assets) |
| |
| if not assets: |
| raise ValueError("未检索到任何资产") |
| |
| |
| scene_json = generate_scene_json( |
| room_spec['task_description'], |
| room_spec['layout_criteria'], |
| room_spec['room_size'], |
| assets |
| ) |
| result['scene_json'] = scene_json |
| result['success'] = True |
| |
| except Exception as e: |
| result['error'] = str(e) |
| print(f" ❌ 预处理失败 [{sample_id}]: {e}") |
| |
| return result |
|
|
|
|
| def preprocess_all_samples(samples: List[Dict], asset_dir: str, |
| use_openshape: bool = True, save_dir: str = None) -> List[Dict]: |
| """ |
| 主进程中预处理所有样本 (LLM 调用 + CUDA 资产检索) |
| """ |
| print("\n" + "=" * 80) |
| print("📦 第一阶段: 预处理 (LLM + OpenShape 检索)") |
| print("=" * 80) |
| |
| |
| if use_openshape: |
| print("🔄 加载 CLIP 模型和 OpenShape embeddings...") |
| load_openclip_model() |
| load_openshape_embeddings() |
| print("✅ 模型加载完成\n") |
| |
| |
| client = setup_azure_client() |
| |
| preprocessed = [] |
| for i, sample in enumerate(tqdm(samples, desc="预处理进度")): |
| sample_id = sample['id'] |
| |
| |
| if save_dir: |
| sample_save_dir = os.path.join(save_dir, f"sample_{i:04d}") |
| scene_path = os.path.join(sample_save_dir, 'scene_config.json') |
| if os.path.exists(scene_path): |
| |
| try: |
| with open(scene_path, 'r') as f: |
| scene_json = json.load(f) |
| preprocessed.append({ |
| 'sample_id': sample_id, |
| 'user_input': sample['user_input'], |
| 'room_type': sample.get('room_type', ''), |
| 'success': True, |
| 'scene_json': scene_json, |
| 'room_spec': None, |
| 'object_list': None, |
| 'num_assets': len(scene_json.get('objects', [])), |
| 'error': None, |
| 'skipped': True, |
| }) |
| print(f" ⏭️ 跳过已预处理: {sample_id}") |
| continue |
| except: |
| pass |
| |
| |
| result = preprocess_sample(sample, asset_dir, client, use_openshape) |
| preprocessed.append(result) |
| |
| |
| if result['success'] and save_dir: |
| sample_save_dir = os.path.join(save_dir, f"sample_{i:04d}") |
| os.makedirs(sample_save_dir, exist_ok=True) |
| scene_path = os.path.join(sample_save_dir, 'scene_config.json') |
| with open(scene_path, 'w') as f: |
| json.dump(result['scene_json'], f, indent=2) |
| |
| |
| success_count = sum(1 for p in preprocessed if p['success']) |
| print(f"\n📊 预处理完成: {success_count}/{len(samples)} 成功") |
| |
| return preprocessed |
|
|
|
|
| |
| |
| |
|
|
| def layoutvlm_worker(args_tuple) -> Dict: |
| """ |
| LayoutVLM 优化 worker (单线程模式) |
| """ |
| idx, preprocessed, save_dir, asset_dir, do_render = args_tuple |
| |
| sample_id = preprocessed['sample_id'] |
| sample_save_dir = os.path.join(save_dir, f"sample_{idx:04d}") |
| |
| proc_name = current_process().name |
| |
| result = { |
| 'sample_id': sample_id, |
| 'user_input': preprocessed['user_input'], |
| 'room_type': preprocessed.get('room_type', ''), |
| 'success': False, |
| 'room_spec': preprocessed.get('room_spec'), |
| 'object_list': preprocessed.get('object_list'), |
| 'num_assets': preprocessed.get('num_assets', 0), |
| 'collision_result': None, |
| 'render_paths': [], |
| 'error': None, |
| } |
| |
| |
| layout_path = os.path.join(sample_save_dir, 'layout.json') |
| result_json_path = os.path.join(sample_save_dir, 'result.json') |
| |
| if os.path.exists(layout_path): |
| if os.path.exists(result_json_path): |
| try: |
| with open(result_json_path, 'r') as f: |
| cached_result = json.load(f) |
| print(f"[{proc_name}] ⏭️ 跳过已完成: {sample_id}") |
| cached_result['skipped'] = True |
| return cached_result |
| except: |
| pass |
| result['success'] = True |
| result['skipped'] = True |
| print(f"[{proc_name}] ⏭️ 跳过已完成: {sample_id}") |
| return result |
| |
| |
| if not preprocessed['success']: |
| result['error'] = preprocessed.get('error', '预处理失败') |
| print(f"[{proc_name}] ⏭️ 跳过预处理失败: {sample_id}") |
| return result |
| |
| try: |
| print(f"\n[{proc_name}] {'='*50}") |
| print(f"[{proc_name}] 📋 处理样本: {sample_id}") |
| |
| scene_json = preprocessed['scene_json'] |
| os.makedirs(sample_save_dir, exist_ok=True) |
| |
| |
| scene_config = prepare_task_assets(scene_json, asset_dir) |
| |
| if not scene_config.get('assets'): |
| raise ValueError("没有有效的资产") |
| |
| |
| print(f"[{proc_name}] LayoutVLM 布局优化...") |
| layout_solver = LayoutVLM( |
| mode="one_shot", |
| save_dir=sample_save_dir, |
| asset_source="objaverse", |
| ) |
| layout = layout_solver.solve(scene_config) |
| |
| |
| with open(layout_path, 'w') as f: |
| json.dump(layout, f, indent=2) |
| |
| |
| print(f"[{proc_name}] 计算碰撞和出界...") |
| collision_result = evaluate_layout_collisions( |
| layout, scene_config, voxel_pitch=0.05 |
| ) |
| |
| result['collision_result'] = { |
| 'total_assets': collision_result.total_assets, |
| 'collision_count': collision_result.collision_count, |
| 'collision_ratio': collision_result.collision_ratio, |
| 'collision_volume': collision_result.collision_volume, |
| 'collision_volume_per_pair': collision_result.collision_volume_per_pair, |
| 'out_of_bounds_count': collision_result.out_of_bounds_count, |
| 'out_of_bounds_ratio': collision_result.out_of_bounds_ratio, |
| 'out_of_bounds_volume': collision_result.out_of_bounds_volume, |
| 'out_of_bounds_volume_per_asset': collision_result.out_of_bounds_volume_per_asset, |
| 'total_asset_volume': collision_result.total_asset_volume, |
| 'collision_pairs': collision_result.collision_pairs, |
| 'out_of_bounds_assets': collision_result.out_of_bounds_assets, |
| } |
| |
| |
| if do_render: |
| print(f"[{proc_name}] Blender 渲染...") |
| render_paths = render_scene(scene_config, layout, sample_save_dir) |
| result['render_paths'] = render_paths |
| |
| result['success'] = True |
| print(f"[{proc_name}] ✅ 完成") |
| |
| except Exception as e: |
| result['error'] = str(e) |
| print(f"[{proc_name}] ❌ 失败: {e}") |
| traceback.print_exc() |
| |
| |
| with open(result_json_path, 'w') as f: |
| json.dump(result, f, indent=2, default=str) |
| |
| return result |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description='测试 layout_instr_bench_test 数据集') |
| parser.add_argument('--data_dir', type=str, |
| default='/home/v-meiszhang/amlt-project/Qwen-Image/layout_instr_bench_test', |
| help='数据目录路径') |
| parser.add_argument('--save_dir', type=str, |
| default='./results/bench_test_700', |
| help='结果保存目录') |
| parser.add_argument('--asset_dir', type=str, |
| default='/home/v-meiszhang/backup/objaverse_processed', |
| help='Objaverse 资产目录') |
| parser.add_argument('--num_samples', type=int, default=0, |
| help='测试样本数量 (0 表示全部 700 个)') |
| parser.add_argument('--start_idx', type=int, default=0, |
| help='起始索引') |
| parser.add_argument('--random_selection', action='store_true', |
| help='使用随机选择而非 OpenShape 检索') |
| parser.add_argument('--skip_render', action='store_true', default=True, |
| help='跳过渲染 (默认开启)') |
| parser.add_argument('--enable_render', action='store_true', |
| help='启用渲染') |
| parser.add_argument('--room_type', type=str, default=None, |
| help='仅测试指定房间类型 (bathroom/bedroom/dining_room/kitchen/living_room/office/study_room)') |
| |
| args = parser.parse_args() |
| |
| do_render = args.enable_render |
| use_openshape = not args.random_selection |
| |
| print("=" * 80) |
| print("🧪 Bench Data 测试脚本 (单线程)") |
| print("=" * 80) |
| print(f"📁 数据路径: {args.data_dir}") |
| print(f"💾 保存目录: {args.save_dir}") |
| print(f"📦 资产目录: {args.asset_dir}") |
| print(f"📊 测试数量: {args.num_samples if args.num_samples > 0 else '全部'}") |
| print(f"🎨 渲染: {'启用' if do_render else '跳过'}") |
| print(f"🔍 资产检索: {'OpenShape' if use_openshape else '随机选择'}") |
| if args.room_type: |
| print(f"🏠 房间类型: {args.room_type}") |
| print() |
| |
| os.makedirs(args.save_dir, exist_ok=True) |
| |
| |
| test_data = load_bench_test_data(args.data_dir) |
| |
| |
| if args.room_type: |
| test_data = [s for s in test_data if s.get('room_type') == args.room_type] |
| print(f"📊 过滤后样本数: {len(test_data)}") |
| |
| |
| if args.num_samples > 0: |
| test_data = test_data[args.start_idx:args.start_idx + args.num_samples] |
| elif args.start_idx > 0: |
| test_data = test_data[args.start_idx:] |
| |
| print(f"📊 实际测试样本数: {len(test_data)}") |
| |
| |
| preprocessed = preprocess_all_samples( |
| test_data, |
| args.asset_dir, |
| use_openshape=use_openshape, |
| save_dir=args.save_dir |
| ) |
| |
| |
| print("\n" + "=" * 80) |
| print("🚀 第二阶段: LayoutVLM 优化 (单线程)") |
| print("=" * 80) |
| |
| |
| worker_args = [ |
| (i, preprocessed[i], args.save_dir, args.asset_dir, do_render) |
| for i in range(len(preprocessed)) |
| ] |
| |
| all_results = [] |
| for args_tuple in tqdm(worker_args, desc="LayoutVLM 进度"): |
| result = layoutvlm_worker(args_tuple) |
| all_results.append(result) |
| |
| |
| if len(all_results) % 10 == 0: |
| results_path = os.path.join(args.save_dir, 'all_results.json') |
| with open(results_path, 'w') as f: |
| json.dump(all_results, f, indent=2, default=str) |
| |
| |
| summary = { |
| 'total_samples': len(test_data), |
| 'successful': 0, |
| 'failed': 0, |
| 'skipped': 0, |
| 'total_collisions': 0, |
| 'total_out_of_bounds': 0, |
| 'avg_collision_ratio': 0, |
| 'avg_out_of_bounds_ratio': 0, |
| |
| 'by_room_type': {}, |
| } |
| |
| collision_ratios = [] |
| out_of_bounds_ratios = [] |
| collision_volumes = [] |
| out_of_bounds_volumes = [] |
| total_asset_volumes = [] |
| |
| |
| room_type_stats = {} |
| |
| for result in all_results: |
| room_type = result.get('room_type', 'unknown') |
| if room_type not in room_type_stats: |
| room_type_stats[room_type] = { |
| 'total': 0, |
| 'successful': 0, |
| 'failed': 0, |
| 'collision_volumes': [], |
| 'out_of_bounds_volumes': [], |
| 'total_asset_volumes': [], |
| } |
| room_type_stats[room_type]['total'] += 1 |
| |
| if result.get('skipped'): |
| summary['skipped'] += 1 |
| summary['successful'] += 1 |
| room_type_stats[room_type]['successful'] += 1 |
| elif result.get('success'): |
| summary['successful'] += 1 |
| room_type_stats[room_type]['successful'] += 1 |
| if result.get('collision_result'): |
| cr = result['collision_result'] |
| summary['total_collisions'] += cr['collision_count'] |
| summary['total_out_of_bounds'] += cr['out_of_bounds_count'] |
| collision_ratios.append(cr['collision_ratio']) |
| out_of_bounds_ratios.append(cr['out_of_bounds_ratio']) |
| collision_volumes.append(cr.get('collision_volume', 0)) |
| out_of_bounds_volumes.append(cr.get('out_of_bounds_volume', 0)) |
| total_asset_volumes.append(cr.get('total_asset_volume', 0)) |
| |
| room_type_stats[room_type]['collision_volumes'].append(cr.get('collision_volume', 0)) |
| room_type_stats[room_type]['out_of_bounds_volumes'].append(cr.get('out_of_bounds_volume', 0)) |
| room_type_stats[room_type]['total_asset_volumes'].append(cr.get('total_asset_volume', 0)) |
| else: |
| summary['failed'] += 1 |
| room_type_stats[room_type]['failed'] += 1 |
| |
| if collision_ratios: |
| summary['avg_collision_ratio'] = sum(collision_ratios) / len(collision_ratios) |
| if out_of_bounds_ratios: |
| summary['avg_out_of_bounds_ratio'] = sum(out_of_bounds_ratios) / len(out_of_bounds_ratios) |
| |
| summary['total_collision_volume'] = sum(collision_volumes) |
| summary['total_out_of_bounds_volume'] = sum(out_of_bounds_volumes) |
| summary['total_asset_volume'] = sum(total_asset_volumes) |
| summary['avg_collision_volume'] = sum(collision_volumes) / len(collision_volumes) if collision_volumes else 0 |
| summary['avg_out_of_bounds_volume'] = sum(out_of_bounds_volumes) / len(out_of_bounds_volumes) if out_of_bounds_volumes else 0 |
| summary['collision_volume_ratio'] = summary['total_collision_volume'] / summary['total_asset_volume'] if summary['total_asset_volume'] > 0 else 0 |
| summary['out_of_bounds_volume_ratio'] = summary['total_out_of_bounds_volume'] / summary['total_asset_volume'] if summary['total_asset_volume'] > 0 else 0 |
| |
| |
| for room_type, stats in room_type_stats.items(): |
| summary['by_room_type'][room_type] = { |
| 'total': stats['total'], |
| 'successful': stats['successful'], |
| 'failed': stats['failed'], |
| 'total_collision_volume': sum(stats['collision_volumes']), |
| 'total_out_of_bounds_volume': sum(stats['out_of_bounds_volumes']), |
| 'total_asset_volume': sum(stats['total_asset_volumes']), |
| 'avg_collision_volume': sum(stats['collision_volumes']) / len(stats['collision_volumes']) if stats['collision_volumes'] else 0, |
| 'avg_out_of_bounds_volume': sum(stats['out_of_bounds_volumes']) / len(stats['out_of_bounds_volumes']) if stats['out_of_bounds_volumes'] else 0, |
| } |
| if sum(stats['total_asset_volumes']) > 0: |
| summary['by_room_type'][room_type]['collision_volume_ratio'] = sum(stats['collision_volumes']) / sum(stats['total_asset_volumes']) |
| summary['by_room_type'][room_type]['out_of_bounds_volume_ratio'] = sum(stats['out_of_bounds_volumes']) / sum(stats['total_asset_volumes']) |
| |
| |
| summary_path = os.path.join(args.save_dir, 'summary.json') |
| with open(summary_path, 'w') as f: |
| json.dump(summary, f, indent=2) |
| |
| results_path = os.path.join(args.save_dir, 'all_results.json') |
| with open(results_path, 'w') as f: |
| json.dump(all_results, f, indent=2, default=str) |
| |
| |
| print("\n" + "=" * 80) |
| print("📊 测试总结") |
| print("=" * 80) |
| print(f"总样本数: {summary['total_samples']}") |
| print(f"成功: {summary['successful']}") |
| print(f"失败: {summary['failed']}") |
| print(f"跳过: {summary['skipped']}") |
| print(f"\n--- 碰撞指标 ---") |
| print(f"总碰撞对数: {summary['total_collisions']}") |
| print(f"平均碰撞比例: {summary['avg_collision_ratio']:.2%}") |
| print(f"总碰撞体积: {summary['total_collision_volume']:.6f} m³") |
| print(f"平均碰撞体积: {summary['avg_collision_volume']:.6f} m³") |
| print(f"碰撞体积比例: {summary['collision_volume_ratio']:.4%}") |
| print(f"\n--- 出界指标 ---") |
| print(f"总出界物体数: {summary['total_out_of_bounds']}") |
| print(f"平均出界比例: {summary['avg_out_of_bounds_ratio']:.2%}") |
| print(f"总出界体积: {summary['total_out_of_bounds_volume']:.6f} m³") |
| print(f"平均出界体积: {summary['avg_out_of_bounds_volume']:.6f} m³") |
| print(f"出界体积比例: {summary['out_of_bounds_volume_ratio']:.4%}") |
| print(f"\n--- 资产体积 ---") |
| print(f"总资产体积: {summary['total_asset_volume']:.6f} m³") |
| |
| |
| print(f"\n--- 按房间类型统计 ---") |
| for room_type in sorted(summary['by_room_type'].keys()): |
| rt_stats = summary['by_room_type'][room_type] |
| print(f"\n {room_type}:") |
| print(f" 样本数: {rt_stats['total']} (成功: {rt_stats['successful']}, 失败: {rt_stats['failed']})") |
| print(f" 平均碰撞体积: {rt_stats['avg_collision_volume']:.6f} m³") |
| print(f" 平均出界体积: {rt_stats['avg_out_of_bounds_volume']:.6f} m³") |
| |
| print(f"\n结果保存在: {args.save_dir}") |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|