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
Sprints 36-40: Python + npm + Docker + Release scripts
atynovface1b64ba3d
diff --git a/Dockerfile b/Dockerfilenew file mode 100644index 0000000..6ae6c67--- /dev/null+++ b/Dockerfile@@ -0,0 +1,40 @@+# FaceX — Face recognition REST API+# Build: docker build -t facex .+# Run: docker run -p 8080:8080 facex+#+# API:+# POST /detect — detect faces + embeddings (multipart image)+# POST /embed — embed pre-aligned 112x112 face+# POST /compare — compare two embeddings+# GET /health — health check++FROM gcc:13 AS builder++WORKDIR /build+COPY 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++WORKDIR /app+COPY --from=builder /build/facex-server /app/+COPY docker/server.py /app/++# Weights must be mounted or baked in+# docker run -v /path/to/weights:/app/weights facex+EXPOSE 8080+CMD ["gunicorn", "-w", "2", "-b", "0.0.0.0:8080", "server:app"]diff --git a/deploy/build_release.sh b/deploy/build_release.shnew file mode 100644index 0000000..03cf1fc--- /dev/null+++ b/deploy/build_release.sh@@ -0,0 +1,70 @@+#!/bin/bash+# Build release archives for Linux x86-64.+# Run in WSL or on Linux.+# Output: deploy/facex-linux-x64.tar.gz+set -e++cd "$(dirname "$0")/.."+ROOT=$(pwd)+VERSION="2.0.0"+OUT="$ROOT/deploy/facex-${VERSION}-linux-x64"++echo "=== Building FaceX ${VERSION} release ==="++rm -rf "$OUT"+mkdir -p "$OUT/lib" "$OUT/include" "$OUT/bin"++# 1. Build static library+echo "[1/4] Building libfacex.a..."+gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static -DFACEX_LIB \+ -c src/facex.c -o /tmp/fx.o \+ -Iinclude+gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static \+ -c src/transformer_ops.c -o /tmp/tops.o+gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static \+ -c src/gemm_int8_4x8c8.c -o /tmp/gemm.o+gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static \+ -c src/threadpool.c -o /tmp/tp.o+gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static \+ -c src/weight_crypto.c -o /tmp/wc.o+gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static \+ -c src/detect.c -o /tmp/det.o -Iinclude+gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static \+ -c src/align.c -o /tmp/align.o+ar rcs "$OUT/lib/libfacex.a" /tmp/fx.o /tmp/tops.o /tmp/gemm.o /tmp/tp.o /tmp/wc.o /tmp/det.o /tmp/align.o+echo " libfacex.a: $(stat -c%s "$OUT/lib/libfacex.a") bytes"++# 2. Build CLI binary+echo "[2/4] Building facex-cli..."+gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static \+ -Iinclude -o "$OUT/bin/facex-cli" \+ src/edgeface_engine.c src/transformer_ops.c src/gemm_int8_4x8c8.c \+ src/threadpool.c src/weight_crypto.c \+ -lm -lpthread+echo " facex-cli: $(stat -c%s "$OUT/bin/facex-cli") bytes"++# 3. Build encrypt tool+echo "[3/4] Building facex-encrypt..."+gcc -O3 -march=x86-64-v3 -static -DWEIGHT_CRYPTO_MAIN \+ -o "$OUT/bin/facex-encrypt" src/weight_crypto.c -lm+echo " facex-encrypt: $(stat -c%s "$OUT/bin/facex-encrypt") bytes"++# 4. Copy headers + docs+echo "[4/4] Packaging..."+cp include/facex.h include/detect.h "$OUT/include/"+cp LICENSE README.md "$OUT/"++# Create archive+cd deploy+tar czf "facex-${VERSION}-linux-x64.tar.gz" "facex-${VERSION}-linux-x64/"+SIZE=$(stat -c%s "facex-${VERSION}-linux-x64.tar.gz")+echo ""+echo "=== Done ==="+echo "Archive: deploy/facex-${VERSION}-linux-x64.tar.gz ($((SIZE/1024)) KB)"+echo ""+echo "Contents:"+echo " lib/libfacex.a — static library"+echo " include/facex.h — unified API"+echo " include/detect.h — detector API"+echo " bin/facex-cli — CLI tool"+echo " bin/facex-encrypt — weight encryption"diff --git a/deploy/publish_release.sh b/deploy/publish_release.shnew file mode 100644index 0000000..096e629--- /dev/null+++ b/deploy/publish_release.sh@@ -0,0 +1,58 @@+#!/bin/bash+# Create GitHub Release with pre-built binaries.+# Requires: gh CLI authenticated.+# Usage: ./deploy/publish_release.sh v2.0.0+set -e++VERSION="${1:-v2.0.0}"+ARCHIVE="deploy/facex-${VERSION#v}-linux-x64.tar.gz"++if [ ! -f "$ARCHIVE" ]; then+ echo "ERROR: $ARCHIVE not found. Run deploy/build_release.sh first."+ exit 1+fi++echo "Creating GitHub Release ${VERSION}..."+gh release create "$VERSION" \+ --title "FaceX ${VERSION}" \+ --notes "$(cat <<EOF+## FaceX ${VERSION}++Face detection + recognition library. Detect → Align → Embed in one call.++### Performance+- **Embedding:** 3.0ms native (CPU), 7.0ms WASM (browser)+- **Detection:** 3.8ms native, 6.5ms WASM+- **Full pipeline:** ~13.5ms in browser = 74 fps+- **Accuracy:** 99.73% LFW++### What's included+- \`libfacex.a\` — static C library (detect + embed)+- \`facex-cli\` — CLI tool (stdin/stdout protocol)+- \`facex-encrypt\` — AES-256 weight encryption+- Headers: \`facex.h\`, \`detect.h\`++### Quick start+\`\`\`bash+tar xzf facex-*-linux-x64.tar.gz+cd facex-*/+# Test+echo "dummy" | ./bin/facex-cli weights.bin+# Link in your project+gcc -Iinclude myapp.c -Llib -lfacex -lm -lpthread+\`\`\`++### Browser (WASM)+\`\`\`+npm install facex-wasm+\`\`\`++### Python+\`\`\`+pip install facex+\`\`\`+EOF+)" \+ "$ARCHIVE"++echo "Done: https://github.com/facex-engine/facex/releases/tag/${VERSION}"diff --git a/docker/server.py b/docker/server.pynew file mode 100644index 0000000..6900bd1--- /dev/null+++ b/docker/server.py@@ -0,0 +1,156 @@+"""+FaceX REST API server.++Endpoints:+ POST /detect — detect faces in image, returns bbox + kps + embeddings+ POST /embed — embed pre-aligned 112x112 face+ POST /compare — compare two embeddings (cosine similarity)+ GET /health — health check++Usage:+ gunicorn -w 2 -b 0.0.0.0:8080 server:app+"""++import json+import os+import subprocess+import struct+import sys+import time++import numpy as np+from flask import Flask, request, jsonify+from PIL import Image+import io++app = Flask(__name__)++# FaceX subprocess pool+FACEX_CLI = os.environ.get('FACEX_CLI', './facex-server')+EMBED_WEIGHTS = os.environ.get('EMBED_WEIGHTS', 'weights/edgeface_xs_fp32.bin')+DETECT_WEIGHTS = os.environ.get('DETECT_WEIGHTS', 'weights/yunet_fp32.bin')+++class FaceXProcess:+ """Persistent subprocess for face embedding."""++ def __init__(self):+ self.proc = subprocess.Popen(+ [FACEX_CLI, EMBED_WEIGHTS, '--server'],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )++ def embed(self, face_112x112_hwc):+ """Compute 512-dim embedding from 112x112 float32 HWC face."""+ data = face_112x112_hwc.astype(np.float32).tobytes()+ self.proc.stdin.write(data)+ self.proc.stdin.flush()+ out = self.proc.stdout.read(512 * 4)+ return np.frombuffer(out, dtype=np.float32).copy()++ def close(self):+ self.proc.terminate()+++# Global process (per worker)+_fx = None+++def get_fx():+ global _fx+ if _fx is None:+ _fx = FaceXProcess()+ return _fx++[email protected]('/health', methods=['GET'])+def health():+ return jsonify({'status': 'ok', 'version': '2.0.0'})++[email protected]('/embed', methods=['POST'])+def embed():+ """Embed a pre-aligned 112x112 face image.++ Input: multipart file upload (JPEG/PNG, 112x112)+ Output: {"embedding": [512 floats], "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').resize((112, 112))+ arr = np.array(img, dtype=np.float32) / 127.5 - 1.0 # normalize to [-1, 1]++ t0 = time.time()+ fx = get_fx()+ emb = fx.embed(arr)+ ms = (time.time() - t0) * 1000++ return jsonify({+ 'embedding': emb.tolist(),+ 'ms': round(ms, 2),+ })++[email protected]('/compare', methods=['POST'])+def compare():+ """Compare two embeddings.++ Input: JSON {"emb1": [512], "emb2": [512]}+ Output: {"similarity": float, "match": bool}+ """+ data = request.get_json()+ if not data or 'emb1' not in data or 'emb2' not in data:+ return jsonify({'error': 'Need emb1 and emb2'}), 400++ emb1 = np.array(data['emb1'], dtype=np.float32)+ emb2 = np.array(data['emb2'], dtype=np.float32)++ sim = float(np.dot(emb1, emb2) / (np.linalg.norm(emb1) * np.linalg.norm(emb2) + 1e-8))++ return jsonify({+ 'similarity': round(sim, 6),+ 'match': sim > 0.3,+ })++[email protected]('/detect', methods=['POST'])+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}+ """+ 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.',+ })+++if __name__ == '__main__':+ app.run(host='0.0.0.0', port=8080, debug=True)diff --git a/python/README.md b/python/README.mdnew file mode 100644index 0000000..dafd55a--- /dev/null+++ b/python/README.md@@ -0,0 +1,100 @@+# FaceX Python++Python binding for the [FaceX](https://github.com/facex-engine/facex) face detection + recognition library.++## Install++```bash+cd python/+pip install -e .++# With Pillow for image loading:+pip install -e ".[image]"+```++## Quick start++```python+import numpy as np+from facex import FaceX++# Initialize (auto-finds library and weights)+fx = FaceX()++# Load an image as RGB uint8 numpy array (H, W, 3)+from PIL import Image+image = np.array(Image.open("photo.jpg").convert("RGB"))++# Detect faces — returns list of dicts+faces = fx.detect(image)+for face in faces:+ print(f"bbox: {face['bbox']}, score: {face['score']:.3f}")+ print(f"keypoints: {face['keypoints']}")+ # face['embedding'] is a 512-dim numpy float32 vector++# Compare two faces+if len(faces) >= 2:+ sim = FaceX.similarity(faces[0]["embedding"], faces[1]["embedding"])+ print(f"Similarity: {sim:.3f} ({'same' if sim > 0.3 else 'different'} person)")+```++## Configuration++### Auto-detection++FaceX looks for the native library and weights relative to the package location+(expects `../../weights/` and `../../libfacex.so` or `../../facex.dll`).++### Environment variables++| Variable | Description |+|---|---|+| `FACEX_LIB` | Path to shared library (`.dll` / `.so` / `.dylib`) |+| `FACEX_CLI` | Path to `facex-cli` binary (subprocess fallback) |+| `FACEX_ROOT` | Root of FaceX project (alternative search path) |+| `FACEX_EMBED_WEIGHTS` | Path to embedding model weights |+| `FACEX_DETECT_WEIGHTS` | Path to detector weights |++### Explicit paths++```python+fx = FaceX(+ lib_path="/path/to/libfacex.so",+ embed_weights="/path/to/embed.bin",+ detect_weights="/path/to/detect.bin",+ score_threshold=0.5,+ nms_threshold=0.4,+ max_faces=20,+)+```++## API reference++### `FaceX()`++Main class. Uses ctypes (shared library) if available, falls back to subprocess (CLI).++- **`detect(image, max_faces=None)`** -- Detect faces in an RGB uint8 image. Returns list of dicts with `bbox`, `score`, `keypoints`, `embedding`.+- **`embed(face_112x112)`** -- Compute embedding for a pre-aligned 112x112 face (ctypes only). Input: float32 HWC in [-1, 1]. Returns 512-dim float32 array.+- **`similarity(emb1, emb2)`** -- Static method. Cosine similarity between two 512-dim embeddings. Returns float in [-1, 1].+- **`close()`** -- Free native resources. Also works as context manager (`with FaceX() as fx: ...`).+- **`backend`** -- Property: `"ctypes"`, `"cli"`, or `"none"`.++### `similarity(emb1, emb2)`++Module-level function, same as `FaceX.similarity()`. Works without initializing FaceX.++```python+from facex import similarity+sim = similarity(emb1, emb2)+```++## Backends++| Backend | Requires | Detection | Embedding (standalone) |+|---|---|---|---|+| ctypes | `libfacex.so` / `facex.dll` | Yes | Yes |+| cli | `facex-cli` binary | Yes | No (use detect) |+| none | nothing | No | No |++Similarity always works (pure numpy).diff --git a/python/facex/__init__.py b/python/facex/__init__.pynew file mode 100644index 0000000..35a20bf--- /dev/null+++ b/python/facex/__init__.py@@ -0,0 +1,14 @@+"""+FaceX — Python binding for face detection + recognition.++Usage:+ from facex import FaceX+ fx = FaceX()+ faces = fx.detect(image_rgb) # numpy uint8 HWC+ sim = FaceX.similarity(emb1, emb2) # cosine similarity+"""++from facex.core import FaceX, similarity++__version__ = "0.1.0"+__all__ = ["FaceX", "similarity"]diff --git a/python/facex/core.py b/python/facex/core.pynew file mode 100644index 0000000..10278d9--- /dev/null+++ b/python/facex/core.py@@ -0,0 +1,486 @@+"""+FaceX core module — ctypes binding with subprocess fallback.+"""++import ctypes+import ctypes.util+import os+import platform+import struct+import subprocess+import sys+from pathlib import Path+from typing import Dict, List, Optional, Tuple++import numpy as np++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------+EMBEDDING_DIM = 512+MAX_FACES_DEFAULT = 20++# FaceXResult struct layout:+# float x1, y1, x2, y2, score (5 floats = 20 bytes)+# float kps[10] (10 floats = 40 bytes)+# float embedding[512] (512 floats = 2048 bytes)+# Total: 527 floats = 2108 bytes+_RESULT_FLOATS = 5 + 10 + EMBEDDING_DIM # 527+_RESULT_BYTES = _RESULT_FLOATS * 4 # 2108+++class FaceXResult(ctypes.Structure):+ """Mirrors the C FaceXResult struct."""+ _fields_ = [+ ("x1", ctypes.c_float),+ ("y1", ctypes.c_float),+ ("x2", ctypes.c_float),+ ("y2", ctypes.c_float),+ ("score", ctypes.c_float),+ ("kps", ctypes.c_float * 10),+ ("embedding", ctypes.c_float * EMBEDDING_DIM),+ ]+++def _result_to_dict(r: FaceXResult) -> dict:+ """Convert a FaceXResult struct to a Python dict."""+ kps_raw = list(r.kps)+ keypoints = [(kps_raw[i], kps_raw[i + 1]) for i in range(0, 10, 2)]+ return {+ "bbox": (r.x1, r.y1, r.x2, r.y2),+ "score": r.score,+ "keypoints": keypoints,+ "embedding": np.array(list(r.embedding), dtype=np.float32),+ }+++# ---------------------------------------------------------------------------+# Library discovery+# ---------------------------------------------------------------------------+def _find_lib() -> Optional[str]:+ """Try to locate the FaceX shared library."""+ # Check env var first+ env = os.environ.get("FACEX_LIB")+ if env and os.path.isfile(env):+ return env++ system = platform.system()+ if system == "Windows":+ names = ["facex.dll", "libfacex.dll"]+ elif system == "Darwin":+ names = ["libfacex.dylib"]+ else:+ names = ["libfacex.so"]++ # Search relative to this file, then facex root, then PATH+ search_dirs = []++ # facex project root (two levels up from python/facex/)+ pkg_dir = Path(__file__).resolve().parent+ facex_root = pkg_dir.parent.parent+ search_dirs.append(facex_root)+ search_dirs.append(facex_root / "lib")+ search_dirs.append(facex_root / "build")+ search_dirs.append(facex_root / "build" / "Release")++ # Also check FACEX_ROOT env+ root_env = os.environ.get("FACEX_ROOT")+ if root_env:+ p = Path(root_env)+ search_dirs.extend([p, p / "lib", p / "build"])++ for d in search_dirs:+ for name in names:+ candidate = d / name+ if candidate.is_file():+ return str(candidate)++ # Last resort: ctypes.util+ found = ctypes.util.find_library("facex")+ return found+++def _find_cli() -> Optional[str]:+ """Try to locate the facex-cli executable."""+ env = os.environ.get("FACEX_CLI")+ if env and os.path.isfile(env):+ return env++ system = platform.system()+ ext = ".exe" if system == "Windows" else ""+ names = [f"facex-cli{ext}", f"facex-example{ext}"]++ pkg_dir = Path(__file__).resolve().parent+ facex_root = pkg_dir.parent.parent+ search_dirs = [facex_root, facex_root / "build", facex_root / "build" / "Release"]++ root_env = os.environ.get("FACEX_ROOT")+ if root_env:+ p = Path(root_env)+ search_dirs.extend([p, p / "build"])++ for d in search_dirs:+ for name in names:+ candidate = d / name+ if candidate.is_file():+ return str(candidate)+ return None+++def _find_weights() -> Tuple[Optional[str], Optional[str]]:+ """Locate default weight files (embed, detect)."""+ env_embed = os.environ.get("FACEX_EMBED_WEIGHTS")+ env_detect = os.environ.get("FACEX_DETECT_WEIGHTS")+ if env_embed and env_detect:+ return env_embed, env_detect++ pkg_dir = Path(__file__).resolve().parent+ facex_root = pkg_dir.parent.parent+ weights_dir = facex_root / "weights"++ embed_names = ["embed.bin", "edgeface_fp32.bin", "edgeface.bin"]+ detect_names = ["detect.bin", "yunet_fp32.bin", "yunet.bin"]++ embed_path = env_embed+ detect_path = env_detect++ if not embed_path:+ for name in embed_names:+ p = weights_dir / name+ if p.is_file():+ embed_path = str(p)+ break++ if not detect_path:+ for name in detect_names:+ p = weights_dir / name+ if p.is_file():+ detect_path = str(p)+ break++ return embed_path, detect_path+++# ---------------------------------------------------------------------------+# Pure-Python similarity (always available)+# ---------------------------------------------------------------------------+def similarity(emb1: np.ndarray, emb2: np.ndarray) -> float:+ """+ Cosine similarity between two 512-dim embeddings.++ Args:+ emb1: numpy float32 array of shape (512,)+ emb2: numpy float32 array of shape (512,)++ Returns:+ Cosine similarity in [-1, 1]. Values > 0.3 indicate same person.+ """+ emb1 = np.asarray(emb1, dtype=np.float32).ravel()+ emb2 = np.asarray(emb2, dtype=np.float32).ravel()+ if emb1.shape[0] != EMBEDDING_DIM or emb2.shape[0] != EMBEDDING_DIM:+ raise ValueError(f"Embeddings must be {EMBEDDING_DIM}-dim, "+ f"got {emb1.shape[0]} and {emb2.shape[0]}")+ dot = np.dot(emb1, emb2)+ norm1 = np.linalg.norm(emb1)+ norm2 = np.linalg.norm(emb2)+ if norm1 < 1e-9 or norm2 < 1e-9:+ return 0.0+ return float(dot / (norm1 * norm2))+++# ---------------------------------------------------------------------------+# FaceX class+# ---------------------------------------------------------------------------+class FaceX:+ """+ Python interface to the FaceX face detection + recognition engine.++ Tries ctypes (shared library) first, falls back to subprocess (CLI).+ Pure-Python similarity is always available even without native code.++ Args:+ lib_path: Path to shared library (.dll/.so/.dylib). Auto-detected if None.+ cli_path: Path to facex-cli binary. Auto-detected if None.+ 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).+ nms_threshold: NMS IoU threshold (default 0.4).+ max_faces: Maximum faces to detect per image (default 20).+ """++ def __init__(+ self,+ lib_path: Optional[str] = None,+ cli_path: Optional[str] = None,+ embed_weights: Optional[str] = None,+ detect_weights: Optional[str] = None,+ license_key: Optional[str] = None,+ score_threshold: float = 0.5,+ nms_threshold: float = 0.4,+ max_faces: int = MAX_FACES_DEFAULT,+ ):+ self._lib = None+ self._handle = None+ self._cli_path = cli_path+ self._max_faces = max_faces+ self._score_threshold = score_threshold+ self._nms_threshold = nms_threshold++ # Resolve weights+ auto_embed, auto_detect = _find_weights()+ self._embed_weights = embed_weights or auto_embed+ self._detect_weights = detect_weights or auto_detect++ # Try ctypes first+ lib_file = lib_path or _find_lib()+ if lib_file:+ try:+ self._init_ctypes(lib_file, license_key)+ return+ except OSError as e:+ print(f"[facex] ctypes load failed ({e}), trying subprocess fallback",+ file=sys.stderr)++ # Fallback: locate CLI+ if not self._cli_path:+ self._cli_path = _find_cli()++ if not self._lib and not self._cli_path:+ print("[facex] WARNING: No shared library or CLI found. "+ "Only similarity() will work. Set FACEX_LIB or FACEX_CLI env var.",+ file=sys.stderr)++ def _init_ctypes(self, lib_path: str, license_key: Optional[str]):+ """Load the shared library and initialize the engine."""+ self._lib = ctypes.CDLL(lib_path)++ # facex_init+ self._lib.facex_init.argtypes = [+ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p+ ]+ self._lib.facex_init.restype = ctypes.c_void_p++ # facex_detect+ self._lib.facex_detect.argtypes = [+ ctypes.c_void_p,+ ctypes.POINTER(ctypes.c_uint8),+ ctypes.c_int,+ ctypes.c_int,+ ctypes.POINTER(FaceXResult),+ ctypes.c_int,+ ]+ self._lib.facex_detect.restype = ctypes.c_int++ # facex_embed+ self._lib.facex_embed.argtypes = [+ ctypes.c_void_p,+ ctypes.POINTER(ctypes.c_float),+ ctypes.POINTER(ctypes.c_float),+ ]+ self._lib.facex_embed.restype = ctypes.c_int++ # facex_similarity+ self._lib.facex_similarity.argtypes = [+ ctypes.POINTER(ctypes.c_float),+ ctypes.POINTER(ctypes.c_float),+ ]+ self._lib.facex_similarity.restype = ctypes.c_float++ # facex_free+ self._lib.facex_free.argtypes = [ctypes.c_void_p]+ self._lib.facex_free.restype = None++ # facex_set_score_threshold+ self._lib.facex_set_score_threshold.argtypes = [+ ctypes.c_void_p, ctypes.c_float+ ]+ self._lib.facex_set_score_threshold.restype = None++ # facex_set_nms_threshold+ self._lib.facex_set_nms_threshold.argtypes = [+ ctypes.c_void_p, ctypes.c_float+ ]+ self._lib.facex_set_nms_threshold.restype = None++ # Init engine+ embed_b = self._embed_weights.encode() if self._embed_weights else None+ detect_b = self._detect_weights.encode() if self._detect_weights else None+ key_b = license_key.encode() if license_key else None++ self._handle = self._lib.facex_init(embed_b, detect_b, key_b)+ if not self._handle:+ self._lib = None+ raise RuntimeError("facex_init returned NULL — check weight paths")++ self._lib.facex_set_score_threshold(self._handle, self._score_threshold)+ self._lib.facex_set_nms_threshold(self._handle, self._nms_threshold)++ @property+ def backend(self) -> str:+ """Return which backend is active: 'ctypes', 'cli', or 'none'."""+ if self._lib and self._handle:+ return "ctypes"+ if self._cli_path:+ return "cli"+ return "none"++ def detect(+ self,+ image: np.ndarray,+ max_faces: Optional[int] = None,+ ) -> List[dict]:+ """+ Detect faces and compute embeddings.++ Args:+ image: RGB uint8 numpy array, shape (H, W, 3).+ max_faces: Override max faces for this call.++ Returns:+ List of dicts, each with keys:+ bbox: (x1, y1, x2, y2) in pixel coords+ score: detection confidence [0, 1]+ keypoints: list of 5 (x, y) tuples+ embedding: numpy float32 array of shape (512,)+ """+ image = np.ascontiguousarray(image, dtype=np.uint8)+ if image.ndim != 3 or image.shape[2] != 3:+ raise ValueError(f"Expected HWC RGB uint8 image, got shape {image.shape}")++ h, w = image.shape[:2]+ mf = max_faces or self._max_faces++ if self._lib and self._handle:+ return self._detect_ctypes(image, w, h, mf)+ elif self._cli_path:+ return self._detect_cli(image, w, h, mf)+ else:+ raise RuntimeError(+ "No backend available. Install the shared library or set FACEX_CLI."+ )++ 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 n < 0:+ raise RuntimeError(f"facex_detect returned error code {n}")+ return [_result_to_dict(results[i]) for i in range(n)]++ def _detect_cli(self, image: np.ndarray, w: int, h: int, max_faces: int) -> List[dict]:+ """Subprocess fallback: pipe image data to CLI and parse output."""+ # Build command — the CLI protocol:+ # stdin: 4 bytes width (le) + 4 bytes height (le) + w*h*3 bytes RGB uint8+ # stdout: 4 bytes num_faces (le) + num_faces * FaceXResult as raw floats+ args = [self._cli_path, "--detect", "--pipe"]+ if self._embed_weights:+ args.extend(["--embed-weights", self._embed_weights])+ if self._detect_weights:+ args.extend(["--detect-weights", self._detect_weights])+ args.extend(["--max-faces", str(max_faces)])+ args.extend(["--score-threshold", str(self._score_threshold)])++ header = struct.pack("<ii", w, h)+ input_data = header + image.tobytes()++ try:+ proc = subprocess.run(+ args,+ input=input_data,+ capture_output=True,+ timeout=30,+ )+ except FileNotFoundError:+ raise RuntimeError(f"CLI not found: {self._cli_path}")+ except subprocess.TimeoutExpired:+ raise RuntimeError("facex-cli timed out")++ if proc.returncode != 0:+ stderr = proc.stderr.decode(errors="replace").strip()+ raise RuntimeError(f"facex-cli failed (rc={proc.returncode}): {stderr}")++ out = proc.stdout+ if len(out) < 4:+ raise RuntimeError("facex-cli produced no output")++ n = struct.unpack("<i", out[:4])[0]+ expected = 4 + n * _RESULT_BYTES+ if len(out) < expected:+ raise RuntimeError(+ f"Incomplete output: expected {expected} bytes, got {len(out)}"+ )++ faces = []+ offset = 4+ for i in range(n):+ floats = struct.unpack_from(f"<{_RESULT_FLOATS}f", out, offset)+ offset += _RESULT_BYTES+ x1, y1, x2, y2, score = floats[:5]+ kps_raw = floats[5:15]+ emb = np.array(floats[15:], dtype=np.float32)+ keypoints = [(kps_raw[j], kps_raw[j + 1]) for j in range(0, 10, 2)]+ faces.append({+ "bbox": (x1, y1, x2, y2),+ "score": score,+ "keypoints": keypoints,+ "embedding": emb,+ })+ return faces++ def embed(self, face_112x112: np.ndarray) -> np.ndarray:+ """+ Compute embedding for a pre-aligned 112x112 face crop.++ Args:+ face_112x112: float32 numpy array shape (112, 112, 3), values in [-1, 1].++ Returns:+ numpy float32 array of shape (512,), L2-normalized.+ """+ face = np.ascontiguousarray(face_112x112, dtype=np.float32)+ if face.shape != (112, 112, 3):+ raise ValueError(f"Expected (112, 112, 3), got {face.shape}")++ if self._lib and self._handle:+ return self._embed_ctypes(face)+ else:+ raise RuntimeError(+ "embed() requires the shared library (ctypes backend). "+ "Use detect() which includes embedding, or install libfacex."+ )++ def _embed_ctypes(self, face: np.ndarray) -> np.ndarray:+ embedding = np.zeros(EMBEDDING_DIM, dtype=np.float32)+ ptr_in = face.ctypes.data_as(ctypes.POINTER(ctypes.c_float))+ ptr_out = embedding.ctypes.data_as(ctypes.POINTER(ctypes.c_float))+ rc = self._lib.facex_embed(self._handle, ptr_in, ptr_out)+ if rc != 0:+ raise RuntimeError(f"facex_embed returned error code {rc}")+ return embedding++ @staticmethod+ def similarity(emb1: np.ndarray, emb2: np.ndarray) -> float:+ """Cosine similarity between two 512-dim embeddings."""+ return similarity(emb1, emb2)++ def close(self):+ """Release native resources."""+ if self._lib and self._handle:+ self._lib.facex_free(self._handle)+ self._handle = None++ def __del__(self):+ try:+ self.close()+ except Exception:+ pass++ def __enter__(self):+ return self++ def __exit__(self, *args):+ self.close()++ def __repr__(self):+ return f"FaceX(backend={self.backend!r})"diff --git a/python/facex/py.typed b/python/facex/py.typednew file mode 100644index 0000000..e69de29diff --git a/python/pyproject.toml b/python/pyproject.tomlnew file mode 100644index 0000000..1cc2831--- /dev/null+++ b/python/pyproject.toml@@ -0,0 +1,20 @@+[build-system]+requires = ["setuptools>=64"]+build-backend = "setuptools.build_meta"++[project]+name = "facex"+version = "0.1.0"+description = "Python binding for FaceX face detection + recognition"+readme = "README.md"+requires-python = ">=3.8"+license = {text = "Apache-2.0"}+authors = [{name = "Baurzhan Atinov"}]+dependencies = ["numpy>=1.20"]++[project.optional-dependencies]+image = ["Pillow>=8.0"]+dev = ["pytest>=7.0", "Pillow>=8.0"]++[tool.setuptools.packages.find]+include = ["facex*"]diff --git a/wasm/index.d.ts b/wasm/index.d.tsnew file mode 100644index 0000000..8d6ea23--- /dev/null+++ b/wasm/index.d.ts@@ -0,0 +1,249 @@+/**+ * facex-wasm — Face recognition in the browser.+ * 75 KB WASM. Detect, align, embed, verify.+ * No server. No dependencies.+ */++// ---------------------------------------------------------------------------+// Options+// ---------------------------------------------------------------------------++/** Configuration options for FaceXSDK */+export interface FaceXOptions {+ /** Detection input size in pixels (default: 160) */+ detSize?: number;+ /** Cosine similarity threshold for a positive match (default: 0.3) */+ threshold?: number;+ /** URL to detector weights file (default: 'yunet_fp32.bin') */+ detWeightsUrl?: string;+ /** URL to embedder weights file (default: 'edgeface_xs_fp32.bin') */+ embWeightsUrl?: string;+ /** Progress callback invoked during loading */+ onProgress?: (message: string) => void;+}++// ---------------------------------------------------------------------------+// Result types+// ---------------------------------------------------------------------------++/** A detected face with bounding box, confidence, and 5 keypoints */+export interface Face {+ /** Left edge of bounding box */+ x1: number;+ /** Top edge of bounding box */+ y1: number;+ /** Right edge of bounding box */+ x2: number;+ /** Bottom edge of bounding box */+ y2: number;+ /** Detection confidence (0 to 1) */+ score: number;+ /**+ * 5 keypoints as a flat array of 10 values:+ * [left_eye_x, left_eye_y, right_eye_x, right_eye_y,+ * nose_x, nose_y, left_mouth_x, left_mouth_y, right_mouth_x, right_mouth_y]+ */+ kps: number[];+}++/** Result from the full detect-align-embed pipeline */+export interface ProcessResult {+ /** Detected faces with bounding boxes and keypoints */+ faces: Face[];+ /** 512-dimensional embedding for each detected face */+ embeddings: Float32Array[];+ /** Total processing time in milliseconds */+ ms: number;+}++/** Result from a verification (1:1 match) operation */+export interface VerifyResult {+ /** Whether the face matches the reference embedding */+ match: boolean;+ /** Cosine similarity between detected and reference embeddings (0 to 1) */+ similarity: number;+ /** Detected faces */+ faces: Face[];+ /** Embedding of the first detected face, if any */+ embedding?: Float32Array;+ /** Total time in milliseconds */+ ms: number;+ /** True when no face was found in the source */+ noFace?: boolean;+}++/** Result from capturing a reference embedding */+export interface CaptureResult {+ /** 512-dimensional reference embedding */+ embedding: Float32Array;+ /** Detected face used for the embedding */+ face: Face;+ /** Canvas containing the aligned 112x112 face crop */+ alignedCanvas: HTMLCanvasElement;+}++// ---------------------------------------------------------------------------+// Liveness+// ---------------------------------------------------------------------------++/** Options for LivenessDetector */+export interface LivenessOptions {+ /** Number of frames to keep in history (default: 30) */+ historySize?: number;+ /** Minimum motion in pixels to consider alive (default: 2.0) */+ motionThreshold?: number;+ /** Eye aspect ratio threshold for blink detection (default: 0.22) */+ blinkThreshold?: number;+}++/** Result from a liveness check */+export interface LivenessResult {+ /** Whether the subject appears to be a live person */+ alive: boolean;+ /** Confidence score (0 to 1) */+ confidence: number;+ /** Human-readable status message */+ reason: string;+ /** Detailed metrics (present when enough frames collected) */+ details?: {+ motion: number;+ blinks: number;+ sizeVar: number;+ };+}++// ---------------------------------------------------------------------------+// FaceXSDK+// ---------------------------------------------------------------------------++/** Input source type accepted by SDK methods */+export type FaceSource = HTMLVideoElement | HTMLCanvasElement | HTMLImageElement;++/**+ * Unified FaceX browser SDK.+ *+ * Provides face detection, alignment, 512-dim embedding, verification,+ * and reference capture from video, image, or canvas elements.+ */+export declare class FaceXSDK {+ constructor(options?: FaceXOptions);++ /** Whether the SDK is loaded and ready to use */+ readonly ready: boolean;++ /**+ * Load WASM engines and model weights. Call once before any other method.+ * @returns The SDK instance for chaining.+ */+ load(): Promise<FaceXSDK>;++ /**+ * Detect faces in a video, image, or canvas element.+ * @param source - Media element to detect faces in.+ * @returns Array of detected faces with bounding boxes and keypoints.+ */+ detect(source: FaceSource): Face[];++ /**+ * Compute a 512-dimensional embedding from an aligned 112x112 face.+ * @param faceImageData - 112x112 RGBA ImageData of an aligned face.+ * @returns 512-dimensional Float32Array embedding.+ */+ embed(faceImageData: ImageData): Float32Array;++ /**+ * Full pipeline: detect faces, align each, compute embeddings.+ * @param source - Media element to process.+ */+ process(source: FaceSource): ProcessResult;++ /**+ * Verify a live source against a previously captured reference embedding.+ * @param source - Media element containing the live face.+ * @param refEmbedding - 512-dim reference embedding to compare against.+ */+ verify(source: FaceSource, refEmbedding: Float32Array): VerifyResult;++ /**+ * Capture a reference embedding from the current frame.+ * @param source - Media element to capture from.+ * @returns Capture result, or null if no face was detected.+ */+ captureReference(source: FaceSource): CaptureResult | null;++ /**+ * Compute cosine similarity between two 512-dimensional embeddings.+ * @returns Similarity score between -1 and 1.+ */+ cosSim(a: Float32Array, b: Float32Array): number;+}++// ---------------------------------------------------------------------------+// LivenessDetector+// ---------------------------------------------------------------------------++/**+ * Basic liveness detection using face keypoint analysis.+ *+ * Detects motion, blinks, and size variation across frames to distinguish+ * a live person from a static photo or screen replay.+ */+export declare class LivenessDetector {+ constructor(options?: LivenessOptions);++ /**+ * Feed a new face detection frame.+ * @param face - Detected face from FaceXSDK.detect(), or null if no face.+ * @returns Liveness assessment.+ */+ update(face: Face | null): LivenessResult;++ /** Reset all accumulated state */+ reset(): void;+}++// ---------------------------------------------------------------------------+// Utility functions+// ---------------------------------------------------------------------------++/**+ * Check if the browser supports WebAssembly SIMD.+ * FaceX requires SIMD: Chrome 91+, Firefox 89+, Safari 16.4+.+ */+export declare function checkWasmSimd(): boolean;++/**+ * Check browser support for all FaceX requirements.+ * @returns Array of human-readable issue strings. Empty array = all good.+ */+export declare function checkBrowserSupport(): string[];++/**+ * Align a face to a canonical 112x112 crop using 5 keypoints.+ * @param srcCtx - Source canvas rendering context (full video frame).+ * @param srcW - Source width.+ * @param srcH - Source height.+ * @param kps - 5 keypoints as [[x,y], ...] in source coordinates.+ * @param dstCtx - Destination 112x112 canvas rendering context.+ * @returns 112x112 ImageData of the aligned face.+ */+export declare function alignFace(+ srcCtx: CanvasRenderingContext2D,+ srcW: number,+ srcH: number,+ kps: [number, number][],+ dstCtx: CanvasRenderingContext2D+): ImageData;++/**+ * Load model weights with IndexedDB caching.+ * First call fetches from network and caches; subsequent calls load from cache.+ * @param url - URL to fetch weights from.+ * @param key - Cache key (e.g. 'det_weights').+ * @param onProgress - Optional progress callback(loaded, total).+ */+export declare function loadWeightsCached(+ url: string,+ key: string,+ onProgress?: (loaded: number, total: number) => void+): Promise<Uint8Array>;diff --git a/wasm/index.js b/wasm/index.jsnew file mode 100644index 0000000..3220258--- /dev/null+++ b/wasm/index.js@@ -0,0 +1,38 @@+/**+ * facex-wasm — Face recognition in the browser.+ *+ * This is the npm package entry point. It re-exports the classes and+ * utilities defined in the individual script files.+ *+ * Usage (bundler / ESM):+ * import { FaceXSDK } from 'facex-wasm';+ * const fx = new FaceXSDK();+ * await fx.load();+ * const result = fx.process(videoElement);+ *+ * Usage (script tag):+ * <script src="node_modules/facex-wasm/detect.js"></script>+ * <script src="node_modules/facex-wasm/facex.js"></script>+ * <script src="node_modules/facex-wasm/align.js"></script>+ * <script src="node_modules/facex-wasm/facex-sdk.js"></script>+ * // FaceXSDK is now available as a global+ */++// The SDK files define globals (FaceXSDK, LivenessDetector, etc.) when+// loaded via <script> tags. For bundler consumers we provide this entry+// point that pulls them together. Because the source files are plain+// browser scripts (no module syntax), we need to reference the globals.++if (typeof globalThis !== 'undefined') {+ // Make sure the exports object exists for CJS consumers+ if (typeof module !== 'undefined' && module.exports) {+ module.exports = {+ get FaceXSDK() { return globalThis.FaceXSDK; },+ get LivenessDetector() { return globalThis.LivenessDetector; },+ get checkWasmSimd() { return globalThis.checkWasmSimd; },+ get checkBrowserSupport() { return globalThis.checkBrowserSupport; },+ get alignFace() { return globalThis.alignFace; },+ get loadWeightsCached() { return globalThis.loadWeightsCached; },+ };+ }+}diff --git a/wasm/package.json b/wasm/package.jsonindex a6efac5..81e2ffc 100644--- a/wasm/package.json+++ b/wasm/package.json@@ -1,29 +1,38 @@{- "name": "facex-web",- "version": "1.0.0",- "description": "Face recognition in the browser. 74 KB WASM. No server, no dependencies.",- "main": "facex-sdk.js",- "types": "facex-sdk.d.ts",+ "name": "facex-wasm",+ "version": "0.1.0",+ "description": "Face recognition in the browser. 75 KB WASM. Detect, align, embed, verify — no server, no dependencies.",+ "main": "index.js",+ "types": "index.d.ts","files": [+ "index.js",+ "index.d.ts","facex-sdk.js","facex-sdk.d.ts","align.js",+ "liveness.js",+ "cache.js",+ "simd_check.js",+ "worker.js","detect.js","detect.wasm","facex.js",- "facex.wasm"+ "facex.wasm",+ "README.md"],"keywords": ["face-recognition","face-detection","face-embedding",+ "face-verification",+ "liveness","webassembly","wasm","simd","browser","privacy",- "zero-dependencies",- "offline"+ "offline",+ "zero-dependencies"],"author": "Baurzhan Atinov","license": "Apache-2.0",@@ -32,5 +41,15 @@"type": "git","url": "https://github.com/facex-engine/facex.git","directory": "wasm"- }+ },+ "sideEffects": false,+ "engines": {+ "node": ">=16"+ },+ "browserslist": [+ "Chrome >= 91",+ "Firefox >= 89",+ "Safari >= 16.4",+ "Edge >= 91"+ ]}