使用 ChatGPT、Stable Diffusion、React 和 NodeJS 构建网站画廊🤯 TLDR;

2025-06-11

使用 ChatGPT、Stable Diffusion、React 和 NodeJS 构建网站画廊🤯

TLDR;

TLDR;

在本文中,您将学习如何构建一个 Web 应用程序,该应用程序使用 ChatGPT 和 Stable Diffusion 为您提供的任何网站描述生成徽标和合适的域名。

简介

人工智能正在统治世界。ChatGPT 和 Stable Diffusion 等技术每天都在震撼着我们的世界。ChatGPT
可以使用其 GPT3.5 模型回答世界上的任何问题。Stable
Diffusion 是一个文本转图像模型,可以将任何文本转换为图片。
将这两种技术结合起来是人工智能的未来。
在本文中,我将向您展示如何结合这两种技术来创建完整的网站品牌。

我对此感到非常兴奋🤩
请点击“喜欢”按钮,这样我才知道您喜欢它并且想要更多。

人工智能

Novu——第一个开源通知基础设施

简单介绍一下我们。Novu 是第一个开源通知基础设施。我们主要负责管理所有产品通知。这些通知可以是应用内通知(类似 Facebook 的铃铛图标 - Websockets)、电子邮件、短信等等。

诺武

如果你能给我们一颗星,我会非常高兴!也请在评论区告诉我❤️
https://github.com/novuhq/novu

什么是稳定扩散?

稳定扩散 (Stable Diffusion) 是一种文本到图像的潜在扩散模型,使用户能够根据给定的文本输入在几秒钟内生成图像。它还用于图像修复、图像外绘制以及生成图像到图像的转换等过程。

ChatGPT也是OpenAI 训练的 AI 语言模型,  用于生成文本并以类似人类的对话方式与用户交互。用户只需几秒钟即可提交请求,并获得历史、科学、数学和时事等广泛主题的信息或问题的答案。

在本文的最后,您将学习如何使用 Stable Diffusion WebUI从文本创建图像,以及如何从 Node.js 应用程序向 ChatGPT 发送消息。

安装并运行稳定的 Diffusion Web UI

您可以在Windows、  Linux和 Apple Silicon上安装稳定的 Diffusion Web UI  。在这里,我将指导您完成在 Apple Silicon 上的安装。

先决条件: 确保您的计算机上已 安装Homebrew  。它是一个软件包,可让您安装 Apple 未提供的各种应用程序。

  • 打开一个新的终端窗口并运行以下命令来安装 WebUI 依赖项。

苹果:

brew install cmake protobuf rust python@3.10 git wget
Enter fullscreen mode Exit fullscreen mode

基于 Debian:

sudo apt install wget git python3 python3-venv
Enter fullscreen mode Exit fullscreen mode

基于 Red Hat:

sudo dnf install wget git python3
Enter fullscreen mode Exit fullscreen mode

基于 Arch:

sudo pacman -S wget git python3
Enter fullscreen mode Exit fullscreen mode
  • 通过运行以下命令克隆 Web UI 存储库:
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui
Enter fullscreen mode Exit fullscreen mode
  • 我们需要下载稳定扩散模型(大文件)。导航至 stable-diffusion-webui/models/Stable-diffusion
cd stable-diffusion-webui/models/Stable-diffusion
Enter fullscreen mode Exit fullscreen mode

下载模型 - 在我们的用例中,我们将使用 Stable Diffusion 1.5,但您也可以下载任何其他版本
下载方法如下:

wget https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt
Enter fullscreen mode Exit fullscreen mode

将模型从 v1-5-pruned-emaonly.ckpt 重命名为 model.ckpt
mv v1-5-pruned-emaonly.ckpt model.ckpt

  • 导航到stable-diffusion-webui文件夹并运行 Web UI 项目以创建虚拟环境并安装其依赖项。
cd stable-diffusion-webui
./webui.sh
Enter fullscreen mode Exit fullscreen mode
  • 访问本地 URL -http://127.0.0.1:7860通过其用户界面与 Web UI 进行交互。

网页界面

  • 要稍后重新启动 Web UI 进程,请导航到stable-diffusion-webui终端上的文件夹并运行命令./webui.sh。如果要使用 Web UI API,请在命令中添加 api 标志./webui.sh --api

构建 Web 应用程序

在本节中,我将指导您创建 Web 应用程序的项目环境。我们将使用 React.js 作为前端,使用 Node.js 作为后端服务器。

通过运行以下代码为 Web 应用程序创建项目文件夹:

