const express = require('express'); const { Client } = require('@gradio/client'); const path = require('path'); const crypto = require('crypto'); // Ditambahkan untuk generate UUID const app = express(); const PORT = process.env.PORT || 7860; app.use(express.json()); app.use(express.static(path.join(__dirname, 'public'))); // Endpoint baru untuk memproses app.py menggunakan NoteGPT app.post('/api/analyze-code', async (req, res) => { try { const { prompt } = req.body; if (!prompt) return res.status(400).json({ error: "Prompt kosong" }); // Generate UUID v4 acak untuk conversation_id const conversationId = crypto.randomUUID(); // Lakukan fetch ke API NoteGPT const response = await fetch("https://notegpt.io/api/v2/chat/stream", { method: "POST", headers: { "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }, body: JSON.stringify({ message: prompt, language: "auto", model: "deepseek-v4-flash", tone: "default", length: "moderate", conversation_id: conversationId, image_urls: [], chat_mode: "standard", enable_web_search: false }) }); if (!response.ok) throw new Error(`NoteGPT Error: ${response.statusText}`); // Satukan potongan stream (SSE) menjadi satu teks utuh const reader = response.body.getReader(); const decoder = new TextDecoder(); let fullText = ""; let buffer = ""; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split("\n"); // Simpan sisa baris yang belum lengkap ke buffer buffer = lines.pop() || ""; for (const line of lines) { if (line.startsWith("data: ")) { const jsonStr = line.slice(6).trim(); if (!jsonStr) continue; try { const parsed = JSON.parse(jsonStr); if (parsed.text) { fullText += parsed.text; } } catch (e) { // Abaikan jika baris data bukan JSON valid (misal: "data: [DONE]") } } } } res.json({ success: true, result: fullText }); } catch (error) { console.error("NoteGPT Integration Error:", error); res.status(500).json({ success: false, error: error.message }); } }); // Endpoint untuk menjalankan fungsi Gradio Space (Versi Perbaikan) app.post('/api/run-gradio', async (req, res) => { try { const { spaceUrl, inputs } = req.body; if (!spaceUrl || !inputs) { return res.status(400).json({ error: "Missing spaceUrl or inputs data" }); } const client = await Client.connect(spaceUrl); const response = await client.predict(0, inputs); // Kirimkan seluruh array 'data' agar frontend bisa memfilter objek gambar yang valid res.json({ success: true, data: response.data }); } catch (error) { console.error("Gradio Integration Error:", error); res.status(500).json({ success: false, error: error.message }); } }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });