File size: 9,285 Bytes
90a7139
 
 
 
 
 
 
 
 
 
 
c5a1c0a
 
 
 
 
90a7139
 
 
0a0be98
 
0c3c853
 
90a7139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a0be98
 
c16a30c
 
0a0be98
c16a30c
 
90a7139
0a0be98
90a7139
 
 
 
 
0a0be98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90a7139
 
 
 
 
0a0be98
90a7139
 
0a0be98
 
90a7139
0a0be98
 
90a7139
 
 
 
0a0be98
90a7139
 
 
 
 
 
 
 
 
 
 
 
 
 
0a0be98
90a7139
 
 
 
0a0be98
 
90a7139
0a0be98
 
90a7139
0a0be98
09eb2f8
90a7139
0a0be98
5cd81f1
0a0be98
90a7139
 
5cd81f1
 
90a7139
 
5cd81f1
09eb2f8
90a7139
 
 
5cd81f1
09eb2f8
90a7139
 
 
09eb2f8
90a7139
0a0be98
0c3c853
0a0be98
 
0c3c853
0a0be98
 
0c3c853
5cd81f1
 
0a0be98
5cd81f1
90a7139
 
 
0a0be98
90a7139
 
 
 
 
 
0a0be98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90a7139
 
 
 
0a0be98
90a7139
 
 
 
 
 
 
 
 
 
0a0be98
90a7139
0a0be98
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const { spawn } = require('child_process');

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

// Middleware
const corsOptions = {
  origin: 'https://image-object-detection-using-yolov5.vercel.app',
  credentials: true,
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.static(path.join(__dirname, 'uploads')));
app.use('/detected', express.static(path.join(__dirname, '../runs/detect')));

// Serve detection results as static files
app.use('/results', express.static('/data/runs/detect'));

// Configure multer for file uploads
const uploadDir = '/data/uploads';
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

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

// Routes
app.get('/', (req, res) => {
  // Check if the request wants HTML or JSON
  const acceptHeader = req.headers.accept || '';
  
  if (acceptHeader.includes('text/html')) {
    // Send HTML response for browser viewing
    res.send(`
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Backend Status</title>
          <style>
              body {
                  font-family: Arial, sans-serif;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  height: 100vh;
                  margin: 0;
                  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                  color: white;
              }
              .container {
                  text-align: center;
                  padding: 2rem;
                  background: rgba(255, 255, 255, 0.1);
                  border-radius: 15px;
                  backdrop-filter: blur(10px);
                  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
              }
              h1 {
                  font-size: 3rem;
                  margin-bottom: 1rem;
                  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
              }
              .status {
                  font-size: 1.5rem;
                  margin-bottom: 1rem;
                  color: #90EE90;
              }
              .info {
                  font-size: 1rem;
                  opacity: 0.8;
              }
              .timestamp {
                  font-size: 0.9rem;
                  opacity: 0.6;
                  margin-top: 2rem;
              }
          </style>
      </head>
      <body>
          <div class="container">
              <h1>🚀 Backend Running!</h1>
              <div class="status">✅ Object Detection API is Active</div>
              <div class="info">
                  <p>Port: ${PORT}</p>
                  <p>Environment: ${process.env.NODE_ENV || 'development'}</p>
                  <p>Upload Endpoint: POST /upload</p>
                  <p>Test Endpoint: GET /test-detected</p>
              </div>
              <div class="timestamp">
                  Started at: ${new Date().toLocaleString()}
              </div>
          </div>
      </body>
      </html>
    `);
  } else {
    // Send JSON response for API calls
    res.json({ 
      message: 'Backend Running!',
      status: 'active',
      port: PORT,
      environment: process.env.NODE_ENV || 'development',
      timestamp: new Date().toISOString()
    });
  }
});