mkdir stable-diffusion-app
cd stable-diffusion-app
mkdir client server
Enter fullscreen mode Exit fullscreen mode

设置 React 应用程序

通过终端导航到客户端文件夹并创建一个新的 React.js 项目。

cd client
npx create-react-app ./
Enter fullscreen mode Exit fullscreen mode

从 React 应用程序中删除冗余文件,例如徽标和测试文件,并更新App.js文件以显示“Hello World”,如下所示。

function App() {
    return (
        <div>
            <p>Hello World!</p>
        </div>
    );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

导航到src/index.css文件并复制以下代码。它包含设计此项目所需的所有 CSS。

@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap");
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    font-family: "Space Grotesk", sans-serif;
}
.app,
.loading,
.result__container > div {
    display: flex;
    align-items: center;
    justify-content: center;
}
.app {
    width: 100%;
    margin: 50px auto;
    flex-direction: column;
}
.app > h1 {
    margin-bottom: 30px;
    color: #2b3467;
}
form {
    display: flex;
    flex-direction: column;
    width: 80%;
}
textarea {
    padding: 20px;
    border: 1px solid #ddd;
    outline: none;
    border-radius: 5px;
    margin: 5px 0px;
    box-shadow: 0 2px 8px 0 rgba(99, 99, 99, 0.2);
}
button {
    margin-top: 15px;
    display: inline-block;
    width: 200px;
    padding: 20px;
    cursor: pointer;
    font-weight: bold;
    border: none;
    border-radius: 5px;
    outline: none;
    font-size: 18px;
    background-color: #f0dbdb;
}
.loading {
    width: 100%;
    height: 100vh;
    background-color: #fefcf3;
}
.result__container {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin-top: 30px;
}
.result__container > div {
    margin: 5px;
    flex-direction: column;
}
.image {
    width: 400px;
    height: 300px;
    margin-bottom: 15px;
}
Enter fullscreen mode Exit fullscreen mode

更新App.js文件以显示一个输入字段,允许您输入建议的网站描述。

import React, { useState } from "react";

const App = () => {
    const [description, setDescription] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log({ description });
        setDescription("");
    };

    return (
        <div className='app'>
            <h1>Website Idea Generator</h1>
            <form method='POST' onSubmit={handleSubmit}>
                <label htmlFor='description'>Enter the description</label>
                <textarea
                    name='description'
                    rows={6}
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                />
                <button>GENERATE</button>
            </form>
        </div>
    );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

设置

设置 Node.js 服务器

导航到终端内的服务器文件夹并创建一个package.json文件。

cd server & npm init -y
Enter fullscreen mode Exit fullscreen mode

安装 Express、Nodemon 和 CORS 库。

npm install express cors nodemon
Enter fullscreen mode Exit fullscreen mode

ExpressJS是一个快速、简约的框架,它提供了在 Node.js 中构建 Web 应用程序的多种功能,  CORS是一个允许不同域之间通信的 Node.js 包,  Nodemon 是一个在检测到文件更改后自动重启服务器的 Node.js 工具。

创建一个index.js文件——Web 服务器的入口点。

touch index.js
Enter fullscreen mode Exit fullscreen mode

使用 ExpressJS 设置 Node.js 服务器。当您http://localhost:4000/api在浏览器中访问时,下面的代码片段会返回一个 JSON 对象。

//👇🏻index.js
const express = require("express");
const cors = require("cors");
const app = express();
const PORT = 4000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());

app.get("/api", (req, res) => {
    res.json({
        message: "Hello world",
    });
});

app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

安装 Axios、 非官方 ChatGPT API 库和 Puppeteer。ChatGPT API 使用 Puppeteer 作为可选的对等依赖项,以自动绕过 Cloudflare 保护。

npm install chatgpt puppeteer axios
Enter fullscreen mode Exit fullscreen mode

要在文件中使用 ChatGPT API server/index.js,您需要将文件配置为使用requireimport关键字来导入库。
因此,请更新server/package.json文件以包含type关键字。

{ "type": "module" }
Enter fullscreen mode Exit fullscreen mode

在文件顶部添加下面的代码片段server/index.js

import { createRequire } from "module";
const require = createRequire(import.meta.url);
//...other code statements
Enter fullscreen mode Exit fullscreen mode

完成最后两个步骤后,您现在就可以在index.js文件中使用 ChatGPT。

通过将启动命令添加到package.json文件中的脚本列表中来配置 Nodemon。下面的代码片段使用 Nodemon 启动服务器。

//In server/package.json

"scripts": {
    "test": "echo \\"Error: no test specified\\" && exit 1",
    "start": "nodemon index.js"
  },
