-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexpress.js
237 lines (190 loc) · 7.04 KB
/
express.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
const express = require('express');
const axios = require('axios');
const sqlite3 = require('sqlite3').verbose();
const dotenv = require('dotenv');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({storage: storage, limits: { fieldSize : 3145728 }})
dotenv.config();
const app = express();
// Enable CORS for all routes
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
const DALLE_API_KEY = process.env.DALLE_API_KEY;
if (!DALLE_API_KEY) {
console.error('DALL-E API key is not set in .env file');
process.exit(1);
}
const dbPath = path.join(__dirname, 'public', 'generated', 'api_usage.db');
// Buat objek database SQLite
const db = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error(err.message);
process.exit(1);
}
console.log('Connected to the SQLite database.');
db.run(`CREATE TABLE IF NOT EXISTS api_usage (date TEXT PRIMARY KEY, count INTEGER)`);
});
const dateLimits = {
'2023-12-24': 3000,
'2023-12-25': 3000,
'2023-12-26': 200,
'2023-12-27': 200,
'2023-12-28': 200,
'2023-12-29': 200,
};
function canMakeApiCall() {
return new Promise((resolve, reject) => {
const now = new Date();
const today = now.toISOString().split('T')[0];
// Check if today's date is in the dateLimits
if (!dateLimits.hasOwnProperty(today)) {
resolve(true); // Allow API calls if the date is not listed
return;
}
db.get('SELECT count FROM api_usage WHERE date = ?', [today], (err, row) => {
if (err) {
reject(err);
return;
}
const currentCount = row ? row.count : 0;
if (currentCount >= dateLimits[today]) {
resolve(false);
} else {
const newCount = currentCount + 1;
db.run('INSERT OR REPLACE INTO api_usage (date, count) VALUES (?, ?)', [today, newCount], (err) => {
if (err) {
reject(err);
return;
}
resolve(true);
});
}
});
});
}
app.post('/generate-image', async (req, res) => {
try {
const canCallApi = await canMakeApiCall();
if (!canCallApi) {
res.status(429).json({ message: 'API call limit reached for today. Please try again tomorrow.' });
return;
}
const { description, customText } = req.body;
const customTextUpper = customText.toUpperCase();
const prompt = `I NEED to test how the tool works with extremely simple prompts. DO NOT add any detail, just use it AS-IS.
DO NOT generate cropped images. ALL ELEMENTS must be centrally composed to PREVENT CROPPING and all the text is inside the picture :
Illustrated Disney Pixar, Christmas SQUARE POSTCARD with ${description}. Merry Christmas text must be in picture handwritten font,
'${customTextUpper}' TEXT MUST BE IN PICTURE`;
const response = await axios.post('https://api.openai.com/v1/images/generations', {
model : 'dall-e-3',
prompt : prompt,
n : 1,
size : '1024x1024',
}, {
headers: { Authorization: `Bearer ${DALLE_API_KEY}` },
});
if (response.status != 200 ||
!response.data ||
!response.data.data[0]
) {
res.status(500).send('Error generating image')
return
}
const imageUrl = response.data.data[0].url
const imageResponse = await axios.get(imageUrl, { responseType: 'arraybuffer' });
if (imageResponse.status != 200 ||
!imageResponse.data
) {
res.status(500).send('Generated image is not valid')
return
}
res.setHeader('Content-Type', 'image/png')
res.send(imageResponse.data)
} catch (error) {
if (error.response?.data?.error) {
//saveErrorLog(JSON.stringify(error.response.data.error))
} else {
//saveErrorLog(JSON.stringify(error))
}
console.error(error);
res.status(500).send('Error calling DALL-E API');
}
});
app.post('/persist-generated-image', upload.single('image'), async (req, res) => {
const image = req.file;
if (!image) {
return res.status(400).send('Image is required');
}
try {
// To Do: set filename to make sure no image replaces each other
const randNum = String(Math.ceil(Math.random() * 9999)).padStart(4, '0')
const dir = 'public/generated'
const path = `${randNum}-${Date.now()}.png`
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
}
fs.writeFile(`${dir}/${path}`, image.buffer, error => {
if (error) {
throw new Error('Failed to persist the generated image')
}
const publicDir = dir.replace('public/', '')
res.json({
imageUrl: `${publicDir}/${path}`,
})
})
} catch (error) {
console.error(error)
//saveErrorLog(JSON.stringify(error))
res.status(500).send('Error saving generated image');
}
})
// app.get('/serve-image', async (req, res) => {
// const imageUrl = req.query.url;
// if (!imageUrl) {
// return res.status(400).send('Image URL is required');
// }
// try {
// const response = await axios({
// method: 'GET',
// url: imageUrl,
// responseType: 'stream'
// });
// const imagePath = path.join(__dirname, 'img', 'downloadedImage.jpg'); // Change 'downloadedImage.jpg' to the desired file name
// const writer = fs.createWriteStream(imagePath);
// response.data.pipe(writer);
// writer.on('finish', () => {
// res.send({ message: 'Image downloaded successfully', path: imagePath });
// });
// writer.on('error', (err) => {
// console.error('Error writing image to disk', err);
// res.status(500).send('Error saving image');
// });
// } catch (error) {
// console.error(error);
// res.status(500).send('Error fetching image');
// }
// });
function saveImageToServer(imageUrl) {
fetch(`/save-image?url=${encodeURIComponent(imageUrl)}`)
.then(response => response.json())
.then(data => {
if (data.message === 'Image saved successfully') {
console.log('Image saved to server:', data.path);
// Tindakan selanjutnya setelah gambar berhasil disimpan
} else {
console.error('Server failed to save the image.');
}
})
.catch(error => {
console.error('Error saving image to server:', error);
});
}
const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});