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.
C avx-512avx2biometricsc99computer-visioncpu-inferencedeep-learningedge-aiembedded-aiface-embeddingface-recognitionface-verificationlow-latencyonnx-runtimeproduction-readysimdzero-dependencies
Use rectangular YuNet inputs for face detection in the REST API
Baurzhan Atynovcb672bee1a7e
diff --git a/Dockerfile b/Dockerfileindex 6ae6c67..9e789d7 100644--- a/Dockerfile+++ b/Dockerfile@@ -8,31 +8,28 @@# POST /compare — compare two embeddings# GET /health — health check-FROM gcc:13 AS builder+FROM gcc:13-bookworm AS builderWORKDIR /buildCOPY src/ src/COPY include/ include/COPY Makefile .-# Build static library + CLI-RUN gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static -DFACEX_LIB \- -Iinclude -o facex-server \- src/facex.c src/detect.c src/align.c src/edgeface_engine.c \- src/transformer_ops.c src/gemm_int8_4x8c8.c src/threadpool.c \- src/weight_crypto.c \- -lm -lpthread && \- strip facex-server--# Runtime — minimal image-FROM alpine:3.19--RUN apk add --no-cache python3 py3-pip && \- pip3 install --break-system-packages flask gunicorn pillow numpy+# Build the embedding CLI and the shared detector against the runtime libc.+RUN make cli CFLAGS="-O3 -march=x86-64-v3" && \+ gcc -O3 -march=x86-64-v3 -shared -fPIC -Iinclude -o libfacex.so \+ src/facex.c src/detect.c src/align.c src/transformer_ops.c \+ src/gemm_int8_4x8c8.c src/threadpool.c src/weight_crypto.c -lm -lpthread && \+ strip facex-cli libfacex.so+FROM python:3.11-slim-bookworm+RUN pip install --no-cache-dir flask gunicorn pillow numpyWORKDIR /app-COPY --from=builder /build/facex-server /app/+COPY --from=builder /build/facex-cli /app/facex-server+COPY --from=builder /build/libfacex.so /app/libfacex.so+COPY python/facex /app/facexCOPY docker/server.py /app/+ENV FACEX_LIB=/app/libfacex.so# Weights must be mounted or baked in# docker run -v /path/to/weights:/app/weights facexdiff --git a/docker/server.py b/docker/server.pyindex 6900bd1..888c240 100644--- a/docker/server.py+++ b/docker/server.py@@ -11,17 +11,15 @@ Usage:gunicorn -w 2 -b 0.0.0.0:8080 server:app"""-import jsonimport osimport subprocess-import struct-import sys+import threadingimport timeimport numpy as npfrom flask import Flask, request, jsonifyfrom PIL import Image-import io+from facex import FaceXapp = Flask(__name__)@@ -56,6 +54,8 @@ class FaceXProcess:# Global process (per worker)_fx = None+_detector = None+_detector_lock = threading.Lock()def get_fx():@@ -122,34 +122,34 @@ def detect():"""Detect faces in image, return bbox + embeddings.Input: multipart file upload (any size JPEG/PNG)- Output: {"faces": [{"bbox": [x1,y1,x2,y2], "score": float, "embedding": [512]}], "ms": float}+ Output: {"faces": [{"bbox": [x1,y1,x2,y2], "keypoints": [[x,y], ...], "score": float, "embedding": [512]}], "ms": float}"""if 'file' not in request.files:return jsonify({'error': 'No file uploaded'}), 400- f = request.files['file']- img = Image.open(f.stream).convert('RGB')-- t0 = time.time()-- # Resize to 160x160 for detection (letterbox)- w, h = img.size- scale = min(160 / w, 160 / h)- nw, nh = int(w * scale), int(h * scale)- img_resized = img.resize((nw, nh), Image.BILINEAR)- padded = Image.new('RGB', (160, 160), (0, 0, 0))- dx, dy = (160 - nw) // 2, (160 - nh) // 2- padded.paste(img_resized, (dx, dy))-- # TODO: run C detector via subprocess or ctypes- # For now, return placeholder- ms = (time.time() - t0) * 1000-- return jsonify({- 'faces': [],- 'ms': round(ms, 2),- 'note': 'Detection via REST API coming soon. Use /embed for pre-aligned faces.',- })+ try:+ with Image.open(request.files['file'].stream) as uploaded:+ rgb = np.asarray(uploaded.convert('RGB'))+ except (OSError, ValueError, Image.DecompressionBombError):+ return jsonify({'error': 'Invalid image'}), 400++ start = time.perf_counter()+ global _detector+ with _detector_lock:+ try:+ if _detector is None:+ engine = FaceX(embed_weights=EMBED_WEIGHTS, detect_weights=DETECT_WEIGHTS,+ input_policy="rectangle", license_key=os.environ.get("LICENSE_KEY"))+ if engine.backend != "ctypes":+ raise RuntimeError("Missing native FaceX library")+ _detector = engine+ faces = _detector.detect(rgb, max_faces=32)+ except (RuntimeError, OSError):+ app.logger.exception("Face detection failed")+ return jsonify({'error': 'Face detection unavailable'}), 503+ for face in faces:+ face['embedding'] = face['embedding'].tolist()+ return jsonify({'faces': faces, 'ms': round((time.perf_counter() - start) * 1000, 2)})if __name__ == '__main__':diff --git a/docs/research/yunet_pixel_budget.md b/docs/research/yunet_pixel_budget.mdindex d005616..020bfe1 100644--- a/docs/research/yunet_pixel_budget.md+++ b/docs/research/yunet_pixel_budget.md@@ -48,3 +48,13 @@ Use the native binary weights exported by tools/export_yunet_weights.py from YuN```shOPENBLAS_NUM_THREADS=1 python tests/bench_yunet_tiles.py yunet.bin WIDER_val.zip wider_face_split.zip```++## Client integration++The Python SDK now exposes the measured policy through `FaceX(input_policy="rectangle")`.+The REST detection endpoint selects it by default. A run through the SDK on the+same 640 evaluation images with the REST limit of 32 faces per image produced+1759 matches, 131 unmatched detections and 990 small matches among 8909 valid+annotations. The experimental detector above allowed more results on crowded+frames. The SDK also clips coordinates to the original image bounds and computes+embeddings from the source image.diff --git a/include/facex.h b/include/facex.hindex e51b831..e6cfbb4 100644--- a/include/facex.h+++ b/include/facex.h@@ -61,6 +61,15 @@ FaceX* facex_init(const char* embed_weights, const char* detect_weights, const cint facex_detect(FaceX* fx, const uint8_t* rgb_hwc, int width, int height,FaceXResult* out, int max_faces);+/* Detect on a prepared RGB canvas and align on the original RGB image.+ * The resized image occupies resized_w by resized_h pixels, centered with+ * integer floor padding on its left and top. Results use original coordinates.+ * The detector returns up to 32 faces per call.+ */+int facex_detect_prepared(FaceX* fx, const uint8_t* rgb_hwc, int width, int height,+ const uint8_t* canvas, int canvas_w, int canvas_h,+ int resized_w, int resized_h, FaceXResult* out, int max_faces);+/** Compute embedding only (no detection). Input must be pre-aligned 112×112.* rgb_hwc: 112*112*3 float32 array, HWC layout, values in [-1, 1]diff --git a/python/README.md b/python/README.mdindex dafd55a..eee5937 100644--- a/python/README.md+++ b/python/README.md@@ -38,6 +38,33 @@ if len(faces) >= 2:print(f"Similarity: {sim:.3f} ({'same' if sim > 0.3 else 'different'} person)")```+## Rectangular YuNet input++For camera frames and photos, initialize the native SDK with the rectangle policy.+Install the image extra for Pillow and build the shared library from this version.++```python+fx = FaceX(embed_weights="weights/edgeface_xs_fp32.bin",+ detect_weights="weights/yunet_fp32.bin",+ input_policy="rectangle")+faces = fx.detect(image)+```++The detector uses up to 409600 input pixels and a default score threshold of 0.58.+For a 1920 × 1080 source it resizes to 832 × 468 and centers that image on an+832 × 480 canvas. Boxes and five keypoints use original image coordinates.+Alignment and embedding sample the original RGB pixels. Set `score_threshold`+explicitly to override the calibrated threshold. Existing SDK callers use native+image dimensions by default.++The Docker REST service uses the rectangle policy for `POST /detect` and returns+up to 32 faces. Mount both weights at the paths above under `/app`, or set+`EMBED_WEIGHTS` and `DETECT_WEIGHTS` to their paths inside the container.++```sh+curl -F [email protected] http://localhost:8080/detect+```+## Configuration### Auto-detectiondiff --git a/python/facex/core.py b/python/facex/core.pyindex 10278d9..cd7bec4 100644--- a/python/facex/core.py+++ b/python/facex/core.py@@ -204,7 +204,8 @@ class FaceX:embed_weights: Path to embedding weights. Auto-detected if None.detect_weights: Path to detector weights. Auto-detected if None.license_key: License key for encrypted weights (None for plain).- score_threshold: Detection confidence threshold (default 0.5).+ score_threshold: Defaults to 0.58 for rectangle input and 0.5 for native input.+ input_policy: Use "rectangle" for budgeted YuNet inference or "native" for original dimensions.nms_threshold: NMS IoU threshold (default 0.4).max_faces: Maximum faces to detect per image (default 20)."""@@ -216,14 +217,20 @@ class FaceX:embed_weights: Optional[str] = None,detect_weights: Optional[str] = None,license_key: Optional[str] = None,- score_threshold: float = 0.5,+ score_threshold: Optional[float] = None,nms_threshold: float = 0.4,max_faces: int = MAX_FACES_DEFAULT,+ input_policy: str = "native",):self._lib = Noneself._handle = Noneself._cli_path = cli_pathself._max_faces = max_faces+ if input_policy not in ("rectangle", "native"):+ raise ValueError("Unknown detector input policy")+ self._input_policy = input_policy+ if score_threshold is None:+ score_threshold = 0.58 if input_policy == "rectangle" else 0.5self._score_threshold = score_thresholdself._nms_threshold = nms_threshold@@ -303,6 +310,17 @@ class FaceX:]self._lib.facex_set_nms_threshold.restype = None+ if self._input_policy == "rectangle":+ if not hasattr(self._lib, "facex_detect_prepared"):+ raise RuntimeError("Rectangle input requires a library with facex_detect_prepared")+ image_ptr = ctypes.POINTER(ctypes.c_uint8)+ self._lib.facex_detect_prepared.argtypes = [+ ctypes.c_void_p, image_ptr, ctypes.c_int, ctypes.c_int,+ image_ptr, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int,+ ctypes.POINTER(FaceXResult), ctypes.c_int,+ ]+ self._lib.facex_detect_prepared.restype = ctypes.c_int+# Init engineembed_b = self._embed_weights.encode() if self._embed_weights else Nonedetect_b = self._detect_weights.encode() if self._detect_weights else None@@ -351,6 +369,8 @@ class FaceX:h, w = image.shape[:2]mf = max_faces or self._max_faces+ if self._input_policy == "rectangle" and self.backend != "ctypes":+ raise RuntimeError("Rectangle input requires the native FaceX shared library")if self._lib and self._handle:return self._detect_ctypes(image, w, h, mf)elif self._cli_path:@@ -363,7 +383,16 @@ class FaceX:def _detect_ctypes(self, image: np.ndarray, w: int, h: int, max_faces: int) -> List[dict]:results = (FaceXResult * max_faces)()ptr = image.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))- n = self._lib.facex_detect(self._handle, ptr, w, h, results, max_faces)+ if self._input_policy == "rectangle":+ from .yunet import prepare_rectangle+ canvas, rw, rh = prepare_rectangle(image)+ ch, cw = canvas.shape[:2]+ n = self._lib.facex_detect_prepared(+ self._handle, ptr, w, h,+ canvas.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)), cw, ch,+ rw, rh, results, max_faces)+ else:+ n = self._lib.facex_detect(self._handle, ptr, w, h, results, max_faces)if n < 0:raise RuntimeError(f"facex_detect returned error code {n}")return [_result_to_dict(results[i]) for i in range(n)]diff --git a/python/facex/yunet.py b/python/facex/yunet.pynew file mode 100644index 0000000..c2e69fa--- /dev/null+++ b/python/facex/yunet.py@@ -0,0 +1,23 @@+"""Prepare the rectangular input used by the native YuNet detector."""+import numpy as np+from PIL import Image+++def rectangle_shape(w, h):+ if min(w, h) <= 0:+ raise ValueError("Image dimensions must be positive")+ # Each cell is 32 x 32. A 640 x 640 canvas fits 400 cells.+ scale = min(1280 / max(w, h), max(+ min(32 * cols / w, 32 * (400 // cols) / h) for cols in range(1, 41)))+ rw, rh = max(1, round(w * scale)), max(1, round(h * scale))+ return rw, rh, (rw + 31) // 32 * 32, (rh + 31) // 32 * 32+++def prepare_rectangle(image):+ h, w = image.shape[:2]+ rw, rh, cw, ch = rectangle_shape(w, h)+ x, y = (cw - rw) // 2, (ch - rh) // 2+ canvas = np.zeros((ch, cw, 3), dtype=np.uint8)+ bicubic = getattr(Image, "Resampling", Image).BICUBIC+ canvas[y:y + rh, x:x + rw] = Image.fromarray(image).resize((rw, rh), bicubic)+ return canvas, rw, rhdiff --git a/src/align.c b/src/align.cindex 28789e1..bd2b6ac 100644--- a/src/align.c+++ b/src/align.c@@ -15,6 +15,7 @@#include <math.h>#include <float.h>#include <stdint.h>+#include <stddef.h>/* Reference 112×112 landmarks (ArcFace order) */static const float REF_KPS[10] = {@@ -98,16 +99,17 @@ int align_face(const uint8_t* src_rgb, int src_w, int src_h,int ix = (int)sx, iy = (int)sy_f;float fx = sx - ix, fy = sy_f - iy;+ const uint8_t* pixel = src_rgb + ((size_t)iy * src_w + ix) * 3;for (int c = 0; c < 3; c++) {float v = 0;if (ix < src_w-1 && iy < src_h-1) {- float v00 = src_rgb[(iy*src_w + ix)*3 + c];- float v10 = src_rgb[(iy*src_w + ix+1)*3 + c];- float v01 = src_rgb[((iy+1)*src_w + ix)*3 + c];- float v11 = src_rgb[((iy+1)*src_w + ix+1)*3 + c];+ float v00 = pixel[c];+ float v10 = pixel[3 + c];+ float v01 = pixel[(size_t)src_w * 3 + c];+ float v11 = pixel[(size_t)src_w * 3 + 3 + c];v = v00*(1-fx)*(1-fy) + v10*fx*(1-fy) + v01*(1-fx)*fy + v11*fx*fy;} else {- v = src_rgb[(iy*src_w + ix)*3 + c];+ v = pixel[c];}out_f32[(dy*112 + dx)*3 + c] = v / 127.5f - 1.0f; /* normalize to [-1, 1] */}diff --git a/src/facex.c b/src/facex.cindex cef8baf..ebc8993 100644--- a/src/facex.c+++ b/src/facex.c@@ -33,23 +33,18 @@ FaceX* facex_init(const char* embed_weights, const char* detect_weights, const cFaceX* fx = (FaceX*)calloc(1, sizeof(FaceX));if (!fx) return NULL;- /* Init embedder */- if (embed_weights) {- if (engine_init(embed_weights, &fx->embed_weights) != 0) {- free(fx);- return NULL;- }- }-- /* Init detector (optional) */if (detect_weights) {fx->detector = detect_init(detect_weights);if (!fx->detector) {- free(fx->embed_weights.raw);free(fx);return NULL;}}+ if (embed_weights && engine_init(embed_weights, &fx->embed_weights) != 0) {+ if (fx->detector) detect_free(fx->detector);+ free(fx);+ return NULL;+ }fx->ready = 1;return fx;@@ -57,27 +52,41 @@ FaceX* facex_init(const char* embed_weights, const char* detect_weights, const cint facex_detect(FaceX* fx, const uint8_t* rgb_hwc, int width, int height,FaceXResult* out, int max_faces) {- if (!fx || !fx->ready || !fx->detector) return -1;- if (!rgb_hwc || !out || max_faces <= 0) return -1;+ return facex_detect_prepared(fx, rgb_hwc, width, height, rgb_hwc,+ width, height, width, height, out, max_faces);+}++static float source_coordinate(float value, int padding, int resized, int original) {+ double mapped = ((double)value - padding) * original / resized;+ return (float)fmax(0, fmin(original, mapped));+}++int facex_detect_prepared(FaceX* fx, const uint8_t* rgb_hwc, int width, int height,+ const uint8_t* canvas, int canvas_w, int canvas_h,+ int resized_w, int resized_h, FaceXResult* out, int max_faces) {+ if (!fx || !fx->ready || !fx->detector || !rgb_hwc || !canvas || !out ||+ width <= 0 || height <= 0 || max_faces <= 0 ||+ resized_w <= 0 || resized_w > canvas_w ||+ resized_h <= 0 || resized_h > canvas_h) return -1;- /* Step 1: Detect faces */DetectFace det_faces[32];int n_det = max_faces < 32 ? max_faces : 32;- int n = detect_run(fx->detector, rgb_hwc, width, height, det_faces, n_det);- if (n <= 0) return n;-- /* Step 2: For each face, align + embed */+ int n = detect_run(fx->detector, canvas, canvas_w, canvas_h, det_faces, n_det);+ int dx = (canvas_w - resized_w) / 2, dy = (canvas_h - resized_h) / 2;for (int i = 0; i < n; i++) {- out[i].x1 = det_faces[i].x1;- out[i].y1 = det_faces[i].y1;- out[i].x2 = det_faces[i].x2;- out[i].y2 = det_faces[i].y2;- out[i].score = det_faces[i].score;- memcpy(out[i].kps, det_faces[i].kps, 10 * sizeof(float));-+ DetectFace* face = &det_faces[i];+ out[i].x1 = source_coordinate(face->x1, dx, resized_w, width);+ out[i].y1 = source_coordinate(face->y1, dy, resized_h, height);+ out[i].x2 = source_coordinate(face->x2, dx, resized_w, width);+ out[i].y2 = source_coordinate(face->y2, dy, resized_h, height);+ out[i].score = face->score;+ for (int k = 0; k < 10; k += 2) {+ out[i].kps[k] = source_coordinate(face->kps[k], dx, resized_w, width);+ out[i].kps[k+1] = source_coordinate(face->kps[k+1], dy, resized_h, height);+ }/* Align face to 112×112 using keypoints */float aligned[112 * 112 * 3];- if (!align_face(rgb_hwc, width, height, det_faces[i].kps, aligned)) {+ if (!fx->embed_weights.raw || !align_face(rgb_hwc, width, height, out[i].kps, aligned)) {memset(out[i].embedding, 0, sizeof(out[i].embedding));continue;}diff --git a/tests/verify_rectangular_client.py b/tests/verify_rectangular_client.pynew file mode 100644index 0000000..07d6ef5--- /dev/null+++ b/tests/verify_rectangular_client.py@@ -0,0 +1,74 @@+"""Exercise the SDK and Flask endpoint with FACEX_LIB, EMBED_WEIGHTS and DETECT_WEIGHTS set."""+import ctypes+import io+import os+import sys++import numpy as np+from PIL import Image++from verify_yunet import ROOT, native_run++sys.path[:0] = [str(ROOT / "python"), str(ROOT / "docker")]+from facex import FaceX+from facex.yunet import prepare_rectangle+from server import app+++def main():+ lib = ctypes.CDLL(os.environ["FACEX_LIB"])+ lib.detect_init.restype = ctypes.c_void_p+ det = ctypes.c_void_p(lib.detect_init(os.fsencode(os.environ["DETECT_WEIGHTS"])))+ assert det+ lib.detect_set_score_threshold(det, ctypes.c_float(.58))+ lib.align_face.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int,+ ctypes.c_void_p, ctypes.c_void_p]+ sdk = FaceX(embed_weights=os.environ["EMBED_WEIGHTS"], detect_weights=os.environ["DETECT_WEIGHTS"],+ input_policy="rectangle")+ client = app.test_client()+ patch = Image.open(ROOT / "data/test_face.jpg").convert("RGB").resize((241, 241))+ try:+ for w, h in ((797, 451), (451, 797), (640, 640)):+ image = Image.new("RGB", (w, h))+ image.paste(patch, ((w - 241) // 2, (h - 241) // 2))+ rgb = np.asarray(image)+ canvas, rw, rh = prepare_rectangle(rgb)+ ch, cw = canvas.shape[:2]+ expected = native_run(lib, det, canvas)+ faces = sdk.detect(rgb)+ assert len(expected) == len(faces) > 0+ for row, face in zip(expected, faces):+ coords = np.r_[row[:4], row[5:]].reshape(-1, 2)+ coords -= [(cw-rw)//2, (ch-rh)//2]+ coords *= [w/rw, h/rh]+ np.clip(coords, [0, 0], [w, h], out=coords)+ actual = np.r_[face["bbox"], np.ravel(face["keypoints"])].reshape(-1, 2)+ np.testing.assert_allclose(actual, coords, atol=.0002)+ pts = np.ascontiguousarray(face["keypoints"], dtype="f")+ aligned = np.empty((112, 112, 3), dtype="f")+ assert lib.align_face(rgb.ctypes.data, w, h, pts.ctypes.data, aligned.ctypes.data)+ np.testing.assert_allclose(face["embedding"], sdk.embed(aligned), atol=1e-5)+ buf = io.BytesIO()+ image.save(buf, format="PNG")+ buf.seek(0)+ response = client.post("/detect", data={"file": (buf, "image.png")})+ assert response.status_code == 200, response.data+ returned = response.get_json()["faces"]+ assert len(returned) == len(faces)+ for api, face in zip(returned, faces):+ for key in ("bbox", "keypoints", "score", "embedding"):+ np.testing.assert_allclose(api[key], face[key], atol=1e-5)+ print(w, h, "canvas", cw, ch, "faces", len(faces))+ assert client.post("/detect").status_code == 400+ assert client.post("/detect", data={"file": (io.BytesIO(b"x"), "bad.png")}).status_code == 400+ blank = io.BytesIO()+ Image.new("RGB", (400, 225)).save(blank, format="PNG")+ blank.seek(0)+ assert client.post("/detect", data={"file": (blank, "blank.png")}).get_json()["faces"] == []+ finally:+ lib.detect_free(det)+ sdk.close()+++if __name__ == "__main__":+ main()