-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
204 lines (190 loc) · 5.97 KB
/
Copy pathscript.js
File metadata and controls
204 lines (190 loc) · 5.97 KB
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
const video = document.getElementById("video");
let myInterval = null;
let streaming = null;
let statusInsert = document.getElementsByClassName("face-memory").length > 0 ? true : false;
let statusGet = document.getElementsByClassName("face-scan").length > 0 ? true : false;
let statusDetectionScan = document.getElementsByClassName("face-scan").length > 0 ? true : false;
let faceDataFromDatabase = [];
let refPerson = "";
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri("/models"),
faceapi.nets.faceLandmark68Net.loadFromUri("/models"),
faceapi.nets.faceRecognitionNet.loadFromUri("/models"),
faceapi.nets.faceExpressionNet.loadFromUri("/models"),
]).then(function () {
if (document.getElementsByClassName("face-memory").length > 0) {
document.getElementById("open-camera").addEventListener("click", (event) => {
if (document.getElementById("ref_person").value !== "") {
startVideo();
} else {
Swal.fire({
position: "center",
icon: "error",
title: "Please enter in your personal references before collecting your face.",
showConfirmButton: false,
timer: 5000,
timerProgressBar: true,
});
}
});
} else {
startVideo();
}
});
function startVideo() {
navigator.getUserMedia(
{ video: {} },
function (stream) {
video.srcObject = stream;
streaming = stream;
}, function (error) {
console.log(error);
});
}
video.addEventListener("play", () => {
const canvas = faceapi.createCanvasFromMedia(video);
document.getElementsByClassName("center-screen")[0].append(canvas);
const displaySize = { width: video.width, height: video.height };
faceapi.matchDimensions(canvas, displaySize);
myInterval = setInterval(async () => {
const minProbability = 0.8;
const detections = await faceapi
.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions())
.withFaceLandmarks()
.withFaceExpressions();
const resizedDetections = faceapi.resizeResults(detections, displaySize);
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, minProbability);
const detectionsToDb = await faceapi
.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions())
.withFaceLandmarks()
.withFaceDescriptors();
const obj = await saveFaceDataToMySQL(detectionsToDb);
if (statusInsert) {
await insertToDb(obj);
}
if (detectionsToDb.length > 0 && statusDetectionScan === true) {
const returnStatus = await faceMatcher(detectionsToDb);
if (!returnStatus) {
statusGet = true;
} else {
statusDetectionScan = false;
Swal.fire({
position: "center",
icon: "success",
title: "Found a face that matched data in the database. " + refPerson.toUpperCase(),
showConfirmButton: false,
timer: 5000,
timerProgressBar: true,
}).then((result) => {
if (result.dismiss === Swal.DismissReason.timer) {
location.reload();
}
});
}
}
}, 100);
});
async function saveFaceDataToMySQL(detections) {
return detections.map((detection) => {
return {
faceId: generateUniqueId(),
landmarks: detection,
timestamp: new Date().toISOString(),
score: detection.detection.score,
};
});
}
async function insertToDb(obj) {
if (obj.length > 0 && obj[0].score > 0.8) {
$.ajax({
url: "insert.php", //endpoint or endpoint API
type: "POST",
data: {
faceId: obj[0].faceId,
timestamp: obj[0].timestamp,
landmarks: JSON.stringify(obj[0].landmarks),
ref_person: document.getElementById("ref_person").value,
},
beforeSend: function () {
statusInsert = false;
},
cache: false,
dataType: "json",
success: function (result) {
if (result["status"] === "success") {
Swal.fire({
position: "center",
icon: "success",
title: "Your work has been saved",
showConfirmButton: false,
timer: 2500,
timerProgressBar: true,
}).then((result) => {
if (result.dismiss === Swal.DismissReason.timer) {
// statusInsert = true;
location.href = 'index.html';
}
});
}
},
});
}
}
async function getFromDb() {
return $.ajax({
url: "get.php",
type: "GET", //endpoint or endpoint API
beforeSend: function () {
statusGet = false;
},
cache: false,
dataType: "json",
});
}
function stopStream(stream) {
stream.getVideoTracks().forEach(function (track) {
track.stop();
});
}
async function faceMatcher(face_cam) {
if (statusGet && faceDataFromDatabase.length <= 0) {
faceDataFromDatabase = await getFromDb();
} else {
if (faceDataFromDatabase["status"] === "success" && faceDataFromDatabase["response"].length > 0) {
if (face_cam[0].landmarks !== undefined) {
for (let faceData of faceDataFromDatabase["response"]) {
if (
await landmarksMatches(
face_cam[0].landmarks._positions,
JSON.parse(faceData.landmarks).landmarks._positions
)
) {
refPerson = faceData.ref_person;
return true;
}
}
}
}
}
return false;
}
async function landmarksMatches(landmarks1, landmarks2) {
const threshold = 10;
for (let i = 0; i < landmarks1.length; i++) {
const point1 = landmarks1[i];
const point2 = landmarks2[i];
const distance = Math.sqrt(
Math.pow(point1._x - point2._x, 2) + Math.pow(point1._y - point2._y, 2)
);
if (distance > threshold) {
return false;
}
}
return true;
}
function generateUniqueId() {
return new Date().getTime() + Math.random();
}