-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
280 lines (240 loc) · 8.93 KB
/
Copy pathserver.ts
File metadata and controls
280 lines (240 loc) · 8.93 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
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
import express from "express";
import path from "path";
import fs from "fs";
import { createServer as createViteServer } from "vite";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const PORT = 3000;
// Set high limits for image base64 uploads
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ limit: "50mb", extended: true }));
// Ensure base datasets directory exists
const DATASETS_ROOT = path.join(process.cwd(), "datasets");
if (!fs.existsSync(DATASETS_ROOT)) {
fs.mkdirSync(DATASETS_ROOT, { recursive: true });
}
// Utility to resolve relative or absolute paths safely
function resolvePath(dirPath: string): string {
if (path.isAbsolute(dirPath)) {
return dirPath;
}
return path.join(process.cwd(), dirPath);
}
// Helper to scan for images
function scanImagesInDirectory(dirPath: string): string[] {
const resolved = resolvePath(dirPath);
if (!fs.existsSync(resolved)) {
return [];
}
const files = fs.readdirSync(resolved);
const extensions = [".png", ".jpg", ".jpeg", ".webp", ".bmp"];
return files
.filter((file) => extensions.includes(path.extname(file).toLowerCase()))
.sort();
}
// Helper to check if mask exists
function getMaskForImage(imageName: string, outputDir: string): { hasMask: boolean; maskPath: string } {
const resolvedOut = resolvePath(outputDir);
// Masks are saved as PNG with matching base name or exact name
const baseName = path.parse(imageName).name;
const maskPath = path.join(resolvedOut, `${baseName}_mask.png`);
return {
hasMask: fs.existsSync(maskPath),
maskPath: maskPath,
};
}
// Helper to check if JSON annotations exist
function getAnnotationsForImage(imageName: string, outputDir: string): { annotations: any | null } {
const resolvedOut = resolvePath(outputDir);
const baseName = path.parse(imageName).name;
const jsonPath = path.join(resolvedOut, `${baseName}_annotations.json`);
if (fs.existsSync(jsonPath)) {
try {
const content = fs.readFileSync(jsonPath, "utf-8");
return { annotations: JSON.parse(content) };
} catch (e) {
console.error("Error parsing annotations JSON:", e);
}
}
return { annotations: null };
}
// API Routes
// 1. Get standard or custom datasets
app.get("/api/datasets", (req, res) => {
try {
const subfolders = fs.readdirSync(DATASETS_ROOT).filter((file) => {
return fs.statSync(path.join(DATASETS_ROOT, file)).isDirectory();
});
const datasets = subfolders.map((folder) => {
const inputDir = path.join("datasets", folder, "input");
const outputDir = path.join("datasets", folder, "masks");
const images = scanImagesInDirectory(inputDir);
return {
name: folder,
inputDir,
outputDir,
imageCount: images.length,
};
});
res.json({ success: true, datasets });
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
});
// 2. Scan custom directory (manual input/output folders)
app.post("/api/scan-directory", (req, res) => {
try {
const { inputDir, outputDir } = req.body;
if (!inputDir || !outputDir) {
return res.status(400).json({ success: false, error: "Input and Output directory paths are required." });
}
const resolvedInput = resolvePath(inputDir);
const resolvedOutput = resolvePath(outputDir);
// Create directories if they do not exist
if (!fs.existsSync(resolvedInput)) {
fs.mkdirSync(resolvedInput, { recursive: true });
}
if (!fs.existsSync(resolvedOutput)) {
fs.mkdirSync(resolvedOutput, { recursive: true });
}
const images = scanImagesInDirectory(inputDir);
const imageDetails = images.map((img) => {
const { hasMask } = getMaskForImage(img, outputDir);
const { annotations } = getAnnotationsForImage(img, outputDir);
return {
name: img,
hasMask,
annotations,
};
});
res.json({
success: true,
inputDir,
outputDir,
images: imageDetails,
});
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
});
// 3. Upload a sample image (handles client-side offscreen generated sample images)
app.post("/api/upload-sample", (req, res) => {
try {
const { datasetName, imageName, imageDataUrl } = req.body;
if (!datasetName || !imageName || !imageDataUrl) {
return res.status(400).json({ success: false, error: "Missing required parameters." });
}
const targetInputFolder = path.join(DATASETS_ROOT, datasetName, "input");
const targetOutputFolder = path.join(DATASETS_ROOT, datasetName, "masks");
if (!fs.existsSync(targetInputFolder)) {
fs.mkdirSync(targetInputFolder, { recursive: true });
}
if (!fs.existsSync(targetOutputFolder)) {
fs.mkdirSync(targetOutputFolder, { recursive: true });
}
// Decode base64 PNG/JPG
const matches = imageDataUrl.match(/^data:image\/([a-zA-Z+]+);base64,(.+)$/);
if (!matches || matches.length !== 3) {
return res.status(400).json({ success: false, error: "Invalid image data URL format." });
}
const imageBuffer = Buffer.from(matches[2], "base64");
const filePath = path.join(targetInputFolder, imageName);
fs.writeFileSync(filePath, imageBuffer);
res.json({ success: true, filePath });
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
});
// 4. Serve an image from any directory
app.get("/api/image", (req, res) => {
try {
const relativePath = req.query.path as string;
if (!relativePath) {
return res.status(400).json({ error: "Path parameter is required" });
}
const resolved = resolvePath(relativePath);
if (!fs.existsSync(resolved)) {
return res.status(404).json({ error: "Image file not found: " + relativePath });
}
res.sendFile(resolved);
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// 5. Serve a mask PNG from output directory
app.get("/api/mask", (req, res) => {
try {
const relativePath = req.query.path as string;
if (!relativePath) {
return res.status(400).json({ error: "Path parameter is required" });
}
const resolved = resolvePath(relativePath);
if (!fs.existsSync(resolved)) {
return res.status(404).json({ error: "Mask file not found: " + relativePath });
}
res.sendFile(resolved);
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// 6. Save annotation PNG mask and JSON coordinates
app.post("/api/save-mask", (req, res) => {
try {
const { imageName, outputDir, maskDataUrl, annotations } = req.body;
if (!imageName || !outputDir) {
return res.status(400).json({ success: false, error: "Missing required parameters." });
}
const resolvedOutput = resolvePath(outputDir);
if (!fs.existsSync(resolvedOutput)) {
fs.mkdirSync(resolvedOutput, { recursive: true });
}
const baseName = path.parse(imageName).name;
// If annotations are cleared/empty, delete both the mask PNG and annotations JSON files
if (annotations && annotations.length === 0) {
const maskPath = path.join(resolvedOutput, `${baseName}_mask.png`);
const jsonPath = path.join(resolvedOutput, `${baseName}_annotations.json`);
if (fs.existsSync(maskPath)) fs.unlinkSync(maskPath);
if (fs.existsSync(jsonPath)) fs.unlinkSync(jsonPath);
return res.json({ success: true, message: `Successfully cleared mask and annotations for ${imageName}` });
}
if (!maskDataUrl) {
return res.status(400).json({ success: false, error: "Missing maskDataUrl." });
}
// Decode and save PNG mask
const matches = maskDataUrl.match(/^data:image\/([a-zA-Z+]+);base64,(.+)$/);
if (matches && matches.length === 3) {
const maskBuffer = Buffer.from(matches[2], "base64");
const maskPath = path.join(resolvedOutput, `${baseName}_mask.png`);
fs.writeFileSync(maskPath, maskBuffer);
} else {
return res.status(400).json({ success: false, error: "Invalid mask data URL." });
}
// Save JSON coordinates for persistence & editing
const jsonPath = path.join(resolvedOutput, `${baseName}_annotations.json`);
fs.writeFileSync(jsonPath, JSON.stringify(annotations, null, 2));
res.json({ success: true, message: `Successfully saved mask for ${imageName}` });
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
});
// Setup Vite Dev Server / Serve static build
async function startServer() {
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), "dist");
app.use(express.static(distPath));
app.get("*", (req, res) => {
res.sendFile(path.join(distPath, "index.html"));
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`Express server running on http://localhost:${PORT}`);
});
}
startServer();