Skip to content

armgit / facex

Public Imported from GitHub
0

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.

12.0 KB
Raw Blame
<!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>Local face detection and recognition with WebAssembly.</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> runs the YuNet face detector.</p>
    <p><code>facex.wasm</code> computes 512-component EdgeFace XS embeddings.</p>
    <p>5-point alignment ensures accurate matching at any head angle.</p>
    <p>Both model files are cached after their first successful download.</p>
  </div>
</div>

<script src="detect.js"></script>
<script src="facex.js"></script>
<script src="align.js"></script>
<script src="liveness.js"></script>
<script src="simd_check.js"></script>
<script src="cache.js"></script>
<script src="facex-sdk.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 });

const sdk = new FaceXSDK();
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 });

// ===== Init =====
async function init() {
  const s = $('status');
  if (!checkWasmSimd()) {
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
    showError(isIOS
      ? 'WebAssembly SIMD not supported in this browser. On iOS, use Safari (not Chrome).'
      : 'WebAssembly SIMD not supported. Use Chrome 91+, Firefox 89+, or Safari 16.4+.');
    return;
  }
  try {
    s.textContent = 'Loading engines...'; s.className = 'status loading';
    sdk.onProgress = message => { s.textContent = message; };
    await sdk.load();
    s.textContent = 'Ready'; 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 start = performance.now();
  const faces = sdk.detect(video);
  return {faces, detMs: performance.now() - start};
}

function runEmbed(image) {
  const start = performance.now();
  const emb = sdk.embed(image);
  return {emb, embMs: performance.now() - start};
}

function cosSim(a, b) { return sdk.cosSim(a, b); }

// ===== 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>