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.

tongue detector: own binary classifier, ~47K params, F1 0.962 on web-scraped data

facex8c9e7f997a18
diff --git a/docs/demo/facex_tongue.enc b/docs/demo/facex_tongue.enc
new file mode 100644
index 0000000..5ed02e4
Binary files /dev/null and b/docs/demo/facex_tongue.enc differ
diff --git a/docs/demo/index.html b/docs/demo/index.html
index 7ca077e..5afa828 100644
--- a/docs/demo/index.html
+++ b/docs/demo/index.html
@@ -262,7 +262,7 @@ const btnLock = $('btnLock');
const btnUnlock = $('btnUnlock');
const btnStop = $('btnStop');
-let detSess = null, lmSess = null, recSess = null, lm3dSess = null, spoof27Sess = null, spoof40Sess = null, meshTopology = null, stream = null, running = false;
+let detSess = null, lmSess = null, recSess = null, lm3dSess = null, spoof27Sess = null, spoof40Sess = null, tongueSess = 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)
@@ -276,6 +276,9 @@ 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
// EMA smoothing for spoof probability — antispoof can flicker on partial occlusion
let emaLive = null;
const SPOOF_EMA = 0.65; // higher → smoother
@@ -428,6 +431,7 @@ async function loadModels() {
['minifasnet_v2_27.enc', 'spoof27'],
['minifasnet_v1se_40.enc', 'spoof40'],
['facex_3d_landmarks.enc', 'lm3d'],
+ ['facex_tongue.enc', 'tongue'],
];
const setSess = (name, s) => {
if (name === 'det') detSess = s;
@@ -436,6 +440,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;
};
for (let i = 0; i < steps.length; i++) {
@@ -642,6 +647,31 @@ 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;
+ 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;
+ const sx = cx - side / 2, sy = cy - side / 2;
+ lmCtx.fillStyle = '#000';
+ lmCtx.fillRect(0, 0, 112, 112);
+ lmCtx.drawImage(video, sx, sy, side, side, 0, 0, 112, 112);
+ const img = lmCtx.getImageData(0, 0, 112, 112).data;
+ 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;
+ }
+ 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)
+}
+
async function predictSpoof(box) {
fillSpoofTensor(box, 2.7, spoofInput27);
fillSpoofTensor(box, 4.0, spoofInput40);
@@ -1381,7 +1411,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 = isMouthWide(pts3d);
+ const tongueOut = (lastTongueProb > TONGUE_THRESH);
for (const [a, b] of meshTopology.TESSELATION) shadedEdge(a, b, 0.75);
for (const grp of [meshTopology.FACE_OVAL,
@@ -1467,7 +1497,7 @@ function drawTrue3D(pts3d, matchFlag) {
}
// (1) Full tessellation — dense mesh
- const tongueOut = isMouthWide(pts3d);
+ const tongueOut = (lastTongueProb > TONGUE_THRESH);
for (const [a, b] of meshTopology.TESSELATION) shadedEdge(a, b, 0.75);
@@ -1604,7 +1634,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; smoothedPts2d = []; busy = false; return; }
+ 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 !== smoothedPts2d.length) smoothedPts2d = []; // reset on face count change
const t1 = performance.now();
const all = [];
@@ -1715,12 +1745,14 @@ async function tick() {
const t3 = performance.now();
const sp = await predictSpoof(f);
spoofMs = performance.now() - t3;
- // EMA smoothing on live probability
emaLive = (emaLive == null) ? sp.live
: SPOOF_EMA * emaLive + (1 - SPOOF_EMA) * sp.live;
lastLive = emaLive;
lastSpoof = 1 - emaLive;
- window.__lastRawLive = sp.live; // for debug HUD
+ window.__lastRawLive = sp.live;
+ // Tongue-out detection on the same face (also primary only).
+ const tprob = await predictTongue(f);
+ lastTongueProb = TONGUE_EMA * lastTongueProb + (1 - TONGUE_EMA) * tprob;
}
}
lmMs = (performance.now() - t1) / faces.length;
diff --git a/training/tongue/runs/train.log b/training/tongue/runs/train.log
new file mode 100644
index 0000000..cfcf5db
--- /dev/null
+++ b/training/tongue/runs/train.log
@@ -0,0 +1,45 @@
+
+=== run: ep=30 batch=128 ===
+ep 1/30 acc 0.819 prec 0.000 rec 0.000 f1 0.000 loss 0.656 time 0.3min lr 2.50e-04
+ep 2/30 acc 0.866 prec 0.718 rec 0.424 f1 0.533 loss 0.562 time 0.0min lr 5.00e-04
+ -> new best F1 0.533
+ep 3/30 acc 0.830 prec 0.523 rec 0.697 f1 0.597 loss 0.479 time 0.0min lr 7.50e-04
+ -> new best F1 0.597
+ep 4/30 acc 0.797 prec 0.467 rec 0.864 f1 0.606 loss 0.423 time 0.0min lr 1.00e-03
+ -> new best F1 0.606
+ep 5/30 acc 0.830 prec 0.518 rec 0.894 f1 0.656 loss 0.379 time 0.0min lr 9.97e-04
+ -> new best F1 0.656
+ep 6/30 acc 0.910 prec 0.709 rec 0.848 f1 0.772 loss 0.325 time 0.0min lr 9.86e-04
+ -> new best F1 0.772
+ep 7/30 acc 0.926 prec 0.831 rec 0.742 f1 0.784 loss 0.304 time 0.0min lr 9.68e-04
+ -> new best F1 0.784
+ep 8/30 acc 0.926 prec 0.747 rec 0.894 f1 0.814 loss 0.248 time 0.0min lr 9.44e-04
+ -> new best F1 0.814
+ep 9/30 acc 0.932 prec 0.766 rec 0.894 f1 0.825 loss 0.219 time 0.0min lr 9.13e-04
+ -> new best F1 0.825
+ep 10/30 acc 0.956 prec 0.868 rec 0.894 f1 0.881 loss 0.181 time 0.0min lr 8.76e-04
+ -> new best F1 0.881
+ep 11/30 acc 0.945 prec 0.859 rec 0.833 f1 0.846 loss 0.175 time 0.0min lr 8.34e-04
+ep 12/30 acc 0.967 prec 0.875 rec 0.955 f1 0.913 loss 0.138 time 0.0min lr 7.86e-04
+ -> new best F1 0.913
+ep 13/30 acc 0.945 prec 0.780 rec 0.970 f1 0.865 loss 0.131 time 0.0min lr 7.35e-04
+ep 14/30 acc 0.953 prec 0.827 rec 0.939 f1 0.879 loss 0.114 time 0.0min lr 6.80e-04
+ep 15/30 acc 0.951 prec 0.800 rec 0.970 f1 0.877 loss 0.099 time 0.0min lr 6.22e-04
+ep 16/30 acc 0.981 prec 0.984 rec 0.909 f1 0.945 loss 0.087 time 0.0min lr 5.63e-04
+ -> new best F1 0.945
+ep 17/30 acc 0.956 prec 0.812 rec 0.985 f1 0.890 loss 0.100 time 0.0min lr 5.03e-04
+ep 18/30 acc 0.962 prec 0.894 rec 0.894 f1 0.894 loss 0.088 time 0.0min lr 4.43e-04
+ep 19/30 acc 0.956 prec 0.829 rec 0.955 f1 0.887 loss 0.082 time 0.0min lr 3.83e-04
+ep 20/30 acc 0.964 prec 0.873 rec 0.939 f1 0.905 loss 0.087 time 0.0min lr 3.26e-04
+ep 21/30 acc 0.981 prec 0.954 rec 0.939 f1 0.947 loss 0.065 time 0.0min lr 2.71e-04
+ -> new best F1 0.947
+ep 22/30 acc 0.967 prec 0.897 rec 0.924 f1 0.910 loss 0.065 time 0.0min lr 2.19e-04
+ep 23/30 acc 0.986 prec 0.955 rec 0.970 f1 0.962 loss 0.066 time 0.0min lr 1.71e-04
+ -> new best F1 0.962
+ep 24/30 acc 0.964 prec 0.873 rec 0.939 f1 0.905 loss 0.064 time 0.0min lr 1.28e-04
+ep 25/30 acc 0.984 prec 0.941 rec 0.970 f1 0.955 loss 0.080 time 0.0min lr 9.08e-05
+ep 26/30 acc 0.975 prec 0.925 rec 0.939 f1 0.932 loss 0.060 time 0.0min lr 5.93e-05
+ep 27/30 acc 0.978 prec 0.953 rec 0.924 f1 0.938 loss 0.063 time 0.0min lr 3.43e-05
+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
diff --git a/training/tongue/scripts/build_dataset.py b/training/tongue/scripts/build_dataset.py
new file mode 100644
index 0000000..51dc9d8
--- /dev/null
+++ b/training/tongue/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/tongue/train_raw.bin (N*112*112*3 uint8)
+ D:/apps/facex/training/data/tongue/train_labels.bin (N uint8)
+ D:/apps/facex/training/data/tongue/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/tongue/faces_pos")
+OUT = Path("D:/apps/facex/training/data/tongue")
+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/tongue/scripts/dataset.py b/training/tongue/scripts/dataset.py
new file mode 100644
index 0000000..ea1db33
--- /dev/null
+++ b/training/tongue/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/tongue")
+SIZE = 112
+
+
+class TongueDataset(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/tongue/scripts/export.py b/training/tongue/scripts/export.py
new file mode 100644
index 0000000..c55b652
--- /dev/null
+++ b/training/tongue/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 TongueNet
+
+
+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/tongue/runs/best.pt")
+ ap.add_argument("--out", default="D:/apps/facex/wasm/facex_tongue.onnx")
+ args = ap.parse_args()
+
+ net = TongueNet().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/tongue/scripts/model.py b/training/tongue/scripts/model.py
new file mode 100644
index 0000000..04ed801
--- /dev/null
+++ b/training/tongue/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 TongueNet(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 = TongueNet().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/tongue/scripts/scrape_positives.py b/training/tongue/scripts/scrape_positives.py
new file mode 100644
index 0000000..daf11ce
--- /dev/null
+++ b/training/tongue/scripts/scrape_positives.py
@@ -0,0 +1,133 @@
+"""Scrape tongue-out face photos from the web.
+
+Strategy: DDGS image search for several variant queries, dedup by URL,
+download with browser-like User-Agent and timeout, then crop to faces
+with YuNet so we get clean 112x112 inputs.
+"""
+
+import os, time, hashlib, urllib.request, ssl
+from pathlib import Path
+
+import cv2
+import numpy as np
+from ddgs import DDGS
+
+OUT = Path("D:/apps/facex/training/data/tongue/raw_pos")
+OUT.mkdir(parents=True, exist_ok=True)
+CROP_OUT = Path("D:/apps/facex/training/data/tongue/faces_pos")
+CROP_OUT.mkdir(parents=True, exist_ok=True)
+
+YUNET = "D:/apps/facex/_unencrypted_backup/yunet_2023mar.onnx"
+
+QUERIES = [
+ "selfie tongue out",
+ "person sticking tongue out",
+ "tongue out face photo",
+ "tongue out portrait",
+ "kid tongue out",
+ "girl tongue out selfie",
+ "man tongue out funny",
+ "tongue out face close up",
+ "high five tongue out",
+ "playful tongue out",
+ "child sticking tongue out",
+ "adult tongue out face",
+ "happy tongue out",
+ "rock concert tongue out",
+ "tongue sticking out close",
+ "miley cyrus tongue",
+ "albert einstein tongue",
+ "musician tongue out stage",
+ "athlete tongue out celebration",
+ "actress tongue out red carpet",
+ "kawaii anime girl tongue out",
+ "boy tongue out funny face",
+ "tongue out kiss face",
+ "tongue out wink",
+ "summer tongue out outdoor",
+]
+
+MAX_PER_QUERY = 200
+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) # cap 5 MB
+ 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
+ crop = cv2.resize(crop, (112, 112))
+ cv2.imwrite(str(dst_path), crop)
+ 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 % 25 == 0:
+ print(f" saved {downloaded} so far")
+ if downloaded >= TARGET_TOTAL: break
+
+ print(f"\nraw saved: {downloaded}")
+
+ # Now face-crop
+ 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/training/tongue/scripts/train.py b/training/tongue/scripts/train.py
new file mode 100644
index 0000000..fbc1002
--- /dev/null
+++ b/training/tongue/scripts/train.py
@@ -0,0 +1,116 @@
+"""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 TongueNet
+from dataset import TongueDataset
+
+
+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 = TongueDataset(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 = TongueNet().to(device)
+ print(f"params: {model.num_params():,}")
+
+ # Class-balanced loss: positives are rare
+ n_pos = sum(1 for _, l in [(None, full._lbl[i] if full._lbl is not None else 0) for i in range(min(100, n))])
+ # Reload meta for true ratio
+ import json
+ meta = json.loads((Path("D:/apps/facex/training/data/tongue") / "meta.json").read_text())
+ pos_w = meta["n_neg"] / max(1, meta["n_pos"])
+ print(f"positive class weight: {pos_w:.2f}")
+ class_weights = torch.tensor([1.0, pos_w], device=device)
+
+ 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/tongue/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)
+ 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/wasm/demo_mesh.html b/wasm/demo_mesh.html
index 7ca077e..5afa828 100644
--- a/wasm/demo_mesh.html
+++ b/wasm/demo_mesh.html
@@ -262,7 +262,7 @@ const btnLock = $('btnLock');
const btnUnlock = $('btnUnlock');
const btnStop = $('btnStop');
-let detSess = null, lmSess = null, recSess = null, lm3dSess = null, spoof27Sess = null, spoof40Sess = null, meshTopology = null, stream = null, running = false;
+let detSess = null, lmSess = null, recSess = null, lm3dSess = null, spoof27Sess = null, spoof40Sess = null, tongueSess = 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)
@@ -276,6 +276,9 @@ 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
// EMA smoothing for spoof probability — antispoof can flicker on partial occlusion
let emaLive = null;
const SPOOF_EMA = 0.65; // higher → smoother
@@ -428,6 +431,7 @@ async function loadModels() {
['minifasnet_v2_27.enc', 'spoof27'],
['minifasnet_v1se_40.enc', 'spoof40'],
['facex_3d_landmarks.enc', 'lm3d'],
+ ['facex_tongue.enc', 'tongue'],
];
const setSess = (name, s) => {
if (name === 'det') detSess = s;
@@ -436,6 +440,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;
};
for (let i = 0; i < steps.length; i++) {
@@ -642,6 +647,31 @@ 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;
+ 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;
+ const sx = cx - side / 2, sy = cy - side / 2;
+ lmCtx.fillStyle = '#000';
+ lmCtx.fillRect(0, 0, 112, 112);
+ lmCtx.drawImage(video, sx, sy, side, side, 0, 0, 112, 112);
+ const img = lmCtx.getImageData(0, 0, 112, 112).data;
+ 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;
+ }
+ 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)
+}
+
async function predictSpoof(box) {
fillSpoofTensor(box, 2.7, spoofInput27);
fillSpoofTensor(box, 4.0, spoofInput40);
@@ -1381,7 +1411,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 = isMouthWide(pts3d);
+ const tongueOut = (lastTongueProb > TONGUE_THRESH);
for (const [a, b] of meshTopology.TESSELATION) shadedEdge(a, b, 0.75);
for (const grp of [meshTopology.FACE_OVAL,
@@ -1467,7 +1497,7 @@ function drawTrue3D(pts3d, matchFlag) {
}
// (1) Full tessellation — dense mesh
- const tongueOut = isMouthWide(pts3d);
+ const tongueOut = (lastTongueProb > TONGUE_THRESH);
for (const [a, b] of meshTopology.TESSELATION) shadedEdge(a, b, 0.75);
@@ -1604,7 +1634,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; smoothedPts2d = []; busy = false; return; }
+ 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 !== smoothedPts2d.length) smoothedPts2d = []; // reset on face count change
const t1 = performance.now();
const all = [];
@@ -1715,12 +1745,14 @@ async function tick() {
const t3 = performance.now();
const sp = await predictSpoof(f);
spoofMs = performance.now() - t3;
- // EMA smoothing on live probability
emaLive = (emaLive == null) ? sp.live
: SPOOF_EMA * emaLive + (1 - SPOOF_EMA) * sp.live;
lastLive = emaLive;
lastSpoof = 1 - emaLive;
- window.__lastRawLive = sp.live; // for debug HUD
+ window.__lastRawLive = sp.live;
+ // Tongue-out detection on the same face (also primary only).
+ const tprob = await predictTongue(f);
+ lastTongueProb = TONGUE_EMA * lastTongueProb + (1 - TONGUE_EMA) * tprob;
}
}
lmMs = (performance.now() - t1) / faces.length;
diff --git a/wasm/tools/encrypt_models.py b/wasm/tools/encrypt_models.py
index 9128cb3..cf2f1da 100644
--- a/wasm/tools/encrypt_models.py
+++ b/wasm/tools/encrypt_models.py
@@ -23,6 +23,7 @@ TARGETS = [
"facex_tiny.onnx",
"minifasnet_v2_27.onnx",
"minifasnet_v1se_40.onnx",
+ "facex_tongue.onnx",
]
KEY_FILE = WASM.parent / ".model_key"