File size: 15,164 Bytes
ebc85b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/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'<answer>(.*?)</answer>'
            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()