-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
136 lines (120 loc) · 4.53 KB
/
Copy pathindex.js
File metadata and controls
136 lines (120 loc) · 4.53 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
const express = require("express");
require("dotenv").config();
const cors = require("cors");
const fs = require("fs");
const path = require("path");
const {
generateScript,
uploadFile
} = require("./utils");
const multer = require("multer")
// Create uploads directory if it doesn't exist
const uploadsDir = '/tmp/uploads';
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, {
recursive: true
});
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadsDir);
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
}
});
const upload = multer({
storage
})
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.urlencoded({
extended: true
}))
app.use(cors())
app.set('trust proxy', true);
app.get("/", (req, res) => {
res.send({
"message": "Welcome to the MemoMosaic Backend!"
})
})
app.post("/create", upload.fields([
{ name: 'assets', maxCount: 30 },
{ name: 'annotationFaces', maxCount: 50 }
]), async (req, res) => {
const uploadedFilePaths = [];
try {
const payload = JSON.parse(req.body.payload)
const mediaFiles = req.files?.assets || []
const annotationFiles = req.files?.annotationFaces || []
// Convert uploaded media files to asset objects with base64 buffers from disk
const assets = mediaFiles.map((file, index) => {
uploadedFilePaths.push(file.path);
const fileBuffer = fs.readFileSync(file.path);
return {
buffer: fileBuffer.toString('base64'),
type: req.body[`assets[${index}].type`] || payload.assetMetadata?.[index]?.type || "IMAGE",
mimeType: file.mimetype,
location: req.body[`assets[${index}].location`] || payload.assetMetadata?.[index]?.location || "Unknown",
creation_time: req.body[`assets[${index}].creation_time`] || payload.assetMetadata?.[index]?.creation_time || new Date().toISOString()
};
})
// Convert uploaded annotation face files to base64 and map to annotations by index
const annotationFaceBuffers = annotationFiles.map((file) => {
uploadedFilePaths.push(file.path);
const fileBuffer = fs.readFileSync(file.path);
return fileBuffer.toString('base64');
});
// Inject base64 face data into annotations array based on faceIndex
if (payload.annotations && Array.isArray(payload.annotations)) {
payload.annotations = payload.annotations.map(annotation => {
if (annotation.faceIndex !== undefined && annotationFaceBuffers[annotation.faceIndex]) {
return {
...annotation,
image: annotationFaceBuffers[annotation.faceIndex],
faceIndex: undefined // Remove index after mapping
};
}
return annotation;
});
}
// Merge assets with payload
payload.assets = assets
const script = await generateScript(payload);
// Upload collages to tmpfiles.org and replace base64 with URLs
script.scenes = await Promise.all(script.scenes.map(async (scene) => {
try {
const uploadUrl = await uploadFile(scene.collage, `collage-${Date.now()}.${scene.type === 'IMAGE' ? 'png' : 'mp4'}`);
return {
...scene,
collage: uploadUrl // Replace base64 with URL
};
} catch (err) {
console.error(`Error uploading collage: ${err.message}`);
// Return scene with base64 if upload fails
return scene;
}
}));
res.send(script);
} catch (err) {
console.error(err);
res.status(500).send({
success: false,
error: err.message
})
} finally {
// Clean up uploaded files from /tmp/uploads
uploadedFilePaths.forEach(filePath => {
try {
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
} catch (err) {
console.error(`Error deleting file ${filePath}: ${err.message}`);
}
});
}
})
app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`)
})