Helper-esm / index.js
Khrisna's picture
Update index.js
f6a7193 verified
raw
history blame
6.69 kB
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}`;
}
}