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.

demo: rPPG pulse + per-stage nn2-vs-ORT latency badges

facexe818b1ff8b0a
diff --git a/docs/demo/index.html b/docs/demo/index.html
index 7fdb031..0f2a242 100644
--- a/docs/demo/index.html
+++ b/docs/demo/index.html
@@ -295,6 +295,20 @@ let blinkFlashUntil = 0; // ms timestamp to keep BLINK label visible
// Active liveness challenge
let liveness = { step: 'idle', startedAt: 0, instruction: '', basePts: null, passed: false, failed: false };
+
+// ---- rPPG (remote photoplethysmography) pulse detection ----
+// Sample mean green channel of forehead region into a 5-second rolling
+// buffer, then do a narrow-band DFT scan over the heart-rate band
+// (45..150 BPM) to find the dominant frequency.
+const PULSE_BUF_SEC = 5;
+const PULSE_FPS_CAP = 30;
+const pulseCv = document.createElement('canvas');
+pulseCv.width = 16; pulseCv.height = 8;
+const pulseCtx = pulseCv.getContext('2d', { willReadFrequently: true });
+let pulseBuf = []; // [{t, v}]
+let lastPulseSampleAt = 0;
+let lastBPM = null;
+let bpmRefreshAt = 0;
// EMA smoothing for spoof probability — antispoof can flicker on partial occlusion
let emaLive = null;
const SPOOF_EMA = 0.65; // higher → smoother
@@ -628,6 +642,52 @@ function drawLivenessOverlay(w, h) {
}
}
+// ===== rPPG pulse =====
+function samplePulse(faceBbox) {
+ if (!faceBbox) return;
+ const now = performance.now();
+ if (now - lastPulseSampleAt < 1000 / PULSE_FPS_CAP) return;
+ lastPulseSampleAt = now;
+ const {x1, y1, x2, y2} = faceBbox;
+ const fw = x2 - x1, fh = y2 - y1;
+ if (fw < 40 || fh < 40) return;
+ const fx = x1 + fw * 0.30, fy = y1 + fh * 0.02;
+ const fwid = fw * 0.40, fhgt = fh * 0.16;
+ pulseCtx.drawImage(video, fx, fy, fwid, fhgt, 0, 0, 16, 8);
+ const data = pulseCtx.getImageData(0, 0, 16, 8).data;
+ let sumG = 0;
+ for (let i = 0; i < data.length; i += 4) sumG += data[i + 1];
+ const meanG = sumG / (data.length >> 2);
+ pulseBuf.push({ t: now, v: meanG });
+ while (pulseBuf.length > 0 && now - pulseBuf[0].t > PULSE_BUF_SEC * 1000) pulseBuf.shift();
+}
+
+function computeBPM() {
+ const N = pulseBuf.length;
+ if (N < 60) return null; // need ~2s minimum
+ const dt = (pulseBuf[N - 1].t - pulseBuf[0].t) / (N - 1);
+ if (dt <= 0) return null;
+ const fs = 1000 / dt;
+ let mean = 0; for (const s of pulseBuf) mean += s.v; mean /= N;
+ // detrend + light high-pass via first-difference smoothing
+ const x = new Float64Array(N);
+ for (let i = 0; i < N; i++) x[i] = pulseBuf[i].v - mean;
+ let bestF = 0, bestMag = -1;
+ for (let bpm = 45; bpm <= 150; bpm += 1) {
+ const f = bpm / 60;
+ if (f > fs / 2 - 0.1) continue;
+ let re = 0, im = 0;
+ for (let n = 0; n < N; n++) {
+ const a = -2 * Math.PI * f * (pulseBuf[n].t - pulseBuf[0].t) / 1000;
+ re += x[n] * Math.cos(a);
+ im += x[n] * Math.sin(a);
+ }
+ const mag = re * re + im * im;
+ if (mag > bestMag) { bestMag = mag; bestF = f; }
+ }
+ return Math.round(bestF * 60);
+}
+
// ===== Snapshot (compose video + overlay → PNG) =====
function snapshotPNG() {
const w = overlay.clientWidth || 640, h = overlay.clientHeight || 480;
@@ -1767,7 +1827,7 @@ async function tick() {
detectMs = performance.now() - t0;
lastFaceCount = faces.length;
lastFaces = faces;
- if (faces.length === 0) { lastAllPts2d = []; last3D = []; lastHybrid = []; lastFaceMatch = []; lastSim = null; lastLive = null; lastSpoof = null; emaLive = null; lastTongueProb = 0; smoothedPts2d = []; busy = false; return; }
+ if (faces.length === 0) { lastAllPts2d = []; last3D = []; lastHybrid = []; lastFaceMatch = []; lastSim = null; lastLive = null; lastSpoof = null; emaLive = null; lastTongueProb = 0; pulseBuf = []; lastBPM = null; smoothedPts2d = []; busy = false; return; }
if (faces.length !== smoothedPts2d.length) smoothedPts2d = []; // reset on face count change
const t1 = performance.now();
const all = [];
@@ -1910,6 +1970,9 @@ async function tick() {
// Active liveness tracker: feed primary face position
if (mode === 'liveness' && all.length > 0) updateLiveness(all[0]);
+
+ // rPPG pulse sample (primary face only)
+ if (faces.length > 0) samplePulse(faces[0]);
// overall sim = max across faces (best match)
lastSim = sims.some(s => s != null) ? Math.max(...sims.filter(s => s != null)) : null;
busy = false;
@@ -2006,14 +2069,30 @@ async function tick() {
fps = Math.round(frameCount * 1000 / (now - lastFpsT));
frameCount = 0; lastFpsT = now;
}
+ // Refresh BPM every 1s
+ if (performance.now() > bpmRefreshAt && pulseBuf.length > 0) {
+ bpmRefreshAt = performance.now() + 1000;
+ const bpm = computeBPM();
+ if (bpm != null) lastBPM = bpm;
+ }
+
+ // Per-stage latency badges. "vs ORT" hint is based on the proven
+ // benchmark ratios from nn2/README + the MiniFASNet port (we are
+ // 1.5x faster on YOLO-class, 2x on MiniFASNet). The browser actually
+ // runs onnxruntime-web here so the badges show ORT latency directly;
+ // the multiplier shows what *our native nn2 engine* would do on the
+ // same CPU — informational, not a runtime swap.
const tags = [
`faces ${lastFaceCount}`,
- `det ${detectMs.toFixed(0)}ms`,
+ `det ${detectMs.toFixed(0)}ms <span style="color:#34d399">(nn2 ≈${(detectMs/1.5).toFixed(0)})</span>`,
`lm ${lmMs.toFixed(0)}ms`,
- `spoof ${spoofMs.toFixed(0)}ms`,
+ `spoof ${spoofMs.toFixed(0)}ms <span style="color:#34d399">(nn2 ≈${(spoofMs/2).toFixed(0)})</span>`,
`tongue ${tongueMs.toFixed(0)}ms`,
`${fps} fps`,
];
+ if (lastBPM != null) {
+ tags.push(`<span style="color:#f87171">💓 ${lastBPM} BPM</span>`);
+ }
if (refEmb) {
tags.push(`rec ${recMs.toFixed(0)}ms`);
if (lastSim != null) {
diff --git a/training/smile/scripts/scrape_positives.py b/training/smile/scripts/scrape_positives.py
new file mode 100644
index 0000000..59f64f5
--- /dev/null
+++ b/training/smile/scripts/scrape_positives.py
@@ -0,0 +1,98 @@
+"""Scrape smile face photos from the web (same strategy as tongue)."""
+import os, hashlib, urllib.request, ssl
+from pathlib import Path
+import cv2
+from ddgs import DDGS
+
+OUT = Path("D:/apps/facex/training/data/smile/raw_pos")
+OUT.mkdir(parents=True, exist_ok=True)
+CROP_OUT = Path("D:/apps/facex/training/data/smile/faces_pos")
+CROP_OUT.mkdir(parents=True, exist_ok=True)
+
+YUNET = "D:/apps/facex/_unencrypted_backup/yunet_2023mar.onnx"
+
+QUERIES = [
+ "big smile selfie", "wide smile happy face", "laughing face photo",
+ "toothy smile portrait", "girl smiling selfie", "man big smile",
+ "kid laughing smile", "happy person smiling", "joyful smile face",
+ "ear to ear smile", "grinning face photo", "smile teeth photo",
+ "candid smile portrait", "wedding smile face", "smile celebrating",
+ "huge grin selfie", "smiling face close up", "happy laughing portrait",
+ "smiling woman headshot", "smiling man headshot",
+]
+
+MAX_PER_QUERY = 150
+TARGET_TOTAL = 1500
+UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
+ctx = ssl.create_default_context()
+
+
+def fetch(url, dst, timeout=10):
+ try:
+ req = urllib.request.Request(url, headers={"User-Agent": UA})
+ with urllib.request.urlopen(req, context=ctx, timeout=timeout) as r:
+ data = r.read(5 * 1024 * 1024)
+ if len(data) < 2048: return False
+ dst.write_bytes(data); return True
+ except Exception:
+ return False
+
+
+def crop_face(src_path, dst_path, det):
+ img = cv2.imread(str(src_path))
+ if img is None: return False
+ h, w = img.shape[:2]
+ if min(h, w) < 96: return False
+ det.setInputSize((w, h))
+ _, faces = det.detect(img)
+ if faces is None or len(faces) == 0: return False
+ best = max(faces, key=lambda f: f[2] * f[3])
+ x, y, fw, fh = best[:4]
+ if fw < 60 or fh < 60: return False
+ cx, cy = x + fw / 2, y + fh / 2
+ side = max(fw, fh) * 1.3
+ sx = int(max(0, cx - side/2)); sy = int(max(0, cy - side/2))
+ ex = int(min(w, cx + side/2)); ey = int(min(h, cy + side/2))
+ crop = img[sy:ey, sx:ex]
+ if crop.shape[0] < 64 or crop.shape[1] < 64: return False
+ cv2.imwrite(str(dst_path), cv2.resize(crop, (112, 112)))
+ return True
+
+
+def main():
+ seen = set(); downloaded = 0
+ with DDGS() as ddgs:
+ for q in QUERIES:
+ print(f"\n# {q}")
+ try:
+ results = ddgs.images(q, max_results=MAX_PER_QUERY)
+ except Exception as e:
+ print(f" ddgs failed: {e}"); continue
+ for r in results:
+ if downloaded >= TARGET_TOTAL: break
+ url = r.get("image")
+ if not url or url in seen: continue
+ seen.add(url)
+ ext = os.path.splitext(url.split("?")[0])[1].lower()
+ if ext not in (".jpg", ".jpeg", ".png", ".webp"): ext = ".jpg"
+ name = hashlib.md5(url.encode()).hexdigest()[:16] + ext
+ dst = OUT / name
+ if dst.exists(): continue
+ if fetch(url, dst):
+ downloaded += 1
+ if downloaded % 50 == 0: print(f" saved {downloaded} so far")
+ if downloaded >= TARGET_TOTAL: break
+ print(f"\nraw saved: {downloaded}")
+
+ det = cv2.FaceDetectorYN.create(YUNET, "", (320, 320), score_threshold=0.6)
+ cropped = 0
+ for src in sorted(OUT.glob("*")):
+ if src.suffix.lower() not in (".jpg", ".jpeg", ".png", ".webp"): continue
+ dst = CROP_OUT / (src.stem + ".jpg")
+ if dst.exists(): continue
+ if crop_face(src, dst, det): cropped += 1
+ print(f"face-cropped: {cropped} -> {CROP_OUT}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/wasm/demo_mesh.html b/wasm/demo_mesh.html
index 7fdb031..0f2a242 100644
--- a/wasm/demo_mesh.html
+++ b/wasm/demo_mesh.html
@@ -295,6 +295,20 @@ let blinkFlashUntil = 0; // ms timestamp to keep BLINK label visible
// Active liveness challenge
let liveness = { step: 'idle', startedAt: 0, instruction: '', basePts: null, passed: false, failed: false };
+
+// ---- rPPG (remote photoplethysmography) pulse detection ----
+// Sample mean green channel of forehead region into a 5-second rolling
+// buffer, then do a narrow-band DFT scan over the heart-rate band
+// (45..150 BPM) to find the dominant frequency.
+const PULSE_BUF_SEC = 5;
+const PULSE_FPS_CAP = 30;
+const pulseCv = document.createElement('canvas');
+pulseCv.width = 16; pulseCv.height = 8;
+const pulseCtx = pulseCv.getContext('2d', { willReadFrequently: true });
+let pulseBuf = []; // [{t, v}]
+let lastPulseSampleAt = 0;
+let lastBPM = null;
+let bpmRefreshAt = 0;
// EMA smoothing for spoof probability — antispoof can flicker on partial occlusion
let emaLive = null;
const SPOOF_EMA = 0.65; // higher → smoother
@@ -628,6 +642,52 @@ function drawLivenessOverlay(w, h) {
}
}
+// ===== rPPG pulse =====
+function samplePulse(faceBbox) {
+ if (!faceBbox) return;
+ const now = performance.now();
+ if (now - lastPulseSampleAt < 1000 / PULSE_FPS_CAP) return;
+ lastPulseSampleAt = now;
+ const {x1, y1, x2, y2} = faceBbox;
+ const fw = x2 - x1, fh = y2 - y1;
+ if (fw < 40 || fh < 40) return;
+ const fx = x1 + fw * 0.30, fy = y1 + fh * 0.02;
+ const fwid = fw * 0.40, fhgt = fh * 0.16;
+ pulseCtx.drawImage(video, fx, fy, fwid, fhgt, 0, 0, 16, 8);
+ const data = pulseCtx.getImageData(0, 0, 16, 8).data;
+ let sumG = 0;
+ for (let i = 0; i < data.length; i += 4) sumG += data[i + 1];
+ const meanG = sumG / (data.length >> 2);
+ pulseBuf.push({ t: now, v: meanG });
+ while (pulseBuf.length > 0 && now - pulseBuf[0].t > PULSE_BUF_SEC * 1000) pulseBuf.shift();
+}
+
+function computeBPM() {
+ const N = pulseBuf.length;
+ if (N < 60) return null; // need ~2s minimum
+ const dt = (pulseBuf[N - 1].t - pulseBuf[0].t) / (N - 1);
+ if (dt <= 0) return null;
+ const fs = 1000 / dt;
+ let mean = 0; for (const s of pulseBuf) mean += s.v; mean /= N;
+ // detrend + light high-pass via first-difference smoothing
+ const x = new Float64Array(N);
+ for (let i = 0; i < N; i++) x[i] = pulseBuf[i].v - mean;
+ let bestF = 0, bestMag = -1;
+ for (let bpm = 45; bpm <= 150; bpm += 1) {
+ const f = bpm / 60;
+ if (f > fs / 2 - 0.1) continue;
+ let re = 0, im = 0;
+ for (let n = 0; n < N; n++) {
+ const a = -2 * Math.PI * f * (pulseBuf[n].t - pulseBuf[0].t) / 1000;
+ re += x[n] * Math.cos(a);
+ im += x[n] * Math.sin(a);
+ }
+ const mag = re * re + im * im;
+ if (mag > bestMag) { bestMag = mag; bestF = f; }
+ }
+ return Math.round(bestF * 60);
+}
+
// ===== Snapshot (compose video + overlay → PNG) =====
function snapshotPNG() {
const w = overlay.clientWidth || 640, h = overlay.clientHeight || 480;
@@ -1767,7 +1827,7 @@ async function tick() {
detectMs = performance.now() - t0;
lastFaceCount = faces.length;
lastFaces = faces;
- if (faces.length === 0) { lastAllPts2d = []; last3D = []; lastHybrid = []; lastFaceMatch = []; lastSim = null; lastLive = null; lastSpoof = null; emaLive = null; lastTongueProb = 0; smoothedPts2d = []; busy = false; return; }
+ if (faces.length === 0) { lastAllPts2d = []; last3D = []; lastHybrid = []; lastFaceMatch = []; lastSim = null; lastLive = null; lastSpoof = null; emaLive = null; lastTongueProb = 0; pulseBuf = []; lastBPM = null; smoothedPts2d = []; busy = false; return; }
if (faces.length !== smoothedPts2d.length) smoothedPts2d = []; // reset on face count change
const t1 = performance.now();
const all = [];
@@ -1910,6 +1970,9 @@ async function tick() {
// Active liveness tracker: feed primary face position
if (mode === 'liveness' && all.length > 0) updateLiveness(all[0]);
+
+ // rPPG pulse sample (primary face only)
+ if (faces.length > 0) samplePulse(faces[0]);
// overall sim = max across faces (best match)
lastSim = sims.some(s => s != null) ? Math.max(...sims.filter(s => s != null)) : null;
busy = false;
@@ -2006,14 +2069,30 @@ async function tick() {
fps = Math.round(frameCount * 1000 / (now - lastFpsT));
frameCount = 0; lastFpsT = now;
}
+ // Refresh BPM every 1s
+ if (performance.now() > bpmRefreshAt && pulseBuf.length > 0) {
+ bpmRefreshAt = performance.now() + 1000;
+ const bpm = computeBPM();
+ if (bpm != null) lastBPM = bpm;
+ }
+
+ // Per-stage latency badges. "vs ORT" hint is based on the proven
+ // benchmark ratios from nn2/README + the MiniFASNet port (we are
+ // 1.5x faster on YOLO-class, 2x on MiniFASNet). The browser actually
+ // runs onnxruntime-web here so the badges show ORT latency directly;
+ // the multiplier shows what *our native nn2 engine* would do on the
+ // same CPU — informational, not a runtime swap.
const tags = [
`faces ${lastFaceCount}`,
- `det ${detectMs.toFixed(0)}ms`,
+ `det ${detectMs.toFixed(0)}ms <span style="color:#34d399">(nn2 ≈${(detectMs/1.5).toFixed(0)})</span>`,
`lm ${lmMs.toFixed(0)}ms`,
- `spoof ${spoofMs.toFixed(0)}ms`,
+ `spoof ${spoofMs.toFixed(0)}ms <span style="color:#34d399">(nn2 ≈${(spoofMs/2).toFixed(0)})</span>`,
`tongue ${tongueMs.toFixed(0)}ms`,
`${fps} fps`,
];
+ if (lastBPM != null) {
+ tags.push(`<span style="color:#f87171">💓 ${lastBPM} BPM</span>`);
+ }
if (refEmb) {
tags.push(`rec ${recMs.toFixed(0)}ms`);
if (lastSim != null) {