Spaces:
Running
Running
Create lib/diffusion.js
Browse files- lib/diffusion.js +83 -0
lib/diffusion.js
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
|
4 |
+
/*
|
5 |
+
//
|
6 |
+
// Dibuat oleh Kaze
|
7 |
+
// https://github.com/KazeDevID
|
8 |
+
// https://whatsapp.com/channel/0029VaFNnRTHLHQR6G0fC01O
|
9 |
+
//
|
10 |
+
*/
|
11 |
+
|
12 |
+
import WebSocket from "ws":
|
13 |
+
import { generateHash } from "hash-generator";
|
14 |
+
|
15 |
+
const generateHash = () => {
|
16 |
+
let m = createHash(12);
|
17 |
+
return {
|
18 |
+
session_hash: m,
|
19 |
+
fn_index: 2
|
20 |
+
}
|
21 |
+
}
|
22 |
+
|
23 |
+
async function stablediff(prompt) {
|
24 |
+
return new Promise((resolve, reject) => {
|
25 |
+
let timerCounter = setTimeout(async () => {
|
26 |
+
reject(new Error('Permintaan Anda telah habis waktu. Silakan coba lagi'));
|
27 |
+
}, 129000)
|
28 |
+
const ws = new WebSocket('wss://stabilityai-stable-diffusion.hf.space/queue/join');
|
29 |
+
const hash = generateHash();
|
30 |
+
|
31 |
+
ws.on('open', () => {});
|
32 |
+
|
33 |
+
ws.on('message', async (message) => {
|
34 |
+
try {
|
35 |
+
const msg = JSON.parse(`${message}`);
|
36 |
+
|
37 |
+
if (msg.msg === 'send_hash') {
|
38 |
+
ws.send(JSON.stringify(hash));
|
39 |
+
} else if (msg.msg === 'send_data') {
|
40 |
+
const data = {
|
41 |
+
data: [prompt,"",10],
|
42 |
+
...hash,
|
43 |
+
};
|
44 |
+
ws.send(JSON.stringify(data));
|
45 |
+
} else if (msg.msg === 'estimation') {
|
46 |
+
} else if (msg.msg === 'process_completed') {
|
47 |
+
clearTimeout(timerCounter)
|
48 |
+
try {
|
49 |
+
const resultsArr = msg.output.data[0];
|
50 |
+
const imgArr = [];
|
51 |
+
const resultsStr = [resultsArr].toString();
|
52 |
+
for (let i = 0; i < resultsArr.length; i++) {
|
53 |
+
const imgData = resultsArr[i].split(',')[1];
|
54 |
+
const buffer = Buffer.from(imgData, 'base64');
|
55 |
+
imgArr.push(buffer);
|
56 |
+
}
|
57 |
+
resolve(imgArr);
|
58 |
+
} catch (error) {
|
59 |
+
console.error(error);
|
60 |
+
} finally {
|
61 |
+
ws.removeAllListeners();
|
62 |
+
ws.close();
|
63 |
+
}
|
64 |
+
} else if (msg.msg === 'queue_full') {
|
65 |
+
try {
|
66 |
+
reject(new Error('Antrean penuh.'));
|
67 |
+
}
|
68 |
+
catch (error) {
|
69 |
+
console.error(error);
|
70 |
+
reject(new Error('Terjadi kesalahan saat menghasilkan gambar'));
|
71 |
+
}
|
72 |
+
}
|
73 |
+
} catch (error) {
|
74 |
+
reject(error);
|
75 |
+
};
|
76 |
+
});
|
77 |
+
ws.on('error', async (error) => {
|
78 |
+
console.error(error)
|
79 |
+
});
|
80 |
+
});
|
81 |
+
}
|
82 |
+
|
83 |
+
export { stablediff }
|