-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
98 lines (87 loc) · 3.08 KB
/
app.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
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
const express = require("express");
const app = express();
const multer = require("multer");
const upload = multer({
storage: multer.diskStorage({}),
fileFilter: (req, file, cb) => {
let ext = path.extname(file.originalname);
if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png") {
cb(new Error("File type is not supported"), false);
return;
}
cb(null, true);
},
});
//MS Specific
const axios = require("axios").default;
const async = require("async");
const fs = require("fs");
const https = require("https");
const path = require("path");
const createReadStream = require("fs").createReadStream;
const sleep = require("util").promisify(setTimeout);
const ComputerVisionClient =
require("@azure/cognitiveservices-computervision").ComputerVisionClient;
const ApiKeyCredentials = require("@azure/ms-rest-js").ApiKeyCredentials;
require("dotenv").config({ path: "./config/.env" });
const cloudinary = require("cloudinary").v2;
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.CLOUD_API_KEY,
api_secret: process.env.CLOUD_API_SECRET,
});
const key = process.env.MS_COMPUTER_VISION_SUBSCRIPTION_KEY;
const endpoint = process.env.MS_COMPUTER_VISION_ENDPOINT;
const faceEndpoint = process.env.MS_FACE_ENDPOINT + "/face/v1.0/detect";
const subscriptionKey = process.env.MS_FACE_SUB_KEY;
const computerVisionClient = new ComputerVisionClient(
new ApiKeyCredentials({ inHeader: { "Ocp-Apim-Subscription-Key": key } }),
endpoint
);
//Server Setup
app.set("view engine", "ejs");
app.use(express.static("public"));
//Routes
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.post("/", upload.single("file-to-upload"), async (req, res) => {
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);
const imageUrl = result.secure_url;
axios({
method: "post",
url: faceEndpoint,
params: {
returnFaceId: true,
returnFaceAttributes:
"age,gender,headPose,smile,facialHair,glasses," +
"emotion,hair,makeup,occlusion,accessories,blur,exposure,noise",
},
data: {
url: imageUrl,
},
headers: { "Ocp-Apim-Subscription-Key": subscriptionKey },
})
.then(function (response) {
// console.log("Status text: " + response.status);
// console.log("Status text: " + response.statusText);
console.log(response.data);
res.render("result.ejs", {
data: response.data.length
? response.data[0].faceAttributes.emotion
: null,
img: imageUrl,
});
})
.catch(function (error) {
res.redirect("/");
console.log(error);
});
} catch (err) {
res.redirect("/");
console.log(err);
}
});
app.listen(process.env.PORT || 8000);