#!/usr/bin/env python3 """ 调试 sample.py 中的 'NoneType' object has no attribute 'get' 错误 专门针对 sample_all_assets 方法中的问题 """ import json import sys import os import traceback import copy import uuid from pathlib import Path # 添加 src 路径 sys.path.insert(0, '/home/v-meiszhang/amlt-project/respace') def load_test_scene(): """加载测试场景数据""" json_path = "/home/v-meiszhang/amlt-project/group-layout/infer_results/individual_samples/full_20250831_112415/checkpoint-270/ae8d145b-5c7c-4970-a4b6-7855e64ea4eb-1f704044-378d-41ca-8978-43c0881b103c.json" print(f"📖 加载测试场景: {json_path}") with open(json_path, 'r', encoding='utf-8') as f: raw_data = json.load(f) # 提取和处理场景数据(简化版本) if "predict" in raw_data: scene_data = raw_data["predict"] # 简单的 JSON 解析 if isinstance(scene_data, str): import re pattern = r'(.*?)' match = re.search(pattern, scene_data, re.DOTALL) if match: scene_data = json.loads(match.group(1).strip()) else: scene_data = json.loads(scene_data) else: scene_data = raw_data # 处理房间边界 if "room_envelope" in scene_data: envelope_data = scene_data["room_envelope"] if isinstance(envelope_data, dict): scene_data["bounds_top"] = envelope_data.get("bounds_top") scene_data["bounds_bottom"] = envelope_data.get("bounds_bottom") # 展平对象 if "groups" in scene_data: scene_data["objects"] = [] for group in scene_data["groups"]: if isinstance(group, dict) and "objects" in group: scene_data["objects"].extend(group["objects"]) return scene_data def debug_sample_all_assets(): """调试 sample_all_assets 方法""" print("🔬 开始调试 sample_all_assets 方法") print("="*60) # 加载环境变量 try: from dotenv import load_dotenv load_dotenv("/home/v-meiszhang/amlt-project/respace/.env") print("✅ 环境变量加载成功") except Exception as e: print(f"⚠️ 环境变量加载失败: {e}") # 加载测试场景 try: scene = load_test_scene() print(f"✅ 测试场景加载成功") print(f" 对象数量: {len(scene.get('objects', []))}") # 检查对象完整性 objects = scene.get('objects', []) for i, obj in enumerate(objects): if obj is None: print(f" ❌ 对象 {i+1} 为 None") elif not isinstance(obj, dict): print(f" ❌ 对象 {i+1} 不是字典: {type(obj)}") else: desc = obj.get("desc", "") size = obj.get("size", []) print(f" ✅ 对象 {i+1}: desc='{desc[:30]}...', size={size}") except Exception as e: print(f"❌ 测试场景加载失败: {e}") traceback.print_exc() return # 初始化采样引擎 try: from src.sample import AssetRetrievalModule print("\n🔧 初始化 AssetRetrievalModule...") sampling_engine = AssetRetrievalModule( lambd=0.5, sigma=0.05, temp=0.2, top_p=0.95, top_k=20, asset_size_threshold=0.5, rand_seed=1234, dvc='cuda' if os.getenv('CUDA_VISIBLE_DEVICES') else 'cpu', do_print=True # 启用详细输出 ) print("✅ AssetRetrievalModule 初始化成功") # 检查元数据 print(f"\n📊 元数据统计:") print(f" all_assets_metadata: {len(sampling_engine.all_assets_metadata)} 条目") print(f" all_assets_metadata_scaled: {len(sampling_engine.all_assets_metadata_scaled)} 条目") print(f" all_jids_catalog: {len(sampling_engine.all_jids_catalog)} 条目") except Exception as e: print(f"❌ AssetRetrievalModule 初始化失败: {e}") traceback.print_exc() return # 修补 create_sampled_obj 方法以添加调试信息 original_create_sampled_obj = sampling_engine.create_sampled_obj def debug_create_sampled_obj(obj, probs, is_greedy_sampling): """带调试信息的 create_sampled_obj""" print(f"\n🎯 调试 create_sampled_obj:") print(f" 输入对象类型: {type(obj)}") if obj is None: print(" ❌ 输入对象为 None!") return None print(f" 对象描述: {obj.get('desc', 'N/A')[:50]}...") print(f" 对象大小: {obj.get('size', 'N/A')}") try: # 获取采样 jid if obj.get("jid") == None: import torch if is_greedy_sampling: _, idx_sampled = torch.max(probs, dim=0) else: idx_sampled = torch.multinomial(probs, num_samples=1) jid_sampled_obj = sampling_engine.all_jids_catalog[idx_sampled] else: jid_sampled_obj = obj.get("jid") print(f" 采样的 JID: {jid_sampled_obj}") # 检查资产存在性 asset = sampling_engine.all_assets_metadata.get(jid_sampled_obj) print(f" 在 all_assets_metadata 中: {asset is not None}") if asset == None: asset = sampling_engine.all_assets_metadata_scaled.get(jid_sampled_obj) print(f" 在 all_assets_metadata_scaled 中: {asset is not None}") if asset is None: print(f" ❌ 无法找到 JID {jid_sampled_obj} 对应的资产!") return None # 检查缩放资产的完整性 size_sampled_obj = asset.get("size") orig_jid = asset.get("jid") print(f" 缩放资产大小: {size_sampled_obj}") print(f" 原始 JID: {orig_jid}") if orig_jid is None: print(f" ❌ 缩放资产没有原始 JID!") return None orig_asset = sampling_engine.all_assets_metadata.get(orig_jid) print(f" 原始资产存在: {orig_asset is not None}") if orig_asset is None: print(f" ❌ 无法找到原始资产 {orig_jid}!") return None desc_sampled_obj = orig_asset.get("summary") print(f" 原始资产描述: {desc_sampled_obj[:30] if desc_sampled_obj else 'None'}...") else: desc_sampled_obj = asset.get("summary") size_sampled_obj = asset.get("size") print(f" 直接资产描述: {desc_sampled_obj[:30] if desc_sampled_obj else 'None'}...") print(f" 直接资产大小: {size_sampled_obj}") # 检查必要字段 if desc_sampled_obj is None: print(f" ❌ 资产描述为 None!") return None if size_sampled_obj is None: print(f" ❌ 资产大小为 None!") return None # 创建新对象 new_obj = copy.deepcopy(obj) new_obj.update({ "sampled_asset_jid": jid_sampled_obj, "sampled_asset_desc": desc_sampled_obj, "sampled_asset_size": size_sampled_obj, "uuid": str(uuid.uuid4()) }) print(f" ✅ 成功创建采样对象") return new_obj except Exception as e: print(f" ❌ create_sampled_obj 内部错误: {e}") traceback.print_exc() return None # 临时替换方法 sampling_engine.create_sampled_obj = debug_create_sampled_obj # 修补 sample_all_assets 方法以添加更多调试信息 print(f"\n🎯 开始调试 sample_all_assets 过程...") try: print(f"📊 场景信息:") print(f" 对象总数: {len(scene.get('objects', []))}") # 手动实现 sample_all_assets 的调试版本 batch_size = 4 # 小批次便于调试 sampled_scene = copy.deepcopy(scene) sampled_scene["objects"] = [] desc_size_map = {} objects = scene.get("objects", []) descriptions = [obj.get("desc") for obj in objects] sizes = [obj.get("size", []) for obj in objects] print(f"📋 准备批处理:") print(f" 描述数量: {len(descriptions)}") print(f" 大小数量: {len(sizes)}") print(f" 批大小: {batch_size}") for batch_start in range(0, len(descriptions), batch_size): batch_end = min(batch_start + batch_size, len(descriptions)) print(f"\n📦 处理批次 {batch_start}-{batch_end}") batch_descriptions = descriptions[batch_start:batch_end] batch_sizes = sizes[batch_start:batch_end] print(f" 批次描述: {len(batch_descriptions)} 条") print(f" 批次大小: {len(batch_sizes)} 条") # 获取批次概率 try: batch_probs = sampling_engine.forward_batch(batch_descriptions, batch_sizes) print(f" ✅ 批次概率计算成功: {batch_probs.shape}") except Exception as e: print(f" ❌ 批次概率计算失败: {e}") traceback.print_exc() continue # 处理批次中的每个对象 for i, obj in enumerate(objects[batch_start:batch_end]): obj_idx = batch_start + i print(f"\n🔍 处理对象 {obj_idx + 1}/{len(objects)}") if obj is None: print(f" ❌ 对象为 None,跳过") continue desc = obj.get("desc") size = obj.get("size", []) print(f" 描述: {desc[:30] if desc else 'None'}...") print(f" 大小: {size}") # 检查是否已有相同描述的对象 if desc in desc_size_map: print(f" 🔍 在缓存中查找相似对象...") matching_obj = None for j, sampled_obj in enumerate(desc_size_map[desc]): print(f" 检查缓存对象 {j+1}: {sampled_obj is not None}") if sampled_obj is None: print(f" ❌ 缓存对象 {j+1} 为 None!") continue if not isinstance(sampled_obj, dict): print(f" ❌ 缓存对象 {j+1} 不是字典: {type(sampled_obj)}") continue if "size" not in sampled_obj: print(f" ❌ 缓存对象 {j+1} 没有 size 字段!") continue cached_size = sampled_obj["size"] if cached_size is None: print(f" ❌ 缓存对象 {j+1} 的 size 为 None!") continue try: size_diff = sampling_engine.calculate_size_difference(size, cached_size) print(f" 大小差异: {size_diff} (阈值: {sampling_engine.asset_size_threshold})") if size_diff <= sampling_engine.asset_size_threshold: matching_obj = sampled_obj print(f" ✅ 找到匹配的缓存对象!") break except Exception as e: print(f" ❌ 计算大小差异失败: {e}") continue if matching_obj: print(f" ✅ 使用缓存对象") new_obj = copy.deepcopy(obj) new_obj.update({ "sampled_asset_jid": matching_obj["sampled_asset_jid"], "sampled_asset_desc": matching_obj["sampled_asset_desc"], "sampled_asset_size": matching_obj["sampled_asset_size"], "uuid": str(uuid.uuid4()) }) else: print(f" 🎯 创建新的采样对象...") new_obj = sampling_engine.create_sampled_obj(obj, batch_probs[i], True) if new_obj is not None: desc_size_map[desc].append(new_obj) print(f" ✅ 新对象已添加到缓存") else: print(f" ❌ 新对象创建失败!") continue else: print(f" 🎯 首次遇到该描述,创建新对象...") new_obj = sampling_engine.create_sampled_obj(obj, batch_probs[i], True) if new_obj is not None: desc_size_map[desc] = [new_obj] print(f" ✅ 新对象已创建缓存条目") else: print(f" ❌ 新对象创建失败!") continue if new_obj is not None: sampled_scene["objects"].append(new_obj) print(f" ✅ 对象已添加到最终场景") else: print(f" ❌ 对象为 None,跳过添加") print(f"\n🎉 采样完成!") print(f" 原始对象数: {len(objects)}") print(f" 采样对象数: {len(sampled_scene['objects'])}") print(f" 缓存条目数: {len(desc_size_map)}") return sampled_scene except Exception as e: print(f"\n❌ sample_all_assets 调试过程出错:") print(f" 错误类型: {type(e).__name__}") print(f" 错误信息: {str(e)}") traceback.print_exc() return None def main(): """主函数""" print("🔬 ReSpace Sample.py 调试工具") print("专门诊断 'NoneType' object has no attribute 'get' 错误") print("="*60) result = debug_sample_all_assets() print("\n" + "="*60) if result is not None: print("🎉 调试完成,采样过程成功执行") print("如果之前有错误,现在应该可以看到具体的问题位置") else: print("❌ 调试发现错误,请查看上面的详细信息") print("错误应该在上面的输出中有详细描述") print("="*60) if __name__ == "__main__": main()