TrueFace
A decoupled real-time facial recognition and identity verification architecture combining in-browser WASM face tracking at 15–30 FPS with server-side MTCNN 5-point alignment and FaceNet 512-dimensional vector embeddings.

TrueFace live browser tracking: 24 FPS client-side tracking with server-side FaceNet 512-D embedding verification.
L2-normalized Euclidean face embeddings extracted via Inception-ResNet-v1 (FaceNet).
Client-side WASM TinyFaceDetector providing real-time bounding box feedback without network lag.
Affine transformation aligning eye pupils horizontally onto a 160x160 normalized tensor.
Cosine similarity threshold ensuring high-confidence identity verification against enrolled index.
Executive Overview
What It Is
TrueFace is an end-to-end real-time facial recognition and identity verification system. It couples an ultra-lightweight client-side browser perception engine with a high-throughput Python FastAPI deep learning microservice.
Why It Exists
Traditional computer vision web applications stream raw, uncompressed video frames (30 FPS × 1080p) from client webcams to backend Python servers. Over standard Indian residential broadband and cellular connections, this saturates network bandwidth, creates 400ms–900ms latency bottlenecks, and crashes server video decoders under multiple concurrent users. Javed engineered TrueFace to decouple client-side visual perception from server-side deep feature extraction.
Who It Serves
Educational institutions, workplace attendance portals, and privacy-conscious web platforms requiring real-time identity verification that operates smoothly in browser environments without expensive GPU streaming servers.
The Engineering Core
A decoupled two-tier architecture: In-browser WebAssembly (TinyFaceDetector) tracks face bounding boxes locally at 15–30 FPS with exponential coordinate smoothing, sending only throttled high-resolution face crops (2–3 per second) to FastAPI for MTCNN 5-point alignment and FaceNet 512-D vector matching.
✨ Key Architecture Takeaways:
- ✓Decouples client-side 30 FPS video tracking from server-side vector embedding extraction.
- ✓MTCNN 5-point facial landmark alignment normalizes facial poses before FaceNet vectorization.
- ✓Zero-retraining dynamic enrollment: registers new users in seconds using centroid vector averages without neural network fine-tuning.
Problem & Ground Motivation
The Bandwidth and Latency Crisis in Web-Based Facial Recognition
Building facial recognition in a native desktop Python application with OpenCV and an attached USB webcam is relatively straightforward. However, transitioning that pipeline to a modern web application accessed by distributed users introduces massive architectural bottlenecks.
Most naive implementations attempt to stream continuous raw video frames over WebSockets or HTTP multipart streams to a backend server running PyTorch. A standard 1080p webcam stream at 30 FPS generates over 25 Mbps of raw image data per user. On residential Indian internet connections, this results in dropped frames, massive network buffer bloat, and roundtrip latencies exceeding 800 milliseconds.
Furthermore, subjecting entire video streams to deep convolutional neural networks (CNNs) on the server overwhelms backend GPUs, limiting server concurrency to 2 or 3 simultaneous users before catastrophic slowdown.
TrueFace was engineered from the ground up to solve this fundamental architectural challenge: How can a web application deliver smooth 30 FPS visual feedback in the browser while maintaining rigorous deep learning verification accuracy on the server?
⚠️ Real-World Ground Constraints:
- ▪Bandwidth constraint: Total network transmission per user must remain under 150 KB/second.
- ▪Pose variation constraint: Users naturally tilt, turn, and pitch their heads in front of laptop webcams, degrading Euclidean vector matching if faces are unaligned.
- ▪Enrollment friction: Adding a new user must not require retraining or fine-tuning neural network weights, which takes hours and requires massive compute.
TrueFace shifts the responsibility of face tracking to the client browser using WebAssembly. The server is freed from processing full video frames and acts purely as a high-precision vector embedding microservice.
Goals & Engineering Constraints
🎯 Functional Goals
- •Track facial bounding boxes in the user browser at a fluid 15–30 FPS with zero server roundtrips.
- •Normalize facial poses on the server using 5-point MTCNN landmark alignment (eyes, nose, mouth corners).
- •Extract 512-dimensional Euclidean face embeddings using Inception-ResNet-v1 (FaceNet).
- •Match extracted vectors against an enrolled user index using Cosine Similarity with a strict 0.45 threshold.
- •Support dynamic zero-retraining enrollment of new identities using 3–5 sample image centroid vectors.
✨ UX & Ergonomics
- •Immediate visual feedback: smooth green bounding box overlay that hugs the user face without visual jitter.
- •Clear verification badges displaying matched user name, confidence score, and real-time FPS.
- •Responsive web interface accessible on standard desktop and laptop browsers.
⚡ Performance Budgets
- •Server HTTP payload limited to cropped face bounding boxes (approx. 250x250 pixels, <40KB JPEG).
- •Server inference turnaround under 120ms per verification request.
- •Zero client-side exposure of the private enrolled biometric vector database.
🛡️ Security & Hardware Guardrails
- •Cosine similarity threshold calibrated to minimize False Acceptance Rate (FAR).
- •L2 normalization of vector embeddings to guarantee consistent Euclidean distance metrics.
- •Local SQLite storage of biometric vectors with zero external cloud API dependencies.
Architecture & System Design
TrueFace splits the vision pipeline into two distinct tiers: Client Edge Perception (in-browser WebAssembly TinyFaceDetector with exponential coordinate smoothing) and Server Deep Inference (Python FastAPI, MTCNN 5-point alignment, FaceNet 512-D embedding generation, and SQLite vector cosine matching).
+--------------------------------------------------------------------------+
| CLIENT TIER (BROWSER EDGE WASM) |
| |
| [ HTML5 Video Webcam Feed (30 FPS) ] |
| | |
| v |
| [ TinyFaceDetector (WASM / WebGL) ] |
| - Tracks Bounding Box locally at 15-30 FPS |
| - Exponential Moving Average (EMA) coordinate smoothing |
| | |
| v (Face Stable & Centered: 2-3 Crops/Sec) |
| [ Canvas Crop & Base64 Encode: 250x250 Face Tensor (<40KB) ] |
+-----------------------------------+--------------------------------------+
|
v (HTTP POST /api/verify)
+-----------------------------------+--------------------------------------+
| SERVER TIER (PYTHON FASTAPI ENGINE) |
| |
| 1. MTCNN 5-Point Landmark Detection |
| - Detects Left Eye, Right Eye, Nose, Left Mouth, Right Mouth |
| - Computes Affine Transformation Matrix (Aligns Eye Line) |
| - Crops & Normalizes to 160x160 Normalized Tensor |
| |
| 2. Inception-ResNet-v1 (FaceNet VGGFace2) Feature Extractor |
| - Deep Convolutional Forward Pass |
| - Extracts 512-Dimensional Vector: v in R^512 |
| - Applies L2 Normalization: ||v||_2 = 1.0 |
| |
| 3. Vector Cosine Similarity Search |
| - Computes Dot Product against SQLite Stored Enrolled Centroids |
| - If Max Cosine Similarity >= 0.45: Return Matched User Identity |
| - Else: Return "Unknown" |
+-----------------------------------+--------------------------------------+
|
v (JSON: { match: "Javed Hussain", conf: 0.97, dist: 0.28 })
+-----------------------------------+--------------------------------------+
| CLIENT UI OVERLAY UPDATE (<120ms) |
| - Renders Green Identification Badge & User Profile Card |
+--------------------------------------------------------------------------+Subsystem Layer Breakdown
Client Edge Perception Layer
WASM 15–30 FPSRole: Browser WASM Face Tracking
Executes lightweight TinyFaceDetector via WebAssembly and WebGL in the browser. Tracks faces at 15–30 FPS and renders bounding box overlays with zero server network latency.
Facial Landmark Alignment Layer
MTCNN 5-PointRole: MTCNN 5-Point Geometric Normalization
Multi-task Cascaded Convolutional Networks locate 5 facial landmarks. Performs affine transformation to align the eye horizontal plane onto a standard 160×160 normalized tensor.
Deep Feature Embedding Layer
512-D FaceNetRole: FaceNet Inception-ResNet-v1 (VGGFace2)
Deep convolutional neural network architecture transforming 160×160 aligned face tensors into 512-dimensional L2-normalized Euclidean vector embeddings.
Vector Database & Matching Layer
SQLite Vector Dot-ProductRole: SQLite Cosine Similarity Index
Stores enrolled identity centroid vectors. Performs rapid dot-product cosine similarity calculations with a strict 0.45 threshold to classify identities or label unknown faces.
Step-by-Step Execution Sequence
- 1User grants webcam permission: HTML5 video feed renders in browser canvas.
- 2WASM TinyFaceDetector detects face coordinates at 24 FPS; EMA filter smooths bounding box to eliminate jitter.
- 3When face is stable, client extracts a cropped 250×250 JPEG and POSTs to FastAPI /api/verify.
- 4FastAPI MTCNN detects 5 facial landmarks, applies affine rotation, and normalizes image to 160×160 pixels.
- 5FaceNet extracts 512-dimensional L2-normalized vector embedding and compares against SQLite enrolled centroids.
- 6Server returns JSON response in <120ms; client updates UI with user identity badge (e.g. Javed Hussain, confidence 0.97).
Technical Stack & Architectural Rationale
Every tool and library was chosen under strict engineering constraints of latency, memory limits, and physical execution reality.
PyTorch
AI/MLRole: Deep Learning Inference Framework
Why Chosen: Powers the Inception-ResNet-v1 neural network backbone, executing accelerated tensor operations and vector normalization.
FaceNet (Inception-ResNet-v1)
AI/MLRole: Deep Feature Extractor Pretrained on VGGFace2
Why Chosen: Extracts highly discriminative 512-dimensional Euclidean embeddings capable of separating facial identities across lighting conditions.
MTCNN (Multi-task Cascaded CNN)
AI/MLRole: 5-Point Facial Landmark Alignment
Why Chosen: Standardizes facial pose angles (pitch, yaw, roll) before feature extraction, eliminating false negatives caused by natural head tilts.
FastAPI (Python 3.11)
BackendRole: High-Concurrency Asynchronous REST Engine
Why Chosen: Provides asynchronous non-blocking request handling with automated Pydantic schema validation for image payloads.
TinyFaceDetector (WASM / WebGL)
FrontendRole: Client-Side Real-Time Browser Face Tracker
Why Chosen: Executes lightweight face detection inside browser memory at 15–30 FPS, eliminating server video streaming bottlenecks.
SQLite Vector Table
Storage/DBRole: Embedded Biometric Persistence
Why Chosen: Stores 512-D centroid vectors as binary blobs, allowing microsecond-speed cosine distance calculations without complex external vector databases.
Chronological Development Journey
From initial field investigations in Teghra to bench prototypes, hardware revisions, and production releases.
Streaming 1080p Video to OpenCV Server Crashes Network
Javed initially built a WebSocket video streamer that piped webcam frames to an OpenCV Python server. Over local 4G, packet queueing caused latency to balloon to 850ms, while server CPU usage spiked to 100% on a single client. This proved that video streaming was fundamentally flawed.
Implementing Browser-Side TinyFaceDetector with Smoothing
Moved face detection entirely to the browser using WebAssembly. The browser tracked bounding boxes at 24 FPS with zero network traffic. Added an Exponential Moving Average (EMA) filter to stop bounding box flickering.
Calibrating 5-Point Landmark Transformation & Cosine Distance
Engineered the Python backend with MTCNN landmark detection. Faces were rotated so that eye pupils aligned horizontally on a 160×160 normalized tensor. Connected Inception-ResNet-v1 to generate 512-D vectors, benchmarking cosine threshold margins between identical and distinct faces.
Live Browser Verification Interface Achieving 0.97 Match at 24 FPS
Assembled the complete full-stack interface. Verified real-time identity recognition with Javed face: achieving 0.97 match confidence, 0.28 cosine distance, and 24 FPS browser rendering.

