-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cjs
More file actions
204 lines (180 loc) · 6.43 KB
/
Copy pathserver.cjs
File metadata and controls
204 lines (180 loc) · 6.43 KB
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
const express = require('express');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const https = require('https');
const fs = require('fs');
const { execFile } = require('child_process');
const axios = require('axios');
const FormData = require('form-data');
require('dotenv').config();
const app = express();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
// Preserve original extension
const ext = path.extname(file.originalname);
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, uniqueSuffix + ext);
}
});
const upload = multer({
storage: storage,
fileFilter: (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);
}
}
});
// Ensure directories exist
const profilesDir = path.join(__dirname, 'profiles');
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(profilesDir)) {
fs.mkdirSync(profilesDir);
}
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir);
}
// --- CORS & FILE UPLOADS ---
app.use(cors({ origin:
[process.env.FRONTEND_URL, process.env.FASTAPI_YOLO_URL, process.env.FASTAPI_DINO_URL, process.env.FASTAPI_FAISS_URL],
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true }));
// --- API ENDPOINTS ---
app.post('/api/upload-image', upload.single('image'), async (req, res) => {
if (!req.file) {
return res.status(400).json({
error: 'No image uploaded',
details: 'req.file is null/undefined'
});
}
const imagePath = req.file.path;
// Check if file exists
if (!fs.existsSync(imagePath)) {
return res.status(500).json({
error: 'File not found on server',
path: imagePath
});
}
// Send the image to FastAPI YOLO endpoint
const form = new FormData();
const fileStream = fs.createReadStream(imagePath);
form.append('file', fileStream);
const response = await axios.post(process.env.FASTAPI_YOLO_URL, form, {
headers: form.getHeaders(),
maxContentLength: Infinity,
maxBodyLength: Infinity,
timeout: 30000, // 30 second timeout
});
const polygons = response.data.polygons;
const imageUrl = '/uploads/' + path.basename(imagePath);
const responseData = { imageUrl, polygons };
res.json(responseData);
// Delete the uploaded file after a short delay
setTimeout(() => {
fs.unlink(imagePath, err => {
if (err) console.error('Failed to delete upload:', imagePath, err);
else console.log('Deleted upload:', imagePath);
});
}, 30000); // 30 seconds
});
// --- GENERATE JERSEY ENDPOINT ---
app.post('/api/generate-jersey', upload.single('image'), async (req, res) => {
if (!req.file) {
return res.status(400).json({ error: 'No image uploaded' });
}
const imagePath = req.file.path;
const area = req.body.area ? JSON.parse(req.body.area) : null;
const isPolygon = req.body.isPolygon ? JSON.parse(req.body.isPolygon) : false;
// Extract maximum rectangle from the cropped image
const maxRectanglePath = await extractMaxRectangle(imagePath, area, isPolygon);
// Extract features using DINO model
const features = await extractDINOFeatures(maxRectanglePath);
if (features) {
// Search for similar images using FAISS
let similarImages = await searchFAISS(features);
// Limit to top 15 results
if (Array.isArray(similarImages)) {
similarImages = similarImages.slice(0, 15);
}
res.status(200).json({
imageUrl: '/uploads/' + path.basename(maxRectanglePath),
message: 'Similar designs found!',
maxRectanglePath,
features: features,
similarDesigns: similarImages || []
});
} else {
res.status(500).json({ error: 'Failed to extract features' });
}
// Delete both the uploaded and processed files after a short delay
setTimeout(() => {
fs.unlink(imagePath, err => {
if (err) console.error('Failed to delete upload:', imagePath, err);
else console.log('Deleted upload:', imagePath);
});
if (maxRectanglePath !== imagePath) {
fs.unlink(maxRectanglePath, err => {
if (err) console.error('Failed to delete processed file:', maxRectanglePath, err);
else console.log('Deleted processed file:', maxRectanglePath);
});
}
}, 30000); // 30 seconds
});
async function extractMaxRectangle(imagePath, area, isPolygon) {
const sharp = require('sharp');
if (isPolygon && area && area.length > 0) {
const image = sharp(imagePath);
const metadata = await image.metadata();
// Calculate bounding rectangle of the polygon
const minX = Math.max(0, Math.round(Math.min(...area.map(([x, y]) => x))));
const minY = Math.max(0, Math.round(Math.min(...area.map(([x, y]) => y))));
const maxX = Math.min(metadata.width, Math.round(Math.max(...area.map(([x, y]) => x))));
const maxY = Math.min(metadata.height, Math.round(Math.max(...area.map(([x, y]) => y))));
const cropWidth = Math.max(1, maxX - minX);
const cropHeight = Math.max(1, maxY - minY);
const outputPath = imagePath.replace(/(\.[^.]+)$/, '_polygon$1');
await image.extract({
left: minX,
top: minY,
width: cropWidth,
height: cropHeight
}).toFile(outputPath);
return outputPath;
} else {
// No polygon provided, just return the original image
return imagePath;
}
}
async function extractDINOFeatures(imagePath) {
const form = new FormData();
form.append('file', fs.createReadStream(imagePath));
const response = await axios.post(process.env.FASTAPI_DINO_URL, form, {
headers: form.getHeaders(),
maxContentLength: Infinity,
maxBodyLength: Infinity,
});
return response.data.features;
}
async function searchFAISS(features) {
const response = await axios.post(process.env.FASTAPI_FAISS_URL, {
features: features
});
return response.data.results;
}
// Serve static files (for placeholder.svg and uploaded images)
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// Serve catalogue directory
const catalogueDir = path.join(__dirname, 'catalogue');
app.use('/catalogue', express.static(catalogueDir));
const PORT = process.env.PORT || 3001;
// Convert HTTPS server to HTTP
app.listen(PORT, () => {
console.log(`API server running on http://localhost:${PORT}`);
});