-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
310 lines (290 loc) · 7.52 KB
/
script.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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
const video = document.getElementById('video');
const videoUpload = document.getElementById('videoUpload');
const cam = document.getElementById('cam');
const TESTER = document.getElementById('tester');
const canvasDiv = document.getElementById('canvasDiv');
let appearElement = document.getElementById('appear');
let actuallyElement = document.getElementById('actually');
let faceMatcher = null;
let expressionCollection = [];
let landmarksCollection = [];
let numDetections = 0;
let count = 0;
let videoName = '';
let index = 0;
let start = Date.now();
let isCam = false;
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
faceapi.nets.faceExpressionNet.loadFromUri('/models'),
]).then(console.log('models loaded'));
let videoSelection = new Promise((resolve, reject) => {
cam.addEventListener('click', () => {
navigator.mediaDevices
.getUserMedia({ video: {} })
.then((stream) => {
video.srcObject = stream;
})
.catch((err) => console.error(err));
video.addEventListener(
'loadeddata',
() => {
firebase
.firestore()
.collection('Webcam')
.doc(start.toString())
.set({ name: start.toString() })
.then(() => console.log('Cam name added'))
.catch((error) => console.warn(error));
isCam = true;
resolve();
},
false
);
});
videoUpload.addEventListener('change', () => {
if (videoUpload) {
let videoURL = window.URL.createObjectURL(videoUpload.files[0]);
video.setAttribute('src', videoURL);
setTimeout(() => {
console.log('video readyState is ' + video.readyState);
videoName = videoUpload.value.substr(
videoUpload.value.lastIndexOf('\\') + 1
);
// add field name to enable document query
firebase
.firestore()
.collection('Emotion')
.doc(videoName)
.set({ name: videoName })
.then(() => console.log('added'))
.catch((error) => console.warn(error));
resolve();
}, 1000);
}
});
});
// plotjs and data preparation
let n = 100;
let x = [];
let y = [];
let updatedData = [];
const expr = [
'happy',
'neutral',
'surprised',
'sad',
'angry',
'fearful',
'disgusted',
];
const weight = [5, 1, 10, 10, 10, 10, 10];
const color = [
'DodgerBlue',
'Orange',
'MediumSeaGreen',
'Tomato',
'SlateBlue',
'Gray',
'Violet',
];
const series = [];
for (i = 0; i < expr.length; i++) {
series[i] = [];
}
// initiate animation coefficients
for (i = 0; i < n; i++) {
x[i] = i + 1; // x takes values from 1 to n
y[i] = 0; // y takes values of 0
// fill expression matrix with 7 by n zeros
series.forEach((element) => {
element[i] = 0; // zero out a column of 7 numbers
});
}
let data = [];
for (let i = 0; i < series.length; i++) {
data[i] = {
x: x,
y: series[i],
stackgroup: 'one',
legendgroup: expr[i],
name: expr[i],
};
}
let layout = {
title: 'Appear to be Diagram',
showlegend: true,
yaxis: { range: [0, 1] },
};
Plotly.newPlot(TESTER, data, layout);
videoSelection
.then(() => {
let canvas = faceapi.createCanvasFromMedia(video);
if (!document.getElementById('vidCanvas')) {
canvas.id = 'vidCanvas';
canvasDiv.insertBefore(canvas, canvasDiv.childNodes[1]);
} else {
canvas = document.getElementById('vidCanvas');
}
let displaySize = {
width: video.offsetWidth,
height: video.offsetHeight,
};
faceapi.matchDimensions(canvas, displaySize);
let firstPlay = true;
// method to be looped
detectFrame = () => {
faceapi
.detectSingleFace(video, new faceapi.TinyFaceDetectorOptions())
.withFaceLandmarks()
.withFaceExpressions()
.then((detections) => {
if (firstPlay) {
video.play();
video.loop = false;
firstPlay = false;
}
function update() {
Plotly.animate(
TESTER,
{
data: updatedData,
},
{
transition: {
duration: 0,
},
frame: {
duration: 0,
redraw: false,
},
}
);
// firestore
firebaseUpdate(detections);
}
if (detections != undefined) {
analysis(detections);
requestAnimationFrame(update);
console.log('detection updated');
const resizedDetections = faceapi.resizeResults(detections, {
width: video.offsetWidth,
height: video.offsetHeight,
});
canvas
.getContext('2d')
.clearRect(0, 0, canvas.width, canvas.height);
faceapi.draw.drawDetections(canvas, resizedDetections);
faceapi.draw.drawFaceLandmarks(canvas, resizedDetections);
faceapi.draw.drawFaceExpressions(canvas, resizedDetections);
} else {
canvas
.getContext('2d')
.clearRect(0, 0, canvas.width, canvas.height);
console.log('detections is undefined ');
}
detectFrame();
})
.catch(() => {
console.log('error');
}); //0.1 second per frame
};
// begin inference
detectFrame();
})
.catch((error) => {
console.log(error);
});
function analysis(detections) {
let accum = 0;
index++;
let expressions = detections.expressions;
// prep the expression arrays
for (let i = 0; i < series.length; i++) {
accum += expressions[expr[i]];
series[i].push(accum);
series[i].shift();
}
for (let i = 0; i < series.length; i++) {
updatedData[i] = { y: series[i] };
}
// you appear to be ***
// index of the emotion with the largest probability
let repExp = Object.keys(expressions).reduce((a, b) =>
expressions[a] > expressions[b] ? a : b
);
appearElement.innerHTML = 'appear to be ' + repExp;
appearElement.style = 'color:' + color[expr.indexOf(repExp)];
// you actually are ***
// calculate area of expressions
let areas = [];
series.forEach((element, idx) => {
areas[idx] = element.slice(-100).reduce((a, b) => a + b, 0); // sum of last 10
});
// subtract area trick
for (let k = series.length - 1; k > 0; k--) {
areas[k] = areas[k] - areas[k - 1];
}
// weighted area
for (let k = 0; k < series.length; k++) {
areas[k] = areas[k] * weight[k];
}
let maxAreaIndex = areas.indexOf(Math.max(...areas));
actuallyElement.innerHTML = 'actually ' + expr[maxAreaIndex];
actuallyElement.style = 'color:' + color[maxAreaIndex];
}
// write to firestore database
async function firebaseUpdate(detections) {
let expressions = detections.expressions;
expressions.timeFrame = (Date.now() - start) / 1000;
expressionCollection.push(JSON.stringify(expressions));
numDetections++;
//Firebase module
//send the extracted info and initialize the arrays for every 10 frame
if (index % 10 == 0) {
await sendStuffToFirebase();
count++;
expressionCollection = [];
}
//Firebase module ends
}
async function sendStuffToFirebase() {
if (!isCam) {
objectToPush = {
name: videoName,
detections: expressionCollection,
numDetections: numDetections,
};
// Pushes video name, expression data, number of frames, time stamps for each frame (and landmarks)
await firebase
.firestore()
.collection('Emotion')
.doc(videoName)
.collection(count.toString())
.doc('data')
.set(objectToPush)
.then(() => console.log('Saved to DB at frame ' + numDetections))
.catch((error) => {
console.warn(error);
});
} else {
if (count == 0) console.log(start);
objectToPush = {
name: start.toString(),
detections: expressionCollection,
numDetections: numDetections,
};
await firebase
.firestore()
.collection('Webcam')
.doc(start.toString())
.collection(count.toString())
.doc('data')
.set(objectToPush)
.then(() => console.log('Saved to DB at frame ' + numDetections))
.catch((error) => {
console.warn(error);
});
}
}