-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathindex.html
More file actions
367 lines (320 loc) · 15.3 KB
/
index.html
File metadata and controls
367 lines (320 loc) · 15.3 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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FaceX — Face Recognition in Your Browser</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0a0a0a; color: #e0e0e0; min-height: 100vh; }
.header { text-align: center; padding: 24px 16px 8px; }
.header h1 { font-size: 24px; color: #fff; }
.header h1 span { color: #10b981; }
.header p { color: #555; font-size: 13px; margin-top: 4px; }
.status { text-align: center; padding: 8px; font-size: 13px; transition: color 0.3s; }
.status.loading { color: #f59e0b; }
.status.ready { color: #10b981; }
.status.error { color: #ef4444; }
.main { max-width: 480px; margin: 0 auto; padding: 0 12px 40px; }
.video-wrap { position: relative; width: 100%; border-radius: 12px; overflow: hidden; background: #111; margin-bottom: 12px; border: 2px solid #222; transition: border-color 0.3s; }
.video-wrap.match { border-color: #10b981; }
.video-wrap.nomatch { border-color: #ef4444; }
video { width: 100%; display: block; transform: scaleX(-1); }
canvas.overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; transform: scaleX(-1); }
.controls { display: flex; gap: 8px; justify-content: center; margin-bottom: 12px; flex-wrap: wrap; }
.btn { padding: 10px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; border: none; transition: all 0.15s; }
.btn:active { transform: scale(0.97); }
.btn-go { background: #10b981; color: #fff; }
.btn-go:hover { background: #059669; }
.btn-stop { background: #ef4444; color: #fff; }
.btn-sec { background: #222; color: #aaa; border: 1px solid #333; }
.btn-sec:hover { background: #333; }
.btn:disabled { background: #1a1a1a; color: #444; cursor: not-allowed; border-color: #1a1a1a; }
.ref-bar { display: flex; align-items: center; gap: 10px; justify-content: center; margin: 10px 0; padding: 10px; background: #111; border-radius: 10px; border: 1px solid #222; }
.ref-bar canvas { width: 56px; height: 56px; border-radius: 6px; border: 1px solid #333; }
.ref-bar .label { font-size: 12px; color: #888; }
.result-bar { text-align: center; padding: 14px; margin: 10px 0; border-radius: 10px; font-size: 15px; font-weight: 600; transition: all 0.2s; }
.result-bar.match { background: #052e16; color: #10b981; border: 1px solid #166534; }
.result-bar.nomatch { background: #1c0a0a; color: #ef4444; border: 1px solid #7f1d1d; }
.result-bar.idle { background: #111; color: #555; border: 1px solid #222; }
.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 10px 0; }
.stat { text-align: center; background: #111; border-radius: 8px; padding: 8px 4px; border: 1px solid #1a1a1a; }
.stat-val { font-size: 18px; font-weight: 700; color: #10b981; }
.stat-label { font-size: 10px; color: #555; text-transform: uppercase; letter-spacing: 0.5px; }
.liveness-bar { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: #111; border-radius: 8px; margin: 8px 0; border: 1px solid #222; }
.liveness-dot { width: 10px; height: 10px; border-radius: 50%; background: #ef4444; transition: background 0.3s; }
.liveness-dot.live { background: #10b981; }
.liveness-text { font-size: 12px; color: #888; }
.info { background: #0d0d0d; border: 1px solid #1a1a1a; border-radius: 10px; padding: 14px; margin-top: 16px; }
.info h3 { font-size: 13px; color: #999; margin-bottom: 8px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
.info p { font-size: 12px; color: #555; line-height: 1.6; margin-bottom: 4px; }
.info code { background: #1a1a1a; padding: 1px 4px; border-radius: 3px; color: #10b981; font-size: 11px; }
.error-msg { text-align: center; padding: 16px; background: #1c0a0a; border: 1px solid #7f1d1d; border-radius: 10px; margin: 12px 0; color: #ef4444; font-size: 13px; display: none; }
</style>
</head>
<body>
<div class="header">
<h1>Face<span>X</span></h1>
<p>74 KB WASM. No server. Everything stays on your device.</p>
</div>
<div id="status" class="status loading">Checking browser support...</div>
<div id="errorMsg" class="error-msg"></div>
<div class="main">
<div class="video-wrap" id="videoWrap">
<video id="video" autoplay playsinline muted></video>
<canvas id="overlay" class="overlay"></canvas>
</div>
<div class="controls">
<button id="btnStart" class="btn btn-go" disabled>Start Camera</button>
<button id="btnCapture" class="btn btn-sec" disabled>Set Reference</button>
<button id="btnVerify" class="btn btn-go" disabled style="display:none">Verify</button>
<button id="btnStop" class="btn btn-stop" style="display:none">Stop</button>
</div>
<div id="refBar" class="ref-bar" style="display:none">
<canvas id="refCanvas" width="112" height="112"></canvas>
<div><div class="label">Reference face</div></div>
</div>
<div id="resultBar" class="result-bar idle">Load engine to begin</div>
<div id="livenessBar" class="liveness-bar" style="display:none">
<div id="livenessDot" class="liveness-dot"></div>
<div id="livenessText" class="liveness-text">Checking liveness...</div>
</div>
<div id="statsGrid" class="stats" style="display:none">
<div class="stat"><div class="stat-val" id="vDet">—</div><div class="stat-label">Detect</div></div>
<div class="stat"><div class="stat-val" id="vEmb">—</div><div class="stat-label">Embed</div></div>
<div class="stat"><div class="stat-val" id="vSim">—</div><div class="stat-label">Match</div></div>
<div class="stat"><div class="stat-val" id="vFps">—</div><div class="stat-label">FPS</div></div>
</div>
<div class="info">
<h3>How it works</h3>
<p><code>detect.wasm</code> (29 KB) finds faces with RetinaFace INT8 + relaxed SIMD.</p>
<p><code>facex.wasm</code> (44 KB) computes 512-dim embeddings via EdgeFace-XS.</p>
<p>5-point alignment ensures accurate matching at any head angle.</p>
<p>Total: <code>74 KB</code> engine + <code>7.7 MB</code> weights (cached after first load).</p>
</div>
</div>
<script src="detect.js"></script>
<script src="facex.js"></script>
<script src="align.js"></script>
<script src="liveness.js"></script>
<script>
const $ = id => document.getElementById(id);
const video = $('video');
const overlay = $('overlay');
const ctx = overlay.getContext('2d');
const refCanvas = $('refCanvas');
const refCtx = refCanvas.getContext('2d', { willReadFrequently: true });
let DetMod, FxMod, detH, fxH;
let refEmb = null, running = false;
const liveness = new LivenessDetector();
// Reusable canvases
const srcCv = document.createElement('canvas');
const srcCtx = srcCv.getContext('2d', { willReadFrequently: true });
const cropCv = document.createElement('canvas');
cropCv.width = 112; cropCv.height = 112;
const cropCtxA = cropCv.getContext('2d', { willReadFrequently: true });
// ===== SIMD Check =====
function checkSimd() {
try {
return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11]));
} catch(e) { return false; }
}
// ===== IndexedDB Cache =====
async function cachedFetch(url, key) {
try {
const db = await new Promise((res, rej) => {
const r = indexedDB.open('facex-cache', 1);
r.onupgradeneeded = () => r.result.createObjectStore('w');
r.onsuccess = () => res(r.result);
r.onerror = () => rej(r.error);
});
const cached = await new Promise(r => {
const tx = db.transaction('w','readonly');
const req = tx.objectStore('w').get(key);
req.onsuccess = () => r(req.result); req.onerror = () => r(null);
});
if (cached) return new Uint8Array(cached);
const buf = await fetch(url).then(r => r.arrayBuffer());
try { const tx = db.transaction('w','readwrite'); tx.objectStore('w').put(buf, key); } catch(e) {}
return new Uint8Array(buf);
} catch(e) { return new Uint8Array(await fetch(url).then(r => r.arrayBuffer())); }
}
// ===== Init =====
async function init() {
const s = $('status');
if (!checkSimd()) {
showError('WebAssembly SIMD not supported. Use Chrome 91+, Firefox 89+, or Safari 16.4+.');
return;
}
try {
s.textContent = 'Loading engines...'; s.className = 'status loading';
[DetMod, FxMod] = await Promise.all([FaceDetModule(), FaceXModule()]);
s.textContent = 'Loading weights (cached after first load)...';
const [dw, fw] = await Promise.all([
cachedFetch('det_500m_int8.bin', 'det'), cachedFetch('edgeface_xs_fp32.bin', 'emb')
]);
DetMod.FS.writeFile('/d.bin', dw); FxMod.FS.writeFile('/e.bin', fw);
detH = DetMod.cwrap('detect_init','number',['string'])('/d.bin');
fxH = FxMod.cwrap('facex_init','number',['string','string'])('/e.bin', null);
if (!detH || !fxH) throw new Error('Engine init failed');
s.textContent = 'Ready — 74 KB engines loaded'; s.className = 'status ready';
$('btnStart').disabled = false;
$('resultBar').textContent = 'Click "Start Camera" to begin';
} catch(e) { showError(e.message); }
}
function showError(msg) {
$('status').textContent = 'Error'; $('status').className = 'status error';
$('errorMsg').textContent = msg; $('errorMsg').style.display = 'block';
}
// ===== Camera =====
$('btnStart').onclick = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 320, height: 240, facingMode: 'user' }});
video.srcObject = stream;
video.onloadedmetadata = () => { overlay.width = video.videoWidth; overlay.height = video.videoHeight; };
$('btnStart').disabled = true; $('btnStart').style.display = 'none';
$('btnCapture').disabled = false;
$('resultBar').textContent = 'Look at camera and click "Set Reference"';
} catch(e) { showError('Camera access denied: ' + e.message); }
};
// ===== Detect =====
function runDetect() {
const W = video.videoWidth, H = video.videoHeight;
const ds = 160;
const detCv = document.createElement('canvas'); detCv.width = ds; detCv.height = ds;
const dCtx = detCv.getContext('2d', { willReadFrequently: true });
const scale = Math.min(ds/W, ds/H);
const nw = Math.round(W*scale), nh = Math.round(H*scale);
const dx = (ds-nw)/2, dy = (ds-nh)/2;
dCtx.fillStyle = '#000'; dCtx.fillRect(0,0,ds,ds);
dCtx.drawImage(video, dx, dy, nw, nh);
const img = dCtx.getImageData(0,0,ds,ds);
const nPx = ds*ds*3;
const inP = DetMod._malloc(nPx*4);
const heap = DetMod.HEAPF32;
const b = inP>>2;
for (let i=0; i<ds*ds; i++) {
heap[b+i*3] = img.data[i*4]/127.5-1; heap[b+i*3+1] = img.data[i*4+1]/127.5-1; heap[b+i*3+2] = img.data[i*4+2]/127.5-1;
}
const outP = DetMod._malloc(15*4*10);
const df = DetMod.cwrap('detect_faces','number',['number','number','number','number','number','number']);
const t0 = performance.now();
const n = df(detH, inP, ds, ds, outP, 10);
const detMs = performance.now() - t0;
const faces = [];
for (let i=0; i<n; i++) {
const fb = (outP>>2)+i*15;
const f = DetMod.HEAPF32;
faces.push({
x1:(f[fb]-dx)/scale, y1:(f[fb+1]-dy)/scale, x2:(f[fb+2]-dx)/scale, y2:(f[fb+3]-dy)/scale,
score:f[fb+4], kps: Array.from({length:10}, (_,j) => (f[fb+5+j]-(j%2===0?dx:dy))/scale)
});
}
DetMod._free(inP); DetMod._free(outP);
return { faces, detMs };
}
// ===== Embed =====
function runEmbed(imgData) {
const N=112*112*3;
const inP = FxMod._malloc(N*4), outP = FxMod._malloc(512*4);
const heap = FxMod.HEAPF32, b = inP>>2;
for (let i=0; i<112*112; i++) {
heap[b+i*3] = imgData.data[i*4]/127.5-1; heap[b+i*3+1] = imgData.data[i*4+1]/127.5-1; heap[b+i*3+2] = imgData.data[i*4+2]/127.5-1;
}
const t0 = performance.now();
FxMod.cwrap('facex_embed','number',['number','number','number'])(fxH, inP, outP);
const embMs = performance.now() - t0;
const emb = new Float32Array(512);
emb.set(heap.subarray(outP>>2, (outP>>2)+512));
FxMod._free(inP); FxMod._free(outP);
return { emb, embMs };
}
function cosSim(a,b) {
let d=0,na=0,nb=0;
for (let i=0;i<512;i++) { d+=a[i]*b[i]; na+=a[i]*a[i]; nb+=b[i]*b[i]; }
return d/Math.sqrt(na*nb);
}
// ===== Align + Crop =====
function alignAndCrop(face) {
const W = video.videoWidth, H = video.videoHeight;
srcCv.width = W; srcCv.height = H;
srcCtx.drawImage(video, 0, 0);
const kps5 = [];
for (let i=0; i<5; i++) kps5.push([face.kps[i*2], face.kps[i*2+1]]);
return alignFace(srcCtx, W, H, kps5, cropCtxA);
}
// ===== Draw =====
function drawFaces(faces, isMatch) {
ctx.clearRect(0,0,overlay.width,overlay.height);
for (const f of faces) {
ctx.strokeStyle = isMatch === undefined ? '#10b981' : (isMatch ? '#10b981' : '#ef4444');
ctx.lineWidth = 2;
ctx.strokeRect(f.x1, f.y1, f.x2-f.x1, f.y2-f.y1);
ctx.fillStyle = ctx.strokeStyle;
for (let j=0; j<5; j++) { ctx.beginPath(); ctx.arc(f.kps[j*2], f.kps[j*2+1], 2, 0, Math.PI*2); ctx.fill(); }
}
}
// ===== Capture Reference =====
$('btnCapture').onclick = () => {
const { faces } = runDetect();
if (!faces.length) { $('resultBar').textContent = 'No face detected — look at camera'; $('resultBar').className = 'result-bar nomatch'; return; }
const aligned = alignAndCrop(faces[0]);
refCtx.putImageData(aligned, 0, 0);
const { emb } = runEmbed(aligned);
refEmb = emb;
$('refBar').style.display = 'flex';
$('btnVerify').style.display = 'inline-block'; $('btnVerify').disabled = false;
$('resultBar').textContent = 'Reference set. Click "Verify".'; $('resultBar').className = 'result-bar idle';
drawFaces(faces);
liveness.reset();
};
// ===== Verify Loop =====
$('btnVerify').onclick = () => {
running = true;
$('btnVerify').style.display = 'none'; $('btnStop').style.display = 'inline-block';
$('btnCapture').disabled = true;
$('statsGrid').style.display = 'grid'; $('livenessBar').style.display = 'flex';
loop();
};
$('btnStop').onclick = () => {
running = false;
$('btnStop').style.display = 'none'; $('btnVerify').style.display = 'inline-block'; $('btnVerify').disabled = false;
$('btnCapture').disabled = false;
ctx.clearRect(0,0,overlay.width,overlay.height);
$('videoWrap').className = 'video-wrap';
};
function loop() {
if (!running) return;
const tAll = performance.now();
const { faces, detMs } = runDetect();
if (!faces.length) {
drawFaces([]);
$('resultBar').textContent = 'No face detected'; $('resultBar').className = 'result-bar idle';
$('videoWrap').className = 'video-wrap';
$('vDet').textContent = detMs.toFixed(0)+'ms';
liveness.update(null);
requestAnimationFrame(loop); return;
}
const aligned = alignAndCrop(faces[0]);
const { emb, embMs } = runEmbed(aligned);
const sim = cosSim(refEmb, emb);
const match = sim > 0.3;
const totalMs = performance.now() - tAll;
// Liveness
const live = liveness.update(faces[0]);
$('livenessDot').className = 'liveness-dot' + (live.alive ? ' live' : '');
$('livenessText').textContent = live.reason;
drawFaces(faces, match);
$('resultBar').textContent = match ? `MATCH — ${(sim*100).toFixed(1)}%` : `NO MATCH — ${(sim*100).toFixed(1)}%`;
$('resultBar').className = 'result-bar ' + (match ? 'match' : 'nomatch');
$('videoWrap').className = 'video-wrap ' + (match ? 'match' : 'nomatch');
$('vDet').textContent = detMs.toFixed(0)+'ms';
$('vEmb').textContent = embMs.toFixed(0)+'ms';
$('vSim').textContent = (sim*100).toFixed(1)+'%';
$('vFps').textContent = (1000/totalMs).toFixed(0);
requestAnimationFrame(loop);
}
init();
</script>
</body>
</html>