在本文中,您将学习怎么经过 ChatGPT 和Stable Diffusion的构建一个 Web 运用程序,为您网站描绘生成描绘和适宜的LOGO。

背景介绍

人工智能正在接管国际。这些技能每天都在震撼咱们的国际:ChatGPT和Stable Diffusion。
ChatGPT 能够运用其 GPT3.5 模型答复国际上的任何问题。 Stable Diffusion是一种文本到图画模型,能够将任何文本转化为图片。 结合这两种技能是人工智能的未来。
在本文中,我将向您展现怎么经过将两者结合起来来创立整个网站LOGO 及描绘。

我对这个
感到十分振奋,请点击“喜爱”按钮,这样我知道你喜爱它,你想要更多。

使用 ChatGPT、Stable Diffusion、React 和 NodeJS  构建一个网站LOGO

Novu – 第一个开源告诉基础架构

Novu 是第一个开源告诉基础架构。咱们基本上经过他管理一切产品告诉。它能够集成到运用内(像你在Facebook中的铃铛图标 –Websockets),电子邮件,短信等。

使用 ChatGPT、Stable Diffusion、React 和 NodeJS  构建一个网站LOGO

什么是Stable Diffusion?

Stable Diffusion是一种文本到图画的潜在分散模型,运用户能够根据给定的文本输入在几秒钟内生成图画。它还用于诸如内涂、外涂和生成图画到图画转化等进程。

ChatGPT也是OpenAI练习的AI语言模型,用于生成文本并以类似人类的对话方法与用户交互。用户能够在几秒钟内提交恳求并取得来自历史、科学、数学和时势等广泛主题的信息或问题的答案。

在本文的最终,您将学习怎么运用Stable Diffusion WebUI从文本创立图画,以及怎么从Node.js运用程序向ChatGPT发送音讯。

装置和运转stable-diffusion Web UI

您能够在Windows,Linux和Apple Silicon上装置Stable Diffusion Web UI。在这里,我将辅导您完成Apple Silicon上的装置。

先决条件: 保证在核算机上装置了homebrew。它是一个软件包,可让您装置Apple未提供的各种运用程序。

  1. 打开一个新的终端窗口并运转以下指令以装置 WebUI 依靠项。

**MAC: **

brew install cmake protobuf rust python@3.10 git wget

**根据 Debian: **

sudo apt install wget git python3 python3-venv

**根据小红帽: **

sudo dnf install wget git python3

根据Arch:

sudo pacman -S wget git python3

2.经过运转以下指令克隆 Web UI 存储库:

git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui

3.咱们需要下载Stable Diffusion模型(大文件)。拜访到如下存储路径

cd stable-diffusion-webui/models/Stable-diffusion

4.下载模型 – 对于咱们的用例,咱们将运用Stable Diffusion 1.5版本,你也可下载您想要的任何其他版本。

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

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

6.导航到该文件夹并运转 Web UI 项目以创立虚拟环境并装置其依靠项。stable-diffusion-webui

cd stable-diffusion-webui
./webui.sh

7.拜访本地 URL – 经过其用户界面与 Web UI 交互。http://127.0.0.1:7860

使用 ChatGPT、Stable Diffusion、React 和 NodeJS  构建一个网站LOGO

8.要稍后重新发动 Web UI 进程,请导航到终端上的文件夹并运转指令 。假如要运用 Web UI API,请将标志 api 标志增加到指令中stable-diffusion-webui``./webui.sh``./webui.sh --api

构建 Web 运用程序

在本节中,我将辅导您为 Web 运用程序创立项目环境。咱们将运用 React.js 用于前端,运用 Node.js 用于后端服务器。

经过运转以下代码为 Web 运用程序创立项目文件夹:

mkdir stable-diffusion-app
cd stable-diffusion-app
mkdir client server

设置 React 运用程序

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

cd client
npx create-react-app ./

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

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

导航到该文件并复制下面的代码。它包括设置此项目款式所需的一切 CSS。src/index.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;
}

更新文件以显现答应您输入主张的网站描绘的输入字段。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;

使用 ChatGPT、Stable Diffusion、React 和 NodeJS  构建一个网站LOGO

设置NODE.js服务器

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

cd server & npm init -y

装置 Express、Nodemon 和 CORS 库。

npm install express cors nodemon

ExpressJS是一个快速,精约的框架,它提供了几个用于在Node.js中构建Web运用程序的功用,CORS是一个Node.js包,答应不同域之间的通讯,Nodemon是一个Node.js东西,在检测到文件更改后主动重新发动服务器。

创立一个文件 – Web 服务器的进口点。index.js

touch index.js

运用 ExpressJS 设置 Node.js 服务器。下面的代码片段会在您在浏览器中拜访 时回来一个 JSON 目标。http://localhost:4000/api