Engineering Challenges & Technical Solutions
Real failure modes encountered on live devices, breadboards, and regional networks, complete with root-cause analysis and code-level resolutions.
Challenge #1: Eliminating False Negatives Caused by Head Tilts and Pose Variations
● ResolvedThe Problem Context
When users naturally tilt or turn their heads in front of a laptop camera, raw FaceNet embeddings shift significantly, causing Euclidean distance to cross the threshold and mistakenly classify enrolled users as "Unknown".
Investigation & Root Cause Analysis
Visualizing embedding distances showed that a 15-degree head tilt increased Euclidean distance between the same user from 0.32 to 0.78, completely crossing the rejection threshold.
The Actual Engineering Resolution
Integrated Multi-task Cascaded Convolutional Networks (MTCNN) 5-point landmark detection before feature extraction. The pipeline calculates the angle between left and right eye coordinates, computes an affine rotation matrix, rotates the image so eyes are perfectly level, and crops to 160×160 pixels.
# Aligning face based on MTCNN 5-point landmarks
import cv2
import numpy as np
def align_face_5point(image, landmarks):
# landmarks: [left_eye, right_eye, nose, left_mouth, right_mouth]
left_eye, right_eye = landmarks[0], landmarks[1]
dx = right_eye[0] - left_eye[0]
dy = right_eye[1] - left_eye[1]
angle = np.degrees(np.arctan2(dy, dx))
# Target eye center
center = (int((left_eye[0] + right_eye[0]) / 2), int((left_eye[1] + right_eye[1]) / 2))
rot_mat = cv2.getRotationMatrix2D(center, angle, scale=1.0)
aligned = cv2.warpAffine(image, rot_mat, (image.shape[1], image.shape[0]))
return cv2.resize(aligned, (160, 160))Challenge #2: Zero-Retraining Dynamic User Enrollment
● ResolvedThe Problem Context
In traditional classification CNNs (e.g. Softmax classifiers), enrolling a new person requires modifying the final fully-connected layer and retraining the network for hundreds of epochs, requiring significant GPU downtime.
Investigation & Root Cause Analysis
Examined metric learning using Euclidean vector spaces. Since FaceNet is trained with Triplet Loss on VGGFace2, its 512-D output represents a clustered Euclidean space where identical identities form tight geometric clusters.
The Actual Engineering Resolution
Implemented dynamic centroid enrollment: When a new user registers, the client captures 3 to 5 face crops from varied angles. The server extracts their 512-D vectors, computes their average centroid vector, normalizes it with L2 norm, and saves it in SQLite alongside the user name. Enrollment completes in under 2 seconds with zero neural network retraining.
# Dynamic zero-retraining enrollment using vector centroids
import numpy as np
def enroll_user(user_id: str, face_tensors: list[np.ndarray], model):
embeddings = []
for tensor in face_tensors:
vec = model(tensor).detach().cpu().numpy().flatten()
vec = vec / np.linalg.norm(vec) # L2 normalization
embeddings.append(vec)
# Compute centroid vector
centroid = np.mean(embeddings, axis=0)
centroid = centroid / np.linalg.norm(centroid)
# Store binary blob in SQLite
db.execute("INSERT INTO users (id, embedding) VALUES (?, ?)", (user_id, centroid.tobytes()))
return {"status": "enrolled", "samples": len(face_tensors)}Features & User Experience Walkthrough
A deep architectural inspection of shipped interfaces, physical control panels, and protocol telemetry.
Real-Time Browser Recognition Overlay
Live webcam video feed running at 24 FPS with smoothed green bounding box, match confidence (0.97), Euclidean distance metric (0.28), and recognized identity badge.