Enter fullscreen mode Exit fullscreen mode

恭喜!您现在可以使用以下命令启动服务器。

npm start
Enter fullscreen mode Exit fullscreen mode

如何在 Node.js 应用程序中与 ChatGPT 通信

在本节中,您将学习如何通过非官方 ChatGPT 库从 Node.js 服务器与 ChatGPT 进行通信 

该库使用基于浏览器的全自动解决方案,使我们能够进入 - 这意味着它执行完整的浏览器自动化,使我们能够登录 OpenAI 网站,解决验证码并通过 OpenAI cookie 发送消息。

您已在上一节中安装了库;接下来,请index.js按如下所示将 ChatGPT API 库导入到文件中。ChatGPT API 使用 Puppeteer 作为可选的对等依赖项,以自动绕过 Cloudflare 保护措施。

import { ChatGPTAPIBrowser } from "chatgpt";
Enter fullscreen mode Exit fullscreen mode

我们需要 ChatGPT 为用户指定的任何描述生成域名,并为 Stable Diffusion API 创建提示。

因此,在服务器上创建一个接受来自 React 应用程序的描述的路由。

app.post("/api", async (req, res) => {
    const { prompt } = req.body;
    console.log(prompt);
});
Enter fullscreen mode Exit fullscreen mode

/api在 React 应用程序中创建一个函数,一旦用户提交表单,该函数就会将描述发送到服务器上的端点。

async function sendDescription() {
    try {
        const request = await fetch("http://localhost:4000/api", {
            method: "POST",
            body: JSON.stringify({
                prompt: description,
            }),
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
        });
        const res = await request.json();
        console.log(res);
    } catch (err) {
        console.error(err);
    }
}
Enter fullscreen mode Exit fullscreen mode

在 React 应用程序中添加一个保存请求状态的加载状态,并在提交表单后调用异步函数。

const [description, setDescription] = useState("");
const [loading, setLoading] = useState(false);

const handleSubmit = (e) => {
    e.preventDefault();
    //👇🏻 calls the async function
    sendDescription();
    setDescription("");
    setLoading(true);
};
Enter fullscreen mode Exit fullscreen mode

更新/api端点以将描述发送到 ChatGPT 并生成域名并提示稳定扩散。

async function chatgptFunction(content) {
    try {
        const api = new ChatGPTAPIBrowser({
            email: "YOUR_CHATGPT_EMAIL_ADDRESS",
            password: "YOUR_CHATGPT_PASSWORD",
        });
        await api.initSession();

        //👇🏻 sends the instruction for the domain name to ChatGPT
        const getDomainName = await api.sendMessage(
            `Can you generate a domain name for a website about: ${content}`
        );
        let domainName = getDomainName.response;

        //👇🏻 sends the instruction for the prompt to ChatGPT
        const generatePrompt = await api.sendMessage(
            `I have a website for ${content}, and I want to generate a logo for it, can you generate a prompt for dall-e for me? make it long like 50 words, you don't need to tell me why you generated the prompt`
        );
        const diffusionPrompt = generatePrompt.response;

        console.log({ domainName, diffusionPrompt });
    } catch (err) {
        console.error(err);
    }
}

app.post("/api", async (req, res) => {
    const { prompt } = req.body;
    const result = await chatgptFunction(prompt);
    res.json({ message: "Retrieved successfully!" });
});
Enter fullscreen mode Exit fullscreen mode

上面的代码片段使用 Puppeteer 启动浏览器并允许您自动登录 ChatGPT 帐户。身份验证后,ChatGPT 会处理请求并返回响应。

在接下来的部分中,我将指导您如何将生成的提示发送到 Stable Diffusion API。

如何与稳定扩散 API 交互

要与 Stable Diffusion API 交互,请通过运行以下命令重新启动 Web UI 进程:

cd stable-diffusion-webui
./webui.sh --api
Enter fullscreen mode Exit fullscreen mode

http://127.0.0.1:7860/docs您可以在“我们将利用/sdapi/v1/txt2img端点进行文本到图像的转换”处查看可用的 API 端点。

AI端点

/sdapi/v1/txt2img以生成的提示作为有效负载向端点发出 POST 请求。

