File size: 6,691 Bytes
3f2aeda
 
a93b6a1
a856a85
dcd36fb
fe6ce24
23f730c
26a38d9
41a98fd
3f2aeda
 
 
 
 
 
 
 
7b34a09
3f2aeda
7b34a09
180e271
0ab6f43
3f2aeda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ab6f43
 
 
 
 
79a8582
0ab6f43
 
 
 
 
 
 
 
 
 
f6a84d4
 
 
0ab6f43
 
f6a84d4
 
 
0ab6f43
 
 
 
 
 
 
 
 
 
 
 
10cb96e
7b34a09
 
 
 
10cb96e
7b34a09
 
10cb96e
7b34a09
 
 
 
 
 
 
 
 
 
 
 
41a98fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f2aeda
 
 
bcbd89a
 
 
 
 
 
 
 
 
 
 
0ab6f43
 
 
 
 
7e0ffd4
3dca5ad
180e271
 
0ab6f43
 
3763082
 
 
c3fed7a
 
3763082
0ab6f43
3763082
0ab6f43
 
 
7b34a09
 
10cb96e
4f085a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a7193
 
4f085a5
f6a7193
4f085a5
 
f6a7193
4f085a5
f6a7193
 
4f085a5
 
 
 
 
 
dcd36fb
4f085a5
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import express from "express";
import os from "os";
import morgan from "morgan";
import bytes from "bytes";
import axios from "axios";
import { FormData, Blob } from "formdata-node";
import { fileTypeFromBuffer } from "file-type";
import { Client } from "@gradio/client";
import { stablediff } from "./lib/diffusion.js"

const app = express();
app.set('json spaces', 4);
app.use(morgan('dev'));
app.use(express.json({ limit: "500mb" }));
app.use(express.urlencoded({ limit: '500mb', extended: true }));
app.use((req, res, next) => {
  next()
});

const apikey = "@SadTeam77";


app.all('/', (req, res) => {
	const status = {}
	const used = process.memoryUsage()
	for (let key in used) status[key] = formatSize(used[key])
	
	const totalmem = os.totalmem()
	const freemem = os.freemem()
	status.memoryUsage = `${formatSize(totalmem - freemem)} / ${formatSize(totalmem)}`

    console.log("YOUR IP: " + req.ip)
	
	res.json({
		creator: "@SadTeams",
		message: 'Hello World!!',
		uptime: new Date(process.uptime() * 1000).toUTCString().split(' ')[4],
		status
	})
})

app.post('/api/img2img', async (req, res) => {
	try {
		console.log(req.body)
		const { images, prompt, status } = req.body
        if (!images) return res.json({ success: false, message: 'Required an images!' })
        if (!prompt) return res.json({ succese: false, message: 'Require an Promot text Image!'})
        if (!status) return res.json({ success: false, message: 'Required an status text!' })

        if(status !== apikey) return res.json({ success: false, message: 'Invalid status!' })
        if (/^(https?|http):\/\//i.test(images)) {
          const data_img = await axios.request({
            method: "GET",
            url: images,
            responseType: "arraybuffer"
          })
          const response = await processImage2Img(data_img.data, prompt)
          //const type_img = await fileTypeFromBuffer(response)
          //res.setHeader('Content-Type', type_img.mime)
          res.json(response)
        } else if (images && typeof images == 'string' && isBase64(images)) {
	   	  const response = await processImage2Img(Buffer.from(images, "base64"), prompt)
          //const type_img = await fileTypeFromBuffer(response)
          //res.setHeader('Content-Type', type_img.mime)
          res.json(response)
        } else {
          res.json({
            success: false, message: 'No url or base64 detected!!' 
          })
        }
	} catch (e) {
		console.log(e)
		e = String(e)
		res.json({ error: true, message: e === '[object Object]' ? 'Internal Server Error' : e })
	}
})

