diff --git a/API_文档.md b/API_文档.md deleted file mode 100644 index 247c9a1..0000000 --- a/API_文档.md +++ /dev/null @@ -1,597 +0,0 @@ -# AI海报生成系统 API 文档 - -## 🎯 API概览 - -AI海报生成系统提供统一的REST API接口,一键生成Vue组件代码和PSD文件。 - -**基础URL**: `http://localhost:8000` - -**主要特性**: -- 🚀 一键生成Vue代码和PSD文件 -- 🎨 集成多个AI模型(DeepSeek + Kimi + ComfyUI) -- 📁 会话管理和文件下载 -- 🔄 自动图片生成和合成 - -## 📋 API端点总览 - -| 端点 | 方法 | 描述 | 状态 | -|------|------|------|------| -| `/` | GET | 获取API信息 | ✅ | -| `/health` | GET | 健康检查 | ✅ | -| `/api/generate-poster` | POST | **主要接口** - 生成海报 | ✅ | -| `/api/download/{file_type}` | GET | 下载文件 | ✅ | -| `/api/status/{session_id}` | GET | 获取会话状态 | ✅ | - -## 🔧 主要接口详情 - -### 1. 生成海报(核心接口) - -**POST** `/api/generate-poster` - -这是唯一需要的主要接口,一次调用完成所有生成任务。 - -**请求示例**: -```json -{ - "user_input": "端午节海报,传统风格,包含荷花和龙舟", - "session_id": "可选 - 用于跟踪会话" -} -``` - -**完整响应示例**: -```json -{ - "status": "success", - "message": "海报生成完成", - "data": { - "vue_code": "完整的Vue 3组件代码", - "suggestions": { - "layer5_logo_content": { - "text": "主办方", - "color": "#000000" - }, - "layer6_title_content": { - "content": "端午节安康", - "font_name": "SimHei", - "color": "#7E0C6E" - }, - "layer7_subtitle_content": { - "content": "粽叶飘香,龙舟竞渡,共庆端午佳节", - "font_name": "Microsoft YaHei", - "color": "#000000" - } - }, - "analysis_result": { - "analyzed_prompt": "端午节海报,传统风格", - "main_theme": "端午节祝福", - "style_preference": "传统", - "width": 1080, - "height": 1920, - "keywords": ["端午节", "传统", "荷花", "龙舟"] - }, - "psd_file_path": "/path/to/session_xxx/final_poster.psd", - "file_size_mb": 5.93, - "generated_images": 2, - "files": { - "vue_file": "/path/to/generated_code.vue", - "psd_file": "/path/to/final_poster.psd" - } - }, - "session_id": "uuid-generated-session-id" -} -``` - -### 2. 文件下载 - -**GET** `/api/download/{file_type}?session_id={session_id}` - -**参数**: -- `file_type`: 文件类型 - - `vue` - Vue组件文件 - - `psd` - PSD文件 - - `json` - 文案建议JSON文件 -- `session_id`: 会话ID(必需) - -**响应**: 直接返回文件流,浏览器会自动下载 - -### 3. 健康检查 - -**GET** `/health` - -**响应**: -```json -{ - "status": "healthy", - "timestamp": "2025-01-02T20:30:00.123456" -} -``` - -### 4. 会话状态查询 - -**GET** `/api/status/{session_id}` - -**响应**: -```json -{ - "status": "success", - "message": "状态获取成功", - "data": { - "user_input": "端午节海报,传统风格", - "analysis_result": "...", - "suggestions": "...", - "vue_path": "/path/to/vue/file", - "psd_path": "/path/to/psd/file", - "created_at": "2025-01-02T20:30:00" - }, - "session_id": "session-id" -} -``` - -## 🛠️ 前端集成指南 - -### JavaScript ES6+ 示例 - -```javascript -class PosterGenerator { - constructor(baseUrl = 'http://localhost:8000') { - this.baseUrl = baseUrl; - } - - // 主要方法:生成海报 - async generatePoster(userInput) { - try { - const response = await fetch(`${this.baseUrl}/api/generate-poster`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - user_input: userInput - }) - }); - - const result = await response.json(); - - if (result.status === 'success') { - console.log('✅ 海报生成成功'); - console.log('Vue代码长度:', result.data.vue_code.length); - console.log('PSD文件大小:', result.data.file_size_mb, 'MB'); - console.log('生成的图片数量:', result.data.generated_images); - - return result; - } else { - throw new Error(result.message || '生成失败'); - } - } catch (error) { - console.error('❌ 海报生成失败:', error); - throw error; - } - } - - // 下载文件 - downloadFile(sessionId, fileType) { - const url = `${this.baseUrl}/api/download/${fileType}?session_id=${sessionId}`; - const a = document.createElement('a'); - a.href = url; - a.download = ''; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - } - - // 获取会话状态 - async getSessionStatus(sessionId) { - const response = await fetch(`${this.baseUrl}/api/status/${sessionId}`); - return await response.json(); - } -} - -// 使用示例 -const generator = new PosterGenerator(); - -async function createPoster() { - try { - // 生成海报 - const result = await generator.generatePoster("春节海报,红色背景,现代风格"); - - // 显示Vue代码 - document.getElementById('vue-code').textContent = result.data.vue_code; - - // 显示文案建议 - document.getElementById('suggestions').textContent = - JSON.stringify(result.data.suggestions, null, 2); - - // 设置下载按钮 - document.getElementById('download-vue').onclick = () => - generator.downloadFile(result.session_id, 'vue'); - document.getElementById('download-psd').onclick = () => - generator.downloadFile(result.session_id, 'psd'); - - } catch (error) { - alert('生成失败: ' + error.message); - } -} -``` - -### Vue.js 组件示例 - -```vue - - - - - -``` - -## ⚡ 快速开始 - -### 1. 启动服务器 -```bash -cd E:\砚生\ai_service\scripts -python run_pipeline.py -# 选择: 2 (API服务器模式) -``` - -### 2. 测试API -```bash -# 健康检查 -curl http://localhost:8000/health - -# 生成海报 -curl -X POST http://localhost:8000/api/generate-poster \ - -H "Content-Type: application/json" \ - -d '{"user_input": "春节海报,红色背景,现代风格"}' -``` - -### 3. 前端调用 -```javascript -// 最简单的调用方式 -fetch('http://localhost:8000/api/generate-poster', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ user_input: '端午节海报,传统风格' }) -}) -.then(response => response.json()) -.then(data => { - if (data.status === 'success') { - console.log('Vue代码:', data.data.vue_code); - // 下载PSD文件 - window.open(`http://localhost:8000/api/download/psd?session_id=${data.session_id}`); - } -}); -``` - -## 🔧 错误处理 - -### 错误响应格式 -```json -{ - "detail": "具体错误信息" -} -``` - -### 常见错误 -- **400 Bad Request**: 请求参数错误 -- **404 Not Found**: 会话不存在或文件不存在 -- **500 Internal Server Error**: 服务器内部错误 - -### 错误处理示例 -```javascript -try { - const response = await fetch('/api/generate-poster', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ user_input: 'test' }) - }); - - if (!response.ok) { - const error = await response.json(); - throw new Error(error.detail || '请求失败'); - } - - const result = await response.json(); - // 处理成功结果 -} catch (error) { - console.error('API调用失败:', error.message); - // 显示错误给用户 -} -``` - -## 🚀 部署配置 - -### 开发环境 -```bash -# 启动开发服务器 -python run_pipeline.py -# 访问: http://localhost:8000 -``` - -### 生产环境 -```bash -# 使用uvicorn直接运行 -uvicorn run_pipeline:app --host 0.0.0.0 --port 8000 - -# 或使用PM2管理 -pm2 start "uvicorn run_pipeline:app --host 0.0.0.0 --port 8000" --name poster-api -``` - -### Docker部署 -```dockerfile -FROM python:3.11 -WORKDIR /app -COPY . . -RUN pip install -r requirements.txt -EXPOSE 8000 -CMD ["uvicorn", "scripts.run_pipeline:app", "--host", "0.0.0.0", "--port", "8000"] -``` - -## 📝 更新日志 - -### v1.0.0 (2025-01-02) -- ✅ 统一API接口设计 -- ✅ 集成DeepSeek + Kimi + ComfyUI -- ✅ 支持Vue组件和PSD文件生成 -- ✅ 会话管理和文件下载 -- ✅ 完整的错误处理和文档 diff --git a/Linux部署指南.md b/Linux部署指南.md deleted file mode 100644 index 8b13789..0000000 --- a/Linux部署指南.md +++ /dev/null @@ -1 +0,0 @@ - diff --git a/README.md b/README.md index 3367724..381e2a1 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,27 @@ # AI海报生成系统 -## 🎯 项目概述 +## 概述 -AI海报生成系统是一个集成多个AI模型的智能海报生成平台,能够根据用户输入一键生成Vue组件代码和PSD文件。 +AI海报生成系统集成DeepSeek、Kimi、ComfyUI三大AI模型,一键生成Vue组件代码和PSD文件。 -**核心特性**: -- 🤖 **AI驱动**: 集成DeepSeek、Kimi、ComfyUI三大AI模型 -- 🎨 **一键生成**: 输入需求,自动生成Vue代码和PSD文件 -- 📱 **前端友好**: 提供统一的REST API接口 -- 🎭 **智能排版**: 自动生成响应式Vue组件布局 -- 🖼️ **图片合成**: 自动生成图片并合成PSD文件 -- ✍️ **文案优化**: AI生成适配的标题和文案内容 +**核心功能**: +- 🤖 **AI驱动**: DeepSeek分析 + Kimi文案 + ComfyUI图片 +- 🎨 **一键生成**: 输入需求 → Vue代码 + PSD文件 +- 📱 **REST API**: 统一接口,支持前端集成 +- 🎭 **预定义模板**: lotus.jpg, nku.png, stamp.jpg, background.png +- 🖼️ **自动合成**: 多图层PSD文件生成 -## 🏗️ 系统架构 +## 系统架构 ``` -┌─────────────┐ HTTP请求 ┌──────────────┐ 调用AI服务 ┌─────────────┐ -│ 前端 │ ─────────────→ │ FastAPI服务器 │ ─────────────→ │ AI模型集群 │ -│ (Vue/React) │ │ (8000端口) │ │ │ -└─────────────┘ └──────────────┘ └─────────────┘ - │ │ - ▼ ▼ - ┌──────────────┐ ┌─────────────┐ - │ 会话管理 │ │ ComfyUI图片 │ - │ 文件存储 │ │ 生成服务 │ - └──────────────┘ │ (101.201.50.90) │ - └─────────────┘ +前端 → FastAPI(8000) → AI模型集群 + ↓ + Vue代码 + PSD文件 ``` -## 🚀 快速开始 +## 快速开始 ### 环境准备 - -1. **Python环境**: ```bash # 创建虚拟环境 conda create -n ai_service python=3.11 @@ -40,235 +29,105 @@ conda activate ai_service # 安装依赖 pip install -r requirements.txt -``` -2. **环境配置**: -```bash -# 复制环境变量文件 +# 配置API密钥 cp .env.example .env - -# 配置API密钥(编辑.env文件) -DEEPSEEK_API_KEY=your_deepseek_api_key -MOONSHOT_API_KEY=your_kimi_api_key +# 编辑 .env 文件,添加: +# DEEPSEEK_API_KEY=your_key +# MOONSHOT_API_KEY=your_key ``` ### 启动服务 - -#### 方式1: 交互式启动 ```bash cd scripts -python run_pipeline.py -# 选择: 2 (API服务器模式) -``` - -#### 方式2: 直接启动API服务器 -```bash -cd scripts -uvicorn run_pipeline:app --host 0.0.0.0 --port 8000 --reload +python run_pipeline.py # 选择: 2 (API服务器) ``` ### 验证服务 - ```bash -# 健康检查 curl http://localhost:8000/health - -# 查看API信息 -curl http://localhost:8000/ ``` -## 📋 主要功能 - -### 1. 智能需求分析 -- 使用**DeepSeek**模型分析用户输入 -- 提取主题、风格、尺寸等关键信息 -- 生成结构化的设计参数 - -### 2. AI图片生成 -- 调用**ComfyUI**服务(101.201.50.90:8188) -- 根据分析结果生成高质量图片 -- 支持多种风格和主题 - -### 3. 智能文案生成 -- 使用**Kimi**模型生成文案内容 -- 智能选择字体和颜色搭配 -- 支持多层级文案结构 - -### 4. Vue组件生成 -- 使用**DeepSeek**生成Vue 3组件代码 -- 响应式布局设计 -- 完整的template、script、style结构 - -### 5. PSD文件合成 -- 自动合成多图层PSD文件 -- 支持手动PSD模板优先 -- 包含预览图片生成 - -## 🛠️ 使用方法 - -### API调用 - -```javascript -// 一键生成海报 -const response = await fetch('http://localhost:8000/api/generate-poster', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - user_input: "端午节海报,传统风格,包含荷花和龙舟" - }) -}); - -const result = await response.json(); - -if (result.status === 'success') { - // 获取Vue代码 - console.log('Vue代码:', result.data.vue_code); - - // 获取文案建议 - console.log('文案建议:', result.data.suggestions); - - // 下载PSD文件 - const downloadUrl = `http://localhost:8000/api/download/psd?session_id=${result.session_id}`; - window.open(downloadUrl); -} -``` - -### 本地开发测试 +## API使用 +### 生成海报 ```bash -cd scripts -python run_pipeline.py -# 选择: 1 (本地测试模式) -# 输入: "春节海报,红色背景,现代风格" +curl -X POST http://localhost:8000/api/generate-poster \ + -H "Content-Type: application/json" \ + -d '{"user_input": "端午节海报,传统风格"}' ``` -## 📁 项目结构 +### 下载文件 +```bash +curl "http://localhost:8000/api/download/psd?session_id=SESSION_ID" -o poster.psd +curl "http://localhost:8000/api/download/vue?session_id=SESSION_ID" -o poster.vue +``` + +## 项目结构 ``` ai_service/ -├── scripts/ # 核心脚本 -│ ├── run_pipeline.py # 主服务入口和API服务器 -│ ├── prompt_analysis.py # 用户输入分析 (DeepSeek) -│ ├── flux_con.py # 图片生成 (ComfyUI) -│ ├── generate_text.py # 文案生成 (Kimi) -│ ├── generate_layout.py # Vue代码生成 (DeepSeek) -│ └── export_psd_from_json.py # PSD文件合成 -├── configs/ # 配置文件 -│ ├── font.yaml # 字体配置 -│ └── example.json # 配置示例 -├── outputs/ # 输出目录 -│ ├── session_*/ # 会话相关文件 -│ ├── *.psd # 生成的PSD文件 -│ ├── *.vue # 生成的Vue组件 -│ └── *.png # 生成的图片 -├── workflows/ # ComfyUI工作流 -│ ├── flux_work.json # 主要工作流配置 -│ └── temp/ # 临时工作流文件 -├── README.md # 项目说明 -├── requirements.txt # Python依赖 -├── API_文档.md # API使用文档 -├── 接口文档.md # 接口技术文档 -└── 部署方案.md # 部署指南 +├── scripts/ # 核心脚本 +│ ├── run_pipeline.py # API服务器 +│ ├── utils.py # 工具函数 +│ ├── generate_layout.py # Vue代码生成 +│ ├── generate_text.py # 文案生成 +│ ├── flux_con.py # 图片生成 +│ └── export_psd_from_json.py # PSD合成 +├── configs/ # 配置文件 +│ ├── vue_templates.yaml # Vue模板 +│ └── font.yaml # 字体配置 +├── outputs/ # 输出目录 +└── workflows/ # ComfyUI工作流 ``` -## 🔧 核心模块 +## 核心模块 -### 1. prompt_analysis.py -- **功能**: 使用DeepSeek分析用户输入 -- **输入**: 用户描述文本 -- **输出**: 结构化分析结果 +| 模块 | 功能 | AI模型 | +|------|------|--------| +| `utils.py` | 用户输入分析 | DeepSeek | +| `flux_con.py` | 图片生成 | ComfyUI | +| `generate_text.py` | 文案生成 | Kimi | +| `generate_layout.py` | Vue代码生成 | DeepSeek | +| `export_psd_from_json.py` | PSD合成 | - | + +## 使用示例 + +### JavaScript调用 +```javascript +const response = await fetch('http://localhost:8000/api/generate-poster', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ user_input: "春节海报,红色背景" }) +}); + +const result = await response.json(); +console.log('Vue代码:', result.data.vue_code); +``` + +### Python调用 ```python -user_input_analysis_result = llm_user_analysis("端午节海报,传统风格") +import requests + +response = requests.post('http://localhost:8000/api/generate-poster', + json={"user_input": "端午节海报,传统风格"}) +result = response.json() + +if result["status"] == "success": + print("生成成功!") + print("Vue代码:", result["data"]["vue_code"]) ``` -### 2. flux_con.py -- **功能**: 调用ComfyUI生成图片 -- **输入**: 分析结果和系统提示 -- **输出**: 图片文件列表 -```python -parse_imglist = comfyui_img_info(user_input_analysis_result, system_prompt) -``` - -### 3. generate_text.py -- **功能**: 使用Kimi生成文案建议 -- **输入**: 分析后的提示词 -- **输出**: 分层文案内容 -```python -suggestions = get_poster_content_suggestions(analyzed_prompt) -``` - -### 4. generate_layout.py -- **功能**: 使用DeepSeek生成Vue组件 -- **输入**: 布局提示词 -- **输出**: 完整Vue组件代码 -```python -vue_code = generate_vue_code(prompt) -``` - -### 5. export_psd_from_json.py -- **功能**: 合成PSD文件 -- **输入**: 图片路径列表 -- **输出**: PSD文件 -```python -create_psd_from_images(image_paths, output_path, canvas_size) -``` - -## 🌐 API接口 - -### 主要接口 - -| 接口 | 方法 | 功能 | 状态 | -|------|------|------|------| -| `/api/generate-poster` | POST | 一键生成海报 | ✅ | -| `/api/download/{type}` | GET | 文件下载 | ✅ | -| `/api/status/{session_id}` | GET | 会话状态 | ✅ | -| `/health` | GET | 健康检查 | ✅ | - -### 请求示例 - +### 本地测试 ```bash -# 生成海报 -curl -X POST http://localhost:8000/api/generate-poster \ - -H "Content-Type: application/json" \ - -d '{"user_input": "春节海报,红色背景,现代风格"}' - -# 下载PSD文件 -curl "http://localhost:8000/api/download/psd?session_id=SESSION_ID" \ - --output poster.psd +cd scripts +python run_pipeline.py # 选择: 1 (本地测试) +# 输入: "春节海报,红色背景,现代风格" ``` -## 🎨 使用示例 +## 部署 -### 1. 传统节日海报 -``` -输入: "端午节海报,传统风格,包含荷花和龙舟" -输出: 传统中式风格的Vue组件 + 精美PSD文件 -``` - -### 2. 现代活动海报 -``` -输入: "科技大会海报,现代简约风格,蓝色主题" -输出: 现代简约风格的Vue组件 + 科技感PSD文件 -``` - -### 3. 节庆祝福海报 -``` -输入: "春节祝福海报,红色背景,包含灯笼烟花" -输出: 喜庆风格的Vue组件 + 节日氛围PSD文件 -``` - -## 🚀 部署方案 - -### 开发环境 -```bash -# 本地启动 -python scripts/run_pipeline.py -# 访问: http://localhost:8000 -``` - -### 生产环境 - -#### Docker部署 +### Docker部署 ```dockerfile FROM python:3.11 WORKDIR /app @@ -278,124 +137,44 @@ EXPOSE 8000 CMD ["uvicorn", "scripts.run_pipeline:app", "--host", "0.0.0.0", "--port", "8000"] ``` +### PM2部署 ```bash -# 构建和运行 -docker build -t ai-poster-generator . -docker run -p 8000:8000 ai-poster-generator -``` - -#### PM2部署 -```bash -# 安装PM2 -npm install -g pm2 - -# 启动服务 pm2 start "uvicorn scripts.run_pipeline:app --host 0.0.0.0 --port 8000" --name poster-api - -# 开机自启 -pm2 startup -pm2 save ``` -### 反向代理(Nginx) +### Nginx反向代理 ```nginx server { listen 80; - server_name your-domain.com; - location / { proxy_pass http://localhost:8000; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } ``` -## 🔍 故障排查 +## 故障排查 ### 常见问题 - -1. **API密钥错误** ```bash -# 检查环境变量 +# 检查API密钥 echo $DEEPSEEK_API_KEY -echo $MOONSHOT_API_KEY -``` -2. **ComfyUI连接失败** -```bash # 测试ComfyUI连接 curl http://101.201.50.90:8188/system_stats -``` -3. **PSD生成失败** -```bash -# 检查pytoshop安装 -pip show pytoshop psd-tools -``` - -4. **端口被占用** -```bash -# 查找占用端口的进程 +# 检查端口占用 netstat -tulpn | grep 8000 -# 或使用其他端口 -uvicorn run_pipeline:app --port 8001 ``` -### 日志查看 -```bash -# 查看实时日志 -tail -f logs/app.log +## 更新日志 -# 检查错误日志 -grep -i error logs/app.log -``` - -## 🤝 贡献指南 - -### 开发环境搭建 -```bash -# 克隆项目 -git clone -cd ai_service - -# 安装开发依赖 -pip install -r requirements.txt -pip install -r requirements-dev.txt - -# 运行测试 -pytest tests/ -``` - -### 代码规范 -- 使用Python 3.11+ -- 遵循PEP 8代码风格 -- 添加类型注解 -- 编写单元测试 - -## 📄 License - -MIT License - 详见 [LICENSE](LICENSE) 文件 - -## 📞 联系方式 - -- **项目维护**: AI海报生成系统团队 -- **技术支持**: 查看[API文档](API_文档.md)和[接口文档](接口文档.md) -- **问题反馈**: 提交Issue到项目仓库 - -## 📝 更新日志 +### v2.0.0 (2025-07-03) +- ✅ 重构代码结构,移除冗余代码 +- ✅ 新增预定义Vue模板系统 +- ✅ 优化工具函数模块化 +- ✅ 简化API接口设计 ### v1.0.0 (2025-01-02) - ✅ 集成DeepSeek + Kimi + ComfyUI - ✅ 统一API接口设计 -- ✅ 支持Vue组件生成 -- ✅ 支持PSD文件合成 -- ✅ 完整的会话管理 -- ✅ 丰富的文档和示例 - -### 近期规划 -- 🔄 支持更多图片风格 -- 🔄 增加文案模板库 -- 🔄 优化PSD分层效果 -- 🔄 增加批量生成功能 +- ✅ 支持Vue组件和PSD文件生成 diff --git a/configs/vue_templates.yaml b/configs/vue_templates.yaml new file mode 100644 index 0000000..b9469bf --- /dev/null +++ b/configs/vue_templates.yaml @@ -0,0 +1,538 @@ +# Vue模板配置文件 +# 为不同图片类型预定义Vue组件模板 + +vue_templates: + lotus.jpg: + theme: "荷花主题" + style: "传统优雅" + template: | + + + + + + + nku.png: + theme: "南开大学" + style: "学术正式" + template: | + + + + + + + stamp.jpg: + theme: "印章装饰" + style: "传统文化" + template: | + + + + + + + background.png: + theme: "通用背景" + style: "简约现代" + template: | + + + + + diff --git a/outputs/80155705_20250703114134_0.png b/outputs/80155705_20250703114134_0.png new file mode 100644 index 0000000..b154ebc Binary files /dev/null and b/outputs/80155705_20250703114134_0.png differ diff --git a/outputs/80155705_20250703114134_1.png b/outputs/80155705_20250703114134_1.png new file mode 100644 index 0000000..c9ea013 Binary files /dev/null and b/outputs/80155705_20250703114134_1.png differ diff --git a/outputs/98856890_20250702220533_0.png b/outputs/98856890_20250702220533_0.png new file mode 100644 index 0000000..08c2392 Binary files /dev/null and b/outputs/98856890_20250702220533_0.png differ diff --git a/outputs/98856890_20250702220533_1.png b/outputs/98856890_20250702220533_1.png new file mode 100644 index 0000000..683939b Binary files /dev/null and b/outputs/98856890_20250702220533_1.png differ diff --git a/outputs/generated_code.vue b/outputs/generated_code.vue index 04c9dc1..2a25d60 100644 --- a/outputs/generated_code.vue +++ b/outputs/generated_code.vue @@ -1,11 +1,23 @@ @@ -13,88 +25,96 @@ \ No newline at end of file + +.lotus-subtitle { + font-size: 32px; + color: #4a6741; + margin-bottom: 40px; + font-family: 'KaiTi', cursive; +} + +.lotus-content { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 70%; +} + +.lotus-decoration { + width: 200px; + height: 200px; + background: radial-gradient(circle, rgba(255,192,203,0.6), rgba(255,182,193,0.3)); + border-radius: 50%; + margin: 0 auto; +} + +.footer-section { + position: absolute; + bottom: 10%; + left: 50%; + transform: translateX(-50%); +} + +.logo-text { + font-size: 24px; + color: #2d5016; + font-weight: 500; +} + diff --git a/outputs/poster_content.json b/outputs/poster_content.json index b83da0f..f5cd123 100644 --- a/outputs/poster_content.json +++ b/outputs/poster_content.json @@ -4,13 +4,13 @@ "color": "#000000" }, "layer6_title_content": { - "content": "端午节安康", + "content": "端午节", "font_name": "SimHei", "color": "#000000" }, "layer7_subtitle_content": { - "content": "粽叶飘香,龙舟竞渡,共庆端午佳节。", - "font_name": "Microsoft YaHei", + "content": "粽叶飘香,龙舟竞渡", + "font_name": "SimHei", "color": "#7E0C6E" } } \ No newline at end of file diff --git a/outputs/temp_config.yaml b/outputs/temp_config.yaml new file mode 100644 index 0000000..6834e55 --- /dev/null +++ b/outputs/temp_config.yaml @@ -0,0 +1,37 @@ +available_fonts: +- displayName: 微软雅黑 + name: Microsoft YaHei + roles: + - title + - subtitle + - content + tags: + - 现代 + - 清晰 +- displayName: 黑体 + name: SimHei + roles: + - title + - subtitle + - content + tags: + - 通用 + - 标准 +default_logo_text: '' +vue_templates: + background.png: + style: 简约现代 + template_name: background_template + theme: 通用背景 + lotus.jpg: + style: 传统优雅 + template_name: lotus_template + theme: 荷花主题 + nku.png: + style: 学术正式 + template_name: nku_template + theme: 南开大学 + stamp.jpg: + style: 传统文化 + template_name: stamp_template + theme: 印章装饰 diff --git a/requirments.txt b/requirments.txt deleted file mode 100644 index 948a569..0000000 Binary files a/requirments.txt and /dev/null differ diff --git a/scripts/__pycache__/generate_layout.cpython-311.pyc b/scripts/__pycache__/generate_layout.cpython-311.pyc index 48cf8dc..0588cad 100644 Binary files a/scripts/__pycache__/generate_layout.cpython-311.pyc and b/scripts/__pycache__/generate_layout.cpython-311.pyc differ diff --git a/scripts/__pycache__/prompt_analysis.cpython-311.pyc b/scripts/__pycache__/prompt_analysis.cpython-311.pyc deleted file mode 100644 index fb250f5..0000000 Binary files a/scripts/__pycache__/prompt_analysis.cpython-311.pyc and /dev/null differ diff --git a/scripts/__pycache__/utils.cpython-311.pyc b/scripts/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000..c0307ec Binary files /dev/null and b/scripts/__pycache__/utils.cpython-311.pyc differ diff --git a/scripts/generate_layout.py b/scripts/generate_layout.py index 5313d4a..6094cc5 100644 --- a/scripts/generate_layout.py +++ b/scripts/generate_layout.py @@ -1,43 +1,44 @@ """ @file generate_layout.py @brief Vue组件代码生成模块 - 基于DeepSeek API生成响应式Vue 3组件布局代码 + 基于DeepSeek API生成响应式Vue 3组件布局代码,支持预定义模板 @author 王秀强 (2310460@mail.nankai.edu.cn) @date 2025.5.19 -@version v1.0.0 +@version v2.0.0 @details 本文件主要实现: - DeepSeek API调用封装和错误处理 - Vue 3 Composition API组件代码生成 - 海报布局的动态排版和样式生成 + - 预定义Vue模板系统 + - 增强Vue代码生成逻辑 - 代码清理和格式化处理 - - 备用Vue模板生成机制 @note - 需要配置DEEPSEEK_API_KEY环境变量 - 支持流式和非流式响应模式 - 生成的Vue代码包含完整的template、script和style部分 - 具备指数退避重试机制处理API限流 +- 支持基于图片类型的预定义模板 @usage # 生成Vue组件代码 -vue_code = generate_vue_code("生成端午节海报Vue组件") +vue_code = generate_vue_code_enhanced("生成端午节海报Vue组件", parse_imglist, suggestions) save_code(vue_code, "../outputs/poster.vue") -# 调用DeepSeek API -result, usage = call_deepseek(prompt="请生成代码", temperature=0.6) - @copyright (c) 2025 砚生项目组 """ import os +import yaml from openai import OpenAI from dotenv import load_dotenv import time from colorama import init, Fore, Back, Style +from typing import List, Dict, Optional # 初始化colorama init(autoreset=True) @@ -125,9 +126,193 @@ def call_deepseek( raise Exception("达到最大重试次数,API 调用失败") +def load_vue_templates() -> Dict: + """加载预定义的Vue模板配置""" + template_path = "../configs/vue_templates.yaml" + + try: + with open(template_path, 'r', encoding='utf-8') as f: + templates = yaml.safe_load(f) + print(f"{Fore.GREEN}✅ Vue模板配置加载成功{Style.RESET_ALL}") + return templates.get('vue_templates', {}) + except Exception as e: + print(f"{Fore.YELLOW}⚠️ Vue模板配置加载失败: {e},使用默认模板{Style.RESET_ALL}") + return {} + + +def get_template_by_images(parse_imglist: List[Dict]) -> Optional[str]: + """ + 根据图片列表选择合适的预定义模板 + + 参数: + parse_imglist: 图片信息列表 + + 返回: + 选中的模板代码,如果没有匹配的模板则返回None + """ + templates = load_vue_templates() + + if not templates or not parse_imglist: + return None + + # 检查固定的图片文件 + fixed_images = ["lotus.jpg", "nku.png", "stamp.jpg", "background.png"] + + for img_name in fixed_images: + img_path = f"../outputs/{img_name}" + if os.path.exists(img_path) and img_name in templates: + print(f"{Fore.CYAN}📋 找到匹配的预定义模板: {img_name}{Style.RESET_ALL}") + return templates[img_name]['template'] + + print(f"{Fore.YELLOW}⚠️ 未找到匹配的预定义模板,将使用AI生成{Style.RESET_ALL}") + return None + + +def generate_layout_prompt(user_input_analysis_result: Dict, parse_imglist: List[Dict], suggestions: Dict = None) -> str: + """ + 生成增强的Vue布局提示,包含文案内容 + 这个函数从run_pipeline.py移动到这里 + """ + width = user_input_analysis_result.get("width", 1080) + height = user_input_analysis_result.get("height", 1920) + theme = user_input_analysis_result.get("main_theme", "活动海报") + + # 构造图片信息字符串 + images_info = "\n".join( + [f"- {img['picture_name']} ({img['picture_description']})" for img in parse_imglist] + ) + + # 构造文案信息 + content_info = "" + if suggestions: + try: + if 'layer6_title_content' in suggestions: + title = suggestions['layer6_title_content'].get('content', theme) + content_info += f"- 主标题: {title}\n" + + if 'layer7_subtitle_content' in suggestions: + subtitle = suggestions['layer7_subtitle_content'].get('content', '精彩活动,敬请参与') + content_info += f"- 副标题: {subtitle}\n" + + if 'layer5_logo_content' in suggestions: + logo = suggestions['layer5_logo_content'].get('text', '主办方') + content_info += f"- Logo文字: {logo}\n" + except Exception as e: + print(f"{Fore.YELLOW}⚠️ 文案信息解析错误: {e}{Style.RESET_ALL}") + content_info = f"- 主标题: {theme}\n- 副标题: 精彩活动,敬请参与\n" + + # 调用DeepSeek生成动态排版Prompt + system_prompt = "你是一个擅长前端开发的AI,专注于生成Vue.js代码。请根据提供的信息生成完整的Vue组件,包含所有必要的HTML结构和基础定位样式。" + + prompt = f""" + 请生成一个Vue.js组件代码,用于{theme}海报,要求如下: + + 组件尺寸: {width}x{height}px + + 图片资源: + {images_info} + + 文案内容: + {content_info} + + 布局要求: + 1. 背景图层: 使用第一张图片作为背景,占据整个组件区域 + 2. 主标题: 位于画布上方1/3处,居中显示 + 3. 副标题: 位于主标题下方,居中显示 + 4. 内容区域: 使用剩余图片,合理布局在中间区域 + 5. Logo区域: 位于底部,居中显示 + + 技术要求: + - 使用Vue 3 Composition API + - 使用absolute定位进行精确布局 + - 包含完整的template、script和style部分 + - 确保所有文本内容都正确显示 + - 图片使用相对路径引用 + + 请生成完整可用的Vue组件代码,不要包含任何说明文字。 + """ + + try: + result, _ = call_deepseek(prompt=prompt, system_prompt=system_prompt, temperature=0.4) + return result + except Exception as e: + print(f"{Fore.RED}❌ 布局提示生成失败: {e}{Style.RESET_ALL}") + return generate_fallback_vue_code(theme, width, height) + + +def fill_template_content(template: str, suggestions: Dict) -> str: + """ + 填充模板中的动态内容 + + 参数: + template: Vue模板代码 + suggestions: 文案建议 + + 返回: + 填充后的Vue代码 + """ + filled_template = template + + try: + # 提取文案内容 + title_content = suggestions.get('layer6_title_content', {}).get('content', '默认标题') + subtitle_content = suggestions.get('layer7_subtitle_content', {}).get('content', '默认副标题') + logo_content = suggestions.get('layer5_logo_content', {}).get('text', '主办方') + + # 替换模板占位符 + filled_template = filled_template.replace('{{ title_content }}', title_content) + filled_template = filled_template.replace('{{ subtitle_content }}', subtitle_content) + filled_template = filled_template.replace('{{ logo_content }}', logo_content) + + print(f"{Fore.GREEN}✅ 模板内容填充完成{Style.RESET_ALL}") + + except Exception as e: + print(f"{Fore.YELLOW}⚠️ 模板填充出错: {e},使用默认内容{Style.RESET_ALL}") + + return filled_template + + +def generate_vue_code_enhanced( + user_input_analysis_result: Dict, + parse_imglist: List[Dict], + suggestions: Dict = None, + prompt: str = None +) -> str: + """ + 增强的Vue代码生成函数 + 优先使用预定义模板,如果没有匹配的模板则使用AI生成 + + 参数: + user_input_analysis_result: 用户输入分析结果 + parse_imglist: 图片信息列表 + suggestions: 文案建议 + prompt: 自定义提示词(可选) + + 返回: + Vue组件代码 + """ + print(f"{Fore.CYAN}🎨 开始增强Vue代码生成...{Style.RESET_ALL}") + + # 1. 尝试使用预定义模板 + template_code = get_template_by_images(parse_imglist) + + if template_code and suggestions: + print(f"{Fore.GREEN}✅ 使用预定义模板生成Vue代码{Style.RESET_ALL}") + vue_code = fill_template_content(template_code, suggestions) + return vue_code + + # 2. 如果没有合适的模板,使用AI生成 + print(f"{Fore.BLUE}🤖 使用AI生成Vue代码{Style.RESET_ALL}") + + if not prompt: + prompt = generate_layout_prompt(user_input_analysis_result, parse_imglist, suggestions) + + return generate_vue_code(prompt) + + def generate_vue_code(prompt=None): """ - 生成Vue组件代码 + 原有的Vue代码生成函数(保持兼容性) """ if not prompt: prompt = ( @@ -170,46 +355,32 @@ def generate_vue_code(prompt=None): print(f"{Fore.RED}❌ Vue代码生成异常: {str(e)}{Style.RESET_ALL}") return generate_fallback_vue_code() -def generate_fallback_vue_code(): +def generate_fallback_vue_code(theme="默认主题", width=1080, height=1920): """ 生成备用的Vue代码 """ print(f"{Fore.YELLOW}⚠️ 使用备用Vue模板{Style.RESET_ALL}") - return """