// Test endpoint to check if detected images are accessible
app.get('/test-detected', (req, res) => {
  const expDir = path.join(__dirname, '../runs/detect/exp');
  try {
    if (fs.existsSync(expDir)) {
      const files = fs.readdirSync(expDir);
      const imageFiles = files.filter(file => /\.(jpg|jpeg|png)$/i.test(file));
      res.json({
        expDir,
        totalFiles: files.length,
        imageFiles: imageFiles,
        staticPath: '/detected/exp/'
      });
    } else {
      res.json({ error: 'Exp directory does not exist', expDir });
    }
  } catch (error) {
    res.json({ error: error.message, expDir });
  }
});

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

    const uploadedImagePath = req.file.path;
    console.log('Image uploaded:', uploadedImagePath);

    // Run YOLOv5 detection
    const detectionResult = await runYOLOv5Detection(uploadedImagePath);
    
    if (detectionResult.success) {
      res.json({
        success: true,
        originalImage: `/uploads/${path.basename(uploadedImagePath)}`,
        detectedImage: detectionResult.detectedImagePath,
        message: 'Object detection completed successfully'
      });
    } else {
      res.status(500).json({
        success: false,
        error: detectionResult.error
      });
    }

  } catch (error) {
    console.error('Error processing upload:', error);
    res.status(500).json({
      success: false,
      error: 'Error processing image upload'
    });
  }
});

// Function to run YOLOv5 detection using Ultralytics API
async function runYOLOv5Detection(imagePath) {
  return new Promise((resolve) => {
    const yolov5Path = path.join(__dirname, 'yolo_detect.py');
         const weightsPath = '/tmp/yolov8s.pt';

    console.log('Calling yolo_detect.py with weights:', weightsPath, 'and image:', imagePath);

    const pythonProcess = spawn('python', [
      yolov5Path,
      weightsPath,
      imagePath,
    ]);

    let output = '';
    let errorOutput = '';

    pythonProcess.stdout.on('data', (data) => {
      output += data.toString();
      console.log('PYTHON STDOUT:', data.toString());
    });

    pythonProcess.stderr.on('data', (data) => {
      errorOutput += data.toString();
      console.error('PYTHON STDERR:', data.toString());
    });

    pythonProcess.on('close', (code) => {
      console.log('Python process exited with code:', code);
      if (code === 0) {
        // Extract the last non-empty line from output as the detected image path
        const lines = output.trim().split('\n');
        const lastLine = lines.reverse().find(line => line.trim().endsWith('.jpg'));
        let detectedImageUrl = null;
        if (lastLine) {
          const detectedImageFilename = path.basename(lastLine);
          detectedImageUrl = `/results/predict/${detectedImageFilename}`;
        }
        resolve({
          success: true,
          detectedImagePath: detectedImageUrl,
        });
      } else {
        resolve({
          success: false,
          error: errorOutput || `YOLOv5 detection failed with code ${code}`,
        });
      }
    });
  });
}

// Function to find the detected image
function findDetectedImage(expDir, originalImageName) {
  try {
    if (!fs.existsSync(expDir)) {
      console.log('Exp directory does not exist:', expDir);
      return null;
    }

    const files = fs.readdirSync(expDir);
    console.log('Files in exp directory:', files);

    // Look for image files (jpg, jpeg, png)
    const imageFiles = files.filter(file => /\.(jpg|jpeg|png)$/i.test(file));

    // Try to find the detected image with the same name as the uploaded file
    const detectedFile = imageFiles.find(file => file === originalImageName);
    if (detectedFile) {
      const detectedImagePath = path.join(expDir, detectedFile);
      console.log('Found detected image:', detectedImagePath);
      return detectedImagePath;
    }

    // Fallback: return the first image if not found (optional)
    if (imageFiles.length > 0) {
      const detectedImagePath = path.join(expDir, imageFiles[0]);
      console.log('Fallback detected image:', detectedImagePath);
      return detectedImagePath;
    }

    return null;
  } catch (error) {
    console.error('Error finding detected image:', error);
    return null;
  }
}

// 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('Server error:', error);
  res.status(500).json({ error: 'Internal server error' });
});

// Start server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`Upload directory: ${path.join(__dirname, 'uploads')}`);
  console.log(`Detected images served from: ${path.join(__dirname, '../runs/detect')}`);
  console.log(`Static file serving configured for /detected -> ${path.join(__dirname, '../runs/detect')}`);
});