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: drop tongue, add smile classifier (F1=0.95) with amber lip overlay

facex0d4582fa5b5e
diff --git a/docs/demo/facex_smile.enc b/docs/demo/facex_smile.enc
new file mode 100644
index 0000000..a8d78bb
Binary files /dev/null and b/docs/demo/facex_smile.enc differ
diff --git a/docs/demo/facex_tongue.enc b/docs/demo/facex_tongue.enc
deleted file mode 100644
index dc1ebe9..0000000
Binary files a/docs/demo/facex_tongue.enc and /dev/null differ
diff --git a/docs/demo/index.html b/docs/demo/index.html
index 34b38d1..7e4c0f0 100644
--- a/docs/demo/index.html
+++ b/docs/demo/index.html
@@ -199,7 +199,7 @@
<span class="chip ours">✦ ours <span class="num">1.1MB</span> <span class="src">98pt landmarks</span></span>
<span class="chip ours">✦ ours <span class="num">5.6MB</span> <span class="src">478pt 3D mesh</span></span>
<span class="chip ours">✦ ours <span class="num">1.8MB</span> <span class="src">recognition</span></span>
- <span class="chip ours">✦ ours <span class="num">187KB</span> <span class="src">tongue</span></span>
+ <span class="chip ours">✦ ours <span class="num">187KB</span> <span class="src">smile</span></span>
<span class="chip apache">Apache <span class="num">3.4MB</span> <span class="src">anti-spoof</span></span>
</div>
@@ -266,7 +266,7 @@ const btnUnlock = $('btnUnlock');
const btnSnap = $('btnSnap');
const btnStop = $('btnStop');
-let detSess = null, lmSess = null, recSess = null, lm3dSess = null, spoof27Sess = null, spoof40Sess = null, tongueSess = null, meshTopology = null, stream = null, running = false;
+let detSess = null, lmSess = null, recSess = null, lm3dSess = null, spoof27Sess = null, spoof40Sess = null, smileSess = null, meshTopology = null, stream = null, running = false;
let mode = 'hybrid';
let last3D = []; // per-face 478 [x,y,z] from true-3D model (overlay coords)
let lastHybrid = []; // per-face 478 [x,y,z] from hybrid (WFLW->MP via TPS)
@@ -280,10 +280,10 @@ let lastSim = null; // most recent cosine similarity to ref
let lastPts2d = null, lastBox = null, lastFaceCount = 0;
let lastLive = null, lastSpoof = null; // P(live), P(spoof) from antispoof model
let spoofMs = 0;
-let lastTongueProb = 0; // EMA-smoothed P(tongue out) from tongue classifier
-const TONGUE_EMA = 0.6;
-const TONGUE_THRESH = 0.6; // tuned for the F1=0.96 model
-let tongueMs = 0;
+let lastSmileProb = 0; // EMA-smoothed P(smile)
+const SMILE_EMA = 0.6;
+const SMILE_THRESH = 0.6;
+let smileMs = 0;
// Eye-blink detection (EAR — Eye Aspect Ratio) from our 98-pt WFLW landmarks.
// WFLW eye indices: left eye 60..67 (8 pts), right eye 68..75 (8 pts).
@@ -461,7 +461,7 @@ async function loadModels() {
['minifasnet_v2_27.enc', 'spoof27'],
['minifasnet_v1se_40.enc', 'spoof40'],
['facex_3d_landmarks.enc', 'lm3d'],
- ['facex_tongue.enc', 'tongue'],
+ ['facex_smile.enc', 'smile'],
];
const setSess = (name, s) => {
if (name === 'det') detSess = s;
@@ -470,7 +470,7 @@ async function loadModels() {
else if (name === 'spoof27') spoof27Sess = s;
else if (name === 'spoof40') spoof40Sess = s;
else if (name === 'lm3d') lm3dSess = s;
- else if (name === 'tongue') tongueSess = s;
+ else if (name === 'smile') smileSess = s;
};
for (let i = 0; i < steps.length; i++) {
@@ -856,11 +856,10 @@ function fillSpoofTensor(box, scale, dst) {
}
}
-// Tongue-out classifier. 112×112 RGB normalized [-1, 1], 2-class softmax.
-// Reuses lmCv canvas since it's 112×112 already. Index 1 = tongue.
-const tongueInput = new Float32Array(3 * 112 * 112);
-async function predictTongue(box) {
- if (!tongueSess) return 0;
+// Smile classifier — same shape/preprocessing as recognition.
+const smileInput = new Float32Array(3 * 112 * 112);
+async function predictSmile(box) {
+ if (!smileSess) return 0;
const bw = box.x2 - box.x1, bh = box.y2 - box.y1;
const side = Math.max(bw, bh) * (1 + 2 * 0.15);
const cx = (box.x1 + box.x2) / 2, cy = (box.y1 + box.y2) / 2;
@@ -872,13 +871,13 @@ async function predictTongue(box) {
const N = 112 * 112;
for (let i = 0, p = 0; i < N; i++) {
const r = img[p++], g = img[p++], b = img[p++]; p++;
- tongueInput[i] = (r - 127.5) / 128;
- tongueInput[N + i] = (g - 127.5) / 128;
- tongueInput[2 * N + i] = (b - 127.5) / 128;
+ smileInput[i] = (r - 127.5) / 128;
+ smileInput[N + i] = (g - 127.5) / 128;
+ smileInput[2 * N + i] = (b - 127.5) / 128;
}
- const t = new ort.Tensor('float32', tongueInput, [1, 3, 112, 112]);
- const o = await tongueSess.run({ input: t });
- return o['prob'].data[1]; // P(tongue out)
+ const t = new ort.Tensor('float32', smileInput, [1, 3, 112, 112]);
+ const o = await smileSess.run({ input: t });
+ return o['prob'].data[1];
}
async function predictSpoof(box) {
@@ -1620,7 +1619,7 @@ function drawHybrid(pts3d, matchFlag) {
// lip (MP idx 13) and lower inner lip (idx 14), normalized by horizontal
// mouth width (78 ↔ 308). If the ratio is high → user is sticking the
// tongue out (or yawning) → dye the LIPS group red for visual feedback.
- const tongueOut = (lastTongueProb > TONGUE_THRESH);
+ const smiling = (lastSmileProb > SMILE_THRESH);
for (const [a, b] of meshTopology.TESSELATION) shadedEdge(a, b, 0.75);
for (const grp of [meshTopology.FACE_OVAL,
@@ -1630,9 +1629,9 @@ function drawHybrid(pts3d, matchFlag) {
for (const [a, b] of grp) shadedEdge(a, b, 1.0);
}
// LIPS — red when mouth wide open (tongue likely visible)
- if (tongueOut) {
+ if (smiling) {
const sR = baseR, sG = baseG, sB = baseB;
- baseR = 255; baseG = 40; baseB = 70;
+ baseR = 251; baseG = 191; baseB = 36; // warm amber for smile
for (const [a, b] of meshTopology.LIPS) shadedEdge(a, b, 1.6);
baseR = sR; baseG = sG; baseB = sB;
} else {
@@ -1645,19 +1644,6 @@ function drawHybrid(pts3d, matchFlag) {
ctx.restore();
}
-// MediaPipe FaceMesh indices: 13 = upper inner lip center,
-// 14 = lower inner lip center, 78 = left inner mouth corner,
-// 308 = right inner mouth corner. Compare vertical opening to horizontal
-// mouth width — high ratio means mouth wide open / tongue out.
-function isMouthWide(pts) {
- if (!pts || pts.length < 309) return false;
- const u = pts[13], l = pts[14], lc = pts[78], rc = pts[308];
- if (!u || !l || !lc || !rc) return false;
- const mouthH = Math.abs(l[1] - u[1]);
- const mouthW = Math.abs(rc[0] - lc[0]);
- if (mouthW < 5) return false;
- return (mouthH / mouthW) > 0.35; // threshold tuned for "deliberate open"
-}
// Render the true-3D mesh from 478 predicted (x,y,z) landmarks.
// Each edge is shaded by the average z of its endpoints (forward = brighter, thicker).
@@ -1706,7 +1692,7 @@ function drawTrue3D(pts3d, matchFlag) {
}
// (1) Full tessellation — dense mesh
- const tongueOut = (lastTongueProb > TONGUE_THRESH);
+ const smiling = (lastSmileProb > SMILE_THRESH);
for (const [a, b] of meshTopology.TESSELATION) shadedEdge(a, b, 0.75);
@@ -1717,9 +1703,9 @@ function drawTrue3D(pts3d, matchFlag) {
meshTopology.NOSE]) {
for (const [a, b] of grp) shadedEdge(a, b, 1.0);
}
- if (tongueOut) {
+ if (smiling) {
const sR = baseR, sG = baseG, sB = baseB;
- baseR = 255; baseG = 40; baseB = 70;
+ baseR = 251; baseG = 191; baseB = 36; // warm amber for smile
for (const [a, b] of meshTopology.LIPS) shadedEdge(a, b, 1.6);
baseR = sR; baseG = sG; baseB = sB;
} else {
@@ -1843,7 +1829,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; pulseBuf = []; lastBPM = null; smoothedPts2d = []; busy = false; return; }
+ if (faces.length === 0) { lastAllPts2d = []; last3D = []; lastHybrid = []; lastFaceMatch = []; lastSim = null; lastLive = null; lastSpoof = null; emaLive = null; lastSmileProb = 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 = [];
@@ -1959,11 +1945,11 @@ async function tick() {
lastLive = emaLive;
lastSpoof = 1 - emaLive;
window.__lastRawLive = sp.live;
- // Tongue-out detection on the same face (also primary only).
- const t4 = performance.now();
- const tprob = await predictTongue(f);
- tongueMs = performance.now() - t4;
- lastTongueProb = TONGUE_EMA * lastTongueProb + (1 - TONGUE_EMA) * tprob;
+ // Smile detection on the same face (primary only).
+ const t5 = performance.now();
+ const sprob = await predictSmile(f);
+ smileMs = performance.now() - t5;
+ lastSmileProb = SMILE_EMA * lastSmileProb + (1 - SMILE_EMA) * sprob;
}
}
lmMs = (performance.now() - t1) / faces.length;
@@ -2103,7 +2089,7 @@ async function tick() {
`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 <span style="color:#34d399">(nn2 ≈${(spoofMs/2).toFixed(0)})</span>`,
- `tongue ${tongueMs.toFixed(0)}ms`,
+ `smile ${smileMs.toFixed(0)}ms`,
`${fps} fps`,
];
if (lastBPM != null) {
@@ -2124,8 +2110,8 @@ async function tick() {
const color = isLive ? '#10b981' : '#ef4444';
tags.push(`<span style="color:${color}">${label}</span>`);
}
- if (lastTongueProb > TONGUE_THRESH && lastFaceCount > 0) {
- tags.push(`<span style="color:#ef4444">👅 TONGUE ${(lastTongueProb*100).toFixed(0)}%</span>`);
+ if (lastSmileProb > SMILE_THRESH && lastFaceCount > 0) {
+ tags.push(`<span style="color:#fbbf24">😀 SMILE ${(lastSmileProb*100).toFixed(0)}%</span>`);
}
if (performance.now() < blinkFlashUntil) {
tags.push(`<span style="color:#60a5fa">👁 BLINK</span>`);
diff --git a/training/smile/scripts/build_dataset.py b/training/smile/scripts/build_dataset.py
new file mode 100644
index 0000000..2702713
--- /dev/null
+++ b/training/smile/scripts/build_dataset.py
@@ -0,0 +1,79 @@
+"""Build a binary tongue-out dataset:
+ class 1 = tongue out (from web-scraped face crops)
+ class 0 = no tongue (from MS1M neutral faces)
+
+Output:
+ D:/apps/facex/training/data/smile/train_raw.bin (N*112*112*3 uint8)
+ D:/apps/facex/training/data/smile/train_labels.bin (N uint8)
+ D:/apps/facex/training/data/smile/meta.json
+"""
+
+import io, json, struct, time
+from pathlib import Path
+import numpy as np
+import cv2
+
+POS_DIR = Path("D:/apps/facex/training/data/smile/faces_pos")
+OUT = Path("D:/apps/facex/training/data/smile")
+OUT.mkdir(parents=True, exist_ok=True)
+MS1M = Path("D:/apps/facex/training/data/ms1m")
+SIZE = 112
+N_NEG = 3000
+
+MS1M_INDEX = struct.Struct("<QII")
+
+
+def main():
+ # === positives ===
+ pos_paths = sorted([p for p in POS_DIR.glob("*.jpg")])
+ print(f"positives available: {len(pos_paths)}")
+ if len(pos_paths) < 50:
+ print("not enough positives, abort"); return
+
+ raw_f = open(OUT / "train_raw.bin", "wb", buffering=8 << 20)
+ lbl_f = open(OUT / "train_labels.bin", "wb", buffering=4 << 20)
+ n_pos = 0; n_neg = 0
+
+ for p in pos_paths:
+ img = cv2.imread(str(p))
+ if img is None: continue
+ if img.shape != (SIZE, SIZE, 3):
+ img = cv2.resize(img, (SIZE, SIZE))
+ rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
+ raw_f.write(rgb.tobytes())
+ lbl_f.write(bytes([1]))
+ n_pos += 1
+
+ # === negatives: random MS1M samples ===
+ idx_mm = np.memmap(MS1M / "index.bin", dtype=np.uint8, mode="r")
+ blob = np.memmap(MS1M / "blob.jpg.bin", dtype=np.uint8, mode="r")
+ n_ms1m = idx_mm.size // 16
+ rng = np.random.default_rng(42)
+ sample_indices = rng.choice(n_ms1m, size=N_NEG * 2, replace=False)
+
+ from PIL import Image
+ for src_idx in sample_indices:
+ if n_neg >= N_NEG: break
+ off, sz, _ = MS1M_INDEX.unpack(idx_mm[src_idx * 16:(src_idx + 1) * 16].tobytes())
+ jpeg = blob[off:off + sz].tobytes()
+ try:
+ img = np.asarray(Image.open(io.BytesIO(jpeg)).convert("RGB"))
+ except Exception:
+ continue
+ if img.shape != (SIZE, SIZE, 3):
+ img = cv2.resize(img, (SIZE, SIZE))
+ raw_f.write(img.tobytes())
+ lbl_f.write(bytes([0]))
+ n_neg += 1
+
+ raw_f.close(); lbl_f.close()
+ total = n_pos + n_neg
+ (OUT / "meta.json").write_text(json.dumps({
+ "n_samples": total, "n_pos": n_pos, "n_neg": n_neg,
+ "image_size": SIZE, "image_bytes": SIZE * SIZE * 3,
+ }, indent=2))
+ print(f"\ndone. {n_pos} positives + {n_neg} negatives = {total} samples")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/training/smile/scripts/dataset.py b/training/smile/scripts/dataset.py
new file mode 100644
index 0000000..84929f8
--- /dev/null
+++ b/training/smile/scripts/dataset.py
@@ -0,0 +1,64 @@
+"""Memory-mapped tongue dataset loader with strong augmentation."""
+
+import json
+from pathlib import Path
+import numpy as np
+import torch
+from torch.utils.data import Dataset
+import cv2
+
+ROOT = Path("D:/apps/facex/training/data/smile")
+SIZE = 112
+
+
+class SmileDataset(Dataset):
+ def __init__(self, augment: bool = True):
+ meta = json.loads((ROOT / "meta.json").read_text())
+ self.n = meta["n_samples"]
+ self.augment = augment
+ self._raw = None
+ self._lbl = None
+
+ def _ensure(self):
+ if self._raw is None:
+ self._raw = np.memmap(ROOT / "train_raw.bin", dtype=np.uint8, mode="r",
+ shape=(self.n, SIZE, SIZE, 3))
+ self._lbl = np.memmap(ROOT / "train_labels.bin", dtype=np.uint8, mode="r",
+ shape=(self.n,))
+
+ def __len__(self): return self.n
+
+ def __getitem__(self, i):
+ self._ensure()
+ arr = np.array(self._raw[i], dtype=np.uint8)
+ label = int(self._lbl[i])
+
+ if self.augment:
+ # horizontal flip
+ if np.random.rand() < 0.5:
+ arr = arr[:, ::-1, :].copy()
+ # random crop & resize (±15%)
+ if np.random.rand() < 0.7:
+ s = np.random.uniform(0.85, 1.0)
+ side = int(SIZE * s)
+ ox = np.random.randint(0, SIZE - side + 1)
+ oy = np.random.randint(0, SIZE - side + 1)
+ arr = cv2.resize(arr[oy:oy+side, ox:ox+side], (SIZE, SIZE))
+ # color jitter
+ if np.random.rand() < 0.85:
+ arr = arr.astype(np.float32)
+ arr *= np.random.uniform(0.75, 1.25)
+ arr += np.random.uniform(-25, 25, size=3)[None, None]
+ arr = np.clip(arr, 0, 255).astype(np.uint8)
+ # mild blur
+ if np.random.rand() < 0.3:
+ arr = cv2.GaussianBlur(arr, (3, 3), 0)
+ # mild rotation
+ if np.random.rand() < 0.4:
+ angle = np.random.uniform(-12, 12)
+ M = cv2.getRotationMatrix2D((SIZE/2, SIZE/2), angle, 1.0)
+ arr = cv2.warpAffine(arr, M, (SIZE, SIZE), borderMode=cv2.BORDER_REFLECT)
+
+ x = (arr.astype(np.float32) - 127.5) / 128.0
+ x = np.transpose(x, (2, 0, 1))
+ return torch.from_numpy(x), torch.tensor(label, dtype=torch.long)
diff --git a/training/smile/scripts/export.py b/training/smile/scripts/export.py
new file mode 100644
index 0000000..4eb33b5
--- /dev/null
+++ b/training/smile/scripts/export.py
@@ -0,0 +1,41 @@
+"""Export trained tongue classifier to ONNX with softmax baked in."""
+
+import argparse
+from pathlib import Path
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from model import SmileNet
+
+
+class Wrap(nn.Module):
+ def __init__(self, net): super().__init__(); self.net = net
+ def forward(self, x): return F.softmax(self.net(x), dim=-1)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--ckpt", default="D:/apps/facex/training/smile/runs/best.pt")
+ ap.add_argument("--out", default="D:/apps/facex/wasm/facex_smile.onnx")
+ args = ap.parse_args()
+
+ net = SmileNet().eval()
+ ck = torch.load(args.ckpt, map_location="cpu", weights_only=False)
+ net.load_state_dict(ck["model"])
+ print(f"loaded (ep {ck['epoch']}, F1={ck['f1']:.3f}, acc={ck['acc']:.3f})")
+
+ m = Wrap(net).eval()
+ x = torch.zeros(1, 3, 112, 112)
+ with torch.no_grad(): y = m(x)
+ print(f"sanity: out shape {tuple(y.shape)}, sum={y.sum():.3f}")
+
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
+ torch.onnx.export(m, x, args.out, input_names=["input"], output_names=["prob"],
+ opset_version=13, do_constant_folding=True, dynamo=False)
+ sz = Path(args.out).stat().st_size / 1024
+ print(f"wrote {args.out} ({sz:.1f} KB)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/training/smile/scripts/model.py b/training/smile/scripts/model.py
new file mode 100644
index 0000000..bc7e960
--- /dev/null
+++ b/training/smile/scripts/model.py
@@ -0,0 +1,59 @@
+"""Tiny binary tongue classifier. ~50K params, 112x112 RGB → 2 classes."""
+
+import torch
+import torch.nn as nn
+
+
+class ConvBN(nn.Module):
+ def __init__(self, ci, co, k=1, s=1, p=0, g=1, act=True):
+ super().__init__()
+ self.conv = nn.Conv2d(ci, co, k, s, p, groups=g, bias=False)
+ self.bn = nn.BatchNorm2d(co)
+ self.act = nn.PReLU(co) if act else None
+
+ def forward(self, x):
+ x = self.bn(self.conv(x))
+ if self.act is not None: x = self.act(x)
+ return x
+
+
+class InvBN(nn.Module):
+ def __init__(self, ci, co, s=1, t=2):
+ super().__init__()
+ h = max(8, ci * t)
+ self.use_res = (s == 1 and ci == co)
+ self.expand = ConvBN(ci, h, 1)
+ self.dw = ConvBN(h, h, 3, s, 1, g=h)
+ self.project = ConvBN(h, co, 1, act=False)
+
+ def forward(self, x):
+ y = self.project(self.dw(self.expand(x)))
+ return y + x if self.use_res else y
+
+
+class SmileNet(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.stem = ConvBN(3, 16, 3, 2, 1)
+ # 112 → 56
+ self.s1 = nn.Sequential(InvBN(16, 24, 2, 2), InvBN(24, 24, 1, 2)) # 28
+ self.s2 = nn.Sequential(InvBN(24, 32, 2, 3), InvBN(32, 32, 1, 3)) # 14
+ self.s3 = nn.Sequential(InvBN(32, 48, 2, 3), InvBN(48, 48, 1, 3)) # 7
+ self.head_conv = ConvBN(48, 64, 1)
+ self.pool = nn.AdaptiveAvgPool2d(1)
+ self.fc = nn.Linear(64, 2)
+
+ def forward(self, x):
+ x = self.stem(x); x = self.s1(x); x = self.s2(x); x = self.s3(x)
+ x = self.head_conv(x); x = self.pool(x).flatten(1)
+ return self.fc(x)
+
+ def num_params(self): return sum(p.numel() for p in self.parameters())
+
+
+if __name__ == "__main__":
+ m = SmileNet().eval()
+ print(f"params: {m.num_params():,}")
+ x = torch.zeros(1, 3, 112, 112)
+ y = m(x)
+ print(f"input {tuple(x.shape)} → output {tuple(y.shape)}")
diff --git a/training/smile/scripts/train.py b/training/smile/scripts/train.py
new file mode 100644
index 0000000..793fc12
--- /dev/null
+++ b/training/smile/scripts/train.py
@@ -0,0 +1,112 @@
+"""Train tongue-out binary classifier."""
+
+import argparse, math, time
+from pathlib import Path
+
+import torch
+import torch.nn.functional as F
+from torch.utils.data import DataLoader, random_split
+
+from model import SmileNet
+from dataset import SmileDataset
+
+
+def cosine_lr(step, total, warmup, base, mn):
+ if step < warmup: return base * (step + 1) / warmup
+ p = (step - warmup) / max(1, total - warmup)
+ return mn + 0.5 * (base - mn) * (1 + math.cos(math.pi * p))
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--epochs", type=int, default=30)
+ ap.add_argument("--batch", type=int, default=128)
+ ap.add_argument("--lr", type=float, default=1e-3)
+ ap.add_argument("--min-lr", type=float, default=1e-6)
+ ap.add_argument("--wd", type=float, default=5e-4)
+ ap.add_argument("--warmup", type=int, default=100)
+ ap.add_argument("--workers", type=int, default=2)
+ args = ap.parse_args()
+
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ torch.backends.cudnn.benchmark = True
+ print(f"device: {device}")
+
+ full = SmileDataset(augment=True)
+ n = len(full); nt = int(n * 0.9); ne = n - nt
+ train_ds, test_ds = random_split(full, [nt, ne],
+ generator=torch.Generator().manual_seed(0))
+ print(f"train {nt:,} test {ne:,}")
+
+ train_l = DataLoader(train_ds, batch_size=args.batch, shuffle=True,
+ num_workers=args.workers, pin_memory=True,
+ persistent_workers=(args.workers > 0), drop_last=True)
+ test_l = DataLoader(test_ds, batch_size=args.batch, shuffle=False,
+ num_workers=args.workers, pin_memory=True)
+
+ model = SmileNet().to(device)
+ print(f"params: {model.num_params():,}")
+
+ # Plain cross-entropy (no class weights) — earlier 4.6x positive weight
+ # made the model over-fire on every face. With ~1:4.6 ratio CE alone
+ # converges fine and gives much cleaner probabilities.
+ class_weights = None
+
+ decay, no_decay = [], []
+ for n_, p in model.named_parameters():
+ if p.ndim < 2 or n_.endswith(".bias") or "bn" in n_.lower(): no_decay.append(p)
+ else: decay.append(p)
+ opt = torch.optim.AdamW([{"params": decay, "weight_decay": args.wd},
+ {"params": no_decay, "weight_decay": 0.0}], lr=args.lr)
+
+ runs = Path("D:/apps/facex/training/smile/runs"); runs.mkdir(parents=True, exist_ok=True)
+ log_f = open(runs / "train.log", "a", buffering=1, encoding="utf-8")
+ log_f.write(f"\n=== run: ep={args.epochs} batch={args.batch} ===\n")
+ best = 0.0
+ spe = len(train_l); total_steps = spe * args.epochs; gs = 0
+
+ for ep in range(args.epochs):
+ model.train(); t0 = time.time(); n_seen = 0; loss_acc = 0
+ for it, (imgs, lbl) in enumerate(train_l):
+ imgs = imgs.to(device, non_blocking=True); lbl = lbl.to(device, non_blocking=True)
+ lr = cosine_lr(gs, total_steps, args.warmup, args.lr, args.min_lr)
+ for g in opt.param_groups: g["lr"] = lr
+ opt.zero_grad(set_to_none=True)
+ with torch.amp.autocast("cuda", dtype=torch.bfloat16):
+ logits = model(imgs)
+ loss = F.cross_entropy(logits, lbl, weight=class_weights) if class_weights is not None else F.cross_entropy(logits, lbl)
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
+ opt.step()
+ n_seen += imgs.size(0); gs += 1; loss_acc += loss.item()
+
+ # eval
+ model.eval(); tp=0; fp=0; tn=0; fn=0
+ with torch.no_grad():
+ for imgs, lbl in test_l:
+ imgs = imgs.to(device); lbl = lbl.to(device)
+ pred = model(imgs).argmax(-1)
+ tp += ((pred == 1) & (lbl == 1)).sum().item()
+ fp += ((pred == 1) & (lbl == 0)).sum().item()
+ tn += ((pred == 0) & (lbl == 0)).sum().item()
+ fn += ((pred == 0) & (lbl == 1)).sum().item()
+ acc = (tp + tn) / max(1, tp + tn + fp + fn)
+ prec = tp / max(1, tp + fp)
+ rec = tp / max(1, tp + fn)
+ f1 = 2 * prec * rec / max(1e-9, prec + rec)
+ msg = (f"ep {ep+1}/{args.epochs} acc {acc:.3f} prec {prec:.3f} rec {rec:.3f} "
+ f"f1 {f1:.3f} loss {loss_acc/spe:.3f} time {(time.time()-t0)/60:.1f}min lr {lr:.2e}")
+ print(msg, flush=True); log_f.write(msg + "\n")
+ torch.save({"epoch": ep, "model": model.state_dict()}, runs / "last.pt")
+ if f1 > best:
+ best = f1
+ torch.save({"epoch": ep, "model": model.state_dict(), "f1": f1,
+ "prec": prec, "rec": rec, "acc": acc}, runs / "best.pt")
+ log_f.write(f" -> new best F1 {f1:.3f}\n")
+
+ log_f.close()
+ print(f"done. best F1 {best:.3f}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/training/tongue/runs/train.log b/training/tongue/runs/train.log
index cfcf5db..e27a260 100644
--- a/training/tongue/runs/train.log
+++ b/training/tongue/runs/train.log
@@ -43,3 +43,43 @@ ep 27/30 acc 0.978 prec 0.953 rec 0.924 f1 0.938 loss 0.063 time 0.0min l
ep 28/30 acc 0.967 prec 0.875 rec 0.955 f1 0.913 loss 0.062 time 0.0min lr 1.61e-05
ep 29/30 acc 0.967 prec 0.875 rec 0.955 f1 0.913 loss 0.055 time 0.0min lr 4.94e-06
ep 30/30 acc 0.975 prec 0.913 rec 0.955 f1 0.933 loss 0.064 time 0.0min lr 1.01e-06
+
+=== run: ep=30 batch=128 ===
+ep 1/30 acc 0.819 prec 0.000 rec 0.000 f1 0.000 loss 0.799 time 0.3min lr 2.50e-04
+ep 2/30 acc 0.866 prec 0.815 rec 0.333 f1 0.473 loss 0.646 time 0.0min lr 5.00e-04
+ -> new best F1 0.473
+ep 3/30 acc 0.874 prec 0.647 rec 0.667 f1 0.657 loss 0.478 time 0.0min lr 7.50e-04
+ -> new best F1 0.657
+ep 4/30 acc 0.893 prec 0.814 rec 0.530 f1 0.642 loss 0.342 time 0.0min lr 1.00e-03
+ep 5/30 acc 0.893 prec 0.966 rec 0.424 f1 0.589 loss 0.263 time 0.1min lr 9.97e-04
+ep 6/30 acc 0.926 prec 1.000 rec 0.591 f1 0.743 loss 0.218 time 0.0min lr 9.86e-04
+ -> new best F1 0.743
+ep 7/30 acc 0.951 prec 0.887 rec 0.833 f1 0.859 loss 0.171 time 0.0min lr 9.68e-04
+ -> new best F1 0.859
+ep 8/30 acc 0.964 prec 1.000 rec 0.803 f1 0.891 loss 0.149 time 0.0min lr 9.44e-04
+ -> new best F1 0.891
+ep 9/30 acc 0.959 prec 0.947 rec 0.818 f1 0.878 loss 0.134 time 0.0min lr 9.13e-04
+ep 10/30 acc 0.956 prec 0.946 rec 0.803 f1 0.869 loss 0.114 time 0.0min lr 8.76e-04
+ep 11/30 acc 0.962 prec 0.964 rec 0.818 f1 0.885 loss 0.098 time 0.0min lr 8.34e-04
+ep 12/30 acc 0.970 prec 0.982 rec 0.848 f1 0.911 loss 0.091 time 0.0min lr 7.86e-04
+ -> new best F1 0.911
+ep 13/30 acc 0.959 prec 0.947 rec 0.818 f1 0.878 loss 0.089 time 0.0min lr 7.35e-04
+ep 14/30 acc 0.986 prec 0.969 rec 0.955 f1 0.962 loss 0.080 time 0.0min lr 6.80e-04
+ -> new best F1 0.962
+ep 15/30 acc 0.978 prec 0.968 rec 0.909 f1 0.937 loss 0.073 time 0.0min lr 6.22e-04
+ep 16/30 acc 0.964 prec 0.982 rec 0.818 f1 0.893 loss 0.061 time 0.0min lr 5.63e-04
+ep 17/30 acc 0.978 prec 0.968 rec 0.909 f1 0.937 loss 0.061 time 0.0min lr 5.03e-04
+ep 18/30 acc 0.959 prec 1.000 rec 0.773 f1 0.872 loss 0.054 time 0.0min lr 4.43e-04
+ep 19/30 acc 0.986 prec 0.984 rec 0.939 f1 0.961 loss 0.051 time 0.0min lr 3.83e-04
+ep 20/30 acc 0.970 prec 0.966 rec 0.864 f1 0.912 loss 0.056 time 0.0min lr 3.26e-04
+ep 21/30 acc 0.975 prec 0.983 rec 0.879 f1 0.928 loss 0.060 time 0.0min lr 2.71e-04
+ep 22/30 acc 0.984 prec 1.000 rec 0.909 f1 0.952 loss 0.045 time 0.0min lr 2.19e-04
+ep 23/30 acc 0.978 prec 0.968 rec 0.909 f1 0.937 loss 0.048 time 0.0min lr 1.71e-04
+ep 24/30 acc 0.975 prec 0.983 rec 0.879 f1 0.928 loss 0.046 time 0.0min lr 1.28e-04
+ep 25/30 acc 0.981 prec 1.000 rec 0.894 f1 0.944 loss 0.044 time 0.0min lr 9.08e-05
+ep 26/30 acc 0.989 prec 0.984 rec 0.955 f1 0.969 loss 0.047 time 0.0min lr 5.93e-05
+ -> new best F1 0.969
+ep 27/30 acc 0.984 prec 0.984 rec 0.924 f1 0.953 loss 0.042 time 0.0min lr 3.43e-05
+ep 28/30 acc 0.973 prec 0.938 rec 0.909 f1 0.923 loss 0.041 time 0.0min lr 1.61e-05
+ep 29/30 acc 0.975 prec 0.952 rec 0.909 f1 0.930 loss 0.042 time 0.0min lr 4.94e-06
+ep 30/30 acc 0.975 prec 0.952 rec 0.909 f1 0.930 loss 0.038 time 0.0min lr 1.01e-06
diff --git a/wasm/demo_mesh.html b/wasm/demo_mesh.html
index 34b38d1..7e4c0f0 100644
--- a/wasm/demo_mesh.html
+++ b/wasm/demo_mesh.html
@@ -199,7 +199,7 @@
<span class="chip ours">✦ ours <span class="num">1.1MB</span> <span class="src">98pt landmarks</span></span>
<span class="chip ours">✦ ours <span class="num">5.6MB</span> <span class="src">478pt 3D mesh</span></span>
<span class="chip ours">✦ ours <span class="num">1.8MB</span> <span class="src">recognition</span></span>
- <span class="chip ours">✦ ours <span class="num">187KB</span> <span class="src">tongue</span></span>
+ <span class="chip ours">✦ ours <span class="num">187KB</span> <span class="src">smile</span></span>
<span class="chip apache">Apache <span class="num">3.4MB</span> <span class="src">anti-spoof</span></span>
</div>
@@ -266,7 +266,7 @@ const btnUnlock = $('btnUnlock');
const btnSnap = $('btnSnap');
const btnStop = $('btnStop');
-let detSess = null, lmSess = null, recSess = null, lm3dSess = null, spoof27Sess = null, spoof40Sess = null, tongueSess = null, meshTopology = null, stream = null, running = false;
+let detSess = null, lmSess = null, recSess = null, lm3dSess = null, spoof27Sess = null, spoof40Sess = null, smileSess = null, meshTopology = null, stream = null, running = false;
let mode = 'hybrid';
let last3D = []; // per-face 478 [x,y,z] from true-3D model (overlay coords)
let lastHybrid = []; // per-face 478 [x,y,z] from hybrid (WFLW->MP via TPS)
@@ -280,10 +280,10 @@ let lastSim = null; // most recent cosine similarity to ref
let lastPts2d = null, lastBox = null, lastFaceCount = 0;
let lastLive = null, lastSpoof = null; // P(live), P(spoof) from antispoof model
let spoofMs = 0;
-let lastTongueProb = 0; // EMA-smoothed P(tongue out) from tongue classifier
-const TONGUE_EMA = 0.6;
-const TONGUE_THRESH = 0.6; // tuned for the F1=0.96 model
-let tongueMs = 0;
+let lastSmileProb = 0; // EMA-smoothed P(smile)
+const SMILE_EMA = 0.6;
+const SMILE_THRESH = 0.6;
+let smileMs = 0;
// Eye-blink detection (EAR — Eye Aspect Ratio) from our 98-pt WFLW landmarks.
// WFLW eye indices: left eye 60..67 (8 pts), right eye 68..75 (8 pts).
@@ -461,7 +461,7 @@ async function loadModels() {
['minifasnet_v2_27.enc', 'spoof27'],
['minifasnet_v1se_40.enc', 'spoof40'],
['facex_3d_landmarks.enc', 'lm3d'],
- ['facex_tongue.enc', 'tongue'],
+ ['facex_smile.enc', 'smile'],
];
const setSess = (name, s) => {
if (name === 'det') detSess = s;
@@ -470,7 +470,7 @@ async function loadModels() {
else if (name === 'spoof27') spoof27Sess = s;
else if (name === 'spoof40') spoof40Sess = s;
else if (name === 'lm3d') lm3dSess = s;
- else if (name === 'tongue') tongueSess = s;
+ else if (name === 'smile') smileSess = s;
};
for (let i = 0; i < steps.length; i++) {
@@ -856,11 +856,10 @@ function fillSpoofTensor(box, scale, dst) {
}
}
-// Tongue-out classifier. 112×112 RGB normalized [-1, 1], 2-class softmax.
-// Reuses lmCv canvas since it's 112×112 already. Index 1 = tongue.
-const tongueInput = new Float32Array(3 * 112 * 112);
-async function predictTongue(box) {
- if (!tongueSess) return 0;
+// Smile classifier — same shape/preprocessing as recognition.
+const smileInput = new Float32Array(3 * 112 * 112);
+async function predictSmile(box) {
+ if (!smileSess) return 0;
const bw = box.x2 - box.x1, bh = box.y2 - box.y1;
const side = Math.max(bw, bh) * (1 + 2 * 0.15);
const cx = (box.x1 + box.x2) / 2, cy = (box.y1 + box.y2) / 2;
@@ -872,13 +871,13 @@ async function predictTongue(box) {
const N = 112 * 112;
for (let i = 0, p = 0; i < N; i++) {
const r = img[p++], g = img[p++], b = img[p++]; p++;
- tongueInput[i] = (r - 127.5) / 128;
- tongueInput[N + i] = (g - 127.5) / 128;
- tongueInput[2 * N + i] = (b - 127.5) / 128;
+ smileInput[i] = (r - 127.5) / 128;
+ smileInput[N + i] = (g - 127.5) / 128;
+ smileInput[2 * N + i] = (b - 127.5) / 128;
}
- const t = new ort.Tensor('float32', tongueInput, [1, 3, 112, 112]);
- const o = await tongueSess.run({ input: t });
- return o['prob'].data[1]; // P(tongue out)
+ const t = new ort.Tensor('float32', smileInput, [1, 3, 112, 112]);
+ const o = await smileSess.run({ input: t });
+ return o['prob'].data[1];
}
async function predictSpoof(box) {
@@ -1620,7 +1619,7 @@ function drawHybrid(pts3d, matchFlag) {
// lip (MP idx 13) and lower inner lip (idx 14), normalized by horizontal
// mouth width (78 ↔ 308). If the ratio is high → user is sticking the
// tongue out (or yawning) → dye the LIPS group red for visual feedback.
- const tongueOut = (lastTongueProb > TONGUE_THRESH);
+ const smiling = (lastSmileProb > SMILE_THRESH);
for (const [a, b] of meshTopology.TESSELATION) shadedEdge(a, b, 0.75);
for (const grp of [meshTopology.FACE_OVAL,
@@ -1630,9 +1629,9 @@ function drawHybrid(pts3d, matchFlag) {
for (const [a, b] of grp) shadedEdge(a, b, 1.0);
}
// LIPS — red when mouth wide open (tongue likely visible)
- if (tongueOut) {
+ if (smiling) {
const sR = baseR, sG = baseG, sB = baseB;
- baseR = 255; baseG = 40; baseB = 70;
+ baseR = 251; baseG = 191; baseB = 36; // warm amber for smile
for (const [a, b] of meshTopology.LIPS) shadedEdge(a, b, 1.6);
baseR = sR; baseG = sG; baseB = sB;
} else {
@@ -1645,19 +1644,6 @@ function drawHybrid(pts3d, matchFlag) {
ctx.restore();
}
-// MediaPipe FaceMesh indices: 13 = upper inner lip center,
-// 14 = lower inner lip center, 78 = left inner mouth corner,
-// 308 = right inner mouth corner. Compare vertical opening to horizontal
-// mouth width — high ratio means mouth wide open / tongue out.
-function isMouthWide(pts) {
- if (!pts || pts.length < 309) return false;
- const u = pts[13], l = pts[14], lc = pts[78], rc = pts[308];
- if (!u || !l || !lc || !rc) return false;
- const mouthH = Math.abs(l[1] - u[1]);
- const mouthW = Math.abs(rc[0] - lc[0]);
- if (mouthW < 5) return false;
- return (mouthH / mouthW) > 0.35; // threshold tuned for "deliberate open"
-}
// Render the true-3D mesh from 478 predicted (x,y,z) landmarks.
// Each edge is shaded by the average z of its endpoints (forward = brighter, thicker).
@@ -1706,7 +1692,7 @@ function drawTrue3D(pts3d, matchFlag) {
}
// (1) Full tessellation — dense mesh
- const tongueOut = (lastTongueProb > TONGUE_THRESH);
+ const smiling = (lastSmileProb > SMILE_THRESH);
for (const [a, b] of meshTopology.TESSELATION) shadedEdge(a, b, 0.75);
@@ -1717,9 +1703,9 @@ function drawTrue3D(pts3d, matchFlag) {
meshTopology.NOSE]) {
for (const [a, b] of grp) shadedEdge(a, b, 1.0);
}
- if (tongueOut) {
+ if (smiling) {
const sR = baseR, sG = baseG, sB = baseB;
- baseR = 255; baseG = 40; baseB = 70;
+ baseR = 251; baseG = 191; baseB = 36; // warm amber for smile
for (const [a, b] of meshTopology.LIPS) shadedEdge(a, b, 1.6);
baseR = sR; baseG = sG; baseB = sB;
} else {
@@ -1843,7 +1829,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; pulseBuf = []; lastBPM = null; smoothedPts2d = []; busy = false; return; }
+ if (faces.length === 0) { lastAllPts2d = []; last3D = []; lastHybrid = []; lastFaceMatch = []; lastSim = null; lastLive = null; lastSpoof = null; emaLive = null; lastSmileProb = 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 = [];
@@ -1959,11 +1945,11 @@ async function tick() {
lastLive = emaLive;
lastSpoof = 1 - emaLive;
window.__lastRawLive = sp.live;
- // Tongue-out detection on the same face (also primary only).
- const t4 = performance.now();
- const tprob = await predictTongue(f);
- tongueMs = performance.now() - t4;
- lastTongueProb = TONGUE_EMA * lastTongueProb + (1 - TONGUE_EMA) * tprob;
+ // Smile detection on the same face (primary only).
+ const t5 = performance.now();
+ const sprob = await predictSmile(f);
+ smileMs = performance.now() - t5;
+ lastSmileProb = SMILE_EMA * lastSmileProb + (1 - SMILE_EMA) * sprob;
}
}
lmMs = (performance.now() - t1) / faces.length;
@@ -2103,7 +2089,7 @@ async function tick() {
`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 <span style="color:#34d399">(nn2 ≈${(spoofMs/2).toFixed(0)})</span>`,
- `tongue ${tongueMs.toFixed(0)}ms`,
+ `smile ${smileMs.toFixed(0)}ms`,
`${fps} fps`,
];
if (lastBPM != null) {
@@ -2124,8 +2110,8 @@ async function tick() {
const color = isLive ? '#10b981' : '#ef4444';
tags.push(`<span style="color:${color}">${label}</span>`);
}
- if (lastTongueProb > TONGUE_THRESH && lastFaceCount > 0) {
- tags.push(`<span style="color:#ef4444">👅 TONGUE ${(lastTongueProb*100).toFixed(0)}%</span>`);
+ if (lastSmileProb > SMILE_THRESH && lastFaceCount > 0) {
+ tags.push(`<span style="color:#fbbf24">😀 SMILE ${(lastSmileProb*100).toFixed(0)}%</span>`);
}
if (performance.now() < blinkFlashUntil) {
tags.push(`<span style="color:#60a5fa">👁 BLINK</span>`);
diff --git a/wasm/tools/encrypt_models.py b/wasm/tools/encrypt_models.py
index cf2f1da..fcd3764 100644
--- a/wasm/tools/encrypt_models.py
+++ b/wasm/tools/encrypt_models.py
@@ -23,7 +23,7 @@ TARGETS = [
"facex_tiny.onnx",
"minifasnet_v2_27.onnx",
"minifasnet_v1se_40.onnx",
- "facex_tongue.onnx",
+ "facex_smile.onnx",
]
KEY_FILE = WASM.parent / ".model_key"