app.post('/api/openai/gpt4', async (req, res) => {
	try {
		console.log(req.body)
		const { prompt, status } = req.body
        if (!prompt) return res.json({ succese: false, message: 'Require an Promot text!'})
        if (!status) return res.json({ success: false, message: 'Required an status text!' })

        if(status !== apikey) return res.json({ success: false, message: 'Invalid status!' })
        const response = await askOpenGPT4o(prompt);

        res.json({
          status: true,
          result: response
        });
	} catch (e) {
		console.log(e)
		e = String(e)
		res.json({ error: true, message: e === '[object Object]' ? 'Internal Server Error' : e })
	}
})

app.post('/api/stabeldiff', async (req, res) => {
	try {
		console.log(req.body)
		const { prompt, status } = req.body
        if (!prompt) return res.json({ succese: false, message: 'Require an Promot text!'})
        if (!status) return res.json({ success: false, message: 'Required an status text!' })

        if(status !== apikey) return res.json({ success: false, message: 'Invalid status!' })
        const response = await stablediff(prompt);
        const type_img = await fileTypeFromBuffer(response[0]);
        
        res.setHeader('Content-Type', type_img.mime);
        res.send(response[0]);
	} catch (e) {
		console.log(e)
		e = String(e)
		res.json({ error: true, message: e === '[object Object]' ? 'Internal Server Error' : e })
	}
})

const PORT = process.env.PORT || 7860
app.listen(PORT, () => {
  console.log('App running on port', PORT)
})

function formatSize(num) {
	return bytes(+num || 0, { unitSeparator: ' ' })
}
function isBase64(str) {
	try {
		return btoa(atob(str)) === str
	} catch {
		return false
	}
}

async function processImage2Img(imgBuffer, prompt) {
  return new Promise(async (resolve, reject) => {
    try {
      const imageArray = Buffer.from(imgBuffer);

      process.env.GRADIO_CLIENT_DEBUG = 'true';

      const app = await Client.connect("Manjushri/SDXL-Turbo-Img2Img-CPU");
      const result = await app.predict("/predict", [
        imageArray, // binary input for the image
        prompt, // string input for the prompt
        1, // number input for the number of iterations
        540388010706833800, // number input for the seed
        0.3, // number input for the strength
      ]);
      resolve(result.data);
    } catch (e) {
      reject(e.message);
    }
  });
}

async function askOpenGPT4o(prompt) {
    try {
      const session_hash = Math.random().toString(36).substring(2).slice(1);
  
      const resPrompt = await axios.post('https://kingnish-opengpt-4o.hf.space/run/predict?__theme=light', {
        data: [{ text: prompt, files: [] }],
        event_data: null,
        fn_index: 3,
        trigger_id: 34,
        session_hash,
      });
  
      const res = await axios.post('https://kingnish-opengpt-4o.hf.space/queue/join?__theme=light', {
        data: [
          null,
          null,
          'idefics2-8b-chatty',
          'Top P Sampling',
          0.5,
          4096,
          1,
          0.9,
          true,
        ],
        event_data: null,
        fn_index: 5,
        trigger_id: 34,
        session_hash,
      });
  
      const event_ID = res.data.event_id;
  
      const anu = await axios.get(`https://kingnish-opengpt-4o.hf.space/queue/data?session_hash=${session_hash}`);
      const lines = anu.data.split('\n');
      const processStartsLine = lines.find(line => line.includes('process_completed'));
      const processStartsData = JSON.parse(processStartsLine.replace('data: ', ''));
      
      const processStartsLine_2 = lines.find(line => line.includes('process_generating'));
      const processStartsData_2 = JSON.parse(processStartsLine_2.replace('data: ', ''));

  
      if (processStartsData?.success) {
        return processStartsData.output.data[0][0][1];
      } else if (processStartsData_2?.success) {
        return processStartsData_2.output.data[0][0][1];
      }
      

    } catch (error) {
      console.error('Error occurred:', error);
      return `Error: ${error.message}`;
    }
  }