annotator/server.js

132 lines
3.7 KiB
JavaScript

const fs = require('fs').promises;
async function main() {
// Imports et constantes.
const fs = require('fs').promises;
const express = require('express');
const bodyParser = require('body-parser')
const ip = '127.0.0.1';
const port = 8000;
const app = express();
let id = 1;
// Permet de récupérer les données venant du client.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Page d'accueil.
app.get('/', async function(req, res) {
let body = '<!doctype HTML>\n';
body += '<html>\n';
body += ' <head>\n';
body += ' <meta charset="utf-8">\n';
body += ' <style>\n';
body += ' * {\n';
body += ' font-family: sans-serif;\n';
body += ' }\n';
body += ' </style>\n';
body += ' </head>\n';
body += ' <body>\n';
let dir = null;
try {
dir = await fs.readdir('static/videos');
} catch (e) {
body += ' <h1>Please put your videos as jpg files in </h1>\n';
}
if (dir !== null) {
body += ' <h1>Available videos to annotate:</h1>\n';
body += ' <ul>\n';
for (let video of dir) {
body += ' <li>\n';
body += ' <a href="/annotator?root=/static/videos/' + video + '">' + video + '</a>\n';
}
body += ' </ul>\n';
}
body += ' </body>\n';
body += '</html>\n';
res.send(body);
});
// Page d'annotation.
app.get('/annotator', async function(req, res) {
const root = req.query.root.slice(1);
if (root.startsWith('/') || root.indexOf('..') !== -1) {
res.status(400);
return res.send('Root is invalid');
}
let annotations = null;
try {
// Try to read and parse annotations
annotions = JSON.parse(await fs.readFile(root + '/annotations.json', 'utf-8'));
} catch (e) {
console.log(e);
// Create default empty annotation file
annotations = {};
let dir = null;
try {
dir = await fs.readdir(root);
} catch (e) {
res.status(400);
res.send('Root does not exist');
}
for (let frame of dir) {
if (frame === "annotations.json") {
continue;
}
annotations[frame.split(".")[0]] = [];
}
await fs.writeFile(root + '/annotations.json', JSON.stringify(annotations, undefined, 4));
}
// On envoie le contenu du fichier index.html.
return res.sendFile(__dirname + '/static/annotator.html');
});
// Route pour envoyer les données d'annotation.
app.post('/data', async function(req, res) {
let root = req.body.root.slice(1);
if (root.startsWith('/') || root.indexOf('..') !== -1) {
res.status(400);
return res.send('Root is invalid');
}
try {
await fs.writeFile(root + '/annotations.json', JSON.stringify(req.body.annotations, undefined, 4));
} catch (e) {
res.status(400);
return res.send('' + e);
}
return res.send('Ok');
});
// Envoi des fichiers statiques.
app.use('/static', express.static('static'))
// On démarre le serveur, puis on peut y accéder dans le navigateur en allant sur http://localhost:8000
app.listen(port, ip, function() {
console.log('Started listening on ' + port);
});
}
main();