async function chatgptFunction(content) {
    try {
        const api = new ChatGPTAPIBrowser({
            email: "asaoludavid234@yahoo.com",
            password: "davidasaolu",
        });
        await api.initSession();

        const getDomainName = await api.sendMessage(
            `Can you generate a domain name for a website about: ${content}`
        );
        let domainName = getDomainName.response;

        const generatePrompt = await api.sendMessage(
            `I have a website for ${content}, and I want to generate a logo for it, can you generate a prompt for dall-e for me? make it long like 50 words, you don't need to tell me why you generated the prompt`
        );
        const diffusionPrompt = generatePrompt.response;

        //👇🏻 Makes a POST request via Axios with the prompt as the payload
        const request = await axios.post("http://127.0.0.1:7860/sdapi/v1/txt2img", {
            prompt: diffusionPrompt,
        });
        //👇🏻 returns the generated logo and the domain name
        let logoImage = await request.data.images;
        return { logoImage, domainName };
    } catch (err) {
        console.error(err);
    }
}
Enter fullscreen mode Exit fullscreen mode

从上面的代码片段中,/sdapi/v1/txt2img端点接受一个名为 prompt 的必需参数——要生成的图像的文本描述。

更新/apiNode.js 服务器上的端点以保存结果并将其发送到 React.js 应用程序。

//👇🏻 holds the results
const database = [];

app.post("/api", async (req, res) => {
    const { prompt } = req.body;
    const result = await chatgptFunction(prompt);
    //👇🏻 saves the result to the database array
    database.push(result);
    //👇🏻 return the result as a response
    res.json({ message: "Retrieved successfully!", result: database });
});
Enter fullscreen mode Exit fullscreen mode

使用 React 应用显示结果

更新sendDescription函数以接收来自服务器的响应。

//👇🏻 React state that holds the result
const [result, setResult] = useState([]);

async function sendDescription() {
    try {
        const request = await fetch("http://localhost:4000/api", {
            method: "POST",
            body: JSON.stringify({
                prompt: description,
            }),
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
        });
        const res = await request.json();
        if (res.message) {
            //👇🏻 update the loading and result states
            setLoading(false);
            setResult(res.result);
        }
    } catch (err) {
        console.error(err);
    }
}
Enter fullscreen mode Exit fullscreen mode

创建一个加载组件,当请求处于待处理状态时向用户显示该组件。

import React from "react";

const Loading = () => {
    return (
        <div className='loading'>
            <h1>Loading, please wait...</h1>
        </div>
    );
};

export default Loading;
Enter fullscreen mode Exit fullscreen mode

添加下面的代码片段以在请求待处理时显示组件。

if (loading) return <Loading />;
Enter fullscreen mode Exit fullscreen mode

更新组件以呈现如下所示生成的结果。

return (
    <div className='app'>
        <h1>Website Idea Generator</h1>
        <form method='POST' onSubmit={handleSubmit}>
            <label htmlFor='description'>Enter the description</label>
            <textarea
                name='description'
                rows={6}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
            />
            <button>GENERATE</button>
        </form>

        <div className='result__container'>
            {result.length > 0 &&
                result.map((item, index) => (
                    <div key={index}>
                        <img
                            src={`data:image/png;base64,${item.logoImage}`}
                            alt={item.domainName}
                            className='image'
                        />
                        <p>Domain: {item.domainName}</p>
                    </div>
                ))}
        </div>
    </div>
);
Enter fullscreen mode Exit fullscreen mode

上面的代码片段显示了针对各种请求生成的徽标和域名。恭喜!🎉您已完成本教程的项目。

以下是鸡尾酒网站的结果示例:

SD

结论

到目前为止,您已经学习了:

  • 什么是稳定扩散,
  • 如何在您的计算机上安装和设置稳定扩散
  • 如何从 Node.js 应用程序向 ChatGPT 发送消息,以及
  • 如何通过稳定扩散 API 从文本生成图像。

本教程将引导您了解使用 Stable Diffusion 和 ChatGPT 构建的应用程序示例。这些 AI 技术可用于创建适用于各个领域的强大应用程序。

本教程的源代码可以在这里找到:

https://github.com/novuhq/blog/tree/main/webapp-with-stable-diffusion-and-chatgpt

感谢您的阅读!

帮帮我!

如果你觉得这篇文章对你有帮助,请点个星,我会非常高兴!也请在评论区告诉我❤️

https://github.com/novuhq/novu
图片描述

鏂囩珷鏉ユ簮锛�https://dev.to/novu/creating-a-website-brand-with-chatgpt-stable-diffusion-react-and-nodejs-e79
PREV
JavaScript: Handling errors like Go Everyday Promise-like functions Converting to async/await Unified return interface with async/await
NEXT
How I become a full stack JavaScript developer from PHP in 2019 First Phage (January – February) Second Phage (March to June) Third Phage (July – September) Fourth Phage (October – December) Frontend (React JS Learning) Backend (Node JS & Express Learning) Databases Rest API & GraphQL