Forgets commited on
Commit
055607b
Β·
verified Β·
1 Parent(s): 4f0a8b0

Update endpoints/imageProcessor

Browse files
Files changed (1) hide show
  1. endpoints/imageProcessor +84 -144
endpoints/imageProcessor CHANGED
@@ -1,165 +1,105 @@
1
  const fs = require('fs');
2
  const https = require('https');
3
- const FormData = require('form-data');
4
 
5
- const SESSION_IDS = [
6
- "neko-" + Date.now(),
7
- "session-" + Math.random().toString(36).substring(2, 15),
8
- "bot-" + Math.random().toString(36).substring(2, 10)
9
- ];
10
-
11
- function getRandomSessionId() {
12
- const sessionId = SESSION_IDS[Math.floor(Math.random() * SESSION_IDS.length)];
13
- console.log(`🎲 DEBUG getRandomSessionId: Selected session ID: ${sessionId}`);
14
- return sessionId;
15
- }
16
-
17
- async function uploadImageToHosting(imageBuffer) {
18
- console.log('πŸ“€ DEBUG uploadImageToHosting: Starting image upload');
19
  return new Promise((resolve, reject) => {
20
- try {
21
- const formData = new FormData();
22
- const filename = `upload-${Date.now()}.jpg`;
23
- formData.append("file", imageBuffer, {
24
- filename: filename,
25
- contentType: "image/jpeg"
26
- });
27
-
28
- console.log(`πŸ“ DEBUG: Uploading file: ${filename}, Size: ${imageBuffer.length} bytes`);
29
-
30
- const options = {
31
- hostname: 'fourmovie-uploader.hf.space',
32
- path: '/api/upload',
33
- method: 'POST',
34
- headers: formData.getHeaders()
35
- };
36
-
37
- const req = https.request(options, (res) => {
38
- let data = '';
39
-
40
- console.log(`πŸ“‘ DEBUG: Upload response status: ${res.statusCode}`);
41
-
42
- res.on('data', (chunk) => {
43
- data += chunk;
44
- });
45
-
46
- res.on('end', () => {
47
- try {
48
- console.log('πŸ“„ DEBUG: Upload response received');
49
- const response = JSON.parse(data);
50
- console.log('πŸ”— DEBUG: Upload response data:', response);
51
-
52
- if (response.file?.url) {
53
- console.log(`βœ… DEBUG: Image uploaded successfully, URL: ${response.file.url}`);
54
- resolve(response.file.url);
55
- } else {
56
- console.log('❌ DEBUG: No URL in upload response');
57
- resolve(null);
58
  }
59
- } catch (error) {
60
- console.error('❌ DEBUG: Error parsing upload response:', error);
61
- resolve(null);
62
- }
63
- });
64
- });
65
-
66
- req.on('error', (error) => {
67
- console.error('❌ DEBUG: Upload request error:', error);
68
- resolve(null);
69
- });
70
-
71
- formData.pipe(req);
72
- console.log('πŸ”„ DEBUG: Form data piped to request');
73
-
74
- } catch (error) {
75
- console.error('❌ DEBUG: Upload failed:', error);
76
- resolve(null);
77
- }
78
- });
79
- }
80
-
81
- async function extractTextFromImage(imagePath) {
82
- console.log(`πŸ–ΌοΈ DEBUG extractTextFromImage: Processing image: ${imagePath}`);
83
- return new Promise(async (resolve, reject) => {
84
- try {
85
- console.log('πŸ“– DEBUG: Reading image file...');
86
- const imageBuffer = fs.readFileSync(imagePath);
87
- console.log(`βœ… DEBUG: Image read successfully, size: ${imageBuffer.length} bytes`);
88
-
89
- console.log('☁️ DEBUG: Uploading image to hosting...');
90
- const imageUrl = await uploadImageToHosting(imageBuffer);
91
- if (!imageUrl) {
92
- console.log('❌ DEBUG: Image upload failed');
93
- return resolve({ status: false, response: 'Gagal mengunggah gambar ke hosting' });
94
  }
 
95
 
96
- console.log(`πŸ”— DEBUG: Image uploaded, URL: ${imageUrl}`);
97
- const sessionId = getRandomSessionId();
98
-
99
- const textParam = encodeURIComponent("hi how are you");
100
- 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.");
101
- const imageUrlParam = encodeURIComponent(imageUrl);
102
-
103
- const apiUrl = `https://api.nekolabs.web.id/ai/gemini/2.5-flash/v2?text=${textParam}&systemPrompt=${systemPrompt}&imageUrl=${imageUrlParam}&sessionId=${sessionId}`;
104
- console.log(`🌐 DEBUG: API URL constructed (short): https://api.nekolabs.web.id/ai/gemini/2.5-flash/v2?...`);
105
-
106
- const options = {
107
- hostname: 'api.nekolabs.web.id',
108
- path: `/ai/gemini/2.0-flash/v2?text=${textParam}&systemPrompt=${systemPrompt}&imageUrl=${imageUrlParam}&sessionId=${sessionId}`,
109
- method: 'GET',
110
- headers: {
111
- 'Accept': 'application/json',
112
- 'Content-Type': 'application/json'
113
- }
114
- };
115
 
116
- console.log('πŸš€ DEBUG: Sending request to nekolabs API...');
117
- const req = https.request(options, (res) => {
118
- let data = '';
119
 
120
- console.log(`πŸ“‘ DEBUG: API response status: ${res.statusCode}`);
121
 
122
- res.on('data', (chunk) => {
123
- data += chunk;
124
- });
125
 
126
- res.on('end', () => {
127
- try {
128
- console.log('πŸ“„ DEBUG: API response received');
129
- const response = JSON.parse(data);
130
- console.log('πŸ” DEBUG: Full API response:', response);
 
 
 
 
 
 
 
 
 
 
131
 
132
- if (response.success && response.result) {
133
- console.log(`βœ… DEBUG: Text extraction successful: "${response.result}"`);
134
- resolve({ status: true, response: response.result });
135
- } else {
136
- console.log('❌ DEBUG: API returned error:', response);
137
- resolve({ status: false, response: response.result || 'Gagal mengekstrak teks' });
138
  }
139
- } catch (error) {
140
- console.error('❌ DEBUG: Error parsing API response:', error);
141
- reject(error);
142
  }
143
- });
 
 
 
 
144
  });
 
145
 
146
- req.on('error', (error) => {
147
- console.error('❌ DEBUG: API request error:', error);
148
- reject(error);
149
- });
150
 
151
- req.end();
152
- console.log('πŸ“€ DEBUG: Request sent to API');
 
 
 
153
 
154
- } catch (error) {
155
- console.error('❌ DEBUG: extractTextFromImage error:', error);
156
- reject(error);
157
- }
 
 
158
  });
159
  }