//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}`);
});

装置Axios、非官方的 ChatGPT API 库和Puppeteer。ChatGPT API 运用 Puppeteer 作为可选的对等依靠项来主动绕过 Cloudflare 保护。

npm install chatgpt puppeteer axios

要在文件中运用 ChatGPT API,您需要将文件配置为同时运用 and 关键字来导入库。
因而,请更新文件以包括关键字。server/index.js``require``import``server/package.json``type

{ "type": "module" }

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

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

完成最终两个过程后,您现在能够在文件中运用 ChatGPT。index.js

经过将发动指令增加到文件中的脚本列表中来配置 Nodemon。下面的代码片段运用 Nodemon 发动服务器。package.json

//In server/package.json
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },

祝贺!现在,您能够运用以下指令发动服务器。

npm start

怎么在 Node.js 运用程序中与 ChatGPT 通讯

在本节中,您将学习怎么经过非官方的 ChatGPT 库从 Node.js 服务器与ChatGPT通讯。

该库运用根据浏览器的全主动解决方案,使咱们能够快速进入 – 这意味着它履行完整的浏览器主动化,答应咱们登录 OpenAI 网站、解决验证码并经过 OpenAI cookie 发送音讯。

您已在上一节中装置了该库;接下来,将 ChatGPT API 库导入到文件中,如下所示。ChatGPT API 运用 Puppeteer 作为可选的对等依靠项来主动绕过 Cloudflare 保护。index.js

import { ChatGPTAPIBrowser } from "chatgpt";

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

因而,在服务器上创立一个接受来自 React 运用程序的描绘的路由。

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

在 React 运用程序中创立一个函数,该函数在用户提交表单后将描绘发送到服务器上的端点。/api

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);
    }
}

在 React 运用程序中增加一个加载状况,用于保存恳求状况,并在提交表单后调用异步函数。

const [description, setDescription] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmit = (e) => {
    e.preventDefault();
    // calls the async function
    sendDescription();
    setDescription("");
    setLoading(true);
};

更新端点以将描绘发送到 ChatGPT,并生成域名并提示Stable Diffusion。/api

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!" });
});

上面的代码片段运用Puppeteer发动浏览器,并使您能够主动登录您的ChatGPT帐户。身份验证后,ChatGPT 处理恳求并回来呼应。

鄙人一节中,我将辅导您怎么将生成的提示发送到Stable Diffusion API。

怎么与Stable Diffusion API 交互

要与Stable Diffusion API 交互,请经过运转以下指令重新发动 Web UI 进程:

cd stable-diffusion-webui
./webui.sh --api

能够在以下方位检查可用的 API 终结点 咱们将运用该终结点进行文本到图画的转化。http://127.0.0.1:7860/docs``/sdapi/v1/txt2img

使用 ChatGPT、Stable Diffusion、React 和 NodeJS  构建一个网站LOGO

向端点发出 POST 恳求,并将生成的提示作为有用负载。/sdapi/v1/txt2img

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);
    }
}

从上面的代码片段中,端点接受称为 prompt 的必需参数 – 要生成的图画的文本说明。/sdapi/v1/txt2img

更新 Node.js 服务器上的端点以保存成果并将其发送到 React.js 运用程序。/api

// 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 });
});

运用 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);
    }
}

创立一个加载组件,每当恳求挂起时都会向用户显现该组件。

import React from "react";
const Loading = () => {
    return (
        <div className='loading'>
            <h1>Loading, please wait...</h1>
        </div>
    );
};
export default Loading;

增加下面的代码片段,以便在恳求挂起时显现组件。

if (loading) return <Loading />;

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

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>
);

上面的代码片段显现了为各种恳求生成的徽标和域名。恭喜!你已完本钱教程的项目。

以下是鸡尾酒网站取得的成果示例:

使用 ChatGPT、Stable Diffusion、React 和 NodeJS  构建一个网站LOGO

定论

到目前为止,您现已了解了:

  • 什么是Stable Diffusion,
  • 怎么在您的核算机上装置和设置Stable Diffusion
  • 怎么从 Node.js 运用程序向 ChatGPT 发送音讯,以及
  • 怎么经过Stable Diffusion API 从文本生成图画。

本教程将引导您完成一个能够运用Stable Diffusion和 ChatGPT 构建的运用程序示例。这些AI技能可用于创立在各个领域有用的强壮运用程序。

本教程的源代码可在此处取得:

github.com/novuhq/blog…

感谢您的阅览!

帮帮我!

假如你觉得这篇文章对你有帮助,假如你能给咱们一颗星,我会十分高兴!并在谈论❤️中让我知道


本文正在参与 人工智能创作者扶持计划