-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp.js
197 lines (168 loc) · 6.3 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
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
const tf = require('@tensorflow/tfjs-node')
const faceapi = require('@vladmandic/face-api')
const Canvas = require('canvas')
const path = require('path')
const Koa = require('koa')
const Static = require('koa-static')
const Router = require('@koa/router')
const bodyParser = require('koa-bodyparser')
const moment = require('moment')
const sqlite3 = require('sqlite3')
const { open } = require('sqlite')
const Uuid = require('uuid')
const fs = require('fs')
const app = new Koa()
const router = new Router()
const debugLevel = process.env.DEBUG || 1
const rollThreshold = process.env.ROLL_THRESHOLD || 15
const pitchThreshold = process.env.PITCH_THRESHOLD || 10
const yawThreshold = process.env.YAW_THRESHOLD || 45
const bip0039 = JSON.parse(fs.readFileSync('bip-0039.json'))
const randomSemantic = () => {
let result = [];
let usedIndices = new Set();
while (result.length < 4) {
let randomIndex = Math.floor(Math.random() * bip0039.length);
if (!usedIndices.has(randomIndex)) {
result.push(bip0039[randomIndex]);
usedIndices.add(randomIndex);
}
}
return result.join(' ')
}
async function openDb() {
return open({
filename: './database.db',
driver: sqlite3.Database
})
}
const init = async () => {
await faceapi.tf.setBackend('tensorflow');
await faceapi.tf.ready();
await faceapi.nets.faceRecognitionNet.loadFromDisk(path.join(process.cwd(), 'models'))
await faceapi.nets.faceLandmark68Net.loadFromDisk(path.join(process.cwd(), 'models'))
await faceapi.nets.ssdMobilenetv1.loadFromDisk(path.join(process.cwd(), 'models'))
await faceapi.nets.faceExpressionNet.loadFromDisk(path.join(process.cwd(), 'models'))
console.log('Models Loaded')
const db = await openDb()
const createSchema = `
CREATE TABLE IF NOT EXISTS biometrics (
uuid VARCHAR(36) PRIMARY KEY,
timestamp TEXT,
semantic VARCHAR(64),
descriptor TEXT,
UNIQUE (semantic)
)`
await db.run(createSchema)
await db.close()
console.log('Database Ready')
}
init()
const insertData = async (db, descriptor) => {
const uuid = Uuid.v4()
const timestamp = moment().toISOString()
const semantic = randomSemantic()
try {
const sql = `INSERT INTO biometrics (uuid, timestamp, descriptor, semantic) VALUES (?, ?, ?, ?)`
await db.run(sql, [uuid, timestamp, descriptor, semantic])
if (debugLevel > 0) {
console.log(`Entry ${uuid} added to the table: ${timestamp}`)
}
return {
uuid, semantic
}
} catch (err) {
console.error(err.message)
}
}
const queryDataAndCount = async (db) => {
try {
// Query to select the rows
const sqlQuery = `SELECT uuid, descriptor, semantic FROM biometrics ORDER BY timestamp DESC`;
const entries = (await db.all(sqlQuery)) || [];
// Query to count the rows
const sqlCount = `SELECT COUNT(*) AS count FROM biometrics`;
const countResult = await db.get(sqlCount);
const count = countResult.count;
return { entries, count };
} catch (err) {
console.error(err.message);
}
}
app.use(bodyParser())
app.use(Static(path.join(process.cwd(), 'public')))
function float32ArrayToBase64(float32Array) {
let buffer = float32Array.buffer
let binary = ''
let bytes = new Uint8Array(buffer)
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i])
}
return Buffer.from(binary, 'binary').toString('base64')
}
function base64ToFloat32Array(base64) {
let binary = Buffer.from(base64, 'base64').toString('binary')
let buffer = new ArrayBuffer(binary.length)
let bytes = new Uint8Array(buffer)
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i)
}
return new Float32Array(buffer)
}
const generateDescriptor = async (img) => {
const detection = await faceapi.detectSingleFace(img).withFaceLandmarks().withFaceDescriptor()
return float32ArrayToBase64(detection.descriptor)
}
router.post('/detect', async (ctx, next) => {
const base64Data = ctx.request.body.base64.replace(/^data:image\/jpeg;base64,/, "");
const buffer = Buffer.from(base64Data, 'base64')
image = await Canvas.loadImage(buffer)
const canvas = Canvas.createCanvas(image.width, image.height)
const canvasCtx = canvas.getContext('2d')
canvasCtx.drawImage(image, 0, 0, image.width, image.height)
const displaySize = { width: image.width, height: image.height }
faceapi.matchDimensions(canvas, displaySize)
const decodeT = faceapi.tf.node.decodeImage(buffer, 3)
const expandT = faceapi.tf.expandDims(decodeT, 0)
const detection = await faceapi.detectSingleFace(expandT).withFaceLandmarks().withFaceDescriptor().withFaceExpressions()
const resizedDetection = faceapi.resizeResults(detection, displaySize)
const expression = ((Object.entries(detection.expressions).reduce((acc, val) => ((val[1] > acc[1]) ? val : acc), ['', 0])).slice(0, 2))
const db = await openDb()
const { entries, count } = await queryDataAndCount(db)
const labeledFaceDescriptors = entries.map(entry => {
return new faceapi.LabeledFaceDescriptors(`${entry.uuid}|${entry.semantic}`, [base64ToFloat32Array(entry.descriptor)])
})
let result
if (labeledFaceDescriptors.length > 0) {
const faceMatcher = new faceapi.FaceMatcher(labeledFaceDescriptors, 0.4)
result = faceMatcher.findBestMatch(resizedDetection.descriptor)
const [label, semantic] = result._label.split('|')
result = { label, semantic, distance: result._distance }
} else {
result = { label: 'unknown', semantic: 'unknown', distance: 1 }
}
const { roll, pitch, yaw } = detection.angle
if (expression[0] != 'neutral' || expression[1] < 0.70 || Math.abs(roll) > rollThreshold || Math.abs(pitch) > pitchThreshold || Math.abs(yaw) > yawThreshold) {
result = { label: 'unknown', semantic: 'unknown', distance: 1 }
} else {
if (!result || !result.label || result.label == 'unknown') {
try {
const { uuid, semantic } = await insertData(db, await generateDescriptor(expandT))
result = { label: uuid, semantic, distance: 0 }
} catch (err) {
result = { label: 'unknown', semantic: 'unknown', distance: 1 }
}
}
}
await db.close()
ctx.body = { detection, result, expression }
})
router.get('/wordlist', async (ctx, next) => {
ctx.status = 200
ctx.type = 'application/json'
ctx.body = bip0039
})
app
.use(router.routes())
.use(router.allowedMethods())
.listen(process.env.PORT || 3000)