demo:
https://aidraw.foxhank.top
0.前言
Cloudflare公司推出了workers-ai,可以免費在 Cloudflare 的全球網路上執行由無伺服器 GPU 提供支援的機器學習模型。
Workers AI 可以 Cloudflare 網路上使用自己的程式碼執行機器學習模型,也就是說,只要寫一個js程式碼,就可以免費呼叫cloudflare提供的大模型。這可以為我們節省大量的GPU支出成本。
當前worker ai提供的模型涵蓋了文字分類、文字生成(GPT)、語音識別、影像分類、翻譯、文生圖等一系列領域,而且呼叫十分方便。
雖然免費使用者每天有限額,但個人使用還是很夠的~
1.前序準備
首先你需要有一個域名,並連線到cloudflare賬戶上。如果沒有域名的話,阿里雲之類的服務商都有新人1元域名活動,一塊錢就能擁有一個屬於自己的網址也是蠻爽的。
而且cloudflare還提供了一系列 白嫖免費計劃,可以零成本(僅域名支出)就能搭建整套的個人網站。
在新增域名的時候,選擇Free計劃
即可。
2.建立專案
2.1 建立worker
在右側的選單裡,選擇 Workers 和 Pages
,隨後點選建立
按鈕。
在下一頁中點選建立Worker
,隨便起個名,點選部署即可
點選右上角的編輯程式碼
,把自帶的演示程式碼全部刪掉,將下方程式碼複製貼上進去
worker.js:
import HTML from './index.html';
export default {
async fetch(request, env) {
const originalHost = request.headers.get("host");
// 設定CORS頭部
const corsHeaders = {
'Access-Control-Allow-Origin': '*', // 允許任何源
'Access-Control-Allow-Methods': 'GET, POST', // 允許的請求方法
'Access-Control-Allow-Headers': 'Content-Type' // 允許的請求頭
};
// 預檢請求
if (request.method === 'OPTIONS') {
return new Response(null, {
status: 204,
headers: corsHeaders
});
}
// 檢查請求方法
if (request.method === 'POST') {
// 處理 POST 請求,用於 AI 繪畫功能
const data = await request.json();
let model = '@cf/lykon/dreamshaper-8-lcm';
if ('prompt' in data && 'model' in data) {
switch(data.model) {
case 'dreamshaper-8-lcm':
model = '@cf/lykon/dreamshaper-8-lcm';
break;
case 'stable-diffusion-xl-base-1.0':
model = '@cf/stabilityai/stable-diffusion-xl-base-1.0';
break;
case 'stable-diffusion-xl-lightning':
model = '@cf/bytedance/stable-diffusion-xl-lightning';
break;
default:
break;
}
const inputs = {
prompt: data.prompt,
};
const response = await env.AI.run(model, inputs);
return new Response(response, {
headers: {
...corsHeaders,
'content-type': 'image/png;base64',
},
});
} else {
return new Response('Missing prompt or model', { status: 400, headers: corsHeaders });
}
} else {
// 處理 GET 請求,返回html頁面
return new Response(HTML.replace(/{{host}}/g, originalHost), {
status: 200,
headers: {
...corsHeaders, // 合併CORS頭部
"content-type": "text/html"
}
});
}
}
};
然後點選左上角的Explorer,選擇New File,新建一個名為index.html
的檔案(如圖所示)
切換到此index.html檔案,將以下程式碼貼上進去:
index.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>AI繪畫</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
display: flex;
flex-direction: column; /* 內容垂直排列 */
}
.box {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(to right, #e6f5ff, #ffe6f5);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.card {
position: absolute;
inset: 2% auto;
max-width: 80%;
width: 90%;
backdrop-filter: blur(21px) saturate(180%);
-webkit-backdrop-filter: blur(21px) saturate(180%);
background-color: rgba(255, 255, 255, 0.53);
border-radius: 10px;
border: 1px solid rgba(209, 213, 219, 0.3);
padding: 20px;
box-sizing: border-box;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 1rem;
left: 50%;
transform: translateX(-50%);
text-align: center;
overflow: hidden;
}
h1 {
font-size: 2.5em;
margin-bottom: 1rem;
}
img {
width: 100%;
max-width: 400px;
height: auto;
margin-bottom: 1rem;
}
select, input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 1rem;
border: 1px solid #ccc;
border-radius: 5px;
line-height: 3.5;
background-color: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(30px) saturate(180%);
border-radius: 5px;
padding: 10px;
outline: none;
transition: background-color 0.3s ease;
}
select, input[type="text"]:focus {
background-color: rgba(255, 255, 255, 99.9);
}
button.submit-btn {
background: linear-gradient(to bottom, #ade8f4, #6cb3e3);
border-radius: 5px;
color: white;
padding: 10px 20px;
font-family: Arial, sans-serif;
cursor: pointer;
border: none;
transition: all 0.3s ease;
}
button.random-btn {
background: white; /* 白色背景 */
color: #007BFF; /* 藍色文字 */
border-radius: 5px;
padding: 5px 40px;
font-family: Arial, sans-serif;
cursor: pointer;
border: 1px solid #007BFF; /* 新增藍色邊框 */
transition: all 0.3s ease;
}
button.submit-btn:hover {
opacity: 0.6;
}
@media screen and (max-width: 600px) {
.card {
inset: 10% auto;
max-width: 100%;
width: 90%;
left: 0%;
transform: none;
/* 保持原有的模糊效果和其他樣式 */
backdrop-filter: blur(21px) saturate(180%);
-webkit-backdrop-filter: blur(21px) saturate(180%);
background-color: rgba(255, 255, 255, 0.53);
border-radius: 10px;
border: 1px solid rgba(209, 213, 219, 0.3);
padding: 20px;
box-sizing: border-box;
display: flex;
flex-direction: column;
justify-content: center;
}
select, input[type="text"] {
width: 90%;
padding: 10px;
margin-bottom: 1rem;
border: 1px solid #ccc;
border-radius: 5px;
line-height: 7;
background-color: rgba(255, 255, 255, 0.1); /* 更改背景顏色以匹配磨砂效果 */
backdrop-filter: blur(30px) saturate(180%); /* 增加模糊量以獲得更重的磨砂效果 */
border-radius: 5px; /* 可選:增加邊框圓角美化 */
padding: 10px; /* 輸入框內邊距,根據需要調整 */
outline: none; /* 移除焦點時的輪廓 */
transition: background-color 0.3s ease; /* 平滑的背景色過渡效果 */
}
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
const submitButton = document.getElementById('submitButton');
submitButton.addEventListener('click', async function (event) {
event.preventDefault();
submitButton.disabled = true;
submitButton.textContent = '正在生成...';
const model = document.getElementById('model').value;
const prompt = document.getElementById('prompt').value;
// 檢查prompt是否為空
if (prompt === '') {
alert('請輸入描述詞');
submitButton.textContent = '提交';
submitButton.disabled = false;
return;
}
const blobToBase64 = (blob) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
// 獲取域名
const currentDomain = window.location.origin;
try {
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => {
controller.abort();
}, 30000); // 30秒超時
const response = await fetch(`${currentDomain}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'model': model,
'prompt': prompt
}),
signal: signal
});
if (!response.ok) {
throw new Error(`請求失敗:${response.status} ${response.statusText}`);
}
// 讀取響應的文字資料
// 將響應體轉換為Blob
const blob = await response.blob();
// 將Blob轉換為Base64編碼的字串
const Image = await blobToBase64(blob);
console.log('Base64 Image:', Image);
// const base64Image = await response.text();
document.getElementById('aiImage').src = `${Image}`;
} catch (error) {
if (error.name === 'AbortError') {
alert('伺服器連線超時,請稍後重試。');
} else {
console.error('Error:', error);
alert('生成過程中發生錯誤,請重試。');
}
} finally {
submitButton.textContent = '提交';
submitButton.disabled = false;
}
});
document.getElementById('randomButton').addEventListener('click', function () {
// 提供的隨機描述詞
var prompts = ['1girl,solo,cute,in glass,atmosphere_X,best quality,beautiful,extremely detailed,masterpiece,very aesthetic',
'a girl,,nahida,light,full body,symbol eye, nahida,1girl,fair_skin,in summer,day,in a meadow,sky,cirrus_fibratus,intense shadows,blonde hair,pleated_dress,collared_shirt,blue eyes,long hair,fang,smile',
'((best quality)), ((masterpiece)),A Chinese couple in Hanfu embracing on an arch bridge, a sky full of rose petals, a romantic atmosphere, a huge moon, colorful clouds, clouds, ethereal, reflections of water, a mirage, a breeze,(Chinese ink style)',
'simple background, flower, signature, no humans, sparkle, leaf, plant, white flower, black background, still life, embroidery',
' 1 girl,(orange light effect),hair ornament,jewelry,looking at viewer,flower,floating hair,water,underwater,air bubble,submerged, 80sDBA style',
'masterpiece,best quality,high quality,loli,1girl, solo, long hair, looking at viewer, blush, bangs, thighhighs, dress, ribbon, brown eyes, very long hair, closed mouth, standing, full body, yellow eyes, white hair, short sleeves, outdoors, sky,no shoes, day, puffy sleeves, looking back, cloud, from behind, white dress, white thighhighs, red ribbon, tree, blue sky, puffy short sleeves, petals, cherry blossoms, skirt hold,',
' 1 girl,Clothes in the shape of snowflake,render,technology, (best quality) (masterpiece), (highly in detailed), 4K,Official art, unit 8 k wallpaper, ultra detailed, masterpiece, best quality, extremely detailed,CG,low saturation, as style, line art',
' best quality,masterpiece,sculpture,wonderland,,chinese fairy tales,an old man,boiling tea,drink tea,a painting of history floating and curved in the background,mountain,white cloud,chinese style courtyard,pavilion,chinese tea mountains,, Chinese architecture, trees,,white hair ,',
' 1girl, absurdres, arrow_(symbol), ata-zhubo, bicycle, billboard, black_eyes, black_footwear, black_hair, blue_sky, bridge, building, car, cardigan, city, cityscape, commentary_request, crosswalk, day, fire_hydrant, folding_bicycle, grey_cardigan, highres, lamppost, loafers, motor_vehicle, necktie, original, overpass, power_lines, railing, red_necktie, red_skirt, road, road_sign, scenery, school_uniform, shoes, short_hair, sign, skirt, sky, solo, stairs, standing, street, traffic_cone, traffic_light, truck, utility_pole, vending_machine',
'1girl, solo, elf, golden eyes, glowing eyes, slit_pupils, silver hair, green gradient hair, long hair, blunt bangs, brown capelet, frilled shirt, long sleeves, green brooch, pouch, belt, brown gloves, upper body, (chibi:0.4), (close-up), (broken:1.3), half-closed eye, expressionless, from side, depth of field, fallen leaves, side light, gingko, tree, masterpiece,bestquality, line art,',
'flower, outdoors, sky, tree, no humans, window, bird, building, scenery, house,oil painting style',
];
var randomIndex = Math.floor(Math.random() * prompts.length);
document.getElementById('prompt').value = prompts[randomIndex];
});
});
</script>
</head>
<body>
<div class="box">
<div class="card">
<h1>AI繪畫</h1>
<img id="aiImage"
src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAIAAAB7GkOtAAADEUlEQVR4nO3BgQAAAADDoPlTX+EAVQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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DreamShaper 8 LCM(容易出黑圖)</option>
<option value="stable-diffusion-xl-base-1.0" selected>Stable Diffusion XL Base 1.0(效果好,速度較慢)</option>
<option value="stable-diffusion-xl-lightning">Stable Diffusion XL Lightning(效果一般,速度較快)</option>
</select>
<input type="text" id="prompt" placeholder="請輸入描述詞...">
<button type="button" class="random-btn" id="randomButton">隨機提示詞</button>
<button type="button" class="submit-btn" id="submitButton">提交</button>
</div>
</div>
</body>
</html>
這裡給定了幾個隨機的提示詞,點選“隨機提示詞”按鈕即可填充,可以根據需要增添。每個提示詞我都生成了幾張示例圖(見最後)。
之後點選右上角的部署
按鈕,並點選“儲存並部署”,即可儲存此Worker。
2.2 繫結AI
返回到worker頁面,選擇設定--變數,向下滑找到"AI繫結"一項。選擇“新增繫結”,
選擇“新增繫結”,名稱寫AI
即可。隨後點選部署按鈕。
2.3 繫結自己的域名
預設的workers.dev域名由於網路原因在國內無法使用,所以需要繫結一個自己的域名。
返回worker頁面,點選“設定”,選擇“新增自定義域”,填入一個剛才繫結在cloudflare的域名,二級域名可以隨便寫,比如:xxx.domain.com,這裡的domain.com就是剛才繫結在cloudflare的域名,xxx可以隨意更改。
輸入後即可點選“新增自定義域”。cloudflare會自動完成解析的工作。
隨後點選下方的“新增路由”,路由輸入框填寫與剛才相同的內容(xxx.domain.com),區域選擇此主域名
稍等片刻,等待證書初始化完成,點選此連結即可訪問剛才部署的頁面。
黑色圖片是佔位符;輸入描述之後點選提交,稍後即可生成圖片。
3.隨機提示詞
以下是部分我使用的提示詞,可以修改html頁面var prompts
部分,每一行是一個提示詞,格式如下:
var prompts = [
'提示詞1',
'提示詞2',
'提示詞3',
];
部分提示詞及生成的圖如下,均使用Stable Diffusion XL Base 1.0生成。
1girl,solo,cute,in glass,atmosphere_X,best quality,beautiful,extremely detailed,masterpiece,very aesthetic
a girl,,nahida,light,full body,symbol eye, nahida,1girl,fair_skin,in summer,day,in a meadow,sky,cirrus_fibratus,intense shadows,blonde hair,pleated_dress,collared_shirt,blue eyes,long hair,fang,smile
((best quality)), ((masterpiece)),A Chinese couple in Hanfu embracing on an arch bridge, a sky full of rose petals, a romantic atmosphere, a huge moon, colorful clouds, clouds, ethereal, reflections of water, a mirage, a breeze,(Chinese ink style)
simple background, flower, signature, no humans, sparkle, leaf, plant, white flower, black background, still life, embroidery
1 girl,(orange light effect),hair ornament,jewelry,looking at viewer,flower,floating hair,water,underwater,air bubble,submerged, 80sDBA style
masterpiece,best quality,high quality,loli,1girl, solo, long hair, looking at viewer, blush, bangs, thighhighs, dress, ribbon, brown eyes, very long hair, closed mouth, standing, full body, yellow eyes, white hair, short sleeves, outdoors, sky,no shoes, day, puffy sleeves, looking back, cloud, from behind, white dress, white thighhighs, red ribbon, tree, blue sky, puffy short sleeves, petals, cherry blossoms, skirt hold,
(ps:效果不太好,AI還是無法理解什麼是手)
1 girl,Clothes in the shape of snowflake,render,technology, (best quality) (masterpiece), (highly in detailed), 4K,Official art, unit 8 k wallpaper, ultra detailed, masterpiece, best quality, extremely detailed,CG,low saturation, as style, line art
best quality,masterpiece,sculpture,wonderland,,chinese fairy tales,an old man,boiling tea,drink tea,a painting of history floating and curved in the background,mountain,white cloud,chinese style courtyard,pavilion,chinese tea mountains,, Chinese architecture, trees,,white hair ,
1girl, absurdres, arrow_(symbol), ata-zhubo, bicycle, billboard, black_eyes, black_footwear, black_hair, blue_sky, bridge, building, car, cardigan, city, cityscape, commentary_request, crosswalk, day, fire_hydrant, folding_bicycle, grey_cardigan, highres, lamppost, loafers, motor_vehicle, necktie, original, overpass, power_lines, railing, red_necktie, red_skirt, road, road_sign, scenery, school_uniform, shoes, short_hair, sign, skirt, sky, solo, stairs, standing, street, traffic_cone, traffic_light, truck, utility_pole, vending_machine
(ps:AI還是沒法把控細節,或者是這個模型的原因...?)
1girl, solo, elf, golden eyes, glowing eyes, slit_pupils, silver hair, green gradient hair, long hair, blunt bangs, brown capelet, frilled shirt, long sleeves, green brooch, pouch, belt, brown gloves, upper body, (chibi:0.4), (close-up), (broken:1.3), half-closed eye, expressionless, from side, depth of field, fallen leaves, side light, gingko, tree, masterpiece,bestquality, line art,
flower, outdoors, sky, tree, no humans, window, bird, building, scenery, house,oil painting style
4.結論
選項全部預設,繪圖大概在10s左右一張圖,倒是可以接受。如果想一次生成多張圖片,可以使用程式給api發請求,worker理論上併發沒限制。
AI還是對手部最佳化不是很理想,涉及到手部的基本都是畸形種,可能是我的模型選取問題...?,而且AI繪畫沒有圖層概念,主體和背景都是交融在一起的,只能期望後續發展了。
['1girl,solo,cute,in glass,atmosphere_X,best quality,beautiful,extremely detailed,masterpiece,very aesthetic',
'a girl,,nahida,light,full body,symbol eye, nahida,1girl,fair_skin,in summer,day,in a meadow,sky,cirrus_fibratus,intense shadows,blonde hair,pleated_dress,collared_shirt,blue eyes,long hair,fang,smile',
'((best quality)), ((masterpiece)),A Chinese couple in Hanfu embracing on an arch bridge, a sky full of rose petals, a romantic atmosphere, a huge moon, colorful clouds, clouds, ethereal, reflections of water, a mirage, a breeze,(Chinese ink style)',
'simple background, flower, signature, no humans, sparkle, leaf, plant, white flower, black background, still life, embroidery',
' 1 girl,(orange light effect),hair ornament,jewelry,looking at viewer,flower,floating hair,water,underwater,air bubble,submerged, 80sDBA style',
'masterpiece,best quality,high quality,loli,1girl, solo, long hair, looking at viewer, blush, bangs, thighhighs, dress, ribbon, brown eyes, very long hair, closed mouth, standing, full body, yellow eyes, white hair, short sleeves, outdoors, sky,no shoes, day, puffy sleeves, looking back, cloud, from behind, white dress, white thighhighs, red ribbon, tree, blue sky, puffy short sleeves, petals, cherry blossoms, skirt hold,',
' 1 girl,Clothes in the shape of snowflake,render,technology, (best quality) (masterpiece), (highly in detailed), 4K,Official art, unit 8 k wallpaper, ultra detailed, masterpiece, best quality, extremely detailed,CG,low saturation, as style, line art',
' best quality,masterpiece,sculpture,wonderland,,chinese fairy tales,an old man,boiling tea,drink tea,a painting of history floating and curved in the background,mountain,white cloud,chinese style courtyard,pavilion,chinese tea mountains,, Chinese architecture, trees,,white hair ,',
' 1girl, absurdres, arrow_(symbol), ata-zhubo, bicycle, billboard, black_eyes, black_footwear, black_hair, blue_sky, bridge, building, car, cardigan, city, cityscape, commentary_request, crosswalk, day, fire_hydrant, folding_bicycle, grey_cardigan, highres, lamppost, loafers, motor_vehicle, necktie, original, overpass, power_lines, railing, red_necktie, red_skirt, road, road_sign, scenery, school_uniform, shoes, short_hair, sign, skirt, sky, solo, stairs, standing, street, traffic_cone, traffic_light, truck, utility_pole, vending_machine',
'Steep stone walls towered into the sky, thunderous waves crashed against the river bank, and the waves stirred up like thousands of piles of white snow.',
'1girl, solo, elf, golden eyes, glowing eyes, slit_pupils, silver hair, green gradient hair, long hair, blunt bangs, brown capelet, frilled shirt, long sleeves, green brooch, pouch, belt, brown gloves, upper body, (chibi:0.4), (close-up), (broken:1.3), half-closed eye, expressionless, from side, depth of field, fallen leaves, side light, gingko, tree, masterpiece,bestquality, line art,',
'flower, outdoors, sky, tree, no humans, window, bird, building, scenery, house,oil painting style',
' (masterpiece,top quality,best quality,official art,beautiful and aesthetic:1.2),gf-hd,1girl,loli,solo,long hair,lovely smilie,(wink),(blazer,white shirt,white blouse:2),cozy,(lace details),v,robinSR,love heart',
' moon,outdoors,full moon,night,flower,cherry blossoms,sky,tree,pink flower flying around,night sky,no humans,masterpiece,illustration,extremely fine and beautiful,perfect details,stream,',
];