const fs = require('fs'); const https = require('https'); const FormData = require('form-data'); const SESSION_IDS = [ "neko-" + Date.now(), "session-" + Math.random().toString(36).substring(2, 15), "bot-" + Math.random().toString(36).substring(2, 10) ]; function getRandomSessionId() { const sessionId = SESSION_IDS[Math.floor(Math.random() * SESSION_IDS.length)]; console.log(`🎲 DEBUG getRandomSessionId: Selected session ID: ${sessionId}`); return sessionId; } async function uploadImageToHosting(imageBuffer) { console.log('📤 DEBUG uploadImageToHosting: Starting image upload'); return new Promise((resolve, reject) => { try { const formData = new FormData(); const filename = `upload-${Date.now()}.jpg`; formData.append("file", imageBuffer, { filename: filename, contentType: "image/jpeg" }); console.log(`📁 DEBUG: Uploading file: ${filename}, Size: ${imageBuffer.length} bytes`); const options = { hostname: 'fourmovie-uploader.hf.space', path: '/api/upload', method: 'POST', headers: formData.getHeaders() }; const req = https.request(options, (res) => { let data = ''; console.log(`📡 DEBUG: Upload response status: ${res.statusCode}`); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { try { console.log('📄 DEBUG: Upload response received'); const response = JSON.parse(data); console.log('🔗 DEBUG: Upload response data:', response); if (response.file?.url) { console.log(`✅ DEBUG: Image uploaded successfully, URL: ${response.file.url}`); resolve(response.file.url); } else { console.log('❌ DEBUG: No URL in upload response'); resolve(null); } } catch (error) { console.error('❌ DEBUG: Error parsing upload response:', error); resolve(null); } }); }); req.on('error', (error) => { console.error('❌ DEBUG: Upload request error:', error); resolve(null); }); formData.pipe(req); console.log('🔄 DEBUG: Form data piped to request'); } catch (error) { console.error('❌ DEBUG: Upload failed:', error); resolve(null); } }); } async function extractTextFromImage(imagePath) { console.log(`🖼️ DEBUG extractTextFromImage: Processing image: ${imagePath}`); return new Promise(async (resolve, reject) => { try { console.log('📖 DEBUG: Reading image file...'); const imageBuffer = fs.readFileSync(imagePath); console.log(`✅ DEBUG: Image read successfully, size: ${imageBuffer.length} bytes`); console.log('☁️ DEBUG: Uploading image to hosting...'); const imageUrl = await uploadImageToHosting(imageBuffer); if (!imageUrl) { console.log('❌ DEBUG: Image upload failed'); return resolve({ status: false, response: 'Gagal mengunggah gambar ke hosting' }); } console.log(`🔗 DEBUG: Image uploaded, URL: ${imageUrl}`); const sessionId = getRandomSessionId(); const textParam = encodeURIComponent("hi how are you"); const systemPrompt = encodeURIComponent("Berikan text yang ada di gambar ini saja, tidak ada informasi lain cukup yang ada di gambar saja, jangan ada text lain kalo bukan dari gambar nya. dan ini adalah pembatas iya _ , : ; dan tolong tiap text berbeda beda kalo ada pembatas itu kirim satu kalimat saja, dan jangan pernah kirim informasi selain dari gambar."); const imageUrlParam = encodeURIComponent(imageUrl); const apiUrl = `https://api.nekolabs.web.id/ai/gemini/2.5-flash/v2?text=${textParam}&systemPrompt=${systemPrompt}&imageUrl=${imageUrlParam}&sessionId=${sessionId}`; console.log(`🌐 DEBUG: API URL constructed (short): https://api.nekolabs.web.id/ai/gemini/2.5-flash/v2?...`); const options = { hostname: 'api.nekolabs.web.id', path: `/ai/gemini/2.0-flash/v2?text=${textParam}&systemPrompt=${systemPrompt}&imageUrl=${imageUrlParam}&sessionId=${sessionId}`, method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }; console.log('🚀 DEBUG: Sending request to nekolabs API...'); const req = https.request(options, (res) => { let data = ''; console.log(`📡 DEBUG: API response status: ${res.statusCode}`); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { try { console.log('📄 DEBUG: API response received'); const response = JSON.parse(data); console.log('🔍 DEBUG: Full API response:', response); if (response.success && response.result) { console.log(`✅ DEBUG: Text extraction successful: "${response.result}"`); resolve({ status: true, response: response.result }); } else { console.log('❌ DEBUG: API returned error:', response); resolve({ status: false, response: response.result || 'Gagal mengekstrak teks' }); } } catch (error) { console.error('❌ DEBUG: Error parsing API response:', error); reject(error); } }); }); req.on('error', (error) => { console.error('❌ DEBUG: API request error:', error); reject(error); }); req.end(); console.log('📤 DEBUG: Request sent to API'); } catch (error) { console.error('❌ DEBUG: extractTextFromImage error:', error); reject(error); } }); } module.exports = { extractTextFromImage, getRandomSessionId, uploadImageToHosting };