Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(selfie): share one tested threshold module between the live capture gate and the photo check
nirholas44e6c37d04ac
diff --git a/src/face-quality.js b/src/face-quality.jsindex ca284a924..3b09048bd 100644--- a/src/face-quality.js+++ b/src/face-quality.js@@ -20,6 +20,8 @@* for subsequent sessions. CDN-hosted for Vite WASM compatibility.*/+import { SLOT_PRESETS, gradeFrame, grayFaceStats } from './selfie-gates.js';+const TASKS_VISION_URL ='https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/+esm';const WASM_ROOT =@@ -27,10 +29,6 @@ const WASM_ROOT =const MODEL_URL ='https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task';-const BLUR_MIN = 3.5;-const LUMA_MIN = 40;-const LUMA_MAX = 218;-let _modPromise = null;let _landmarkerPromise = null;@@ -66,14 +64,11 @@ export function preload() {}/**- * Slot presets for yaw-angle gating.- * Yaw sign: looking left (camera's right) → positive.+ * Slot presets for yaw-angle gating live in selfie-gates.js (the shared,+ * unit-tested threshold module); re-exported here so existing consumers keep+ * their import path. Yaw sign: looking left (camera's right) → positive.*/-export const SLOT_PRESETS = {- frontal: { label: 'Frontal', min: -15, max: 15 },- left: { label: 'Left ~45°', min: 30, max: 60 },- right: { label: 'Right ~45°', min: -60, max: -30 },-};+export { SLOT_PRESETS };/*** @typedef {Object} QualityReport@@ -88,6 +83,7 @@ export const SLOT_PRESETS = {* @property {number|null} roll* @property {number} blur* @property {number} luma+ * @property {string|null} reason User-facing retake prompt; null when allPass.* @property {Array|null} landmarks*/@@ -168,8 +164,7 @@ export async function createQualitySession(videoEl, canvasEl, opts = {}) {const lms = result.faceLandmarks?.[0];if (!lms || lms.length < 468) {return {- faceFound: false, centered: false, yawOk: false,- blurOk: false, lumaOk: false, allPass: false,+ ...gradeFrame({ faceFound: false }),yaw: null, pitch: null, roll: null,blur: 0, luma: 0, landmarks: null,};@@ -179,21 +174,20 @@ export async function createQualitySession(videoEl, canvasEl, opts = {}) {const pose = estimateHeadPose(lms);const nose = lms[1] || lms[4];- const centered = nose && Math.abs(nose.x - 0.5) < 0.22 && Math.abs(nose.y - 0.5) < 0.28;const q = computeFaceQuality(videoEl, lms);- const slotCfg = SLOT_PRESETS[_slot] || SLOT_PRESETS.frontal;- const yawOk = pose.yaw >= slotCfg.min && pose.yaw <= slotCfg.max;- const blurOk = q.blur >= BLUR_MIN;- const lumaOk = q.luma >= LUMA_MIN && q.luma <= LUMA_MAX;+ const grade = gradeFrame({+ faceFound: true,+ slot: _slot,+ yaw: pose.yaw,+ noseX: nose ? nose.x : null,+ noseY: nose ? nose.y : null,+ blur: q.blur,+ luma: q.luma,+ });return {- faceFound: true,- centered,- yawOk,- blurOk,- lumaOk,- allPass: yawOk && centered && blurOk && lumaOk,+ ...grade,yaw: pose.yaw,pitch: pose.pitch,roll: pose.roll,@@ -252,30 +246,12 @@ export async function createQualitySession(videoEl, canvasEl, opts = {}) {_qCtx.drawImage(video, fx, fy, fw, fh, 0, 0, SIZE, SIZE);const { data: d } = _qCtx.getImageData(0, 0, SIZE, SIZE);- const n = SIZE * SIZE;- const grays = new Float32Array(n);- let lumaSum = 0;+ const grays = new Float32Array(SIZE * SIZE);for (let i = 0, j = 0; i < d.length; i += 4, j++) {- const g = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];- grays[j] = g;- lumaSum += g;+ grays[j] = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];}- const luma = lumaSum / n;- let ls = 0, ls2 = 0, ln = 0;- for (let row = 1; row < SIZE - 1; row++) {- for (let col = 1; col < SIZE - 1; col++) {- const c = grays[row * SIZE + col];- const lap = 4 * c- - grays[(row - 1) * SIZE + col]- - grays[(row + 1) * SIZE + col]- - grays[row * SIZE + (col - 1)]- - grays[row * SIZE + (col + 1)];- ls += lap; ls2 += lap * lap; ln++;- }- }- const mean = ls / ln;- const blur = Math.sqrt(Math.max(0, ls2 / ln - mean * mean));- return { luma, blur };+ const { luma, blurStddev } = grayFaceStats(grays, SIZE, SIZE);+ return { luma, blur: blurStddev };}return session;@@ -304,10 +280,13 @@ export function estimateHeadPose(lms) {}/**- * Run a one-shot quality check on a static image.- * Useful for validating uploaded photos.+ * Run a one-shot quality check on a static image (an upload, or the frozen+ * still the camera captured after the countdown). Unlike the live session,+ * this measures the exact pixels that would be submitted, so countdown motion+ * blur and lighting shifts that happened after the live gates passed are+ * still caught. Applies the same shared gates as the viewfinder.*- * @param {HTMLImageElement|ImageBitmap} source+ * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} source* @param {string} [slot='frontal']* @returns {Promise<QualityReport>}*/@@ -327,8 +306,7 @@ export async function checkImageQuality(source, slot = 'frontal') {const lms = result.faceLandmarks?.[0];if (!lms || lms.length < 468) {return {- faceFound: false, centered: false, yawOk: false,- blurOk: true, lumaOk: true, allPass: false,+ ...gradeFrame({ faceFound: false }),yaw: null, pitch: null, roll: null,blur: 0, luma: 0, landmarks: null,};@@ -336,22 +314,67 @@ export async function checkImageQuality(source, slot = 'frontal') {const pose = estimateHeadPose(lms);const nose = lms[1] || lms[4];- const centered = nose && Math.abs(nose.x - 0.5) < 0.30 && Math.abs(nose.y - 0.5) < 0.35;- const slotCfg = SLOT_PRESETS[slot] || SLOT_PRESETS.frontal;- const yawOk = pose.yaw >= slotCfg.min && pose.yaw <= slotCfg.max;+ const q = measureStillFace(source, lms);- return {+ const grade = gradeFrame({faceFound: true,- centered,- yawOk,- blurOk: true,- lumaOk: true,- allPass: yawOk && centered,+ slot,+ yaw: pose.yaw,+ noseX: nose ? nose.x : null,+ noseY: nose ? nose.y : null,+ blur: q.blur,+ luma: q.luma,+ });++ return {+ ...grade,yaw: pose.yaw,pitch: pose.pitch,roll: pose.roll,- blur: 0,- luma: 0,+ blur: q.blur,+ luma: q.luma,landmarks: lms,};}++/**+ * Blur/luma measurement for a static source: crop to the landmark bounding+ * box (small padding) and sample at the same 64px working size the live+ * session uses, so the shared thresholds apply to both paths.+ *+ * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} source+ * @param {Array<{x:number,y:number}>} lms normalised landmarks+ * @returns {{ luma: number, blur: number }}+ */+function measureStillFace(source, lms) {+ const SIZE = 64;+ const sw = source.videoWidth || source.naturalWidth || source.width;+ const sh = source.videoHeight || source.naturalHeight || source.height;+ if (!sw || !sh) return { luma: 0, blur: 0 };+ let minX = 1, minY = 1, maxX = 0, maxY = 0;+ for (const lm of lms) {+ if (lm.x < minX) minX = lm.x;+ if (lm.y < minY) minY = lm.y;+ if (lm.x > maxX) maxX = lm.x;+ if (lm.y > maxY) maxY = lm.y;+ }+ const pad = 0.05;+ const fx = Math.max(0, minX - pad) * sw;+ const fy = Math.max(0, minY - pad) * sh;+ const fw = Math.min(sw - fx, (maxX - minX + 2 * pad) * sw);+ const fh = Math.min(sh - fy, (maxY - minY + 2 * pad) * sh);+ if (fw < 4 || fh < 4) return { luma: 0, blur: 0 };++ const canvas = document.createElement('canvas');+ canvas.width = canvas.height = SIZE;+ const ctx = canvas.getContext('2d', { willReadFrequently: true });+ if (!ctx) return { luma: 0, blur: 0 };+ ctx.drawImage(source, fx, fy, fw, fh, 0, 0, SIZE, SIZE);+ const { data: d } = ctx.getImageData(0, 0, SIZE, SIZE);+ const grays = new Float32Array(SIZE * SIZE);+ for (let i = 0, j = 0; i < d.length; i += 4, j++) {+ grays[j] = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];+ }+ const { luma, blurStddev } = grayFaceStats(grays, SIZE, SIZE);+ return { luma, blur: blurStddev };+}diff --git a/src/selfie-gates.js b/src/selfie-gates.jsnew file mode 100644index 000000000..d6300b0d2--- /dev/null+++ b/src/selfie-gates.js@@ -0,0 +1,177 @@+/**+ * Selfie capture gates: the single source of truth for every quality threshold+ * the /create/selfie viewfinder and photo assessment enforce, plus the pure+ * scoring functions that apply them. No DOM, no MediaPipe: everything here is+ * unit-testable math over numbers the callers extract from frames.+ *+ * Why these numbers and not invented ones: each threshold is traced to a way+ * the reconstruction pipeline actually fails, so the client rejects for the+ * same reasons the backend would. Sources of truth, in the repo:+ *+ * - "no face" is the native worker's ONLY hard input rejection+ * (workers/avatar-reconstruction/face_pipeline.py raises+ * InputError("no face detected in any of the provided photos") after a+ * FaceMesh pass at min_detection_confidence=0.4 and a BlazeFace small-face+ * rescue at 0.3). The client mirrors it as the only capture-blocking gate.+ * - Yaw: face_pipeline.MAX_MORPH_YAW_DEG = 35. Above ~35 degrees the worker+ * skips the geometry morph because the self-occluded half of the face is+ * depth extrapolation, not structure (eval/detection_guard.py: clean+ * frontals peak at 2.7 degrees, the one benchmark input that breaks the+ * morph band reads 58.6). The frontal window of +/-15 keeps captures deep+ * inside the morph-safe zone; side slots target the ~45 degree band the+ * multi-view texture pass expects.+ * - Blur: the provider reconstruction lanes fail jobs whose error text the+ * status mapper (src/selfie-pipeline.js friendlyJobError) matches on+ * "blur", and the worker's robustness benchmark+ * (workers/avatar-reconstruction/eval/robustness.py `blurred`) models the+ * defect as a Gaussian blur of radius longestEdge/220. BLUR_STDDEV_MIN is+ * the live-feed equivalent: the Laplacian response stddev of a 64px face+ * crop under that degradation drops well below 3.5 while handheld-sharp+ * faces sit far above it. SHARPNESS_VAR_MIN = 90 is the same idea at+ * still-photo resolution (variance, not stddev, at up to 1024px), the+ * threshold src/selfie-refine.js has always applied at submit time.+ * - Lighting: the robustness benchmark's `dim` degradation (brightness x0.42,+ * "indoor evening") lands a typical selfie's mean face luma at the LUMA_MIN+ * boundary, and the adversarial set's "hard-backlight, face in deep shadow"+ * case is the classic path to the worker's no-face InputError. LUMA_MAX+ * catches the blown-highlight mirror image (a washed-out face loses the+ * texture the UV warp samples).+ * - Centering: the refine stage (src/selfie-refine.js computeSubjectFrame)+ * reframes to a head-and-shoulders square around the detected face, so a+ * badly off-centre face costs crop headroom rather than failing outright.+ * CENTER_TOL_X/Y bound the nose offset so the reframe never has to choose+ * between cutting the head and leaving the subject at the frame edge.+ */++/** Yaw windows per capture slot, in degrees. Positive = looking left. */+export const SLOT_PRESETS = Object.freeze({+ frontal: Object.freeze({ label: 'Frontal', min: -15, max: 15 }),+ left: Object.freeze({ label: 'Left ~45°', min: 30, max: 60 }),+ right: Object.freeze({ label: 'Right ~45°', min: -60, max: -30 }),+});++export const GATES = Object.freeze({+ /** Laplacian-response stddev floor on the 64px live face crop. */+ BLUR_STDDEV_MIN: 3.5,+ /** Variance-of-Laplacian floor for still photos at up to 1024px. */+ SHARPNESS_VAR_MIN: 90,+ /** Mean face luma bounds (Rec. 601, 0..255). */+ LUMA_MIN: 40,+ LUMA_MAX: 218,+ /** Max nose offset from frame centre, as a fraction of frame size. */+ CENTER_TOL_X: 0.22,+ CENTER_TOL_Y: 0.28,+ /** Worker skips the geometry morph above this head yaw (degrees). */+ MORPH_YAW_MAX: 35,+});++/**+ * Mean luma and Laplacian-response stddev of an 8-bit grey buffer.+ * This is the live viewfinder's blur/lighting measurement, extracted pure so+ * it can be pinned by unit tests. `blurStddev` is the standard deviation of a+ * 4-neighbour Laplacian over the interior pixels: sharp facial detail yields+ * strong high-frequency response, defocus and motion blur collapse it.+ *+ * @param {Uint8Array|Uint8ClampedArray|Float32Array|number[]} grey row-major, length w*h+ * @param {number} w+ * @param {number} h+ * @returns {{ luma: number, blurStddev: number }}+ */+export function grayFaceStats(grey, w, h) {+ const n = w * h;+ if (n === 0) return { luma: 0, blurStddev: 0 };+ let lumaSum = 0;+ for (let i = 0; i < n; i++) lumaSum += grey[i];+ const luma = lumaSum / n;+ if (w < 3 || h < 3) return { luma, blurStddev: 0 };+ let ls = 0;+ let ls2 = 0;+ let ln = 0;+ for (let row = 1; row < h - 1; row++) {+ for (let col = 1; col < w - 1; col++) {+ const c = grey[row * w + col];+ const lap =+ 4 * c -+ grey[(row - 1) * w + col] -+ grey[(row + 1) * w + col] -+ grey[row * w + (col - 1)] -+ grey[row * w + (col + 1)];+ ls += lap;+ ls2 += lap * lap;+ ln++;+ }+ }+ const mean = ls / ln;+ const blurStddev = Math.sqrt(Math.max(0, ls2 / ln - mean * mean));+ return { luma, blurStddev };+}++/**+ * Grade one live viewfinder frame against the capture gates and name exactly+ * what is wrong, in the order the user should fix it. Pure.+ *+ * @param {{+ * faceFound: boolean,+ * slot?: 'frontal'|'left'|'right'|string,+ * yaw?: number|null,+ * noseX?: number|null, noseY?: number|null,+ * blur?: number,+ * luma?: number,+ * }} m `blur` is the grayFaceStats blurStddev; noseX/noseY are normalised 0..1.+ * @returns {{+ * faceFound: boolean, yawOk: boolean, centered: boolean,+ * blurOk: boolean, lumaOk: boolean, allPass: boolean,+ * reason: string|null,+ * }} `reason` is the user-facing retake prompt, null when every gate passes.+ */+export function gradeFrame(m) {+ if (!m.faceFound) {+ return {+ faceFound: false,+ yawOk: false,+ centered: false,+ blurOk: false,+ lumaOk: false,+ allPass: false,+ reason: 'No face detected. Face the camera.',+ };+ }+ const slot = m.slot || 'frontal';+ const cfg = SLOT_PRESETS[slot] || SLOT_PRESETS.frontal;+ const yaw = typeof m.yaw === 'number' ? m.yaw : 0;+ const yawOk = yaw >= cfg.min && yaw <= cfg.max;+ const centered =+ typeof m.noseX === 'number' &&+ typeof m.noseY === 'number' &&+ Math.abs(m.noseX - 0.5) < GATES.CENTER_TOL_X &&+ Math.abs(m.noseY - 0.5) < GATES.CENTER_TOL_Y;+ const blurOk = (m.blur ?? 0) >= GATES.BLUR_STDDEV_MIN;+ const lumaOk = (m.luma ?? 0) >= GATES.LUMA_MIN && (m.luma ?? 0) <= GATES.LUMA_MAX;++ let reason = null;+ if (!yawOk) {+ reason =+ slot === 'frontal'+ ? 'Face the camera straight on.'+ : `Turn your head ${slot === 'left' ? 'left' : 'right'} about 45°.`;+ } else if (!centered) {+ reason = 'Center your face in the oval.';+ } else if (!blurOk) {+ reason = 'Hold steady. The image is blurry.';+ } else if (!lumaOk) {+ reason =+ (m.luma ?? 0) < GATES.LUMA_MIN+ ? 'Too dark. Find better light.'+ : 'Too bright. Reduce glare.';+ }++ return {+ faceFound: true,+ yawOk,+ centered,+ blurOk,+ lumaOk,+ allPass: yawOk && centered && blurOk && lumaOk,+ reason,+ };+}diff --git a/src/selfie-refine.js b/src/selfie-refine.jsindex 9a6e2efea..6ff6bc5e9 100644--- a/src/selfie-refine.js+++ b/src/selfie-refine.js@@ -27,6 +27,7 @@* and never throws into the capture flow.*/+import { GATES } from './selfie-gates.js';import { log } from './shared/log.js';// MediaPipe tasks-vision — same pinned build the face stack uses, so the WASM@@ -175,7 +176,9 @@ export function meanSaturation(rgba, w, h, stride = 4) {* sharpness: number,* flatness: number,* saturation: number,- * }} m+ * luma?: number,+ * }} m `luma` is the mean face luma (0..255) when the caller measured it;+ * omitted, lighting is not judged (the server stays the final authority).* @returns {{ verdict: 'good'|'warn'|'block', issues: string[], primary: string|null, message: string }}*/export function assessPhotoQuality(m) {@@ -201,6 +204,10 @@ export function assessPhotoQuality(m) {if (m.width < THRESH.minDimPx || m.height < THRESH.minDimPx) issues.push('low-res');if (m.sharpness < THRESH.sharpnessBlurry) issues.push('blurry');+ if (typeof m.luma === 'number') {+ if (m.luma < GATES.LUMA_MIN) issues.push('dark');+ else if (m.luma > GATES.LUMA_MAX) issues.push('bright');+ }if (m.flatness > THRESH.flatnessHigh && m.saturation > THRESH.saturationHigh)issues.push('illustration');@@ -208,12 +215,14 @@ export function assessPhotoQuality(m) {illustration:'This looks like a drawing or cartoon. 3D works best from a real photo — a flat illustration may come out flat. You can continue, but a real selfie gives a real you.',blurry: 'This photo looks soft. A sharper, well-lit shot reconstructs with more detail.',+ dark: 'Your face is in shadow. Face a light source so your features are visible.',+ bright: 'Your face is washed out. Step away from direct light or glare.',far: 'Your face is small in frame. Move closer or crop tighter for a stronger likeness.','low-res': 'This image is low-resolution. A larger photo captures more facial detail.','multiple-faces': "More than one face detected — we'll use the largest. Crop to just you for the best result.",};- const order = ['illustration', 'blurry', 'far', 'low-res', 'multiple-faces'];+ const order = ['illustration', 'blurry', 'dark', 'bright', 'far', 'low-res', 'multiple-faces'];const primary = order.find((k) => issues.includes(k)) || null;return {verdict: issues.length ? 'warn' : 'good',@@ -453,6 +462,20 @@ export async function assessPhoto(bitmap) {? { x: face.x * w, y: face.y * h, w: face.w * w, h: face.h * h }: null;+ // Mean luma over the face region (whole frame when no box): the lighting+ // gate cares whether the FACE is legible, not whether the room is bright.+ let luma;+ {+ const bx = face ? Math.max(0, Math.round(face.x * s.w)) : 0;+ const by = face ? Math.max(0, Math.round(face.y * s.h)) : 0;+ const bw = face ? Math.min(s.w - bx, Math.max(1, Math.round(face.w * s.w))) : s.w;+ const bh = face ? Math.min(s.h - by, Math.max(1, Math.round(face.h * s.h))) : s.h;+ let sum = 0;+ for (let y = by; y < by + bh; y++)+ for (let x = bx; x < bx + bw; x++) sum += grey[y * s.w + x];+ luma = sum / (bw * bh);+ }+const assessment = assessPhotoQuality({width: w,height: h,@@ -461,6 +484,7 @@ export async function assessPhoto(bitmap) {sharpness: laplacianVariance(grey, s.w, s.h),flatness: flatnessScore(grey, s.w, s.h),saturation: meanSaturation(data, s.w, s.h),+ luma,});return { ...assessment, faceBox: faceBoxPx };} catch (err) {