CiEL7 commited on
Commit
568802f
·
verified ·
1 Parent(s): cbc41ba

Upload 8 files

Browse files
fast.js ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fastify = require('fastify')({ logger: true });
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const chokidar = require('chokidar');
5
+
6
+ const pluginsDir = path.join(__dirname, 'plugins');
7
+
8
+ // Registrasi EJS
9
+ fastify.register(require('@fastify/view'), {
10
+ engine: { ejs: require('ejs') },
11
+ root: path.join(__dirname, 'plugins') // Template ditaruh di folder plugins
12
+ });
13
+
14
+ let availablePlugins = [];
15
+
16
+ async function loadPlugins() {
17
+ availablePlugins = [];
18
+ if (!fs.existsSync(pluginsDir)) return;
19
+
20
+ const files = fs.readdirSync(pluginsDir);
21
+
22
+ files.forEach(file => {
23
+ if (file.endsWith('.js')) {
24
+ const filePath = path.join(pluginsDir, file);
25
+ delete require.cache[require.resolve(filePath)];
26
+
27
+ try {
28
+ const plugin = require(filePath);
29
+ if (plugin.path && plugin.handler) {
30
+ // Daftarkan route ke Fastify
31
+ fastify.route({
32
+ method: plugin.method || 'GET',
33
+ url: plugin.path,
34
+ handler: plugin.handler
35
+ });
36
+
37
+ // Simpan metadata untuk UI
38
+ availablePlugins.push({
39
+ name: file.replace('.js', ''),
40
+ path: plugin.path,
41
+ method: plugin.method || 'GET',
42
+ description: plugin.description || 'Tidak ada deskripsi'
43
+ });
44
+ }
45
+ } catch (err) {
46
+ console.error(`Error loading ${file}:`, err.message);
47
+ }
48
+ }
49
+ });
50
+ }
51
+
52
+ // Endpoint Utama untuk dokumentasi EJS
53
+ fastify.get('/', async (request, reply) => {
54
+ return reply.view('index.ejs', { plugins: availablePlugins });
55
+ });
56
+
57
+ const start = async () => {
58
+ try {
59
+ await loadPlugins();
60
+ await fastify.listen({ port: 3000, host: '0.0.0.0' });
61
+ console.log('Dokumentasi manual ready di http://localhost:3000');
62
+ } catch (err) {
63
+ fastify.log.error(err);
64
+ process.exit(1);
65
+ }
66
+ };
67
+
68
+ // Auto-reload saat ada file baru
69
+ chokidar.watch(pluginsDir, { ignoreInitial: true }).on('add', () => loadPlugins());
70
+
71
+ start();
package.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dependencies": {
3
+ "@fastify/swagger": "^9.7.0",
4
+ "@fastify/swagger-ui": "^5.2.5",
5
+ "@fastify/view": "^11.1.1",
6
+ "axios": "^1.15.0",
7
+ "chokidar": "^5.0.0",
8
+ "ejs": "^5.0.2",
9
+ "fastify": "^5.8.5",
10
+ "puppeteer": "^24.41.0",
11
+ "undici": "^8.1.0"
12
+ }
13
+ }
plugins/bonsai.js ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Logika internal untuk berkomunikasi dengan API Bonsai
3
+ */
4
+ async function getBonsaiResponse(userMessage) {
5
+ const url = "https://prism-ml-bonsai-demo.hf.space/v1/chat/completions";
6
+ const payload = {
7
+ messages: [{ role: "user", content: userMessage }],
8
+ stream: true,
9
+ temperature: 0.5,
10
+ max_tokens: -1,
11
+ samplers: ["penalties", "dry", "top_n_sigma", "top_k", "typ_p", "top_p", "min_p", "xtc", "temperature"]
12
+ };
13
+
14
+ const response = await fetch(url, {
15
+ method: "POST",
16
+ headers: {
17
+ "Content-Type": "application/json",
18
+ "Referer": "https://prism-ml-bonsai-demo.hf.space/",
19
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
20
+ },
21
+ body: JSON.stringify(payload),
22
+ });
23
+
24
+ if (!response.body) throw new Error("No response body from Bonsai");
25
+
26
+ const reader = response.body.getReader();
27
+ const decoder = new TextDecoder();
28
+ let fullResponse = "";
29
+
30
+ while (true) {
31
+ const { done, value } = await reader.read();
32
+ if (done) break;
33
+
34
+ const chunk = decoder.decode(value);
35
+ const lines = chunk.split("\n");
36
+
37
+ for (const line of lines) {
38
+ if (line.startsWith("data: ") && line !== "data: [DONE]") {
39
+ try {
40
+ const jsonStr = line.replace("data: ", "");
41
+ const data = JSON.parse(jsonStr);
42
+ const content = data.choices[0]?.delta?.content || "";
43
+ fullResponse += content;
44
+ } catch (e) {
45
+ // Mengabaikan error parsing kecil pada chunk yang tidak lengkap
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ return fullResponse;
52
+ }
53
+
54
+ // Export untuk sistem Plug-and-Play Fastify
55
+ module.exports = {
56
+ path: '/bonsai-chat',
57
+ method: 'GET',
58
+ handler: async (request, reply) => {
59
+ const { q } = request.query; // Menggunakan param 'q' untuk pertanyaan
60
+
61
+ if (!q) {
62
+ return reply.status(400).send({
63
+ status: "error",
64
+ message: "Query parameter 'q' diperlukan. Contoh: /bonsai-chat?q=halo"
65
+ });
66
+ }
67
+
68
+ try {
69
+ const result = await getBonsaiResponse(q);
70
+ return {
71
+ status: "success",
72
+ plugin: "bonsai_ai",
73
+ input: q,
74
+ response: result
75
+ };
76
+ } catch (err) {
77
+ return reply.status(500).send({
78
+ status: "error",
79
+ message: err.message
80
+ });
81
+ }
82
+ }
83
+ };
plugins/deepseek.js ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fetch = require('node-fetch');
2
+ const FormData = require('form-data');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ module.exports = {
7
+ path: '/deepseek-ocr',
8
+ method: 'GET',
9
+ description: 'Ekstraksi teks dari gambar (OCR) menggunakan model DeepSeek via Worker Proxy.',
10
+ handler: async (request, reply) => {
11
+ // Menggunakan query 'image' untuk path file lokal (misal: ?image=test.png)
12
+ const { image } = request.query;
13
+
14
+ if (!image) {
15
+ return reply.status(400).send({
16
+ status: "error",
17
+ message: "Query parameter 'image' (path file) diperlukan."
18
+ });
19
+ }
20
+
21
+ const WORKER_PREFIX = "https://proxy2.afjasaku.workers.dev/?u=";
22
+ const HF_DOMAIN = "https://merterbak-deepseek-ocr-demo.hf.space";
23
+ const API_BASE = `${WORKER_PREFIX}${encodeURIComponent(HF_DOMAIN + "/gradio_api")}`;
24
+ const session_hash = Math.random().toString(36).substring(2);
25
+ const filePath = path.resolve(image);
26
+
27
+ try {
28
+ if (!fs.existsSync(filePath)) throw new Error(`File tidak ditemukan di path: ${filePath}`);
29
+
30
+ const stats = fs.statSync(filePath);
31
+ const fileName = path.basename(filePath);
32
+
33
+ // 1. Upload Gambar
34
+ const form = new FormData();
35
+ form.append('files', fs.createReadStream(filePath));
36
+
37
+ const uploadRes = await fetch(`${API_BASE}/upload?upload_id=${session_hash}`, {
38
+ method: "POST",
39
+ body: form,
40
+ headers: form.getHeaders()
41
+ });
42
+
43
+ const uploadData = await uploadRes.json();
44
+ const remotePath = uploadData[0];
45
+
46
+ // 2. Join Antrean DeepSeek
47
+ const payload = {
48
+ "data": [
49
+ null,
50
+ {
51
+ "path": remotePath,
52
+ "url": `${HF_DOMAIN}/gradio_api/file=${remotePath}`,
53
+ "orig_name": fileName,
54
+ "size": stats.size,
55
+ "mime_type": "image/png",
56
+ "meta": { "_type": "gradio.FileData" }
57
+ },
58
+ "📋 Markdown",
59
+ null,
60
+ 1
61
+ ],
62
+ "fn_index": 6,
63
+ "trigger_id": 9,
64
+ "session_hash": session_hash
65
+ };
66
+
67
+ await fetch(`${API_BASE}/queue/join`, {
68
+ method: "POST",
69
+ headers: { "Content-Type": "application/json" },
70
+ body: JSON.stringify(payload)
71
+ });
72
+
73
+ // 3. Mendengarkan Hasil via Stream
74
+ const streamUrl = `${API_BASE}/queue/data?session_hash=${session_hash}`;
75
+ const response = await fetch(streamUrl, {
76
+ headers: { "Accept": "text/event-stream" }
77
+ });
78
+
79
+ return new Promise((resolve, reject) => {
80
+ response.body.on('data', (chunk) => {
81
+ const dataStr = chunk.toString();
82
+ const lines = dataStr.split("\n");
83
+
84
+ for (let line of lines) {
85
+ if (!line.trim().startsWith("data: ")) continue;
86
+
87
+ try {
88
+ const json = JSON.parse(line.replace("data: ", ""));
89
+
90
+ if (json.msg === "process_completed") {
91
+ if (json.success) {
92
+ resolve({
93
+ status: "success",
94
+ plugin: "deepseek_ocr",
95
+ file: fileName,
96
+ result: json.output.data[0]
97
+ });
98
+ } else {
99
+ throw new Error(json.output.error || "Gagal memproses OCR");
100
+ }
101
+ }
102
+ } catch (e) {
103
+ // Abaikan jika chunk terpotong
104
+ }
105
+ }
106
+ });
107
+
108
+ // Timeout 60 detik
109
+ setTimeout(() => reject(new Error("OCR Processing Timeout")), 60000);
110
+ });
111
+
112
+ } catch (err) {
113
+ return reply.status(500).send({
114
+ status: "error",
115
+ message: err.message
116
+ });
117
+ }
118
+ }
119
+ };
plugins/huggingface1.js ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const puppeteer = require('puppeteer');
2
+ const fetch = require('node-fetch');
3
+
4
+ /**
5
+ * Logika utama Scraper & Generator
6
+ */
7
+ async function generateHeartsync(prompt) {
8
+ const browser = await puppeteer.launch({
9
+ headless: true,
10
+ executablePath: '/usr/bin/google-chrome-stable', // Path default di linux
11
+ args: [
12
+ '--no-sandbox',
13
+ '--disable-setuid-sandbox',
14
+ '--disable-dev-shm-usage',
15
+ '--disable-accelerated-2d-canvas',
16
+ '--no-first-run',
17
+ '--no-zygote',
18
+ '--single-process', // Penting untuk menghemat RAM di Space gratisan
19
+ '--disable-gpu'
20
+ ]
21
+ });
22
+ const page = await browser.newPage();
23
+
24
+ return new Promise(async (resolve, reject) => {
25
+ try {
26
+ // 1. Bypass CroxyProxy
27
+ await page.goto('https://www.croxyproxy.com/', { waitUntil: 'networkidle2' });
28
+ const targetUrl = 'https://heartsync-nsfw-uncensored-photo.hf.space/';
29
+ await page.waitForSelector('#url');
30
+ await page.type('#url', targetUrl);
31
+
32
+ await Promise.all([
33
+ page.click('#requestSubmit'),
34
+ page.waitForNavigation({ waitUntil: 'networkidle0' }),
35
+ ]);
36
+
37
+ await new Promise(r => setTimeout(r, 5000));
38
+
39
+ // 2. Ekstraksi Sesi
40
+ const currentUrl = page.url();
41
+ const urlObj = new URL(currentUrl);
42
+ const proxyBase = `${urlObj.protocol}//${urlObj.host}`;
43
+ const cpoToken = urlObj.searchParams.get('__cpo');
44
+
45
+ if (!cpoToken) throw new Error("Gagal mengambil token __cpo!");
46
+
47
+ const cookies = await page.cookies();
48
+ const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
49
+ const userAgent = await page.evaluate(() => navigator.userAgent);
50
+ const session_hash = Math.random().toString(36).substring(2);
51
+
52
+ const headers = {
53
+ "Content-Type": "application/json",
54
+ "Cookie": cookieString,
55
+ "User-Agent": userAgent,
56
+ "Referer": currentUrl,
57
+ "Accept": "*/*"
58
+ };
59
+
60
+ // 3. Join Antrean (fn_index: 2 sesuai file test1.js)
61
+ const joinRes = await fetch(`${proxyBase}/gradio_api/queue/join?__cpo=${cpoToken}`, {
62
+ method: "POST",
63
+ headers,
64
+ body: JSON.stringify({
65
+ data: [prompt, 1024, 1024, 18, 0, true, 4],
66
+ fn_index: 2,
67
+ trigger_id: 19,
68
+ session_hash: session_hash
69
+ })
70
+ });
71
+
72
+ const joinData = await joinRes.json();
73
+ if (!joinData.event_id) throw new Error("Gagal join antrean!");
74
+
75
+ // 4. Listen Stream Data
76
+ const streamRes = await fetch(`${proxyBase}/gradio_api/queue/data?session_hash=${session_hash}&__cpo=${cpoToken}`, { headers });
77
+
78
+ streamRes.body.on('data', (chunk) => {
79
+ const lines = chunk.toString().split("\n\n");
80
+ for (const line of lines) {
81
+ if (!line.startsWith("data: ")) continue;
82
+
83
+ try {
84
+ const json = JSON.parse(line.replace("data: ", ""));
85
+
86
+ if (json.msg === "process_completed") {
87
+ if (json.success) {
88
+ // Mapping URL hasil generate
89
+ const urls = json.output.data[0].map(img => img.image?.url || img.url);
90
+ browser.close();
91
+ resolve(urls);
92
+ } else {
93
+ throw new Error(json.output.error || "Gagal proses di server Gradio.");
94
+ }
95
+ }
96
+ } catch (e) {
97
+ // Parsing error biasanya karena chunk data terpotong, biarkan sampai chunk berikutnya
98
+ }
99
+ }
100
+ });
101
+
102
+ } catch (err) {
103
+ if (browser) await browser.close();
104
+ reject(err);
105
+ }
106
+ });
107
+ }
108
+
109
+ // Export untuk sistem Plug-and-Play Fastify
110
+ module.exports = {
111
+ path: '/huggingface1',
112
+ method: 'GET',
113
+ handler: async (request, reply) => {
114
+ const { prompt } = request.query;
115
+
116
+ if (!prompt) {
117
+ return reply.status(400).send({ status: "error", message: "Query prompt harus diisi!" });
118
+ }
119
+
120
+ try {
121
+ const images = await generateHeartsync(prompt);
122
+ return {
123
+ status: "success",
124
+ plugin: "heartsync_v2",
125
+ prompt: prompt,
126
+ results: images
127
+ };
128
+ } catch (err) {
129
+ return reply.status(500).send({
130
+ status: "error",
131
+ message: err.message
132
+ });
133
+ }
134
+ }
135
+ };
plugins/huggingface2.js ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const puppeteer = require('puppeteer');
2
+ const fetch = require('node-fetch');
3
+
4
+ // Logika utama tetap sama, dibungkus dalam fungsi
5
+ async function generateImage(prompt, negativePrompt = "low quality") {
6
+ const browser = await puppeteer.launch({
7
+ headless: true,
8
+ executablePath: '/usr/bin/google-chrome-stable', // Path default di linux
9
+ args: [
10
+ '--no-sandbox',
11
+ '--disable-setuid-sandbox',
12
+ '--disable-dev-shm-usage',
13
+ '--disable-accelerated-2d-canvas',
14
+ '--no-first-run',
15
+ '--no-zygote',
16
+ '--single-process', // Penting untuk menghemat RAM di Space gratisan
17
+ '--disable-gpu'
18
+ ]
19
+ });
20
+
21
+ const page = await browser.newPage();
22
+
23
+ return new Promise(async (resolve, reject) => {
24
+ try {
25
+ await page.goto('https://www.croxyproxy.com/', { waitUntil: 'networkidle2' });
26
+ await page.type('#url', 'https://nech-c-wainsfwillustrious-v140.hf.space/');
27
+
28
+ await Promise.all([
29
+ page.click('#requestSubmit'),
30
+ page.waitForNavigation({ waitUntil: 'networkidle0' }),
31
+ ]);
32
+
33
+ await new Promise(r => setTimeout(r, 5000));
34
+
35
+ const currentUrl = page.url();
36
+ const urlObj = new URL(currentUrl);
37
+ const proxyBase = `${urlObj.protocol}//${urlObj.host}`;
38
+ const cpoToken = urlObj.searchParams.get('__cpo');
39
+ const cookies = await page.cookies();
40
+ const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
41
+
42
+ const session_hash = Math.random().toString(36).substring(2);
43
+ const headers = {
44
+ "accept": "*/*",
45
+ "content-type": "application/json",
46
+ "cookie": cookieString,
47
+ "user-agent": await page.evaluate(() => navigator.userAgent),
48
+ "referer": currentUrl
49
+ };
50
+
51
+ const joinRes = await fetch(`${proxyBase}/gradio_api/queue/join?__cpo=${cpoToken}`, {
52
+ method: "POST",
53
+ headers,
54
+ body: JSON.stringify({
55
+ "data": ["v160", prompt, "masterpiece, best quality, " + prompt, negativePrompt, Math.floor(Math.random() * 2000000000), true, 1024, 1024, 6, 30, 1, null, true, null],
56
+ "fn_index": 12,
57
+ "session_hash": session_hash
58
+ })
59
+ });
60
+
61
+ const joinData = await joinRes.json();
62
+ if (!joinData.event_id) throw new Error("Gagal Queue");
63
+
64
+ const response = await fetch(`${proxyBase}/gradio_api/queue/data?session_hash=${session_hash}&__cpo=${cpoToken}`, { headers });
65
+
66
+ response.body.on('data', (chunk) => {
67
+ const dataStr = chunk.toString();
68
+ if (dataStr.includes("process_completed")) {
69
+ const json = JSON.parse(dataStr.split("data: ")[1].trim());
70
+ const gallery = json.output.data.find(item => Array.isArray(item));
71
+ const results = gallery?.map(item => {
72
+ const pathOnly = (item.image?.url || item.url).split('gradio_api')[1].split('&')[0];
73
+ return `https://nech-c-wainsfwillustrious-v140.hf.space/gradio_api${pathOnly}`;
74
+ }) || [];
75
+
76
+ browser.close();
77
+ resolve(results);
78
+ }
79
+ });
80
+ } catch (err) {
81
+ browser.close();
82
+ reject(err);
83
+ }
84
+ });
85
+ }
86
+
87
+ // Export dengan nama route dan metodenya
88
+ module.exports = {
89
+ path: '/huggingface2',
90
+ method: 'GET',
91
+ handler: async (request, reply) => {
92
+ const { prompt } = request.query;
93
+ if (!prompt) return { error: "Isi prompt di query?prompt=..." };
94
+ const images = await generateImage(prompt);
95
+ return { status: "success", images };
96
+ }
97
+ };
plugins/index.ejs ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>My API Dashboard</title>
7
+ <style>
8
+ body { font-family: sans-serif; background: #121212; color: #eee; padding: 40px; }
9
+ .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }
10
+ .card { background: #1e1e1e; padding: 20px; border-radius: 12px; border: 1px solid #333; }
11
+ .method { font-weight: bold; color: #00ff88; margin-right: 8px; }
12
+ .path { color: #00bfff; font-family: monospace; }
13
+ a { text-decoration: none; color: inherit; }
14
+ .card:hover { border-color: #00bfff; }
15
+ h1 { margin-bottom: 30px; }
16
+ </style>
17
+ </head>
18
+ <body>
19
+ <h1>API Plugins Dashboard</h1>
20
+ <div class="grid">
21
+ <% plugins.forEach(plugin => { %>
22
+ <a href="<%= plugin.path %>" target="_blank">
23
+ <div class="card">
24
+ <h3><%= plugin.name.toUpperCase() %></h3>
25
+ <p><span class="method"><%= plugin.method %></span> <span class="path"><%= plugin.path %></span></p>
26
+ <small><%= plugin.description %></small>
27
+ </div>
28
+ </a>
29
+ <% }) %>
30
+ </div>
31
+ </body>
32
+ </html>
plugins/wai.js ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const puppeteer = require('puppeteer');
2
+ const fetch = require('node-fetch');
3
+
4
+ module.exports = {
5
+ path: '/wai',
6
+ method: 'GET',
7
+ description: 'Generate gambar menggunakan model Illustrious-v140 via CroxyProxy bypass.',
8
+ handler: async (request, reply) => {
9
+ const { prompt } = request.query;
10
+ if (!prompt) return { error: "Prompt kosong!" };
11
+
12
+ const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
13
+ const page = await browser.newPage();
14
+
15
+ return new Promise(async (resolve) => {
16
+ try {
17
+ await page.goto('https://www.croxyproxy.com/', { waitUntil: 'networkidle2' });
18
+ await page.type('#url', 'https://nech-c-wainsfwillustrious-v140.hf.space/');
19
+ await Promise.all([page.click('#requestSubmit'), page.waitForNavigation({ waitUntil: 'networkidle0' })]);
20
+ await new Promise(r => setTimeout(r, 5000));
21
+
22
+ const currentUrl = page.url();
23
+ const urlObj = new URL(currentUrl);
24
+ const proxyBase = `${urlObj.protocol}//${urlObj.host}`;
25
+ const cpoToken = urlObj.searchParams.get('__cpo');
26
+ const cookies = await page.cookies();
27
+ const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
28
+ const session_hash = Math.random().toString(36).substring(2);
29
+
30
+ const headers = { "content-type": "application/json", "cookie": cookieString, "referer": currentUrl };
31
+
32
+ const joinRes = await fetch(`${proxyBase}/gradio_api/queue/join?__cpo=${cpoToken}`, {
33
+ method: "POST",
34
+ headers,
35
+ body: JSON.stringify({
36
+ "data": ["v160", prompt, "masterpiece, best quality", "low quality", Math.floor(Math.random() * 2000000000), true, 1024, 1024, 6, 30, 1, null, true, null],
37
+ "fn_index": 12,
38
+ "session_hash": session_hash
39
+ })
40
+ });
41
+
42
+ const streamRes = await fetch(`${proxyBase}/gradio_api/queue/data?session_hash=${session_hash}&__cpo=${cpoToken}`, { headers });
43
+
44
+ streamRes.body.on('data', (chunk) => {
45
+ const dataStr = chunk.toString();
46
+ // Pisahkan berdasarkan baris karena satu chunk bisa berisi beberapa event data
47
+ const lines = dataStr.split("\n");
48
+
49
+ for (let line of lines) {
50
+ if (!line.startsWith("data: ")) continue;
51
+
52
+ try {
53
+ // Membersihkan string "data: " untuk mendapatkan JSON murni
54
+ const rawJson = line.replace("data: ", "").trim();
55
+ if (!rawJson || rawJson === "[DONE]") continue;
56
+
57
+ const json = JSON.parse(rawJson);
58
+
59
+ // Pastikan pesan adalah process_completed dan data yang dicari ada
60
+ if (json.msg === "process_completed" && json.output && json.output.data) {
61
+ const gallery = json.output.data.find(item => Array.isArray(item));
62
+
63
+ if (gallery) {
64
+ const results = gallery.map(img => {
65
+ const rawUrl = img.image?.url || img.url;
66
+ const pathOnly = rawUrl.split('gradio_api')[1].split('&')[0];
67
+ return `https://nech-c-wainsfwillustrious-v140.hf.space/gradio_api${pathOnly}`;
68
+ });
69
+
70
+ browser.close();
71
+ resolve({ status: "success", images: results });
72
+ }
73
+ }
74
+ } catch (e) {
75
+ // Abaikan error parsing jika chunk terpotong di tengah jalan
76
+ continue;
77
+ }
78
+ }
79
+ });
80
+ } catch (e) {
81
+ browser.close();
82
+ resolve({ error: e.message });
83
+ }
84
+ });
85
+ }
86
+ };