ZoneMaestro_code / tools /utils /test_asset_system.py
kkkkiiii's picture
Add files using upload-large-folder tool
afb311a verified
#!/usr/bin/env python3
"""
快速启动脚本 - 测试整个系统
"""
import os
import sys
import json
from pathlib import Path
# 添加项目路径
SCRIPT_DIR = Path(__file__).parent
REPO_ROOT = SCRIPT_DIR.parent
sys.path.insert(0, str(REPO_ROOT))
from tools.asset_description_manager import AssetDescriptionManager
from tools.asset_finder import AssetFinder
def test_cache_manager():
"""测试缓存管理器"""
print("="*60)
print("TEST 1: Asset Description Manager")
print("="*60)
manager = AssetDescriptionManager()
# 测试保存和读取
test_uid = "test_model_uid_001"
test_desc = "A beautiful wooden chair with armrests and cushion"
print(f"✓ Created manager at: {manager.cache_file}")
# 清除测试数据
if test_uid in manager.cache:
del manager.cache[test_uid]
manager._save_cache()
print(f"\n1. Saving description...")
manager.set_description(test_uid, test_desc, category="chair")
print(f" ✓ Saved: {test_desc}")
print(f"\n2. Reading description...")
retrieved_desc = manager.get_description(test_uid)
assert retrieved_desc == test_desc, "Description mismatch!"
print(f" ✓ Retrieved: {retrieved_desc}")
print(f"\n3. Checking if exists...")
exists = manager.has_description(test_uid)
assert exists, "Should exist!"
print(f" ✓ Exists: {exists}")
print(f"\n4. Stats...")
stats = manager.get_stats()
print(f" ✓ Total cached: {stats['total_assets']}")
print(f" ✓ Cache file: {stats['cache_file']}")
print("\n✓ Cache manager test PASSED\n")
def test_asset_finder():
"""测试资产查找器"""
print("="*60)
print("TEST 2: Asset Finder")
print("="*60)
asset_lib = "/home/v-meiszhang/amlt-project/InternScenes/data/asset_library"
if not os.path.exists(asset_lib):
print(f"✗ Asset library not found: {asset_lib}")
print(" Skipping this test")
return
finder = AssetFinder(asset_lib)
print(f"✓ Created finder for: {asset_lib}")
# 测试查找
test_cases = [
"hssd-models/objects/8/8046bdb393aa1e9257f1e0611c91f89f28f37355",
"partnet_mobility/7290",
]
print(f"\nTesting asset lookup:")
for uid in test_cases:
print(f"\n Searching for: {uid}")
info = finder.find_asset_info(uid)
print(f" Found: {info['found']}")
if info['found']:
print(f" GLB: {os.path.basename(info['glb_path'])}")
print(f" Category: {info['category']}")
print("\n✓ Asset finder test PASSED\n")
def test_layout_structure():
"""测试layout文件结构"""
print("="*60)
print("TEST 3: Layout File Structure")
print("="*60)
layout_file = "/home/v-meiszhang/amlt-project/InternScenes/data/Layout_info/scannet/scene0000_01/layout_with_boundary.json"
if not os.path.exists(layout_file):
print(f"✗ Layout file not found: {layout_file}")
return
print(f"✓ Found layout file: {layout_file}")
with open(layout_file, 'r') as f:
layout = json.load(f)
print(f"\n1. Layout structure:")
print(f" ✓ Has 'instances': {'instances' in layout}")
if "instances" in layout:
num_instances = len(layout["instances"])
print(f" ✓ Number of instances: {num_instances}")
# 统计model_uid
model_uids = set()
for inst in layout["instances"]:
if "model_uid" in inst:
model_uids.add(inst["model_uid"])
print(f" ✓ Unique model UIDs: {len(model_uids)}")
# 显示样本
print(f"\n2. Sample instance:")
if layout["instances"]:
sample = layout["instances"][0]
for key, value in sample.items():
if key != "pos" and key != "rot" and key != "size":
print(f" {key}: {value}")
# 检查是否已有description字段
has_desc = any("description" in inst for inst in layout["instances"])
print(f"\n3. Current status:")
print(f" ✓ Already has description field: {has_desc}")
print("\n✓ Layout structure test PASSED\n")
def test_gpt_setup():
"""测试Azure OpenAI API设置"""
print("="*60)
print("TEST 4: Azure GPT API Setup")
print("="*60)
try:
from openai import AzureOpenAI
from azure.identity import ChainedTokenCredential, AzureCliCredential, ManagedIdentityCredential, get_bearer_token_provider
print("✓ Azure OpenAI packages are installed")
# Try to initialize the client
try:
scope = "api://trapi/.default"
credential = get_bearer_token_provider(ChainedTokenCredential(
AzureCliCredential(),
ManagedIdentityCredential(),
), scope)
api_version = '2024-12-01-preview'
deployment_name = 'gpt-4o_2024-11-20'
instance = 'msra/shared'
endpoint = f'https://trapi.research.microsoft.com/{instance}'
client = AzureOpenAI(
azure_endpoint=endpoint,
azure_ad_token_provider=credential,
api_version=api_version,
)
print("✓ Azure OpenAI client created successfully")
# Test simple API call
print("\nTesting API connection...")
response = client.chat.completions.create(
model=deployment_name,
messages=[
{"role": "user", "content": "Say 'test' in one word."}
],
max_tokens=10
)
print(f"✓ API Response: {response.choices[0].message.content}")
print("✓ Azure OpenAI API is working!")
except Exception as e:
print(f"⚠ Failed to initialize Azure OpenAI client: {e}")
print(" Make sure you are logged in with: az login")
except ImportError as e:
print("✗ Azure OpenAI packages not installed")
print(f" Error: {e}")
print(" Install with: pip install openai azure-identity")
except Exception as e:
print(f"✗ Error: {e}")
print()
def test_render_script():
"""测试render_to_image.py"""
print("="*60)
print("TEST 5: Render Script Availability")
print("="*60)
render_script = Path(__file__).parent.parent / "render_to_image.py"
if render_script.exists():
print(f"✓ Found render script: {render_script}")
# 尝试导入或检查语法
try:
with open(render_script, 'r') as f:
content = f.read(100)
print(f"✓ Script is readable")
except Exception as e:
print(f"✗ Cannot read script: {e}")
else:
print(f"✗ render_to_image.py not found at: {render_script}")
print()
def main():
print("\n" + "="*60)
print("ASSET DESCRIPTION SYSTEM - QUICK START TEST")
print("="*60 + "\n")
try:
test_cache_manager()
test_asset_finder()
test_layout_structure()
test_gpt_setup()
test_render_script()
print("="*60)
print("ALL TESTS COMPLETED")
print("="*60)
print("\nNext steps:")
print("1. Make sure you are logged in with: az login")
print("2. Run: python tools/process_asset_descriptions.py --dry-run")
print("3. Then: python tools/process_asset_descriptions.py")
print()
except Exception as e:
print(f"\n✗ Test failed with error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()