大家好,很高兴又见面了,我是高级前端进阶,由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发! 今天给大家带来的是360奇舞团前端开发工程师翻译的一篇文章《使用ChatGPT、StableDiffuison、React和NodeJS构建网站图库》,原文链接在文末。话不多说,直接开始!摘要 在本文中,您将学习如何构建一个Web应用程序,该应用程序根据你提供的网站描述,使用ChatGPT和StableDiffusion,生成图标和合适的域名。简介 人工智能正在接管世界。这些技术每天都在震撼着我们的世界:ChatGPT和StableDiffusion。 ChatGPT使用其GPT3。5模型回答世界上的任何问题。 StableDiffusion是一个文本转图片的模型,可以将任何文本转换为图片。 结合使用这两种技术是人工智能的未来。 在本文中,我将向您展示如何通过结合两者来创建整个网站品牌。 我真的很兴奋关于这个技术 什么是StableDiffusion? StableDiffusion是一种文本到图像的潜在扩散模型,使用户能够根据给定的文本输入在几秒钟内生成图像。它还用于诸如图像修复和生成图像到图像的等过程。 ChatGPT也是OpenAI训练的一个AI语言模型,用于生成文本以类似人类的对话方式与用户互动。用户可以在几秒钟内提交请求,并从历史、科学、数学和当前事件等广泛的主题中获得信息或问题的答案。 在本文的最后,你将学到如何使用StableDiffusionWebUI从文本创建图像,以及如何使用Node。js应用程序向ChatGPT发送消息。安装和运行稳定版的DiffusionWebUI 你可以在Windows、Linux、AppleSilicon上下载StableDiffusionWebUI。在这里,我将指导你在AppleSilicon上完成安装。 前提条件:确保你的电脑上已经安装了Homebrew,这是一个安装包,可以让你安装Apple未提供的各种应用程序。打开一个命令行终端,然后输入下面的命令用于下载WebUI的依赖。 MAC:brewinstallcmakeprotobufrustpython3。10gitwget Debianbased:sudoaptinstallwgetgitpython3python3venv RedHatbased:sudodnfinstallwgetgitpython3 Archbased:sudopacmanSwgetgitpython3通过运行以下命令克隆WebUI库gitclonehttps:github。comAUTOMATIC1111stablediffusionwebui我们需要下载稳定版本的StableDiffusion模型(大文件),然后cd进入到stablediffusionwebuimodelsStablediffusion文件夹。cdstablediffusionwebuimodelsStablediffusion 下载此模型对于本次的示例我们使用的是StableDiffusion版本,但是你可以随意下载你想要的其他版本。wgethttps:huggingface。corunwaymlstablediffusionv15resolvemainv15prunedemaonly。ckpt 将模型从v15prunedemaonly。ckpt重命名为model。ckptmvv15prunedemaonly。ckptmodel。ckpt进入到stablediffusionwebui文件夹并且运行webUI工程,创建虚拟环境并安装依赖项。cdstablediffusionwebui。webui。sh访问本地URLhttp:127。0。0。1:7860以通过其用户界面与WebUI交互。在之后要重新启动WebUI进程,请进入到终端上的stablediffusionwebui文件夹并运行命令。webui。sh。如果要使用WebUIAPI,需要在命令中添加API标志。webui。shapi。构建web应用程序 在本节中,我将指导你创建web应用程序的项目环境,我们将使用React。js做前端,Node。js做后端服务器。 使用下面的代码为web应用程序创建项目的文件夹:mkdirstablediffusionappcdstablediffusionappmkdirclientserver设置React应用程序 通过命令进入到client文件夹,然后创建一个新的React。js项目。cdclientnpxcreatereactapp。 从React程序中删除冗余的文件,比如logo和测试文件,并且更新App。js文件以显示HelloWorld,如下所示:functionApp(){return(pHelloWorld!);}exportdefaultA 进入到srcindex。css文件然后拷贝下面的代码,这里面包含此项目需要的所有css样式。importurl(https:fonts。googleapis。comcss2?familySpaceGrotesk:wght300;400;500;600;700displayswap);{boxsizing:margin:0;padding:0;fontfamily:SpaceGrotesk,}。app,。loading,。resultcontainerp{display:alignitems:justifycontent:}。app{width:100;margin:50flexdirection:}。apph1{marginbottom:30color:2b3467;}form{display:flexdirection:width:80;}textarea{padding:20border:1outline:borderradius:5margin:5px0boxshadow:02px8px0rgba(99,99,99,0。2);}button{margintop:15display:width:200padding:20cursor:fontweight:border:borderradius:5outline:fontsize:18backgroundcolor:f0}。loading{width:100;height:100backgroundcolor:fefcf3;}。resultcontainer{display:alignitems:flexwrap:margintop:30}。resultcontainerp{margin:5flexdirection:}。image{width:400height:300marginbottom:15} 更新App。js文件,显示一个输入字框,允许你输入建议的网站描述。importReact,{useState}constApp(){const〔description,setDescription〕useState();consthandleSubmit(e){e。preventDefault();console。log({description});setDescription();};return(h1WebsiteIdeaGeneratorh1);};exportdefaultA 设置Node。js服务器 使用命令行终端进入到server文件夹创建一个package。json文件cdservernpminity 安装Express、Nodemon、CORS库。npminstallexpresscorsnodemon ExpressJS是一个快速、极简的框架,在Node。js中构建Web应用程序它提供了多项功能。CORS是一个Node。js包,允许在不同域之间的通信,Nodemon是一个Node。js工具,可以检测到文件改变的时候重启服务。 创建一个index。js文件web服务器的入口touchindex。js 使用ExpressJS设置Node。js服务器,当在浏览器中访问http:localhost:4000api时,下面的代码会返回一个json对象index。jsconstexpressrequire(express);constcorsrequire(cors);constappexpress();constPORT4000;app。use(express。urlencoded({extended:true}));app。use(express。json());app。use(cors());app。get(api,(req,res){res。json({message:Helloworld,});});app。listen(PORT,(){console。log(Serverlisteningon{PORT});}); 安装Axios、非官方ChatGPTAPIlibrary、Puppeteer。ChatGPTAPI使用Puppeteer作为一个可选的对等依赖,以自动绕过Cloudflare的保护。npminstallchatgptpuppeteeraxios 要在serverindex。js文件中使用ChatGPTAPI,您需要对该文件进行配置,以使用require和import关键词来导入库。因此,更新serverpackage。json文件以包含type关键字。{type:module 在serverindex。js的文件顶部加入下面的代码。import{createRequire}constrequirecreateRequire(import。meta。url);。。。othercodestatement 完成最后两个步骤之后,你现在可以在index。js文件中使用ChatGPT 通过在package。json文件的脚本列表中添加start命令来配置Nodemon。下面的代码片段使用Nodemon启动服务器。Inserverpackage。jsonscripts:{test:echoError:notestspecifiedexit1,start:nodemonindex。js} 恭喜你!现在你可以通过下面的命令来启动服务器npmstart如何在Node。js应用程序中与ChatGPT通信 在本节中,你将学习如何通过非官方的ChatGPT库从Node。js服务器与ChatGPT通信。 该库使用了一个完全自动化的基于浏览器的解决方案,使我们能够爬取我们的方法这意味着它执行了完全的浏览器自动化,使我们能够登录到OpenAI网站,解决验证码,并通过OpenAI的cookies发送消息。 你在一节中已经安装了库,接下来在index。js文件中导入ChatGPTAPI库如下所示,ChatGPTAPI使用Puppeteer作为一个可选的对等依赖,以自动绕过Cloudflare的保护。import{ChatGPTAPIBrowser}fromchatgpt 我们需要ChatGPT,根据用户指定的任何描述生成一个域名,并为StableDiffusionAPI创建一个提示符。 因此,在服务器上创建一个路由,接受来自React应用程序的描述。app。post(api,async(req,res){const{prompt}req。console。log(prompt);}); 在React应用程序中创建一个函数,当用户提交表单,就将描述信息发到服务器上的api端点。asyncfunctionsendDescription(){try{constrequestawaitfetch(http:localhost:4000api,{method:POST,body:JSON。stringify({prompt:description,}),headers:{Accept:applicationjson,ContentType:applicationjson,},});constresawaitrequest。json();console。log(res);}catch(err){console。error(err);}} 在React应用程序中添加一个加载状态,用于保存请求状态,并在提交表单后调用async函数。const〔description,setDescription〕useState();const〔loading,setLoading〕useState(false);consthandleSubmit(e){e。preventDefault();callstheasyncfunctionsendDescription();setDescription();setLoading(true);}; 更新api端点以将描述发送给ChatGPT,并生成一个域名并给StableDiffusion提示。asyncfunctionchatgptFunction(content){try{constapinewChatGPTAPIBrowser({email:YOURCHATGPTEMAILADDRESS,password:YOURCHATGPTPASSWORD,});awaitapi。initSession();sendstheinstructionforthedomainnametoChatGPTconstgetDomainNameawaitapi。sendMessage(Canyougenerateadomainnameforawebsiteabout:{content});letdomainNamegetDomainName。sendstheinstructionfortheprompttoChatGPTconstgeneratePromptawaitapi。sendMessage(Ihaveawebsitefor{content},andIwanttogeneratealogoforit,canyougenerateapromptfordalleforme?makeitlonglike50words,youdontneedtotellmewhyyougeneratedtheprompt);constdiffusionPromptgeneratePrompt。console。log({domainName,diffusionPrompt});}catch(err){console。error(err);}}app。post(api,async(req,res){const{prompt}req。constresultawaitchatgptFunction(prompt);res。json({message:Retrievedsuccessfully!});}); 在上面的代码中使用Puppeteer启动浏览器,并自动登录你的ChatGPT账号,验证完成后,ChatGPT处理请求并返回响应信息。 在下面的部分,我将指导你如何将ChatGPT生成的提示发送到StableDiffusionAPI。如何与StableDiffusionAPI交互 要与StableDiffusionAPI进行交互,请通过下面的命令重启webUI进程。cdstablediffusionwebui。webui。shapi 你可以在http:127。0。0。1:7860docs,查看可用的API端点。我们将利用sdapiv1txt2img端点进行文本到图像的转换。 使用生成的提示作为payload向sdapiv1txt2img端点发送POST请求。asyncfunctionchatgptFunction(content){try{constapinewChatGPTAPIBrowser({email:asaoludavid234yahoo。com,password:davidasaolu,});awaitapi。initSession();constgetDomainNameawaitapi。sendMessage(Canyougenerateadomainnameforawebsiteabout:{content});letdomainNamegetDomainName。constgeneratePromptawaitapi。sendMessage(Ihaveawebsitefor{content},andIwanttogeneratealogoforit,canyougenerateapromptfordalleforme?makeitlonglike50words,youdontneedtotellmewhyyougeneratedtheprompt);constdiffusionPromptgeneratePrompt。MakesaPOSTrequestviaAxioswiththepromptasthepayloadconstrequestawaitaxios。post(http:127。0。0。1:7860sdapiv1txt2img,{prompt:diffusionPrompt,});returnsthegeneratedlogoandthedomainnameletlogoImageawaitrequest。data。return{logoImage,domainName};}catch(err){console。error(err);}} 从上面的代码中,sdapiv1txt2img端点接收一个名为prompt的必须参数要生成图片的文本描述。 更新Node。js服务器上的api端点并保存结果,将其发送到React。js应用程序。使用React程序展示结果 更新sendDescription函数,以接收服务器返回的响应结果。Reactstatethatholdstheresultconst〔result,setResult〕useState(〔〕);asyncfunctionsendDescription(){try{constrequestawaitfetch(http:localhost:4000api,{method:POST,body:JSON。stringify({prompt:description,}),headers:{Accept:applicationjson,ContentType:applicationjson,},});constresawaitrequest。json();if(res。message){updatetheloadingandresultstatessetLoading(false);setResult(res。result);}}catch(err){console。error(err);}} 创建一个Loading组件,在请求等待的过程中显示给用户。importRconstLoading(){return(h1Loading,pleasewait。。。h1);};exportdefaultL 添加下面的代码当请求等待的过程中展示组件。if(loading)returnLoading 更新组件以渲染生成的结果,如下所示。return(h1WebsiteIdeaGeneratorh1{result。length0result。map((item,index)(imgsrca2020imgdataimg。jpgdatasrc{data:base64,{item。logoImage}}alt{item。domainName}classNameimagepDomain:{item。domainName}))}); 上面的代码展示为各样的请求生成图标和域名,恭喜!你完成了本项目的教程。 以下是鸡尾酒网站获得的结果示例: 结论: 到目前为止,你已经学会了:什么是StableDiffusion,如何在你的电脑上安装和配置StableDiffusion如何从Node。js应用发送消息给ChatGPT如何通过StableDiffusionAPI从文本生成图像。 本教程带领你完成一个应用程序示例,你可以使用StableDiffusion和ChatGPT构建应用程序,这些AI技术可以被应用在各个领域创建强大的应用程序。 这个教程的源代码在这里: https:github。comnovuhqblogtreemainwebappwithstablediffusionandchatgpt 感谢你的阅读! 本文译者为360奇舞团前端开发工程师 原文标题:BuildingawebsitegallerywithChatGPT,StableDiffusion,ReactandNodeJS 原文作者:NevoDavid 原文地址:https:javascript。plainenglish。iobuildingawebsitegallerywithchatgptstablediffusionreactandnodejsafe8cdd9567a