欢迎光临
我们一直在努力

Stable-Diffusion-v1-5-archive创意工作流整合:Figma/Notion/Slack自动化触发方案

Stable Diffusion v1.5 Archive创意工作流整合:Figma/Notion/Slack自动化触发方案

你是不是也遇到过这样的场景?在Figma里画着设计稿,突然需要一个背景图;在Notion里写着产品文档,想配一张概念图;或者在Slack群里讨论创意,需要快速生成一张示意图来辅助沟通。每次都要手动打开Stable Diffusion界面,输入提示词,等待生成,再下载图片,最后上传到对应工具里——这个过程太繁琐了。

今天我要分享的,就是如何把Stable Diffusion v1.5 Archive这个经典的文生图模型,无缝整合到你的日常创意工作流中。通过一套自动化方案,让你在Figma、Notion、Slack里直接触发图片生成,就像调用一个内置功能一样简单。

1. 为什么需要自动化创意工作流?

在开始技术实现之前,我们先聊聊为什么要做这件事。传统的AI图片生成流程有几个明显的痛点:

效率瓶颈:从创意想法到最终图片,中间有太多手动步骤。设计师、产品经理、内容创作者的时间都很宝贵,每次生成图片都要切换工具,打断工作流,效率损失严重。

创意断层:当你在Figma里设计时,突然需要一张背景图,如果切换到另一个工具去生成,再回来时可能已经失去了刚才的设计灵感。这种上下文切换对创意工作来说是致命的。

协作障碍:团队协作时,一个人生成了图片,其他人可能不知道参数,无法复现或修改。如果能在Notion文档里直接生成并记录参数,协作就会顺畅很多。

质量不稳定:不同人生成的图片风格、质量参差不齐,缺乏统一的标准和流程。

Stable Diffusion v1.5 Archive作为经典的文生图模型,虽然不如最新的SDXL或SD3那么强大,但它在通用图像生成、创意草图和风格化出图方面表现稳定,而且推理速度快,非常适合集成到自动化工作流中。

2. 整体方案架构设计

我们的目标很简单:在Figma、Notion、Slack中触发图片生成,自动调用Stable Diffusion v1.5 Archive,然后把生成的图片和参数返回到原工具中。

2.1 核心组件

