Spaces:
Sleeping
Sleeping
Update server.js
Browse files
server.js
CHANGED
|
@@ -17,8 +17,6 @@ app.use(cors(corsOptions));
|
|
| 17 |
app.use(express.json());
|
| 18 |
app.use(express.static(path.join(__dirname, 'uploads')));
|
| 19 |
app.use('/detected', express.static(path.join(__dirname, '../runs/detect')));
|
| 20 |
-
|
| 21 |
-
// Serve detection results as static files
|
| 22 |
app.use('/results', express.static('/data/runs/detect'));
|
| 23 |
|
| 24 |
// Configure multer for file uploads
|
|
@@ -39,138 +37,42 @@ const storage = multer.diskStorage({
|
|
| 39 |
const upload = multer({
|
| 40 |
storage: storage,
|
| 41 |
fileFilter: function (req, file, cb) {
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
}
|
|
|
|
|
|
|
|
|
|
| 49 |
limits: {
|
| 50 |
-
fileSize:
|
| 51 |
}
|
| 52 |
});
|
| 53 |
|
| 54 |
// Routes
|
| 55 |
app.get('/', (req, res) => {
|
| 56 |
-
|
| 57 |
-
const acceptHeader = req.headers.accept || '';
|
| 58 |
-
|
| 59 |
-
if (acceptHeader.includes('text/html')) {
|
| 60 |
-
// Send HTML response for browser viewing
|
| 61 |
-
res.send(`
|
| 62 |
-
<!DOCTYPE html>
|
| 63 |
-
<html lang="en">
|
| 64 |
-
<head>
|
| 65 |
-
<meta charset="UTF-8">
|
| 66 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 67 |
-
<title>Backend Status</title>
|
| 68 |
-
<style>
|
| 69 |
-
body {
|
| 70 |
-
font-family: Arial, sans-serif;
|
| 71 |
-
display: flex;
|
| 72 |
-
justify-content: center;
|
| 73 |
-
align-items: center;
|
| 74 |
-
height: 100vh;
|
| 75 |
-
margin: 0;
|
| 76 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 77 |
-
color: white;
|
| 78 |
-
}
|
| 79 |
-
.container {
|
| 80 |
-
text-align: center;
|
| 81 |
-
padding: 2rem;
|
| 82 |
-
background: rgba(255, 255, 255, 0.1);
|
| 83 |
-
border-radius: 15px;
|
| 84 |
-
backdrop-filter: blur(10px);
|
| 85 |
-
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
|
| 86 |
-
}
|
| 87 |
-
h1 {
|
| 88 |
-
font-size: 3rem;
|
| 89 |
-
margin-bottom: 1rem;
|
| 90 |
-
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
|
| 91 |
-
}
|
| 92 |
-
.status {
|
| 93 |
-
font-size: 1.5rem;
|
| 94 |
-
margin-bottom: 1rem;
|
| 95 |
-
color: #90EE90;
|
| 96 |
-
}
|
| 97 |
-
.info {
|
| 98 |
-
font-size: 1rem;
|
| 99 |
-
opacity: 0.8;
|
| 100 |
-
}
|
| 101 |
-
.timestamp {
|
| 102 |
-
font-size: 0.9rem;
|
| 103 |
-
opacity: 0.6;
|
| 104 |
-
margin-top: 2rem;
|
| 105 |
-
}
|
| 106 |
-
</style>
|
| 107 |
-
</head>
|
| 108 |
-
<body>
|
| 109 |
-
<div class="container">
|
| 110 |
-
<h1>🚀 Backend Running!</h1>
|
| 111 |
-
<div class="status">✅ Object Detection API is Active</div>
|
| 112 |
-
<div class="info">
|
| 113 |
-
<p>Port: ${PORT}</p>
|
| 114 |
-
<p>Environment: ${process.env.NODE_ENV || 'development'}</p>
|
| 115 |
-
<p>Upload Endpoint: POST /upload</p>
|
| 116 |
-
<p>Test Endpoint: GET /test-detected</p>
|
| 117 |
-
</div>
|
| 118 |
-
<div class="timestamp">
|
| 119 |
-
Started at: ${new Date().toLocaleString()}
|
| 120 |
-
</div>
|
| 121 |
-
</div>
|
| 122 |
-
</body>
|
| 123 |
-
</html>
|
| 124 |
-
`);
|
| 125 |
-
} else {
|
| 126 |
-
// Send JSON response for API calls
|
| 127 |
-
res.json({
|
| 128 |
-
message: 'Backend Running!',
|
| 129 |
-
status: 'active',
|
| 130 |
-
port: PORT,
|
| 131 |
-
environment: process.env.NODE_ENV || 'development',
|
| 132 |
-
timestamp: new Date().toISOString()
|
| 133 |
-
});
|
| 134 |
-
}
|
| 135 |
-
});
|
| 136 |
-
|
| 137 |
-
// Test endpoint to check if detected images are accessible
|
| 138 |
-
app.get('/test-detected', (req, res) => {
|
| 139 |
-
const expDir = path.join(__dirname, '../runs/detect/exp');
|
| 140 |
-
try {
|
| 141 |
-
if (fs.existsSync(expDir)) {
|
| 142 |
-
const files = fs.readdirSync(expDir);
|
| 143 |
-
const imageFiles = files.filter(file => /\.(jpg|jpeg|png)$/i.test(file));
|
| 144 |
-
res.json({
|
| 145 |
-
expDir,
|
| 146 |
-
totalFiles: files.length,
|
| 147 |
-
imageFiles: imageFiles,
|
| 148 |
-
staticPath: '/detected/exp/'
|
| 149 |
-
});
|
| 150 |
-
} else {
|
| 151 |
-
res.json({ error: 'Exp directory does not exist', expDir });
|
| 152 |
-
}
|
| 153 |
-
} catch (error) {
|
| 154 |
-
res.json({ error: error.message, expDir });
|
| 155 |
-
}
|
| 156 |
});
|
| 157 |
|
| 158 |
app.post('/upload', upload.single('image'), async (req, res) => {
|
| 159 |
try {
|
| 160 |
if (!req.file) {
|
| 161 |
-
return res.status(400).json({ error: 'No image file uploaded' });
|
| 162 |
}
|
| 163 |
|
| 164 |
-
const
|
| 165 |
-
console.log('
|
| 166 |
|
| 167 |
-
// Run
|
| 168 |
-
const detectionResult = await
|
| 169 |
|
| 170 |
if (detectionResult.success) {
|
| 171 |
res.json({
|
| 172 |
success: true,
|
| 173 |
-
originalImage: `/uploads/${path.basename(
|
| 174 |
detectedImage: detectionResult.detectedImagePath,
|
| 175 |
message: 'Object detection completed successfully'
|
| 176 |
});
|
|
@@ -185,23 +87,23 @@ app.post('/upload', upload.single('image'), async (req, res) => {
|
|
| 185 |
console.error('Error processing upload:', error);
|
| 186 |
res.status(500).json({
|
| 187 |
success: false,
|
| 188 |
-
error: 'Error processing
|
| 189 |
});
|
| 190 |
}
|
| 191 |
});
|
| 192 |
|
| 193 |
-
// Function to run
|
| 194 |
-
async function
|
| 195 |
return new Promise((resolve) => {
|
| 196 |
-
const
|
| 197 |
-
|
| 198 |
|
| 199 |
-
console.log('Calling yolo_detect.py with weights:', weightsPath, 'and
|
| 200 |
|
| 201 |
const pythonProcess = spawn('python', [
|
| 202 |
-
|
| 203 |
weightsPath,
|
| 204 |
-
|
| 205 |
]);
|
| 206 |
|
| 207 |
let output = '';
|
|
@@ -220,69 +122,33 @@ async function runYOLOv5Detection(imagePath) {
|
|
| 220 |
pythonProcess.on('close', (code) => {
|
| 221 |
console.log('Python process exited with code:', code);
|
| 222 |
if (code === 0) {
|
| 223 |
-
// Extract the last non-empty line from output as the detected
|
| 224 |
const lines = output.trim().split('\n');
|
| 225 |
-
const lastLine = lines.reverse().find(line => line.trim().
|
| 226 |
-
let
|
| 227 |
if (lastLine) {
|
| 228 |
-
const
|
| 229 |
-
|
| 230 |
}
|
| 231 |
resolve({
|
| 232 |
success: true,
|
| 233 |
-
detectedImagePath:
|
| 234 |
});
|
| 235 |
} else {
|
| 236 |
resolve({
|
| 237 |
success: false,
|
| 238 |
-
error: errorOutput || `
|
| 239 |
});
|
| 240 |
}
|
| 241 |
});
|
| 242 |
});
|
| 243 |
}
|
| 244 |
|
| 245 |
-
// Function to find the detected image
|
| 246 |
-
function findDetectedImage(expDir, originalImageName) {
|
| 247 |
-
try {
|
| 248 |
-
if (!fs.existsSync(expDir)) {
|
| 249 |
-
console.log('Exp directory does not exist:', expDir);
|
| 250 |
-
return null;
|
| 251 |
-
}
|
| 252 |
-
|
| 253 |
-
const files = fs.readdirSync(expDir);
|
| 254 |
-
console.log('Files in exp directory:', files);
|
| 255 |
-
|
| 256 |
-
// Look for image files (jpg, jpeg, png)
|
| 257 |
-
const imageFiles = files.filter(file => /\.(jpg|jpeg|png)$/i.test(file));
|
| 258 |
-
|
| 259 |
-
// Try to find the detected image with the same name as the uploaded file
|
| 260 |
-
const detectedFile = imageFiles.find(file => file === originalImageName);
|
| 261 |
-
if (detectedFile) {
|
| 262 |
-
const detectedImagePath = path.join(expDir, detectedFile);
|
| 263 |
-
console.log('Found detected image:', detectedImagePath);
|
| 264 |
-
return detectedImagePath;
|
| 265 |
-
}
|
| 266 |
-
|
| 267 |
-
// Fallback: return the first image if not found (optional)
|
| 268 |
-
if (imageFiles.length > 0) {
|
| 269 |
-
const detectedImagePath = path.join(expDir, imageFiles[0]);
|
| 270 |
-
console.log('Fallback detected image:', detectedImagePath);
|
| 271 |
-
return detectedImagePath;
|
| 272 |
-
}
|
| 273 |
-
|
| 274 |
-
return null;
|
| 275 |
-
} catch (error) {
|
| 276 |
-
console.error('Error finding detected image:', error);
|
| 277 |
-
return null;
|
| 278 |
-
}
|
| 279 |
-
}
|
| 280 |
-
|
| 281 |
// Error handling middleware
|
| 282 |
app.use((error, req, res, next) => {
|
| 283 |
if (error instanceof multer.MulterError) {
|
| 284 |
if (error.code === 'LIMIT_FILE_SIZE') {
|
| 285 |
-
return res.status(400).json({ error: 'File too large. Maximum size is
|
| 286 |
}
|
| 287 |
}
|
| 288 |
console.error('Server error:', error);
|
|
@@ -293,6 +159,6 @@ app.use((error, req, res, next) => {
|
|
| 293 |
app.listen(PORT, () => {
|
| 294 |
console.log(`Server running on port ${PORT}`);
|
| 295 |
console.log(`Upload directory: ${path.join(__dirname, 'uploads')}`);
|
| 296 |
-
console.log(`Detected images served from: ${path.join(__dirname, '../runs/detect')}`);
|
| 297 |
console.log(`Static file serving configured for /detected -> ${path.join(__dirname, '../runs/detect')}`);
|
| 298 |
-
});
|
|
|
|
| 17 |
app.use(express.json());
|
| 18 |
app.use(express.static(path.join(__dirname, 'uploads')));
|
| 19 |
app.use('/detected', express.static(path.join(__dirname, '../runs/detect')));
|
|
|
|
|
|
|
| 20 |
app.use('/results', express.static('/data/runs/detect'));
|
| 21 |
|
| 22 |
// Configure multer for file uploads
|
|
|
|
| 37 |
const upload = multer({
|
| 38 |
storage: storage,
|
| 39 |
fileFilter: function (req, file, cb) {
|
| 40 |
+
// Accept image and video files
|
| 41 |
+
if (
|
| 42 |
+
file.mimetype.startsWith('image/') ||
|
| 43 |
+
file.mimetype.startsWith('video/')
|
| 44 |
+
) {
|
| 45 |
+
cb(null, true);
|
| 46 |
+
} else {
|
| 47 |
+
cb(new Error('Only image and video files are allowed!'), false);
|
| 48 |
+
}
|
| 49 |
+
},
|
| 50 |
limits: {
|
| 51 |
+
fileSize: 100 * 1024 * 1024 // 100MB limit for videos
|
| 52 |
}
|
| 53 |
});
|
| 54 |
|
| 55 |
// Routes
|
| 56 |
app.get('/', (req, res) => {
|
| 57 |
+
res.json({ message: 'Backend Running!' });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
});
|
| 59 |
|
| 60 |
app.post('/upload', upload.single('image'), async (req, res) => {
|
| 61 |
try {
|
| 62 |
if (!req.file) {
|
| 63 |
+
return res.status(400).json({ error: 'No image or video file uploaded' });
|
| 64 |
}
|
| 65 |
|
| 66 |
+
const uploadedMediaPath = req.file.path;
|
| 67 |
+
console.log('Media uploaded:', uploadedMediaPath);
|
| 68 |
|
| 69 |
+
// Run YOLO detection
|
| 70 |
+
const detectionResult = await runYOLODetection(uploadedMediaPath);
|
| 71 |
|
| 72 |
if (detectionResult.success) {
|
| 73 |
res.json({
|
| 74 |
success: true,
|
| 75 |
+
originalImage: `/uploads/${path.basename(uploadedMediaPath)}`,
|
| 76 |
detectedImage: detectionResult.detectedImagePath,
|
| 77 |
message: 'Object detection completed successfully'
|
| 78 |
});
|
|
|
|
| 87 |
console.error('Error processing upload:', error);
|
| 88 |
res.status(500).json({
|
| 89 |
success: false,
|
| 90 |
+
error: 'Error processing media upload'
|
| 91 |
});
|
| 92 |
}
|
| 93 |
});
|
| 94 |
|
| 95 |
+
// Function to run YOLO detection using Ultralytics API
|
| 96 |
+
async function runYOLODetection(mediaPath) {
|
| 97 |
return new Promise((resolve) => {
|
| 98 |
+
const yolopyPath = path.join(__dirname, 'yolo_detect.py');
|
| 99 |
+
const weightsPath = '/tmp/yolov8s.pt'; // or your preferred weights
|
| 100 |
|
| 101 |
+
console.log('Calling yolo_detect.py with weights:', weightsPath, 'and media:', mediaPath);
|
| 102 |
|
| 103 |
const pythonProcess = spawn('python', [
|
| 104 |
+
yolopyPath,
|
| 105 |
weightsPath,
|
| 106 |
+
mediaPath,
|
| 107 |
]);
|
| 108 |
|
| 109 |
let output = '';
|
|
|
|
| 122 |
pythonProcess.on('close', (code) => {
|
| 123 |
console.log('Python process exited with code:', code);
|
| 124 |
if (code === 0) {
|
| 125 |
+
// Extract the last non-empty line from output as the detected media path
|
| 126 |
const lines = output.trim().split('\n');
|
| 127 |
+
const lastLine = lines.reverse().find(line => line.trim().match(/\.(jpg|jpeg|png|mp4|webm|avi|mov)$/i));
|
| 128 |
+
let detectedMediaUrl = null;
|
| 129 |
if (lastLine) {
|
| 130 |
+
const detectedMediaFilename = path.basename(lastLine);
|
| 131 |
+
detectedMediaUrl = `/results/predict/${detectedMediaFilename}`;
|
| 132 |
}
|
| 133 |
resolve({
|
| 134 |
success: true,
|
| 135 |
+
detectedImagePath: detectedMediaUrl,
|
| 136 |
});
|
| 137 |
} else {
|
| 138 |
resolve({
|
| 139 |
success: false,
|
| 140 |
+
error: errorOutput || `YOLO detection failed with code ${code}`,
|
| 141 |
});
|
| 142 |
}
|
| 143 |
});
|
| 144 |
});
|
| 145 |
}
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
// Error handling middleware
|
| 148 |
app.use((error, req, res, next) => {
|
| 149 |
if (error instanceof multer.MulterError) {
|
| 150 |
if (error.code === 'LIMIT_FILE_SIZE') {
|
| 151 |
+
return res.status(400).json({ error: 'File too large. Maximum size is 100MB.' });
|
| 152 |
}
|
| 153 |
}
|
| 154 |
console.error('Server error:', error);
|
|
|
|
| 159 |
app.listen(PORT, () => {
|
| 160 |
console.log(`Server running on port ${PORT}`);
|
| 161 |
console.log(`Upload directory: ${path.join(__dirname, 'uploads')}`);
|
| 162 |
+
console.log(`Detected images/videos served from: ${path.join(__dirname, '../runs/detect')}`);
|
| 163 |
console.log(`Static file serving configured for /detected -> ${path.join(__dirname, '../runs/detect')}`);
|
| 164 |
+
});
|