160
 
161
- module.exports = {
162
- extractTextFromImage,
163
- getRandomSessionId,
164
- uploadImageToHosting
165
- };
 
1
  const fs = require('fs');
2
  const https = require('https');
 
3
 
4
+ async function extractTextFromImage(imageBuffer) {
5
+ console.log('[DEBUG] extractTextFromImage: Starting image text extraction');
6
+ console.log('[DEBUG] Image buffer size:', imageBuffer.length, 'bytes');
7
+
 
 
 
 
 
 
 
 
 
 
8
  return new Promise((resolve, reject) => {
9
+ const base64Image = imageBuffer.toString('base64');
10
+ console.log('[DEBUG] Base64 image length:', base64Image.length);
11
+
12
+ const requestData = JSON.stringify({
13
+ "contents": [
14
+ {
15
+ "parts": [
16
+ {
17
+ "inline_data": {
18
+ "mime_type": "image/png",
19
+ "data": base64Image
20
+ }
21
+ },
22
+ {
23
+ "text": "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."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
+ ]
26
+ }
27
+ ]
28
+ });
29
+
30
+ console.log('[DEBUG] Request data prepared, length:', requestData.length);
31
+
32
+ const options = {
33
+ hostname: 'generativelanguage.googleapis.com',
34
+ path: '/v1beta/models/gemini-2.5-flash-lite:generateContent',
35
+ method: 'POST',
36
+ headers: {
37
+ 'x-goog-api-key': 'AIzaSyB3-2egs0udKCDX_F7I58uVRAwv7OUX1G8',
38
+ 'Content-Type': 'application/json',
39
+ 'Content-Length': Buffer.byteLength(requestData)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
+ };
42
 
43
+ console.log('[DEBUG] Making request to Gemini API...');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ const req = https.request(options, (res) => {
46
+ console.log('[DEBUG] API Response status:', res.statusCode);
47
+ console.log('[DEBUG] API Response headers:', res.headers);
48
 
49
+ let data = '';
50
 
51
+ res.on('data', (chunk) => {
52
+ data += chunk;
53
+ });
54
 
55
+ res.on('end', () => {
56
+ console.log('[DEBUG] Received all response data');
57
+ console.log('[DEBUG] Response data length:', data.length);
58
+
59
+ try {
60
+ const response = JSON.parse(data);
61
+ console.log('[DEBUG] Response parsed successfully');
62
+
63
+ if (response.candidates && response.candidates[0] && response.candidates[0].content) {
64
+ const text = response.candidates[0].content.parts[0].text;
65
+ console.log('[DEBUG] βœ… Text extracted:', text);
66
+ resolve({ status: true, response: text });
67
+ } else {
68
+ console.log('[DEBUG] ❌ No text found in response');
69
+ console.log('[DEBUG] Response structure:', JSON.stringify(response, null, 2));
70
 
71
+ if (response.error) {
72
+ console.log('[DEBUG] API Error:', response.error);
 
 
 
 
73
  }
74
+
75
+ resolve({ status: false, response: 'Tidak ada teks yang ditemukan' });
 
76
  }
77
+ } catch (error) {
78
+ console.error('[DEBUG] ❌ JSON parse error:', error);
79
+ console.log('[DEBUG] Raw response data:', data);
80
+ reject(error);
81
+ }
82
  });
83
+ });
84
 
85
+ req.on('error', (error) => {
86
+ console.error('[DEBUG] ❌ Request error:', error);
87
+ reject(error);
88
+ });
89
 
90
+ req.on('timeout', () => {
91
+ console.error('[DEBUG] ❌ Request timeout');
92
+ req.destroy();
93
+ reject(new Error('Request timeout'));
94
+ });
95
 
96
+ req.setTimeout(30000); // 30 second timeout
97
+
98
+ console.log('[DEBUG] Sending request...');
99
+ req.write(requestData);
100
+ req.end();
101
+ console.log('[DEBUG] Request sent');
102
  });
103
  }
104
 
105
+ module.exports = { extractTextFromImage };