ambon commited on
Commit
ebe720b
·
verified ·
1 Parent(s): a478764

Create index.js

Browse files
Files changed (1) hide show
  1. index.js +106 -0
index.js ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (async function () {
2
+ require('dotenv').config()
3
+ const express = require('express')
4
+ const tf = require("@tensorflow/tfjs-node")
5
+ const sharp = require("sharp");
6
+ const jpeg = require("jpeg-js")
7
+ const ffmpeg = require("fluent-ffmpeg")
8
+ const { fileTypeFromBuffer } = (await import('file-type'));
9
+ const stream = require("stream")
10
+ const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
11
+ const ffprobePath = require('@ffprobe-installer/ffprobe').path;
12
+ const nsfwjs = require("nsfwjs");
13
+ const fs = require("fs")
14
+ ffmpeg.setFfprobePath(ffprobePath);
15
+ ffmpeg.setFfmpegPath(ffmpegPath);
16
+ // require("./model").loadModel()
17
+ const app = express()
18
+ const model = await nsfwjs.load("InceptionV3");
19
+ app.use(express.json())
20
+
21
+ app.all('/', async (req, res) => {
22
+ try {
23
+ const { img, auth } = req.query
24
+ if (img) {
25
+ if (process.env.AUTH) {
26
+ if (!auth || process.env.AUTH != auth) return res.send("Invalid auth code")
27
+ }
28
+ const imageBuffer = await fetch(img).then(async c => await c.arrayBuffer())
29
+ // console.log((await fileTypeFromBuffer(imageBuffer)).mime)
30
+ if ((await fileTypeFromBuffer(imageBuffer)).mime.includes("image")) {
31
+ const convertedBuffer = await sharp(Buffer.from(imageBuffer)).jpeg().toBuffer(); // convert webp to jpeg
32
+ const image = await convert(convertedBuffer)
33
+ const predictions = await model.classify(image);
34
+ image.dispose(); // Tensor memory must be managed explicitly (it is not sufficient to let a tf.Tensor go out of scope for its memory to be released).
35
+ return res.send(predictions);
36
+ } else {
37
+ let inputStream1 = new stream.PassThrough();
38
+ inputStream1.end(Buffer.from(imageBuffer));
39
+
40
+ ffmpeg.ffprobe(inputStream1, function (err, metadata) {
41
+ if (err) {
42
+ console.error(err);
43
+ return;
44
+ }
45
+
46
+ // Get a random second
47
+ const randomSecond = Math.floor(Math.random() * metadata.format.duration);
48
+
49
+ // Create a new input stream for the ffmpeg command
50
+ let inputStream2 = new stream.PassThrough();
51
+ inputStream2.end(Buffer.from(imageBuffer));
52
+
53
+ // Create a PassThrough stream to collect the output
54
+ const output = new stream.PassThrough();
55
+
56
+ // Set up the ffmpeg command
57
+ ffmpeg({ source: inputStream2 })
58
+ .seekInput(randomSecond)
59
+ .outputOptions('-vframes', '1')
60
+ .outputOptions('-f', 'image2pipe')
61
+ .outputOptions('-vcodec', 'png')
62
+ .output(output)
63
+ .on('error', console.error)
64
+ .run();
65
+
66
+ // Collect the output into a buffer
67
+ const chunks = [];
68
+ output.on('data', chunk => chunks.push(chunk));
69
+ output.on('end', async () => {
70
+ const buffer = Buffer.concat(chunks);
71
+ fs.writeFileSync("aa.png", buffer)
72
+ const convertedBuffer = await sharp(buffer).jpeg().toBuffer(); // convert webp to jpeg
73
+ const cimage = await convert(convertedBuffer)
74
+ const apredictions = await model.classify(cimage);
75
+ cimage.dispose(); // Tensor memory must be managed explicitly (it is not sufficient to let a tf.Tensor go out of scope for its memory to be released).
76
+ return res.send(apredictions);
77
+ });
78
+ });
79
+ }
80
+
81
+ }else{
82
+ return res.send('Hello World!')
83
+ }
84
+ } catch (err) {
85
+ console.log(err)
86
+ return res.status(500).json({ error: err.toString() })
87
+ }
88
+ })
89
+
90
+ const port = process.env.PORT || process.env.SERVER_PORT || 7860
91
+
92
+ app.listen(port, () => {
93
+ console.log(`Example app listening on port ${port}`)
94
+ })
95
+ const convert = async (img) => {
96
+ // Decoded image in UInt8 Byte array
97
+ const image = await jpeg.decode(img, { useTArray: true });
98
+ const numChannels = 3;
99
+ const numPixels = image.width * image.height;
100
+ const values = new Int32Array(numPixels * numChannels);
101
+ for (let i = 0; i < numPixels; i++)
102
+ for (let c = 0; c < numChannels; ++c)
103
+ values[i * numChannels + c] = image.data[i * 4 + c];
104
+ return tf.tensor3d(values, [image.height, image.width, numChannels], "int32");
105
+ };
106
+ })()