⚡ Engineering Highlights:
- ✓Fluid 15–30 FPS client-side tracking via WebAssembly.
- ✓Sub-120ms server verification latency over throttled HTTP.
- ✓Accurate cosine distance thresholding separating enrolled users from strangers.
5-Point Facial Landmark Pose Normalization
Automatic detection of left eye, right eye, nose tip, and mouth corners to align the face horizontally before vector embedding extraction.
⚡ Engineering Highlights:
- ✓Compensates for natural head tilts and angled webcam setups.
- ✓Scales cropped face onto a standardized 160×160 normalized tensor.
- ✓Reduces false negative classification rates by over 40% in lab tests.
512-Dimensional Inception-ResNet Vector Engine
Extracts deep Euclidean embeddings pretrained on millions of face samples in the VGGFace2 dataset, normalized to unit length for cosine dot-product comparisons.
⚡ Engineering Highlights:
- ✓512-dimensional continuous vector representation per face.
- ✓L2 normalization ensuring all vectors lie on a unit hypersphere.
- ✓High inter-class variance with tight intra-class clustering.
Zero-Retraining Multi-Angle Centroid Enrollment
Enroll new team members or students in under 2 seconds. Captures 3–5 sample crops, computes their geometric vector centroid, and saves directly to SQLite.
⚡ Engineering Highlights:
- ✓Zero GPU backpropagation or network retraining required.
- ✓Average centroid calculation creates resilient multi-angle identity anchors.
- ✓Immediate availability for real-time verification upon database commit.
Results & Honest Current Status
TrueFace is a fully operational lab prototype and benchmarked API. The decoupled two-tier architecture successfully demonstrates real-time 24 FPS in-browser tracking with sub-120ms server vector verification.
✅ Verified Implemented Functionality
- •Client-side WebAssembly TinyFaceDetector tracking faces at 15–30 FPS.
- •Exponential Moving Average (EMA) bounding box coordinate smoothing.
- •Throttled HTTP client-server crop transmission (<40KB per request).
- •Server-side MTCNN 5-point facial landmark alignment.
- •Inception-ResNet-v1 (FaceNet) 512-dimensional vector embedding extraction.
- •SQLite vector database with dot-product cosine similarity matching.
- •Dynamic multi-sample centroid enrollment pipeline without neural network retraining.
⚠️ Known Limitations & Ground Reality
- •Server inference currently runs on PyTorch CPU; while response time is ~110ms on single requests, GPU acceleration (CUDA / TensorRT) will be required for high-concurrency deployments.
- •Anti-spoof liveness detection (detecting printed paper photos or phone screen replays) is in early experimental testing and not yet production-hardened.
- •Extreme low-light conditions degrade client-side WASM face detection before images reach the server.
➔ Immediate Engineering Next Steps:
- ➔Implement passive liveness detection (micro-texture analysis and blink detection) to prevent photo spoofing.
- ➔Port server embedding model to ONNX Runtime with INT8 quantization for sub-30ms CPU inference.
- ➔Package client library as a drop-in React/Next.js component for third-party web apps.
Lessons Learned & Engineering Reflections
First-principles insights gathered while building, testing, and debugging directly in Indian field conditions.
Streaming full video frames to AI backends is an anti-pattern for web applications; computing perception at the edge and inference at the core is far more scalable.
Metric learning embedding architectures are vastly superior to softmax classifiers for open-set identity verification.
Geometric landmark alignment is indispensable for maintaining high cosine similarity across natural human movement.
Future Roadmap
Clear distinction between verified accomplishments and prospective architectural exploration.
- ✓Browser WASM real-time face tracking at 24 FPS.
- ✓FastAPI backend with MTCNN alignment and FaceNet 512-D embeddings.
- ✓SQLite vector persistence and cosine similarity classification.
- ✓Dynamic zero-retraining enrollment pipeline.
- •ONNX Runtime conversion for accelerated CPU inference.
- •Client-side frame quality scoring (blur detection before transmission).
- ◦Passive 3D liveness detection to defeat photo and video playback spoofing.
- ◦Automated attendance export to CSV and webhook integrations.
- ?In-browser client-side embedding extraction using WebGPU and ONNX Web for 100% serverless verification.