-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
39 lines (31 loc) · 1.13 KB
/
index.js
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
import express from "express";
import multer from "multer";
import { decode } from "jpeg-js";
import tfjs from "@tensorflow/tfjs-node";
import { load } from "nsfwjs";
import gracefulShutdown from "http-graceful-shutdown";
const app = express();
const upload = multer();
let _model = await load();
const convert = async (img) => {
// Decoded image in UInt8 Byte array
const image = decode(img);
const numChannels = 3;
const numPixels = image.width * image.height;
const values = new Int32Array(numPixels * numChannels);
for (let i = 0; i < numPixels; i++)
for (let c = 0; c < numChannels; ++c)
values[i * numChannels + c] = image.data[i * 4 + c];
return tfjs.tensor3d(values, [image.height, image.width, numChannels], "int32");
};
app.post("/", upload.single("file"), async (req, res) => {
if (!req.file) res.status(400).send("Missing image multipart/form-data");
else {
const image = await convert(req.file.buffer);
const predictions = await _model.classify(image);
image.dispose();
res.json(predictions);
}
});
app.listen(8080, () => console.info(`running: http://0.0.0.0:8080`,))
gracefulShutdown(app)