Wan2.1 VAE与MySQL联动:构建带用户历史记录的图像生成平台
Wan2.1 VAE与MySQL联动构建带用户历史记录的图像生成平台你有没有想过自己用AI生成的每一张图片都能被自动保存下来形成一个专属的创意作品集今天我们就来动手搭建一个这样的平台。它不仅能让你用Wan2.1 VAE模型轻松生成图像还能把每一次的创作记录、用户信息和生成的图片都妥善地保存到MySQL数据库里。这样一来你不仅可以随时回顾自己的“AI绘画史”还能方便地管理和分享自己的作品。这个项目非常适合那些希望将AI图像生成能力集成到自有应用中的开发者或者任何想拥有一个私人、可追溯的图像创作工具的朋友。下面我就带你从零开始一步步实现这个集成了前端、后端、AI模型和数据库的完整Web应用。1. 项目整体设计与核心思路在开始写代码之前我们先理清整个平台是怎么运转的。想象一下用户的操作流程打开网页输入一段文字描述比如“一只在星空下奔跑的柴犬”点击生成。接下来后台会默默完成一系列工作记录是谁提交的请求调用Wan2.1 VAE模型把文字变成图片把生成的图片保存好最后把这次任务的所有信息——谁、什么时候、要画什么、画出来存哪儿——都记到数据库的小本本上。为了实现这个流程我们的系统需要四个核心部分前端界面一个简单的网页让用户能输入文字、看到生成的图片和历史记录列表。后端服务接收前端的请求负责调度AI模型、处理数据、和数据库打交道。Wan2.1 VAE模型我们图像生成能力的核心负责将文本描述转化为图像。MySQL数据库系统的“记忆中枢”持久化存储用户、任务和图像信息。它们之间的关系可以用下面这个简单的图来理解用户 - 前端 - 后端 - (调用Wan2.1 VAE 读写MySQL) - 前端 - 用户整个项目的代码结构也会按照这个逻辑来组织清晰明了。2. 数据库设计与搭建为系统打造记忆库数据库是我们平台的基石设计得好后续开发会顺畅很多。我们需要存储三类主要信息用户、生成任务、以及图片本身或图片的存储信息。2.1 核心数据表设计我们将创建三张表它们之间通过“用户ID”和“任务ID”关联起来。用户表 (users)这张表记录平台的使用者。我们设计得简单一点主要包含id: 每个用户的唯一标识主键。username: 用户名用于登录和显示。email: 用户邮箱。created_at: 账户创建时间。生成任务表 (generation_tasks)这是最核心的表记录每一次图像生成请求的完整上下文。id: 每次生成任务的唯一标识主键。user_id: 关联到是哪个用户发起的任务外键。prompt: 用户输入的文本描述这是生成图像的“指令”。status: 任务状态比如“处理中”、“成功”、“失败”。这能让前端知道任务进度。image_url: 生成成功后图片在服务器上存储的路径或访问地址。created_at和updated_at: 任务创建和最后更新时间便于排序和查询历史。图片元数据表 (image_metadata)这张表用于存储更详细的图片信息作为对generation_tasks的补充方便未来扩展比如按风格、尺寸筛选。id: 元数据记录ID。task_id: 关联对应的生成任务外键。model_name: 生成所用的模型名称这里是“Wan2.1 VAE”。image_size: 图片的尺寸如“512x512”。inference_steps: 生成时使用的推理步数这会影响图像质量和生成时间。2.2 使用SQL语句创建表现在让我们打开MySQL客户端执行以下SQL语句来创建数据库和表。如果你还没有安装MySQL可以很容易地找到相关的安装配置教程这里我们假设你已经准备好了MySQL环境。-- 创建数据库 CREATE DATABASE IF NOT EXISTS ai_image_platform; USE ai_image_platform; -- 创建用户表 CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- 创建生成任务表 CREATE TABLE generation_tasks ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, prompt TEXT NOT NULL, status ENUM(pending, processing, success, failed) DEFAULT pending, image_url VARCHAR(500), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ); -- 创建图片元数据表 CREATE TABLE image_metadata ( id INT AUTO_INCREMENT PRIMARY KEY, task_id INT UNIQUE NOT NULL, model_name VARCHAR(100) DEFAULT Wan2.1 VAE, image_size VARCHAR(20), inference_steps INT, FOREIGN KEY (task_id) REFERENCES generation_tasks(id) ON DELETE CASCADE );执行完这些命令你的数据库“记忆库”就初始化好了。FOREIGN KEY确保了数据之间的关联完整性比如删除一个用户他所有的任务记录也会被自动清理ON DELETE CASCADE。3. 后端服务开发连接一切的桥梁后端我们使用Python的Flask框架因为它轻量、灵活适合快速构建Web API。我们将创建几个关键的API端点并实现与数据库和AI模型的交互。3.1 项目初始化与依赖安装首先创建一个新的项目目录并安装必要的Python包。mkdir wan2-vae-platform cd wan2-vae-platform python -m venv venv # Windows: venv\Scripts\activate # Linux/Mac: source venv/bin/activate pip install flask flask-cors pymysql torch transformers diffusers pillow这里我们安装了Flask及其CORS扩展用于处理网页请求、PyMySQL连接MySQL、以及PyTorch和Diffusers等运行Wan2.1 VAE所需的库。3.2 核心API与业务逻辑实现接下来我们创建主应用文件app.py。代码有点长但我会分段详细解释。from flask import Flask, request, jsonify, send_from_directory from flask_cors import CORS import pymysql import os from datetime import datetime import uuid from PIL import Image import torch from diffusers import StableDiffusionPipeline app Flask(__name__) CORS(app) # 允许前端跨域请求 # 数据库连接配置请根据你的MySQL设置修改 DB_CONFIG { host: localhost, user: your_username, password: your_password, database: ai_image_platform, charset: utf8mb4 } # 图片存储目录 UPLOAD_FOLDER static/generated_images os.makedirs(UPLOAD_FOLDER, exist_okTrue) app.config[UPLOAD_FOLDER] UPLOAD_FOLDER # 初始化Wan2.1 VAE模型这里以Stable Diffusion为例实际需替换为Wan2.1 VAE加载方式 # 注意首次运行会下载模型需要一定时间和网络 device cuda if torch.cuda.is_available() else cpu print(fUsing device: {device}) # 此处需要替换为实际的Wan2.1 VAE模型加载代码 # pipe StableDiffusionPipeline.from_pretrained(runwayml/stable-diffusion-v1-5).to(device) model_loaded False # 标记位实际使用时需要正确加载模型 def get_db_connection(): 创建并返回一个数据库连接 return pymysql.connect(**DB_CONFIG) app.route(/api/generate, methods[POST]) def generate_image(): 接收生成请求调用模型保存结果到数据库 data request.json user_id data.get(user_id) prompt data.get(prompt, ) if not user_id or not prompt: return jsonify({error: Missing user_id or prompt}), 400 if not model_loaded: return jsonify({error: AI model not ready}), 503 # 1. 在数据库中创建初始任务记录状态为 pending task_id None conn get_db_connection() try: with conn.cursor() as cursor: sql INSERT INTO generation_tasks (user_id, prompt, status) VALUES (%s, %s, pending) cursor.execute(sql, (user_id, prompt)) conn.commit() task_id cursor.lastrowid except Exception as e: conn.close() return jsonify({error: fDatabase error: {str(e)}}), 500 # 2. 异步调用AI模型生成图片实际生产环境应使用任务队列如Celery # 这里为了简化我们模拟一个生成过程并同步更新状态 try: # 更新状态为 processing with conn.cursor() as cursor: update_sql UPDATE generation_tasks SET statusprocessing WHERE id%s cursor.execute(update_sql, (task_id,)) conn.commit() # 调用模型生成图片 (伪代码需替换为实际模型调用) # with torch.no_grad(): # image pipe(prompt).images[0] # 模拟生成一个随机图片或调用实际模型 # 假设我们生成了一张图片并保存 image_filename f{uuid.uuid4().hex}.png image_path os.path.join(app.config[UPLOAD_FOLDER], image_filename) # 实际 image.save(image_path) # 模拟 创建一个简单图片占位 img Image.new(RGB, (512, 512), color(73, 109, 137)) img.save(image_path) image_url f/static/generated_images/{image_filename} # 3. 任务成功更新数据库记录 with conn.cursor() as cursor: update_sql UPDATE generation_tasks SET statussuccess, image_url%s WHERE id%s cursor.execute(update_sql, (image_url, task_id)) # 同时插入图片元数据 meta_sql INSERT INTO image_metadata (task_id, model_name, image_size, inference_steps) VALUES (%s, %s, %s, %s) cursor.execute(meta_sql, (task_id, Wan2.1 VAE, 512x512, 50)) conn.commit() return jsonify({ task_id: task_id, status: success, image_url: image_url, message: Image generated successfully }), 200 except Exception as e: # 4. 如果失败更新任务状态为 failed with conn.cursor() as cursor: update_sql UPDATE generation_tasks SET statusfailed WHERE id%s cursor.execute(update_sql, (task_id,)) conn.commit() return jsonify({error: fImage generation failed: {str(e)}}), 500 finally: conn.close() app.route(/api/history/int:user_id, methods[GET]) def get_user_history(user_id): 获取指定用户的所有生成历史记录 conn get_db_connection() try: with conn.cursor(pymysql.cursors.DictCursor) as cursor: sql SELECT t.id, t.prompt, t.status, t.image_url, t.created_at, m.model_name, m.image_size FROM generation_tasks t LEFT JOIN image_metadata m ON t.id m.task_id WHERE t.user_id %s ORDER BY t.created_at DESC cursor.execute(sql, (user_id,)) tasks cursor.fetchall() return jsonify({user_id: user_id, history: tasks}), 200 except Exception as e: return jsonify({error: fDatabase error: {str(e)}}), 500 finally: conn.close() app.route(/static/generated_images/filename) def serve_image(filename): 提供生成的图片静态文件访问 return send_from_directory(app.config[UPLOAD_FOLDER], filename) if __name__ __main__: # 在实际部署中这里应该加载真正的Wan2.1 VAE模型 # 并设置 model_loaded True print(启动服务器模型加载需单独配置...) app.run(debugTrue, port5000)这段代码构建了后端的核心骨架。/api/generate接口处理生成请求它严谨地遵循了“创建任务记录 - 处理 - 更新结果”的流程即使中间出错数据库的状态也是准确的。/api/history/user_id接口则通过关联查询将用户的任务记录和对应的图片元数据一并返回前端用这些数据就能渲染出历史记录列表。重要提示代码中AI模型加载和调用的部分是伪代码。你需要根据 Wan2.1 VAE 模型的具体使用方式例如是否基于Diffusers库模型ID是什么来替换这部分。同时将数据库配置DB_CONFIG中的用户名、密码替换成你自己的。4. 前端界面实现用户的创作台前端我们保持简洁使用原生HTML、JavaScript并稍微用一点CSS让界面看起来舒服点。创建一个index.html文件。!DOCTYPE html html langzh-CN head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 title我的AI图像生成工坊/title style body { font-family: sans-serif; max-width: 1000px; margin: 20px auto; padding: 20px; } .container { display: flex; gap: 40px; } .generation-panel, .history-panel { flex: 1; } textarea { width: 100%; height: 100px; margin: 10px 0; padding: 10px; } button { padding: 10px 20px; background-color: #4CAF50; color: white; border: none; cursor: pointer; } button:hover { background-color: #45a049; } button:disabled { background-color: #cccccc; } #resultImage { max-width: 512px; margin-top: 15px; border: 1px solid #ddd; } .task-item { border-bottom: 1px solid #eee; padding: 15px 0; } .task-prompt { font-weight: bold; color: #333; } .task-status { display: inline-block; padding: 3px 8px; border-radius: 3px; font-size: 0.9em; margin-left: 10px; } .status-success { background-color: #d4edda; color: #155724; } .status-processing { background-color: #fff3cd; color: #856404; } .status-failed { background-color: #f8d7da; color: #721c24; } .task-image { max-width: 150px; margin-top: 10px; } /style /head body h1 AI图像生成工坊 (集成Wan2.1 VAE)/h1 p输入描述生成你的专属图像所有作品将自动保存至你的历史记录中。/p div classcontainer div classgeneration-panel h2生成新图像/h2 div label foruserId你的用户ID (示例): /label input typenumber iduserId value1 readonly stylewidth:60px; small(实际应用中应为登录后获取的真实ID)/small /div div label forpromptInput描述你想生成的画面/labelbr textarea idpromptInput placeholder例如一只戴着礼帽、在咖啡馆看书的小猫蒸汽朋克风格/textarea /div button idgenerateBtn onclickgenerateImage()开始生成/button div idgenerationStatus/div div idresultContainer styledisplay:none; h3生成结果/h3 img idresultImage src alt生成的图像 p idresultPrompt/p /div /div div classhistory-panel h2我的历史作品/h2 button onclickloadHistory()刷新历史记录/button div idhistoryList p点击上方按钮加载你的创作历史。/p /div /div /div script const API_BASE http://localhost:5000/api; // 指向你的后端地址 async function generateImage() { const userId document.getElementById(userId).value; const prompt document.getElementById(promptInput).value.trim(); const btn document.getElementById(generateBtn); const statusDiv document.getElementById(generationStatus); if (!prompt) { alert(请输入图像描述); return; } btn.disabled true; statusDiv.innerHTML p⏳ 正在提交任务并生成图像请稍候.../p; try { const response await fetch(${API_BASE}/generate, { method: POST, headers: { Content-Type: application/json }, body: JSON.stringify({ user_id: userId, prompt: prompt }) }); const result await response.json(); if (response.ok) { statusDiv.innerHTML p stylecolor:green;✅ 图像生成成功/p; // 显示结果 document.getElementById(resultContainer).style.display block; document.getElementById(resultImage).src result.image_url; document.getElementById(resultPrompt).textContent 描述: ${prompt}; // 清空输入框 document.getElementById(promptInput).value ; // 自动刷新历史记录 loadHistory(); } else { statusDiv.innerHTML p stylecolor:red;❌ 生成失败: ${result.error}/p; } } catch (error) { statusDiv.innerHTML p stylecolor:red;❌ 网络或服务器错误: ${error.message}/p; } finally { btn.disabled false; } } async function loadHistory() { const userId document.getElementById(userId).value; const historyListDiv document.getElementById(historyList); historyListDiv.innerHTML p正在加载历史记录.../p; try { const response await fetch(${API_BASE}/history/${userId}); const data await response.json(); if (response.ok data.history.length 0) { let html ; data.history.forEach(task { const statusClass status-${task.status}; const date new Date(task.created_at).toLocaleString(); html div classtask-item div classtask-prompt${task.prompt}/div span classtask-status ${statusClass}${task.status}/span divsmall${date} | 模型: ${task.model_name || N/A} | 尺寸: ${task.image_size || N/A}/small/div ${task.image_url ? img classtask-image src${task.image_url} alt生成图 onerrorthis.style.displaynone : } /div; }); historyListDiv.innerHTML html; } else { historyListDiv.innerHTML p暂无历史记录快去生成第一张作品吧/p; } } catch (error) { historyListDiv.innerHTML p stylecolor:red;加载历史记录失败: ${error.message}/p; } } // 页面加载时自动获取一次历史记录 window.onload loadHistory; /script /body /html这个前端页面提供了最核心的功能输入描述并生成、查看历史记录。它通过JavaScript调用我们刚刚写好的后端API。界面里任务状态用不同颜色的小标签区分得很清楚历史记录里图文并茂体验直观。5. 运行、测试与展望现在让我们把这个平台跑起来。启动后端在终端确保你在项目目录下并且虚拟环境已激活运行python app.py。你应该看到服务器在http://localhost:5000启动的提示。访问前端直接用浏览器打开index.html文件。或者如果你想让前端也通过后端服务可以把HTML文件放到Flask的static目录下并配置路由但当前直接打开文件也能工作因为API地址是localhost:5000。模拟用户前端默认用户ID是1。你需要先在MySQL的users表里插入一条ID为1的用户记录。INSERT INTO users (username, email) VALUES (test_user, testexample.com);开始创作在前端输入描述点击“开始生成”。由于我们后端的模型调用是模拟的你会立刻得到一张纯色占位图但整个流程——创建任务记录、更新状态、保存图片URL、插入元数据、返回结果、刷新历史列表——会完整地走通。观察后端终端的日志和数据库表的数据变化你能清晰地看到整个数据流转过程。更进一步从演示到实用我们搭建了一个功能完整、逻辑清晰的演示系统。要把它变成一个真正可用的生产级应用你还需要考虑以下几个方向的深化集成真实模型这是最关键的一步。你需要根据Wan2.1 VAE模型的具体格式和推理方式替换掉后端代码中的模型加载和调用部分。这可能涉及调整Diffusers的pipeline或者使用模型原生的推理脚本。用户认证系统替换掉前端写死的用户ID。实现一个完整的注册、登录系统可以使用Flask-Login等扩展用户登录后后端从会话中获取真实的用户ID。异步任务队列图像生成是耗时操作。在生产环境中绝不能像我们演示这样在Web请求中同步等待。应该使用Celery Redis/RabbitMQ等消息队列将生成任务丢到后台异步执行并通过WebSocket或前端轮询通知用户任务完成。文件存储优化现在图片存在本地服务器。可以考虑使用云存储服务如AWS S3、阿里云OSS、腾讯云COS将图片上传到云端数据库中只存储URL这样更利于扩展和CDN加速。前端美化与功能增强使用Vue.js、React等现代前端框架重构界面增加图片下载、分享、删除历史记录、按标签分类等功能。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2474592.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!