File size: 2,432 Bytes
e6cc3a0
 
 
 
 
 
 
 
 
 
 
e9d9924
b96b581
 
 
 
 
 
 
 
 
 
 
 
 
 
e6cc3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96



/*
//
// Dibuat oleh Kaze 
// https://github.com/KazeDevID
// https://whatsapp.com/channel/0029VaFNnRTHLHQR6G0fC01O
//
*/

import WebSocket from "ws";


function createHash(length) {
  var chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  var text = '';

  length = length || 6;

  for (var i = 0; i < length; i++) {
    text += chars.charAt(Math.floor(Math.random() * chars.length));
  }

  return text;
}

const generateHash = () => {
  let m = createHash(12);
  return {
    session_hash: m,
    fn_index: 2
  }
}

async function stablediff(prompt) {
  return new Promise((resolve, reject) => {
    let timerCounter = setTimeout(async () => {
      reject(new Error('Permintaan Anda telah habis waktu. Silakan coba lagi'));
    }, 129000)
    const ws = new WebSocket('wss://stabilityai-stable-diffusion.hf.space/queue/join');
    const hash = generateHash();
    
    ws.on('open', () => {});
    
    ws.on('message', async (message) => {
      try {
        const msg = JSON.parse(`${message}`);
      
        if (msg.msg === 'send_hash') {
          ws.send(JSON.stringify(hash));
        } else if (msg.msg === 'send_data') {
          const data = {
            data: [prompt,"",10],
            ...hash,
          };
          ws.send(JSON.stringify(data));
        } else if (msg.msg === 'estimation') {
        } else if (msg.msg === 'process_completed') {
          clearTimeout(timerCounter)
          try {
            const resultsArr = msg.output.data[0];
            const imgArr = [];
            const resultsStr = [resultsArr].toString();
            for (let i = 0; i < resultsArr.length; i++) {
              const imgData = resultsArr[i].split(',')[1];
              const buffer = Buffer.from(imgData, 'base64');
              imgArr.push(buffer);
            }
            resolve(imgArr);
          } catch (error) {
            console.error(error);
          } finally {
            ws.removeAllListeners();
            ws.close();
          }
        } else if (msg.msg === 'queue_full') {
          try {
            reject(new Error('Antrean penuh.'));
          }
          catch (error) {
            console.error(error);
            reject(new Error('Terjadi kesalahan saat menghasilkan gambar'));
          }
        }
      } catch (error) {
        reject(error);
      };
    });
    ws.on('error', async (error) => {
      console.error(error)
    }); 
  });    
}

export { stablediff }