bangbang-aigc-server/travel-algorithms/example/vibrant_poster_example.py

222 lines
6.9 KiB
Python
Raw Normal View History

2025-07-31 15:35:23 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Vibrant海报生成使用示例
展示如何使用重构后的海报生成功能
"""
import asyncio
from pathlib import Path
from PIL import Image
# 导入算法包
from travel_algorithms import (
create_poster_pipeline,
create_default_config,
PosterGenerator,
TextGenerator
)
async def simple_vibrant_example():
"""简单的Vibrant海报生成示例"""
print("🎨 Vibrant海报生成示例")
print("=" * 40)
# 1. 创建配置(指向你的资源目录)
config = create_default_config(
resource_base_directory="./resource" # 你的提示词目录
)
# 2. 创建海报生成流水线
pipeline = create_poster_pipeline(config)
poster_generator = pipeline["poster_generator"]
text_generator = pipeline["text_generator"]
# 3. 准备内容数据也可以让AI生成
content = {
"title": "正佳极地海洋世界",
"slogan": "都说海洋馆是约会圣地!那锦峰夜场将是绝杀!",
"price": "199",
"ticket_type": "夜场票",
"content_button": "套餐内容",
"content_items": [
"正佳极地海洋世界夜场票1张",
"有效期至2025.06.02",
"多种动物表演全部免费"
],
"remarks": [
"工作日可直接入园",
"周末请提前1天预约"
],
"tag": "#520特惠",
"pagination": "1/3"
}
# 4. 生成海报(支持多种输出格式)
# 4a. 透明底图版本
print("\n🖼️ 生成透明底图海报...")
transparent_poster = await poster_generator.generate_poster(
content=content,
images=[], # 无底图
template_name="vibrant",
use_transparent_bg=True,
output_format="image"
)
# 保存透明底图海报
output_dir = Path("output")
output_dir.mkdir(exist_ok=True)
transparent_poster.save(output_dir / "vibrant_transparent.png")
print("✅ 透明底图海报已保存")
# 4b. Fabric.js JSON版本用于Web编辑器
print("\n🔧 生成Fabric.js JSON...")
test_bg = Image.new("RGB", (900, 1200), (50, 100, 150))
fabric_json = await poster_generator.generate_poster(
content=content,
images=[test_bg],
template_name="vibrant",
output_format="fabric_json"
)
import json
with open(output_dir / "vibrant_fabric.json", 'w', encoding='utf-8') as f:
json.dump(fabric_json, f, ensure_ascii=False, indent=2)
print("✅ Fabric.js JSON已保存")
# 4c. 分层数据版本替代PSD
print("\n📚 生成分层数据...")
layer_data = await poster_generator.generate_poster(
content=content,
images=[test_bg],
template_name="vibrant",
output_format="layers"
)
print(f"✅ 生成了 {len(layer_data)} 个图层")
for i, layer in enumerate(layer_data):
print(f" - {layer['name']}: {layer['type']}")
print("\n🎉 所有格式生成完成!")
async def ai_content_generation_example():
"""AI内容生成示例"""
print("\n🤖 AI内容生成示例")
print("=" * 40)
# 创建文本生成器
config = create_default_config(resource_base_directory="./resource")
pipeline = create_poster_pipeline(config)
text_generator = pipeline["text_generator"]
# 准备信息
scenic_info = """
上海迪士尼乐园
- 位于上海浦东新区
- 拥有六大主题园区
- 适合全家游玩
- 有独特的中国文化元素
"""
product_info = """
一日门票套餐
- 标准票价499
- 包含乐园门票1张
- 有效期购买后6个月内
- 特色所有游乐设施无限次
"""
try:
# 让AI生成Vibrant格式的内容
ai_content = await text_generator.generate_vibrant_content(
scenic_info=scenic_info,
product_info=product_info,
tweet_info="神奇王国等你来探索!"
)
print("✅ AI生成的内容:")
import json
print(json.dumps(ai_content, ensure_ascii=False, indent=2))
# 用AI生成的内容创建海报
config = create_default_config(resource_base_directory="./resource")
pipeline = create_poster_pipeline(config)
poster_generator = pipeline["poster_generator"]
ai_poster = await poster_generator.generate_poster(
content=ai_content,
images=[],
template_name="vibrant",
use_transparent_bg=True,
output_format="image"
)
output_dir = Path("output")
output_dir.mkdir(exist_ok=True)
ai_poster.save(output_dir / "ai_generated_poster.png")
print("✅ AI生成的海报已保存")
except Exception as e:
print(f"❌ AI内容生成失败: {e}")
print("可能是因为没有配置AI服务或提示词文件")
def show_config_example():
"""展示配置示例"""
print("\n⚙️ 配置示例")
print("=" * 40)
# 展示如何自定义配置
config = create_default_config(
resource_base_directory="./resource",
ai_model="gpt-4", # 可以换成其他模型
# 还可以添加更多配置...
)
print("✅ 配置创建成功")
print(f" - AI模型: {config.ai_model.model}")
print(f" - 资源目录: {config.resources.resource_base_directory}")
print(f" - 海报默认尺寸: {config.poster_generation.default_size}")
print(f" - 支持的颜色主题: {list(config.poster_generation.color_themes.keys())}")
async def main():
"""主函数"""
print("🚀 Vibrant海报生成系统使用示例")
print("📖 本示例展示了重构后的海报生成功能")
print("\n包含的新功能:")
print(" ✨ 透明底图支持")
print(" ✨ Fabric.js JSON输出")
print(" ✨ 分层数据替代PSD")
print(" ✨ AI驱动的内容生成")
print(" ✨ 两栏布局设计")
print(" ✨ 动态提示词加载")
print("\n" + "=" * 50)
# 展示配置
show_config_example()
# 简单的海报生成
await simple_vibrant_example()
# AI内容生成需要AI服务配置
await ai_content_generation_example()
print("\n" + "=" * 50)
print("🎊 示例演示完成!")
print("\n📁 生成的文件保存在 ./output/ 目录下")
print("📖 查看 vibrant_fabric.json 了解Fabric.js格式")
print("🎨 查看 *.png 文件了解海报效果")
if __name__ == "__main__":
asyncio.run(main())