File size: 7,590 Bytes
6d8bed1
 
 
 
 
 
 
 
a95ab94
6d8bed1
 
 
9fe9c9b
a95ab94
 
 
18ea579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d8bed1
18ea579
 
 
 
 
6d8bed1
18ea579
 
 
 
 
6d8bed1
18ea579
 
 
 
 
6d8bed1
18ea579
 
 
 
 
 
 
 
 
 
a95ab94
 
 
 
 
 
18ea579
 
a95ab94
18ea579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fe9c9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18ea579
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import express from 'express';
import multer from 'multer';
import cors from 'cors';
import * as tf from '@tensorflow/tfjs';
import '@tensorflow/tfjs-backend-wasm';
import '@tensorflow/tfjs-backend-cpu';
import { createCanvas, loadImage } from 'canvas';
import { createRequire } from 'module';

// Pro importy CommonJS balíčků
const require = createRequire(import.meta.url);



// Import Upscaler using dynamic import
let Upscaler;

const app = express();
const PORT = process.env.PORT || 7860;

// Middleware
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));

// Serve static files from public directory
app.use(express.static('public'));

// Configure multer for file uploads
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB limit
  },
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('Only image files are allowed'), false);
    }
  }
});

// Global upscaler instance
let upscalerInstance = null;

// Get model for scale and type
async function getModelForScaleAndType(scale, modelType) {
  switch (modelType) {
    case 'esrgan-slim':
      const { x2: slimX2, x3: slimX3, x4: slimX4 } = await import('@upscalerjs/esrgan-slim');
      if (scale === 2) return slimX2;
      if (scale === 3) return slimX3;
      return slimX4;

    case 'esrgan-medium':
      const { x2: mediumX2, x3: mediumX3, x4: mediumX4 } = await import('@upscalerjs/esrgan-medium');
      if (scale === 2) return mediumX2;
      if (scale === 3) return mediumX3;
      return mediumX4;

    case 'esrgan-thick':
      const { x2: thickX2, x3: thickX3, x4: thickX4 } = await import('@upscalerjs/esrgan-thick');
      if (scale === 2) return thickX2;
      if (scale === 3) return thickX3;
      return thickX4;

    default:
      const { x2: defaultX2, x3: defaultX3, x4: defaultX4 } = await import('@upscalerjs/esrgan-slim');
      if (scale === 2) return defaultX2;
      if (scale === 3) return defaultX3;
      return defaultX4;
  }
}

// Initialize upscaler with specific model
async function initializeUpscaler(scale = 2, modelType = 'esrgan-slim') {
  try {
    console.log(`Initializing upscaler with scale ${scale}x and model ${modelType}...`);

    if (!Upscaler) {
      const upscalerModule = await import('upscaler');
      Upscaler = upscalerModule.default;
    }

    const model = await getModelForScaleAndType(scale, modelType);
    upscalerInstance = new Upscaler({ model });

    console.log('Upscaler initialized successfully');
    return upscalerInstance;
  } catch (error) {
    console.error('Failed to initialize upscaler:', error);
    throw error;
  }
}

// Convert buffer to base64 data URL
function bufferToDataURL(buffer, mimeType = 'image/png') {
  const base64 = buffer.toString('base64');
  return `data:${mimeType};base64,${base64}`;
}

// Health check endpoint
app.get('/', (req, res) => {
  res.json({
    status: 'ok',
    message: 'AI Image Upscaler API',
    backend: tf.getBackend(),
    version: '1.0.0',
    endpoints: {
      upscale: 'POST /upscale',
      health: 'GET /'
    }
  });
});

// Main upscale endpoint
app.post('/upscale', upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: 'No image file provided' });
    }

    const { scale = 2, modelType = 'esrgan-slim', patchSize = 128, padding = 8 } = req.body;
    
    // Validate parameters
    const validScales = [2, 3, 4];
    const validModels = ['esrgan-slim', 'esrgan-medium', 'esrgan-thick'];
    
    if (!validScales.includes(parseInt(scale))) {
      return res.status(400).json({ error: 'Invalid scale. Must be 2, 3, or 4' });
    }
    
    if (!validModels.includes(modelType)) {
      return res.status(400).json({ error: 'Invalid model type' });
    }

    console.log(`Processing image with scale ${scale}x, model ${modelType}`);
    
    // Initialize upscaler if needed
    if (!upscalerInstance) {
      await initializeUpscaler(parseInt(scale), modelType);
    }

    // Convert image buffer to data URL
    const inputDataURL = bufferToDataURL(req.file.buffer, req.file.mimetype);
    
    // Perform upscaling
    console.log('Starting upscaling...');
    const startTime = Date.now();
    
    const result = await upscalerInstance.upscale(inputDataURL, {
      output: 'base64',
      patchSize: parseInt(patchSize),
      padding: parseInt(padding),
      awaitNextFrame: true
    });
    
    const processingTime = Date.now() - startTime;
    console.log(`Upscaling completed in ${processingTime}ms`);

    // Return the upscaled image
    res.json({
      success: true,
      result: result,
      metadata: {
        scale: parseInt(scale),
        modelType: modelType,
        patchSize: parseInt(patchSize),
        padding: parseInt(padding),
        processingTime: processingTime,
        backend: tf.getBackend()
      }
    });

  } catch (error) {
    console.error('Upscaling error:', error);
    res.status(500).json({
      error: 'Failed to upscale image',
      message: error.message,
      backend: tf.getBackend()
    });
  }
});

// Error handling middleware
app.use((error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({ error: 'File too large. Maximum size is 10MB' });
    }
  }
  
  console.error('Unhandled error:', error);
  res.status(500).json({ error: 'Internal server error' });
});

// Initialize TensorFlow.js
async function initializeTensorFlow() {
  try {
    console.log('Initializing TensorFlow.js...');
    
    // Try WASM backend first
    try {
      await tf.setBackend('wasm');
      await tf.ready();
      console.log('TensorFlow.js initialized with WASM backend');
      console.log('Current backend:', tf.getBackend());
      return true;
    } catch (wasmError) {
      console.warn('WASM backend failed, trying CPU backend:', wasmError.message);
      
      // Fallback to CPU backend
      try {
        await tf.setBackend('cpu');
        await tf.ready();
        console.log('TensorFlow.js initialized with CPU backend');
        console.log('Current backend:', tf.getBackend());
        return true;
      } catch (cpuError) {
        console.error('Both WASM and CPU backends failed:', cpuError.message);
        return false;
      }
    }
  } catch (error) {
    console.error('Failed to initialize TensorFlow.js:', error);
    return false;
  }
}

// Start server
async function startServer() {
  try {
    // Initialize TensorFlow.js
    const tfInitialized = await initializeTensorFlow();
    if (!tfInitialized) {
      console.error('Failed to initialize TensorFlow.js. Exiting...');
      process.exit(1);
    }

    // Start the server
    app.listen(PORT, '0.0.0.0', () => {
      console.log(`🚀 Upscaler API server running on port ${PORT}`);
      console.log(`📊 TensorFlow.js backend: ${tf.getBackend()}`);
      console.log(`🔗 Health check: http://localhost:${PORT}/`);
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

// Handle graceful shutdown
process.on('SIGTERM', () => {
  console.log('Received SIGTERM, shutting down gracefully...');
  if (upscalerInstance) {
    try {
      upscalerInstance.dispose();
    } catch (error) {
      console.warn('Error disposing upscaler:', error);
    }
  }
  process.exit(0);
});

// Start the server
startServer();