Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.
C avx-512avx2biometricsc99computer-visioncpu-inferencedeep-learningedge-aiembedded-aiface-embeddingface-recognitionface-verificationlow-latencyonnx-runtimeproduction-readysimdzero-dependencies
Desktop: detect + align + box overlay. Mobile: center crop.
atynovc0624b506a36
diff --git a/docs/demo/index.html b/docs/demo/index.htmlindex e9ac5a4..5044fa3 100644--- a/docs/demo/index.html+++ b/docs/demo/index.html@@ -13,7 +13,9 @@ h1 span { color: #10b981; }#log { color: #f59e0b; font-size: 13px; margin-bottom: 12px; min-height: 20px; }#log.ok { color: #10b981; }#log.err { color: #ef4444; }-video { width: 100%; max-width: 400px; border-radius: 10px; background: #111; display: block; margin: 0 auto 12px; }+.vid-wrap { position: relative; display: inline-block; max-width: 400px; width: 100%; margin-bottom: 12px; }+video { width: 100%; border-radius: 10px; background: #111; display: block; }+canvas.overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; border-radius: 10px; }.btns { display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; margin-bottom: 12px; }button { padding: 10px 20px; border-radius: 8px; border: none; font-size: 14px; font-weight: 600; cursor: pointer; }button:disabled { opacity: 0.3; cursor: default; }@@ -25,16 +27,19 @@ button:disabled { opacity: 0.3; cursor: default; }#result.nomatch { background: #1c0a0a; color: #ef4444; }#result.idle { background: #111; color: #555; }.stats { display: flex; gap: 12px; justify-content: center; font-size: 13px; color: #888; }-canvas { display: none; }+canvas.hidden { display: none; }</style></head><body><h1>Face<span>X</span> Demo</h1>-<p class="sub">Face embedding in the browser. 44 KB WASM.</p>+<p class="sub">Face recognition in the browser. 44 KB WASM. No server.</p><div id="log">Loading...</div>-<video id="vid" autoplay playsinline muted></video>+<div class="vid-wrap">+ <video id="vid" autoplay playsinline muted></video>+ <canvas id="overlay" class="overlay"></canvas>+</div><div class="btns"><button id="bCam" class="green" disabled>Start Camera</button>@@ -50,63 +55,186 @@ canvas { display: none; }<span id="sFps">—</span></div>-<canvas id="crop" width="112" height="112"></canvas>+<canvas id="crop" class="hidden" width="112" height="112"></canvas>+<canvas id="src" class="hidden"></canvas>+<script src="detect.js"></script><script src="facex.js"></script><script>const vid = document.getElementById('vid');+const overlay = document.getElementById('overlay');+const oCtx = overlay.getContext('2d');const crop = document.getElementById('crop');const cropCtx = crop.getContext('2d', {willReadFrequently: true});+const srcCv = document.getElementById('src');+const srcCtx = srcCv.getContext('2d', {willReadFrequently: true});const log = document.getElementById('log');const result = document.getElementById('result');-let FxMod, fxH, refEmb = null, running = false;+let DetMod, FxMod, detH, fxH;+let refEmb = null, running = false;+const isMobile = /iPhone|iPad|Android/i.test(navigator.userAgent);function setLog(msg, cls) { log.textContent = msg; log.className = cls || ''; }-// ===== Load embedding engine only (no detector — simple center crop) =====-async function init() {- try {- setLog('Loading FaceX engine (44 KB)...');- FxMod = await FaceXModule();+// ===== ArcFace 5-point alignment =====+const REF = [[38.2946,51.6963],[73.5318,51.5014],[56.0252,71.7366],[41.5493,92.3655],[70.7299,92.2041]];- setLog('Downloading model (7 MB, cached after first load)...');- const data = await loadCached('edgeface_xs_fp32.bin', 'facex_emb_v1');- FxMod.FS.writeFile('/w.bin', data);+function alignFace(kps5) {+ const W = vid.videoWidth, H = vid.videoHeight;+ srcCv.width = W; srcCv.height = H;+ srcCtx.drawImage(vid, 0, 0);- setLog('Initializing...');- fxH = FxMod.cwrap('facex_init', 'number', ['string', 'string'])('/w.bin', null);- if (!fxH) throw new Error('Init failed');+ // Similarity transform: src(kps5) → dst(REF)+ const src = kps5, dst = REF, n = 5;+ let sx=0,sy=0,dx=0,dy=0;+ for (let i=0;i<n;i++) { sx+=src[i][0];sy+=src[i][1];dx+=dst[i][0];dy+=dst[i][1]; }+ sx/=n;sy/=n;dx/=n;dy/=n;+ let n1=0,n2=0,den=0;+ for (let i=0;i<n;i++) {+ const sxc=src[i][0]-sx,syc=src[i][1]-sy,dxc=dst[i][0]-dx,dyc=dst[i][1]-dy;+ n1+=dxc*sxc+dyc*syc; n2+=dxc*syc-dyc*sxc; den+=sxc*sxc+syc*syc;+ }+ const a=n1/den,b=n2/den,tx=dx-a*sx+b*sy,ty=dy-b*sx-a*sy;+ // Inverse+ const det=a*a+b*b,ai=a/det,bi=b/det,txi=-(ai*tx+bi*ty),tyi=bi*tx-ai*ty;- setLog('Ready', 'ok');- document.getElementById('bCam').disabled = false;- } catch(e) {- setLog('Error: ' + e.message, 'err');+ const srcData = srcCtx.getImageData(0,0,W,H);+ const dstData = cropCtx.createImageData(112,112);+ const s = srcData.data, d = dstData.data;+ for (let dy=0;dy<112;dy++) for (let dx=0;dx<112;dx++) {+ const sx2=ai*dx-bi*dy+txi, sy2=bi*dx+ai*dy+tyi;+ const x0=Math.floor(sx2),y0=Math.floor(sy2),fx=sx2-x0,fy=sy2-y0;+ if (x0>=0&&x0+1<W&&y0>=0&&y0+1<H) {+ const i00=(y0*W+x0)*4,i10=(y0*W+x0+1)*4,i01=((y0+1)*W+x0)*4,i11=((y0+1)*W+x0+1)*4;+ const di=(dy*112+dx)*4;+ for (let c=0;c<3;c++) d[di+c]=Math.round(s[i00+c]*(1-fx)*(1-fy)+s[i10+c]*fx*(1-fy)+s[i01+c]*(1-fx)*fy+s[i11+c]*fx*fy);+ d[di+3]=255;+ }+ }+ cropCtx.putImageData(dstData,0,0);+ return dstData;+}++// ===== Center crop fallback (mobile) =====+function centerCrop() {+ const W = vid.videoWidth, H = vid.videoHeight;+ const sz = Math.min(W,H)*0.6, sx=(W-sz)/2, sy=(H-sz)/2;+ cropCtx.drawImage(vid, sx, sy, sz, sz, 0, 0, 112, 112);+ return cropCtx.getImageData(0,0,112,112);+}++// ===== Detect faces (desktop only) =====+function detectFaces() {+ const W = vid.videoWidth, H = vid.videoHeight, 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), 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(vid,dx,dy,nw,nh);+ const img=dCtx.getImageData(0,0,ds,ds);++ const nPx=ds*ds*3, inP=DetMod._malloc(nPx*4), h=DetMod.HEAPF32, base=inP>>2;+ for (let i=0;i<ds*ds;i++) { h[base+i*3]=img.data[i*4]/127.5-1; h[base+i*3+1]=img.data[i*4+1]/127.5-1; h[base+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 nf=df(detH,inP,ds,ds,outP,10);+ const detMs=performance.now()-t0;++ const faces=[];+ for (let i=0;i<nf;i++) {+ const fb=(outP>>2)+i*15, 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 };+}++// ===== Draw face box =====+function drawBox(face, color) {+ oCtx.clearRect(0,0,overlay.width,overlay.height);+ if (!face) return;+ oCtx.strokeStyle = color; oCtx.lineWidth = 2;+ oCtx.strokeRect(face.x1,face.y1,face.x2-face.x1,face.y2-face.y1);+ oCtx.fillStyle = color;+ for (let j=0;j<5;j++) { oCtx.beginPath(); oCtx.arc(face.kps[j*2],face.kps[j*2+1],3,0,Math.PI*2); oCtx.fill(); }+}++// ===== Embed =====+function embed(imgData) {+ const N=112*112*3, inP=FxMod._malloc(N*4), outP=FxMod._malloc(512*4);+ const h=FxMod.HEAPF32, b=inP>>2, px=imgData.data;+ for (let i=0;i<112*112;i++) { h[b+i*3]=px[i*4]/127.5-1; h[b+i*3+1]=px[i*4+1]/127.5-1; h[b+i*3+2]=px[i*4+2]/127.5-1; }+ const t0=performance.now();+ FxMod.cwrap('facex_embed','number',['number','number','number'])(fxH,inP,outP);+ const ms=performance.now()-t0;+ const emb=new Float32Array(512);+ emb.set(h.subarray(outP>>2,(outP>>2)+512));+ FxMod._free(inP); FxMod._free(outP);+ return { emb, ms };+}++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); }++// ===== Get face: detect+align on desktop, center crop on mobile =====+function getFace() {+ if (!isMobile && detH) {+ const { faces, detMs } = detectFaces();+ if (faces.length > 0) {+ const f = faces[0];+ const kps5 = [];+ for (let i=0;i<5;i++) kps5.push([f.kps[i*2], f.kps[i*2+1]]);+ const aligned = alignFace(kps5);+ return { imgData: aligned, face: f, detMs };+ }+ return { imgData: null, face: null, detMs };}+ return { imgData: centerCrop(), face: null, detMs: 0 };+}++// ===== Init =====+async function init() {+ try {+ setLog('Loading engines...');++ if (!isMobile) {+ // Desktop: load detector + embedder+ [DetMod, FxMod] = await Promise.all([FaceDetModule(), FaceXModule()]);+ setLog('Downloading weights...');+ const [dw, fw] = await Promise.all([loadCached('det_500m_int8.bin','det'), loadCached('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('Init failed');+ setLog('Ready — detect + embed (desktop mode)', 'ok');+ } else {+ // Mobile: embedder only+ FxMod = await FaceXModule();+ setLog('Downloading model (7 MB)...');+ const fw = await loadCached('edgeface_xs_fp32.bin','emb');+ FxMod.FS.writeFile('/e.bin', fw);+ fxH = FxMod.cwrap('facex_init','number',['string','string'])('/e.bin', null);+ if (!fxH) throw new Error('Init failed');+ setLog('Ready — embed only (mobile mode, hold face centered)', 'ok');+ }+ document.getElementById('bCam').disabled = false;+ } catch(e) { setLog('Error: ' + e.message, 'err'); }}-// ===== IndexedDB cache =====async function loadCached(url, key) {try {- const db = await new Promise((r, j) => {- const q = indexedDB.open('facex', 1);- q.onupgradeneeded = () => q.result.createObjectStore('w');- q.onsuccess = () => r(q.result);- q.onerror = () => j(q.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) { setLog('Loaded from cache', 'ok'); return new Uint8Array(cached); }- const buf = await fetch(url).then(r => r.arrayBuffer());- try { db.transaction('w','readwrite').objectStore('w').put(buf, key); } catch(e) {}+ const db = await new Promise((r,j)=>{const q=indexedDB.open('facex',1);q.onupgradeneeded=()=>q.result.createObjectStore('w');q.onsuccess=()=>r(q.result);q.onerror=()=>j(q.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{db.transaction('w','readwrite').objectStore('w').put(buf,key);}catch(e){}return new Uint8Array(buf);- } catch(e) {- return new Uint8Array(await fetch(url).then(r => r.arrayBuffer()));- }+ } catch(e) { return new Uint8Array(await fetch(url).then(r=>r.arrayBuffer())); }}// ===== Camera =====@@ -114,83 +242,50 @@ document.getElementById('bCam').onclick = async () => {try {document.getElementById('bCam').textContent = 'Starting...';document.getElementById('bCam').disabled = true;- const stream = await navigator.mediaDevices.getUserMedia({- video: { facingMode: 'user', width: {ideal: 320}, height: {ideal: 240} }- });+ const stream = await navigator.mediaDevices.getUserMedia({video:{facingMode:'user',width:{ideal:320},height:{ideal:240}}});vid.srcObject = stream;await vid.play();- // Wait up to 2s for valid dimensions- for (let i = 0; i < 40; i++) {- if (vid.videoWidth > 0) break;- await new Promise(r => setTimeout(r, 50));- }+ for (let i=0;i<40;i++) { if(vid.videoWidth>0) break; await new Promise(r=>setTimeout(r,50)); }+ overlay.width = vid.videoWidth; overlay.height = vid.videoHeight;document.getElementById('bCam').style.display = 'none';document.getElementById('bRef').disabled = false;- result.textContent = 'Camera ready. Look at camera and click "Capture Reference".';+ result.textContent = isMobile ? 'Hold face centered and tap "Capture Reference"' : 'Click "Capture Reference"';result.className = 'idle';} catch(e) {- setLog('Camera error: ' + e.message, 'err');+ setLog('Camera error: '+e.message,'err');document.getElementById('bCam').disabled = false;document.getElementById('bCam').textContent = 'Start Camera';}};-// ===== Crop face from center of video =====-function cropFace() {- const W = vid.videoWidth, H = vid.videoHeight;- if (!W || !H) return null;- // Take center square, 60% of shorter dimension- const sz = Math.min(W, H) * 0.6;- const sx = (W - sz) / 2, sy = (H - sz) / 2;- cropCtx.drawImage(vid, sx, sy, sz, sz, 0, 0, 112, 112);- return cropCtx.getImageData(0, 0, 112, 112);-}--// ===== Compute embedding =====-function embed(imgData) {- const N = 112 * 112 * 3;- const inP = FxMod._malloc(N * 4);- const outP = FxMod._malloc(512 * 4);- const h = FxMod.HEAPF32;- const b = inP >> 2;- const px = imgData.data;- for (let i = 0; i < 112*112; i++) {- h[b+i*3] = px[i*4] / 127.5 - 1;- h[b+i*3+1] = px[i*4+1] / 127.5 - 1;- h[b+i*3+2] = px[i*4+2] / 127.5 - 1;- }- const t0 = performance.now();- FxMod.cwrap('facex_embed','number',['number','number','number'])(fxH, inP, outP);- const ms = performance.now() - t0;- const emb = new Float32Array(512);- emb.set(h.subarray(outP>>2, (outP>>2)+512));- FxMod._free(inP);- FxMod._free(outP);- return { emb, ms };-}--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);-}--// ===== Capture reference =====+// ===== Capture =====document.getElementById('bRef').onclick = () => {- const img = cropFace();- if (!img) { result.textContent = 'Camera not ready'; return; }- result.textContent = 'Computing embedding...';+ document.getElementById('bRef').disabled = true;+ document.getElementById('bRef').textContent = 'Processing...';+ result.textContent = 'Detecting and embedding...';setTimeout(() => {- const { emb, ms } = embed(img);+ const { imgData, face, detMs } = getFace();+ if (!imgData) {+ result.textContent = 'No face detected. Move closer, ensure good lighting.';+ result.className = 'nomatch';+ document.getElementById('bRef').disabled = false;+ document.getElementById('bRef').textContent = 'Capture Reference';+ return;+ }+ if (face) drawBox(face, '#10b981');+ const { emb, ms } = embed(imgData);refEmb = emb;- result.textContent = 'Reference captured (' + ms.toFixed(0) + 'ms). Click "Start Verify".';+ const total = detMs + ms;+ result.textContent = 'Reference captured (' + total.toFixed(0) + 'ms). Click "Start Verify".';result.className = 'idle';document.getElementById('bGo').style.display = 'inline-block';document.getElementById('bGo').disabled = false;+ document.getElementById('bRef').disabled = false;+ document.getElementById('bRef').textContent = 'Capture Reference';}, 30);};-// ===== Verify loop =====+// ===== Verify =====document.getElementById('bGo').onclick = () => {running = true;document.getElementById('bGo').style.display = 'none';@@ -205,26 +300,32 @@ document.getElementById('bStop').onclick = () => {document.getElementById('bGo').style.display = 'inline-block';document.getElementById('bGo').disabled = false;document.getElementById('bRef').disabled = false;+ oCtx.clearRect(0,0,overlay.width,overlay.height);};function loop() {if (!running) return;- const img = cropFace();- if (!img) { requestAnimationFrame(loop); return; }- const t0 = performance.now();- const { emb, ms } = embed(img);+ const { imgData, face, detMs } = getFace();+ if (!imgData) {+ result.textContent = 'No face'; result.className = 'idle';+ oCtx.clearRect(0,0,overlay.width,overlay.height);+ requestAnimationFrame(loop); return;+ }+ const { emb, ms } = embed(imgData);const sim = cosSim(refEmb, emb);- const total = performance.now() - t0;const match = sim > 0.3;+ const total = detMs + ms;++ if (face) drawBox(face, match ? '#10b981' : '#ef4444');result.textContent = match- ? 'MATCH — ' + (sim*100).toFixed(1) + '%'- : 'NO MATCH — ' + (sim*100).toFixed(1) + '%';+ ? 'Same person — ' + (sim*100).toFixed(0) + '% confidence'+ : 'Different person — ' + (sim*100).toFixed(0) + '% similarity';result.className = match ? 'match' : 'nomatch';- document.getElementById('sEmb').textContent = 'Embed: ' + ms.toFixed(0) + 'ms';- document.getElementById('sSim').textContent = 'Sim: ' + (sim*100).toFixed(1) + '%';- document.getElementById('sFps').textContent = 'FPS: ' + (1000/total).toFixed(0);+ document.getElementById('sEmb').textContent = (detMs > 0 ? 'Det+' : '') + 'Emb: ' + total.toFixed(0) + 'ms';+ document.getElementById('sSim').textContent = (sim*100).toFixed(0) + '%';+ document.getElementById('sFps').textContent = (1000/total).toFixed(0) + ' fps';requestAnimationFrame(loop);}