使用 Cloudflare Workers AI 免费搭建 stable-diffusion 绘画 API
终于 Cloudflare Workers AI 模型增加了 @cf/stabilityai/stable-diffusion-xl-base-1.0
,目前可以免费白嫖,记录一下使用过程。
准备
- Cloudflare 账号
- Node 环境
1.安装 Wrangler
sudo npm install -g wrangler
2.授权
wrangler login
执行这个命令后会跳转到浏览器 Cloudflare 授权界面,操作授权即可。
3.初始化项目
wrangler init
根据提示选择配置,模版选择 "Hello World"。
╭ Create an application with Cloudflare Step 1 of 3
│
├ In which directory do you want to create your application?
│ dir ./tiny-frog-cc56
│
├ What type of application do you want to create?
│ type "Hello World" Worker
│
├ Do you want to use TypeScript?
│ no typescript
│
├ Copying files from "hello-world" template
│
├ Retrieving current workerd compatibility date
│ compatibility date 2023-10-30
│
├ Do you want to use git for version control?
│ yes git
│
╰ Application created
╭ Installing dependencies Step 2 of 3
│
├ Installing dependencies
│ installed via `npm install`
│
├ Committing new files
│ git commit
│
╰ Dependencies Installed
╭ Deploy with Cloudflare Step 3 of 3
│
├ Do you want to deploy your application?
│ no deploy via `npm run deploy`
│
├ APPLICATION CREATED Deploy your application with npm run deploy
│
│ Navigate to the new directory cd tiny-frog-cc56
│ Run the development server npm run start
│ Deploy your application npm run deploy
│ Read the documentation https://developers.cloudflare.com/workers
│ Stuck? Join us at https://discord.gg/cloudflaredev
│
╰ See you again soon!
4.安装 AI 相关依赖和配置
npm install --save @cloudflare/ai
在 wrangler.toml 添加:
[ai]
binding = "AI"
5.修改 src/index.js
import { Ai } from '@cloudflare/ai'
export default {
async fetch(request, env) {
const url = new URL(request.url);
const prompt = url.searchParams.get("prompt");
const ai = new Ai(env.AI);
const inputs = {
prompt: prompt,
};
const response = await ai.run("@cf/stabilityai/stable-diffusion-xl-base-1.0", inputs);
return new Response(response, {
headers: {
"content-type": "image/png",
},
});
}
}
6.运行
wrangler dev --remote
浏览器访问 http://127.0.0.1:8787/?prompt=cyberpunk%20cat
,prompt 参数就是提示词。
7.部署
其实本地运行就够了,如果想放到线上,执行以下部署命令:
wrangler deploy