sam12345324 commited on
Commit
9fb7b1b
·
verified ·
1 Parent(s): 8745eb1

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +78 -31
server.js CHANGED
@@ -1,47 +1,94 @@
1
  import express from 'express';
2
  import multer from 'multer';
3
- import fs from 'fs';
4
  import path from 'path';
5
 
6
  const app = express();
7
  const PORT = process.env.PORT || 7860;
8
 
9
- // Multer storage in memory (keeps files in RAM)
10
- const storage = multer.memoryStorage();
11
- const upload = multer({ storage });
12
 
13
- // Accept ANY files, any field name
14
- app.post('/upload', upload.any(), async (req, res) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  try {
16
- if (!req.files || req.files.length === 0) {
17
- return res.status(400).json({ error: 'No files uploaded' });
18
- }
19
-
20
- // Save uploaded files locally for processing
21
- const savedFiles = [];
22
- for (const file of req.files) {
23
- const filePath = path.join('/tmp', file.originalname);
24
- fs.writeFileSync(filePath, file.buffer);
25
- savedFiles.push(filePath);
26
- }
27
-
28
- // Here is where you process files (e.g., image conversion)
29
- console.log('Files received:', savedFiles);
30
-
31
- res.json({
32
- message: 'Files uploaded successfully!',
33
- files: savedFiles
34
- });
35
- } catch (err) {
36
- console.error(err);
37
- res.status(500).json({ error: 'File processing failed' });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  });
40
 
41
  app.get('/', (req, res) => {
42
- res.send('Server is running and ready for uploads!');
43
  });
44
 
45
  app.listen(PORT, () => {
46
- console.log(`Server running on port ${PORT}`);
47
- });
 
1
  import express from 'express';
2
  import multer from 'multer';
3
+ import sharp from 'sharp';
4
  import path from 'path';
5
 
6
  const app = express();
7
  const PORT = process.env.PORT || 7860;
8
 
9
+ // Multer with memory storage (no disk needed)
10
+ const upload = multer({ storage: multer.memoryStorage() });
 
11
 
12
+ app.post('/convert', upload.any(), async (req, res) => {
13
+ console.log('Received POST /convert request'); // Log for debugging in HF logs
14
+ try {
15
+ const files = req.files || [];
16
+ if (files.length === 0) {
17
+ console.log('No files received');
18
+ return res.status(400).json({ error: 'No files uploaded' });
19
+ }
20
+ if (files.length > 10) {
21
+ return res.status(400).json({ error: 'Max 10 files per request' });
22
+ }
23
+
24
+ // Parse optional bg hex (for transparent images)
25
+ const bgHex = req.body.bg || '#FFFFFF';
26
+ let bgColor = [255, 255, 255]; // Default white
27
  try {
28
+ const hex = bgHex.replace('#', '');
29
+ bgColor = [parseInt(hex.substr(0, 2), 16), parseInt(hex.substr(2, 2), 16), parseInt(hex.substr(4, 2), 16)];
30
+ } catch {}
31
+
32
+ const results = [];
33
+ const errors = [];
34
+
35
+ // Process each file concurrently
36
+ await Promise.all(files.map(async (file) => {
37
+ try {
38
+ console.log(`Processing file: ${file.originalname}`); // Debug log
39
+ let img = sharp(file.buffer);
40
+
41
+ // Flatten transparency onto background
42
+ img = img.flatten({ background: { r: bgColor[0], g: bgColor[1], b: bgColor[2] } });
43
+
44
+ // Convert to JPEG with high quality
45
+ const jpegBuffer = await img
46
+ .jpeg({
47
+ quality: 95,
48
+ mozjpeg: true, // Better compression with minimal loss
49
+ chromaSubsampling: '4:4:4', // Preserve color detail
50
+ progressive: true,
51
+ force: true,
52
+ })
53
+ .toBuffer();
54
+
55
+ // Base64 for response
56
+ const base64 = jpegBuffer.toString('base64');
57
+ const outputName = path.basename(file.originalname, path.extname(file.originalname)) + '.jpg';
58
+
59
+ results.push({ filename: outputName, data: base64 });
60
+ } catch (err) {
61
+ console.error(`Error processing ${file.originalname}: ${err.message}`);
62
+ errors.push({ filename: file.originalname, error: err.message });
63
+ }
64
+ }));
65
+
66
+ if (results.length === 0 && errors.length > 0) {
67
+ return res.status(500).json({ error: 'All conversions failed', details: errors });
68
  }
69
+
70
+ console.log(`Conversion complete: ${results.length} successes, ${errors.length} errors`); // Debug log
71
+
72
+ // If single file, simplify response
73
+ if (results.length === 1 && errors.length === 0) {
74
+ return res.json({ message: 'Conversion successful', file: results[0] });
75
+ }
76
+
77
+ res.json({
78
+ message: 'Conversions successful',
79
+ files: results,
80
+ errors: errors.length > 0 ? errors : undefined,
81
+ });
82
+ } catch (err) {
83
+ console.error(`Server error: ${err.message}`);
84
+ res.status(500).json({ error: 'Server error' });
85
+ }
86
  });
87
 
88
  app.get('/', (req, res) => {
89
+ res.send('Server ready for image conversions!');
90
  });
91
 
92
  app.listen(PORT, () => {
93
+ console.log(`Server running on port ${PORT}`);
94
+ });