2025-07-31 15:35:23 +08:00

237 lines
8.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Vibrant海报生成测试脚本
测试重构后的海报生成功能包括fabric.js输出和透明底图支持
"""
import asyncio
import json
from pathlib import Path
from PIL import Image
from travel_algorithms import create_poster_pipeline, create_default_config
async def test_vibrant_poster():
"""测试Vibrant海报生成功能"""
print("🎨 开始测试Vibrant海报生成功能...")
# 1. 创建配置和流水线
print("\n📋 创建配置和流水线...")
config = create_default_config(
resource_base_directory="../resource", # 假设提示词在这里
ai_model="qwq-plus"
)
pipeline = create_poster_pipeline(config)
poster_generator = pipeline["poster_generator"]
text_generator = pipeline["text_generator"]
print("✅ 流水线创建成功")
# 2. 测试Vibrant内容生成
print("\n📝 测试Vibrant内容生成...")
scenic_info = """
正佳极地海洋世界
- 位于广州天河正佳广场
- 拥有各种海洋动物表演
- 企鹅、白鲸、海豚等明星动物
- 夜场特色项目更加浪漫
"""
product_info = """
夜场门票套餐
- 价格199元
- 包含夜场门票1张
- 有效期至2025年6月2日
- 特色:动物表演全部免费观看
- 适合:情侣约会、家庭出游
"""
tweet_info = """
都说海洋馆是约会圣地!那锦峰夜场将是绝杀!
浪漫的夜晚,神秘的海底世界,还有什么比这更浪漫的吗?
"""
try:
vibrant_content = await text_generator.generate_vibrant_content(
scenic_info=scenic_info,
product_info=product_info,
tweet_info=tweet_info
)
print("✅ 内容生成成功:")
print(json.dumps(vibrant_content, ensure_ascii=False, indent=2))
except Exception as e:
print(f"❌ 内容生成失败: {e}")
# 使用默认内容继续测试
vibrant_content = {
"title": "正佳极地海洋世界",
"slogan": "都说海洋馆是约会圣地!那锦峰夜场将是绝杀!",
"price": "199",
"ticket_type": "夜场票",
"content_button": "套餐内容",
"content_items": [
"正佳极地海洋世界夜场票1张",
"有效期至2025.06.02",
"多种动物表演全部免费"
],
"remarks": [
"工作日可直接入园",
"周末请提前1天预约"
],
"tag": "#520特惠",
"pagination": ""
}
print("使用默认内容继续测试...")
# 3. 测试透明底图生成
print("\n🖼️ 测试透明底图海报生成...")
try:
transparent_poster = await poster_generator.generate_poster(
content=vibrant_content,
images=[], # 不提供图像
template_name="vibrant",
use_transparent_bg=True,
output_format="image"
)
if isinstance(transparent_poster, Image.Image):
# 保存透明底图海报
output_path = Path("test_output/vibrant_transparent.png")
output_path.parent.mkdir(exist_ok=True)
transparent_poster.save(output_path)
print(f"✅ 透明底图海报生成成功,保存至: {output_path}")
else:
print("❌ 返回的不是Image对象")
except Exception as e:
print(f"❌ 透明底图海报生成失败: {e}")
# 4. 测试Fabric.js JSON输出
print("\n🔧 测试Fabric.js JSON输出...")
try:
# 创建一个测试图像
test_image = Image.new("RGB", (900, 1200), color=(100, 150, 200))
fabric_json = await poster_generator.generate_poster(
content=vibrant_content,
images=[test_image],
template_name="vibrant",
output_format="fabric_json"
)
if isinstance(fabric_json, dict):
# 保存Fabric.js JSON
output_path = Path("test_output/vibrant_fabric.json")
output_path.parent.mkdir(exist_ok=True)
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(fabric_json, f, ensure_ascii=False, indent=2)
print(f"✅ Fabric.js JSON生成成功保存至: {output_path}")
print(f"包含 {len(fabric_json.get('objects', []))} 个对象")
else:
print("❌ 返回的不是字典对象")
except Exception as e:
print(f"❌ Fabric.js JSON生成失败: {e}")
# 5. 测试分层数据输出
print("\n📚 测试分层数据输出...")
try:
test_image = Image.new("RGB", (900, 1200), color=(100, 150, 200))
layer_data = await poster_generator.generate_poster(
content=vibrant_content,
images=[test_image],
template_name="vibrant",
output_format="layers"
)
if isinstance(layer_data, list):
print(f"✅ 分层数据生成成功,包含 {len(layer_data)} 个图层:")
for i, layer in enumerate(layer_data):
print(f" - 图层 {i+1}: {layer.get('name', 'Unknown')} ({layer.get('type', 'Unknown')})")
else:
print("❌ 返回的不是列表对象")
except Exception as e:
print(f"❌ 分层数据生成失败: {e}")
# 6. 测试常规图像海报生成
print("\n🎯 测试常规图像海报生成...")
try:
test_image = Image.new("RGB", (900, 1200), color=(50, 100, 150))
regular_poster = await poster_generator.generate_poster(
content=vibrant_content,
images=[test_image],
template_name="vibrant",
glass_intensity=1.8,
output_format="image"
)
if isinstance(regular_poster, Image.Image):
# 保存常规海报
output_path = Path("test_output/vibrant_regular.png")
output_path.parent.mkdir(exist_ok=True)
regular_poster.save(output_path)
print(f"✅ 常规海报生成成功,保存至: {output_path}")
else:
print("❌ 返回的不是Image对象")
except Exception as e:
print(f"❌ 常规海报生成失败: {e}")
print("\n🎉 Vibrant海报生成测试完成")
def test_template_manager():
"""测试模板管理器功能"""
print("\n🔧 测试模板管理器...")
config = create_default_config()
pipeline = create_poster_pipeline(config)
template_manager = pipeline["template_manager"]
# 测试获取可用模板
available_templates = template_manager.get_available_templates()
print(f"✅ 可用模板: {available_templates}")
# 测试获取模板信息
for template_name in available_templates:
try:
template_info = template_manager.get_template_info(template_name)
print(f"📋 模板 {template_name}:")
print(f" - 类名: {template_info.get('class_name')}")
print(f" - 支持功能: {template_info.get('supported_features', [])}")
except Exception as e:
print(f"❌ 获取模板 {template_name} 信息失败: {e}")
async def main():
"""主测试函数"""
print("🚀 开始Vibrant海报生成系统测试")
print("=" * 50)
# 测试模板管理器
test_template_manager()
# 测试海报生成
await test_vibrant_poster()
print("\n" + "=" * 50)
print("🎊 所有测试完成!")
if __name__ == "__main__":
asyncio.run(main())