整个方案由四个核心部分组成:

  • Stable Diffusion v1.5 Archive服务:这是我们的图片生成引擎,已经部署在CSDN星图镜像上,开箱即用。
  • API网关层:接收来自不同工具的请求,统一格式后转发给SD服务,再把结果返回。
  • 工具集成插件:为Figma、Notion、Slack开发的客户端插件或机器人。
  • 参数管理与模板系统:存储常用的提示词模板、风格预设,确保生成质量的一致性。
  • 2.2 工作流程

    让我用一个具体的场景来说明整个流程:

    假设你在Figma里设计一个电商网站的登录页,需要一张“现代简约的办公室背景图”。

  • 你在Figma插件里输入“modern minimalist office background”
  • 插件通过API网关调用Stable Diffusion服务
  • SD服务在20秒内生成图片
  • 图片和生成参数自动插入到你的Figma画板中
  • 同时,这次生成记录被保存到Notion数据库,方便团队查看和复现
  • 整个过程完全自动化,你不需要离开Figma界面。

    3. 技术实现详解

    现在我们来拆解每个部分的具体实现。我会提供核心代码和配置,你可以根据自己的需求调整。

    3.1 Stable Diffusion API服务封装

    首先,我们需要为Stable Diffusion v1.5 Archive服务包装一个REST API。虽然镜像本身提供了Web界面,但我们需要一个程序可调用的接口。

    # sd_api_wrapper.py
    import requests
    import json
    import base64
    from io import BytesIO
    from PIL import Image

    class StableDiffusionAPI:
    def __init__(self, base_url="https://gpu-{实例ID}-7860.web.gpu.csdn.net/"):
    self.base_url = base_url
    self.api_endpoint = f"{base_url}/api/predict"

    def generate_image(self, prompt, negative_prompt="", steps=25,
    guidance_scale=7.5, width=512, height=512, seed=-1):
    """
    调用Stable Diffusion生成图片
    """
    # 构建请求数据
    payload = {
    "data": [
    prompt,
    negative_prompt,
    steps,
    guidance_scale,
    width,
    height,
    seed
    ]
    }

    try:
    # 发送请求到Gradio API
    response = requests.post(self.api_endpoint, json=payload, timeout=120)
    response.raise_for_status()

    result = response.json()

    # 解析返回的图片数据
    if "data" in result and len(result["data"]) > 0:
    # 第一个元素是图片的base64数据
    image_data = result["data"][0]

    # 移除base64前缀
    if "base64," in image_data:
    image_data = image_data.split("base64,")[1]

    # 解码base64
    image_bytes = base64.b64decode(image_data)
    image = Image.open(BytesIO(image_bytes))

    # 第二个元素是JSON格式的生成参数
    params_json = result["data"][1] if len(result["data"]) > 1 else "{}"
    generation_params = json.loads(params_json)

    return {
    "success": True,
    "image": image,
    "image_bytes": image_bytes,
    "params": generation_params,
    "prompt": prompt,
    "seed": generation_params.get("Seed", seed)
    }
    else:
    return {"success": False, "error": "No image data in response"}

    except Exception as e:
    return {"success": False, "error": str(e)}

    def generate_and_save(self, prompt, output_path="generated_image.png", **kwargs):
    """
    生成图片并保存到本地
    """
    result = self.generate_image(prompt, **kwargs)

    if result["success"]:
    result["image"].save(output_path)
    print(f"图片已保存到: {output_path}")
    print(f"生成参数: {result['params']}")

    # 同时保存参数到JSON文件
    params_path = output_path.replace(".png", "_params.json")
    with open(params_path, "w") as f:
    json.dump(result["params"], f, indent=2)

    return result
    else:
    print(f"生成失败: {result['error']}")
    return result

    # 使用示例
    if __name__ == "__main__":
    sd_api = StableDiffusionAPI()

    # 测试生成
    result = sd_api.generate_and_save(
    prompt="a modern minimalist office with large windows, plants, natural lighting, 3d render",
    negative_prompt="lowres, blurry, messy, cluttered",
    steps=28,
    guidance_scale=7.5,
    width=768,
    height=512,
    seed=42,
    output_path="office_background.png"
    )

    这个API封装类提供了两个主要方法:generate_image用于生成图片并返回结果对象,generate_and_save在生成的同时保存图片和参数到本地。

    3.2 API网关与Webhook服务

    为了让Figma、Notion、Slack能够调用我们的SD服务,我们需要一个中间层来处理不同的请求格式,并提供身份验证、限流等功能。

    # api_gateway.py
    from flask import Flask, request, jsonify
    import os
    from sd_api_wrapper import StableDiffusionAPI
    import hashlib
    import time
    from functools import wraps

    app = Flask(__name__)

    # 配置
    SD_BASE_URL = os.getenv("SD_BASE_URL", "https://gpu-{实例ID}-7860.web.gpu.csdn.net/")
    API_KEYS = {
    "figma": os.getenv("FIGMA_API_KEY"),
    "notion": os.getenv("NOTION_API_KEY"),
    "slack": os.getenv("SLACK_API_KEY")
    }

    # 初始化SD API
    sd_api = StableDiffusionAPI(SD_BASE_URL)

    # 简单的API密钥验证装饰器
    def require_api_key(platform):
    def decorator(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
    api_key = request.headers.get('X-API-Key')
    expected_key = API_KEYS.get(platform)

    if not expected_key or api_key != expected_key:
    return jsonify({"error": "Invalid API key"}), 401
    return f(*args, **kwargs)
    return decorated_function
    return decorator

    @app.route('/api/generate', methods=['POST'])
    def generate_image():
    """
    统一的图片生成接口
    支持来自不同平台的请求
    """
    data = request.json

    # 验证必要参数
    if not data or 'prompt' not in data:
    return jsonify({"error": "Missing required parameter: prompt"}), 400

    # 提取参数(带默认值)
    prompt = data['prompt']
    negative_prompt = data.get('negative_prompt', '')
    steps = data.get('steps', 25)
    guidance_scale = data.get('guidance_scale', 7.5)
    width = data.get('width', 512)
    height = data.get('height', 512)
    seed = data.get('seed', -1)

    # 平台特定处理
    platform = data.get('platform', 'generic')

    if platform == 'figma':
    # Figma通常需要特定尺寸的图片
    width = data.get('width', 1024)
    height = data.get('height', 768)
    elif platform == 'slack':
    # Slack对图片大小有限制,生成小一点的图
    width = min(data.get('width', 512), 1024)
    height = min(data.get('height', 512), 1024)

    # 调用SD生成图片
    result = sd_api.generate_image(
    prompt=prompt,
    negative_prompt=negative_prompt,
    steps=steps,
    guidance_scale=guidance_scale,
    width=width,
    height=height,
    seed=seed
    )

    if result['success']:
    # 将图片转换为base64,方便不同平台使用
    import base64
    from io import BytesIO

    img_byte_arr = BytesIO()
    result['image'].save(img_byte_arr, format='PNG')
    img_base64 = base64.b64encode(img_byte_arr.getvalue()).decode('utf-8')

    response_data = {
    "success": True,
    "image_base64": img_base64,
    "params": result['params'],
    "prompt": prompt,
    "seed": result['seed'],
    "platform": platform,
    "timestamp": time.time()
    }

    # 根据平台返回不同格式
    if platform == 'notion':
    # Notion需要图片URL,这里我们生成一个临时URL
    # 实际部署时应该上传到图床或S3
    image_id = hashlib.md5(f"{prompt}_{seed}".encode()).hexdigest()[:8]
    response_data['image_url'] = f"/temp_images/{image_id}.png"

    # 保存图片到临时目录(生产环境应该用云存储)
    temp_dir = "temp_images"
    os.makedirs(temp_dir, exist_ok=True)
    result['image'].save(f"{temp_dir}/{image_id}.png")

    return jsonify(response_data)
    else:
    return jsonify({
    "success": False,
    "error": result['error'],
    "platform": platform
    }), 500

    @app.route('/api/templates', methods=['GET'])
    def get_templates():
    """
    获取预定义的提示词模板
    """
    templates = {
    "ui_backgrounds": [
    {
    "name": "现代科技背景",
    "prompt": "futuristic tech background, blue gradient, abstract shapes, clean design, 4k",
    "negative_prompt": "text, logo, watermark, blurry",
    "width": 1920,
    "height": 1080
    },
    {
    "name": "自然风景背景",
    "prompt": "peaceful nature landscape, mountains and lake, morning mist, photorealistic, 8k",
    "negative_prompt": "people, buildings, cars, text",
    "width": 1920,
    "height": 1080
    }
    ],
    "product_concepts": [
    {
    "name": "智能设备概念图",
    "prompt": "sleek smart home device on wooden table, product photography, studio lighting, clean background",
    "negative_prompt": "cluttered, dirty, poor lighting",
    "width": 1024,
    "height": 768
    }
    ],
    "illustrations": [
    {
    "name": "扁平化插画",
    "prompt": "flat design illustration of [subject], minimal colors, clean lines, vector style",
    "negative_prompt": "realistic, photorealistic, 3d, detailed",
    "width": 800,
    "height": 600
    }
    ]
    }

    return jsonify(templates)

    @app.route('/api/health', methods=['GET'])
    def health_check():
    """
    健康检查端点
    """
    return jsonify({
    "status": "healthy",
    "service": "Stable Diffusion API Gateway",
    "sd_available": True,
    "timestamp": time.time()
    })

    if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

    这个API网关提供了几个关键功能:

  • 统一的图片生成接口,支持来自不同平台的请求
  • API密钥验证,确保只有授权的工具可以调用
  • 平台特定的参数处理(如Figma需要大图,Slack需要小图)
  • 提示词模板管理,确保生成质量的一致性
  • 健康检查端点,方便监控服务状态
  • 3.3 Figma插件开发

    Figma插件使用HTML/CSS/JavaScript开发,可以通过Figma的插件API与设计工具交互。

    // figma-plugin.js
    // 主要逻辑:在Figma中调用SD API生成图片并插入画板

    // 插件UI HTML
    const html = `
    <div style="padding: 20px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;">
    <h2>🎨 AI图像生成</h2>

    <div style="margin-bottom: 15px;">
    <label style="display: block; margin-bottom: 5px; font-weight: 500;">提示词(英文)</label>
    <textarea id="promptInput"
    style="width: 100%; height: 80px; padding: 10px; border: 1px solid #e0e0e0; border-radius: 4px; font-size: 14px;"
    placeholder="例如: a modern minimalist office background with plants and natural light"></textarea>
    </div>

    <div style="margin-bottom: 15px;">
    <label style="display: block; margin-bottom: 5px; font-weight: 500;">排除内容(可选)</label>
    <input type="text" id="negativePrompt"
    style="width: 100%; padding: 10px; border: 1px solid #e0e0e0; border-radius: 4px; font-size: 14px;"
    placeholder="例如: text, logo, watermark, blurry">
    </div>

    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px;">
    <div>
    <label style="display: block; margin-bottom: 5px; font-weight: 500;">宽度</label>
    <select id="widthSelect" style="width: 100%; padding: 8px; border: 1px solid #e0e0e0; border-radius: 4px;">
    <option value="512">512px</option>
    <option value="768">768px</option>
    <option value="1024" selected>1024px</option>
    <option value="1920">1920px</option>
    </select>
    </div>
    <div>
    <label style="display: block; margin-bottom: 5px; font-weight: 500;">高度</label>
    <select id="heightSelect" style="width: 100%; padding: 8px; border: 1px solid #e0e0e0; border-radius: 4px;">
    <option value="512">512px</option>
    <option value="768" selected>768px</option>
    <option value="1024">1024px</option>
    <option value="1080">1080px</option>
    </select>
    </div>
    </div>

    <div style="margin-bottom: 20px;">
    <label style="display: block; margin-bottom: 5px; font-weight: 500;">模板</label>
    <select id="templateSelect" style="width: 100%; padding: 8px; border: 1px solid #e0e0e0; border-radius: 4px;">
    <option value="">自定义提示词</option>
    <option value="ui_background_modern">UI背景 – 现代科技</option>
    <option value="ui_background_nature">UI背景 – 自然风景</option>
    <option value="product_concept">产品概念图</option>
    <option value="illustration_flat">扁平化插画</option>
    </select>
    </div>

    <button id="generateBtn"
    style="width: 100%; padding: 12px; background: #18a0fb; color: white; border: none; border-radius: 4px; font-size: 16px; font-weight: 500; cursor: pointer;">
    生成图片
    </button>

    <div id="status" style="margin-top: 15px; padding: 10px; border-radius: 4px; display: none;"></div>

    <div id="templateInfo" style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 4px; display: none;">
    <h4 style="margin-top: 0;">模板说明</h4>
    <p id="templateDescription"></p>
    </div>
    </div>
    `;

    // 显示插件UI
    figma.showUI(html, { width: 400, height: 500 });

    // 处理UI消息
    figma.ui.onmessage = async (message) => {
    if (message.type === 'generate-image') {
    const { prompt, negativePrompt, width, height, template } = message;

    // 显示生成状态
    figma.ui.postMessage({
    type: 'status',
    message: '正在生成图片…',
    status: 'loading'
    });

    try {
    // 调用我们的API网关
    const response = await fetch('https://your-api-gateway.com/api/generate', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your-figma-api-key-here'
    },
    body: JSON.stringify({
    prompt: prompt,
    negative_prompt: negativePrompt || '',
    width: parseInt(width),
    height: parseInt(height),
    platform: 'figma',
    template: template
    })
    });

    const result = await response.json();

    if (result.success) {
    // 将base64图片转换为Uint8Array
    const imageBytes = Uint8Array.from(atob(result.image_base64), c => c.charCodeAt(0));

    // 在Figma中创建图片
    const image = figma.createImage(imageBytes);

    // 创建矩形框架并填充图片
    const frame = figma.createFrame();
    frame.resize(parseInt(width), parseInt(height));
    frame.fills = [{
    type: 'IMAGE',
    imageHash: image.hash,
    scaleMode: 'FILL'
    }];

    // 将图片添加到当前页面
    figma.currentPage.appendChild(frame);

    // 将生成参数添加到图片描述中
    frame.name = `AI生成: ${prompt.substring(0, 50)}…`;
    frame.description = `提示词: ${prompt}\\n负向提示: ${negativePrompt}\\n尺寸: ${width}x${height}\\n种子: ${result.seed}`;

    // 选中新创建的图片
    figma.currentPage.selection = [frame];
    figma.viewport.scrollAndZoomIntoView([frame]);

    figma.ui.postMessage({
    type: 'status',
    message: '图片已生成并插入画板!',
    status: 'success'
    });

    // 记录到Notion(可选)
    await logToNotion({
    prompt: prompt,
    negative_prompt: negativePrompt,
    width: width,
    height: height,
    seed: result.seed,
    platform: 'figma',
    file_url: figma.fileKey ? `https://www.figma.com/file/${figma.fileKey}` : 'local'
    });

    } else {
    figma.ui.postMessage({
    type: 'status',
    message: `生成失败: ${result.error}`,
    status: 'error'
    });
    }

    } catch (error) {
    figma.ui.postMessage({
    type: 'status',
    message: `请求失败: ${error.message}`,
    status: 'error'
    });
    }
    }

    if (message.type === 'get-templates') {
    // 获取模板列表
    try {
    const response = await fetch('https://your-api-gateway.com/api/templates');
    const templates = await response.json();
    figma.ui.postMessage({
    type: 'templates-data',
    templates: templates
    });
    } catch (error) {
    console.error('获取模板失败:', error);
    }
    }
    };

    // 记录到Notion的函数
    async function logToNotion(generationData) {
    try {
    const response = await fetch('https://your-api-gateway.com/api/log-to-notion', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your-notion-api-key-here'
    },
    body: JSON.stringify(generationData)
    });
    return await response.json();
    } catch (error) {
    console.error('记录到Notion失败:', error);
    }
    }

    这个Figma插件提供了完整的UI界面,用户可以直接在Figma中输入提示词、选择尺寸和模板,然后一键生成图片并插入到当前画板中。生成的图片还会自动记录生成参数,方便后续修改和复现。

    3.4 Notion集成方案

    Notion可以通过官方API和Webhook进行集成。我们可以创建一个Notion数据库来记录所有生成的图片,并在Notion中直接触发生成。

    # notion_integration.py
    import requests
    import json
    from datetime import datetime

    class NotionIntegration:
    def __init__(self, api_key, database_id):
    self.api_key = api_key
    self.database_id = database_id
    self.headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28"
    }

    def create_generation_record(self, prompt, image_url, params, platform="notion"):
    """
    在Notion中创建生成记录
    """
    # 构建Notion页面数据
    page_data = {
    "parent": {"database_id": self.database_id},
    "properties": {
    "Name": {
    "title": [
    {
    "text": {
    "content": prompt[:50] + ("…" if len(prompt) > 50 else "")
    }
    }
    ]
    },
    "Prompt": {
    "rich_text": [
    {
    "text": {
    "content": prompt
    }
    }
    ]
    },
    "Platform": {
    "select": {
    "name": platform
    }
    },
    "Date": {
    "date": {
    "start": datetime.now().isoformat()
    }
    },
    "Seed": {
    "number": params.get("Seed", -1)
    },
    "Status": {
    "status": {
    "name": "已完成"
    }
    }
    },
    "children": [
    {
    "object": "block",
    "type": "image",
    "image": {
    "type": "external",
    "external": {
    "url": image_url
    }
    }
    },
    {
    "object": "block",
    "type": "code",
    "code": {
    "rich_text": [
    {
    "type": "text",
    "text": {
    "content": json.dumps(params, indent=2)
    }
    }
    ],
    "language": "json"
    }
    }
    ]
    }

    # 调用Notion API创建页面
    response = requests.post(
    "https://api.notion.com/v1/pages",
    headers=self.headers,
    json=page_data
    )

    if response.status_code == 200:
    return response.json()
    else:
    print(f"创建Notion记录失败: {response.status_code}, {response.text}")
    return None

    def generate_from_notion(self, prompt, page_id):
    """
    从Notion页面触发图片生成
    """
    # 调用SD API生成图片
    sd_api = StableDiffusionAPI()
    result = sd_api.generate_image(prompt=prompt)

    if result["success"]:
    # 上传图片到图床(这里简化处理,实际应该用S3或云存储)
    image_url = self.upload_to_cdn(result["image_bytes"])

    # 在Notion中更新页面,添加生成的图片
    self.update_notion_page_with_image(page_id, image_url, result["params"])

    return {
    "success": True,
    "image_url": image_url,
    "page_id": page_id
    }
    else:
    return {"success": False, "error": result["error"]}

    def upload_to_cdn(self, image_bytes):
    """
    上传图片到CDN(简化版,实际应该用AWS S3、阿里云OSS等)
    """
    # 这里应该实现真正的CDN上传逻辑
    # 为了示例,我们返回一个假URL
    import hashlib
    image_hash = hashlib.md5(image_bytes).hexdigest()[:16]
    return f"https://your-cdn.com/images/{image_hash}.png"

    def update_notion_page_with_image(self, page_id, image_url, params):
    """
    在Notion页面中添加生成的图片
    """
    update_data = {
    "children": [
    {
    "object": "block",
    "type": "heading_2",
    "heading_2": {
    "rich_text": [
    {
    "type": "text",
    "text": {
    "content": "🎨 生成的图片"
    }
    }
    ]
    }
    },
    {
    "object": "block",
    "type": "image",
    "image": {
    "type": "external",
    "external": {
    "url": image_url
    }
    }
    },
    {
    "object": "block",
    "type": "heading_3",
    "heading_3": {
    "rich_text": [
    {
    "type": "text",
    "text": {
    "content": "生成参数"
    }
    }
    ]
    }
    },
    {
    "object": "block",
    "type": "code",
    "code": {
    "rich_text": [
    {
    "type": "text",
    "text": {
    "content": json.dumps(params, indent=2)
    }
    }
    ],
    "language": "json"
    }
    }
    ]
    }

    # 在页面末尾追加内容
    response = requests.patch(
    f"https://api.notion.com/v1/blocks/{page_id}/children",
    headers=self.headers,
    json=update_data
    )

    return response.status_code == 200

    # Notion机器人配置示例
    NOTION_CONFIG = {
    "api_key": "your-notion-integration-token",
    "database_id": "your-database-id-here",
    "webhook_secret": "your-webhook-secret"
    }

    # 使用示例
    if __name__ == "__main__":
    notion = NotionIntegration(
    api_key=NOTION_CONFIG["api_key"],
    database_id=NOTION_CONFIG["database_id"]
    )

    # 测试创建记录
    record = notion.create_generation_record(
    prompt="a beautiful sunset over mountains, digital art",
    image_url="https://example.com/sunset.png",
    params={
    "Steps": 25,
    "Guidance Scale": 7.5,
    "Seed": 12345,
    "Width": 512,
    "Height": 512
    },
    platform="测试"
    )

    if record:
    print(f"已在Notion中创建记录: {record['id']}")

    Notion集成提供了两个主要功能:

  • 自动记录所有图片生成任务到Notion数据库,方便团队管理和检索
  • 通过Notion页面直接触发图片生成,适合文档编写时的配图需求
  • 3.5 Slack机器人集成

    Slack机器人可以让团队成员在聊天中直接生成图片,非常适合头脑风暴和快速沟通。

    # slack_bot.py
    from slack_bolt import App
    from slack_bolt.adapter.socket_mode import SocketModeHandler
    import os
    from sd_api_wrapper import StableDiffusionAPI

    # Slack应用配置
    SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
    SLACK_APP_TOKEN = os.environ.get("SLACK_APP_TOKEN")

    # 初始化Slack应用
    app = App(token=SLACK_BOT_TOKEN)
    sd_api = StableDiffusionAPI()

    # 处理Slash命令
    @app.command("/generate-image")
    def handle_generate_image_command(ack, say, command):
    # 立即确认命令接收
    ack()

    prompt = command["text"]
    user_id = command["user_id"]
    channel_id = command["channel_id"]

    if not prompt:
    say("请提供图片描述,例如:`/generate-image a cute cat wearing glasses`")
    return

    # 发送生成中的消息
    message = say(f"<@{user_id}> 正在生成图片: *{prompt}*… :hourglass_flowing_sand:")

    try:
    # 调用SD API生成图片
    result = sd_api.generate_image(
    prompt=prompt,
    negative_prompt="lowres, blurry, text, watermark",
    steps=20,
    width=512,
    height=512
    )

    if result["success"]:
    # 保存图片到临时文件
    import tempfile
    with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_file:
    result["image"].save(tmp_file.name)
    tmp_file_path = tmp_file.name

    # 上传图片到Slack
    from slack_sdk import WebClient
    client = WebClient(token=SLACK_BOT_TOKEN)

    upload_result = client.files_upload_v2(
    channel=channel_id,
    file=tmp_file_path,
    title=f"AI生成: {prompt[:50]}…",
    initial_comment=f"<@{user_id}> 图片生成完成!\\n提示词: {prompt}\\n种子: {result['params'].get('Seed', '随机')}"
    )

    # 删除临时文件
    os.unlink(tmp_file_path)

    # 更新原始消息
    client.chat_update(
    channel=channel_id,
    ts=message["ts"],
    text=f"<@{user_id}> 图片生成完成! :white_check_mark:"
    )

    else:
    say(f"<@{user_id}> 图片生成失败: {result['error']}")

    except Exception as e:
    say(f"<@{user_id}> 生成过程中出现错误: {str(e)}")

    # 处理消息中的图片生成请求
    @app.message("生成图片:")
    def handle_generate_image_message(message, say):
    text = message["text"]

    # 提取提示词("生成图片: "之后的内容)
    if text.startswith("生成图片:"):
    prompt = text[5:].strip() # 移除"生成图片:",中文冒号

    if prompt:
    user_id = message["user"]

    # 发送生成中的消息
    say(f"<@{user_id}> 正在为你生成: *{prompt}*…")

    try:
    # 调用SD API
    result = sd_api.generate_image(
    prompt=prompt,
    negative_prompt="lowres, blurry, text, watermark",
    steps=20,
    width=512,
    height=512
    )

    if result["success"]:
    # 保存并上传图片
    import tempfile
    with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_file:
    result["image"].save(tmp_file.name)
    tmp_file_path = tmp_file.name

    from slack_sdk import WebClient
    client = WebClient(token=SLACK_BOT_TOKEN)

    upload_result = client.files_upload_v2(
    channel=message["channel"],
    file=tmp_file_path,
    title=f"AI生成: {prompt[:50]}…",
    initial_comment=f"<@{user_id}> 你要的图片来啦!\\n提示词: {prompt}"
    )

    os.unlink(tmp_file_path)
    else:
    say(f"<@{user_id}> 生成失败: {result['error']}")

    except Exception as e:
    say(f"<@{user_id}> 出错了: {str(e)}")

    # 处理快捷方式(Shortcut)
    @app.shortcut("generate_image_shortcut")
    def handle_generate_image_shortcut(ack, body, client):
    ack()

    # 打开模态窗口
    client.views_open(
    trigger_id=body["trigger_id"],
    view={
    "type": "modal",
    "callback_id": "generate_image_modal",
    "title": {
    "type": "plain_text",
    "text": "AI图片生成"
    },
    "submit": {
    "type": "plain_text",
    "text": "生成"
    },
    "close": {
    "type": "plain_text",
    "text": "取消"
    },
    "blocks": [
    {
    "type": "input",
    "block_id": "prompt_block",
    "label": {
    "type": "plain_text",
    "text": "图片描述(英文)"
    },
    "element": {
    "type": "plain_text_input",
    "action_id": "prompt_input",
    "multiline": True,
    "placeholder": {
    "type": "plain_text",
    "text": "例如: a futuristic cityscape at night with neon lights and flying cars"
    }
    }
    },
    {
    "type": "input",
    "block_id": "negative_prompt_block",
    "label": {
    "type": "plain_text",
    "text": "排除内容(可选)"
    },
    "optional": True,
    "element": {
    "type": "plain_text_input",
    "action_id": "negative_prompt_input",
    "placeholder": {
    "type": "plain_text",
    "text": "例如: text, logo, watermark, blurry"
    }
    }
    },
    {
    "type": "section",
    "block_id": "size_block",
    "text": {
    "type": "mrkdwn",
    "text": "选择图片尺寸:"
    },
    "accessory": {
    "type": "static_select",
    "action_id": "size_select",
    "placeholder": {
    "type": "plain_text",
    "text": "选择尺寸"
    },
    "options": [
    {
    "text": {
    "type": "plain_text",
    "text": "小 (512×512)"
    },
    "value": "512"
    },
    {
    "text": {
    "type": "plain_text",
    "text": "中 (768×768)"
    },
    "value": "768"
    },
    {
    "text": {
    "type": "plain_text",
    "text": "大 (1024×1024)"
    },
    "value": "1024"
    }
    ]
    }
    }
    ]
    }
    )

    # 处理模态窗口提交
    @app.view("generate_image_modal")
    def handle_modal_submission(ack, body, client, view):
    ack()

    # 提取用户输入
    values = view["state"]["values"]
    prompt = values["prompt_block"]["prompt_input"]["value"]
    negative_prompt = values.get("negative_prompt_block", {}).get("negative_prompt_input", {}).get("value", "")
    size = values["size_block"]["size_select"]["selected_option"]["value"]

    user_id = body["user"]["id"]
    channel_id = body["view"]["private_metadata"] # 可以从metadata获取频道ID

    if not prompt:
    return

    # 在频道中发送生成消息
    client.chat_postMessage(
    channel=channel_id,
    text=f"<@{user_id}> 正在生成图片: *{prompt}*…"
    )

    # 调用SD API生成图片
    try:
    result = sd_api.generate_image(
    prompt=prompt,
    negative_prompt=negative_prompt,
    steps=25,
    width=int(size),
    height=int(size)
    )

    if result["success"]:
    # 保存并上传图片
    import tempfile
    with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_file:
    result["image"].save(tmp_file.name)
    tmp_file_path = tmp_file.name

    upload_result = client.files_upload_v2(
    channel=channel_id,
    file=tmp_file_path,
    title=f"AI生成: {prompt[:50]}…",
    initial_comment=f"<@{user_id}> 图片生成完成!\\n提示词: {prompt}\\n尺寸: {size}x{size}\\n种子: {result['params'].get('Seed', '随机')}"
    )

    os.unlink(tmp_file_path)
    else:
    client.chat_postMessage(
    channel=channel_id,
    text=f"<@{user_id}> 图片生成失败: {result['error']}"
    )

    except Exception as e:
    client.chat_postMessage(
    channel=channel_id,
    text=f"<@{user_id}> 生成过程中出现错误: {str(e)}"
    )

    # 启动Slack机器人
    if __name__ == "__main__":
    if not SLACK_BOT_TOKEN or not SLACK_APP_TOKEN:
    print("错误: 请设置SLACK_BOT_TOKEN和SLACK_APP_TOKEN环境变量")
    exit(1)

    handler = SocketModeHandler(app, SLACK_APP_TOKEN)
    print("Slack机器人已启动,等待命令…")
    handler.start()

    这个Slack机器人提供了三种使用方式:

  • Slash命令:输入/generate-image 图片描述直接生成
  • 消息触发:发送"生成图片: 描述"格式的消息
  • 快捷方式:通过Slack快捷方式打开模态窗口,填写更详细的参数
  • 4. 部署与配置指南

    现在你已经有了所有代码,接下来看看如何部署这个自动化工作流。

    4.1 环境准备

    首先,确保你已经部署了Stable Diffusion v1.5 Archive服务。如果你使用CSDN星图镜像,可以直接在镜像广场找到并一键部署。

    # 1. 部署Stable Diffusion v1.5 Archive服务
    # 访问CSDN星图镜像广场,搜索"stable-diffusion-v1-5-archive"
    # 点击部署,等待服务启动

    # 2. 获取服务访问地址
    # 部署完成后,你会得到一个类似这样的地址:
    # https://gpu-abc123-7860.web.gpu.csdn.net/

    # 3. 测试服务是否正常
    curl https://gpu-abc123-7860.web.gpu.csdn.net/

    4.2 API网关部署

    API网关可以使用任何你熟悉的云服务部署,这里以Python Flask应用为例:

    # 1. 创建项目目录
    mkdir sd-automation-workflow
    cd sd-automation-workflow

    # 2. 创建虚拟环境
    python -m venv venv
    source venv/bin/activate # Linux/Mac
    # venv\\Scripts\\activate # Windows

    # 3. 安装依赖
    pip install flask requests pillow

    # 4. 创建配置文件
    cat > config.py << 'EOF'
    import os

    # Stable Diffusion服务地址
    SD_BASE_URL = os.getenv("SD_BASE_URL", "https://gpu-{你的实例ID}-7860.web.gpu.csdn.net/")

    # API密钥配置
    API_KEYS = {
    "figma": os.getenv("FIGMA_API_KEY", "your-figma-api-key"),
    "notion": os.getenv("NOTION_API_KEY", "your-notion-api-key"),
    "slack": os.getenv("SLACK_API_KEY", "your-slack-api-key")
    }

    # 服务端口
    PORT = int(os.getenv("PORT", 5000))
    EOF

    # 5. 启动服务
    python api_gateway.py

    4.3 工具配置

    Figma插件配置:

  • 在Figma开发者门户创建新插件
  • 将figma-plugin.js代码复制到main.js
  • 配置manifest.json文件
  • 在插件设置中填入API网关地址和API密钥
  • Notion集成配置:

  • 在Notion开发者门户创建新集成
  • 获取API密钥
  • 创建数据库并分享给集成
  • 在API网关中配置Notion API密钥
  • Slack机器人配置:

  • 在Slack API门户创建新应用
  • 启用Socket Mode
  • 配置Slash命令和快捷方式
  • 安装应用到工作空间
  • 获取Bot Token和App Token
  • 4.4 安全考虑

    在实际部署时,需要考虑以下几个安全方面:

  • API密钥管理:不要将API密钥硬编码在代码中,使用环境变量或密钥管理服务
  • 请求限流:防止API被滥用,可以添加速率限制
  • 输入验证:验证所有输入参数,防止注入攻击
  • 错误处理:友好的错误提示,不泄露内部信息
  • 访问日志:记录所有API调用,方便审计和调试
  • 5. 实际应用案例与效果

    让我分享几个实际使用这个自动化工作流的场景,看看它能带来多大的效率提升。

    5.1 设计团队的工作流优化

    某电商公司的设计团队,每天需要为上百个商品生成主图。传统流程是设计师手动在Stable Diffusion WebUI中生成,然后下载、裁剪、上传到设计稿中。

    使用自动化工作流后:

    • 设计师在Figma中直接调用插件生成图片
    • 平均每张图片生成时间从5分钟缩短到30秒
    • 所有生成记录自动同步到Notion数据库
    • 团队可以复用成功的提示词和参数
    • 月度图片生成量从200张提升到1500张

    5.2 内容团队的协作改进

    一个内容创作团队,需要在文章、社交媒体、邮件营销等多个渠道使用配图。

    使用自动化工作流后:

    • 编辑在Notion中写文章时,直接生成配图
    • 社交媒体经理在Slack中讨论创意时,实时生成示意图
    • 所有生成的图片和参数自动记录,确保品牌一致性
    • 新成员可以快速学习成功的提示词模板
    • 内容产出速度提升40%

    5.3 产品团队的快速原型

    产品团队需要快速制作界面原型和概念图。

    使用自动化工作流后:

    • 产品经理在Figma中快速生成界面背景、插图
    • 在Slack讨论功能时,实时生成概念图辅助沟通
    • 所有生成物自动归档,方便后续查找和复用
    • 原型制作时间减少60%

    6. 总结

    通过将Stable Diffusion v1.5 Archive集成到Figma、Notion、Slack等日常工具中,我们构建了一个无缝的创意自动化工作流。这个方案的核心价值在于:

    效率大幅提升:从想法到图片的时间从几分钟缩短到几秒钟,无需切换工具,无需手动操作。

    创意流程连贯:在设计、写作、讨论的上下文中直接生成图片,保持创意连贯性。

    协作更加顺畅:所有生成记录自动同步,团队可以共享成功的提示词和参数。

    质量可控可复现:通过模板系统和参数记录,确保生成质量的一致性。

    技术门槛降低:非技术人员也能轻松使用AI图片生成,无需学习复杂的Stable Diffusion界面。

    实施这个方案的技术要点包括:

  • 封装Stable Diffusion API服务
  • 构建统一的API网关
  • 开发各工具的客户端集成
  • 设计参数管理和模板系统
  • 确保安全性和稳定性
  • 虽然初始设置需要一些技术工作,但一旦部署完成,它将持续为团队创造价值。无论是设计、内容、产品还是营销团队,都能从这个自动化工作流中受益。

    最重要的是,这个方案是可扩展的。你可以根据需要添加更多工具集成(如Trello、Jira、Teams等),或者升级到更强大的Stable Diffusion模型。核心架构保持不变,只是更换底层的图片生成引擎。

    如果你正在寻找提升团队创意效率的方法,不妨试试这个自动化方案。从一个小团队开始,验证价值,然后逐步推广到整个组织。


    获取更多AI镜像

    想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。

    赞(0)
    未经允许不得转载:171主机测评 » Stable-Diffusion-v1-5-archive创意工作流整合:Figma/Notion/Slack自动化触发方案
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址