UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.
Python computer-visiondeep-learningface-alignmentface-analysisface-anonymizationface-anti-spoofingface-attributesface-detectionface-meshface-parsingface-quality-assessmentface-recognitionface-segmentationface-trackingfacial-landmarksgaze-estimationhead-pose-estimationonnxruntimeportrait-mattingpython
feat: Release v4.0.0 (#130)
Yakhyokhuja Valikhujaev4d6f29a1139a
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.ymlindex 5725388..5601514 100644--- a/.github/workflows/docs.yml+++ b/.github/workflows/docs.yml@@ -4,11 +4,20 @@ on:workflow_dispatch:permissions:- contents: write+ contents: read+ pages: write+ id-token: write++concurrency:+ group: pages+ cancel-in-progress: falsejobs:deploy:runs-on: ubuntu-latest+ environment:+ name: github-pages+ url: ${{ steps.deployment.outputs.page_url }}steps:- uses: actions/checkout@v5with:@@ -28,11 +37,14 @@ jobs:MKDOCS_GIT_COMMITTERS_APIKEY: ${{ secrets.MKDOCS_GIT_COMMITTERS_APIKEY }}run: uv run mkdocs build --strict- - name: Deploy to GitHub Pages- uses: peaceiris/actions-gh-pages@v4- env:- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true+ - name: Configure GitHub Pages+ uses: actions/configure-pages@v5++ - name: Upload site artifact+ uses: actions/upload-pages-artifact@v4with:- github_token: ${{ secrets.GITHUB_TOKEN }}- publish_dir: ./site- destination_dir: docs+ path: ./site++ - name: Deploy to GitHub Pages+ id: deployment+ uses: actions/deploy-pages@v4diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 031cf32..1cc4075 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -196,7 +196,15 @@ jobs:needs: [validate, publish]if: needs.validate.outputs.is_prerelease == 'false'permissions:- contents: write+ contents: read+ pages: write+ id-token: write+ environment:+ name: github-pages+ url: ${{ steps.deployment.outputs.page_url }}+ concurrency:+ group: pages+ cancel-in-progress: falsesteps:- name: Checkout tag@@ -219,11 +227,14 @@ jobs:MKDOCS_GIT_COMMITTERS_APIKEY: ${{ secrets.MKDOCS_GIT_COMMITTERS_APIKEY }}run: uv run mkdocs build --strict- - name: Deploy to GitHub Pages- uses: peaceiris/actions-gh-pages@v4- env:- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true+ - name: Configure GitHub Pages+ uses: actions/configure-pages@v5++ - name: Upload site artifact+ uses: actions/upload-pages-artifact@v4with:- github_token: ${{ secrets.GITHUB_TOKEN }}- publish_dir: ./site- destination_dir: docs+ path: ./site++ - name: Deploy to GitHub Pages+ id: deployment+ uses: actions/deploy-pages@v4diff --git a/.gitignore b/.gitignoreindex 2eb578f..681bbf0 100644--- a/.gitignore+++ b/.gitignore@@ -1,5 +1,6 @@tmp_*.vscode/+.claude# Byte-compiled / optimized / DLL files__pycache__/diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..c95e3b5--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,64 @@+# Changelog++Notable changes to UniFace are documented here. Earlier releases are covered by+the autogenerated notes on the [GitHub releases page](https://github.com/yakhyo/uniface/releases).++## 4.0.0 - 2026-08-03++### Breaking changes++- **Factory functions are gone.** `create_detector()` and its siblings no longer+ exist. Construct model classes directly.+- **`FaceAnalyzer(attributes=...)` is now `predictors=`.** The parameter accepts+ any list of `BaseAttribute` subclasses.+- **`Attribute` is renamed `BaseAttribute`**, matching `BaseDetector`,+ `BaseRecognizer`, and the other base classes.+- **Constructors are keyword-only.** Every model class, plus `FaceAnalyzer`,+ `BlurFace`, `EllipticalBlur`, `FAISS`, and `BYTETracker`, rejects positional+ arguments. `SCRFD(model_name)` raises `TypeError`; write+ `SCRFD(model_name=...)`.+- **Detector `**kwargs` replaced with explicit options.** `RetinaFace` takes+ `pre_nms_topk`, `post_nms_topk`, and `dynamic_size`; `YOLOv5Face` and+ `YOLOv8Face` take `max_det`. Misspelled options now fail instead of being+ silently ignored.+- **`input_size` removed from `MobileGaze`, `HeadPose`, `BiSeNet`, and+ `Landmark106`.** These models always resized to the size in the ONNX graph;+ the parameter had no effect and is gone.+- **Inputs are validated.** Detectors and landmarkers require 3-channel `uint8`+ BGR images. Float or grayscale arrays now raise `ValueError` instead of+ silently returning no faces.+- **Detector capability flags are opt-in.** `supports_landmarks` and+ `supports_alignment` default to `False` on `BaseDetector`. Third-party+ detector subclasses that produce 5-point alignment landmarks must now declare+ both flags; boxes-only subclasses need no declaration.++### Migrating from 3.x++| 3.x | 4.0 |+| --- | --- |+| `create_detector('retinaface', ...)` | `RetinaFace(...)` |+| `RetinaFace(RetinaFaceWeights.MNET_V2)` | `RetinaFace(model_name=RetinaFaceWeights.MNET_V2)` |+| `FaceAnalyzer(attributes=[AgeGender()])` | `FaceAnalyzer(predictors=[AgeGender()])` |+| `class MyPredictor(Attribute)` | `class MyPredictor(BaseAttribute)` |+| `RetinaFace(**{'pre_nms_topk': 1000})` | `RetinaFace(pre_nms_topk=1000)` |+| `HeadPose(input_size=(224, 224))` | `HeadPose()` |++### Added++- `BlazeFace` detector: MediaPipe short-range face detector with 6 keypoints.+- `CenterFace` detector.+- `FaceMesh` landmarker: MediaPipe dense 3D face mesh, 468 points or 478 with+ irises (`FaceMeshWeights.V2_478`).+- `FaceAttribNet` predictor: eye openness, eyeglasses, sunglasses, and mask+ probabilities as `FaceStateResult`, enriching `Face` in-place.+- Hugging Face mirror fallback for weight downloads when GitHub Releases is+ unreachable, pinned to an immutable revision.+- `uniface.common.validate_image` is public for use in custom models.++### Fixed++- `BlazeFace` weighted NMS could loop forever with `iou_threshold=1.0` or a+ zero-area box; it now always terminates.+- `Face.__repr__` no longer assumes all five face-state fields are set together.+- Attribute models normalize `input_size` and warn when it disagrees with the+ ONNX metadata; `FaceAttribNet` rejects non-square sizes.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5dd3d31..c6ddf44 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -88,22 +88,22 @@ def process(items: List[str], config: Optional[Dict[str, int]] = None) -> Tuple[Use [Google-style docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) for all public APIs:```python-def create_detector(method: str = 'retinaface', **kwargs: Any) -> BaseDetector:- """Factory function to create face detectors.+def detect(self, image: np.ndarray, **kwargs: Any) -> list[Face]:+ """Detect faces in an image.Args:- method: Detection method. Options: 'retinaface', 'scrfd', 'yolov5face', 'yolov8face'.- **kwargs: Detector-specific parameters.+ image: Input image as numpy array with shape (H, W, C) in BGR format.+ **kwargs: Additional detection parameters.Returns:- Initialized detector instance.+ List of detected Face objects.Raises:- ValueError: If method is not supported.+ ValueError: If the image is empty, not 3-channel BGR, or not uint8.Example:- >>> from uniface import create_detector- >>> detector = create_detector('retinaface', confidence_threshold=0.8)+ >>> from uniface import RetinaFace+ >>> detector = RetinaFace(confidence_threshold=0.8)>>> faces = detector.detect(image)>>> print(f"Found {len(faces)} faces")"""@@ -159,7 +159,7 @@ pytest tests/pytest tests/ -v# Run specific test file-pytest tests/test_factory.py+pytest tests/test_scrfd.py# Run with coveragepytest tests/ --cov=uniface --cov-report=html@@ -193,6 +193,10 @@ Example notebooks demonstrating library usage:| Face Segmentation | [09_face_segmentation.ipynb](examples/09_face_segmentation.ipynb) || Face Vector Store | [10_face_vector_store.ipynb](examples/10_face_vector_store.ipynb) || Head Pose Estimation | [11_head_pose_estimation.ipynb](examples/11_head_pose_estimation.ipynb) |+| Face Recognition | [12_face_recognition.ipynb](examples/12_face_recognition.ipynb) |+| Portrait Matting | [13_portrait_matting.ipynb](examples/13_portrait_matting.ipynb) |+| Face Attributes | [14_face_attributes.ipynb](examples/14_face_attributes.ipynb) |+| Face Mesh | [15_face_mesh.ipynb](examples/15_face_mesh.ipynb) |## Release Processdiff --git a/README.md b/README.mdindex ea7e570..5ce8bb5 100644--- a/README.md+++ b/README.md@@ -16,30 +16,27 @@<img src="https://raw.githubusercontent.com/yakhyo/uniface/main/.github/logos/uniface_rounded_q80.webp" width="90%" alt="UniFace - A Unified Face Analysis Library for Python"></div>------**UniFace** is a lightweight, production-ready Python library for face detection, recognition, tracking, landmark analysis, face parsing, gaze estimation, and face attributes.-----+> [!NOTE]+> **UniFace** is a lightweight, production-ready Python library for face detection, recognition, tracking, landmark analysis, face parsing, gaze estimation, and face attributes.## Features-- **Face Detection** — RetinaFace, SCRFD, YOLOv5-Face, and YOLOv8-Face with 5-point landmarks-- **Face Recognition** — AdaFace, ArcFace, EdgeFace, MobileFace, and SphereFace embeddings-- **Face Tracking** — Multi-object tracking with [BYTETracker](https://github.com/yakhyo/bytetrack-tracker) for persistent IDs across video frames-- **Facial Landmarks** — 106-point (2d106det) and 98 / 68-point (PIPNet) landmark localization (separate from the 5-point detector landmarks)-- **Face Parsing** — BiSeNet semantic segmentation (19 classes), XSeg face masking-- **Portrait Matting** — Trimap-free alpha matte with MODNet (background removal, green screen, compositing)-- **Gaze Estimation** — Real-time gaze direction with MobileGaze-- **Head Pose Estimation** — 3D head orientation (pitch, yaw, roll) with 6D rotation representation-- **Attribute Analysis** — Age, gender, race (FairFace), and emotion-- **Vector Store** — FAISS-backed embedding store for fast multi-identity search-- **Anti-Spoofing** — Face liveness detection with MiniFASNet-- **Face Quality Assessment** — eDifFIQA single-score quality (T/S/M/L, NIST FATE-Quality #1 with the L variant)-- **Face Anonymization** — 5 blur methods for privacy protection-- **Hardware Acceleration** — ARM64 (Apple Silicon), CUDA (NVIDIA), CPU-----+| Feature | Details |+| --------------------------- | ------------------------------------------------------------------------------------------------ |+| **Face Detection** | RetinaFace, SCRFD, CenterFace, YOLOv5-Face, and YOLOv8-Face with 5-point landmarks; BlazeFace (MediaPipe, 6 keypoints) |+| **Face Recognition** | AdaFace, ArcFace, EdgeFace, MobileFace, and SphereFace embeddings |+| **Face Tracking** | Multi-object tracking with [BYTETracker](https://github.com/yakhyo/bytetrack-tracker) for persistent IDs across video frames |+| **Facial Landmarks** | 106-point (2d106det), 98 / 68-point (PIPNet), and 468 / 478-point dense 3D mesh (MediaPipe Face Mesh, the 478 variant adding irises) — separate from the 5-point detector landmarks |+| **Face Parsing** | BiSeNet semantic segmentation (19 classes), XSeg face masking |+| **Portrait Matting** | Trimap-free alpha matte with MODNet (background removal, green screen, compositing) |+| **Gaze Estimation** | Real-time gaze direction with MobileGaze |+| **Head Pose Estimation** | 3D head orientation (pitch, yaw, roll) with 6D rotation representation |+| **Attribute Analysis** | Age, gender, race (FairFace), emotion, and face states (eye openness, glasses, sunglasses, mask with FaceAttribNet) |+| **Vector Store** | FAISS-backed embedding store for fast multi-identity search |+| **Anti-Spoofing** | Face liveness detection with MiniFASNet |+| **Face Quality Assessment** | eDifFIQA single-score quality (T/S/M/L, NIST FATE-Quality #1 with the L variant) |+| **Face Anonymization** | 5 blur methods for privacy protection |+| **Hardware Acceleration** | ARM64 (Apple Silicon), CUDA (NVIDIA), CPU |## Visual Examples@@ -73,8 +70,6 @@</tr></table>-----## Installation**CPU / Apple Silicon**@@ -111,8 +106,6 @@ pip install faiss-cpu # or faiss-gpu for CUDA- YOLOv5-Face and YOLOv8-Face support faster NMS with `torchvision`:`pip install torch torchvision` then use `nms_mode='torchvision'`-----## Model Downloads and CacheModels are downloaded automatically on first use and verified via SHA-256.@@ -132,8 +125,6 @@ print(get_cache_dir()) # /data/modelsexport UNIFACE_CACHE_DIR=/data/models```-----## Quick Example (Detection)```python@@ -154,8 +145,6 @@ for face in faces:print(f"Landmarks: {face.landmarks.shape}")```-----## Example (Face Analyzer)```python@@ -180,15 +169,13 @@ With attributes:```pythonfrom uniface import FaceAnalyzer, AgeGender-analyzer = FaceAnalyzer(attributes=[AgeGender()])+analyzer = FaceAnalyzer(predictors=[AgeGender()])faces = analyzer.analyze(image)for face in faces:print(f"{face.sex}, {face.age}y, embedding={face.embedding.shape}")```-----## Example (Portrait Matting)```python@@ -213,12 +200,10 @@ result = (image * matte_3ch + bg * (1 - matte_3ch)).astype(np.uint8)cv2.imwrite("green_screen.jpg", result)```-----## Jupyter Notebooks-| Example | Colab | Description |-| -------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | --------------------------------------- |+| Example | Colab | Description |+| ---------------------------------------------------------------------- | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | --------------------------------------- || [01_face_detection.ipynb](examples/01_face_detection.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/01_face_detection.ipynb) | Face detection and landmarks || [02_face_alignment.ipynb](examples/02_face_alignment.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/02_face_alignment.ipynb) | Face alignment for recognition || [03_face_verification.ipynb](examples/03_face_verification.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/03_face_verification.ipynb) | Compare faces for identity |@@ -232,15 +217,15 @@ cv2.imwrite("green_screen.jpg", result)| [11_head_pose_estimation.ipynb](examples/11_head_pose_estimation.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/11_head_pose_estimation.ipynb) | Head pose estimation (pitch, yaw, roll) || [12_face_recognition.ipynb](examples/12_face_recognition.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/12_face_recognition.ipynb) | Standalone face recognition pipeline || [13_portrait_matting.ipynb](examples/13_portrait_matting.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/13_portrait_matting.ipynb) | Portrait matting with MODNet |-----+| [14_face_attributes.ipynb](examples/14_face_attributes.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/14_face_attributes.ipynb) | Face states (eyes, glasses, sunglasses, mask) |+| [15_face_mesh.ipynb](examples/15_face_mesh.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb) | 468 / 478-point dense 3D face mesh |## DocumentationFull documentation: https://yakhyo.github.io/uniface/-| Resource | Description |-| ------------------------------------------------------------------ | ------------------------------------------- |+| Resource | Description |+| -------------------------------------------------------------------- | ------------------------------------------- || [Quickstart](https://yakhyo.github.io/uniface/quickstart/) | Get up and running in 5 minutes || [Model Zoo](https://yakhyo.github.io/uniface/models/) | All models, benchmarks, and selection guide || [API Reference](https://yakhyo.github.io/uniface/modules/detection/) | Detailed module documentation |@@ -248,8 +233,6 @@ Full documentation: https://yakhyo.github.io/uniface/| [Guides](https://yakhyo.github.io/uniface/concepts/overview/) | Architecture and design principles || [Datasets](https://yakhyo.github.io/uniface/datasets/) | Training data and evaluation benchmarks |-----## Execution Providers (ONNX Runtime)```python@@ -262,27 +245,25 @@ detector = RetinaFace(providers=["CPUExecutionProvider"])See more in the docs:https://yakhyo.github.io/uniface/concepts/execution-providers/-----## Datasets| Task | Training Dataset | Models || ----------- | --------------------------- | ------------------------------------------- |-| Detection | WIDER FACE | RetinaFace, SCRFD, YOLOv5-Face, YOLOv8-Face |+| Detection | WIDER FACE | RetinaFace, SCRFD, CenterFace, YOLOv5-Face, YOLOv8-Face || Recognition | MS1MV2 | MobileFace, SphereFace || Recognition | WebFace600K | ArcFace |-| Recognition | WebFace4M / 12M | AdaFace |-| Recognition | MS1MV2 | EdgeFace |+| Recognition | WebFace4M / 12M | AdaFace, EdgeFace || Landmarks | WFLW, 300W+CelebA | PIPNet (98 / 68 pts) |+| Detection | Proprietary (Google) | BlazeFace (short-range) |+| Landmarks | Proprietary (Google) | Face Mesh (468 / 478 pts) || Gaze | Gaze360 | MobileGaze || Head Pose | 300W-LP | HeadPose (ResNet, MobileNet) || Parsing | CelebAMask-HQ | BiSeNet || Attributes | CelebA, FairFace, AffectNet | AgeGender, FairFace, Emotion |+| Attributes | Proprietary (Qualcomm) | FaceAttribNet |> See [Datasets documentation](https://yakhyo.github.io/uniface/datasets/) for download links, benchmarks, and details.-----## Licensing and Model UsageUniFace is MIT-licensed, but several pretrained models carry their own licenses.@@ -292,35 +273,36 @@ Notable examples:- YOLOv5-Face and YOLOv8-Face weights are GPL-3.0- FairFace weights are CC BY 4.0+- FaceAttribNet weights are BSD-3-Clause (© Qualcomm Technologies, Inc.)+- BlazeFace and Face Mesh weights are Apache-2.0 (© Google, from MediaPipe)If you plan commercial use, verify model license compatibility.-----## References-| Feature | Repository | Training | Description |-| ------------- | ------------------------------------------------------------------------------------- | :------: | ------------------------------------ |+| Feature | Repository | Training | Description |+| ------------- | --------------------------------------------------------------------------------------- | :------: | ------------------------------------ || Detection | [retinaface-pytorch](https://github.com/yakhyo/retinaface-pytorch) | ✓ | RetinaFace PyTorch Training & Export |-| Detection | [yolov5-face-onnx-inference](https://github.com/yakhyo/yolov5-face-onnx-inference) | - | YOLOv5-Face ONNX Inference |-| Detection | [yolov8-face-onnx-inference](https://github.com/yakhyo/yolov8-face-onnx-inference) | - | YOLOv8-Face ONNX Inference |+| Detection | [yolov5-face-onnx-inference](https://github.com/yakhyo/yolov5-face-onnx-inference) | - | YOLOv5-Face Inference |+| Detection | [yolov8-face-onnx-inference](https://github.com/yakhyo/yolov8-face-onnx-inference) | - | YOLOv8-Face Inference |+| Detection | [Star-Clouds/CenterFace](https://github.com/Star-Clouds/CenterFace) | - | CenterFace Original Weights || Tracking | [bytetrack-tracker](https://github.com/yakhyo/bytetrack-tracker) | - | BYTETracker Multi-Object Tracking || Recognition | [face-recognition](https://github.com/yakhyo/face-recognition) | ✓ | MobileFace, SphereFace Training |-| Recognition | [edgeface-onnx](https://github.com/yakhyo/edgeface-onnx) | - | EdgeFace ONNX Inference |-| Landmarks | [pipnet-onnx](https://github.com/yakhyo/pipnet-onnx) | - | PIPNet 98 / 68-point ONNX Inference |+| Recognition | [edgeface-onnx](https://github.com/yakhyo/edgeface-onnx) | - | EdgeFace Inference |+| Landmarks | [pipnet-onnx](https://github.com/yakhyo/pipnet-onnx) | - | PIPNet 98 / 68-point Inference |+| Landmarks | [mediapipe-face-mesh-onnx](https://github.com/yakhyo/mediapipe-face-mesh-onnx) | - | Face Mesh 468 / 478-point Inference || Parsing | [face-parsing](https://github.com/yakhyo/face-parsing) | ✓ | BiSeNet Face Parsing || Parsing | [face-segmentation](https://github.com/yakhyo/face-segmentation) | - | XSeg Face Segmentation || Gaze | [gaze-estimation](https://github.com/yakhyo/gaze-estimation) | ✓ | MobileGaze Training || Head Pose | [head-pose-estimation](https://github.com/yakhyo/head-pose-estimation) | ✓ | Head Pose Training (6DRepNet-style) || Matting | [modnet](https://github.com/yakhyo/modnet) | - | MODNet Portrait Matting || Anti-Spoofing | [face-anti-spoofing](https://github.com/yakhyo/face-anti-spoofing) | - | MiniFASNet Inference |-| Quality | [face-image-quality-assessment](https://github.com/yakhyo/face-image-quality-assessment) | - | eDifFIQA ONNX Inference |-| Attributes | [fairface-onnx](https://github.com/yakhyo/fairface-onnx) | - | FairFace ONNX Inference |+| Quality | [face-image-quality-assessment](https://github.com/yakhyo/face-image-quality-assessment) | - | eDifFIQA Inference |+| Attributes | [fairface-onnx](https://github.com/yakhyo/fairface-onnx) | - | FairFace Inference |+| Attributes | [face-attribute](https://github.com/yakhyo/face-attribute) | - | FaceAttribNet Inference |*SCRFD and ArcFace models are from [InsightFace](https://github.com/deepinsight/insightface).-----## ContributingContributions are welcome. Please see [CONTRIBUTING.md](CONTRIBUTING.md).diff --git a/assets/demos/face_attributes.png b/assets/demos/face_attributes.pngnew file mode 100644index 0000000..c006d1fBinary files /dev/null and b/assets/demos/face_attributes.png differdiff --git a/assets/test_images/attributes/eyeglasses.jpg b/assets/test_images/attributes/eyeglasses.jpgnew file mode 100644index 0000000..48e8ebcBinary files /dev/null and b/assets/test_images/attributes/eyeglasses.jpg differdiff --git a/assets/test_images/attributes/mask.jpg b/assets/test_images/attributes/mask.jpgnew file mode 100644index 0000000..250de86Binary files /dev/null and b/assets/test_images/attributes/mask.jpg differdiff --git a/assets/test_images/attributes/sunglasses.jpg b/assets/test_images/attributes/sunglasses.jpgnew file mode 100644index 0000000..dc49b8eBinary files /dev/null and b/assets/test_images/attributes/sunglasses.jpg differdiff --git a/docs/concepts/coordinate-systems.md b/docs/concepts/coordinate-systems.mdindex 9f1b2fb..29baaa3 100644--- a/docs/concepts/coordinate-systems.md+++ b/docs/concepts/coordinate-systems.md@@ -88,6 +88,16 @@ landmarks = face.landmarks # Shape: (5, 2)3 ● ● 4```+This ordering is the *alignment template* (`uniface.face_utils.reference_alignment`)+that recognition, quality scoring, and XSeg parsing all require.++!!! warning "BlazeFace uses a different layout"+ `BlazeFace` returns 6 keypoints — right eye, left eye, nose tip, mouth **center**,+ right ear tragion, left ear tragion — named from the subject's perspective, so rows+ 0/1 are still the viewer-left and viewer-right eye. With no mouth corners they+ cannot be fitted to the template above, which is why `BlazeFace.supports_alignment`+ is `False`.+### 106-Point LandmarksReturned by `Landmark106`:@@ -132,6 +142,26 @@ The 98-point output follows the standard [WFLW](https://wywu.github.io/projects/[300W / iBUG](https://ibug.doc.ic.ac.uk/resources/300-W/) layout. Coordinates are in original-imagepixel space, identical in convention to `Landmark106`.+### 468-Point Landmarks (Face Mesh)++`FaceMesh` is the only model in UniFace that returns **three** coordinates per point:++```python+from uniface import FaceMesh++results = FaceMesh().predict(image, faces)+results[0].landmarks # Shape: (468, 3)+```++| Axis | Meaning |+|------|---------|+| `x`, `y` | Original-image pixel coordinates, same convention as every other landmarker |+| `z` | **Relative** depth, on the same pixel scale as `x`/`y`. Smaller is closer to the camera |++`z` has no absolute origin — it is only meaningful *within* one face, for comparing which+features sit nearer the camera. It is not a distance measurement and is not comparable+between faces or between images. Use `results[0].points_2d` to drop it.+---## Face Cropdiff --git a/docs/concepts/inputs-outputs.md b/docs/concepts/inputs-outputs.mdindex 3b5acbb..8fad962 100644--- a/docs/concepts/inputs-outputs.md+++ b/docs/concepts/inputs-outputs.md@@ -28,6 +28,20 @@ print(f"Dtype: {image.dtype}") # uint8bgr_image = np.array(pil_image)[:, :, ::-1] # RGB → BGR```+!!! warning "Dtype"+ Images must be `uint8` in `[0, 255]`, three-channel. A float `[0, 1]` array or a+ grayscale frame raises `ValueError` rather than returning quietly wrong results:++ ```python+ detector.detect(image.astype(np.float32) / 255.0)+ # ValueError: Expected dtype uint8, got float32. Scale to [0, 255] and cast with .astype(np.uint8).++ detector.detect(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY))+ # ValueError: Expected a BGR image of shape (H, W, 3), got (480, 640). Convert with cv2.cvtColor.+ ```++ Normalization is each model's job — pass the raw `cv2.imread` array through.+---## Output: Face Dataclass@@ -43,7 +57,8 @@ class Face:# Required (from detection)bbox: np.ndarray # [x1, y1, x2, y2]confidence: float # 0.0 to 1.0- landmarks: np.ndarray # (5, 2) from detectors. Dense landmarkers return (106, 2), (98, 2), or (68, 2).+ landmarks: np.ndarray # (5, 2) from detectors — except BlazeFace, which returns (6, 2).+ # Dense landmarkers return (106, 2), (98, 2), (68, 2), (468, 3), or (478, 3).# Optional (enriched by analyzers)embedding: np.ndarray | None = None@@ -53,6 +68,12 @@ class Face:race: str | None = None # "East Asian", etc.emotion: str | None = None # "Happy", etc.emotion_confidence: float | None = None+ left_eye_open: float | None = None # [0, 1] probability, from FaceAttribNet+ right_eye_open: float | None = None # [0, 1] probability, from FaceAttribNet+ eyeglasses: float | None = None # [0, 1] probability, from FaceAttribNet+ mask: float | None = None # [0, 1] probability, from FaceAttribNet+ sunglasses: float | None = None # [0, 1] probability, from FaceAttribNet+ quality: float | None = None # [0, 1] quality score from eDifFIQAtrack_id: int | None = None # Persistent ID from tracker```@@ -77,6 +98,9 @@ similarity = face1.compute_similarity(face2)# Convert to dictionaryface_dict = face.to_dict()++# Convert to JSON string+face_json = face.to_json(indent=2)```---@@ -146,11 +170,11 @@ print(f"{label}: {result.confidence:.1%}")----### AttributeResult+### DemographyResult```python@dataclass(frozen=True)-class AttributeResult:+class DemographyResult:gender: int # 0=Female, 1=Maleage: int | None # Years (AgeGender model)age_group: str | None # "20-29" (FairFace model)@@ -186,6 +210,59 @@ class EmotionResult:---+### QualityResult++```python+@dataclass(frozen=True)+class QualityResult:+ score: float # 0.0 to 1.0, higher = better quality+```++---++### FaceStateResult++```python+@dataclass(frozen=True)+class FaceStateResult:+ left_eye_open: float # Probability the left eye is open+ right_eye_open: float # Probability the right eye is open+ eyeglasses: float # Probability eyeglasses are present+ mask: float # Probability a face mask is present+ sunglasses: float # Probability sunglasses are present+```++The five values come from independent binary heads: they do not sum to 1 and several can+be high at once. Threshold each attribute separately; never `argmax`.++**Usage:**++```python+result = face_attrib_net.predict(image, face)+print(result.as_dict()) # {'left_eye_open': 0.98, ...}+print(result.labels(0.5)) # ['left_eye_open', 'right_eye_open', 'eyeglasses']+```++---++### FaceMeshResult++```python+@dataclass(frozen=True)+class FaceMeshResult:+ landmarks: np.ndarray # (468, 3) or (478, 3); x, y in image pixels, z is relative depth+ score: float # Face presence, 0.0 to 1.0++ @property+ def points_2d(self) -> np.ndarray:+ return self.landmarks[:, :2] # (N, 2), depth dropped+```++`score` saturates near 1.0 for anything plausible. It confirms the model ran; it is not a+discriminative confidence, so do not threshold on it.++---+## EmbeddingsFace recognition models return normalized 512-dimensional embeddings:diff --git a/docs/concepts/model-cache-offline.md b/docs/concepts/model-cache-offline.mdindex 6519f3c..ec87f27 100644--- a/docs/concepts/model-cache-offline.md+++ b/docs/concepts/model-cache-offline.md@@ -18,6 +18,10 @@ detector = RetinaFace() # ~3.5 MB downloaddetector = RetinaFace() # Instant```+Weights come from GitHub Releases, with a [Hugging Face mirror](https://huggingface.co/yakhyo/uniface-weights)+as an automatic fallback when GitHub is unreachable. There is nothing to configure, and no+Hugging Face token is needed.+---## Cache Location@@ -152,14 +156,16 @@ detector = RetinaFace() # No network requiredModels are verified with SHA-256 checksums:```python-from uniface.constants import MODEL_SHA256, RetinaFaceWeights+from uniface.constants import MODEL_REGISTRY, RetinaFaceWeights# Check expected checksum-expected = MODEL_SHA256[RetinaFaceWeights.MNET_V2]+expected = MODEL_REGISTRY[RetinaFaceWeights.MNET_V2].sha256print(f"Expected SHA256: {expected}")```-If a model fails verification, it's re-downloaded automatically.+If a model fails verification, it's re-downloaded automatically. The same checksum is enforced+whichever source served the file, so a corrupted or stale mirror falls through to the other+source instead of being cached.---diff --git a/docs/concepts/overview.md b/docs/concepts/overview.mdindex 6fa15bc..d82b663 100644--- a/docs/concepts/overview.md+++ b/docs/concepts/overview.md@@ -94,11 +94,13 @@ ONNX Runtime is installed separately via the `uniface[cpu]` or `uniface[gpu]` exDirect class instantiation:```python-from uniface.detection import RetinaFace, SCRFD+from uniface.detection import CenterFace, RetinaFace, SCRFDdetector = RetinaFace()# ordetector = SCRFD()+# or+detector = CenterFace()```### 4. Type Safety@@ -116,11 +118,11 @@ def detect(self, image: np.ndarray) -> list[Face]:```uniface/-├── detection/ # Face detection (RetinaFace, SCRFD, YOLOv5Face, YOLOv8Face)+├── detection/ # Face detection (BlazeFace, CenterFace, RetinaFace, SCRFD, YOLOv5Face, YOLOv8Face)├── recognition/ # Face recognition (AdaFace, ArcFace, EdgeFace, MobileFace, SphereFace)├── tracking/ # Multi-object tracking (BYTETracker)-├── landmark/ # Dense landmarks (Landmark106 = 106 pts, PIPNet = 98 / 68 pts)-├── attribute/ # Age, gender, emotion, race+├── landmark/ # Dense landmarks (Landmark106 = 106 pts, PIPNet = 98 / 68 pts, FaceMesh = 468 / 478 pts)+├── attribute/ # Age, gender, emotion, race, face states├── parsing/ # Face semantic segmentation├── matting/ # Portrait matting (MODNet)├── gaze/ # Gaze estimation@@ -188,9 +190,9 @@ age_gender = AgeGender()fairface = FairFace()analyzer = FaceAnalyzer(- detector,+ detector=detector,recognizer=recognizer,- attributes=[age_gender, fairface],+ predictors=[age_gender, fairface],)faces = analyzer.analyze(image)@@ -203,7 +205,7 @@ for face in faces:## Model Lifecycle-1. **First use**: Model is downloaded from GitHub releases+1. **First use**: Model is downloaded from GitHub Releases, with a [Hugging Face mirror](https://huggingface.co/yakhyo/uniface-weights) as an automatic fallback when GitHub is unreachable2. **Cached**: Stored in `~/.uniface/models/` (configurable via `set_cache_dir()` or `UNIFACE_CACHE_DIR`)3. **Verified**: SHA-256 checksum validation4. **Loaded**: ONNX Runtime session createddiff --git a/docs/datasets.md b/docs/datasets.mdindex 3841566..45c43d3 100644--- a/docs/datasets.md+++ b/docs/datasets.md@@ -8,11 +8,14 @@ Overview of all training datasets and evaluation benchmarks used by UniFace mode| Task | Dataset | Scale | Models || ----------- | ------------------------------------------------ | ---------------------- | ------------------------------------------- |-| Detection | [WIDER FACE](#wider-face) | 32K images | RetinaFace, SCRFD, YOLOv5-Face, YOLOv8-Face |+| Detection | [WIDER FACE](#wider-face) | 32K images | RetinaFace, SCRFD, CenterFace, YOLOv5-Face, YOLOv8-Face |+| Detection | Proprietary (Google) | - | BlazeFace || Recognition | [MS1MV2](#ms1mv2) | 5.8M images, 85.7K IDs | MobileFace, SphereFace || Recognition | [WebFace600K](#webface600k) | 600K images | ArcFace |-| Recognition | [WebFace4M / WebFace12M](#webface4m--webface12m) | 4M / 12M images | AdaFace |-| Landmarks | [WFLW](#wflw) / [300W+CelebA](#300w--celeba) | 10K / 3.8K labeled + 202.6K unlabeled | PIPNet (98 / 68 pts) |+| Recognition | [WebFace4M / WebFace12M](#webface4m-webface12m) | 4M / 12M images | AdaFace, EdgeFace |+| Landmarks | [WFLW](#wflw) / [300W+CelebA](#300w-celeba) | 10K / 3.8K labeled + 202.6K unlabeled | PIPNet (98 / 68 pts) |+| Landmarks | Proprietary (Google) | - | Face Mesh (468 / 478 pts) |+| Attributes | Proprietary (Qualcomm) | - | FaceAttribNet || Gaze | [Gaze360](#gaze360) | 238 subjects | MobileGaze || Parsing | [CelebAMask-HQ](#celebamask-hq) | 30K images | BiSeNet || Attributes | [CelebA](#celeba) | 200K images | AgeGender |@@ -81,7 +84,7 @@ Medium-scale face recognition dataset from the WebFace series.#### WebFace4M / WebFace12M-Large-scale face recognition datasets from the WebFace260M collection. Used for training AdaFace models with adaptive quality-aware margin.+Large-scale face recognition datasets from the WebFace260M collection. Used for training AdaFace models with adaptive quality-aware margin, and EdgeFace models for edge devices.| Property | WebFace4M | WebFace12M || -------- | ------------- | -------------- |diff --git a/docs/index.md b/docs/index.mdindex ca0b362..91ce5c1 100644--- a/docs/index.md+++ b/docs/index.md@@ -26,7 +26,7 @@ template: home.html<div class="feature-card" markdown>### :material-face-recognition: Face Detection-RetinaFace, SCRFD, and YOLO detectors with 5-point landmarks.+RetinaFace, SCRFD, CenterFace, and YOLO detectors with 5-point landmarks, plus BlazeFace for short-range MediaPipe parity.<a class="feature-card-link" href="modules/detection/" aria-label="Face Detection"></a></div>@@ -38,22 +38,28 @@ AdaFace, ArcFace, EdgeFace, MobileFace, and SphereFace embeddings for identity v<div class="feature-card" markdown>### :material-map-marker: Landmarks-Dense facial landmark localization — 106-point (2d106det) and 98 / 68-point (PIPNet) variants.+Dense facial landmark localization — 106-point (2d106det), 98 / 68-point (PIPNet), and 468/478-point 3D mesh (Face Mesh, the 478 variant adding irises) variants.<a class="feature-card-link" href="modules/landmarks/" aria-label="Landmarks"></a></div><div class="feature-card" markdown>### :material-account-details: Attributes-Age, gender, race (FairFace), and emotion detection from faces.+Age, gender, race (FairFace), emotion, and face states (FaceAttribNet) from faces.<a class="feature-card-link" href="modules/attributes/" aria-label="Attributes"></a></div><div class="feature-card" markdown>### :material-face-man-shimmer: Face Parsing-BiSeNet semantic segmentation with 19 facial component classes.+BiSeNet semantic segmentation with 19 facial component classes, plus XSeg face masking.<a class="feature-card-link" href="modules/parsing/" aria-label="Face Parsing"></a></div>+<div class="feature-card" markdown>+### :material-image-off: Portrait Matting+Trimap-free alpha matte with MODNet for background removal and compositing.+<a class="feature-card-link" href="modules/matting/" aria-label="Portrait Matting"></a>+</div>+<div class="feature-card" markdown>### :material-eye: Gaze EstimationReal-time gaze direction prediction with MobileGaze models.diff --git a/docs/installation.md b/docs/installation.mdindex ed24379..85e3db4 100644--- a/docs/installation.md+++ b/docs/installation.md@@ -6,7 +6,7 @@ This guide covers all installation options for UniFace.## Requirements-- **Python**: 3.10 or higher+- **Python**: 3.10 – 3.14- **Operating Systems**: macOS, Linux, Windows---@@ -200,7 +200,7 @@ pip install uniface[gpu] # install the one you want## Pre-release Versions-UniFace ships release candidates and betas to PyPI ahead of stable releases (versions like `0.7.0rc1`, `0.7.0b1`, `0.7.0a1`). These let you try upcoming features before they're finalized.+UniFace ships release candidates and betas to PyPI ahead of stable releases (versions like `4.0.0rc1`, `4.0.0b1`, `4.0.0a1`). These let you try upcoming features before they're finalized.`pip install uniface` always installs the latest **stable** release. To opt in to pre-releases:@@ -209,7 +209,7 @@ UniFace ships release candidates and betas to PyPI ahead of stable releases (verpip install uniface[cpu] --pre# A specific pre-release-pip install uniface[cpu]==0.7.0rc1+pip install uniface[cpu]==4.0.0rc1```Pre-releases are not recommended for production — APIs may still change before the stable release.diff --git a/docs/license-attribution.md b/docs/license-attribution.mdindex ed8e39f..24e3bc4 100644--- a/docs/license-attribution.md+++ b/docs/license-attribution.md@@ -12,6 +12,8 @@ UniFace is released under the [MIT License](https://opensource.org/licenses/MIT)|-------|--------|---------|| RetinaFace | [yakhyo/retinaface-pytorch](https://github.com/yakhyo/retinaface-pytorch) | MIT || SCRFD | [InsightFace](https://github.com/deepinsight/insightface) | MIT |+| CenterFace | [Star-Clouds/CenterFace](https://github.com/Star-Clouds/CenterFace) | MIT |+| BlazeFace | [yakhyo/mediapipe-face-mesh-onnx](https://github.com/yakhyo/mediapipe-face-mesh-onnx) — architecture & weights from Google [MediaPipe](https://github.com/google-ai-edge/mediapipe) | Apache-2.0 || YOLOv5-Face | [yakhyo/yolov5-face-onnx-inference](https://github.com/yakhyo/yolov5-face-onnx-inference) | GPL-3.0 || YOLOv8-Face | [yakhyo/yolov8-face-onnx-inference](https://github.com/yakhyo/yolov8-face-onnx-inference) | GPL-3.0 || AdaFace | [yakhyo/adaface-onnx](https://github.com/yakhyo/adaface-onnx) | MIT |@@ -23,4 +25,6 @@ UniFace is released under the [MIT License](https://opensource.org/licenses/MIT)| MODNet | [yakhyo/modnet](https://github.com/yakhyo/modnet) | Apache-2.0 || MiniFASNet | [yakhyo/face-anti-spoofing](https://github.com/yakhyo/face-anti-spoofing) | Apache-2.0 || FairFace | [yakhyo/fairface-onnx](https://github.com/yakhyo/fairface-onnx) | CC BY 4.0 |+| FaceAttribNet | [yakhyo/face-attribute](https://github.com/yakhyo/face-attribute) — architecture & weights © Qualcomm Technologies, Inc. ([qualcomm/ai-hub-models](https://github.com/qualcomm/ai-hub-models)) | BSD-3-Clause || PIPNet | [yakhyo/pipnet-onnx](https://github.com/yakhyo/pipnet-onnx) — meanface tables vendored from [jhb86253817/PIPNet](https://github.com/jhb86253817/PIPNet) | MIT |+| Face Mesh | [yakhyo/mediapipe-face-mesh-onnx](https://github.com/yakhyo/mediapipe-face-mesh-onnx) — topology & weights from Google [MediaPipe](https://github.com/google-ai-edge/mediapipe), sourced via [PINTO0309's ONNX conversion](https://github.com/PINTO0309/facemesh_onnx_tensorrt); tessellation tables vendored from the same source | Apache-2.0 |diff --git a/docs/models.md b/docs/models.mdindex 6350360..82ad0f3 100644--- a/docs/models.md+++ b/docs/models.md@@ -47,6 +47,55 @@ SCRFD (Sample and Computation Redistribution for Efficient Face Detection) model---+### CenterFace++CenterFace is an anchor-free detector (MobileNetV2 + FPN) that treats faces as center points, with joint 5-point landmark prediction. Trained on [WIDER FACE](datasets.md#wider-face) dataset.++| Model Name | Size | Easy | Medium | Hard |+| ---------- | ----- | ------ | ------ | ------ |+| `DEFAULT` :material-check-circle: | 7.0MB | 92.2%* | 91.1%* | 78.2%* |++*\* Single inference on the original image (SIO). With multi-scale and flip testing the+[original repo](https://github.com/Star-Clouds/CenterFace) reports 93.5% / 92.4% / 87.5%.*++!!! info "Accuracy & Benchmarks"+ **Accuracy**: WIDER FACE validation set - from [CenterFace paper](https://arxiv.org/abs/1911.03599)++ **Speed**: Benchmark on your own hardware using `python tools/detect.py --source <image> --method centerface`++!!! note "Input Size"+ Input width and height must be multiples of 32 (default 640×640). The ONNX model+ supports dynamic batch and spatial dimensions.++---++### BlazeFace++Google MediaPipe's short-range SSD detector — the one `mp.solutions.face_mesh` runs+internally. Pairing it with [Face Mesh](#face-mesh-468-or-478-points) reproduces MediaPipe's own output.++| Model Name | Input | Keypoints | Size |+| ---------- | ----- | --------- | ---- |+| `DEFAULT` :material-check-circle: | 128×128 | 6 | 0.5MB |++!!! warning "Not for recognition pipelines"+ BlazeFace emits 6 MediaPipe keypoints (right eye, left eye, nose tip, mouth **center**,+ right/left ear tragion), not the 5-point alignment template. With no mouth corners they+ cannot drive face alignment, so `supports_alignment` is `False` and `FaceAnalyzer`+ disables recognition for it.++!!! note "Short range"+ Tuned for faces within roughly 2m. Not benchmarked on WIDER FACE, and less accurate+ than SCRFD or YOLOv8 on small or distant faces. Choose it for its 0.5MB footprint or+ for MediaPipe parity.++!!! info "Reference"+ **Paper**: [BlazeFace: Sub-millisecond Neural Face Detection on Mobile GPUs](https://arxiv.org/abs/1907.05047)++ **Source**: [yakhyo/mediapipe-face-mesh-onnx](https://github.com/yakhyo/mediapipe-face-mesh-onnx) — ONNX export of Google [MediaPipe](https://github.com/google-ai-edge/mediapipe)++---+### YOLOv5-Face FamilyYOLOv5-Face models provide detection with 5-point facial landmarks, trained on [WIDER FACE](datasets.md#wider-face) dataset.@@ -98,7 +147,7 @@ Face recognition using adaptive margin based on image quality.| `IR_101` | IR-101 | WebFace12M | 249 MB | - | 97.66% |!!! info "Training Data & Accuracy"- **Dataset**: [WebFace4M / WebFace12M](datasets.md#webface4m--webface12m) (4M / 12M images)+ **Dataset**: [WebFace4M / WebFace12M](datasets.md#webface4m-webface12m) (4M / 12M images)**Accuracy**: IJB-B and IJB-C benchmarks, TAR@FAR=0.01%@@ -187,7 +236,7 @@ Facial landmark localization model.| Model Name | Points | Params | Size || ---------- | ------ | ------ | ---- |-| `2D106` | 106 | 3.7M | 14MB |+| `DEFAULT` (2d_106) | 106 | 3.7M | 14MB |**Landmark Groups:**@@ -221,13 +270,40 @@ PIPNet (Pixel-in-Pixel Net) facial landmark detector. ResNet-18 backbone, 256×2---+### Face Mesh (468 or 478 points)++Google MediaPipe's dense mesh. The only UniFace landmarker that returns 3D points and a+face-presence score, and the only model that batches every face of an image into one+inference call.++| Model Name | Points | Input | Size |+| ---------- | ------ | ----- | ---- |+| `V1_468` :material-check-circle: | 468 (3D) | 192×192 | 2.4MB |+| `V2_478` | 478 (3D, with irises) | 256×256 | 4.6MB |++!!! info "Reference"+ **Paper**: [Real-time Facial Surface Geometry from Monocular Video on Mobile GPUs](https://arxiv.org/abs/1907.06724)++ **Source**: [yakhyo/mediapipe-face-mesh-onnx](https://github.com/yakhyo/mediapipe-face-mesh-onnx) — architectures recovered from Google [MediaPipe](https://github.com/google-ai-edge/mediapipe). `V1_468`'s weights came via [PINTO0309's conversion](https://github.com/PINTO0309/facemesh_onnx_tensorrt); `V2_478`'s were read directly from the `.tflite` in Google's `face_landmarker.task` bundle++!!! note "Works with any detector"+ Face Mesh needs a bounding box plus the first two landmarks (the eyes) to align its+ crop. Rows 0/1 are the viewer-left and viewer-right eye in both the 5-point template+ and BlazeFace's 6-point layout, so every UniFace detector can seed it.++!!! note "Relative depth"+ The `z` coordinate is relative depth on the same pixel scale as `x`/`y` (smaller is+ closer). It has no absolute origin and is not comparable between faces or images.++---+## Attribute Analysis Models### Age & Gender Detection| Model Name | Attributes | Params | Size || ----------- | ----------- | ------ | ---- |-| `AgeGender` | Age, Gender | 2.1M | 8MB |+| `DEFAULT` | Age, Gender | 2.1M | 8MB |!!! info "Training Data"**Dataset**: Trained on [CelebA](datasets.md#celeba)@@ -241,7 +317,7 @@ PIPNet (Pixel-in-Pixel Net) facial landmark detector. ResNet-18 backbone, 256×2| Model Name | Attributes | Params | Size || ----------- | --------------------- | ------ | ----- |-| `FairFace` | Race, Gender, Age Group | - | 44MB |+| `DEFAULT` | Race, Gender, Age Group | - | 44MB |!!! info "Training Data"**Dataset**: Trained on [FairFace](datasets.md#fairface) dataset with balanced demographics@@ -274,6 +350,23 @@ PIPNet (Pixel-in-Pixel Net) facial landmark detector. ResNet-18 backbone, 256×2---+### Face State Detection (FaceAttribNet)++| Model Name | Attributes | Params | Size |+| --------------- | ------------------------------------------------------- | ------ | ---- |+| `DEFAULT` | Eye openness (L/R), Eyeglasses, Mask, Sunglasses | 10.8M | 41MB |++Qualcomm's [Facial-Attribute-Detection](https://github.com/qualcomm/ai-hub-models/tree/main/src/qai_hub_models/models/face_attrib_net) model. Outputs five independent binary probabilities from a 128x128 face crop.++!!! info "Training Data"+ **Dataset**: Trained by Qualcomm on a proprietary face dataset++!!! warning "Multi-label Output"+ The five probabilities come from independent binary heads: they do not sum to 1+ and several can be high at once. Threshold each attribute separately; never `argmax`.++---+## Gaze Estimation Models### MobileGaze Family@@ -470,9 +563,10 @@ Face image quality assessment. Predicts a single scalar score from an aligned 11Models are automatically downloaded and cached on first use.+- **Sources**: GitHub Releases, falling back automatically to a [Hugging Face mirror](https://huggingface.co/yakhyo/uniface-weights) when GitHub is unreachable- **Cache location**: `~/.uniface/models/` (configurable via `set_cache_dir()` or `UNIFACE_CACHE_DIR` env var)- **Inspect cache path**: `get_cache_dir()` returns the resolved active path-- **Verification**: Models are verified with SHA-256 checksums+- **Verification**: Models are verified with SHA-256 checksums, whichever source served them- **Concurrent download**: `download_models([...])` fetches multiple models in parallel- **Manual download**: Use `python tools/download_model.py` to pre-download models@@ -500,6 +594,7 @@ See [Model Cache & Offline Use](concepts/model-cache-offline.md) for full detail- **Face Anti-Spoofing**: [yakhyo/face-anti-spoofing](https://github.com/yakhyo/face-anti-spoofing) - MiniFASNet ONNX inference (weights from [minivision-ai/Silent-Face-Anti-Spoofing](https://github.com/minivision-ai/Silent-Face-Anti-Spoofing))- **Face Image Quality Assessment**: [yakhyo/face-image-quality-assessment](https://github.com/yakhyo/face-image-quality-assessment) - eDifFIQA PyTorch inference, ONNX export and inference- **FairFace**: [yakhyo/fairface-onnx](https://github.com/yakhyo/fairface-onnx) - FairFace ONNX inference for race, gender, age prediction+- **FaceAttribNet**: [yakhyo/face-attribute](https://github.com/yakhyo/face-attribute) - FaceAttribNet ONNX export and inference (weights from [qualcomm/ai-hub-models](https://github.com/qualcomm/ai-hub-models/tree/main/src/qai_hub_models/models/face_attrib_net))- **PIPNet**: [yakhyo/pipnet-onnx](https://github.com/yakhyo/pipnet-onnx) - PIPNet ONNX export and inference (from [jhb86253817/PIPNet](https://github.com/jhb86253817/PIPNet))- **InsightFace**: [deepinsight/insightface](https://github.com/deepinsight/insightface) - Model architectures and pretrained weightsdiff --git a/docs/modules/attributes.md b/docs/modules/attributes.mdindex 9920c27..ca9a2b8 100644--- a/docs/modules/attributes.md+++ b/docs/modules/attributes.md@@ -1,6 +1,6 @@# Attributes-Facial attribute analysis for age, gender, race, and emotion detection.+Facial attribute analysis for age, gender, race, emotion, and face state detection (eye openness, glasses, mask).<figure markdown="span">{ width="100%" }@@ -16,6 +16,7 @@ Facial attribute analysis for age, gender, race, and emotion detection.| **AgeGender** | Age, Gender | 8 MB | Exact age prediction || **FairFace** | Gender, Age Group, Race | 44 MB | Balanced demographics || **Emotion** | 7-8 emotions | 2 MB | Requires PyTorch |+| **FaceAttribNet** | Eye openness, Eyeglasses, Mask, Sunglasses | 41 MB | Multi-label (independent probabilities) |---@@ -44,7 +45,7 @@ for face in faces:### Output```python-# AttributeResult fields+# DemographyResult fieldsresult.gender # 0=Female, 1=Maleresult.sex # "Female" or "Male" (property)result.age # int, age in years@@ -80,7 +81,7 @@ for face in faces:### Output```python-# AttributeResult fields+# DemographyResult fieldsresult.gender # 0=Female, 1=Maleresult.sex # "Female" or "Male"result.age # None (not provided by this model)@@ -131,10 +132,10 @@ Predicts facial emotions. Requires PyTorch.```pythonfrom uniface.detection import RetinaFacefrom uniface.attribute import Emotion-from uniface.constants import DDAMFNWeights+from uniface.constants import EmotionWeightsdetector = RetinaFace()-emotion = Emotion(model_name=DDAMFNWeights.AFFECNET7)+emotion = Emotion(model_name=EmotionWeights.AFFECNET7)faces = detector.detect(image)@@ -175,13 +176,62 @@ for face in faces:```pythonfrom uniface.attribute import Emotion-from uniface.constants import DDAMFNWeights+from uniface.constants import EmotionWeights# 7-class emotion-emotion = Emotion(model_name=DDAMFNWeights.AFFECNET7)+emotion = Emotion(model_name=EmotionWeights.AFFECNET7)# 8-class emotion-emotion = Emotion(model_name=DDAMFNWeights.AFFECNET8)+emotion = Emotion(model_name=EmotionWeights.AFFECNET8)+```++---++## FaceAttribNet++Predicts five independent binary face states from a face crop: left/right eye openness, eyeglasses, face mask, and sunglasses. Based on Qualcomm's [Facial-Attribute-Detection](https://github.com/qualcomm/ai-hub-models/tree/main/src/qai_hub_models/models/face_attrib_net) model.++<figure markdown="span">+ { width="100%" }+ <figcaption>Face state prediction: per-attribute True/False with probabilities</figcaption>+</figure>++!!! warning "Multi-label output"+ The five values come from independent binary heads: they do not sum to 1 and+ several can be high at once (a face can wear both sunglasses and a mask).+ Threshold each attribute separately; never `argmax`.++### Basic Usage++```python+from uniface.attribute import FaceAttribNet+from uniface.detection import RetinaFace++detector = RetinaFace()+face_attrib = FaceAttribNet()++faces = detector.detect(image)++for face in faces:+ result = face_attrib.predict(image, face)+ print(result.as_dict()) # {'left_eye_open': 0.99, 'right_eye_open': 0.98, ...}+ print(result.labels(threshold=0.5)) # e.g. ['left_eye_open', 'right_eye_open', 'eyeglasses']+ # face.left_eye_open, face.right_eye_open, face.eyeglasses,+ # face.mask, face.sunglasses are also set automatically+```++### Output++```python+# FaceStateResult fields (all probabilities in [0, 1])+result.left_eye_open # Probability the left eye is open+result.right_eye_open # Probability the right eye is open+result.eyeglasses # Probability eyeglasses are present+result.mask # Probability a face mask is present+result.sunglasses # Probability sunglasses are present++result.as_dict() # name -> probability mapping+result.labels(threshold) # names of attributes above the threshold```---@@ -189,11 +239,12 @@ emotion = Emotion(model_name=DDAMFNWeights.AFFECNET8)## Available Attribute Models```python-from uniface.attribute import AgeGender, Emotion, FairFace+from uniface.attribute import AgeGender, Emotion, FaceAttribNet, FairFaceage_gender = AgeGender()fairface = FairFace()emotion = Emotion() # requires the optional `torch` dependency+face_attrib = FaceAttribNet()```---@@ -233,8 +284,8 @@ from uniface.attribute import AgeGenderfrom uniface.detection import RetinaFaceanalyzer = FaceAnalyzer(- RetinaFace(),- attributes=[AgeGender()],+ detector=RetinaFace(),+ predictors=[AgeGender()],)faces = analyzer.analyze(image)@@ -290,6 +341,7 @@ cv2.imwrite("attributes.jpg", image)- **AgeGender**: Trained on CelebA; accuracy varies by demographic- **FairFace**: Trained for balanced demographics; better cross-racial accuracy- **Emotion**: Accuracy depends on facial expression clarity+ - **FaceAttribNet**: Trained by Qualcomm on a proprietary dataset; tinted eyeglasses may register as sunglassesAlways test on your specific use case and consider cultural context.diff --git a/docs/modules/detection.md b/docs/modules/detection.mdindex 4a089d2..19dbdc1 100644--- a/docs/modules/detection.md+++ b/docs/modules/detection.md@@ -1,6 +1,6 @@# Detection-Face detection is the first step in any face analysis pipeline. UniFace provides four detection models.+Face detection is the first step in any face analysis pipeline. UniFace provides six detection models.<figure markdown="span">{ width="100%" }@@ -15,11 +15,36 @@ Face detection is the first step in any face analysis pipeline. UniFace provides|-------|----------|------|------|--------|------|:---------:|| **RetinaFace** | MobileNet V2 | 3.5 MB | 91.7% | 91.0% | 86.6% | :material-check: || **SCRFD** | SCRFD-10G | 17 MB | 95.2% | 93.9% | 83.1% | :material-check: |+| **CenterFace** | MobileNet V2 | 7.0 MB | 92.2% | 91.1% | 78.2% | :material-check: || **YOLOv5-Face** | YOLOv5s | 28 MB | 94.3% | 92.6% | 83.2% | :material-check: || **YOLOv8-Face** | YOLOv8n | 12 MB | 94.6% | 92.3% | 79.6% | :material-check: |+| **BlazeFace** | BlazeFace (short-range) | 0.5 MB | — | — | — | 6-point |!!! note "Dataset"- All models trained on WIDERFACE dataset.+ All models except BlazeFace are trained on the WIDERFACE dataset and benchmarked against it.+ BlazeFace comes from Google MediaPipe and is not benchmarked on WIDERFACE.++!!! warning "BlazeFace landmarks are not alignment landmarks"+ Every other detector returns the 5-point alignment template — left eye, right eye,+ nose, left mouth corner, right mouth corner — which+ [recognition](recognition.md), [quality](quality.md), and XSeg+ [parsing](parsing.md) all consume.++ BlazeFace returns **6** MediaPipe keypoints whose fourth point is a mouth+ *center*, not corners, so they cannot be fitted to that template. It leaves+ `supports_alignment = False`, and `FaceAnalyzer` disables recognition+ with a warning rather than producing broken embeddings.++ ```python+ detector.supports_alignment # False for BlazeFace, True for every other detector+ detector.supports_landmarks # True for every built-in detector+ ```++ `supports_landmarks` answers the earlier question: does the detector fill+ `Face.landmarks` at all? Every built-in detector does. Both flags are opt-in on+ `BaseDetector`, so a custom boxes-only detector reports `False` for both without+ declaring anything — see [Custom Models](../recipes/custom-models.md).+---## RetinaFace@@ -129,6 +154,55 @@ detector = SCRFD(---+## CenterFace++Anchor-free detection that treats faces as center points (MobileNetV2 + FPN), with joint 5-point landmark prediction. Lightweight and fast on CPU.++Paper: [CenterFace: Joint Face Detection and Alignment Using Face as Point](https://arxiv.org/abs/1911.03599)++### Basic Usage++```python+from uniface.detection import CenterFace++detector = CenterFace()+faces = detector.detect(image)+```++| Variant | Size | Easy | Medium | Hard |+|---------|------|------|--------|------|+| **DEFAULT** :material-check-circle: | 7.0 MB | 92.2% | 91.1% | 78.2% |++!!! note "Benchmark schema"+ Scores are WIDER FACE val with single inference on the original image (SIO).+ With multi-scale and flip testing the [original repo](https://github.com/Star-Clouds/CenterFace)+ reports 93.5% / 92.4% / 87.5%.++!!! warning "Limitations"+ - **Landmark precision**: landmarks are decoded from a single coarse feature-map cell+ per face, so they are less precise than SCRFD or RetinaFace (roughly 5% of box size+ deviation on upright faces). For alignment-critical recognition, prefer SCRFD/RetinaFace,+ or refine with [PIPNet / Landmark106](landmarks.md) on CenterFace boxes.+ - **Rotated faces**: detection recall and landmark accuracy drop faster than SCRFD as+ in-plane rotation increases (noticeable beyond ~20-30 degrees). Best suited for+ roughly upright faces (webcams, portraits, surveillance).++### Configuration++```python+from uniface.constants import CenterFaceWeights++detector = CenterFace(+ model_name=CenterFaceWeights.DEFAULT,+ confidence_threshold=0.35,+ nms_threshold=0.3,+ input_size=(640, 640), # width and height must be multiples of 32+ providers=None, # Auto-detect, or ['CPUExecutionProvider']+)+```++---+## YOLOv5-FaceYOLO-based detection optimized for faces.@@ -229,20 +303,67 @@ detector = YOLOv8Face(---+## BlazeFace++Google MediaPipe's short-range SSD detector — the one `mp.solutions.face_mesh` runs+internally. Pair it with [FaceMesh](landmarks.md#face-mesh-468-or-478-points-3d) to reproduce MediaPipe's+own output exactly.++At 0.5 MB it is by far the smallest detector here, but it is tuned for faces within+roughly 2 m and is less accurate than SCRFD or YOLOv8 on small or distant faces.+Choose it for its footprint or for MediaPipe parity — not as a general-purpose detector.++### Basic Usage++```python+from uniface.detection import BlazeFace++detector = BlazeFace()+faces = detector.detect(image)++for face in faces:+ print(f"Confidence: {face.confidence:.2f}")+ print(f"Keypoints: {face.landmarks.shape}") # (6, 2), not (5, 2)+```++### Keypoint Layout++```python+# [right_eye, left_eye, nose_tip, mouth_center, right_ear, left_ear]+# Named from the subject's perspective, so rows 0/1 are the viewer-left+# and viewer-right eye — the same geometric order the 5-point template uses.+```++### Configuration++```python+detector = BlazeFace(+ confidence_threshold=0.5,+ nms_threshold=0.3, # MediaPipe blends overlapping boxes rather than dropping them+ providers=None, # Auto-detect, or ['CPUExecutionProvider']+)+```++---+## Available DetectorsImport the detector class you need:```python-from uniface.detection import RetinaFace, SCRFD, YOLOv5Face, YOLOv8Face+from uniface.detection import BlazeFace, CenterFace, RetinaFace, SCRFD, YOLOv5Face, YOLOv8Facedetector = RetinaFace()# ordetector = SCRFD()# or+detector = CenterFace()+# ordetector = YOLOv5Face()# ordetector = YOLOv8Face()+# or+detector = BlazeFace() # 6 keypoints; supports_alignment is False```---@@ -259,9 +380,11 @@ for face in faces:# Detection confidence (0-1)confidence = face.confidence- # 5-point landmarks (5, 2)+ # Landmarks (K, 2)landmarks = face.landmarks- # [left_eye, right_eye, nose, left_mouth, right_mouth]+ # K == 5 for every detector except BlazeFace:+ # [left_eye, right_eye, nose, left_mouth, right_mouth]+ # BlazeFace returns K == 6 in MediaPipe's own order; see the warning above.```---diff --git a/docs/modules/headpose.md b/docs/modules/headpose.mdindex 53f4145..47604c7 100644--- a/docs/modules/headpose.md+++ b/docs/modules/headpose.md@@ -139,10 +139,10 @@ draw_head_pose(image, face.bbox, result.pitch, result.yaw, result.roll, draw_typfrom uniface.draw import draw_head_pose_cube, draw_head_pose_axis# Draw cube directly-draw_head_pose_cube(image, yaw=10.0, pitch=-5.0, roll=2.0, bbox=[100, 100, 250, 280])+draw_head_pose_cube(image, [100, 100, 250, 280], pitch=-5.0, yaw=10.0, roll=2.0)# Draw axes directly-draw_head_pose_axis(image, yaw=10.0, pitch=-5.0, roll=2.0, bbox=[100, 100, 250, 280])+draw_head_pose_axis(image, [100, 100, 250, 280], pitch=-5.0, yaw=10.0, roll=2.0)```---diff --git a/docs/modules/landmarks.md b/docs/modules/landmarks.mdindex c6e6a96..b8b9903 100644--- a/docs/modules/landmarks.md+++ b/docs/modules/landmarks.md@@ -17,9 +17,12 @@ Facial landmark detection provides precise localization of facial features.| **Landmark106** | 106 | 14 MB || **PIPNet (WFLW-98)** | 98 | 47 MB || **PIPNet (300W+CelebA-68)** | 68 | 46 MB |+| **FaceMesh** (`V1_468`) | 468 (3D) | 2.4 MB |+| **FaceMesh** (`V2_478`) | 478 (3D, with irises) | 4.6 MB |!!! info "5-Point Landmarks"- Basic 5-point landmarks are included with all detection models (RetinaFace, SCRFD, YOLOv5-Face, YOLOv8-Face).+ Basic 5-point landmarks are included with all detection models (RetinaFace, SCRFD, CenterFace, YOLOv5-Face, YOLOv8-Face).+ BlazeFace is the exception — it returns 6 MediaPipe keypoints instead; see [Detection](detection.md#blazeface).---@@ -124,9 +127,123 @@ print(landmarks.shape) # (68, 2)---+## Face Mesh (468 or 478 points, 3D)++Google MediaPipe's dense mesh. Unlike the other landmarkers it returns **3D** points+and a face-presence score, and it processes every face in an image in a single batched+inference call.++### Basic Usage++Works with any detector — it needs a bounding box, plus the first two landmarks (the+eyes) to align the crop:++```python+from uniface import SCRFD, FaceMesh++detector, mesher = SCRFD(), FaceMesh()++faces = detector.detect(image)+results = mesher.predict(image, faces) # one batched call for all faces++results[0].landmarks.shape # (468, 3) — x, y in image pixels; z is relative depth+results[0].points_2d.shape # (468, 2) — depth dropped+results[0].score # face presence, [0, 1]+```++Without a detector, pass boxes directly:++```python+results = mesher.predict(image, bboxes=[[x1, y1, x2, y2]])+```++### Iris landmarks++`V2_478` is MediaPipe's Face Landmarker: the same 468 mesh points in the same order,+plus ten iris points. Everything else — the detector, the ROI, the drawing edges — is+unchanged, so switching is a one-word change.++Following MediaPipe, the result stays a flat array and region membership lives in+named constants:++```python+from uniface import SCRFD, FaceMesh+from uniface.constants import FaceMeshWeights+from uniface.landmark import IRIS_LEFT, IRIS_RIGHT, NUM_MESH_LANDMARKS++mesher = FaceMesh(model_name=FaceMeshWeights.V2_478)+result = mesher.predict(image, SCRFD().detect(image))[0]++result.landmarks.shape # (478, 3)+result.landmarks[:NUM_MESH_LANDMARKS] # the 468 mesh points, as V1_468 returns them+result.landmarks[IRIS_LEFT] # (5, 3) — center, right, top, left, bottom+result.landmarks[IRIS_RIGHT] # (5, 3)++left_pupil = result.landmarks[IRIS_LEFT][0, :2]+```++Each iris is ordered center-first, so the mean distance from point 0 to the other four+gives the iris radius. A human iris is close to 11.7 mm across regardless of the+person, which makes that radius usable as a scale reference for real-world distance.++`V2_478` runs at 256×256 against `V1_468`'s 192×192 — 113 against 35 MMac. The+wall-clock gap is narrower than that ratio since neither model saturates a modern CPU,+so benchmark your own target. It is an addition, not a replacement: stay on `V1_468`+unless you need the irises.++### Drop-in Use++`FaceMesh` implements the same interface as `Landmark106` and `PIPNet`, so it can be+swapped into existing code that expects 2D points:++```python+landmarks = mesher.get_landmarks(image, face.bbox) # (478, 2) for the V2_478 mesher above+```++### MediaPipe Parity++Seeding the mesh with [BlazeFace](detection.md#blazeface) — the detector MediaPipe uses+internally — reproduces MediaPipe's own output:++```python+from uniface import BlazeFace, FaceMesh++detector, mesher = BlazeFace(), FaceMesh()+results = mesher.predict(image, detector.detect(image))+```++### Visualization++```python+from uniface.draw import draw_mesh++draw_mesh(image, results[0].landmarks) # 'partial': contours + points+draw_mesh(image, results[0].landmarks, mode='full') # dense 2556-edge tessellation+draw_mesh(image, results[0].landmarks, mode='points') # points only+```++!!! tip "Use `partial` or `points` for video"+ `mode='full'` issues 2556 line draws per face. It is the most detailed view but+ noticeably slower — prefer the other two for real-time work.++### Notes++- The crop follows MediaPipe's ROI rule: a square region at 1.5× the detector box,+ rotated so the eye line is horizontal. Tune it with `margin=` if the mesh clips.+- Passing `Face` objects roll-normalizes the crop automatically. With bare `bboxes`+ the crop is axis-aligned, which degrades the mesh on tilted heads.+- `roi_from_box` and `warp_roi` are public, so you can build MediaPipe's video-mode+ ROI tracking (ROI from the previous frame's mesh) on top of the model.+- `score` saturates near 1.0 for anything plausible. It confirms the model ran; it is+ not a discriminative confidence, so do not threshold on it.++---+## 5-Point Landmarks (Detection)-All detection models provide 5-point landmarks:+All detection models except BlazeFace provide 5-point landmarks. BlazeFace returns 6+MediaPipe keypoints instead, so its `supports_alignment` is `False`; see+[Detection](detection.md#blazeface).```pythonfrom uniface.detection import RetinaFace@@ -287,8 +404,8 @@ def estimate_head_pose(landmarks, image_shape):## Available Landmarkers```python-from uniface.constants import PIPNetWeights-from uniface.landmark import Landmark106, PIPNet+from uniface.constants import FaceMeshWeights, PIPNetWeights+from uniface.landmark import FaceMesh, Landmark106, PIPNet# Default: 106-point InsightFace modellandmarker = Landmark106()@@ -298,6 +415,12 @@ landmarker = PIPNet()# 68-point PIPNet (300W+CelebA)landmarker = PIPNet(model_name=PIPNetWeights.DW300_CELEBA_68)++# 468-point dense 3D mesh (MediaPipe Face Mesh)+landmarker = FaceMesh()++# 478-point dense 3D mesh with irises (MediaPipe Face Landmarker)+landmarker = FaceMesh(model_name=FaceMeshWeights.V2_478)```---diff --git a/docs/modules/privacy.md b/docs/modules/privacy.mdindex b4a52ae..92e29e5 100644--- a/docs/modules/privacy.md+++ b/docs/modules/privacy.md@@ -91,6 +91,15 @@ blurrer = BlurFace(method='elliptical', blur_strength=3.0, margin=20)| `blur_strength` | 3.0 | Blur intensity || `margin` | 20 | Margin around face |+The elliptical blur is also available as a standalone class for direct use on bounding boxes:++```python+from uniface.privacy import EllipticalBlur++blur = EllipticalBlur(blur_strength=3.0, margin=20)+result = blur(image, bboxes=[face.bbox for face in faces])+```+### MedianEdge-preserving blur with artistic effect:diff --git a/docs/notebooks.md b/docs/notebooks.mdindex 31e450d..ca25f21 100644--- a/docs/notebooks.md+++ b/docs/notebooks.md@@ -21,6 +21,8 @@ Run UniFace examples directly in your browser with Google Colab, or download and| [Head Pose Estimation](https://github.com/yakhyo/uniface/blob/main/examples/11_head_pose_estimation.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/11_head_pose_estimation.ipynb) | 3D head orientation estimation || [Face Recognition](https://github.com/yakhyo/uniface/blob/main/examples/12_face_recognition.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/12_face_recognition.ipynb) | Standalone face recognition pipeline || [Portrait Matting](https://github.com/yakhyo/uniface/blob/main/examples/13_portrait_matting.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/13_portrait_matting.ipynb) | Portrait matting with MODNet |+| [Face Attributes](https://github.com/yakhyo/uniface/blob/main/examples/14_face_attributes.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/14_face_attributes.ipynb) | Face states (eyes, glasses, sunglasses, mask) |+| [Face Mesh](https://github.com/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb) | [](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb) | 468 / 478-point dense 3D mesh |---diff --git a/docs/quickstart.md b/docs/quickstart.mdindex ae6cf7b..4dc9dfa 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -166,9 +166,9 @@ Face 2: Female, 20-29, White----## Facial Landmarks (106 / 98 / 68 Points)+## Facial Landmarks (106 / 98 / 68 / 468 / 478 Points)-UniFace ships two dense-landmark families. Pick whichever fits your downstream task:+UniFace ships three dense-landmark families. Pick whichever fits your downstream task:```pythonimport cv2@@ -207,6 +207,20 @@ landmarker_68 = PIPNet(model_name=PIPNetWeights.DW300_CELEBA_68)landmarks = landmarker_98.get_landmarks(image, faces[0].bbox) # (98, 2)```+**Face Mesh (468 / 478 points, 3D)** is MediaPipe's dense mesh, run over every detected face+in a single batched call. Pass `FaceMeshWeights.V2_478` for the 478-point variant with irises:++```python+from uniface.landmark import FaceMesh++mesher = FaceMesh() # default: 468 points+results = mesher.predict(image, faces)++print(results[0].landmarks.shape) # (468, 3), x/y in image pixels, z is relative depth+print(results[0].points_2d.shape) # (468, 2), depth dropped+print(results[0].score) # face presence, [0, 1]+```+---## Gaze Estimation@@ -504,16 +518,33 @@ For detailed model comparisons and benchmarks, see the [Model Zoo](models.md).| Task | Available Models ||------|------------------|-| Detection | `RetinaFace`, `SCRFD`, `YOLOv5Face`, `YOLOv8Face` |+| Detection | `RetinaFace`, `SCRFD`, `CenterFace`, `YOLOv5Face`, `YOLOv8Face`, `BlazeFace` (short-range, 6 keypoints) || Recognition | `ArcFace`, `AdaFace`, `EdgeFace`, `MobileFace`, `SphereFace` |-| Landmarks | `Landmark106` (106 pts), `PIPNet` (98 / 68 pts) |+| Landmarks | `Landmark106` (106 pts), `PIPNet` (98 / 68 pts), `FaceMesh` (468 or 478 pts, 3D) || Tracking | `BYTETracker` || Gaze | `MobileGaze` (ResNet18/34/50, MobileNetV2, MobileOneS0) || Head Pose | `HeadPose` (ResNet18/34/50, MobileNetV2/V3) |-| Parsing | `BiSeNet` (ResNet18/34) |-| Attributes | `AgeGender`, `FairFace`, `Emotion` |+| Parsing | `BiSeNet` (ResNet18/34), `XSeg` |+| Matting | `MODNet` |+| Attributes | `AgeGender`, `FairFace`, `Emotion`, `FaceAttribNet` (face states) || Anti-Spoofing | `MiniFASNet` (V1SE, V2) || Quality | `EDifFIQA` (T, S, M, L) |+| Privacy | `BlurFace` (5 blur methods) |+| Vector Store | `FAISS` |++---++## Verbose Logging++Enable logging to see what happens during model loading and inference (useful for debugging):++```python+import logging+from uniface import enable_logging++enable_logging() # INFO level+enable_logging(level=logging.DEBUG) # DEBUG level+```---@@ -552,12 +583,13 @@ python -c "import platform; print(platform.machine())"### Import Errors```python-from uniface.detection import RetinaFace, SCRFD+from uniface.detection import BlazeFace, CenterFace, RetinaFace, SCRFD, YOLOv5Face, YOLOv8Facefrom uniface.recognition import ArcFace, AdaFace-from uniface.attribute import AgeGender, FairFace-from uniface.landmark import Landmark106, PIPNet+from uniface.attribute import AgeGender, Emotion, FaceAttribNet, FairFace+from uniface.landmark import FaceMesh, Landmark106, PIPNetfrom uniface.gaze import MobileGazefrom uniface.headpose import HeadPose+from uniface.matting import MODNetfrom uniface.parsing import BiSeNet, XSegfrom uniface.privacy import BlurFacefrom uniface.quality import EDifFIQAdiff --git a/docs/recipes/custom-models.md b/docs/recipes/custom-models.mdindex 94cce5b..aaaa899 100644--- a/docs/recipes/custom-models.md+++ b/docs/recipes/custom-models.md@@ -26,6 +26,17 @@ from uniface.types import Faceimport numpy as npclass MyDetector(BaseDetector):+ # Both flags default to False, so a boxes-only detector declares neither.++ # Opt in if your detector fills Face.landmarks.+ supports_landmarks = True++ # Opt in only if those landmarks ARE the 5-point alignment template+ # (left eye, right eye, nose, left mouth corner, right mouth corner).+ # Left False, FaceAnalyzer disables recognition instead of producing+ # broken embeddings.+ supports_alignment = True+def __init__(self, model_path: str, confidence_threshold: float = 0.5):super().__init__(confidence_threshold=confidence_threshold)self.session = create_onnx_session(model_path)@@ -62,13 +73,47 @@ from uniface.recognition.base import BaseRecognizer, PreprocessConfigclass MyRecognizer(BaseRecognizer):def __init__(self, model_path: str, providers=None):preprocessing = PreprocessConfig(input_mean=127.5, input_std=127.5, input_size=(112, 112))- super().__init__(model_path, preprocessing, providers=providers)+ super().__init__(model_path=model_path, preprocessing=preprocessing, providers=providers)# Optional: override preprocess() if your model expects custom normalization.```---+## Add Custom Per-Face Predictor++`FaceAnalyzer` runs any `BaseAttribute` subclass on each detected face via the+`predictors=` list. Implement `predict(image, face)` to read what you need from+the `Face` (bbox, landmarks), run inference, and write results back:++```python+from uniface.attribute import BaseAttribute++class MyPredictor(BaseAttribute):+ def _initialize_model(self):+ ... # load your model++ def preprocess(self, image, *args):+ ... # crop and normalize++ def postprocess(self, prediction):+ ... # raw output to a result object++ def predict(self, image, face):+ result = self.postprocess(self._run(self.preprocess(image, face.bbox)))+ face.age = result.age # enrich the Face in-place+ return result+```++```python+from uniface import FaceAnalyzer++analyzer = FaceAnalyzer(predictors=[MyPredictor()])+faces = analyzer.analyze(image)+```++---+## Usage```pythondiff --git a/docs/recipes/image-pipeline.md b/docs/recipes/image-pipeline.mdindex 4f54f9c..879161b 100644--- a/docs/recipes/image-pipeline.md+++ b/docs/recipes/image-pipeline.md@@ -76,9 +76,9 @@ recognizer = ArcFace()age_gender = AgeGender()analyzer = FaceAnalyzer(- detector,+ detector=detector,recognizer=recognizer,- attributes=[age_gender],+ predictors=[age_gender],)# Process imagediff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.cssindex 79914d7..1f0bba3 100644--- a/docs/stylesheets/extra.css+++ b/docs/stylesheets/extra.css@@ -59,13 +59,6 @@background-clip: text;}-.hero-tagline {- font-size: 1.5rem;- color: var(--md-default-fg-color);- margin-bottom: 0.5rem !important;- font-weight: 500;-}-.hero-subtitle {font-size: 1rem;color: var(--md-default-fg-color--light);diff --git a/examples/01_face_detection.ipynb b/examples/01_face_detection.ipynbindex eead195..501c0ce 100644--- a/examples/01_face_detection.ipynb+++ b/examples/01_face_detection.ipynb@@ -185,14 +185,7 @@{"cell_type": "markdown","metadata": {},- "source": [- "## Notes\n",- "\n",- "- `detect()` returns a list of `Face` objects with attributes: `bbox`, `confidence`, `landmarks`\n",- "- Access attributes using dot notation: `face.bbox`, `face.confidence`, `face.landmarks`\n",- "- Adjust `conf_thresh` and `nms_thresh` for your use case\n",- "- Use `max_num` to limit detected faces"- ]+ "source": "## Notes\n\n- `detect()` returns a list of `Face` objects with attributes: `bbox`, `confidence`, `landmarks`\n- Access attributes using dot notation: `face.bbox`, `face.confidence`, `face.landmarks`\n- Adjust `confidence_threshold` and `nms_threshold` for your use case\n- Use `max_num` to limit detected faces"},{"cell_type": "code",diff --git a/examples/05_face_analyzer.ipynb b/examples/05_face_analyzer.ipynbindex de71b14..331c2d8 100644--- a/examples/05_face_analyzer.ipynb+++ b/examples/05_face_analyzer.ipynb@@ -84,7 +84,7 @@"analyzer = FaceAnalyzer(\n"," detector=RetinaFace(confidence_threshold=0.5),\n"," recognizer=ArcFace(),\n",- " attributes=[AgeGender()]\n",+ " predictors=[AgeGender()]\n",")"]},diff --git a/examples/07_face_anonymization.ipynb b/examples/07_face_anonymization.ipynbindex af35317..4aaa611 100644--- a/examples/07_face_anonymization.ipynb+++ b/examples/07_face_anonymization.ipynb@@ -132,23 +132,7 @@"execution_count": null,"metadata": {},"outputs": [],- "source": [- "# Initialize detector\n",- "detector = RetinaFace(conf_thresh=0.5)\n",- "faces = detector.detect(image)\n",- "print(f'Detected {len(faces)} faces')\n",- "\n",- "# Test all blur methods\n",- "methods = ['gaussian', 'pixelate', 'blackout', 'elliptical', 'median']\n",- "\n",- "for method in methods:\n",- " blurrer = BlurFace(method=method)\n",- " anonymized = blurrer.anonymize(image.copy(), faces)\n",- "\n",- " output = cv2.cvtColor(anonymized, cv2.COLOR_BGR2RGB)\n",- " print(f'\\\\n{method.upper()}:')\n",- " display.display(Image.fromarray(output))\n"- ]+ "source": "# Initialize detector\ndetector = RetinaFace(confidence_threshold=0.5)\nfaces = detector.detect(image)\nprint(f'Detected {len(faces)} faces')\n\n# Test all blur methods\nmethods = ['gaussian', 'pixelate', 'blackout', 'elliptical', 'median']\n\nfor method in methods:\n blurrer = BlurFace(method=method)\n anonymized = blurrer.anonymize(image.copy(), faces)\n\n output = cv2.cvtColor(anonymized, cv2.COLOR_BGR2RGB)\n print(f'\\n{method.upper()}:')\n display.display(Image.fromarray(output))\n"},{"cell_type": "markdown",diff --git a/examples/14_face_attributes.ipynb b/examples/14_face_attributes.ipynbnew file mode 100644index 0000000..fa49aca--- /dev/null+++ b/examples/14_face_attributes.ipynb@@ -0,0 +1,260 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Face Attribute Detection with UniFace\n",+ "\n",+ "<div style=\"display:flex; flex-wrap:wrap; align-items:center;\">\n",+ " <a style=\"margin-right:10px; margin-bottom:6px;\" href=\"https://pepy.tech/projects/uniface\"><img alt=\"PyPI Downloads\" src=\"https://static.pepy.tech/personalized-badge/uniface?period=total&units=international_system&left_color=grey&right_color=blue&left_text=Downloads\"></a>\n",+ " <a style=\"margin-right:10px; margin-bottom:6px;\" href=\"https://pypi.org/project/uniface/\"><img alt=\"PyPI Version\" src=\"https://img.shields.io/pypi/v/uniface.svg\"></a>\n",+ " <a style=\"margin-right:10px; margin-bottom:6px;\" href=\"https://opensource.org/licenses/MIT\"><img alt=\"License\" src=\"https://img.shields.io/badge/License-MIT-blue.svg\"></a>\n",+ " <a style=\"margin-bottom:6px;\" href=\"https://github.com/yakhyo/uniface\"><img alt=\"GitHub Stars\" src=\"https://img.shields.io/github/stars/yakhyo/uniface.svg?style=social\"></a>\n",+ "</div>\n",+ "\n",+ "**UniFace** is a lightweight, production-ready Python library for face detection, recognition, tracking, landmark analysis, face parsing, gaze estimation, and face attributes.\n",+ "\n",+ "🔗 **GitHub**: [github.com/yakhyo/uniface](https://github.com/yakhyo/uniface) | 📚 **Docs**: [yakhyo.github.io/uniface](https://yakhyo.github.io/uniface)\n",+ "\n",+ "---\n",+ "\n",+ "This notebook demonstrates face attribute detection with **FaceAttribNet** — five independent binary face states per face: left/right eye openness, eyeglasses, face mask, and sunglasses.\n",+ "\n",+ "## 1. Install UniFace"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "%pip install -q \"uniface[cpu]\"\n",+ "\n",+ "# Clone repo for assets (Colab only)\n",+ "import os\n",+ "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",+ " if not os.path.exists('uniface'):\n",+ " !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",+ " os.chdir('uniface/examples')"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 2. Import Libraries"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import cv2\n",+ "import matplotlib.pyplot as plt\n",+ "from pathlib import Path\n",+ "\n",+ "import uniface\n",+ "from uniface.attribute import FaceAttribNet\n",+ "from uniface.detection import RetinaFace\n",+ "\n",+ "print(f\"UniFace version: {uniface.__version__}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 3. Initialize Models"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Initialize face detector\n",+ "detector = RetinaFace(confidence_threshold=0.5)\n",+ "\n",+ "# Initialize face attribute model\n",+ "face_attrib = FaceAttribNet()\n",+ "\n",+ "print(\"Models initialized successfully!\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 4. Process All Test Images\n",+ "\n",+ "Each face gets a `FaceStateResult` with five **independent** probabilities: `left_eye_open`, `right_eye_open`, `eyeglasses`, `mask`, `sunglasses`.\n",+ "\n",+ "> ⚠️ These come from independent binary heads — they do not sum to 1 and several can be high at once (a face can wear both sunglasses and a mask). Threshold each attribute separately; never `argmax`."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "THRESHOLD = 0.5\n",+ "\n",+ "\n",+ "def annotate(image, face, result):\n",+ " \"\"\"Draw the face box and the attributes that exceed THRESHOLD.\"\"\"\n",+ " x1, y1, x2, y2 = map(int, face.bbox)\n",+ " cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)\n",+ "\n",+ " scale = max(0.6, (x2 - x1) / 250)\n",+ " for i, label in enumerate(result.labels(THRESHOLD)):\n",+ " y_text = y1 + int((i + 1) * 32 * scale)\n",+ " cv2.putText(image, label, (x2 + 8, y_text), cv2.FONT_HERSHEY_SIMPLEX, scale, (0, 255, 0), 2, cv2.LINE_AA)\n",+ "\n",+ "\n",+ "test_images_dir = Path('../assets/test_images/attributes')\n",+ "test_images = sorted(test_images_dir.glob('*.jpg'))\n",+ "\n",+ "original_images = []\n",+ "annotated_images = []\n",+ "titles = []\n",+ "\n",+ "for img_path in test_images:\n",+ " image = cv2.imread(str(img_path))\n",+ " if image is None:\n",+ " continue\n",+ "\n",+ " original_images.append(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n",+ "\n",+ " faces = detector.detect(image)\n",+ " for face in faces:\n",+ " result = face_attrib.predict(image, face)\n",+ " active = ', '.join(result.labels(THRESHOLD)) or 'none'\n",+ " print(f\"{img_path.name}: {active}\")\n",+ " annotate(image, face, result)\n",+ "\n",+ " annotated_images.append(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n",+ " titles.append(img_path.stem)\n",+ "\n",+ "print(f\"\\nProcessed {len(original_images)} images\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 5. Visualize Results\n",+ "\n",+ "**First row**: Original images\n",+ "**Second row**: Faces annotated with the attributes above the threshold"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "num_images = len(original_images)\n",+ "\n",+ "fig, axes = plt.subplots(2, num_images, figsize=(4 * num_images, 9))\n",+ "\n",+ "if num_images == 1:\n",+ " axes = axes.reshape(2, 1)\n",+ "\n",+ "for i in range(num_images):\n",+ " axes[0, i].imshow(original_images[i])\n",+ " axes[0, i].set_title(titles[i], fontsize=12)\n",+ " axes[0, i].axis('off')\n",+ "\n",+ " axes[1, i].imshow(annotated_images[i])\n",+ " axes[1, i].set_title('Attributes', fontsize=12)\n",+ " axes[1, i].axis('off')\n",+ "\n",+ "plt.tight_layout()\n",+ "plt.show()"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 6. Inspect a Single Prediction\n",+ "\n",+ "`predict()` returns a `FaceStateResult` and also writes the probabilities back onto the `Face` object (`face.left_eye_open`, `face.right_eye_open`, `face.eyeglasses`, `face.mask`, `face.sunglasses`)."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "image = cv2.imread(str(test_images_dir / 'sunglasses.jpg'))\n",+ "face = detector.detect(image)[0]\n",+ "\n",+ "result = face_attrib.predict(image, face)\n",+ "\n",+ "print(result)\n",+ "print()\n",+ "for name, prob in result.as_dict().items():\n",+ " marker = '✔' if prob > THRESHOLD else '✘'\n",+ " print(f\" {marker} {name:15s} {prob:.4f}\")\n",+ "\n",+ "print()\n",+ "print(f\"Face enriched: sunglasses={face.sunglasses:.4f}, left_eye_open={face.left_eye_open:.4f}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Notes\n",+ "\n",+ "- **Input**: full image + detected `Face` (the model crops by `face.bbox` internally, letterboxes to 128×128)\n",+ "- **Output**: `FaceStateResult` with five independent probabilities in `[0, 1]`\n",+ "- **Multi-label**: threshold each attribute separately (`result.labels(threshold)`); never `argmax`\n",+ "- **Face enrichment**: `predict()` also sets `face.left_eye_open`, `face.right_eye_open`, `face.eyeglasses`, `face.mask`, `face.sunglasses`\n",+ "- **Model**: Qualcomm's [FaceAttribNet](https://github.com/qualcomm/ai-hub-models/tree/main/src/qai_hub_models/models/face_attrib_net) (\"Facial-Attribute-Detection\"), ONNX export from [yakhyo/face-attribute](https://github.com/yakhyo/face-attribute)\n",+ "\n",+ "### With FaceAnalyzer\n",+ "\n",+ "```python\n",+ "from uniface import FaceAnalyzer, FaceAttribNet\n",+ "\n",+ "analyzer = FaceAnalyzer(predictors=[FaceAttribNet()])\n",+ "faces = analyzer.analyze(image)\n",+ "\n",+ "for face in faces:\n",+ " print(face.eyeglasses, face.mask, face.sunglasses)\n",+ "```"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "base",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.13.5"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 4+}diff --git a/examples/15_face_mesh.ipynb b/examples/15_face_mesh.ipynbnew file mode 100644index 0000000..085089f--- /dev/null+++ b/examples/15_face_mesh.ipynb@@ -0,0 +1,287 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Dense Face Mesh with UniFace\n",+ "\n",+ "<div style=\"display:flex; flex-wrap:wrap; align-items:center;\">\n",+ " <a style=\"margin-right:10px; margin-bottom:6px;\" href=\"https://pepy.tech/projects/uniface\"><img alt=\"PyPI Downloads\" src=\"https://static.pepy.tech/personalized-badge/uniface?period=total&units=international_system&left_color=grey&right_color=blue&left_text=Downloads\"></a>\n",+ " <a style=\"margin-right:10px; margin-bottom:6px;\" href=\"https://pypi.org/project/uniface/\"><img alt=\"PyPI Version\" src=\"https://img.shields.io/pypi/v/uniface.svg\"></a>\n",+ " <a style=\"margin-right:10px; margin-bottom:6px;\" href=\"https://opensource.org/licenses/MIT\"><img alt=\"License\" src=\"https://img.shields.io/badge/License-MIT-blue.svg\"></a>\n",+ " <a style=\"margin-bottom:6px;\" href=\"https://github.com/yakhyo/uniface\"><img alt=\"GitHub Stars\" src=\"https://img.shields.io/github/stars/yakhyo/uniface.svg?style=social\"></a>\n",+ "</div>\n",+ "\n",+ "**UniFace** is a lightweight, production-ready Python library for face detection, recognition, tracking, landmark analysis, face parsing, gaze estimation, and face attributes.\n",+ "\n",+ "🔗 **GitHub**: [github.com/yakhyo/uniface](https://github.com/yakhyo/uniface) | 📚 **Docs**: [yakhyo.github.io/uniface](https://yakhyo.github.io/uniface)\n",+ "\n",+ "---\n",+ "\n",+ "This notebook demonstrates **MediaPipe Face Mesh** — 468 dense 3D landmarks per face.\n",+ "\n",+ "Unlike the other landmark models it returns **three** coordinates per point and a face-presence score, and it runs every face in an image through a **single batched inference call**.\n",+ "\n",+ "## 1. Install UniFace"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "%pip install -q \"uniface[cpu]\"\n",+ "\n",+ "# Clone repo for assets (Colab only)\n",+ "import os\n",+ "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",+ " if not os.path.exists('uniface'):\n",+ " !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",+ " os.chdir('uniface/examples')"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 2. Import Libraries"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import cv2\n",+ "import matplotlib.pyplot as plt\n",+ "import numpy as np\n",+ "from pathlib import Path\n",+ "\n",+ "import uniface\n",+ "from uniface.detection import SCRFD, BlazeFace\n",+ "from uniface.draw import draw_mesh\n",+ "from uniface.landmark import FaceMesh\n",+ "\n",+ "print(f\"UniFace version: {uniface.__version__}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 3. Initialize Models"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Any detector works — Face Mesh only needs a box plus the two eye points\n",+ "detector = SCRFD()\n",+ "mesher = FaceMesh()\n",+ "\n",+ "print(f\"Landmarks: {mesher.num_landmarks}\")\n",+ "print(f\"Input size: {mesher.input_size}x{mesher.input_size}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 4. Detect and Mesh\n",+ "\n",+ "Face Mesh needs a bounding box plus the first two landmarks (the eyes), which it uses to rotate the crop so the eye line is horizontal. Passing `Face` objects does this automatically."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "image = cv2.imread('../assets/einstein.png')\n",+ "\n",+ "faces = detector.detect(image)\n",+ "print(f\"Detected {len(faces)} face(s)\")\n",+ "\n",+ "# One batched call for every face in the image\n",+ "results = mesher.predict(image, faces)\n",+ "\n",+ "result = results[0]\n",+ "print(f\"Landmarks shape: {result.landmarks.shape}\") # (468, 3)\n",+ "print(f\"2D only: {result.points_2d.shape}\") # (468, 2)\n",+ "print(f\"Presence score: {result.score:.4f}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 5. Visualize\n",+ "\n",+ "`draw_mesh` has three render modes. `full` draws the dense 2556-edge tessellation — the most detailed, but noticeably slower. Prefer `partial` or `points` for video."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",+ "\n",+ "for ax, mode in zip(axes, ['points', 'partial', 'full']):\n",+ " canvas = image.copy()\n",+ " draw_mesh(canvas, result.landmarks, mode=mode)\n",+ " ax.imshow(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))\n",+ " ax.set_title(f\"mode='{mode}'\")\n",+ " ax.axis('off')\n",+ "\n",+ "plt.tight_layout()\n",+ "plt.show()"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 6. The Depth Coordinate\n",+ "\n",+ "`z` is **relative** depth on the same pixel scale as `x`/`y`, where smaller is closer to the camera. It has no absolute origin, so it is only meaningful *within* one face — not between faces or between images."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "points = result.landmarks\n",+ "\n",+ "plt.figure(figsize=(7, 7))\n",+ "scatter = plt.scatter(points[:, 0], points[:, 1], c=points[:, 2], cmap='viridis', s=8)\n",+ "plt.colorbar(scatter, label='z (relative depth, smaller = closer)')\n",+ "plt.gca().invert_yaxis()\n",+ "plt.gca().set_aspect('equal')\n",+ "plt.title('468 landmarks coloured by depth')\n",+ "plt.show()\n",+ "\n",+ "print(f\"z range: {points[:, 2].min():.1f} .. {points[:, 2].max():.1f}\")\n",+ "print(\"The nose tip is the closest point; the ears and jaw edges sit furthest back.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 7. MediaPipe Parity\n",+ "\n",+ "Seeding the mesh with **BlazeFace** reproduces MediaPipe's own pipeline exactly.\n",+ "\n",+ "> ⚠️ BlazeFace returns **6** MediaPipe keypoints whose 4th point is a mouth *center*, not corners, so they cannot be fitted to the 5-point alignment template. It declares this with `supports_alignment = False`, and `FaceAnalyzer` disables recognition for it rather than producing broken embeddings."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# BlazeFace is the detector mp.solutions.face_mesh runs internally\n",+ "blazeface = BlazeFace()\n",+ "\n",+ "bf_faces = blazeface.detect(image)\n",+ "bf_results = mesher.predict(image, bf_faces)\n",+ "\n",+ "print(f\"BlazeFace keypoints: {bf_faces[0].landmarks.shape}\") # (6, 2), not (5, 2)\n",+ "print(f\"supports_alignment: {blazeface.supports_alignment}\") # False\n",+ "\n",+ "canvas = image.copy()\n",+ "draw_mesh(canvas, bf_results[0].landmarks, mode='full')\n",+ "\n",+ "plt.figure(figsize=(7, 7))\n",+ "plt.imshow(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))\n",+ "plt.title('MediaPipe parity: BlazeFace + Face Mesh')\n",+ "plt.axis('off')\n",+ "plt.show()"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## 8. Other Ways to Call It"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Face Mesh implements the same interface as Landmark106 and PIPNet\n",+ "landmarks_2d = mesher.get_landmarks(image, faces[0].bbox)\n",+ "print(f\"get_landmarks: {landmarks_2d.shape}\")\n",+ "\n",+ "# Without a detector, pass boxes directly\n",+ "x1, y1, x2, y2 = faces[0].bbox\n",+ "manual = mesher.predict(image, bboxes=[[x1, y1, x2, y2]])\n",+ "print(f\"From a raw box: {manual[0].landmarks.shape}\")\n",+ "\n",+ "# Tune the crop with margin= if the mesh clips on unusual framing\n",+ "tight = mesher.predict(image, faces, margin=0.1)[0]\n",+ "print(f\"Tighter crop shifts the fit: {not np.allclose(tight.landmarks, result.landmarks)}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Summary\n",+ "\n",+ "| | |\n",+ "|---|---|\n",+ "| **Output** | `(468, 3)` — `x`/`y` in image pixels, `z` relative depth on the same scale |\n",+ "| **Presence score** | Saturates near 1.0; confirms the model ran, not a discriminative confidence |\n",+ "| **Detectors** | Works with any of them — needs a box plus the two eye points |\n",+ "| **Batching** | `predict()` runs all faces in one inference call |\n",+ "| **Drop-in** | `get_landmarks()` matches `Landmark106` / `PIPNet` |\n",+ "\n",+ "### Next steps\n",+ "\n",+ "- [Landmarks documentation](https://yakhyo.github.io/uniface/modules/landmarks/)\n",+ "- [Detection documentation](https://yakhyo.github.io/uniface/modules/detection/) — BlazeFace and the 6-keypoint layout\n",+ "- [Coordinate systems](https://yakhyo.github.io/uniface/concepts/coordinate-systems/) — what `z` means\n",+ "\n",+ "> Face Mesh and BlazeFace weights originate from Google MediaPipe and are Apache-2.0 licensed.\n",+ "> See [Licenses & Attribution](https://yakhyo.github.io/uniface/license-attribution/)."+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "base",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.13.5"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 4+}diff --git a/mkdocs.yml b/mkdocs.ymlindex 426a966..ca3a470 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -7,7 +7,7 @@ repo_name: yakhyo/unifacerepo_url: https://github.com/yakhyo/unifaceedit_uri: edit/main/docs/-copyright: Copyright © 2025 Yakhyokhuja Valikhujaev+copyright: Copyright © 2026 Yakhyokhuja Valikhujaevtheme:name: material@@ -15,7 +15,7 @@ theme:palette:- media: "(prefers-color-scheme)"toggle:- icon: material/link+ icon: material/brightness-autoname: Switch to light mode- media: "(prefers-color-scheme: light)"scheme: defaultdiff --git a/pyproject.toml b/pyproject.tomlindex a88fae8..290adaf 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[project]name = "uniface"-version = "3.7.1"+version = "4.0.0rc1"description = "UniFace: A Unified Face Analysis Library for Python"readme = "README.md"license = "MIT"@@ -48,7 +48,6 @@ dependencies = ["scipy>=1.7.0","requests>=2.28.0","tqdm>=4.64.0",- "typing_extensions>=4.5.0",][project.optional-dependencies]@@ -76,7 +75,7 @@ Documentation = "https://yakhyo.github.io/uniface""Model Zoo" = "https://yakhyo.github.io/uniface/models/"[build-system]-requires = ["setuptools>=64", "wheel"]+requires = ["setuptools>=77"]build-backend = "setuptools.build_meta"[tool.setuptools]@@ -117,6 +116,8 @@ select = ["C4", # flake8-comprehensions"SIM", # flake8-simplify"RUF", # Ruff-specific rules+ "D205", # pydocstyle: blank line between docstring summary and description+ "D212", # pydocstyle: multi-line docstring summary starts on the first line]ignore = ["E501", # Line too long (handled by formatter)diff --git a/tests/test_age_gender.py b/tests/test_age_gender.pyindex d0f73d0..c06502c 100644--- a/tests/test_age_gender.py+++ b/tests/test_age_gender.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport numpy as npimport pytest-from uniface.attribute import AgeGender, AttributeResult+from uniface.attribute import AgeGender, DemographyResultfrom uniface.types import Face@@ -40,7 +40,7 @@ def test_model_initialization(age_gender_model):def test_prediction_output_format(age_gender_model, mock_image, mock_face):result = age_gender_model.predict(mock_image, mock_face)- assert isinstance(result, AttributeResult), f'Result should be AttributeResult, got {type(result)}'+ assert isinstance(result, DemographyResult), f'Result should be DemographyResult, got {type(result)}'assert isinstance(result.gender, int), f'Gender should be int, got {type(result.gender)}'assert isinstance(result.age, int), f'Age should be int, got {type(result.age)}'assert isinstance(result.sex, str), f'Sex should be str, got {type(result.sex)}'@@ -149,7 +149,7 @@ def test_output_format_for_visualization(age_gender_model, mock_image, mock_facedef test_attribute_result_fields(age_gender_model, mock_image, mock_face):- """Test that AttributeResult has correct fields for AgeGender model."""+ """Test that DemographyResult has correct fields for AgeGender model."""result = age_gender_model.predict(mock_image, mock_face)assert result.gender is not Nonediff --git a/tests/test_analyzer.py b/tests/test_analyzer.pynew file mode 100644index 0000000..fd54e53--- /dev/null+++ b/tests/test_analyzer.py@@ -0,0 +1,123 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++import numpy as np+import pytest++from uniface.analyzer import FaceAnalyzer+from uniface.attribute import BaseAttribute+from uniface.detection.base import BaseDetector+from uniface.types import Face+++class StubDetector(BaseDetector):+ """Returns a fixed number of faces without any model or download."""++ supports_landmarks = True+ supports_alignment = True++ def __init__(self, num_faces: int = 2) -> None:+ super().__init__()+ self.num_faces = num_faces++ def detect(self, image: np.ndarray, **kwargs) -> list[Face]:+ return [+ Face(+ bbox=np.array([10.0 * i, 10.0, 50.0 + 10.0 * i, 60.0]),+ confidence=0.9,+ landmarks=np.zeros((5, 2)),+ )+ for i in range(self.num_faces)+ ]++ def preprocess(self, image: np.ndarray) -> np.ndarray:+ return image++ def postprocess(self, outputs, **kwargs):+ return outputs+++class AgeStampPredictor(BaseAttribute):+ """Enriches each face in-place and counts its calls."""++ def __init__(self) -> None:+ self.calls = 0++ def _initialize_model(self) -> None: ...++ def preprocess(self, image, *args):+ return image++ def postprocess(self, prediction):+ return prediction++ def predict(self, image: np.ndarray, face: Face) -> None:+ self.calls += 1+ face.age = 30+++class FailingPredictor(BaseAttribute):+ """Always raises, to exercise the analyzer's per-predictor error handling."""++ def _initialize_model(self) -> None: ...++ def preprocess(self, image, *args):+ return image++ def postprocess(self, prediction):+ return prediction++ def predict(self, image: np.ndarray, face: Face) -> None:+ raise RuntimeError('boom')+++def image():+ return np.zeros((240, 320, 3), dtype=np.uint8)+++def test_predictors_run_once_per_face(image):+ predictor = AgeStampPredictor()+ analyzer = FaceAnalyzer(detector=StubDetector(num_faces=3), recognizer=None, predictors=[predictor])++ faces = analyzer.analyze(image)++ assert predictor.calls == 3+ assert all(face.age == 30 for face in faces)+++def test_failing_predictor_does_not_break_the_pipeline(image):+ """One bad predictor must not abort analysis or starve the others."""+ stamper = AgeStampPredictor()+ analyzer = FaceAnalyzer(+ detector=StubDetector(num_faces=2),+ recognizer=None,+ predictors=[FailingPredictor(), stamper],+ )++ faces = analyzer.analyze(image)++ assert len(faces) == 2+ assert stamper.calls == 2+++def test_predictors_default_to_empty(image):+ analyzer = FaceAnalyzer(detector=StubDetector(), recognizer=None)++ assert analyzer.predictors == []+ assert len(analyzer.analyze(image)) == 2+++def test_repr_lists_predictors():+ analyzer = FaceAnalyzer(detector=StubDetector(), recognizer=None, predictors=[AgeStampPredictor()])++ assert 'predictors=[AgeStampPredictor]' in repr(analyzer)+ assert 'recognizer' not in repr(analyzer)+++def test_constructor_is_keyword_only():+ with pytest.raises(TypeError):+ FaceAnalyzer(StubDetector())diff --git a/tests/test_blazeface.py b/tests/test_blazeface.pynew file mode 100644index 0000000..b620aa8--- /dev/null+++ b/tests/test_blazeface.py@@ -0,0 +1,190 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++from pathlib import Path+import threading++import cv2+import numpy as np+import pytest++from uniface.constants import BlazeFaceWeights+from uniface.detection import BlazeFace+from uniface.detection.blazeface import _weighted_nms++TEST_IMAGE = Path(__file__).resolve().parent.parent / 'assets' / 'einstein.png'++[email protected](scope='module')+def blazeface_model():+ return BlazeFace(model_name=BlazeFaceWeights.DEFAULT)++[email protected](scope='module')+def face_image():+ image = cv2.imread(str(TEST_IMAGE))+ assert image is not None, f'Missing test asset: {TEST_IMAGE}'+ return image+++def test_model_initialization(blazeface_model):+ assert blazeface_model is not None+ assert blazeface_model.input_size == 128+ assert blazeface_model.anchors.shape == (896, 2)+++def test_does_not_support_alignment(blazeface_model):+ """The contract that keeps BlazeFace out of recognition pipelines."""+ assert blazeface_model.supports_alignment is False+ assert blazeface_model.supports_landmarks is True+ assert blazeface_model.get_info()['supports_alignment'] is False+++def test_detect_returns_faces(blazeface_model, face_image):+ faces = blazeface_model.detect(face_image)++ assert isinstance(faces, list)+ assert len(faces) >= 1++ for face in faces:+ assert 0.0 <= face.confidence <= 1.0+++def test_emits_six_keypoints(blazeface_model, face_image):+ """MediaPipe's layout, not the 5-point alignment template."""+ face = blazeface_model.detect(face_image)[0]++ assert face.landmarks.shape == (6, 2)+ assert face.landmarks.dtype == np.float32+++def test_first_two_keypoints_are_the_eyes(blazeface_model, face_image):+ """Row 0 is the viewer-left eye, row 1 the viewer-right — what FaceMesh reads."""+ face = blazeface_model.detect(face_image)[0]++ assert face.landmarks[0][0] < face.landmarks[1][0]+++def test_bbox_is_clipped_to_the_frame(blazeface_model, face_image):+ """Decoded boxes can run past the frame; detect() clips them."""+ height, width = face_image.shape[:2]++ for face in blazeface_model.detect(face_image):+ x1, y1, x2, y2 = face.bbox+ assert x1 < x2 and y1 < y2+ assert 0 <= x1 <= width and 0 <= x2 <= width+ assert 0 <= y1 <= height and 0 <= y2 <= height+++def test_no_faces_in_blank_images(blazeface_model):+ """Also covers letterboxing in both orientations."""+ for shape in ((480, 640, 3), (640, 480, 3)):+ assert blazeface_model.detect(np.zeros(shape, dtype=np.uint8)) == []+++ ('label', 'bad_image'),+ [+ ('float [0, 1]', np.random.rand(480, 640, 3).astype(np.float32)),+ ('grayscale', np.zeros((480, 640), dtype=np.uint8)),+ ('empty', np.zeros((0, 0, 3), dtype=np.uint8)),+ ],+)+def test_detect_rejects_unusable_images(blazeface_model, label, bad_image):+ """This detector warps its own input, bypassing the shared resize helpers.++ A float image used to return zero faces silently and a grayscale one raised+ an opaque IndexError, both unlike every other detector.+ """+ with pytest.raises(ValueError):+ blazeface_model.detect(bad_image)+++def test_no_overflow_warning_on_extreme_logits(blazeface_model, face_image):+ """Anchor logits are clipped before the sigmoid; numpy must not warn."""+ with np.errstate(all='raise'):+ blazeface_model.detect(face_image)+++def test_weighted_nms_blends_overlapping_boxes():+ """MediaPipe averages overlapping candidates rather than discarding them."""+ columns = 5 + 2 * 6+ rows = np.zeros((2, columns))+ rows[0, :5] = [0.9, 0.50, 0.50, 0.20, 0.20]+ rows[1, :5] = [0.3, 0.52, 0.52, 0.20, 0.20]++ merged = _weighted_nms(rows, iou_threshold=0.3)++ assert len(merged) == 1+ assert merged[0, 0] == pytest.approx(0.9)+ # Pulled toward the weaker box rather than ignoring it.+ assert 0.50 < merged[0, 1] < 0.52+++def test_weighted_nms_keeps_disjoint_boxes():+ columns = 5 + 2 * 6+ rows = np.zeros((2, columns))+ rows[0, :5] = [0.9, 0.20, 0.20, 0.10, 0.10]+ rows[1, :5] = [0.8, 0.80, 0.80, 0.10, 0.10]++ assert len(_weighted_nms(rows, iou_threshold=0.3)) == 2+++def _nms_within(rows: np.ndarray, iou_threshold: float, seconds: float = 5.0) -> np.ndarray:+ """Run `_weighted_nms` on a worker thread so a non-terminating loop fails instead of hanging."""+ result: list[np.ndarray] = []+ worker = threading.Thread(target=lambda: result.append(_weighted_nms(rows, iou_threshold)), daemon=True)+ worker.start()+ worker.join(seconds)++ assert not worker.is_alive(), f'_weighted_nms did not terminate within {seconds}s'+ return result[0]+++def test_weighted_nms_terminates_when_threshold_excludes_self_overlap():+ """iou_threshold=1.0 fails the strict `>` even for the winner's self-IoU of 1.0."""+ columns = 5 + 2 * 6+ rows = np.zeros((2, columns))+ rows[0, :5] = [0.9, 0.50, 0.50, 0.20, 0.20]+ rows[1, :5] = [0.3, 0.52, 0.52, 0.20, 0.20]++ with np.errstate(all='raise'):+ merged = _nms_within(rows, iou_threshold=1.0)++ # Nothing overlaps enough to blend, so both survive untouched.+ assert len(merged) == 2+ assert merged[0, 1] == pytest.approx(0.50)+ assert merged[1, 1] == pytest.approx(0.52)+++def test_weighted_nms_terminates_on_zero_area_box():+ """A degenerate box scores an IoU of 0 against itself."""+ columns = 5 + 2 * 6+ rows = np.zeros((1, columns))+ rows[0, :5] = [0.9, 0.50, 0.50, 0.0, 0.0]++ with np.errstate(all='raise'):+ merged = _nms_within(rows, iou_threshold=0.3)++ assert len(merged) == 1+ assert merged[0, :5] == pytest.approx([0.9, 0.50, 0.50, 0.0, 0.0])+++def test_analyzer_disables_recognition(blazeface_model, face_image):+ """The regression test for the alignment seam.++ An unalignable detector must not crash the analyzer, must not silently+ produce broken embeddings, and must say so once rather than per face.+ """+ from uniface.analyzer import FaceAnalyzer+ from uniface.recognition import ArcFace++ analyzer = FaceAnalyzer(detector=blazeface_model, recognizer=ArcFace())++ assert analyzer.recognizer is None++ faces = analyzer.analyze(face_image)+ assert all(face.embedding is None for face in faces)diff --git a/tests/test_centerface.py b/tests/test_centerface.pynew file mode 100644index 0000000..4926608--- /dev/null+++ b/tests/test_centerface.py@@ -0,0 +1,74 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo+++from __future__ import annotations++import numpy as np+import pytest++from uniface.constants import CenterFaceWeights+from uniface.detection import CenterFace+++def centerface_model():+ return CenterFace(+ model_name=CenterFaceWeights.DEFAULT,+ confidence_threshold=0.35,+ nms_threshold=0.3,+ )+++def test_model_initialization(centerface_model):+ assert centerface_model is not None, 'Model initialization failed.'+++def test_invalid_input_size():+ with pytest.raises(ValueError, match='multiple of 32'):+ CenterFace(input_size=(650, 480))+++def test_inference_on_640x640_image(centerface_model):+ mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)+ faces = centerface_model.detect(mock_image)++ assert isinstance(faces, list), 'Detections should be a list.'++ for face in faces:+ # Face is a dataclass, check attributes exist+ assert hasattr(face, 'bbox'), "Each detection should have a 'bbox' attribute."+ assert hasattr(face, 'confidence'), "Each detection should have a 'confidence' attribute."+ assert hasattr(face, 'landmarks'), "Each detection should have a 'landmarks' attribute."++ bbox = face.bbox+ assert len(bbox) == 4, 'BBox should have 4 values (x1, y1, x2, y2).'++ landmarks = face.landmarks+ assert len(landmarks) == 5, 'Should have 5 landmark points.'+ assert all(len(pt) == 2 for pt in landmarks), 'Each landmark should be (x, y).'+++def test_confidence_threshold(centerface_model):+ mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)+ faces = centerface_model.detect(mock_image)++ for face in faces:+ confidence = face.confidence+ assert confidence >= 0.35, f'Detection has confidence {confidence} below threshold 0.35'+++def test_no_faces_detected(centerface_model):+ empty_image = np.zeros((640, 640, 3), dtype=np.uint8)+ faces = centerface_model.detect(empty_image)+ assert len(faces) == 0, 'Should detect no faces in a blank image.'+++def test_different_input_sizes(centerface_model):+ test_sizes = [(480, 640, 3), (720, 1280, 3), (1080, 1920, 3)]++ for size in test_sizes:+ mock_image = np.random.randint(0, 255, size, dtype=np.uint8)+ faces = centerface_model.detect(mock_image)+ assert isinstance(faces, list), f'Should return list for size {size}'diff --git a/tests/test_detector_base.py b/tests/test_detector_base.pynew file mode 100644index 0000000..8421d74--- /dev/null+++ b/tests/test_detector_base.py@@ -0,0 +1,63 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++import numpy as np+import pytest++from uniface.analyzer import FaceAnalyzer+from uniface.detection import SCRFD, BlazeFace, CenterFace, RetinaFace, YOLOv5Face, YOLOv8Face+from uniface.detection.base import BaseDetector+from uniface.types import Face++LANDMARK_DETECTORS = [SCRFD, RetinaFace, CenterFace, YOLOv5Face, YOLOv8Face, BlazeFace]+ALIGNMENT_DETECTORS = [SCRFD, RetinaFace, CenterFace, YOLOv5Face, YOLOv8Face]+++class BoxOnlyDetector(BaseDetector):+ """A subclass that declares nothing, like a third-party boxes-only detector."""++ def detect(self, image: np.ndarray, **kwargs) -> list[Face]:+ return []++ def preprocess(self, image: np.ndarray) -> np.ndarray:+ return image++ def postprocess(self, outputs, **kwargs):+ return outputs+++def test_capability_flags_are_opt_in():+ """A subclass that declares nothing must not claim capabilities it does not have."""+ detector = BoxOnlyDetector()++ assert BaseDetector.supports_landmarks is False+ assert BaseDetector.supports_alignment is False+ assert detector.supports_landmarks is False+ assert detector.supports_alignment is False+ assert detector.get_info()['supports_landmarks'] is False+ assert detector.get_info()['supports_alignment'] is False+++def test_analyzer_disables_recognition_for_box_only_detector():+ """A boxes-only detector must take the recognition-disabled branch, not load ArcFace."""+ analyzer = FaceAnalyzer(detector=BoxOnlyDetector())++ assert analyzer.recognizer is None++[email protected]('detector_cls', LANDMARK_DETECTORS, ids=lambda c: c.__name__)+def test_builtin_detectors_declare_landmarks(detector_cls):+ assert detector_cls.supports_landmarks is True++[email protected]('detector_cls', ALIGNMENT_DETECTORS, ids=lambda c: c.__name__)+def test_builtin_detectors_declare_alignment(detector_cls):+ assert detector_cls.supports_alignment is True+++def test_blazeface_declares_landmarks_without_alignment():+ assert BlazeFace.supports_landmarks is True+ assert BlazeFace.supports_alignment is Falsediff --git a/tests/test_faceattribnet.py b/tests/test_faceattribnet.pynew file mode 100644index 0000000..db3e1ed--- /dev/null+++ b/tests/test_faceattribnet.py@@ -0,0 +1,136 @@+# Copyright 2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo+++from __future__ import annotations++import numpy as np+import pytest++from uniface.attribute import FaceAttribNet, FaceStateResult+from uniface.types import Face++ATTRIBUTE_NAMES = ('left_eye_open', 'right_eye_open', 'eyeglasses', 'mask', 'sunglasses')+++def _make_face(bbox: list[int] | np.ndarray) -> Face:+ """Helper: build a minimal Face from a bounding box."""+ bbox = np.asarray(bbox)+ landmarks = np.zeros((5, 2), dtype=np.float32)+ return Face(bbox=bbox, confidence=0.99, landmarks=landmarks)++[email protected](scope='module')+def model():+ return FaceAttribNet()+++def mock_image():+ return np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)+++def mock_face():+ return _make_face([100, 100, 300, 300])+++def test_model_initialization(model):+ assert model is not None, 'FaceAttribNet model initialization failed.'+++def test_prediction_output_format(model, mock_image, mock_face):+ result = model.predict(mock_image, mock_face)+ assert isinstance(result, FaceStateResult), f'Result should be FaceStateResult, got {type(result)}'+ for name in ATTRIBUTE_NAMES:+ value = getattr(result, name)+ assert isinstance(value, float), f'{name} should be float, got {type(value)}'+++def test_probabilities_in_range(model, mock_image, mock_face):+ result = model.predict(mock_image, mock_face)+ for name, value in result.as_dict().items():+ assert 0.0 <= value <= 1.0, f'{name} should be in [0, 1], got {value}'+++def test_as_dict_keys(model, mock_image, mock_face):+ result = model.predict(mock_image, mock_face)+ assert tuple(result.as_dict().keys()) == ATTRIBUTE_NAMES+++def test_labels_thresholding(model, mock_image, mock_face):+ result = model.predict(mock_image, mock_face)+ assert result.labels(threshold=-0.1) == list(ATTRIBUTE_NAMES), 'All attributes should exceed a negative threshold'+ assert result.labels(threshold=1.1) == [], 'No attribute should exceed a threshold above 1'+++def test_preprocess_output_shape(model, mock_image, mock_face):+ blob = model.preprocess(mock_image, mock_face.bbox)+ assert blob.shape == (1, 3, 128, 128), f'Blob shape should be (1, 3, 128, 128), got {blob.shape}'+ assert blob.dtype == np.float32, f'Blob dtype should be float32, got {blob.dtype}'+ assert blob.min() >= 0.0 and blob.max() <= 1.0, 'Blob values should be in [0, 1]'+++def test_face_enrichment(model, mock_image, mock_face):+ """predict() must write the five state probabilities back to the Face object."""+ for name in ATTRIBUTE_NAMES:+ assert getattr(mock_face, name) is None++ result = model.predict(mock_image, mock_face)++ for name in ATTRIBUTE_NAMES:+ assert getattr(mock_face, name) == getattr(result, name)+++def test_consistency(model, mock_image, mock_face):+ result1 = model.predict(mock_image, mock_face)+ result2 = model.predict(mock_image, mock_face)+ assert result1.as_dict() == result2.as_dict(), 'Same input should produce identical predictions'+++def test_different_bbox_sizes(model, mock_image):+ test_bboxes = [+ [50, 50, 150, 150],+ [100, 100, 300, 300],+ [50, 50, 400, 400],+ ]++ for bbox in test_bboxes:+ face = _make_face(bbox)+ result = model.predict(mock_image, face)+ for name, value in result.as_dict().items():+ assert 0.0 <= value <= 1.0, f'{name} out of range for bbox {bbox}'+++def test_different_image_sizes(model):+ test_sizes = [(480, 640, 3), (720, 1280, 3), (1080, 1920, 3)]+ face = _make_face([100, 100, 300, 300])++ for size in test_sizes:+ mock_image = np.random.randint(0, 255, size, dtype=np.uint8)+ result = model.predict(mock_image, face)+ for name, value in result.as_dict().items():+ assert 0.0 <= value <= 1.0, f'{name} out of range for image size {size}'+++def test_non_overlapping_bbox_raises(model, mock_image):+ face = _make_face([700, 700, 800, 800]) # outside the 640x640 image+ with pytest.raises(ValueError, match='does not overlap'):+ model.predict(mock_image, face)+++def test_margin_expands_crop(mock_image, mock_face, model):+ """A margin model should still produce valid probabilities."""+ margin_model = FaceAttribNet(margin=0.2, providers=model.providers)+ result = margin_model.predict(mock_image, mock_face)+ for name, value in result.as_dict().items():+ assert 0.0 <= value <= 1.0, f'{name} out of range with margin'+++def test_result_repr(model, mock_image, mock_face):+ result = model.predict(mock_image, mock_face)+ text = repr(result)+ assert text.startswith('FaceStateResult(')+ for name in ATTRIBUTE_NAMES:+ assert name in textdiff --git a/tests/test_facemesh.py b/tests/test_facemesh.pynew file mode 100644index 0000000..14bab88--- /dev/null+++ b/tests/test_facemesh.py@@ -0,0 +1,229 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo+++from __future__ import annotations++import numpy as np+import pytest++from uniface.constants import FaceMeshWeights+from uniface.landmark import IRIS_LEFT, IRIS_RIGHT, NUM_MESH_LANDMARKS, FaceMesh, roi_from_box+from uniface.types import FaceMeshResult++[email protected](scope='module', params=list(FaceMeshWeights), ids=lambda w: w.name)+def mesher(request):+ """Every shared test runs against both generations.++ Assertions here go through `num_landmarks` rather than a literal, so the suite+ covers 468 and 478 with one body and a third model would need no new tests.+ """+ return FaceMesh(model_name=request.param)+++def mock_image():+ return np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)+++def mock_bbox():+ return np.array([100, 100, 300, 300], dtype=np.float32)+++def mock_keypoints():+ """Five alignment landmarks with a horizontal eye line."""+ return np.array(+ [[150.0, 160.0], [250.0, 160.0], [200.0, 210.0], [160.0, 260.0], [240.0, 260.0]],+ dtype=np.float32,+ )+++ ('weights', 'num_landmarks', 'input_size'),+ [(FaceMeshWeights.V1_468, 468, 192), (FaceMeshWeights.V2_478, 478, 256)],+)+def test_model_geometry(weights, num_landmarks, input_size):+ """Both are read from the ONNX graph, never hardcoded in the class."""+ mesher = FaceMesh(model_name=weights)++ assert mesher.num_landmarks == num_landmarks+ assert mesher.input_size == input_size+++def test_get_landmarks_shape(mesher, mock_image, mock_bbox):+ """The BaseLandmarker contract: 2D only, one face."""+ landmarks = mesher.get_landmarks(mock_image, mock_bbox)++ assert landmarks.shape == (mesher.num_landmarks, 2)+ assert landmarks.dtype == np.float32+++def test_call_shortcut_forwards_keypoints(mesher, mock_image, mock_bbox, mock_keypoints):+ """__call__ is overridden; the base class signature would drop keypoints."""+ direct = mesher.get_landmarks(mock_image, mock_bbox, mock_keypoints)+ called = mesher(mock_image, mock_bbox, mock_keypoints)++ assert np.allclose(direct, called)+++def test_predict_returns_results(mesher, mock_image, mock_bbox):+ results = mesher.predict(mock_image, bboxes=[mock_bbox])++ assert len(results) == 1+ assert isinstance(results[0], FaceMeshResult)+ assert results[0].landmarks.shape == (mesher.num_landmarks, 3)+ assert results[0].landmarks.dtype == np.float32+ assert 0.0 <= results[0].score <= 1.0+ assert results[0].points_2d.shape == (mesher.num_landmarks, 2)+++def test_predict_batches_multiple_faces(mesher, mock_image, mock_bbox):+ """All faces go through a single batched session call."""+ boxes = [mock_bbox, mock_bbox + 50, mock_bbox + 100]+ results = mesher.predict(mock_image, bboxes=boxes)++ assert len(results) == 3+ assert all(r.landmarks.shape == (mesher.num_landmarks, 3) for r in results)+++def test_predict_input_validation(mesher, mock_image, mock_bbox, mock_keypoints):+ """faces and bboxes are mutually exclusive, and keypoints must line up."""+ assert mesher.predict(mock_image, bboxes=[]) == []++ with pytest.raises(ValueError, match='either faces or bboxes'):+ mesher.predict(mock_image)++ with pytest.raises(ValueError, match='either faces or bboxes'):+ mesher.predict(mock_image, [], bboxes=[mock_bbox])++ with pytest.raises(ValueError, match='keypoint sets'):+ mesher.predict(mock_image, bboxes=[mock_bbox, mock_bbox], keypoints=[mock_keypoints])+++def test_depth_is_populated(mesher, mock_image, mock_bbox, mock_keypoints):+ """z must carry real depth, not a zero-filled placeholder."""+ result = mesher.predict(mock_image, bboxes=[mock_bbox], keypoints=[mock_keypoints])[0]++ assert not np.allclose(result.landmarks[:, 2], 0.0)+ assert np.allclose(result.points_2d, result.landmarks[:, :2])+++def test_landmarks_map_back_to_the_image(mesher, mock_image, mock_bbox, mock_keypoints):+ """Catches an inverted or mis-scaled ROI transform."""+ result = mesher.predict(mock_image, bboxes=[mock_bbox], keypoints=[mock_keypoints])[0]+ points = result.landmarks[:, :2]++ assert 100 <= points[:, 0].mean() <= 300+ assert 100 <= points[:, 1].mean() <= 300+++def test_roll_normalization_changes_the_result(mesher, mock_image, mock_bbox, mock_keypoints):+ """Rotating the eye line must rotate the ROI, and so change the landmarks."""+ tilted = mock_keypoints.copy()+ tilted[1] = [230.0, 240.0] # drop the right eye to tilt the eye line++ upright = mesher.get_landmarks(mock_image, mock_bbox, mock_keypoints)+ rotated = mesher.get_landmarks(mock_image, mock_bbox, tilted)++ assert not np.allclose(upright, rotated)+++def test_works_with_any_detector(mesher, mock_image):+ """The cross-detector guarantee: Face objects from SCRFD feed FaceMesh directly."""+ from uniface.detection import SCRFD++ faces = SCRFD().detect(mock_image)+ results = mesher.predict(mock_image, faces)++ assert len(results) == len(faces)+ assert all(r.landmarks.shape == (mesher.num_landmarks, 3) for r in results)+++# roi_from_box — MediaPipe's detection_to_roi rule+def test_roi_is_square_on_the_long_side(mock_bbox):+ center_x, center_y, side, angle = roi_from_box(mock_bbox, margin=0.25)++ assert (center_x, center_y) == (200.0, 200.0)+ assert side == pytest.approx(200.0 * 1.5) # MediaPipe's 1.5x scale+ assert angle == 0.0++ # Never a stretched rectangle: the long side wins.+ assert roi_from_box(np.array([0, 0, 100, 200]), margin=0.0)[2] == pytest.approx(200.0)+++def test_roi_angle_comes_from_the_eyes(mock_bbox):+ level = np.array([[0.0, 0.0], [10.0, 0.0]])+ tilted = np.array([[0.0, 0.0], [10.0, 10.0]])+ # BlazeFace's 6-point layout also has the eyes in rows 0/1.+ six = np.array([[0.0, 0.0], [10.0, 0.0], [5.0, 5.0], [5.0, 8.0], [-2.0, 2.0], [12.0, 2.0]])++ assert roi_from_box(mock_bbox, level)[3] == pytest.approx(0.0)+ assert roi_from_box(mock_bbox, tilted)[3] == pytest.approx(45.0)+ assert roi_from_box(mock_bbox, six)[3] == pytest.approx(0.0)+++def test_result_equality_does_not_raise():+ """eq=False: comparison falls back to identity instead of an ndarray ValueError."""+ a = FaceMeshResult(landmarks=np.zeros((468, 3), dtype=np.float32), score=1.0)+ b = FaceMeshResult(landmarks=np.zeros((468, 3), dtype=np.float32), score=1.0)++ assert a == a+ assert a != b # identity, not value semantics+ assert hash(a) is not None+++# Iris landmarks — indexed through the shared constants, MediaPipe's own convention+def test_iris_slices_cover_the_extra_points(mesher, mock_image, mock_bbox):+ """The 478-point model appends exactly the two irises after the mesh."""+ result = mesher.predict(mock_image, bboxes=[mock_bbox])[0]++ if mesher.num_landmarks == NUM_MESH_LANDMARKS:+ assert result.landmarks[IRIS_LEFT].shape == (0, 3) # nothing past the mesh+ return++ assert result.landmarks[IRIS_LEFT].shape == (5, 3)+ assert result.landmarks[IRIS_RIGHT].shape == (5, 3)+ assert len(result.landmarks) == NUM_MESH_LANDMARKS + 10+++ ('label', 'bad_image'),+ [+ ('float [0, 1]', np.random.rand(640, 640, 3).astype(np.float32)),+ ('grayscale', np.zeros((640, 640), dtype=np.uint8)),+ ('empty', np.zeros((0, 0, 3), dtype=np.uint8)),+ ],+)+def test_predict_rejects_unusable_images(mesher, mock_bbox, label, bad_image):+ """`preprocess` divides by 255, so a float image would silently mesh garbage."""+ with pytest.raises(ValueError):+ mesher.predict(bad_image, bboxes=[mock_bbox])+++def test_get_landmarks_rejects_unusable_images(mesher, mock_bbox):+ """The score that would flag the bad input is dropped on this path."""+ with pytest.raises(ValueError, match='uint8'):+ mesher.get_landmarks(np.random.rand(640, 640, 3).astype(np.float32), mock_bbox)+++def test_iris_constants_are_contiguous_and_ordered():+ """468-472 then 473-477, with no gap and no overlap."""+ assert (IRIS_LEFT.start, IRIS_LEFT.stop) == (NUM_MESH_LANDMARKS, NUM_MESH_LANDMARKS + 5)+ assert (IRIS_RIGHT.start, IRIS_RIGHT.stop) == (NUM_MESH_LANDMARKS + 5, NUM_MESH_LANDMARKS + 10)+++def test_irises_sit_inside_the_face(mesher, mock_image, mock_bbox, mock_keypoints):+ """Catches an off-by-one in the slice or a bad inverse transform."""+ if mesher.num_landmarks == NUM_MESH_LANDMARKS:+ pytest.skip('468-point model has no irises')++ result = mesher.predict(mock_image, bboxes=[mock_bbox], keypoints=[mock_keypoints])[0]+ mesh = result.landmarks[:NUM_MESH_LANDMARKS, :2]++ for iris in (result.landmarks[IRIS_LEFT], result.landmarks[IRIS_RIGHT]):+ assert np.all(iris[:, 0] > mesh[:, 0].min()) and np.all(iris[:, 0] < mesh[:, 0].max())+ assert np.all(iris[:, 1] > mesh[:, 1].min()) and np.all(iris[:, 1] < mesh[:, 1].max())diff --git a/tests/test_model_store.py b/tests/test_model_store.pynew file mode 100644index 0000000..369dde9--- /dev/null+++ b/tests/test_model_store.py@@ -0,0 +1,94 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo+++from __future__ import annotations++from enum import Enum+import os++import pytest++from uniface import model_store+import uniface.constants as const+from uniface.model_store import _mirror_url, verify_model_weights+++def model():+ """A registry entry to exercise source resolution against."""+ return const.BlazeFaceWeights.DEFAULT+++class TestMirrorUrl:+ """Mirror URL construction."""++ def test_mirror_url_shape(self, model):+ """Assert the literal URL, so a wrong repo id or revision fails the test."""+ assert _mirror_url(model, const.MODEL_REGISTRY[model].url) == (+ 'https://huggingface.co/yakhyo/uniface-weights/resolve/'+ '4c7ed723a20deb7ff154b1ba7d6e73747d954016/blazeface.onnx'+ )++ def test_extension_follows_primary_url(self, model):+ """Not every weight is ONNX; the mirror must not hardcode the extension."""+ assert _mirror_url(model, 'https://example.com/x/affecnet7.script').endswith(f'/{model.value}.script')++ def test_mirror_names_unique_across_registry(self):+ """A basename-keyed mirror would collide; enum values are the only unique key."""+ mirrors = [_mirror_url(k, v.url) for k, v in const.MODEL_REGISTRY.items()]+ assert len(set(mirrors)) == len(const.MODEL_REGISTRY)+++class TestFallback:+ """Failover behaviour across sources, with no network access."""++ def test_falls_back_to_second_source(self, model, tmp_path, monkeypatch):+ attempted = []++ def fake_download(url, dest_path, **kwargs):+ attempted.append(url)+ if len(attempted) == 1:+ raise ConnectionError('primary unreachable')+ with open(dest_path, 'wb') as f:+ f.write(b'weights')++ monkeypatch.setattr(model_store, 'download_file', fake_download)+ monkeypatch.setitem(const.MODEL_REGISTRY, model, const.ModelInfo(url='https://gh.invalid/a.onnx', sha256=''))++ path = verify_model_weights(model, root=str(tmp_path))+ assert len(attempted) == 2+ assert attempted[1].startswith(const.HF_MIRROR_URL)+ assert os.path.exists(path)++ def test_no_fallback_when_primary_succeeds(self, model, tmp_path, monkeypatch):+ attempted = []++ def fake_download(url, dest_path, **kwargs):+ attempted.append(url)+ with open(dest_path, 'wb') as f:+ f.write(b'weights')++ monkeypatch.setattr(model_store, 'download_file', fake_download)+ monkeypatch.setitem(const.MODEL_REGISTRY, model, const.ModelInfo(url='https://gh.invalid/a.onnx', sha256=''))++ verify_model_weights(model, root=str(tmp_path))+ assert attempted == ['https://gh.invalid/a.onnx']++ def test_all_sources_failing_raises(self, model, tmp_path, monkeypatch):+ def fake_download(url, dest_path, **kwargs):+ raise ConnectionError('unreachable')++ monkeypatch.setattr(model_store, 'download_file', fake_download)+ monkeypatch.setitem(const.MODEL_REGISTRY, model, const.ModelInfo(url='https://gh.invalid/a.onnx', sha256=''))++ with pytest.raises(ConnectionError, match='GH Releases and HF Mirror'):+ verify_model_weights(model, root=str(tmp_path))++ def test_unknown_model_still_raises_value_error(self, tmp_path):+ class Bogus(str, Enum):+ X = 'bogus'++ with pytest.raises(ValueError, match='Unknown model identifier'):+ verify_model_weights(Bogus.X, root=str(tmp_path))diff --git a/tests/test_recognition.py b/tests/test_recognition.pyindex 0e3b33b..f68730d 100644--- a/tests/test_recognition.py+++ b/tests/test_recognition.py@@ -13,25 +13,19 @@ from uniface.recognition import ArcFace, EdgeFace, MobileFace, SphereFace@pytest.fixturedef arcface_model():- """- Fixture to initialize the ArcFace model for testing.- """+ """Fixture to initialize the ArcFace model for testing."""return ArcFace()@pytest.fixturedef mobileface_model():- """- Fixture to initialize the MobileFace model for testing.- """+ """Fixture to initialize the MobileFace model for testing."""return MobileFace()@pytest.fixturedef sphereface_model():- """- Fixture to initialize the SphereFace model for testing.- """+ """Fixture to initialize the SphereFace model for testing."""return SphereFace()@@ -43,17 +37,13 @@ def edgeface_model():@pytest.fixturedef mock_aligned_face():- """- Create a mock 112x112 aligned face image.- """+ """Create a mock 112x112 aligned face image."""return np.random.randint(0, 255, (112, 112, 3), dtype=np.uint8)@pytest.fixturedef mock_landmarks():- """- Create mock 5-point facial landmarks.- """+ """Create mock 5-point facial landmarks."""return np.array([[38.2946, 51.6963],@@ -68,16 +58,12 @@ def mock_landmarks():# ArcFace Testsdef test_arcface_initialization(arcface_model):- """- Test that the ArcFace model initializes correctly.- """+ """Test that the ArcFace model initializes correctly."""assert arcface_model is not None, 'ArcFace model initialization failed.'def test_arcface_embedding_shape(arcface_model, mock_aligned_face):- """- Test that ArcFace produces embeddings with the correct shape.- """+ """Test that ArcFace produces embeddings with the correct shape."""embedding = arcface_model.get_embedding(mock_aligned_face)# ArcFace get_embedding returns raw ONNX output with batch dimension@@ -86,9 +72,7 @@ def test_arcface_embedding_shape(arcface_model, mock_aligned_face):def test_arcface_normalized_embedding(arcface_model, mock_landmarks):- """- Test that normalized embeddings have unit length.- """+ """Test that normalized embeddings have unit length."""# Create a larger mock image for alignmentmock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)@@ -101,17 +85,13 @@ def test_arcface_normalized_embedding(arcface_model, mock_landmarks):def test_arcface_embedding_dtype(arcface_model, mock_aligned_face):- """- Test that embeddings have the correct data type.- """+ """Test that embeddings have the correct data type."""embedding = arcface_model.get_embedding(mock_aligned_face)assert embedding.dtype == np.float32, f'Expected float32, got {embedding.dtype}'def test_arcface_consistency(arcface_model, mock_aligned_face):- """- Test that the same input produces the same embedding.- """+ """Test that the same input produces the same embedding."""embedding1 = arcface_model.get_embedding(mock_aligned_face)embedding2 = arcface_model.get_embedding(mock_aligned_face)@@ -120,16 +100,12 @@ def test_arcface_consistency(arcface_model, mock_aligned_face):# MobileFace Testsdef test_mobileface_initialization(mobileface_model):- """- Test that the MobileFace model initializes correctly.- """+ """Test that the MobileFace model initializes correctly."""assert mobileface_model is not None, 'MobileFace model initialization failed.'def test_mobileface_embedding_shape(mobileface_model, mock_aligned_face):- """- Test that MobileFace produces embeddings with the correct shape.- """+ """Test that MobileFace produces embeddings with the correct shape."""embedding = mobileface_model.get_embedding(mock_aligned_face)# MobileFace get_embedding returns raw ONNX output with batch dimension@@ -138,9 +114,7 @@ def test_mobileface_embedding_shape(mobileface_model, mock_aligned_face):def test_mobileface_normalized_embedding(mobileface_model, mock_landmarks):- """- Test that MobileFace normalized embeddings have unit length.- """+ """Test that MobileFace normalized embeddings have unit length."""mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)embedding = mobileface_model.get_normalized_embedding(mock_image, mock_landmarks)@@ -152,16 +126,12 @@ def test_mobileface_normalized_embedding(mobileface_model, mock_landmarks):# SphereFace Testsdef test_sphereface_initialization(sphereface_model):- """- Test that the SphereFace model initializes correctly.- """+ """Test that the SphereFace model initializes correctly."""assert sphereface_model is not None, 'SphereFace model initialization failed.'def test_sphereface_embedding_shape(sphereface_model, mock_aligned_face):- """- Test that SphereFace produces embeddings with the correct shape.- """+ """Test that SphereFace produces embeddings with the correct shape."""embedding = sphereface_model.get_embedding(mock_aligned_face)# SphereFace get_embedding returns raw ONNX output with batch dimension@@ -170,9 +140,7 @@ def test_sphereface_embedding_shape(sphereface_model, mock_aligned_face):def test_sphereface_normalized_embedding(sphereface_model, mock_landmarks):- """- Test that SphereFace normalized embeddings have unit length.- """+ """Test that SphereFace normalized embeddings have unit length."""mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)embedding = sphereface_model.get_normalized_embedding(mock_image, mock_landmarks)@@ -223,9 +191,7 @@ def test_edgeface_consistency(edgeface_model, mock_aligned_face):# Cross-model comparison testsdef test_different_models_different_embeddings(arcface_model, mobileface_model, mock_aligned_face):- """- Test that different models produce different embeddings for the same input.- """+ """Test that different models produce different embeddings for the same input."""arcface_emb = arcface_model.get_embedding(mock_aligned_face)mobileface_emb = mobileface_model.get_embedding(mock_aligned_face)@@ -235,9 +201,7 @@ def test_different_models_different_embeddings(arcface_model, mobileface_model,def test_embedding_similarity_computation(arcface_model, mock_aligned_face):- """- Test computing similarity between embeddings.- """+ """Test computing similarity between embeddings."""# Get two embeddingsemb1 = arcface_model.get_embedding(mock_aligned_face)@@ -256,9 +220,7 @@ def test_embedding_similarity_computation(arcface_model, mock_aligned_face):def test_same_face_high_similarity(arcface_model, mock_aligned_face):- """- Test that the same face produces high similarity.- """+ """Test that the same face produces high similarity."""emb1 = arcface_model.get_embedding(mock_aligned_face)emb2 = arcface_model.get_embedding(mock_aligned_face)diff --git a/tests/test_types.py b/tests/test_types.pyindex 3ef6bcb..fc902d0 100644--- a/tests/test_types.py+++ b/tests/test_types.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport numpy as npimport pytest-from uniface.types import AttributeResult, EmotionResult, Face, GazeResult, SpoofingResult+from uniface.types import DemographyResult, EmotionResult, Face, GazeResult, SpoofingResultclass TestGazeResult:@@ -112,11 +112,11 @@ class TestEmotionResult:hash(result)-class TestAttributeResult:- """Tests for AttributeResult dataclass."""+class TestDemographyResult:+ """Tests for DemographyResult dataclass."""def test_age_gender_result(self):- result = AttributeResult(gender=1, age=25)+ result = DemographyResult(gender=1, age=25)assert result.gender == 1assert result.age == 25assert result.age_group is None@@ -124,7 +124,7 @@ class TestAttributeResult:assert result.sex == 'Male'def test_fairface_result(self):- result = AttributeResult(gender=0, age_group='20-29', race='East Asian')+ result = DemographyResult(gender=0, age_group='20-29', race='East Asian')assert result.gender == 0assert result.age is Noneassert result.age_group == '20-29'@@ -132,34 +132,34 @@ class TestAttributeResult:assert result.sex == 'Female'def test_sex_property_female(self):- result = AttributeResult(gender=0)+ result = DemographyResult(gender=0)assert result.sex == 'Female'def test_sex_property_male(self):- result = AttributeResult(gender=1)+ result = DemographyResult(gender=1)assert result.sex == 'Male'def test_immutability(self):- result = AttributeResult(gender=1, age=30)+ result = DemographyResult(gender=1, age=30)with pytest.raises(AttributeError):result.age = 31 # type: ignoredef test_repr_age_gender(self):- result = AttributeResult(gender=1, age=25)+ result = DemographyResult(gender=1, age=25)repr_str = repr(result)- assert 'AttributeResult' in repr_str+ assert 'DemographyResult' in repr_strassert 'Male' in repr_strassert 'age=25' in repr_strdef test_repr_fairface(self):- result = AttributeResult(gender=0, age_group='30-39', race='White')+ result = DemographyResult(gender=0, age_group='30-39', race='White')repr_str = repr(result)assert 'Female' in repr_strassert 'age_group=30-39' in repr_strassert 'race=White' in repr_strdef test_hashable(self):- result = AttributeResult(gender=1, age=25)+ result = DemographyResult(gender=1, age=25)hash(result)@@ -239,6 +239,29 @@ class TestFace:assert 'sex=Male' in repr_strassert 'emotion=Happy' in repr_str+ _FACE_STATES = ('left_eye_open', 'right_eye_open', 'eyeglasses', 'mask', 'sunglasses')++ @pytest.mark.parametrize('name', _FACE_STATES)+ def test_repr_with_a_single_face_state(self, sample_face, name):+ """Each of the five is optional on its own; __repr__ must never raise."""+ setattr(sample_face, name, 0.75)++ repr_str = repr(sample_face)++ assert f'{name}=0.75' in repr_str+ assert all(other not in repr_str for other in self._FACE_STATES if other != name)++ def test_repr_with_all_face_states(self, sample_face):+ for idx, name in enumerate(self._FACE_STATES):+ setattr(sample_face, name, idx / 10)++ repr_str = repr(sample_face)++ assert 'left_eye_open=0.00, right_eye_open=0.10, eyeglasses=0.20, mask=0.30, sunglasses=0.40' in repr_str++ def test_repr_omits_face_states_when_unset(self, sample_face):+ assert all(name not in repr(sample_face) for name in self._FACE_STATES)+def test_compute_similarity_no_embeddings(self, sample_face):other_face = Face(bbox=np.array([50, 50, 150, 150]),diff --git a/tests/test_utils.py b/tests/test_utils.pyindex 365c59a..1288e66 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -9,20 +9,19 @@ import numpy as npimport pytestfrom uniface import compute_similarity, face_alignment+from uniface.face_utils import estimate_norm@pytest.fixturedef mock_image():- """- Create a mock 640x640 BGR image.- """+ """Create a mock 640x640 BGR image."""return np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)@pytest.fixturedef mock_landmarks():- """- Create mock 5-point facial landmarks.+ """Create mock 5-point facial landmarks.+Standard positions for a face roughly centered at (112/2, 112/2)."""return np.array(@@ -39,9 +38,7 @@ def mock_landmarks():# compute_similarity testsdef test_compute_similarity_same_embedding():- """- Test that similarity of an embedding with itself is 1.0.- """+ """Test that similarity of an embedding with itself is 1.0."""embedding = np.random.randn(1, 512).astype(np.float32)embedding = embedding / np.linalg.norm(embedding) # Normalize@@ -50,9 +47,7 @@ def test_compute_similarity_same_embedding():def test_compute_similarity_range():- """- Test that similarity is always in the range [-1, 1].- """+ """Test that similarity is always in the range [-1, 1]."""# Test with multiple random embeddingsfor _ in range(10):emb1 = np.random.randn(1, 512).astype(np.float32)@@ -67,9 +62,7 @@ def test_compute_similarity_range():def test_compute_similarity_orthogonal():- """- Test that orthogonal embeddings have similarity close to 0.- """+ """Test that orthogonal embeddings have similarity close to 0."""# Create orthogonal embeddingsemb1 = np.zeros((1, 512), dtype=np.float32)emb1[0, 0] = 1.0 # [1, 0, 0, ..., 0]@@ -82,9 +75,7 @@ def test_compute_similarity_orthogonal():def test_compute_similarity_opposite():- """- Test that opposite embeddings have similarity close to -1.- """+ """Test that opposite embeddings have similarity close to -1."""emb1 = np.ones((1, 512), dtype=np.float32)emb1 = emb1 / np.linalg.norm(emb1)@@ -95,9 +86,7 @@ def test_compute_similarity_opposite():def test_compute_similarity_symmetry():- """- Test that similarity(A, B) == similarity(B, A).- """+ """Test that similarity(A, B) == similarity(B, A)."""emb1 = np.random.randn(1, 512).astype(np.float32)emb2 = np.random.randn(1, 512).astype(np.float32)@@ -112,9 +101,7 @@ def test_compute_similarity_symmetry():def test_compute_similarity_dtype():- """- Test that compute_similarity returns a float.- """+ """Test that compute_similarity returns a float."""emb1 = np.random.randn(1, 512).astype(np.float32)emb2 = np.random.randn(1, 512).astype(np.float32)@@ -128,27 +115,21 @@ def test_compute_similarity_dtype():# face_alignment testsdef test_face_alignment_output_shape(mock_image, mock_landmarks):- """- Test that face_alignment produces output with the correct shape.- """+ """Test that face_alignment produces output with the correct shape."""aligned, _ = face_alignment(mock_image, mock_landmarks, image_size=(112, 112))assert aligned.shape == (112, 112, 3), f'Expected shape (112, 112, 3), got {aligned.shape}'def test_face_alignment_dtype(mock_image, mock_landmarks):- """- Test that aligned face has the correct data type.- """+ """Test that aligned face has the correct data type."""aligned, _ = face_alignment(mock_image, mock_landmarks, image_size=(112, 112))assert aligned.dtype == np.uint8, f'Expected uint8, got {aligned.dtype}'def test_face_alignment_different_sizes(mock_image, mock_landmarks):- """- Test face alignment with different output sizes.- """+ """Test face alignment with different output sizes."""# Only test sizes that are multiples of 112 or 128 as required by the functiontest_sizes = [(112, 112), (128, 128), (224, 224)]@@ -158,9 +139,7 @@ def test_face_alignment_different_sizes(mock_image, mock_landmarks):def test_face_alignment_consistency(mock_image, mock_landmarks):- """- Test that the same input produces the same aligned face.- """+ """Test that the same input produces the same aligned face."""aligned1, _ = face_alignment(mock_image, mock_landmarks, image_size=(112, 112))aligned2, _ = face_alignment(mock_image, mock_landmarks, image_size=(112, 112))@@ -168,9 +147,7 @@ def test_face_alignment_consistency(mock_image, mock_landmarks):def test_face_alignment_landmarks_as_list(mock_image):- """- Test that landmarks can be passed as a list of lists (converted to array).- """+ """Test that landmarks can be passed as a list of lists (converted to array)."""landmarks_list = [[38.2946, 51.6963],[73.5318, 51.5014],@@ -186,9 +163,7 @@ def test_face_alignment_landmarks_as_list(mock_image):def test_face_alignment_value_range(mock_image, mock_landmarks):- """- Test that aligned face pixel values are in valid range [0, 255].- """+ """Test that aligned face pixel values are in valid range [0, 255]."""aligned, _ = face_alignment(mock_image, mock_landmarks, image_size=(112, 112))assert np.all(aligned >= 0), 'Pixel values should be >= 0'@@ -196,9 +171,7 @@ def test_face_alignment_value_range(mock_image, mock_landmarks):def test_face_alignment_not_all_zeros(mock_image, mock_landmarks):- """- Test that aligned face is not all zeros (actual transformation occurred).- """+ """Test that aligned face is not all zeros (actual transformation occurred)."""aligned, _ = face_alignment(mock_image, mock_landmarks, image_size=(112, 112))# At least some pixels should be non-zero@@ -206,9 +179,7 @@ def test_face_alignment_not_all_zeros(mock_image, mock_landmarks):def test_face_alignment_from_different_positions(mock_image):- """- Test alignment with landmarks at different positions in the image.- """+ """Test alignment with landmarks at different positions in the image."""# Landmarks at different positionspositions = [np.array(@@ -231,9 +202,7 @@ def test_face_alignment_from_different_positions(mock_image):def test_face_alignment_landmark_count(mock_image):- """- Test that face_alignment works specifically with 5-point landmarks.- """+ """Test that face_alignment works specifically with 5-point landmarks."""# Standard 5-point landmarkslandmarks_5pt = np.array([@@ -251,9 +220,7 @@ def test_face_alignment_landmark_count(mock_image):def test_compute_similarity_with_recognition_embeddings():- """- Test compute_similarity with realistic embedding dimensions.- """+ """Test compute_similarity with realistic embedding dimensions."""# Simulate ArcFace/MobileFace/SphereFace embeddings (512-dim)emb1 = np.random.randn(1, 512).astype(np.float32)emb2 = np.random.randn(1, 512).astype(np.float32)@@ -267,3 +234,36 @@ def test_compute_similarity_with_recognition_embeddings():# Should be a valid similarity scoreassert -1.0 <= similarity <= 1.0assert isinstance(similarity, float | np.floating)+++# estimate_norm landmark-count validation+def test_estimate_norm_accepts_five_points(mock_landmarks):+ """estimate_norm should accept the 5-point alignment template."""+ matrix, inverse_matrix = estimate_norm(mock_landmarks)++ assert matrix.shape == (2, 3)+ assert inverse_matrix.shape == (2, 3)+++def test_estimate_norm_rejects_six_points():+ """A 6-keypoint layout (e.g. BlazeFace) cannot be fitted to the alignment template.++ Must raise ValueError, not AssertionError: asserts are stripped under `python -O`,+ which would let the mismatch fall through to an opaque scikit-image matmul error.+ """+ six_points = np.zeros((6, 2), dtype=np.float32)++ with pytest.raises(ValueError, match='requires 5 alignment landmarks'):+ estimate_norm(six_points)+++def test_estimate_norm_error_names_the_constraint():+ """The error should tell the caller which detectors are unusable and why."""+ with pytest.raises(ValueError, match='supports_alignment'):+ estimate_norm(np.zeros((3, 2), dtype=np.float32))+++def test_face_alignment_rejects_six_points(mock_image):+ """The rejection should propagate through face_alignment, the public entry point."""+ with pytest.raises(ValueError, match='requires 5 alignment landmarks'):+ face_alignment(mock_image, np.zeros((6, 2), dtype=np.float32))diff --git a/tools/README.md b/tools/README.mdindex b4e5107..dd5f81b 100644--- a/tools/README.md+++ b/tools/README.md@@ -14,11 +14,13 @@ CLI utilities for testing and running UniFace features.| `gaze.py` | Gaze direction estimation || `headpose.py` | Head pose estimation (pitch, yaw, roll) || `landmarks.py` | 106-point facial landmark detection |+| `facemesh.py` | 468 / 478-point dense 3D face mesh (MediaPipe), irises with `--model v2_478` || `recognize.py` | Face embedding extraction and comparison || `search.py` | Real-time face matching against reference || `faiss_search.py` | FAISS index build and multi-identity face search || `fairface.py` | FairFace attribute prediction (race, gender, age) || `attribute.py` | Age and gender prediction |+| `facestate.py` | Face states (eye openness, glasses, mask, sunglasses) with FaceAttribNet || `spoofing.py` | Face anti-spoofing detection || `quality.py` | Face image quality assessment (eDifFIQA) || `parse.py` | Face semantic segmentation (BiSeNet) |@@ -60,6 +62,11 @@ python tools/attribute.py --source 0python tools/emotion.py --source assets/test.jpgpython tools/emotion.py --source 0+# Face states (eye openness, glasses, mask, sunglasses)+python tools/facestate.py --source assets/test.jpg+python tools/facestate.py --source 0+python tools/facestate.py --source assets/test.jpg --threshold 0.7 --margin 0.1+# Gaze estimationpython tools/gaze.py --source assets/test.jpgpython tools/gaze.py --source 0@@ -73,6 +80,12 @@ python tools/headpose.py --source 0 --draw-type axispython tools/landmarks.py --source assets/test.jpgpython tools/landmarks.py --source 0+# Face mesh (468 / 478-point dense 3D)+python tools/facemesh.py --source assets/test.jpg+python tools/facemesh.py --source 0 --mode points+python tools/facemesh.py --source assets/test.jpg --detector blazeface # MediaPipe parity+python tools/facemesh.py --source 0 --model v2_478 --mode points # with irises+# FairFace attributespython tools/fairface.py --source assets/test.jpgpython tools/fairface.py --source 0@@ -121,7 +134,7 @@ python tools/download_model.py # downloads all| Option | Description ||--------|-------------|| `--source` | Input source: image/video path or camera ID (0, 1, ...) |-| `--detector` | Choose detector: `retinaface`, `scrfd`, `yolov5face`, `yolov8face` |+| `--detector` | Choose detector: `retinaface`, `scrfd`, `centerface`, `blazeface`, `yolov5face`, `yolov8face` || `--threshold` | Visualization confidence threshold (default: varies) || `--save-dir` | Output directory (default: `outputs`) |diff --git a/tools/analyze.py b/tools/analyze.pyindex 06db786..506e40c 100644--- a/tools/analyze.py+++ b/tools/analyze.py@@ -197,7 +197,7 @@ def main():detector = RetinaFace()recognizer = ArcFace()age_gender = AgeGender()- analyzer = FaceAnalyzer(detector, recognizer=recognizer, attributes=[age_gender])+ analyzer = FaceAnalyzer(detector=detector, recognizer=recognizer, predictors=[age_gender])source_type = get_source_type(args.source)diff --git a/tools/anonymize.py b/tools/anonymize.pyindex 9ae5e6a..92fec76 100644--- a/tools/anonymize.py+++ b/tools/anonymize.py@@ -219,11 +219,11 @@ Examples:args = parser.parse_args()- # Parse color+ # The CLI takes R,G,B but BlurFace expects BGRcolor_values = [int(x) for x in args.color.split(',')]if len(color_values) != 3:parser.error('--color must be in format R,G,B (e.g., 0,0,0)')- color = tuple(color_values)+ color = tuple(reversed(color_values))# Initialize detectorprint(f'Initializing face detector (confidence_threshold={args.confidence_threshold})...')diff --git a/tools/detect.py b/tools/detect.pyindex 80640d6..b52b66e 100644--- a/tools/detect.py+++ b/tools/detect.py@@ -22,16 +22,25 @@ from _common import get_source_typeimport cv2from tqdm import tqdm-from uniface.constants import RetinaFaceWeights, SCRFDWeights, YOLOv5FaceWeights, YOLOv8FaceWeights-from uniface.detection import SCRFD, RetinaFace, YOLOv5Face, YOLOv8Face+from uniface.constants import (+ BlazeFaceWeights,+ CenterFaceWeights,+ RetinaFaceWeights,+ SCRFDWeights,+ YOLOv5FaceWeights,+ YOLOv8FaceWeights,+)+from uniface.detection import SCRFD, BlazeFace, CenterFace, RetinaFace, YOLOv5Face, YOLOv8Facefrom uniface.draw import draw_detections# detector name -> (class, weights enum, default weights)DETECTORS = {'retinaface': (RetinaFace, RetinaFaceWeights, RetinaFaceWeights.MNET_V2),'scrfd': (SCRFD, SCRFDWeights, SCRFDWeights.SCRFD_10G_KPS),+ 'centerface': (CenterFace, CenterFaceWeights, CenterFaceWeights.DEFAULT),'yolov5face': (YOLOv5Face, YOLOv5FaceWeights, YOLOv5FaceWeights.YOLOV5M),'yolov8face': (YOLOv8Face, YOLOv8FaceWeights, YOLOv8FaceWeights.YOLOV8N),+ 'blazeface': (BlazeFace, BlazeFaceWeights, BlazeFaceWeights.DEFAULT),}diff --git a/tools/download_model.py b/tools/download_model.pyindex 1b1f1b5..bbc6e3e 100644--- a/tools/download_model.py+++ b/tools/download_model.py@@ -4,8 +4,8 @@ from uniface.constants import (AdaFaceWeights,AgeGenderWeights,ArcFaceWeights,- DDAMFNWeights,EdgeFaceWeights,+ EmotionWeights,HeadPoseWeights,LandmarkWeights,MobileFaceWeights,@@ -23,7 +23,7 @@ MODEL_TYPES = {'mobileface': MobileFaceWeights,'sphereface': SphereFaceWeights,'scrfd': SCRFDWeights,- 'ddamfn': DDAMFNWeights,+ 'ddamfn': EmotionWeights,'agegender': AgeGenderWeights,'landmark': LandmarkWeights,'headpose': HeadPoseWeights,diff --git a/tools/facemesh.py b/tools/facemesh.pynew file mode 100644index 0000000..9a80ade--- /dev/null+++ b/tools/facemesh.py@@ -0,0 +1,175 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++"""Dense 3D face mesh (MediaPipe): 468 landmarks, or 478 with irises.++Usage:+ python tools/facemesh.py --source path/to/image.jpg+ python tools/facemesh.py --source path/to/video.mp4 --mode points+ python tools/facemesh.py --source 0 # webcam+ python tools/facemesh.py --source image.jpg --detector blazeface # MediaPipe parity+ python tools/facemesh.py --source 0 --model v2_478 # with iris landmarks+"""++from __future__ import annotations++import argparse+import os+from pathlib import Path++from _common import get_source_type+import cv2++from uniface.constants import FaceMeshWeights+from uniface.detection import SCRFD, BlazeFace, RetinaFace+from uniface.draw import draw_mesh+from uniface.landmark import FaceMesh++DETECTORS = {'scrfd': SCRFD, 'retinaface': RetinaFace, 'blazeface': BlazeFace}+MODELS = {w.name.lower(): w for w in FaceMeshWeights}+++def annotate(image, detector, mesher, mode: str) -> int:+ """Detect, mesh, and draw every face. Returns the number of faces found."""+ faces = detector.detect(image)+ if not faces:+ return 0++ # One batched inference for every face in the frame.+ for result in mesher.predict(image, faces):+ draw_mesh(image, result.landmarks, mode=mode)++ return len(faces)+++def process_image(detector, mesher, image_path: str, mode: str, save_dir: str = 'outputs'):+ """Process a single image."""+ image = cv2.imread(image_path)+ if image is None:+ print(f"Error: Failed to load image from '{image_path}'")+ return++ faces = detector.detect(image)+ print(f'Detected {len(faces)} face(s)')++ if faces:+ results = mesher.predict(image, faces)+ for i, result in enumerate(results):+ print(f' Face {i + 1}: {result.landmarks.shape[0]} landmarks, presence {result.score:.3f}')+ draw_mesh(image, result.landmarks, mode=mode)++ os.makedirs(save_dir, exist_ok=True)+ output_path = os.path.join(save_dir, f'{Path(image_path).stem}_facemesh.jpg')+ cv2.imwrite(output_path, image)+ print(f'Output saved: {output_path}')+++def process_video(detector, mesher, video_path: str, mode: str, save_dir: str = 'outputs'):+ """Process a video file."""+ cap = cv2.VideoCapture(video_path)+ if not cap.isOpened():+ print(f"Error: Cannot open video file '{video_path}'")+ return++ fps = cap.get(cv2.CAP_PROP_FPS)+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))++ os.makedirs(save_dir, exist_ok=True)+ output_path = os.path.join(save_dir, f'{Path(video_path).stem}_facemesh.mp4')+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')+ out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))++ print(f'Processing video: {video_path} ({total_frames} frames)')+ frame_count = 0++ while True:+ ret, frame = cap.read()+ if not ret:+ break++ frame_count += 1+ num_faces = annotate(frame, detector, mesher, mode)++ cv2.putText(frame, f'Faces: {num_faces}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)+ out.write(frame)++ if frame_count % 100 == 0:+ print(f' Processed {frame_count}/{total_frames} frames...')++ cap.release()+ out.release()+ print(f'Done! Output saved: {output_path}')+++def run_camera(detector, mesher, mode: str, camera_id: int = 0):+ """Run real-time face mesh on webcam."""+ cap = cv2.VideoCapture(camera_id)+ if not cap.isOpened():+ print(f'Cannot open camera {camera_id}')+ return++ print("Press 'q' to quit")++ while True:+ ret, frame = cap.read()+ if not ret:+ break+ frame = cv2.flip(frame, 1)++ num_faces = annotate(frame, detector, mesher, mode)++ cv2.putText(frame, f'Faces: {num_faces}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)+ cv2.imshow(f'Face Mesh ({mesher.num_landmarks} points)', frame)++ if cv2.waitKey(1) & 0xFF == ord('q'):+ break++ cap.release()+ cv2.destroyAllWindows()+++def main():+ parser = argparse.ArgumentParser(description='Run dense 3D face mesh (468 or 478 landmarks)')+ parser.add_argument('--source', type=str, required=True, help='Image/video path or camera ID (0, 1, ...)')+ parser.add_argument(+ '--detector',+ type=str,+ default='scrfd',+ choices=list(DETECTORS),+ help="Seed detector. 'blazeface' reproduces MediaPipe's own pipeline.",+ )+ parser.add_argument(+ '--mode',+ type=str,+ default='partial',+ choices=['full', 'partial', 'points'],+ help="Render style. 'full' is the dense tessellation and is slow for video.",+ )+ parser.add_argument(+ '--model',+ type=str,+ default='v1_468',+ choices=list(MODELS),+ help="'v1_468' is the classic mesh; 'v2_478' adds iris landmarks at ~3x the compute.",+ )+ parser.add_argument('--save-dir', type=str, default='outputs', help='Output directory')+ args = parser.parse_args()++ detector = DETECTORS[args.detector]()+ mesher = FaceMesh(model_name=MODELS[args.model])++ source_type = get_source_type(args.source)++ if source_type == 'camera':+ run_camera(detector, mesher, args.mode, int(args.source))+ elif source_type == 'video':+ process_video(detector, mesher, args.source, args.mode, args.save_dir)+ else:+ process_image(detector, mesher, args.source, args.mode, args.save_dir)+++if __name__ == '__main__':+ main()diff --git a/tools/facestate.py b/tools/facestate.pynew file mode 100644index 0000000..6def1a1--- /dev/null+++ b/tools/facestate.py@@ -0,0 +1,220 @@+# Copyright 2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++"""Face state prediction on detected faces with FaceAttribNet.++Predicts five independent binary attributes per face: left/right eye openness,+eyeglasses, face mask, and sunglasses. Each probability comes from its own+classifier head, so several can be high at once; each is thresholded separately.++Usage:+ python tools/facestate.py --source path/to/image.jpg+ python tools/facestate.py --source path/to/video.mp4+ python tools/facestate.py --source 0 # webcam+"""++from __future__ import annotations++import argparse+import os+from pathlib import Path++from _common import get_source_type+import cv2++from uniface.attribute import FaceAttribNet+from uniface.detection import SCRFD, RetinaFace+from uniface.types import FaceStateResult++INK, GREEN, RED = (55, 41, 31), (45, 128, 21), (28, 28, 185) # BGR+++def draw_face_states(image, bbox, result: FaceStateResult, threshold: float = 0.5) -> None:+ """Draw a face bounding box and a True/False panel for every attribute.++ The panel is placed above the box when there is room, otherwise inside it.+ Panel size scales with the box width so it stays readable on both small+ and large faces.++ Args:+ image: Image to annotate in-place (BGR).+ bbox: Face bounding box [x1, y1, x2, y2].+ result: Predicted per-attribute probabilities.+ threshold: Probability above which an attribute counts as present.+ """+ x1, y1, x2, y2 = (int(v) for v in bbox[:4])+ cv2.rectangle(image, (x1, y1), (x2, y2), (255, 255, 255), 2)++ probs = result.as_dict()++ def tf(prob: float) -> tuple[str, tuple[int, int, int]]:+ return ('True', GREEN) if prob > threshold else ('False', RED)++ rows = [+ [('Eyes ', INK), tf(probs['left_eye_open']), (', ', INK), tf(probs['right_eye_open'])],+ [('Mask ', INK), tf(probs['mask'])],+ [('Glasses ', INK), tf(probs['eyeglasses'])],+ [('Sunglasses ', INK), tf(probs['sunglasses'])],+ ]+ font = cv2.FONT_HERSHEY_SIMPLEX+ scale = max(0.5, min(1.6, (x2 - x1) / 350))+ thickness = 1 if scale < 0.7 else 2+ line_h, pad = int(38 * scale), int(8 * scale)++ panel_w = max(sum(cv2.getTextSize(t, font, scale, thickness)[0][0] for t, _ in row) for row in rows)+ panel_h = len(rows) * line_h + pad+ y_top = y1 - panel_h - pad if y1 - panel_h - pad >= 0 else y1 + pad # above the box, else inside it+ cv2.rectangle(image, (x1, y_top), (x1 + panel_w + 2 * pad, y_top + panel_h), (255, 255, 255), -1)+ for i, row in enumerate(rows):+ x, y = x1 + pad, y_top + (i + 1) * line_h - int(6 * scale)+ for text, color in row:+ cv2.putText(image, text, (x, y), font, scale, color, thickness, cv2.LINE_AA)+ x += cv2.getTextSize(text, font, scale, thickness)[0][0]+++def process_image(+ detector,+ face_attrib,+ image_path: str,+ save_dir: str = 'outputs',+ threshold: float = 0.5,+):+ """Process a single image."""+ image = cv2.imread(image_path)+ if image is None:+ print(f"Error: Failed to load image from '{image_path}'")+ return++ faces = detector.detect(image)+ print(f'Detected {len(faces)} face(s)')++ if not faces:+ return++ for i, face in enumerate(faces):+ result = face_attrib.predict(image, face)+ active = ', '.join(result.labels(threshold)) or 'none'+ print(f' Face {i + 1}: {result}')+ print(f' Face {i + 1}: active -> {active}')+ draw_face_states(image, face.bbox, result, threshold)++ os.makedirs(save_dir, exist_ok=True)+ output_path = os.path.join(save_dir, f'{Path(image_path).stem}_facestate.jpg')+ cv2.imwrite(output_path, image)+ print(f'Output saved: {output_path}')+++def process_video(+ detector,+ face_attrib,+ video_path: str,+ save_dir: str = 'outputs',+ threshold: float = 0.5,+):+ """Process a video file."""+ cap = cv2.VideoCapture(video_path)+ if not cap.isOpened():+ print(f"Error: Cannot open video file '{video_path}'")+ return++ fps = cap.get(cv2.CAP_PROP_FPS)+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))++ os.makedirs(save_dir, exist_ok=True)+ output_path = os.path.join(save_dir, f'{Path(video_path).stem}_facestate.mp4')+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')+ out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))++ print(f'Processing video: {video_path} ({total_frames} frames)')+ frame_count = 0++ while True:+ ret, frame = cap.read()+ if not ret:+ break++ frame_count += 1+ faces = detector.detect(frame)++ for face in faces:+ result = face_attrib.predict(frame, face)+ draw_face_states(frame, face.bbox, result, threshold)++ cv2.putText(frame, f'Faces: {len(faces)}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)+ out.write(frame)++ if frame_count % 100 == 0:+ print(f' Processed {frame_count}/{total_frames} frames...')++ cap.release()+ out.release()+ print(f'Done! Output saved: {output_path}')+++def run_camera(detector, face_attrib, camera_id: int = 0, threshold: float = 0.5):+ """Run real-time face state prediction on webcam."""+ cap = cv2.VideoCapture(camera_id)+ if not cap.isOpened():+ print(f'Cannot open camera {camera_id}')+ return++ print("Press 'q' to quit")++ while True:+ ret, frame = cap.read()+ if not ret:+ break+ frame = cv2.flip(frame, 1)++ faces = detector.detect(frame)++ for face in faces:+ result = face_attrib.predict(frame, face)+ draw_face_states(frame, face.bbox, result, threshold)++ cv2.putText(frame, f'Faces: {len(faces)}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)+ cv2.imshow('Face State Detection', frame)++ if cv2.waitKey(1) & 0xFF == ord('q'):+ break++ cap.release()+ cv2.destroyAllWindows()+++def main():+ parser = argparse.ArgumentParser(description='Run face state prediction (FaceAttribNet)')+ parser.add_argument('--source', type=str, required=True, help='Image/video path or camera ID (0, 1, ...)')+ parser.add_argument('--detector', type=str, default='retinaface', choices=['retinaface', 'scrfd'])+ parser.add_argument('--threshold', type=float, default=0.5, help='Probability above which an attribute is present')+ parser.add_argument('--margin', type=float, default=0.0, help='Fraction to expand each face crop by on each side')+ parser.add_argument('--save-dir', type=str, default='outputs', help='Output directory')+ args = parser.parse_args()++ detector = RetinaFace() if args.detector == 'retinaface' else SCRFD()+ face_attrib = FaceAttribNet(margin=args.margin)++ source_type = get_source_type(args.source)++ if source_type == 'camera':+ run_camera(detector, face_attrib, int(args.source), args.threshold)+ elif source_type == 'image':+ if not os.path.exists(args.source):+ print(f'Error: Image not found: {args.source}')+ return+ process_image(detector, face_attrib, args.source, args.save_dir, args.threshold)+ elif source_type == 'video':+ if not os.path.exists(args.source):+ print(f'Error: Video not found: {args.source}')+ return+ process_video(detector, face_attrib, args.source, args.save_dir, args.threshold)+ else:+ print(f"Error: Unknown source type for '{args.source}'")+ print('Supported formats: images (.jpg, .png, ...), videos (.mp4, .avi, ...), or camera ID (0, 1, ...)')+++if __name__ == '__main__':+ main()diff --git a/tools/parse.py b/tools/parse.pyindex a96f9ba..9433dbb 100644--- a/tools/parse.py+++ b/tools/parse.py@@ -32,8 +32,7 @@ def expand_bbox(expand_ratio: float = 0.2,expand_top_ratio: float = 0.4,) -> tuple[int, int, int, int]:- """- Expand bounding box to include full head region for face parsing.+ """Expand bounding box to include full head region for face parsing.Face detection typically returns tight face boxes, but face parsingrequires the full head including hair, ears, and neck.diff --git a/uniface/__init__.py b/uniface/__init__.pyindex da845f3..0c92d3b 100644--- a/uniface/__init__.py+++ b/uniface/__init__.py@@ -4,25 +4,19 @@# You may obtain a copy of the License at## https://opensource.org/licenses/MIT-#-# Unless required by applicable law or agreed to in writing, software-# distributed under the License is distributed on an "AS IS" BASIS,-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-# See the License for the specific language governing permissions and-# limitations under the License."""UniFace: A comprehensive library for face analysis.This library provides unified APIs for:-- Face detection (RetinaFace, SCRFD, YOLOv5Face, YOLOv8Face)+- Face detection (BlazeFace, CenterFace, RetinaFace, SCRFD, YOLOv5Face, YOLOv8Face)- Face recognition (AdaFace, ArcFace, EdgeFace, MobileFace, SphereFace)- Face tracking (ByteTrack with Kalman filtering)-- Facial landmarks (106 / 98 / 68-point detection: 2d106det, PIPNet)+- Facial landmarks (106 / 98 / 68-point: 2d106det, PIPNet; 468/478-point dense: FaceMesh)- Face parsing (semantic segmentation)- Portrait matting (trimap-free alpha matte)- Gaze estimation- Head pose estimation-- Age, gender, and emotion prediction+- Age, gender, emotion, and face state prediction (eyes open, glasses, mask)- Face anti-spoofing- Face image quality assessment (eDifFIQA)- Privacy/anonymization@@ -32,39 +26,40 @@ from __future__ import annotations__license__ = 'MIT'__author__ = 'Yakhyokhuja Valikhujaev'-__version__ = '3.7.1'--import contextlib+__version__ = '4.0.0rc1'from uniface.face_utils import compute_similarity, face_alignmentfrom uniface.log import Logger, enable_loggingfrom uniface.model_store import download_models, get_cache_dir, set_cache_dir, verify_model_weightsfrom .analyzer import FaceAnalyzer-from .attribute import AgeGender, Emotion, FairFace, create_attribute_predictor-from .detection import (- SCRFD,- RetinaFace,- YOLOv5Face,- YOLOv8Face,- create_detector,- list_available_detectors,-)-from .gaze import MobileGaze, create_gaze_estimator-from .headpose import HeadPose, create_head_pose_estimator-from .landmark import Landmark106, PIPNet, create_landmarker-from .matting import MODNet, create_matting_model-from .parsing import BiSeNet, XSeg, create_face_parser+from .attribute import AgeGender, Emotion, FaceAttribNet, FairFace+from .detection import SCRFD, BlazeFace, CenterFace, RetinaFace, YOLOv5Face, YOLOv8Face+from .gaze import MobileGaze+from .headpose import HeadPose+from .landmark import FaceMesh, Landmark106, PIPNet+from .matting import MODNet+from .parsing import BiSeNet, XSegfrom .privacy import BlurFacefrom .quality import EDifFIQA-from .recognition import AdaFace, ArcFace, EdgeFace, MobileFace, SphereFace, create_recognizer-from .spoofing import MiniFASNet, create_spoofer-from .tracking import BYTETracker-from .types import AttributeResult, EmotionResult, Face, GazeResult, HeadPoseResult, QualityResult, SpoofingResult+from .recognition import AdaFace, ArcFace, EdgeFace, MobileFace, SphereFace+from .spoofing import MiniFASNet-# Optional: FAISS vector store (requires `pip install faiss-cpu`)-with contextlib.suppress(ImportError):- from .stores import FAISS+# The faiss dependency is imported lazily at FAISS(...) construction, so this+# import succeeds even without faiss-cpu installed.+from .stores import FAISS+from .tracking import BYTETracker+from .types import (+ DemographyResult,+ EmotionResult,+ Face,+ FaceMeshResult,+ FaceStateResult,+ GazeResult,+ HeadPoseResult,+ QualityResult,+ SpoofingResult,+)__all__ = [# Metadata@@ -74,17 +69,9 @@ __all__ = [# Core classes'Face','FaceAnalyzer',- # Factory functions- 'create_detector',- 'create_face_parser',- 'create_gaze_estimator',- 'create_matting_model',- 'create_head_pose_estimator',- 'create_landmarker',- 'create_recognizer',- 'create_spoofer',- 'list_available_detectors',# Detection models+ 'BlazeFace',+ 'CenterFace','RetinaFace','SCRFD','YOLOv5Face',@@ -96,6 +83,8 @@ __all__ = ['MobileFace','SphereFace',# Landmark models+ 'FaceMesh',+ 'FaceMeshResult','Landmark106','PIPNet',# Gaze models@@ -111,10 +100,11 @@ __all__ = ['XSeg',# Attribute models'AgeGender',- 'AttributeResult',- 'create_attribute_predictor',+ 'DemographyResult','Emotion','EmotionResult',+ 'FaceAttribNet',+ 'FaceStateResult','FairFace',# Spoofing models'MiniFASNet',diff --git a/uniface/analyzer.py b/uniface/analyzer.pyindex 3f425cc..c12c7ad 100644--- a/uniface/analyzer.py+++ b/uniface/analyzer.py@@ -8,7 +8,7 @@ from typing import Anyimport numpy as np-from uniface.attribute.base import Attribute+from uniface.attribute.base import BaseAttributefrom uniface.detection.base import BaseDetectorfrom uniface.log import Loggerfrom uniface.recognition.base import BaseRecognizer@@ -20,42 +20,43 @@ _UNSET: Any = object()class FaceAnalyzer:- """Unified face analyzer combining detection, recognition, and attributes.+ """Unified face analyzer combining detection, recognition, and per-face predictors.This class provides a high-level interface for face analysis by combiningmultiple components: face detection, recognition (embedding extraction),- and an extensible list of attribute predictors (age, gender, race,+ and an extensible list of per-face predictors (age, gender, race,emotion, etc.).- Any :class:`~uniface.attribute.base.Attribute` subclass can be passed- via the ``attributes`` list. Each predictor's ``predict(image, face)``- is called once per detected face, enriching the :class:`Face` in-place.+ Any `BaseAttribute` subclass can be passed+ via the `predictors` list. Each predictor's `predict(image, face)`+ is called once per detected face, enriching the `Face` in-place.When called with no arguments, uses SCRFD (500M) for detection andArcFace (MobileNet) for recognition — the smallest and fastest variants.Args:- detector: Face detector instance. Defaults to ``SCRFD(SCRFD_500M_KPS)``.+ detector: Face detector instance. Defaults to `SCRFD(SCRFD_500M_KPS)`.recognizer: Face recognizer for extracting embeddings.- Defaults to ``ArcFace(MNET)``. Pass ``None`` to disable recognition.- attributes: Optional list of ``Attribute`` predictors to run on- each detected face (e.g. ``[AgeGender()]``).+ Defaults to `ArcFace(MNET)`. Pass `None` to disable recognition.+ predictors: Optional list of `BaseAttribute` predictors to run on+ each detected face (e.g. `[AgeGender()]`).- Examples:+ Example:>>> from uniface import FaceAnalyzer>>> analyzer = FaceAnalyzer()>>> faces = analyzer.analyze(image)>>> from uniface import FaceAnalyzer, AgeGender- >>> analyzer = FaceAnalyzer(attributes=[AgeGender()])+ >>> analyzer = FaceAnalyzer(predictors=[AgeGender()])>>> faces = analyzer.analyze(image)"""def __init__(self,+ *,detector: BaseDetector | None = None,recognizer: BaseRecognizer | None = _UNSET,- attributes: list[Attribute] | None = None,+ predictors: list[BaseAttribute] | None = None,) -> None:if detector is None:from uniface.constants import SCRFDWeights@@ -63,6 +64,16 @@ class FaceAnalyzer:detector = SCRFD(model_name=SCRFDWeights.SCRFD_500M_KPS)+ # Checked before the _UNSET branch below so an unusable recognizer is never loaded.+ if not getattr(detector, 'supports_alignment', False):+ if recognizer is _UNSET or recognizer is not None:+ Logger.warning(+ f'{detector.__class__.__name__} does not produce alignment landmarks; '+ 'recognition disabled. Use SCRFD, RetinaFace, CenterFace, YOLOv5Face or '+ 'YOLOv8Face if you need embeddings.'+ )+ recognizer = None+if recognizer is _UNSET:from uniface.recognition import ArcFace@@ -70,25 +81,25 @@ class FaceAnalyzer:self.detector = detectorself.recognizer = recognizer- self.attributes: list[Attribute] = attributes or []+ self.predictors: list[BaseAttribute] = predictors or []Logger.info(f'Initialized FaceAnalyzer with detector={detector.__class__.__name__}')if recognizer:Logger.info(f'Recognition enabled: {recognizer.__class__.__name__}')- for attr in self.attributes:- Logger.info(f'Attribute enabled: {attr.__class__.__name__}')+ for attr in self.predictors:+ Logger.info(f'Predictor enabled: {attr.__class__.__name__}')def analyze(self, image: np.ndarray) -> list[Face]:"""Analyze faces in an image.Performs face detection, optionally extracts embeddings, and runs- every registered attribute predictor on each detected face.+ every registered predictor on each detected face.Args:image: Input image as numpy array with shape (H, W, C) in BGR format.Returns:- List of Face objects with detection results and any predicted attributes.+ List of Face objects with detection results and any predictor results."""faces = self.detector.detect(image)Logger.debug(f'Detected {len(faces)} face(s)')@@ -101,7 +112,7 @@ class FaceAnalyzer:except Exception as e:Logger.warning(f'Face {idx + 1}: Failed to extract embedding: {e}')- for attr in self.attributes:+ for attr in self.predictors:attr_name = attr.__class__.__name__try:attr.predict(image, face)@@ -114,7 +125,7 @@ class FaceAnalyzer:parts = [f'detector={self.detector.__class__.__name__}']if self.recognizer is not None:parts.append(f'recognizer={self.recognizer.__class__.__name__}')- if self.attributes:- attr_names = ', '.join(attr.__class__.__name__ for attr in self.attributes)- parts.append(f'attributes=[{attr_names}]')+ if self.predictors:+ attr_names = ', '.join(attr.__class__.__name__ for attr in self.predictors)+ parts.append(f'predictors=[{attr_names}]')return f'FaceAnalyzer({", ".join(parts)})'diff --git a/uniface/attribute/__init__.py b/uniface/attribute/__init__.pyindex be77efb..326c398 100644--- a/uniface/attribute/__init__.py+++ b/uniface/attribute/__init__.py@@ -7,22 +7,18 @@ from __future__ import annotationsfrom typing import Anyimport numpy as np-from typing_extensions import deprecatedfrom uniface.attribute.age_gender import AgeGender-from uniface.attribute.base import Attribute+from uniface.attribute.base import BaseAttribute+from uniface.attribute.faceattribnet import FaceAttribNetfrom uniface.attribute.fairface import FairFace-from uniface.constants import AgeGenderWeights, DDAMFNWeights, FairFaceWeights-from uniface.types import AttributeResult, EmotionResult, Face+from uniface.types import DemographyResult, EmotionResult, Face, FaceStateResulttry:from uniface.attribute.emotion import Emotion-- _EMOTION_AVAILABLE = Trueexcept ImportError:- _EMOTION_AVAILABLE = False- class Emotion(Attribute): # type: ignore[no-redef]+ class Emotion(BaseAttribute): # type: ignore[no-redef]"""Stub for Emotion when PyTorch is not installed."""def __init__(self, *args: Any, **kwargs: Any) -> None:@@ -36,54 +32,11 @@ except ImportError:__all__ = ['AgeGender',- 'AttributeResult',+ 'BaseAttribute',+ 'DemographyResult','Emotion','EmotionResult',+ 'FaceAttribNet',+ 'FaceStateResult','FairFace',- 'create_attribute_predictor',]--_ATTRIBUTE_MODELS = {- **dict.fromkeys(AgeGenderWeights, AgeGender),- **dict.fromkeys(FairFaceWeights, FairFace),-}--if _EMOTION_AVAILABLE:- _ATTRIBUTE_MODELS.update(dict.fromkeys(DDAMFNWeights, Emotion))---@deprecated(- 'create_attribute_predictor() is deprecated and will be removed in uniface 4.0. '- 'Instantiate the attribute class directly, e.g. '- '`from uniface.attribute import AgeGender; AgeGender(model_name=...)`.'-)-def create_attribute_predictor(- model_name: AgeGenderWeights | DDAMFNWeights | FairFaceWeights, **kwargs: Any-) -> Attribute:- """Factory function to create an attribute predictor instance.-- .. deprecated:: 3.7.0- Use the attribute class directly (``AgeGender``, ``FairFace``,- ``Emotion``). This factory will be removed in uniface 4.0.-- Args:- model_name: The enum corresponding to the desired attribute model- (e.g., AgeGenderWeights.DEFAULT, DDAMFNWeights.AFFECNET7,- or FairFaceWeights.DEFAULT).- **kwargs: Additional keyword arguments passed to the model constructor.-- Returns:- An initialized Attribute predictor (AgeGender, FairFace, or Emotion).-- Raises:- ValueError: If the provided model_name is not a supported enum.- """- model_class = _ATTRIBUTE_MODELS.get(model_name)-- if model_class is None:- raise ValueError(- f'Unsupported attribute model: {model_name}. '- f'Please choose from AgeGenderWeights, FairFaceWeights, or DDAMFNWeights.'- )-- return model_class(model_name=model_name, **kwargs)diff --git a/uniface/attribute/age_gender.py b/uniface/attribute/age_gender.pyindex 6cce5db..2967382 100644--- a/uniface/attribute/age_gender.py+++ b/uniface/attribute/age_gender.py@@ -6,60 +6,62 @@import cv2import numpy as np-from uniface.attribute.base import Attribute+from uniface.attribute.base import BaseAttributefrom uniface.constants import AgeGenderWeightsfrom uniface.face_utils import bbox_center_alignmentfrom uniface.log import Loggerfrom uniface.model_store import verify_model_weightsfrom uniface.onnx_utils import create_onnx_session-from uniface.types import AttributeResult, Face+from uniface.types import DemographyResult, Face__all__ = ['AgeGender']-class AgeGender(Attribute):- """- Age and gender prediction model using ONNX Runtime.+class AgeGender(BaseAttribute):+ """Age and gender prediction model using ONNX Runtime.- This class inherits from the base `Attribute` class and implements the+ This class inherits from the `BaseAttribute` base class and implements thefunctionality for predicting age (in years) and gender ID (0 for Female,1 for Male) from a face image. It requires a bounding box to locate the face.Args:model_name (AgeGenderWeights): The enum specifying the model weights to load.Defaults to `AgeGenderWeights.DEFAULT`.- input_size (Optional[Tuple[int, int]]): Input size (height, width).+ input_size (tuple[int, int] | None): Input size (height, width).If None, automatically detected from model metadata. Defaults to None.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.++ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize."""def __init__(self,+ *,model_name: AgeGenderWeights = AgeGenderWeights.DEFAULT,input_size: tuple[int, int] | None = None,providers: list[str] | None = None,) -> None:- """- Initializes the AgeGender prediction model.+ """Initializes the AgeGender prediction model.Args:model_name (AgeGenderWeights): The enum specifying the model weights to load.- input_size (Optional[Tuple[int, int]]): Input size (height, width).+ input_size (tuple[int, int] | None): Input size (height, width).If None, automatically detected from model metadata. Defaults to None.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU."""Logger.info(f'Initializing AgeGender with model={model_name.name}')self.model_path = verify_model_weights(model_name)- self._user_input_size = input_size # Store user preference+ # Normalized to a tuple so a [224, 224] list still compares equal to the ONNX metadata.+ self.input_size = tuple(input_size) if input_size is not None else Noneself.providers = providersself._initialize_model()def _initialize_model(self) -> None:- """- Initializes the ONNX model and creates an inference session.- """+ """Initializes the ONNX model and creates an inference session."""try:self.session = create_onnx_session(self.model_path, providers=self.providers)# Get model input details from the loaded model@@ -68,9 +70,8 @@ class AgeGender(Attribute):# Use user-provided size if given, otherwise auto-detect from modelmodel_input_size = tuple(input_meta.shape[2:4]) # (height, width)- if self._user_input_size is not None:- self.input_size = self._user_input_size- if self._user_input_size != model_input_size:+ if self.input_size is not None:+ if all(isinstance(v, int) for v in model_input_size) and self.input_size != model_input_size:Logger.warning(f'Using custom input_size {self.input_size}, 'f'but model expects {model_input_size}. This may affect accuracy.'@@ -88,12 +89,11 @@ class AgeGender(Attribute):raise RuntimeError(f'Failed to initialize AgeGender model: {e}') from edef preprocess(self, image: np.ndarray, bbox: list | np.ndarray) -> np.ndarray:- """- Aligns the face based on the bounding box and preprocesses it for inference.+ """Aligns the face based on the bounding box and preprocesses it for inference.Args:image (np.ndarray): The full input image in BGR format.- bbox (Union[List, np.ndarray]): The face bounding box coordinates [x1, y1, x2, y2].+ bbox (list | np.ndarray): The face bounding box coordinates [x1, y1, x2, y2].Returns:np.ndarray: The preprocessed image blob ready for inference.@@ -104,7 +104,6 @@ class AgeGender(Attribute):center = ((bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2)scale = self.input_size[1] / (max(width, height) * 1.5)- # **Rotation parameter restored here**rotation = 0.0aligned_face, _ = bbox_center_alignment(image, center, self.input_size[1], scale, rotation)@@ -117,31 +116,30 @@ class AgeGender(Attribute):)return blob- def postprocess(self, prediction: np.ndarray) -> AttributeResult:- """- Processes the raw model output to extract gender and age.+ def postprocess(self, prediction: np.ndarray) -> DemographyResult:+ """Processes the raw model output to extract gender and age.Args:prediction (np.ndarray): The raw output from the model inference.Returns:- AttributeResult: Result containing gender (0=Female, 1=Male) and age (in years).+ DemographyResult: Result containing gender (0=Female, 1=Male) and age (in years)."""# First two values are gender logitsgender = int(np.argmax(prediction[:2]))# Third value is normalized age, scaled by 100age = int(np.round(prediction[2] * 100))- return AttributeResult(gender=gender, age=age)+ return DemographyResult(gender=gender, age=age)- def predict(self, image: np.ndarray, face: Face) -> AttributeResult:+ def predict(self, image: np.ndarray, face: Face) -> DemographyResult:"""Predict age and gender and enrich the Face in-place.Args:image: The full input image in BGR format.- face: Detected face; ``face.bbox`` is used for alignment.+ face: Detected face; `face.bbox` is used for alignment.Returns:- ``AttributeResult`` with gender (0=Female, 1=Male) and age (years).+ `DemographyResult` with gender (0=Female, 1=Male) and age (years)."""face_blob = self.preprocess(image, face.bbox)prediction = self.session.run(self.output_names, {self.input_name: face_blob})[0][0]diff --git a/uniface/attribute/base.py b/uniface/attribute/base.pyindex f21f466..8f81887 100644--- a/uniface/attribute/base.py+++ b/uniface/attribute/base.py@@ -9,18 +9,18 @@ from typing import Anyimport numpy as np-from uniface.types import AttributeResult, EmotionResult, Face+from uniface.types import DemographyResult, EmotionResult, Face, FaceStateResult-__all__ = ['Attribute', 'AttributeResult', 'EmotionResult']+__all__ = ['BaseAttribute', 'DemographyResult', 'EmotionResult', 'FaceStateResult']-class Attribute(ABC):+class BaseAttribute(ABC):"""Abstract base class for face attribute models.All attribute models (age-gender, emotion, FairFace, etc.) implement this- interface so they can be used interchangeably inside ``FaceAnalyzer``.+ interface so they can be used interchangeably inside `FaceAnalyzer`.- The ``predict`` method accepts an image and a :class:`Face` object. Each+ The `predict` method accepts an image and a `Face` object. Eachsubclass extracts what it needs (bbox, landmarks) from the Face, runsinference, writes the results back to the Face **and** returns a typedresult dataclass.@@ -52,16 +52,16 @@ class Attribute(ABC):prediction: Raw output from the model.Returns:- An ``AttributeResult`` or ``EmotionResult``.+ An `DemographyResult`, `EmotionResult`, or `FaceStateResult`."""raise NotImplementedError('Subclasses must implement the postprocess method.')@abstractmethod- def predict(self, image: np.ndarray, face: Face) -> AttributeResult | EmotionResult:+ def predict(self, image: np.ndarray, face: Face) -> DemographyResult | EmotionResult | FaceStateResult:"""Run end-to-end prediction and enrich the Face in-place.- Each subclass extracts what it needs from *face* (e.g. ``face.bbox``- or ``face.landmarks``), runs the full preprocess-infer-postprocess+ Each subclass extracts what it needs from *face* (e.g. `face.bbox`+ or `face.landmarks`), runs the full preprocess-infer-postprocesspipeline, writes relevant fields back to *face*, and returns theresult dataclass.@@ -70,10 +70,10 @@ class Attribute(ABC):face: Detected face whose attribute fields will be populated.Returns:- The prediction result (``AttributeResult`` or ``EmotionResult``).+ The prediction result (`DemographyResult`, `EmotionResult`, or `FaceStateResult`)."""raise NotImplementedError('Subclasses must implement the predict method.')- def __call__(self, image: np.ndarray, face: Face) -> AttributeResult | EmotionResult:- """Callable shortcut for :meth:`predict`."""+ def __call__(self, image: np.ndarray, face: Face) -> DemographyResult | EmotionResult | FaceStateResult:+ """Callable shortcut for `predict`."""return self.predict(image, face)diff --git a/uniface/attribute/emotion.py b/uniface/attribute/emotion.pyindex 64a1295..0ca6760 100644--- a/uniface/attribute/emotion.py+++ b/uniface/attribute/emotion.py@@ -7,8 +7,8 @@ import cv2import numpy as npimport torch-from uniface.attribute.base import Attribute-from uniface.constants import DDAMFNWeights+from uniface.attribute.base import BaseAttribute+from uniface.constants import EmotionWeightsfrom uniface.face_utils import face_alignmentfrom uniface.log import Loggerfrom uniface.model_store import verify_model_weights@@ -17,26 +17,29 @@ from uniface.types import EmotionResult, Face__all__ = ['Emotion']-class Emotion(Attribute):- """- Emotion recognition model using a TorchScript model.+class Emotion(BaseAttribute):+ """Emotion recognition model using a TorchScript model.- This class inherits from the base `Attribute` class and implements the+ This class inherits from the `BaseAttribute` base class and implements thefunctionality for predicting one of several emotion categories from a faceimage. It requires 5-point facial landmarks for alignment.++ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the TorchScript model fails to load or initialize."""def __init__(self,- model_name: DDAMFNWeights = DDAMFNWeights.AFFECNET7,+ *,+ model_name: EmotionWeights = EmotionWeights.AFFECNET7,input_size: tuple[int, int] = (112, 112),) -> None:- """- Initializes the emotion recognition model.+ """Initializes the emotion recognition model.Args:- model_name (DDAMFNWeights): The enum for the model weights to load.- input_size (Tuple[int, int]): The expected input size for the model.+ model_name (EmotionWeights): The enum for the model weights to load.+ input_size (tuple[int, int]): The expected input size for the model."""Logger.info(f'Initializing Emotion with model={model_name.name}')@@ -60,15 +63,13 @@ class Emotion(Attribute):'Disgust','Angry',]- if model_name == DDAMFNWeights.AFFECNET8:+ if model_name == EmotionWeights.AFFECNET8:self.emotion_labels.append('Contempt')self._initialize_model()def _initialize_model(self) -> None:- """- Loads and initializes the TorchScript model for inference.- """+ """Loads and initializes the TorchScript model for inference."""try:self.model = torch.jit.load(self.model_path, map_location=self.device)self.model.eval()@@ -81,20 +82,19 @@ class Emotion(Attribute):Logger.error(f"Failed to load Emotion model from '{self.model_path}'", exc_info=True)raise RuntimeError(f'Failed to initialize Emotion model: {e}') from e- def preprocess(self, image: np.ndarray, landmark: list | np.ndarray) -> torch.Tensor:- """- Aligns the face using landmarks and preprocesses it into a tensor.+ def preprocess(self, image: np.ndarray, landmarks: list | np.ndarray) -> torch.Tensor:+ """Aligns the face using landmarks and preprocesses it into a tensor.Args:image (np.ndarray): The full input image in BGR format.- landmark (Union[List, np.ndarray]): The 5-point facial landmarks.+ landmarks (list | np.ndarray): The 5-point facial landmarks.Returns:torch.Tensor: The preprocessed image tensor ready for inference."""- landmark = np.asarray(landmark)+ landmarks = np.asarray(landmarks)- aligned_image, _ = face_alignment(image, landmark)+ aligned_image, _ = face_alignment(image, landmarks)# Convert BGR to RGB, resize, normalize, and convert to a CHW tensorrgb_image = cv2.cvtColor(aligned_image, cv2.COLOR_BGR2RGB)@@ -107,9 +107,7 @@ class Emotion(Attribute):return torch.from_numpy(transposed_image).unsqueeze(0).to(self.device)def postprocess(self, prediction: torch.Tensor) -> EmotionResult:- """- Processes the raw model output to get the emotion label and confidence score.- """+ """Processes the raw model output to get the emotion label and confidence score."""probabilities = torch.nn.functional.softmax(prediction, dim=1).squeeze().cpu().numpy()pred_index = np.argmax(probabilities)emotion_label = self.emotion_labels[pred_index]@@ -121,10 +119,10 @@ class Emotion(Attribute):Args:image: The full input image in BGR format.- face: Detected face; ``face.landmarks`` is used for alignment.+ face: Detected face; `face.landmarks` is used for alignment.Returns:- ``EmotionResult`` with emotion label and confidence score.+ `EmotionResult` with emotion label and confidence score."""input_tensor = self.preprocess(image, face.landmarks)with torch.no_grad():diff --git a/uniface/attribute/faceattribnet.py b/uniface/attribute/faceattribnet.pynew file mode 100644index 0000000..fcf1ffa--- /dev/null+++ b/uniface/attribute/faceattribnet.py@@ -0,0 +1,183 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo+++import numpy as np++from uniface.attribute.base import BaseAttribute+from uniface.common import letterbox_resize+from uniface.constants import FaceAttribNetWeights+from uniface.log import Logger+from uniface.model_store import verify_model_weights+from uniface.onnx_utils import create_onnx_session+from uniface.types import Face, FaceStateResult++__all__ = ['FaceAttribNet']+++class FaceAttribNet(BaseAttribute):+ """FaceAttribNet face state prediction model using ONNX Runtime.++ This class inherits from the `BaseAttribute` base class and implements the+ functionality for predicting five independent binary face attributes from+ a face crop: left/right eye openness, eyeglasses, face mask, and+ sunglasses. It requires a bounding box to locate the face.++ Each attribute comes from its own binary classifier head, so the five+ probabilities do not sum to 1 and several can be high at once (a face can+ wear both sunglasses and a mask). Threshold each one separately.++ The model is Qualcomm's "Facial-Attribute-Detection" (FaceAttribNet),+ mean/std normalization is baked into the ONNX graph itself, so+ preprocessing only scales pixel values to [0, 1].+ Original model: https://github.com/qualcomm/ai-hub-models/tree/main/src/qai_hub_models/models/face_attrib_net+ ONNX export and inference: https://github.com/yakhyo/face-attribute++ Args:+ model_name (FaceAttribNetWeights): The enum specifying the model weights to load.+ Defaults to `FaceAttribNetWeights.DEFAULT`.+ input_size (tuple[int, int] | None): Input size (height, width).+ If None, defaults to (128, 128). Defaults to None.+ margin (float): Fraction of box size to expand the face crop by on each+ side before inference. Defaults to 0.0.+ providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detects+ the best available provider. Example: ['CPUExecutionProvider'] to force CPU.++ Raises:+ ValueError: If the model weights are invalid or not found, or `input_size` is not square.+ RuntimeError: If the ONNX model fails to load or initialize.+ """++ def __init__(+ self,+ *,+ model_name: FaceAttribNetWeights = FaceAttribNetWeights.DEFAULT,+ input_size: tuple[int, int] | None = None,+ margin: float = 0.0,+ providers: list[str] | None = None,+ ) -> None:+ """Initializes the FaceAttribNet prediction model.++ Args:+ model_name (FaceAttribNetWeights): The enum specifying the model weights to load.+ input_size (tuple[int, int] | None): Input size (height, width). Must be square:+ preprocessing letterboxes into a square canvas. If None, defaults to (128, 128).+ margin (float): Fraction of box size to expand the face crop by on each side.+ providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detects+ the best available provider. Example: ['CPUExecutionProvider'] to force CPU.++ Raises:+ ValueError: If `input_size` is not square.+ """+ Logger.info(f'Initializing FaceAttribNet with model={model_name.name}')+ self.model_path = verify_model_weights(model_name)+ # Normalized to a tuple so a [128, 128] list still compares equal to the ONNX metadata.+ self.input_size = tuple(input_size) if input_size is not None else (128, 128)+ # letterbox_resize pads into a square canvas, so a non-square request cannot be honored.+ if self.input_size[0] != self.input_size[1]:+ raise ValueError(f'input_size must be square, got {self.input_size}')+ self.margin = margin+ self.providers = providers+ self._initialize_model()++ def _initialize_model(self) -> None:+ """Initializes the ONNX model and creates an inference session."""+ try:+ self.session = create_onnx_session(self.model_path, providers=self.providers)+ input_meta = self.session.get_inputs()[0]+ self.input_name = input_meta.name++ # Warn when a custom input_size disagrees with the model metadata+ model_input_size = tuple(input_meta.shape[2:4]) # (height, width)+ if all(isinstance(v, int) for v in model_input_size) and self.input_size != model_input_size:+ Logger.warning(+ f'Using custom input_size {self.input_size}, '+ f'but model expects {model_input_size}. This may affect accuracy.'+ )++ self.output_names = [output.name for output in self.session.get_outputs()]+ Logger.info(f'Successfully initialized FaceAttribNet model with input size {self.input_size}')+ except Exception as e:+ Logger.error(+ f"Failed to load FaceAttribNet model from '{self.model_path}'",+ exc_info=True,+ )+ raise RuntimeError(f'Failed to initialize FaceAttribNet model: {e}') from e++ def preprocess(self, image: np.ndarray, bbox: list | np.ndarray | None = None) -> np.ndarray:+ """Preprocesses the face image for inference.++ Crops the face (optionally expanded by `margin`), letterboxes it to+ the model input size with centered zero padding, and scales pixel+ values to [0, 1]. No mean/std normalization is applied here: it is+ baked into the model graph.++ Args:+ image (np.ndarray): The input image in BGR format.+ bbox (list | np.ndarray | None): Face bounding box [x1, y1, x2, y2].+ If None, uses the entire image.++ Returns:+ np.ndarray: The preprocessed image blob ready for inference.++ Raises:+ ValueError: If the bounding box does not overlap the image.+ """+ if bbox is not None:+ height, width = image.shape[:2]+ x1, y1, x2, y2 = (float(v) for v in np.asarray(bbox)[:4])++ if self.margin:+ dw, dh = (x2 - x1) * self.margin, (y2 - y1) * self.margin+ x1, y1, x2, y2 = x1 - dw, y1 - dh, x2 + dw, y2 + dh++ x1, y1 = max(0, round(x1)), max(0, round(y1))+ x2, y2 = min(width, round(x2)), min(height, round(y2))++ if x2 <= x1 or y2 <= y1:+ raise ValueError(f'Bounding box {bbox[:4]} does not overlap the {width}x{height} image')++ image = image[y1:y2, x1:x2]++ blob, _, _ = letterbox_resize(image, self.input_size[0], fill_value=0)+ return blob++ def postprocess(self, prediction: np.ndarray) -> FaceStateResult:+ """Processes the raw model output into per-attribute probabilities.++ Args:+ prediction (np.ndarray): Raw model output with shape (1, 5).++ Returns:+ FaceStateResult: Five independent probabilities in [0, 1].+ """+ left_eye_open, right_eye_open, eyeglasses, mask, sunglasses = np.squeeze(prediction).astype(float).tolist()+ return FaceStateResult(+ left_eye_open=left_eye_open,+ right_eye_open=right_eye_open,+ eyeglasses=eyeglasses,+ mask=mask,+ sunglasses=sunglasses,+ )++ def predict(self, image: np.ndarray, face: Face) -> FaceStateResult:+ """Predict face states and enrich the Face in-place.++ Args:+ image: The full input image in BGR format.+ face: Detected face; `face.bbox` is used for cropping.++ Returns:+ `FaceStateResult` with the five attribute probabilities.+ """+ input_blob = self.preprocess(image, face.bbox)+ outputs = self.session.run(self.output_names, {self.input_name: input_blob})+ result = self.postprocess(outputs[0])++ face.left_eye_open = result.left_eye_open+ face.right_eye_open = result.right_eye_open+ face.eyeglasses = result.eyeglasses+ face.mask = result.mask+ face.sunglasses = result.sunglasses+ return resultdiff --git a/uniface/attribute/fairface.py b/uniface/attribute/fairface.pyindex 38fdd2c..3ab48f1 100644--- a/uniface/attribute/fairface.py+++ b/uniface/attribute/fairface.py@@ -6,13 +6,13 @@import cv2import numpy as np-from uniface.attribute.base import Attribute+from uniface.attribute.base import BaseAttributefrom uniface.common import softmaxfrom uniface.constants import FairFaceWeightsfrom uniface.log import Loggerfrom uniface.model_store import verify_model_weightsfrom uniface.onnx_utils import create_onnx_session-from uniface.types import AttributeResult, Face+from uniface.types import DemographyResult, Face__all__ = ['AGE_LABELS', 'RACE_LABELS', 'FairFace']@@ -29,11 +29,10 @@ RACE_LABELS = [AGE_LABELS = ['0-2', '3-9', '10-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70+']-class FairFace(Attribute):- """- FairFace attribute prediction model using ONNX Runtime.+class FairFace(BaseAttribute):+ """FairFace attribute prediction model using ONNX Runtime.- This class inherits from the base `Attribute` class and implements the+ This class inherits from the `BaseAttribute` base class and implements thefunctionality for predicting race (7 categories), gender (2 categories),and age (9 groups) from a face image. It requires a bounding box to locate the face.@@ -43,43 +42,55 @@ class FairFace(Attribute):Args:model_name (FairFaceWeights): The enum specifying the model weights to load.Defaults to `FairFaceWeights.DEFAULT`.- input_size (Optional[Tuple[int, int]]): Input size (height, width).+ input_size (tuple[int, int] | None): Input size (height, width).If None, defaults to (224, 224). Defaults to None.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.++ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize."""def __init__(self,+ *,model_name: FairFaceWeights = FairFaceWeights.DEFAULT,input_size: tuple[int, int] | None = None,providers: list[str] | None = None,) -> None:- """- Initializes the FairFace prediction model.+ """Initializes the FairFace prediction model.Args:model_name (FairFaceWeights): The enum specifying the model weights to load.- input_size (Optional[Tuple[int, int]]): Input size (height, width).+ input_size (tuple[int, int] | None): Input size (height, width).If None, defaults to (224, 224).providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU."""Logger.info(f'Initializing FairFace with model={model_name.name}')self.model_path = verify_model_weights(model_name)- self.input_size = input_size if input_size is not None else (224, 224)+ # Normalized to a tuple so a [224, 224] list still compares equal to the ONNX metadata.+ self.input_size = tuple(input_size) if input_size is not None else (224, 224)self.providers = providersself._initialize_model()def _initialize_model(self) -> None:- """- Initializes the ONNX model and creates an inference session.- """+ """Initializes the ONNX model and creates an inference session."""try:self.session = create_onnx_session(self.model_path, providers=self.providers)# Get model input details from the loaded modelinput_meta = self.session.get_inputs()[0]self.input_name = input_meta.name++ # Warn when a custom input_size disagrees with the model metadata+ model_input_size = tuple(input_meta.shape[2:4]) # (height, width)+ if all(isinstance(v, int) for v in model_input_size) and self.input_size != model_input_size:+ Logger.warning(+ f'Using custom input_size {self.input_size}, '+ f'but model expects {model_input_size}. This may affect accuracy.'+ )+self.output_names = [output.name for output in self.session.get_outputs()]Logger.info(f'Successfully initialized FairFace model with input size {self.input_size}')except Exception as e:@@ -90,12 +101,11 @@ class FairFace(Attribute):raise RuntimeError(f'Failed to initialize FairFace model: {e}') from edef preprocess(self, image: np.ndarray, bbox: list | np.ndarray | None = None) -> np.ndarray:- """- Preprocesses the face image for inference.+ """Preprocesses the face image for inference.Args:image (np.ndarray): The input image in BGR format.- bbox (Optional[Union[List, np.ndarray]]): Face bounding box [x1, y1, x2, y2].+ bbox (list | np.ndarray | None): Face bounding box [x1, y1, x2, y2].If None, uses the entire image.Returns:@@ -137,16 +147,15 @@ class FairFace(Attribute):return image- def postprocess(self, prediction: tuple[np.ndarray, np.ndarray, np.ndarray]) -> AttributeResult:- """- Processes the raw model output to extract race, gender, and age.+ def postprocess(self, prediction: tuple[np.ndarray, np.ndarray, np.ndarray]) -> DemographyResult:+ """Processes the raw model output to extract race, gender, and age.Args:- prediction (Tuple[np.ndarray, np.ndarray, np.ndarray]): Raw outputs from model+ prediction (tuple[np.ndarray, np.ndarray, np.ndarray]): Raw outputs from model(race_logits, gender_logits, age_logits).Returns:- AttributeResult: Result containing gender (0=Female, 1=Male), age_group, and race.+ DemographyResult: Result containing gender (0=Female, 1=Male), age_group, and race."""race_logits, gender_logits, age_logits = prediction@@ -163,21 +172,21 @@ class FairFace(Attribute):# Normalize gender: model outputs 0=Male, 1=Female → standard 0=Female, 1=Malegender = 1 - raw_gender_idx- return AttributeResult(+ return DemographyResult(gender=gender,age_group=AGE_LABELS[age_idx],race=RACE_LABELS[race_idx],)- def predict(self, image: np.ndarray, face: Face) -> AttributeResult:+ def predict(self, image: np.ndarray, face: Face) -> DemographyResult:"""Predict race, gender, and age and enrich the Face in-place.Args:image: The full input image in BGR format.- face: Detected face; ``face.bbox`` is used for cropping.+ face: Detected face; `face.bbox` is used for cropping.Returns:- ``AttributeResult`` with gender, age_group, and race.+ `DemographyResult` with gender, age_group, and race."""input_blob = self.preprocess(image, face.bbox)outputs = self.session.run(self.output_names, {self.input_name: input_blob})diff --git a/uniface/common.py b/uniface/common.pyindex 7c2fc77..6d34c9b 100644--- a/uniface/common.py+++ b/uniface/common.py@@ -1,363 +1,397 @@-# Copyright 2025-2026 Yakhyokhuja Valikhujaev-# Author: Yakhyokhuja Valikhujaev-# GitHub: https://github.com/yakhyo--from __future__ import annotations--import itertools-import math--import cv2-import numpy as np--__all__ = [- 'decode_boxes',- 'decode_landmarks',- 'distance2bbox',- 'distance2kps',- 'generate_anchors',- 'letterbox_resize',- 'non_max_suppression',- 'resize_image',- 'softmax',- 'xyxy_to_cxcywh',-]---def resize_image(- frame: np.ndarray,- target_shape: tuple[int, int] = (640, 640),-) -> tuple[np.ndarray, float]:- """Resize an image to fit within a target shape while keeping its aspect ratio.-- The image is resized to fit within the target dimensions and placed on a- blank canvas (zero-padded to target size).-- Args:- frame: Input image with shape (H, W, C).- target_shape: Target size as (width, height). Defaults to (640, 640).-- Returns:- A tuple containing:- - Resized image on a blank canvas with shape (height, width, 3).- - The resize factor as a float.- """- width, height = target_shape-- # Aspect-ratio preserving resize- im_ratio = float(frame.shape[0]) / frame.shape[1]- model_ratio = height / width- if im_ratio > model_ratio:- new_height = height- new_width = int(new_height / im_ratio)- else:- new_width = width- new_height = int(new_width * im_ratio)-- resize_factor = float(new_height) / frame.shape[0]- resized_frame = cv2.resize(frame, (new_width, new_height))-- # Create blank image and place resized image on it- image = np.zeros((height, width, 3), dtype=np.uint8)- image[:new_height, :new_width, :] = resized_frame-- return image, resize_factor---def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:- """Compute the numerically stable softmax of an array along ``axis``.-- Args:- x: Input array.- axis: Axis along which softmax is computed. Defaults to the last axis.-- Returns:- Array of the same shape as *x* with values in ``[0, 1]`` summing to 1- along *axis*.- """- exp_x = np.exp(x - np.max(x, axis=axis, keepdims=True))- return exp_x / np.sum(exp_x, axis=axis, keepdims=True)---def xyxy_to_cxcywh(bboxes: np.ndarray) -> np.ndarray:- """Convert bounding boxes from ``[x1, y1, x2, y2]`` to ``[cx, cy, w, h]``.-- Args:- bboxes: Array of shape (N, 4) or (4,) with ``[x1, y1, x2, y2]`` coordinates.-- Returns:- Array of the same shape with ``[cx, cy, w, h]`` coordinates.- """- out = np.empty_like(bboxes)- out[..., 0] = (bboxes[..., 0] + bboxes[..., 2]) / 2 # cx- out[..., 1] = (bboxes[..., 1] + bboxes[..., 3]) / 2 # cy- out[..., 2] = bboxes[..., 2] - bboxes[..., 0] # w- out[..., 3] = bboxes[..., 3] - bboxes[..., 1] # h- return out---def generate_anchors(image_size: tuple[int, int] = (640, 640)) -> np.ndarray:- """Generate anchor boxes for a given image size (RetinaFace specific).-- Args:- image_size: Input image size as (width, height). Defaults to (640, 640).-- Returns:- Anchor box coordinates as a numpy array with shape (num_anchors, 4).- """- # RetinaFace FPN strides and corresponding anchor sizes per level- steps = [8, 16, 32]- min_sizes = [[16, 32], [64, 128], [256, 512]]-- anchors = []- feature_maps = [[math.ceil(image_size[0] / step), math.ceil(image_size[1] / step)] for step in steps]-- for k, (map_height, map_width) in enumerate(feature_maps):- step = steps[k]- for i, j in itertools.product(range(map_height), range(map_width)):- for min_size in min_sizes[k]:- s_kx = min_size / image_size[1]- s_ky = min_size / image_size[0]-- dense_cx = [x * step / image_size[1] for x in [j + 0.5]]- dense_cy = [y * step / image_size[0] for y in [i + 0.5]]- for cy, cx in itertools.product(dense_cy, dense_cx):- anchors += [cx, cy, s_kx, s_ky]-- output = np.array(anchors, dtype=np.float32).reshape(-1, 4)- return output---def non_max_suppression(dets: np.ndarray, threshold: float) -> list[int]:- """Apply Non-Maximum Suppression (NMS) to reduce overlapping bounding boxes.-- Args:- dets: Array of detections with each row as [x1, y1, x2, y2, score].- threshold: IoU threshold for suppression.-- Returns:- Indices of bounding boxes retained after suppression.- """- x1 = dets[:, 0]- y1 = dets[:, 1]- x2 = dets[:, 2]- y2 = dets[:, 3]- scores = dets[:, 4]-- areas = (x2 - x1 + 1) * (y2 - y1 + 1)- order = scores.argsort()[::-1]-- keep = []- while order.size > 0:- i = order[0]- keep.append(i)- xx1 = np.maximum(x1[i], x1[order[1:]])- yy1 = np.maximum(y1[i], y1[order[1:]])- xx2 = np.minimum(x2[i], x2[order[1:]])- yy2 = np.minimum(y2[i], y2[order[1:]])-- w = np.maximum(0.0, xx2 - xx1 + 1)- h = np.maximum(0.0, yy2 - yy1 + 1)- inter = w * h- ovr = inter / (areas[i] + areas[order[1:]] - inter)-- inds = np.where(ovr <= threshold)[0]- order = order[inds + 1]-- return keep---def decode_boxes(- loc: np.ndarray,- priors: np.ndarray,- variances: list[float] | None = None,-) -> np.ndarray:- """Decode locations from predictions using priors (RetinaFace specific).-- Undoes the encoding done for offset regression at train time.-- Args:- loc: Location predictions for loc layers, shape: [num_priors, 4].- priors: Prior boxes in center-offset form, shape: [num_priors, 4].- variances: Variances of prior boxes. Defaults to [0.1, 0.2].-- Returns:- Decoded bounding box predictions with shape [num_priors, 4].- """- if variances is None:- variances = [0.1, 0.2]- # Compute centers of predicted boxes- cxcy = priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:]-- # Compute widths and heights of predicted boxes- wh = priors[:, 2:] * np.exp(loc[:, 2:] * variances[1])-- # Convert center, size to corner coordinates- boxes = np.zeros_like(loc)- boxes[:, :2] = cxcy - wh / 2 # xmin, ymin- boxes[:, 2:] = cxcy + wh / 2 # xmax, ymax-- return boxes---def decode_landmarks(- predictions: np.ndarray,- priors: np.ndarray,- variances: list[float] | None = None,-) -> np.ndarray:- """Decode landmark predictions using prior boxes (RetinaFace specific).-- Args:- predictions: Landmark predictions, shape: [num_priors, 10].- priors: Prior boxes, shape: [num_priors, 4].- variances: Scaling factors for landmark offsets. Defaults to [0.1, 0.2].-- Returns:- Decoded landmarks, shape: [num_priors, 10].- """- if variances is None:- variances = [0.1, 0.2]-- # Reshape predictions to [num_priors, 5, 2] to process landmark points- predictions = predictions.reshape(predictions.shape[0], 5, 2)-- # Expand priors to match (num_priors, 5, 2)- priors_xy = np.repeat(priors[:, :2][:, np.newaxis, :], 5, axis=1) # (num_priors, 5, 2)- priors_wh = np.repeat(priors[:, 2:][:, np.newaxis, :], 5, axis=1) # (num_priors, 5, 2)-- # Compute absolute landmark positions- landmarks = priors_xy + predictions * variances[0] * priors_wh-- # Flatten back to [num_priors, 10]- landmarks = landmarks.reshape(landmarks.shape[0], -1)-- return landmarks---def distance2bbox(- points: np.ndarray,- distance: np.ndarray,- max_shape: tuple[int, int] | None = None,-) -> np.ndarray:- """Decode distance prediction to bounding box (SCRFD specific).-- Args:- points: Anchor points with shape (n, 2), [x, y].- distance: Distance from the given point to 4 boundaries- (left, top, right, bottom) with shape (n, 4).- max_shape: Shape of the image (height, width) for clipping.-- Returns:- Decoded bounding boxes with shape (n, 4) as [x1, y1, x2, y2].- """- x1 = points[:, 0] - distance[:, 0]- y1 = points[:, 1] - distance[:, 1]- x2 = points[:, 0] + distance[:, 2]- y2 = points[:, 1] + distance[:, 3]-- if max_shape is not None:- x1 = np.clip(x1, 0, max_shape[1])- y1 = np.clip(y1, 0, max_shape[0])- x2 = np.clip(x2, 0, max_shape[1])- y2 = np.clip(y2, 0, max_shape[0])- else:- x1 = np.maximum(x1, 0)- y1 = np.maximum(y1, 0)- x2 = np.maximum(x2, 0)- y2 = np.maximum(y2, 0)-- return np.stack([x1, y1, x2, y2], axis=-1)---def distance2kps(- points: np.ndarray,- distance: np.ndarray,- max_shape: tuple[int, int] | None = None,-) -> np.ndarray:- """Decode distance prediction to keypoints (SCRFD specific).-- Args:- points: Anchor points with shape (n, 2), [x, y].- distance: Distance from the given point to keypoints with shape (n, 2k).- max_shape: Shape of the image (height, width) for clipping.-- Returns:- Decoded keypoints with shape (n, 2k).- """- preds = []- for i in range(0, distance.shape[1], 2):- px = points[:, i % 2] + distance[:, i]- py = points[:, i % 2 + 1] + distance[:, i + 1]- if max_shape is not None:- px = np.clip(px, 0, max_shape[1])- py = np.clip(py, 0, max_shape[0])- preds.append(px)- preds.append(py)- return np.stack(preds, axis=-1)---def letterbox_resize(- image: np.ndarray,- target_size: int,- fill_value: int = 114,-) -> tuple[np.ndarray, float, tuple[int, int]]:- """Letterbox resize with center padding for YOLO-style detectors.-- Maintains aspect ratio by scaling the image to fit within target_size,- then center-pads with a constant fill value. Converts BGR to RGB,- normalizes to [0, 1], and transposes to NCHW format.-- This preprocessing strategy is standard for YOLO models and ensures- no distortion while maintaining a square input size.-- Args:- image: Input image in BGR format with shape (H, W, C).- target_size: Target square size (e.g., 640 for 640x640 input).- fill_value: Padding fill value (default: 114 for gray background).-- Returns:- Tuple of (preprocessed_tensor, scale_ratio, padding):- - preprocessed_tensor: Shape (1, 3, target_size, target_size),- RGB, normalized [0, 1], NCHW format, float32, contiguous.- - scale_ratio: Resize scale factor for coordinate transformation.- - padding: Padding offsets as (pad_w, pad_h) for coordinate transformation.-- Example:- >>> image = cv2.imread('face.jpg') # (480, 640, 3)- >>> tensor, scale, (pad_w, pad_h) = letterbox_resize(image, 640)- >>> tensor.shape- (1, 3, 640, 640)- >>> # To transform coordinates back to original:- >>> x_orig = (x_detected - pad_w) / scale- >>> y_orig = (y_detected - pad_h) / scale- """- # Get original image shape- img_h, img_w = image.shape[:2]-- # Calculate scale ratio to fit within target_size- scale = min(target_size / img_h, target_size / img_w)- new_h, new_w = int(img_h * scale), int(img_w * scale)-- # Resize image maintaining aspect ratio- img_resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)-- # Create padded canvas with fill_value- img_padded = np.full((target_size, target_size, 3), fill_value, dtype=np.uint8)-- # Calculate padding to center the image- pad_h = (target_size - new_h) // 2- pad_w = (target_size - new_w) // 2-- # Place resized image in center of canvas- img_padded[pad_h : pad_h + new_h, pad_w : pad_w + new_w] = img_resized-- # Convert BGR to RGB and normalize to [0, 1]- img_rgb = cv2.cvtColor(img_padded, cv2.COLOR_BGR2RGB)- img_normalized = img_rgb.astype(np.float32) / 255.0-- # Transpose to CHW format and add batch dimension (NCHW)- img_transposed = np.transpose(img_normalized, (2, 0, 1))- img_batch = np.expand_dims(img_transposed, axis=0)- img_batch = np.ascontiguousarray(img_batch)-- return img_batch, scale, (pad_w, pad_h)+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++import itertools+import math++import cv2+import numpy as np++__all__ = [+ 'decode_boxes',+ 'decode_landmarks',+ 'distance2bbox',+ 'distance2kps',+ 'generate_anchors',+ 'letterbox_resize',+ 'non_max_suppression',+ 'resize_image',+ 'softmax',+ 'validate_image',+ 'xyxy_to_cxcywh',+]+++def validate_image(image: np.ndarray) -> None:+ """Reject images the preprocessing paths below would silently corrupt.++ Both resize helpers paste the input onto a `uint8` canvas: a float image+ would be truncated to zeros (detectors then return no faces with no error),+ and a grayscale or BGRA image would fail to broadcast into the 3-channel+ canvas. Models that warp the input themselves — BlazeFace, FaceMesh — call+ this directly for the same guarantee. Failing loudly here turns silent+ corruption into actionable errors.++ Args:+ image: The caller-supplied image.++ Raises:+ ValueError: If the image is empty, not 3-channel BGR, or not uint8.+ """+ if not isinstance(image, np.ndarray) or image.size == 0:+ raise ValueError('Input image must be a non-empty numpy array.')+ if image.ndim != 3 or image.shape[2] != 3:+ raise ValueError(f'Expected a BGR image of shape (H, W, 3), got {image.shape}. Convert with cv2.cvtColor.')+ if image.dtype != np.uint8:+ raise ValueError(f'Expected dtype uint8, got {image.dtype}. Scale to [0, 255] and cast with .astype(np.uint8).')+++def resize_image(+ frame: np.ndarray,+ target_shape: tuple[int, int] = (640, 640),+) -> tuple[np.ndarray, float]:+ """Resize an image to fit within a target shape while keeping its aspect ratio.++ The image is resized to fit within the target dimensions and placed on a+ blank canvas (zero-padded to target size).++ Args:+ frame: Input image with shape (H, W, C).+ target_shape: Target size as (width, height). Defaults to (640, 640).++ Returns:+ A tuple containing:+ - Resized image on a blank canvas with shape (height, width, 3).+ - The resize factor as a float.++ Raises:+ ValueError: If the image is empty, not 3-channel BGR, or not uint8.+ """+ validate_image(frame)+ width, height = target_shape++ # Aspect-ratio preserving resize+ im_ratio = float(frame.shape[0]) / frame.shape[1]+ model_ratio = height / width+ if im_ratio > model_ratio:+ new_height = height+ new_width = int(new_height / im_ratio)+ else:+ new_width = width+ new_height = int(new_width * im_ratio)++ resize_factor = float(new_height) / frame.shape[0]+ resized_frame = cv2.resize(frame, (new_width, new_height))++ # Create blank image and place resized image on it+ image = np.zeros((height, width, 3), dtype=np.uint8)+ image[:new_height, :new_width, :] = resized_frame++ return image, resize_factor+++def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:+ """Compute the numerically stable softmax of an array along `axis`.++ Args:+ x: Input array.+ axis: Axis along which softmax is computed. Defaults to the last axis.++ Returns:+ Array of the same shape as *x* with values in `[0, 1]` summing to 1+ along *axis*.+ """+ exp_x = np.exp(x - np.max(x, axis=axis, keepdims=True))+ return exp_x / np.sum(exp_x, axis=axis, keepdims=True)+++def xyxy_to_cxcywh(bboxes: np.ndarray) -> np.ndarray:+ """Convert bounding boxes from `[x1, y1, x2, y2]` to `[cx, cy, w, h]`.++ Args:+ bboxes: Array of shape (N, 4) or (4,) with `[x1, y1, x2, y2]` coordinates.++ Returns:+ Array of the same shape with `[cx, cy, w, h]` coordinates.+ """+ out = np.empty_like(bboxes)+ out[..., 0] = (bboxes[..., 0] + bboxes[..., 2]) / 2 # cx+ out[..., 1] = (bboxes[..., 1] + bboxes[..., 3]) / 2 # cy+ out[..., 2] = bboxes[..., 2] - bboxes[..., 0] # w+ out[..., 3] = bboxes[..., 3] - bboxes[..., 1] # h+ return out+++def generate_anchors(image_size: tuple[int, int] = (640, 640)) -> np.ndarray:+ """Generate anchor boxes for a given image size (RetinaFace specific).++ Args:+ image_size: Input image size as (width, height). Defaults to (640, 640).++ Returns:+ Anchor box coordinates as a numpy array with shape (num_anchors, 4).+ """+ # RetinaFace FPN strides and corresponding anchor sizes per level+ steps = [8, 16, 32]+ min_sizes = [[16, 32], [64, 128], [256, 512]]++ anchors = []+ feature_maps = [[math.ceil(image_size[0] / step), math.ceil(image_size[1] / step)] for step in steps]++ for k, (map_height, map_width) in enumerate(feature_maps):+ step = steps[k]+ for i, j in itertools.product(range(map_height), range(map_width)):+ for min_size in min_sizes[k]:+ s_kx = min_size / image_size[1]+ s_ky = min_size / image_size[0]++ dense_cx = [x * step / image_size[1] for x in [j + 0.5]]+ dense_cy = [y * step / image_size[0] for y in [i + 0.5]]+ for cy, cx in itertools.product(dense_cy, dense_cx):+ anchors += [cx, cy, s_kx, s_ky]++ output = np.array(anchors, dtype=np.float32).reshape(-1, 4)+ return output+++def non_max_suppression(dets: np.ndarray, threshold: float) -> list[int]:+ """Apply Non-Maximum Suppression (NMS) to reduce overlapping bounding boxes.++ Args:+ dets: Array of detections with each row as [x1, y1, x2, y2, score].+ threshold: IoU threshold for suppression.++ Returns:+ Indices of bounding boxes retained after suppression.+ """+ x1 = dets[:, 0]+ y1 = dets[:, 1]+ x2 = dets[:, 2]+ y2 = dets[:, 3]+ scores = dets[:, 4]++ areas = (x2 - x1 + 1) * (y2 - y1 + 1)+ order = scores.argsort()[::-1]++ keep = []+ while order.size > 0:+ i = order[0]+ keep.append(i)+ xx1 = np.maximum(x1[i], x1[order[1:]])+ yy1 = np.maximum(y1[i], y1[order[1:]])+ xx2 = np.minimum(x2[i], x2[order[1:]])+ yy2 = np.minimum(y2[i], y2[order[1:]])++ w = np.maximum(0.0, xx2 - xx1 + 1)+ h = np.maximum(0.0, yy2 - yy1 + 1)+ inter = w * h+ ovr = inter / (areas[i] + areas[order[1:]] - inter)++ inds = np.where(ovr <= threshold)[0]+ order = order[inds + 1]++ return keep+++def decode_boxes(+ loc: np.ndarray,+ priors: np.ndarray,+ variances: list[float] | None = None,+) -> np.ndarray:+ """Decode locations from predictions using priors (RetinaFace specific).++ Undoes the encoding done for offset regression at train time.++ Args:+ loc: Location predictions for loc layers, shape: [num_priors, 4].+ priors: Prior boxes in center-offset form, shape: [num_priors, 4].+ variances: Variances of prior boxes. Defaults to [0.1, 0.2].++ Returns:+ Decoded bounding box predictions with shape [num_priors, 4].+ """+ if variances is None:+ variances = [0.1, 0.2]+ # Compute centers of predicted boxes+ cxcy = priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:]++ # Compute widths and heights of predicted boxes+ wh = priors[:, 2:] * np.exp(loc[:, 2:] * variances[1])++ # Convert center, size to corner coordinates+ boxes = np.zeros_like(loc)+ boxes[:, :2] = cxcy - wh / 2 # xmin, ymin+ boxes[:, 2:] = cxcy + wh / 2 # xmax, ymax++ return boxes+++def decode_landmarks(+ predictions: np.ndarray,+ priors: np.ndarray,+ variances: list[float] | None = None,+) -> np.ndarray:+ """Decode landmark predictions using prior boxes (RetinaFace specific).++ Args:+ predictions: Landmark predictions, shape: [num_priors, 10].+ priors: Prior boxes, shape: [num_priors, 4].+ variances: Scaling factors for landmark offsets. Defaults to [0.1, 0.2].++ Returns:+ Decoded landmarks, shape: [num_priors, 10].+ """+ if variances is None:+ variances = [0.1, 0.2]++ # Reshape predictions to [num_priors, 5, 2] to process landmark points+ predictions = predictions.reshape(predictions.shape[0], 5, 2)++ # Expand priors to match (num_priors, 5, 2)+ priors_xy = np.repeat(priors[:, :2][:, np.newaxis, :], 5, axis=1) # (num_priors, 5, 2)+ priors_wh = np.repeat(priors[:, 2:][:, np.newaxis, :], 5, axis=1) # (num_priors, 5, 2)++ # Compute absolute landmark positions+ landmarks = priors_xy + predictions * variances[0] * priors_wh++ # Flatten back to [num_priors, 10]+ landmarks = landmarks.reshape(landmarks.shape[0], -1)++ return landmarks+++def distance2bbox(+ points: np.ndarray,+ distance: np.ndarray,+ max_shape: tuple[int, int] | None = None,+) -> np.ndarray:+ """Decode distance prediction to bounding box (SCRFD specific).++ Args:+ points: Anchor points with shape (n, 2), [x, y].+ distance: Distance from the given point to 4 boundaries+ (left, top, right, bottom) with shape (n, 4).+ max_shape: Shape of the image (height, width) for clipping.++ Returns:+ Decoded bounding boxes with shape (n, 4) as [x1, y1, x2, y2].+ """+ x1 = points[:, 0] - distance[:, 0]+ y1 = points[:, 1] - distance[:, 1]+ x2 = points[:, 0] + distance[:, 2]+ y2 = points[:, 1] + distance[:, 3]++ if max_shape is not None:+ x1 = np.clip(x1, 0, max_shape[1])+ y1 = np.clip(y1, 0, max_shape[0])+ x2 = np.clip(x2, 0, max_shape[1])+ y2 = np.clip(y2, 0, max_shape[0])+ else:+ x1 = np.maximum(x1, 0)+ y1 = np.maximum(y1, 0)+ x2 = np.maximum(x2, 0)+ y2 = np.maximum(y2, 0)++ return np.stack([x1, y1, x2, y2], axis=-1)+++def distance2kps(+ points: np.ndarray,+ distance: np.ndarray,+ max_shape: tuple[int, int] | None = None,+) -> np.ndarray:+ """Decode distance prediction to keypoints (SCRFD specific).++ Args:+ points: Anchor points with shape (n, 2), [x, y].+ distance: Distance from the given point to keypoints with shape (n, 2k).+ max_shape: Shape of the image (height, width) for clipping.++ Returns:+ Decoded keypoints with shape (n, 2k).+ """+ preds = []+ for i in range(0, distance.shape[1], 2):+ px = points[:, i % 2] + distance[:, i]+ py = points[:, i % 2 + 1] + distance[:, i + 1]+ if max_shape is not None:+ px = np.clip(px, 0, max_shape[1])+ py = np.clip(py, 0, max_shape[0])+ preds.append(px)+ preds.append(py)+ return np.stack(preds, axis=-1)+++def letterbox_resize(+ image: np.ndarray,+ target_size: int,+ fill_value: int = 114,+) -> tuple[np.ndarray, float, tuple[int, int]]:+ """Letterbox resize with center padding for YOLO-style detectors.++ Maintains aspect ratio by scaling the image to fit within target_size,+ then center-pads with a constant fill value. Converts BGR to RGB,+ normalizes to [0, 1], and transposes to NCHW format.++ This preprocessing strategy is standard for YOLO models and ensures+ no distortion while maintaining a square input size.++ Args:+ image: Input image in BGR format with shape (H, W, C).+ target_size: Target square size (e.g., 640 for 640x640 input).+ fill_value: Padding fill value (default: 114 for gray background).++ Returns:+ Tuple of (preprocessed_tensor, scale_ratio, padding):+ - preprocessed_tensor: Shape (1, 3, target_size, target_size),+ RGB, normalized [0, 1], NCHW format, float32, contiguous.+ - scale_ratio: Resize scale factor for coordinate transformation.+ - padding: Padding offsets as (pad_w, pad_h) for coordinate transformation.++ Example:+ >>> image = cv2.imread('face.jpg') # (480, 640, 3)+ >>> tensor, scale, (pad_w, pad_h) = letterbox_resize(image, 640)+ >>> tensor.shape+ (1, 3, 640, 640)+ >>> # To transform coordinates back to original:+ >>> x_orig = (x_detected - pad_w) / scale+ >>> y_orig = (y_detected - pad_h) / scale++ Raises:+ ValueError: If the image is empty, not 3-channel BGR, or not uint8.+ """+ validate_image(image)++ # Get original image shape+ img_h, img_w = image.shape[:2]++ # Calculate scale ratio to fit within target_size+ scale = min(target_size / img_h, target_size / img_w)+ new_h, new_w = int(img_h * scale), int(img_w * scale)++ # Resize image maintaining aspect ratio+ img_resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)++ # Create padded canvas with fill_value+ img_padded = np.full((target_size, target_size, 3), fill_value, dtype=np.uint8)++ # Calculate padding to center the image+ pad_h = (target_size - new_h) // 2+ pad_w = (target_size - new_w) // 2++ # Place resized image in center of canvas+ img_padded[pad_h : pad_h + new_h, pad_w : pad_w + new_w] = img_resized++ # Convert BGR to RGB and normalize to [0, 1]+ img_rgb = cv2.cvtColor(img_padded, cv2.COLOR_BGR2RGB)+ img_normalized = img_rgb.astype(np.float32) / 255.0++ # Transpose to CHW format and add batch dimension (NCHW)+ img_transposed = np.transpose(img_normalized, (2, 0, 1))+ img_batch = np.expand_dims(img_transposed, axis=0)+ img_batch = np.ascontiguousarray(img_batch)++ return img_batch, scale, (pad_w, pad_h)diff --git a/uniface/constants.py b/uniface/constants.pyindex 873217d..37f14da 100644--- a/uniface/constants.py+++ b/uniface/constants.py@@ -21,18 +21,27 @@ class ModelInfo:sha256: str+DOWNLOAD_CHUNK_SIZE = 256 * 1024 # 256 KiB+HASH_CHUNK_SIZE = 1024 * 1024 # 1 MiB++# Fallback source when a primary (GitHub Releases) URL is unreachable. Pinned to a+# commit SHA so the fallback serves immutable bytes, matching the SHA-256 guarantee+# of the primary path. Bump the SHA whenever new weights land in the mirror repo.+HF_MIRROR_URL = 'https://huggingface.co/yakhyo/uniface-weights/resolve/4c7ed723a20deb7ff154b1ba7d6e73747d954016'++# fmt: offclass SphereFaceWeights(str, Enum):- """- Trained on MS1M V2 dataset with 5.8 million images of 85k identities.+ """Trained on MS1M V2 dataset with 5.8 million images of 85k identities.+https://github.com/yakhyo/face-recognition"""SPHERE20 = "sphere20"SPHERE36 = "sphere36"class MobileFaceWeights(str, Enum):- """- Trained on MS1M V2 dataset with 5.8 million images of 85k identities.+ """Trained on MS1M V2 dataset with 5.8 million images of 85k identities.+https://github.com/yakhyo/face-recognition"""MNET_025 = "mobilenetv1_025"@@ -41,8 +50,8 @@ class MobileFaceWeights(str, Enum):MNET_V3_LARGE = "mobilenetv3_large"class ArcFaceWeights(str, Enum):- """- Pretrained weights from ArcFace model (insightface).+ """Pretrained weights from ArcFace model (insightface).+https://github.com/deepinsight/insightface"""MNET = "arcface_mnet"@@ -50,16 +59,16 @@ class ArcFaceWeights(str, Enum):class AdaFaceWeights(str, Enum):- """- AdaFace model weights trained on WebFace datasets.+ """AdaFace model weights trained on WebFace datasets.+https://github.com/yakhyo/adaface-onnx"""IR_18 = "adaface_ir_18"IR_101 = "adaface_ir_101"class EdgeFaceWeights(str, Enum):- """- EdgeFace: Efficient Face Recognition Model for Edge Devices.+ """EdgeFace: Efficient Face Recognition Model for Edge Devices.+Based on EdgeNeXt backbone with optional LoRA low-rank compression.All models output 512-D embeddings from 112x112 aligned face crops.https://github.com/yakhyo/edgeface-onnx@@ -70,8 +79,8 @@ class EdgeFaceWeights(str, Enum):BASE = "edgeface_base"class RetinaFaceWeights(str, Enum):- """- Trained on WIDER FACE dataset.+ """Trained on WIDER FACE dataset.+https://github.com/yakhyo/retinaface-pytorch"""MNET_025 = "retinaface_mnet025"@@ -84,17 +93,49 @@ class RetinaFaceWeights(str, Enum):class SCRFDWeights(str, Enum):- """- Trained on WIDER FACE dataset.+ """Trained on WIDER FACE dataset.+https://github.com/deepinsight/insightface"""SCRFD_10G_KPS = "scrfd_10g"SCRFD_500M_KPS = "scrfd_500m"-class YOLOv5FaceWeights(str, Enum):+class CenterFaceWeights(str, Enum):+ """CenterFace: Joint Face Detection and Alignment Using Face as Point.++ Anchor-free detector (MobileNetV2 + FPN) with 5-point landmarks, trained on WIDER FACE.+ Paper: https://arxiv.org/abs/1911.03599+ Original weights: https://github.com/Star-Clouds/CenterFace++ Re-exported to ONNX (opset 17, dynamic batch/height/width) from the original+ weights; outputs verified numerically identical to the upstream model.++ Model Performance (WIDER FACE val, single inference on the original image):+ - 92.2% Easy / 91.1% Medium / 78.2% Hard"""- Trained on WIDER FACE dataset.+ DEFAULT = "centerface"+++class BlazeFaceWeights(str, Enum):+ """BlazeFace short-range: SSD face detector on a 128x128 letterboxed image.++ The detector MediaPipe's Face Mesh seeds from, reproducing its exact output.++ Emits 6 keypoints (right eye, left eye, nose tip, mouth center, right ear+ tragion, left ear tragion) rather than the 5-point alignment template, so it+ cannot feed recognition, quality scoring, or XSeg parsing.++ Short-range: tuned for faces within ~2m and weaker on WIDER FACE than+ SCRFD/YOLOv8. Its value is 460KB and MediaPipe parity, not general detection.+ https://github.com/yakhyo/mediapipe-face-mesh-onnx+ """+ DEFAULT = "blazeface" # face_detection_short_range+++class YOLOv5FaceWeights(str, Enum):+ """Trained on WIDER FACE dataset.+Original implementation: https://github.com/deepcam-cn/yolov5-faceExported to ONNX from: https://github.com/yakhyo/yolov5-face-onnx-inference@@ -109,8 +150,8 @@ class YOLOv5FaceWeights(str, Enum):class YOLOv8FaceWeights(str, Enum):- """- YOLOv8-Face models trained on WIDER FACE dataset.+ """YOLOv8-Face models trained on WIDER FACE dataset.+Uses anchor-free design with DFL (Distribution Focal Loss) for bbox regression.Exported to ONNX from: https://github.com/yakhyo/yolov8-face-onnx-inference@@ -122,9 +163,9 @@ class YOLOv8FaceWeights(str, Enum):YOLOV8N = "yolov8n_face"-class DDAMFNWeights(str, Enum):- """- Trained on AffectNet dataset.+class EmotionWeights(str, Enum):+ """DDAMFN emotion recognition models trained on AffectNet dataset.+https://github.com/SainingZhang/DDAMFN/tree/main/DDAMFN"""AFFECNET7 = "affecnet7"@@ -132,33 +173,45 @@ class DDAMFNWeights(str, Enum):class AgeGenderWeights(str, Enum):- """- Trained on CelebA dataset.+ """Trained on CelebA dataset.+https://github.com/deepinsight/insightface"""DEFAULT = "age_gender"class FairFaceWeights(str, Enum):- """- FairFace attribute prediction (race, gender, age).+ """FairFace attribute prediction (race, gender, age).+Trained on FairFace dataset with balanced demographics.https://github.com/yakhyo/fairface-onnx"""DEFAULT = "fairface"-class LandmarkWeights(str, Enum):+class FaceAttribNetWeights(str, Enum):+ """FaceAttribNet (Qualcomm "Facial-Attribute-Detection").++ Predicts five independent binary face attributes from a 128x128 face crop:+ left/right eye openness, eyeglasses, sunglasses, and face mask.+ Trained by Qualcomm on a proprietary face dataset.+ https://github.com/qualcomm/ai-hub-models/tree/main/src/qai_hub_models/models/face_attrib_net+ https://github.com/yakhyo/face-attribute"""- MobileNet 0.5 from Insightface+ DEFAULT = "face_attrib_net"+++class LandmarkWeights(str, Enum):+ """MobileNet 0.5 from Insightface+https://github.com/deepinsight/insightface/tree/master/alignment/coordinate_reg"""DEFAULT = "2d_106"class PIPNetWeights(str, Enum):- """- PIPNet: Pixel-in-Pixel Net for facial landmark detection.+ """PIPNet: Pixel-in-Pixel Net for facial landmark detection.+ResNet-18 backbone, 256x256 input.https://github.com/yakhyo/pipnet-onnx"""@@ -166,9 +219,33 @@ class PIPNetWeights(str, Enum):DW300_CELEBA_68 = "pipnet_r18_300w_celeba_68"-class GazeWeights(str, Enum):+class FaceMeshWeights(str, Enum):+ """MediaPipe dense face landmarks, in two generations.++ V1 is the classic Face Mesh: 468 landmarks from a 192x192 crop.+ V2 is MediaPipe's Face Landmarker, the model its current Tasks API ships: 478+ landmarks from a 256x256 crop — the same 468 points in the same order, plus ten+ iris points (468-472 left, 473-477 right, each ordered center, right, top, left,+ bottom). Its z is predicted rather than derived, but Google trains z on synthetic+ data and excludes it from their own accuracy evaluation, so treat it as a weaker+ signal than x/y in both models.++ Both are detector-agnostic, take the same ROI, and have a dynamic batch dimension,+ so they are interchangeable apart from the point count. V2 costs roughly 3x the+ multiply-accumulates; prefer V1 unless you need the irises.++ Architectures recovered from Google's MediaPipe. V1's weights were sourced through+ PINTO0309's ONNX conversion; V2's were read directly from the .tflite in Google's+ face_landmarker.task bundle.+ https://github.com/yakhyo/mediapipe-face-mesh-onnx"""- MobileGaze: Real-Time Gaze Estimation models.+ V1_468 = "face_mesh"+ V2_478 = "face_landmarker"+++class GazeWeights(str, Enum):+ """MobileGaze: Real-Time Gaze Estimation models.+Trained on Gaze360 dataset.https://github.com/yakhyo/gaze-estimation"""@@ -180,8 +257,8 @@ class GazeWeights(str, Enum):class HeadPoseWeights(str, Enum):- """- Head pose estimation models using 6D rotation representation.+ """Head pose estimation models using 6D rotation representation.+Trained on 300W-LP dataset, evaluated on AFLW2000.https://github.com/yakhyo/head-pose-estimation"""@@ -194,8 +271,8 @@ class HeadPoseWeights(str, Enum):class ParsingWeights(str, Enum):- """- Face Parsing: Semantic Segmentation of Facial Components.+ """Face Parsing: Semantic Segmentation of Facial Components.+Trained on CelebAMask-HQ dataset.https://github.com/yakhyo/face-parsing"""@@ -204,8 +281,8 @@ class ParsingWeights(str, Enum):class XSegWeights(str, Enum):- """- XSeg face segmentation model from DeepFaceLab.+ """XSeg face segmentation model from DeepFaceLab.+Outputs mask for face region.https://github.com/iperov/DeepFaceLab"""@@ -213,8 +290,8 @@ class XSegWeights(str, Enum):class MODNetWeights(str, Enum):- """- MODNet: Real-Time Trimap-Free Portrait Matting via Objective Decomposition.+ """MODNet: Real-Time Trimap-Free Portrait Matting via Objective Decomposition.+https://github.com/yakhyo/modnet"""PHOTOGRAPHIC = "modnet_photographic"@@ -222,8 +299,8 @@ class MODNetWeights(str, Enum):class MiniFASNetWeights(str, Enum):- """- MiniFASNet: Lightweight Face Anti-Spoofing models.+ """MiniFASNet: Lightweight Face Anti-Spoofing models.+Trained on face anti-spoofing datasets.https://github.com/yakhyo/face-anti-spoofing@@ -236,8 +313,8 @@ class MiniFASNetWeights(str, Enum):class EDifFIQAWeights(str, Enum):- """- eDifFIQA: Face Image Quality Assessment.+ """eDifFIQA: Face Image Quality Assessment.+Predicts a single quality score from an aligned 112x112 face.Higher score = better quality.@@ -363,6 +440,18 @@ MODEL_REGISTRY: dict[Enum, ModelInfo] = {sha256='5e4447f50245bbd7966bd6c0fa52938c61474a04ec7def48753668a9d8b4ea3a'),+ # CenterFace+ CenterFaceWeights.DEFAULT: ModelInfo(+ url='https://github.com/yakhyo/uniface/releases/download/weights/centerface.onnx',+ sha256='f50be8b97eae35b969905619136765897e401171ab4f92aa2b8c9909292d2ba0'+ ),++ # BlazeFace (MediaPipe short-range)+ BlazeFaceWeights.DEFAULT: ModelInfo(+ url='https://github.com/yakhyo/uniface/releases/download/weights/face_detection_short_range.onnx',+ sha256='2f2689b040becf555706d2cb978d2f0e3296ea82413734fba9a856c66c5f2b17'+ ),+# YOLOv5-FaceYOLOv5FaceWeights.YOLOV5N: ModelInfo(url='https://github.com/yakhyo/yolov5-face-onnx-inference/releases/download/weights/yolov5n_face.onnx',@@ -387,12 +476,12 @@ MODEL_REGISTRY: dict[Enum, ModelInfo] = {sha256='33f3951af7fc0c4d9b321b29cdcd8c9a59d0a29a8d4bdc01fcb5507d5c714809'),- # DDAFM- DDAMFNWeights.AFFECNET7: ModelInfo(+ # Emotion (DDAMFN)+ EmotionWeights.AFFECNET7: ModelInfo(url='https://github.com/yakhyo/uniface/releases/download/weights/affecnet7.script',sha256='10535bf8b6afe8e9d6ae26cea6c3add9a93036e9addb6adebfd4a972171d015d'),- DDAMFNWeights.AFFECNET8: ModelInfo(+ EmotionWeights.AFFECNET8: ModelInfo(url='https://github.com/yakhyo/uniface/releases/download/weights/affecnet8.script',sha256='8c66963bc71db42796a14dfcbfcd181b268b65a3fc16e87147d6a3a3d7e0f487'),@@ -409,6 +498,12 @@ MODEL_REGISTRY: dict[Enum, ModelInfo] = {sha256='9c8c47d437cd310538d233f2465f9ed0524cb7fb51882a37f74e8bc22437fdbf'),+ # FaceAttribNet+ FaceAttribNetWeights.DEFAULT: ModelInfo(+ url='https://github.com/yakhyo/uniface/releases/download/weights/face_attrib_net.onnx',+ sha256='1bf7c6453bec2fb28e0830f3a76dceb9ffd020124f87b28da5355940a7bc6e48'+ ),+# LandmarksLandmarkWeights.DEFAULT: ModelInfo(url='https://github.com/yakhyo/uniface/releases/download/weights/2d106det.onnx',@@ -425,6 +520,16 @@ MODEL_REGISTRY: dict[Enum, ModelInfo] = {sha256='63fa56fd4b8f6ccc4b88f2b36e00fa3d8c21a2c4244ab9381e8b432cef35197b'),+ # Face Mesh (468 dense 3D landmarks) and Face Landmarker (478, with irises)+ FaceMeshWeights.V1_468: ModelInfo(+ url='https://github.com/yakhyo/uniface/releases/download/weights/face_mesh_Nx3x192x192.onnx',+ sha256='3ca77cf59c18e4da0eccb46695bf604683fa564253e3385892981a5c274fb10f'+ ),+ FaceMeshWeights.V2_478: ModelInfo(+ url='https://github.com/yakhyo/uniface/releases/download/weights/face_landmarker_Nx3x256x256.onnx',+ sha256='111795f8703cdeb6d0c68a9f3cc966a0f23f8786bb00f4577a11f461fc4276ac'+ ),+# Gaze (MobileGaze)GazeWeights.RESNET18: ModelInfo(url='https://github.com/yakhyo/gaze-estimation/releases/download/weights/resnet18_gaze.onnx',@@ -527,11 +632,3 @@ MODEL_REGISTRY: dict[Enum, ModelInfo] = {sha256='72238239298cf645d3f5954d657b4aca7b64fd25bc808c0260778386da9b00a1'),}---# Backward compatibility (optional, can be removed if all code uses MODEL_REGISTRY)-MODEL_URLS: dict[Enum, str] = {k: v.url for k, v in MODEL_REGISTRY.items()}-MODEL_SHA256: dict[Enum, str] = {k: v.sha256 for k, v in MODEL_REGISTRY.items()}--DOWNLOAD_CHUNK_SIZE = 256 * 1024 # 256 KiB-HASH_CHUNK_SIZE = 1024 * 1024 # 1 MiBdiff --git a/uniface/detection/__init__.py b/uniface/detection/__init__.pyindex 051ed03..b818698 100644--- a/uniface/detection/__init__.py+++ b/uniface/detection/__init__.py@@ -4,155 +4,20 @@from __future__ import annotations-from typing import Any--from typing_extensions import deprecated--from uniface.constants import (- RetinaFaceWeights,- SCRFDWeights,- YOLOv5FaceWeights,- YOLOv8FaceWeights,-)-from .base import BaseDetector+from .blazeface import BlazeFace+from .centerface import CenterFacefrom .retinaface import RetinaFacefrom .scrfd import SCRFDfrom .yolov5 import YOLOv5Facefrom .yolov8 import YOLOv8Face--@deprecated(- 'create_detector() is deprecated and will be removed in uniface 4.0. '- 'Instantiate the detector class directly, e.g. '- '`from uniface.detection import SCRFD; SCRFD(**kwargs)`.'-)-def create_detector(method: str = 'retinaface', **kwargs: Any) -> BaseDetector:- """Factory function to create face detectors.-- .. deprecated:: 3.7.0- Use the detector class directly (``RetinaFace``, ``SCRFD``,- ``YOLOv5Face``, ``YOLOv8Face``). This factory will be removed in- uniface 4.0.-- Args:- method: Detection method. Options:- - 'retinaface': RetinaFace detector (default)- - 'scrfd': SCRFD detector (fast and accurate)- - 'yolov5face': YOLOv5-Face detector (accurate with landmarks)- - 'yolov8face': YOLOv8-Face detector (anchor-free, accurate)- **kwargs: Detector-specific parameters.-- Returns:- Initialized detector instance.-- Raises:- ValueError: If method is not supported.-- Example:- >>> # Basic usage- >>> from uniface.detection import RetinaFace- >>> detector = RetinaFace()-- >>> # SCRFD detector with custom parameters- >>> from uniface.detection import SCRFD- >>> from uniface.constants import SCRFDWeights- >>> detector = SCRFD(model_name=SCRFDWeights.SCRFD_10G_KPS, confidence_threshold=0.8, input_size=(640, 640))-- >>> # YOLOv8-Face detector- >>> from uniface.detection import YOLOv8Face- >>> from uniface.constants import YOLOv8FaceWeights- >>> detector = YOLOv8Face(model_name=YOLOv8FaceWeights.YOLOV8N, confidence_threshold=0.5)- """- method = method.lower()-- if method == 'retinaface':- return RetinaFace(**kwargs)-- elif method == 'scrfd':- return SCRFD(**kwargs)-- elif method == 'yolov5face':- return YOLOv5Face(**kwargs)-- elif method == 'yolov8face':- return YOLOv8Face(**kwargs)-- else:- available_methods = ['retinaface', 'scrfd', 'yolov5face', 'yolov8face']- raise ValueError(f"Unsupported detection method: '{method}'. Available methods: {available_methods}")---@deprecated(- 'list_available_detectors() is deprecated and will be removed in uniface 4.0. '- 'Import the detector classes directly from `uniface.detection` instead.'-)-def list_available_detectors() -> dict[str, dict[str, Any]]:- """List all available detection methods with their descriptions and parameters.-- .. deprecated:: 3.7.0- Import the detector classes (``RetinaFace``, ``SCRFD``, ``YOLOv5Face``,- ``YOLOv8Face``) directly from ``uniface.detection``. This helper will be- removed in uniface 4.0.-- Returns:- Dictionary mapping detector names to their information including- description, landmark support, paper reference, and default parameters.- """- return {- 'retinaface': {- 'description': 'RetinaFace detector with high accuracy',- 'supports_landmarks': True,- 'paper': 'https://arxiv.org/abs/1905.00641',- 'default_params': {- 'model_name': RetinaFaceWeights.MNET_V2.value,- 'confidence_threshold': 0.5,- 'nms_threshold': 0.4,- 'input_size': (640, 640),- },- },- 'scrfd': {- 'description': 'SCRFD detector - fast and accurate with efficient architecture',- 'supports_landmarks': True,- 'paper': 'https://arxiv.org/abs/2105.04714',- 'default_params': {- 'model_name': SCRFDWeights.SCRFD_10G_KPS.value,- 'confidence_threshold': 0.5,- 'nms_threshold': 0.4,- 'input_size': (640, 640),- },- },- 'yolov5face': {- 'description': 'YOLOv5-Face detector - accurate face detection with landmarks',- 'supports_landmarks': True,- 'paper': 'https://arxiv.org/abs/2105.12931',- 'default_params': {- 'model_name': YOLOv5FaceWeights.YOLOV5S.value,- 'confidence_threshold': 0.6,- 'nms_threshold': 0.5,- 'input_size': 640,- },- },- 'yolov8face': {- 'description': 'YOLOv8-Face detector - anchor-free design with DFL for accurate detection',- 'supports_landmarks': True,- 'paper': 'https://github.com/derronqi/yolov8-face',- 'default_params': {- 'model_name': YOLOv8FaceWeights.YOLOV8N.value,- 'confidence_threshold': 0.5,- 'nms_threshold': 0.45,- 'input_size': 640,- },- },- }--__all__ = ['SCRFD','BaseDetector',+ 'BlazeFace',+ 'CenterFace','RetinaFace','YOLOv5Face','YOLOv8Face',- 'create_detector',- 'list_available_detectors',]diff --git a/uniface/detection/base.py b/uniface/detection/base.pyindex 033a5a5..6eb4caa 100644--- a/uniface/detection/base.py+++ b/uniface/detection/base.py@@ -22,9 +22,21 @@ class BaseDetector(ABC):Attributes:config: Dictionary containing detector configuration parameters.- _supports_landmarks: Flag indicating if detector supports landmark detection.+ supports_landmarks: Whether the detector emits facial landmarks alongside boxes.+ Opt-in: defaults to False so a subclass that only produces boxes is never+ mistaken for a landmark detector. False means `Face.landmarks` is empty and+ landmark-driven stages are unavailable.+ supports_alignment: Whether those landmarks fit the 5-point alignment template+ (left eye, right eye, nose, left mouth corner, right mouth corner) in+ `uniface.face_utils.reference_alignment`. False means recognition, quality+ scoring, and XSeg parsing cannot consume them. Also opt-in: a boxes-only+ subclass that declares neither flag is safe by default, and setting this to+ True without `supports_landmarks = True` is meaningless."""+ supports_landmarks: bool = False+ supports_alignment: bool = False+def __init__(self, **kwargs: Any) -> None:"""Initialize the detector with configuration parameters.@@ -32,7 +44,6 @@ class BaseDetector(ABC):**kwargs: Detector-specific configuration parameters."""self.config: dict[str, Any] = kwargs- self._supports_landmarks: bool = False@abstractmethoddef detect(self, image: np.ndarray, **kwargs: Any) -> list[Face]:@@ -46,14 +57,15 @@ class BaseDetector(ABC):List of detected Face objects, each containing:- bbox: Bounding box coordinates with shape (4,) as [x1, y1, x2, y2].- confidence: Detection confidence score (0.0 to 1.0).- - landmarks: Facial landmarks with shape (5, 2) for 5-point landmarks.+ - landmarks: Facial landmarks with shape (K, 2). K is 5 for detectors+ whose `supports_alignment` is True; BlazeFace emits 6.Example:>>> faces = detector.detect(image)>>> for face in faces:... bbox = face.bbox # np.ndarray with shape (4,)... confidence = face.confidence # float- ... landmarks = face.landmarks # np.ndarray with shape (5, 2)+ ... landmarks = face.landmarks # np.ndarray with shape (K, 2)"""@abstractmethod@@ -87,24 +99,16 @@ class BaseDetector(ABC):"""Detailed string representation."""return self.__str__()- @property- def supports_landmarks(self) -> bool:- """Whether this detector supports landmark detection.-- Returns:- True if landmarks are supported, False otherwise.- """- return hasattr(self, '_supports_landmarks') and self._supports_landmarks-def get_info(self) -> dict[str, Any]:"""Get detector information and configuration.Returns:- Dictionary containing detector name, landmark support, and config.+ Dictionary containing detector name, landmark support, alignment support, and config."""return {'name': self.__class__.__name__,- 'supports_landmarks': self._supports_landmarks,+ 'supports_landmarks': self.supports_landmarks,+ 'supports_alignment': self.supports_alignment,'config': self.config,}@@ -136,7 +140,7 @@ class BaseDetector(ABC):Args:detections: Array of shape (N, 5) as [x1, y1, x2, y2, confidence].- landmarks: Array of shape (N, 5, 2) for 5-point landmarks.+ landmarks: Array of shape (N, K, 2). Only axis 0 is indexed, so any K works.max_num: Maximum number of faces to keep. If 0 or >= N, returns all.original_shape: Original image shape as (height, width).metric: Ranking metric:@@ -179,7 +183,7 @@ class BaseDetector(ABC):Args:detections: Array of shape (N, 5) as [x1, y1, x2, y2, confidence].- landmarks: Array of shape (N, 5, 2) for 5-point landmarks.+ landmarks: Array of shape (N, K, 2). Only axis 0 is indexed, so any K works.Returns:List of Face objects.diff --git a/uniface/detection/blazeface.py b/uniface/detection/blazeface.pynew file mode 100644index 0000000..26aa229--- /dev/null+++ b/uniface/detection/blazeface.py@@ -0,0 +1,346 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++from typing import Literal++import cv2+import numpy as np++from uniface.common import validate_image+from uniface.constants import BlazeFaceWeights+from uniface.log import Logger+from uniface.model_store import verify_model_weights+from uniface.onnx_utils import create_onnx_session+from uniface.types import Face++from .base import BaseDetector++__all__ = ['BlazeFace']++# Keypoint order: right eye, left eye, nose tip, mouth center, right ear, left ear.+# FaceMesh reads rows 0/1 for the ROI roll angle+_NUM_KEYPOINTS = 6++# SsdAnchorsCalculator config for face_detection_short_range; hardcoded because every+# output dimension except the input size is a dynamic symbol in the ONNX metadata+_ANCHOR_STRIDES = (8, 16, 16, 16)+_NUM_ANCHORS = 896++# MediaPipe's score_clipping_thresh, applied before the sigmoid+_SCORE_CLIP = 100.0+++def _generate_face_anchors(input_size: int) -> np.ndarray:+ """Build the SSD anchor centers for the short-range face detector.++ Layers sharing a stride stack their anchors per cell, giving 16x16x2 + 8x8x6 = 896+ anchors at 128px (aspect ratio 1.0, one interpolated scale, fixed anchor size).++ Args:+ input_size: The model's input edge length in pixels.++ Returns:+ Normalized (896, 2) anchor centers.++ Raises:+ ValueError: If the anchor count does not match the exported head.+ """+ anchors = []+ idx = 0+ while idx < len(_ANCHOR_STRIDES):+ last = idx+ while last < len(_ANCHOR_STRIDES) and _ANCHOR_STRIDES[last] == _ANCHOR_STRIDES[idx]:+ last += 1+ repeats = 2 * (last - idx)+ cells = input_size // _ANCHOR_STRIDES[idx]+ for y in range(cells):+ for x in range(cells):+ anchors.extend([((x + 0.5) / cells, (y + 0.5) / cells)] * repeats)+ idx = last++ if len(anchors) != _NUM_ANCHORS:+ raise ValueError(f'Expected {_NUM_ANCHORS} anchors for a {input_size}px input, generated {len(anchors)}')++ return np.array(anchors)+++def _weighted_nms(detections: np.ndarray, iou_threshold: float) -> np.ndarray:+ """Apply MediaPipe's *weighted* non-maximum suppression.++ Overlapping candidates are score-averaged into the winner rather than discarded,+ boxes and keypoints alike, so `common.non_max_suppression` cannot be reused.++ Args:+ detections: Rows of (score, cx, cy, w, h, kp0x, kp0y, ...), normalized.+ iou_threshold: Overlap above which candidates are blended into the winner.++ Returns:+ Blended detections in the same row layout, highest score first.+ """+ remaining = detections[np.argsort(-detections[:, 0])]+ output = []+ while len(remaining):+ top = remaining[0]+ x1 = remaining[:, 1] - remaining[:, 3] / 2+ y1 = remaining[:, 2] - remaining[:, 4] / 2+ x2 = remaining[:, 1] + remaining[:, 3] / 2+ y2 = remaining[:, 2] + remaining[:, 4] / 2+ tx1, ty1 = top[1] - top[3] / 2, top[2] - top[4] / 2+ tx2, ty2 = top[1] + top[3] / 2, top[2] + top[4] / 2++ inter = np.maximum(0, np.minimum(x2, tx2) - np.maximum(x1, tx1)) * np.maximum(+ 0, np.minimum(y2, ty2) - np.maximum(y1, ty1)+ )+ union = (x2 - x1) * (y2 - y1) + (tx2 - tx1) * (ty2 - ty1) - inter+ iou = inter / np.maximum(union, 1e-9)++ # The winner joins its own blend unconditionally. Relying on its self-IoU clearing+ # the threshold loops forever when it cannot: iou_threshold=1.0 fails the strict+ # `>`, and a zero-area box scores an IoU of 0 against itself.+ merge = iou > iou_threshold+ merge[0] = True++ overlapping = remaining[merge]+ weights = overlapping[:, :1]+ blended = top.copy()+ total_weight = weights.sum()+ if total_weight > 0:+ blended[1:] = (overlapping[:, 1:] * weights).sum(axis=0) / total_weight+ output.append(blended)+ remaining = remaining[~merge]++ return np.array(output)+++class BlazeFace(BaseDetector):+ """Short-range face detector based on the BlazeFace architecture (MediaPipe).++ Title: "BlazeFace: Sub-millisecond Neural Face Detection on Mobile GPUs"+ Paper: https://arxiv.org/abs/1907.05047+ Code: https://github.com/google-ai-edge/mediapipe++ An SSD detector over two anchor grids on a 128x128 letterboxed image, decoded with+ MediaPipe's *weighted* NMS: overlapping candidates are score-averaged, not discarded.+ This is the detector `mp.solutions.face_mesh` runs internally, so pairing it with+ `FaceMesh` reproduces MediaPipe's own output.++ Note:+ Emits 6 MediaPipe keypoints rather than the 5-point alignment template, so+ `supports_alignment` is False: recognition, quality scoring, and XSeg parsing+ cannot consume them, and `FaceAnalyzer` disables recognition with a warning.+ Short-range covers faces within roughly 2m and scores below SCRFD/YOLOv8 on+ WIDER FACE; choose it for its 460KB footprint or for MediaPipe parity.++ Args:+ model_name (BlazeFaceWeights): Predefined model enum. Defaults to BlazeFaceWeights.DEFAULT.+ confidence_threshold (float): Confidence threshold for filtering detections. Defaults to 0.5.+ nms_threshold (float): IoU above which candidates are blended. Defaults to 0.3.+ providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detects+ the best available provider. Example: ['CPUExecutionProvider'] to force CPU.++ Attributes:+ model_name (BlazeFaceWeights): Selected model variant.+ confidence_threshold (float): Threshold used to filter low-confidence detections.+ nms_threshold (float): Threshold used during weighted NMS to blend overlapping boxes.+ input_size (int): Input edge length read from the model. 128 for the short-range weights.+ anchors (np.ndarray): Precomputed anchor centers with shape (896, 2), normalized.+ _model_path (str): Absolute path to the downloaded/verified model weights.++ Raises:+ ValueError: If the generated anchor count does not match the exported head.+ RuntimeError: If the ONNX model fails to load or initialize.+ """++ supports_landmarks = True+ supports_alignment = False++ def __init__(+ self,+ *,+ model_name: BlazeFaceWeights = BlazeFaceWeights.DEFAULT,+ confidence_threshold: float = 0.5,+ nms_threshold: float = 0.3,+ providers: list[str] | None = None,+ ) -> None:+ super().__init__(+ model_name=model_name,+ confidence_threshold=confidence_threshold,+ nms_threshold=nms_threshold,+ providers=providers,+ )++ self.model_name = model_name+ self.confidence_threshold = confidence_threshold+ self.nms_threshold = nms_threshold+ self.providers = providers++ Logger.info(+ f'Initializing BlazeFace with model={self.model_name}, '+ f'confidence_threshold={self.confidence_threshold}, '+ f'nms_threshold={self.nms_threshold}'+ )++ self._model_path = verify_model_weights(self.model_name)+ Logger.info(f'Verified model weights located at: {self._model_path}')++ self._initialize_model(self._model_path)++ def _initialize_model(self, model_path: str) -> None:+ """Initialize the ONNX session and precompute the SSD anchors.++ Args:+ model_path: The file path to the ONNX model.++ Raises:+ RuntimeError: If the model fails to load.+ """+ try:+ self.session = create_onnx_session(model_path, providers=self.providers)+ self.input_names = self.session.get_inputs()[0].name+ self.output_names = [x.name for x in self.session.get_outputs()]++ # Only the input size survives export as a concrete dimension+ self.input_size = int(self.session.get_inputs()[0].shape[2])+ self.anchors = _generate_face_anchors(self.input_size)++ Logger.info(f'Successfully initialized the model from {model_path}')+ except Exception as e:+ Logger.error(f"Failed to load model from '{model_path}': {e}", exc_info=True)+ raise RuntimeError(f"Failed to initialize model session for '{model_path}'") from e++ def preprocess(self, image: np.ndarray) -> np.ndarray:+ """Convert a letterboxed BGR canvas into the network input tensor.++ BlazeFace expects RGB normalized to [-1, 1], unlike the landmark models' [0, 1].++ Args:+ image: Letterboxed canvas with shape (input_size, input_size, 3) in BGR.++ Returns:+ Preprocessed tensor with shape (1, 3, input_size, input_size).+ """+ rgb = image[:, :, ::-1].astype(np.float32)+ blob = np.transpose((rgb - 127.5) / 127.5, (2, 0, 1))+ return blob[np.newaxis]++ def postprocess(+ self,+ outputs: list[np.ndarray],+ scale: float,+ pad_x: float,+ pad_y: float,+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """Decode anchor predictions into full-image detections.++ Args:+ outputs: Raw outputs [regressors (1, 896, 16), logits (1, 896, 1)].+ scale: Letterbox scale factor applied in `detect`.+ pad_x: Horizontal letterbox padding in canvas pixels.+ pad_y: Vertical letterbox padding in canvas pixels.++ Returns:+ Tuple of (bboxes (N, 4), keypoints (N, 6, 2), scores (N,)) in+ full-image pixel coordinates.+ """+ regressors, logits = outputs+ size = self.input_size++ # Clipped before the sigmoid: strongly-negative anchor logits overflow np.exp+ raw = np.clip(logits[0].ravel().astype(np.float64), -_SCORE_CLIP, _SCORE_CLIP)+ scores = 1.0 / (1.0 + np.exp(-raw))+ keep = scores >= self.confidence_threshold+ if not keep.any():+ return (+ np.empty((0, 4), dtype=np.float32),+ np.empty((0, _NUM_KEYPOINTS, 2), dtype=np.float32),+ np.empty(0, dtype=np.float32),+ )++ reg, anchor = regressors[0][keep].astype(np.float64), self.anchors[keep]+ rows = np.empty((int(keep.sum()), 5 + 2 * _NUM_KEYPOINTS))+ rows[:, 0] = scores[keep]+ rows[:, 1:3] = reg[:, 0:2] / size + anchor # center x, y+ rows[:, 3:5] = reg[:, 2:4] / size # width, height+ for k in range(_NUM_KEYPOINTS):+ rows[:, 5 + 2 * k : 7 + 2 * k] = reg[:, 4 + 2 * k : 6 + 2 * k] / size + anchor++ rows = _weighted_nms(rows, self.nms_threshold)++ def unletterbox(xy_normalized: np.ndarray) -> np.ndarray:+ return (xy_normalized * size - (pad_x, pad_y)) / scale++ centers = unletterbox(rows[:, 1:3])+ halves = rows[:, 3:5] * size / scale / 2.0+ bboxes = np.concatenate([centers - halves, centers + halves], axis=1)+ keypoints = unletterbox(rows[:, 5:].reshape(-1, _NUM_KEYPOINTS, 2))++ return bboxes.astype(np.float32), keypoints.astype(np.float32), rows[:, 0].astype(np.float32)++ def detect(+ self,+ image: np.ndarray,+ *,+ max_num: int = 0,+ metric: Literal['default', 'max'] = 'max',+ center_weight: float = 2.0,+ ) -> list[Face]:+ """Detect faces in an image.++ Args:+ image (np.ndarray): Input image as a NumPy array of shape (H, W, C) in BGR.+ max_num (int): Maximum number of detections to return. Use 0 for all.+ metric (Literal["default", "max"]): Metric for ranking when `max_num` is set.+ - "default": Prioritize detections closer to the image center.+ - "max": Prioritize detections with larger bounding box areas.+ center_weight (float): Penalty weight for distance from center under+ the "default" metric. Defaults to 2.0.++ Returns:+ list[Face]: List of Face objects, each containing:+ - bbox (np.ndarray): Bounding box with shape (4,) as [x1, y1, x2, y2]+ - confidence (float): Detection confidence score (0.0 to 1.0)+ - landmarks (np.ndarray): 6-point MediaPipe keypoints, shape (6, 2)++ Raises:+ ValueError: If the image is empty, not 3-channel BGR, or not uint8.++ Example:+ >>> faces = detector.detect(image)+ >>> for face in faces:+ ... bbox = face.bbox # np.ndarray with shape (4,)+ ... keypoints = face.landmarks # np.ndarray with shape (6, 2)+ """+ # This detector warps the input itself, so it never reaches the resize helpers+ # that validate for the other detectors.+ validate_image(image)++ height, width = image.shape[:2]+ size = self.input_size++ # Aspect-preserving letterbox onto a square canvas, centered.+ scale = size / max(height, width)+ pad_x, pad_y = (size - width * scale) / 2.0, (size - height * scale) / 2.0+ matrix = np.array([[scale, 0.0, pad_x], [0.0, scale, pad_y]])+ canvas = cv2.warpAffine(image, matrix, (size, size))++ image_tensor = self.preprocess(canvas)+ outputs = self.session.run(self.output_names, {self.input_names: image_tensor})+ bboxes, keypoints, scores = self.postprocess(outputs, scale, pad_x, pad_y)++ if bboxes.shape[0] == 0:+ return []++ # The decoded box can extend past the frame+ bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, width)+ bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, height)++ detections = np.hstack((bboxes, scores[:, None])).astype(np.float32, copy=False)++ detections, keypoints = self._select_top_detections(+ detections, keypoints, max_num, (height, width), metric, center_weight+ )++ return self._detections_to_faces(detections, keypoints)diff --git a/uniface/detection/centerface.py b/uniface/detection/centerface.pynew file mode 100644index 0000000..1de0ae1--- /dev/null+++ b/uniface/detection/centerface.py@@ -0,0 +1,257 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo++from __future__ import annotations++from typing import Literal++import numpy as np++from uniface.common import non_max_suppression, resize_image+from uniface.constants import CenterFaceWeights+from uniface.log import Logger+from uniface.model_store import verify_model_weights+from uniface.onnx_utils import create_onnx_session+from uniface.types import Face++from .base import BaseDetector++__all__ = ['CenterFace']++# CenterFace predicts on a single feature map downsampled 4x from the input+_STRIDE = 4+++class CenterFace(BaseDetector):+ """Anchor-free face detector based on the CenterFace architecture.++ Title: "CenterFace: Joint Face Detection and Alignment Using Face as Point"+ Paper: https://arxiv.org/abs/1911.03599+ Code: https://github.com/Star-Clouds/CenterFace++ Faces are detected as center points on a single stride-4 feature map with four+ prediction heads: center heatmap, box scale, center offset, and 5-point landmarks.++ Note:+ Landmarks are decoded from a single coarse feature-map cell per face and are less+ precise than SCRFD/RetinaFace; accuracy also degrades faster for in-plane rotated+ faces (beyond ~20-30 degrees). Best suited for roughly upright faces.++ Args:+ model_name (CenterFaceWeights): Predefined model enum. Defaults to CenterFaceWeights.DEFAULT.+ confidence_threshold (float): Confidence threshold for filtering detections. Defaults to 0.35.+ nms_threshold (float): Non-Maximum Suppression threshold. Defaults to 0.3.+ input_size (tuple[int, int]): Input image size (width, height). Both must be multiples of 32.+ Defaults to (640, 640).+ providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detects+ the best available provider. Example: ['CPUExecutionProvider'] to force CPU.++ Attributes:+ model_name (CenterFaceWeights): Selected model variant.+ confidence_threshold (float): Threshold used to filter low-confidence detections.+ nms_threshold (float): Threshold used during NMS to suppress overlapping boxes.+ input_size (tuple[int, int]): Image size to which inputs are resized before inference.+ _model_path (str): Absolute path to the downloaded/verified model weights.++ Raises:+ ValueError: If `input_size` is not a multiple of 32, or the model weights are invalid.+ RuntimeError: If the ONNX model fails to load or initialize.+ """++ supports_landmarks = True+ supports_alignment = True++ def __init__(+ self,+ *,+ model_name: CenterFaceWeights = CenterFaceWeights.DEFAULT,+ confidence_threshold: float = 0.35,+ nms_threshold: float = 0.3,+ input_size: tuple[int, int] = (640, 640),+ providers: list[str] | None = None,+ ) -> None:+ super().__init__(+ model_name=model_name,+ confidence_threshold=confidence_threshold,+ nms_threshold=nms_threshold,+ input_size=input_size,+ providers=providers,+ )+ if input_size[0] % 32 != 0 or input_size[1] % 32 != 0:+ raise ValueError(f'input_size must be a multiple of 32, got {input_size}')++ self.model_name = model_name+ self.confidence_threshold = confidence_threshold+ self.nms_threshold = nms_threshold+ self.input_size = input_size+ self.providers = providers++ Logger.info(+ f'Initializing CenterFace with model={self.model_name}, '+ f'confidence_threshold={self.confidence_threshold}, '+ f'nms_threshold={self.nms_threshold}, input_size={self.input_size}'+ )++ self._model_path = verify_model_weights(self.model_name)+ Logger.info(f'Verified model weights located at: {self._model_path}')++ self._initialize_model(self._model_path)++ def _initialize_model(self, model_path: str) -> None:+ """Initialize an ONNX model session from the given path.++ Args:+ model_path: The file path to the ONNX model.++ Raises:+ RuntimeError: If the model fails to load.+ """+ try:+ self.session = create_onnx_session(model_path, providers=self.providers)+ self.input_names = self.session.get_inputs()[0].name+ self.output_names = [x.name for x in self.session.get_outputs()]+ Logger.info(f'Successfully initialized the model from {model_path}')+ except Exception as e:+ Logger.error(f"Failed to load model from '{model_path}': {e}", exc_info=True)+ raise RuntimeError(f"Failed to initialize model session for '{model_path}'") from e++ def preprocess(self, image: np.ndarray) -> np.ndarray:+ """Preprocess image for inference.++ CenterFace consumes raw pixel values (no mean subtraction or scaling).++ Args:+ image: Input image with shape (H, W, C).++ Returns:+ Preprocessed image tensor with shape (1, C, H, W).+ """+ image = image.astype(np.float32)+ image = image.transpose(2, 0, 1) # HWC to CHW+ image = np.expand_dims(image, axis=0)++ return image++ def inference(self, input_tensor: np.ndarray) -> list[np.ndarray]:+ """Perform model inference on the preprocessed image tensor.++ Args:+ input_tensor: Preprocessed input tensor with shape (1, C, H, W).++ Returns:+ List of raw model outputs: [heatmap, scale, offset, landmarks].+ """+ return self.session.run(self.output_names, {self.input_names: input_tensor})++ def postprocess(+ self,+ outputs: list[np.ndarray],+ image_size: tuple[int, int],+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ """Decode center-point predictions into detection results.++ Args:+ outputs: Raw outputs [heatmap (1,1,H/4,W/4), scale (1,2,H/4,W/4),+ offset (1,2,H/4,W/4), landmarks (1,10,H/4,W/4)].+ image_size: Size of the model input image as (height, width).++ Returns:+ Tuple of (bboxes (N, 4), scores (N,), landmarks (N, 5, 2)).+ """+ heatmap, scale, offset, lms = outputs+ height, width = image_size++ heatmap = heatmap[0, 0]+ cy, cx = np.where(heatmap > self.confidence_threshold)+ if len(cy) == 0:+ empty = np.empty((0,), dtype=np.float32)+ return np.empty((0, 4), dtype=np.float32), empty, np.empty((0, 5, 2), dtype=np.float32)++ scores = heatmap[cy, cx]+ box_h = np.exp(scale[0, 0, cy, cx]) * _STRIDE+ box_w = np.exp(scale[0, 1, cy, cx]) * _STRIDE+ offset_y = offset[0, 0, cy, cx]+ offset_x = offset[0, 1, cy, cx]++ x1 = np.clip((cx + offset_x + 0.5) * _STRIDE - box_w / 2, 0, width)+ y1 = np.clip((cy + offset_y + 0.5) * _STRIDE - box_h / 2, 0, height)+ x2 = np.clip(x1 + box_w, 0, width)+ y2 = np.clip(y1 + box_h, 0, height)+ bboxes = np.stack([x1, y1, x2, y2], axis=1)++ # Landmarks are predicted relative to the box: (dy, dx) pairs per point+ points = lms[0][:, cy, cx] # (10, N)+ kps_x = points[1::2].T * box_w[:, None] + x1[:, None]+ kps_y = points[0::2].T * box_h[:, None] + y1[:, None]+ landmarks = np.stack([kps_x, kps_y], axis=2) # (N, 5, 2)++ return bboxes, scores, landmarks++ def detect(+ self,+ image: np.ndarray,+ *,+ max_num: int = 0,+ metric: Literal['default', 'max'] = 'max',+ center_weight: float = 2.0,+ ) -> list[Face]:+ """Perform face detection on an input image and return bounding boxes and facial landmarks.++ Args:+ image (np.ndarray): Input image as a NumPy array of shape (H, W, C).+ max_num (int): Maximum number of detections to return. Use 0 to return all detections. Defaults to 0.+ metric (Literal["default", "max"]): Metric for ranking detections when `max_num` is limited.+ - "default": Prioritize detections closer to the image center.+ - "max": Prioritize detections with larger bounding box areas.+ center_weight (float): Weight for penalizing detections farther from the image center+ when using the "default" metric. Defaults to 2.0.++ Returns:+ list[Face]: List of Face objects, each containing:+ - bbox (np.ndarray): Bounding box coordinates with shape (4,) as [x1, y1, x2, y2]+ - confidence (float): Detection confidence score (0.0 to 1.0)+ - landmarks (np.ndarray): 5-point facial landmarks with shape (5, 2)++ Example:+ >>> faces = detector.detect(image)+ >>> for face in faces:+ ... bbox = face.bbox # np.ndarray with shape (4,)+ ... confidence = face.confidence # float+ ... landmarks = face.landmarks # np.ndarray with shape (5, 2)+ """++ original_height, original_width = image.shape[:2]++ image, resize_factor = resize_image(image, target_shape=self.input_size)++ image_tensor = self.preprocess(image)++ outputs = self.inference(image_tensor)++ # Postprocessing+ bboxes, scores, landmarks = self.postprocess(outputs, image_size=image.shape[:2])++ # Handle case when no faces are detected+ if bboxes.shape[0] == 0:+ return []++ bboxes = bboxes / resize_factor+ landmarks = landmarks / resize_factor++ order = scores.argsort()[::-1]+ pre_det = np.hstack((bboxes, scores[:, None])).astype(np.float32, copy=False)+ pre_det = pre_det[order, :]+ landmarks = landmarks[order]++ keep = non_max_suppression(pre_det, threshold=self.nms_threshold)++ detections = pre_det[keep, :]+ landmarks = landmarks[keep].astype(np.float32)++ # Filter to top max_num faces if requested+ detections, landmarks = self._select_top_detections(+ detections, landmarks, max_num, (original_height, original_width), metric, center_weight+ )++ return self._detections_to_faces(detections, landmarks)diff --git a/uniface/detection/retinaface.py b/uniface/detection/retinaface.pyindex a46763e..16e92c2 100644--- a/uniface/detection/retinaface.py+++ b/uniface/detection/retinaface.py@@ -4,7 +4,7 @@from __future__ import annotations-from typing import Any, Literal+from typing import Literalimport numpy as np@@ -25,8 +25,7 @@ from .base import BaseDetectorclass RetinaFace(BaseDetector):- """- Face detector based on the RetinaFace architecture.+ """Face detector based on the RetinaFace architecture.Title: "RetinaFace: Single-stage Dense Face Localisation in the Wild"Paper: https://arxiv.org/abs/1905.00641@@ -36,15 +35,14 @@ class RetinaFace(BaseDetector):model_name (RetinaFaceWeights): Model weights to use. Defaults to `RetinaFaceWeights.MNET_V2`.confidence_threshold (float): Confidence threshold for filtering detections. Defaults to 0.5.nms_threshold (float): Non-maximum suppression (NMS) IoU threshold. Defaults to 0.4.- input_size (Tuple[int, int]): Fixed input size (width, height) if `dynamic_size=False`.+ input_size (tuple[int, int]): Fixed input size (width, height) if `dynamic_size=False`.Defaults to (640, 640).Note: Non-default sizes may cause slower inference and CoreML compatibility issues.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.- **kwargs: Advanced options:- pre_nms_topk (int): Number of top-scoring boxes considered before NMS. Defaults to 5000.- post_nms_topk (int): Max number of detections kept after NMS. Defaults to 750.- dynamic_size (bool): If True, generate anchors dynamically per input image. Defaults to False.+ pre_nms_topk (int): Number of top-scoring boxes considered before NMS. Defaults to 5000.+ post_nms_topk (int): Max number of detections kept after NMS. Defaults to 750.+ dynamic_size (bool): If True, generate anchors dynamically per input image. Defaults to False.Attributes:model_name (RetinaFaceWeights): Selected model variant.@@ -53,16 +51,18 @@ class RetinaFace(BaseDetector):pre_nms_topk (int): Limit on proposals before applying NMS.post_nms_topk (int): Limit on retained detections after NMS.dynamic_size (bool): Flag indicating dynamic or static input sizing.- input_size (Tuple[int, int]): Static input size if `dynamic_size=False`.+ input_size (tuple[int, int]): Static input size if `dynamic_size=False`._model_path (str): Absolute path to the verified model weights._priors (np.ndarray): Precomputed anchor boxes (if static size).- _supports_landmarks (bool): Indicates landmark prediction support.Raises:ValueError: If the model weights are invalid or not found.RuntimeError: If the ONNX model fails to load or initialize."""+ supports_landmarks = True+ supports_alignment = True+def __init__(self,*,@@ -71,7 +71,9 @@ class RetinaFace(BaseDetector):nms_threshold: float = 0.4,input_size: tuple[int, int] = (640, 640),providers: list[str] | None = None,- **kwargs: Any,+ pre_nms_topk: int = 5000,+ post_nms_topk: int = 750,+ dynamic_size: bool = False,) -> None:super().__init__(model_name=model_name,@@ -79,9 +81,10 @@ class RetinaFace(BaseDetector):nms_threshold=nms_threshold,input_size=input_size,providers=providers,- **kwargs,+ pre_nms_topk=pre_nms_topk,+ post_nms_topk=post_nms_topk,+ dynamic_size=dynamic_size,)- self._supports_landmarks = True # RetinaFace supports landmarksself.model_name = model_nameself.confidence_threshold = confidence_threshold@@ -89,17 +92,16 @@ class RetinaFace(BaseDetector):self.input_size = input_sizeself.providers = providers- # Advanced options from kwargs- self.pre_nms_topk = kwargs.get('pre_nms_topk', 5000)- self.post_nms_topk = kwargs.get('post_nms_topk', 750)- self.dynamic_size = kwargs.get('dynamic_size', False)+ # Advanced options+ self.pre_nms_topk = pre_nms_topk+ self.post_nms_topk = post_nms_topk+ self.dynamic_size = dynamic_sizeLogger.info(f'Initializing RetinaFace with model={self.model_name}, confidence_threshold={self.confidence_threshold}, 'f'nms_threshold={self.nms_threshold}, input_size={self.input_size}')- # Get path to model weightsself._model_path = verify_model_weights(self.model_name)Logger.info(f'Verified model weights located at: {self._model_path}')@@ -108,7 +110,6 @@ class RetinaFace(BaseDetector):self._priors = generate_anchors(image_size=self.input_size)Logger.debug('Generated anchors for static input size.')- # Initialize modelself._initialize_model(self._model_path)def _initialize_model(self, model_path: str) -> None:@@ -162,8 +163,7 @@ class RetinaFace(BaseDetector):metric: Literal['default', 'max'] = 'max',center_weight: float = 2.0,) -> list[Face]:- """- Perform face detection on an input image and return bounding boxes and facial landmarks.+ """Perform face detection on an input image and return bounding boxes and facial landmarks.Args:image (np.ndarray): Input image as a NumPy array of shape (H, W, C).@@ -175,7 +175,7 @@ class RetinaFace(BaseDetector):when using the "default" metric. Defaults to 2.0.Returns:- List[Face]: List of Face objects, each containing:+ list[Face]: List of Face objects, each containing:- bbox (np.ndarray): Bounding box coordinates with shape (4,) as [x1, y1, x2, y2]- confidence (float): Detection confidence score (0.0 to 1.0)- landmarks (np.ndarray): 5-point facial landmarks with shape (5, 2)@@ -202,7 +202,6 @@ class RetinaFace(BaseDetector):height, width, _ = image.shapeimage_tensor = self.preprocess(image)- # Inferenceoutputs = self.inference(image_tensor)# Postprocessingdiff --git a/uniface/detection/scrfd.py b/uniface/detection/scrfd.pyindex f09c5d9..0d20d10 100644--- a/uniface/detection/scrfd.py+++ b/uniface/detection/scrfd.py@@ -4,7 +4,7 @@from __future__ import annotations-from typing import Any, Literal+from typing import Literalimport numpy as np@@ -21,8 +21,7 @@ __all__ = ['SCRFD']class SCRFD(BaseDetector):- """- Face detector based on the SCRFD architecture.+ """Face detector based on the SCRFD architecture.Title: "Sample and Computation Redistribution for Efficient Face Detection"Paper: https://arxiv.org/abs/2105.04714@@ -33,20 +32,19 @@ class SCRFD(BaseDetector):Specifies the SCRFD variant to load. Defaults to SCRFD_10G_KPS.confidence_threshold (float): Confidence threshold for filtering detections. Defaults to 0.5.nms_threshold (float): Non-Maximum Suppression threshold. Defaults to 0.4.- input_size (Tuple[int, int]): Input image size (width, height).+ input_size (tuple[int, int]): Input image size (width, height).Defaults to (640, 640).Note: Non-default sizes may cause slower inference and CoreML compatibility issues.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.- **kwargs: Reserved for future advanced options.Attributes:model_name (SCRFDWeights): Selected model variant.confidence_threshold (float): Threshold used to filter low-confidence detections.nms_threshold (float): Threshold used during NMS to suppress overlapping boxes.- input_size (Tuple[int, int]): Image size to which inputs are resized before inference.+ input_size (tuple[int, int]): Image size to which inputs are resized before inference._num_feature_maps (int): Number of feature map levels used in the model.- _feat_stride_fpn (List[int]): Feature map strides corresponding to each detection level.+ _feat_stride_fpn (list[int]): Feature map strides corresponding to each detection level._num_anchors (int): Number of anchors per feature location._center_cache (Dict): Cached anchor centers for efficient forward passes._model_path (str): Absolute path to the downloaded/verified model weights.@@ -56,6 +54,9 @@ class SCRFD(BaseDetector):RuntimeError: If the ONNX model fails to load or initialize."""+ supports_landmarks = True+ supports_alignment = True+def __init__(self,*,@@ -64,7 +65,6 @@ class SCRFD(BaseDetector):nms_threshold: float = 0.4,input_size: tuple[int, int] = (640, 640),providers: list[str] | None = None,- **kwargs: Any,) -> None:super().__init__(model_name=model_name,@@ -72,9 +72,7 @@ class SCRFD(BaseDetector):nms_threshold=nms_threshold,input_size=input_size,providers=providers,- **kwargs,)- self._supports_landmarks = True # SCRFD supports landmarksself.model_name = model_nameself.confidence_threshold = confidence_threshold@@ -94,11 +92,9 @@ class SCRFD(BaseDetector):f'nms_threshold={self.nms_threshold}, input_size={self.input_size}')- # Get path to model weightsself._model_path = verify_model_weights(self.model_name)Logger.info(f'Verified model weights located at: {self._model_path}')- # Initialize modelself._initialize_model(self._model_path)def _initialize_model(self, model_path: str) -> None:@@ -164,8 +160,6 @@ class SCRFD(BaseDetector):bboxes_list = []kpss_list = []- image_size = image_size-num_feature_maps = self._num_feature_mapsfor idx, stride in enumerate(self._feat_stride_fpn):scores = outputs[idx]@@ -213,8 +207,7 @@ class SCRFD(BaseDetector):metric: Literal['default', 'max'] = 'max',center_weight: float = 2.0,) -> list[Face]:- """- Perform face detection on an input image and return bounding boxes and facial landmarks.+ """Perform face detection on an input image and return bounding boxes and facial landmarks.Args:image (np.ndarray): Input image as a NumPy array of shape (H, W, C).@@ -226,7 +219,7 @@ class SCRFD(BaseDetector):when using the "default" metric. Defaults to 2.0.Returns:- List[Face]: List of Face objects, each containing:+ list[Face]: List of Face objects, each containing:- bbox (np.ndarray): Bounding box coordinates with shape (4,) as [x1, y1, x2, y2]- confidence (float): Detection confidence score (0.0 to 1.0)- landmarks (np.ndarray): 5-point facial landmarks with shape (5, 2)@@ -247,7 +240,6 @@ class SCRFD(BaseDetector):image_tensor = self.preprocess(image)- # Inferenceoutputs = self.inference(image_tensor)# Postprocessingdiff --git a/uniface/detection/yolov5.py b/uniface/detection/yolov5.pyindex fd8529d..5ad4717 100644--- a/uniface/detection/yolov5.py+++ b/uniface/detection/yolov5.py@@ -2,7 +2,7 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-from typing import Any, Literal+from typing import Literalimport numpy as np@@ -28,8 +28,7 @@ __all__ = ['YOLOv5Face']class YOLOv5Face(BaseDetector):- """- Face detector based on the YOLOv5-Face architecture.+ """Face detector based on the YOLOv5-Face architecture.Title: "YOLO5Face: Why Reinventing a Face Detector"Paper: https://arxiv.org/abs/2105.12931@@ -46,8 +45,7 @@ class YOLOv5Face(BaseDetector):or 'numpy' (no dependencies). Defaults to 'numpy'.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.- **kwargs: Advanced options:- max_det (int): Maximum number of detections to return. Defaults to 750.+ max_det (int): Maximum number of detections to return. Defaults to 750.Attributes:model_name (YOLOv5FaceWeights): Selected model variant.@@ -63,6 +61,9 @@ class YOLOv5Face(BaseDetector):RuntimeError: If the ONNX model fails to load or initialize."""+ supports_landmarks = True+ supports_alignment = True+def __init__(self,*,@@ -72,7 +73,7 @@ class YOLOv5Face(BaseDetector):input_size: int = 640,nms_mode: Literal['torchvision', 'numpy'] = 'numpy',providers: list[str] | None = None,- **kwargs: Any,+ max_det: int = 750,) -> None:super().__init__(model_name=model_name,@@ -81,9 +82,8 @@ class YOLOv5Face(BaseDetector):input_size=input_size,nms_mode=nms_mode,providers=providers,- **kwargs,+ max_det=max_det,)- self._supports_landmarks = True # YOLOv5-Face supports landmarks# Validate input sizeif input_size != 640:@@ -104,24 +104,21 @@ class YOLOv5Face(BaseDetector):else:self.nms_mode = nms_mode- # Advanced options from kwargs- self.max_det = kwargs.get('max_det', 750)+ # Advanced options+ self.max_det = max_detLogger.info(f'Initializing YOLOv5Face with model={self.model_name}, confidence_threshold={self.confidence_threshold}, 'f'nms_threshold={self.nms_threshold}, input_size={self.input_size}, nms_mode={self.nms_mode}')- # Get path to model weightsself._model_path = verify_model_weights(self.model_name)Logger.info(f'Verified model weights located at: {self._model_path}')- # Initialize modelself._initialize_model(self._model_path)def _initialize_model(self, model_path: str) -> None:- """- Initializes an ONNX model session from the given path.+ """Initializes an ONNX model session from the given path.Args:model_path (str): The file path to the ONNX model.@@ -156,7 +153,7 @@ class YOLOv5Face(BaseDetector):input_tensor (np.ndarray): Preprocessed input tensor.Returns:- List[np.ndarray]: Raw model outputs.+ list[np.ndarray]: Raw model outputs."""return self.session.run(self.output_names, {self.input_names: input_tensor})@@ -166,21 +163,20 @@ class YOLOv5Face(BaseDetector):scale: float,padding: tuple[int, int],) -> tuple[np.ndarray, np.ndarray]:- """- Postprocess model predictions.+ """Postprocess model predictions.Args:predictions (np.ndarray): Raw model outputscale (float): Scale ratio used in preprocessing- padding (Tuple[int, int]): Padding used in preprocessing+ padding (tuple[int, int]): Padding used in preprocessingReturns:- Tuple[np.ndarray, np.ndarray]: Filtered detections and landmarks+ tuple[np.ndarray, np.ndarray]: Filtered detections and landmarks- detections: [x1, y1, x2, y2, conf]- landmarks: [5, 2] for each detection"""# predictions shape: (1, 25200, 16)- # 16 = [x, y, w, h, obj_conf, cls_conf, 10 landmarks (5 points * 2 coords)]+ # 16 = [x, y, w, h, obj_conf, 10 landmark coords (5 points * 2), cls_conf]predictions = predictions[0] # Remove batch dimension@@ -194,7 +190,7 @@ class YOLOv5Face(BaseDetector):# Convert from xywh to xyxyboxes = self._xywh2xyxy(predictions[:, :4])- # Get confidence scores+ # Column 4 is the objectness score; the trailing cls_conf column is not usedscores = predictions[:, 4]# Get landmarks (5 points, 10 coordinates)@@ -239,8 +235,7 @@ class YOLOv5Face(BaseDetector):return detections, landmarksdef _xywh2xyxy(self, x: np.ndarray) -> np.ndarray:- """- Convert bounding box format from xywh to xyxy.+ """Convert bounding box format from xywh to xyxy.Args:x (np.ndarray): Boxes in [x, y, w, h] format@@ -263,8 +258,7 @@ class YOLOv5Face(BaseDetector):metric: Literal['default', 'max'] = 'max',center_weight: float = 2.0,) -> list[Face]:- """- Perform face detection on an input image and return bounding boxes and facial landmarks.+ """Perform face detection on an input image and return bounding boxes and facial landmarks.Args:image (np.ndarray): Input image as a NumPy array of shape (H, W, C).@@ -276,7 +270,7 @@ class YOLOv5Face(BaseDetector):when using the "default" metric. Defaults to 2.0.Returns:- List[Face]: List of Face objects, each containing:+ list[Face]: List of Face objects, each containing:- bbox (np.ndarray): Bounding box coordinates with shape (4,) as [x1, y1, x2, y2]- confidence (float): Detection confidence score (0.0 to 1.0)- landmarks (np.ndarray): 5-point facial landmarks with shape (5, 2)@@ -293,13 +287,11 @@ class YOLOv5Face(BaseDetector):original_height, original_width = image.shape[:2]- # Preprocessimage_tensor, scale, padding = self.preprocess(image)# ONNXRuntime inferenceoutputs = self.inference(image_tensor)- # Postprocessdetections, landmarks = self.postprocess(outputs[0], scale, padding)# Handle case when no faces are detecteddiff --git a/uniface/detection/yolov8.py b/uniface/detection/yolov8.pyindex 31def87..0520f93 100644--- a/uniface/detection/yolov8.py+++ b/uniface/detection/yolov8.py@@ -2,7 +2,7 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-from typing import Any, Literal+from typing import Literalimport numpy as np@@ -28,8 +28,7 @@ __all__ = ['YOLOv8Face']class YOLOv8Face(BaseDetector):- """- Face detector based on the YOLOv8-Face architecture.+ """Face detector based on the YOLOv8-Face architecture.Uses anchor-free design with DFL (Distribution Focal Loss) for bbox regression.Outputs 3 feature maps at different scales for multi-scale detection.@@ -47,8 +46,7 @@ class YOLOv8Face(BaseDetector):or 'numpy' (no dependencies). Defaults to 'numpy'.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.- **kwargs: Advanced options:- max_det (int): Maximum number of detections to return. Defaults to 750.+ max_det (int): Maximum number of detections to return. Defaults to 750.Attributes:model_name (YOLOv8FaceWeights): Selected model variant.@@ -64,6 +62,9 @@ class YOLOv8Face(BaseDetector):RuntimeError: If the ONNX model fails to load or initialize."""+ supports_landmarks = True+ supports_alignment = True+def __init__(self,*,@@ -73,7 +74,7 @@ class YOLOv8Face(BaseDetector):input_size: int = 640,nms_mode: Literal['torchvision', 'numpy'] = 'numpy',providers: list[str] | None = None,- **kwargs: Any,+ max_det: int = 750,) -> None:super().__init__(model_name=model_name,@@ -82,9 +83,8 @@ class YOLOv8Face(BaseDetector):input_size=input_size,nms_mode=nms_mode,providers=providers,- **kwargs,+ max_det=max_det,)- self._supports_landmarks = True # YOLOv8-Face supports landmarks# Validate input sizeif input_size != 640:@@ -105,8 +105,8 @@ class YOLOv8Face(BaseDetector):else:self.nms_mode = nms_mode- # Advanced options from kwargs- self.max_det = kwargs.get('max_det', 750)+ # Advanced options+ self.max_det = max_det# YOLOv8 strides for 640x640 input (3 feature maps: 80x80, 40x40, 20x20)self.strides = [8, 16, 32]@@ -116,16 +116,13 @@ class YOLOv8Face(BaseDetector):f'nms_threshold={self.nms_threshold}, input_size={self.input_size}, nms_mode={self.nms_mode}')- # Get path to model weightsself._model_path = verify_model_weights(self.model_name)Logger.info(f'Verified model weights located at: {self._model_path}')- # Initialize modelself._initialize_model(self._model_path)def _initialize_model(self, model_path: str) -> None:- """- Initializes an ONNX model session from the given path.+ """Initializes an ONNX model session from the given path.Args:model_path (str): The file path to the ONNX model.@@ -160,7 +157,7 @@ class YOLOv8Face(BaseDetector):input_tensor (np.ndarray): Preprocessed input tensor.Returns:- List[np.ndarray]: Raw model outputs (3 feature maps).+ list[np.ndarray]: Raw model outputs (3 feature maps)."""return self.session.run(self.output_names, {self.input_names: input_tensor})@@ -171,17 +168,16 @@ class YOLOv8Face(BaseDetector):padding: tuple[int, int],original_shape: tuple[int, int],) -> tuple[np.ndarray, np.ndarray]:- """- Postprocess model predictions with DFL decoding and coordinate scaling.+ """Postprocess model predictions with DFL decoding and coordinate scaling.Args:- predictions (List[np.ndarray]): Raw model outputs (3 feature maps)+ predictions (list[np.ndarray]): Raw model outputs (3 feature maps)scale (float): Scale ratio used in preprocessing- padding (Tuple[int, int]): Padding (pad_w, pad_h) used in preprocessing- original_shape (Tuple[int, int]): Original image shape (height, width)+ padding (tuple[int, int]): Padding (pad_w, pad_h) used in preprocessing+ original_shape (tuple[int, int]): Original image shape (height, width)Returns:- Tuple[np.ndarray, np.ndarray]: Filtered detections and landmarks+ tuple[np.ndarray, np.ndarray]: Filtered detections and landmarks- detections: [N, 5] as [x1, y1, x2, y2, conf]- landmarks: [N, 5, 2] for each detection"""@@ -301,8 +297,7 @@ class YOLOv8Face(BaseDetector):metric: Literal['default', 'max'] = 'max',center_weight: float = 2.0,) -> list[Face]:- """- Perform face detection on an input image and return bounding boxes and facial landmarks.+ """Perform face detection on an input image and return bounding boxes and facial landmarks.Args:image (np.ndarray): Input image as a NumPy array of shape (H, W, C) in BGR format.@@ -314,7 +309,7 @@ class YOLOv8Face(BaseDetector):when using the "default" metric. Defaults to 2.0.Returns:- List[Face]: List of Face objects, each containing:+ list[Face]: List of Face objects, each containing:- bbox (np.ndarray): Bounding box coordinates with shape (4,) as [x1, y1, x2, y2]- confidence (float): Detection confidence score (0.0 to 1.0)- landmarks (np.ndarray): 5-point facial landmarks with shape (5, 2)@@ -328,7 +323,6 @@ class YOLOv8Face(BaseDetector):"""original_height, original_width = image.shape[:2]- # Preprocessimage_tensor, scale, padding = self.preprocess(image)# ONNXRuntime inferencediff --git a/uniface/draw.py b/uniface/draw.pyindex af1ebc5..7d9cf61 100644--- a/uniface/draw.py+++ b/uniface/draw.py@@ -24,6 +24,7 @@ __all__ = ['draw_head_pose','draw_head_pose_axis','draw_head_pose_cube',+ 'draw_mesh','draw_quality_score','draw_text_label','draw_tracks',@@ -87,6 +88,9 @@ _LANDMARK_COLORS = ((255, 0, 0),)+#: Iris points of a 478-point mesh, drawn red so they read against the mesh points.+_IRIS_COLOR = (60, 60, 255)+def _get_color(idx: int) -> tuple[int, int, int]:"""Get a visually distinct BGR color for a given index.@@ -111,7 +115,7 @@ def calculate_optimal_line_thickness(resolution_wh: tuple[int, int]) -> int:"""Calculate adaptive line thickness based on image resolution.Args:- resolution_wh: Image resolution as ``(width, height)``.+ resolution_wh: Image resolution as `(width, height)`.Returns:Recommended line thickness in pixels.@@ -129,7 +133,7 @@ def calculate_optimal_text_scale(resolution_wh: tuple[int, int]) -> float:"""Calculate adaptive font scale based on image resolution.Args:- resolution_wh: Image resolution as ``(width, height)``.+ resolution_wh: Image resolution as `(width, height)`.Returns:Recommended font scale factor.@@ -157,8 +161,8 @@ def draw_corner_bbox(Args:image: Input image to draw on (modified in-place).- bbox: Bounding box in xyxy format ``[x1, y1, x2, y2]``.- color: BGR color of the box. Defaults to green ``(0, 255, 0)``.+ bbox: Bounding box in xyxy format `[x1, y1, x2, y2]`.+ color: BGR color of the box. Defaults to green `(0, 255, 0)`.thickness: Thickness of corner bracket lines. Defaults to 3.proportion: Corner length as a fraction of the shorter side.Defaults to 0.2.@@ -206,7 +210,7 @@ def draw_text_label(image: Input image to draw on (modified in-place).text: The text string to render.x: Left x-coordinate for the label.- y: Bottom y-coordinate for the label (e.g. ``bbox[1]``).+ y: Bottom y-coordinate for the label (e.g. `bbox[1]`).bg_color: BGR background fill color.text_color: BGR text color. Defaults to white.font_scale: OpenCV font scale factor. Defaults to 0.5.@@ -247,21 +251,24 @@ def draw_detections(Modifies the image in-place.- Accepts either a list of :class:`Face` objects (preferred) or separate+ Accepts either a list of `Face` objects (preferred) or separatelists of bboxes, scores, and landmarks for backward compatibility.Args:image: Input image to draw on (modified in-place).faces: List of Face objects from detection. When provided,- ``bboxes``, ``scores``, and ``landmarks`` are ignored.- bboxes: List of bounding boxes in xyxy format ``[x1, y1, x2, y2]``.+ `bboxes`, `scores`, and `landmarks` are ignored.+ bboxes: List of bounding boxes in xyxy format `[x1, y1, x2, y2]`.scores: List of confidence scores.- landmarks: List of landmark sets with shape ``(5, 2)``.+ landmarks: List of landmark sets with shape `(5, 2)`.vis_threshold: Confidence threshold for filtering. Defaults to 0.6.draw_score: Whether to draw confidence scores. Defaults to False.corner_bbox: Use corner-style bounding boxes. Defaults to True.- Examples:+ Raises:+ ValueError: If `faces` is None and any of `bboxes`, `scores`, or `landmarks` is missing.++ Example:>>> draw_detections(image=image, faces=faces)>>> draw_detections(image=image, faces=faces, vis_threshold=0.7, draw_score=True)"""@@ -297,9 +304,89 @@ def draw_detections(font_scale=font_scale,)- landmark_set = np.array(landmarks[i], dtype=np.int32)- for j, point in enumerate(landmark_set):- cv2.circle(image, tuple(point), line_thickness + 1, _LANDMARK_COLORS[j % len(_LANDMARK_COLORS)], -1)+ if landmarks[i] is not None:+ landmark_set = np.array(landmarks[i], dtype=np.int32)+ for j, point in enumerate(landmark_set):+ cv2.circle(image, tuple(point), line_thickness + 1, _LANDMARK_COLORS[j % len(_LANDMARK_COLORS)], -1)+++def draw_mesh(+ image: np.ndarray,+ landmarks: np.ndarray,+ *,+ mode: str = 'partial',+ color: tuple[int, int, int] = (0, 255, 0),+ point_color: tuple[int, int, int] = (0, 220, 255),+) -> np.ndarray:+ """Draw a dense face mesh onto an image.++ Args:+ image: Image to draw on, modified in place.+ landmarks: Dense landmarks with shape (N, 2) or (N, 3), where N is 468 or 478;+ the depth component is ignored. Typically `FaceMeshResult.landmarks`.+ mode: What to render.+ - `'partial'`: sparse contour edges plus every landmark point (default).+ - `'full'`: the dense tessellation, 2556 edges. Detailed but heavy —+ prefer `'partial'` or `'points'` for video.+ - `'points'`: landmark points only, no edges.+ color: Edge color in BGR.+ point_color: Landmark point color in BGR. A 478-point mesh draws its ten iris+ points separately, in red with a circle fitted to each, so they stand out.++ Returns:+ The annotated image (the same array that was passed in).++ Raises:+ ValueError: If `mode` is not one of the three supported values.++ Example:+ >>> results = FaceMesh().predict(image, faces)+ >>> draw_mesh(image, results[0].landmarks)+ """+ if mode not in ('full', 'partial', 'points'):+ raise ValueError(f"mode must be 'full', 'partial', or 'points', got {mode!r}")++ # Imported lazily: a module-level import would pull in uniface.landmark and+ # therefore onnxruntime, which is an optional extra. draw_mesh stays usable+ # in a numpy/OpenCV-only environment.+ from uniface.landmark._tessellation import (+ FACEMESH_TESSELATION_FULL,+ FACEMESH_TESSELATION_PARTIAL,+ IRIS_LEFT,+ IRIS_RIGHT,+ NUM_MESH_LANDMARKS,+ )++ points = np.rint(np.asarray(landmarks)[:, :2]).astype(np.int32)+ # The tessellation only indexes the mesh and the irises are drawn separately, so+ # keep the two sets apart from here on.+ mesh = points[:NUM_MESH_LANDMARKS]++ face_height = mesh[:, 1].max() - mesh[:, 1].min()+ radius = max(1, round(face_height / 120))++ if mode in ('full', 'partial'):+ edges = FACEMESH_TESSELATION_FULL if mode == 'full' else FACEMESH_TESSELATION_PARTIAL+ for start_idx, end_idx in edges:+ cv2.line(image, points[start_idx], points[end_idx], color, 1, cv2.LINE_AA)++ if mode in ('partial', 'points'):+ for x, y in mesh:+ cv2.circle(image, (x, y), radius, point_color, -1, cv2.LINE_AA)++ # Circle each iris and mark its five points. Slicing past a 468-point mesh yields+ # an empty array, so this is a no-op there rather than a branch. Drawn in every+ # mode, since the irises are the whole reason to pick the 478-point model.+ for iris in (points[IRIS_LEFT], points[IRIS_RIGHT]):+ if len(iris) == 0:+ continue+ center = iris[0]+ iris_radius = round(float(np.linalg.norm(iris[1:] - center, axis=1).mean()))+ cv2.circle(image, center, max(iris_radius, 1), _IRIS_COLOR, 1, cv2.LINE_AA)+ for x, y in iris:+ cv2.circle(image, (x, y), max(radius, 2), _IRIS_COLOR, -1, cv2.LINE_AA)++ return imagedef draw_gaze(@@ -318,7 +405,7 @@ def draw_gaze(Args:image: Input image to draw on (modified in-place).- bbox: Face bounding box in xyxy format ``[x1, y1, x2, y2]``.+ bbox: Face bounding box in xyxy format `[x1, y1, x2, y2]`.pitch: Vertical gaze angle in radians.yaw: Horizontal gaze angle in radians.draw_bbox: Whether to draw the bounding box. Defaults to True.@@ -376,10 +463,10 @@ def draw_gaze(def draw_head_pose_cube(image: np.ndarray,- yaw: float,+ bbox: list[int] | np.ndarray,pitch: float,+ yaw: float,roll: float,- bbox: list[int] | np.ndarray,size: int | None = None,) -> None:"""Draw a 3D wireframe cube representing head orientation on an image.@@ -391,15 +478,15 @@ def draw_head_pose_cube(Args:image: Input image to draw on (modified in-place).- yaw: Yaw angle in degrees.+ bbox: Bounding box as `[x_min, y_min, x_max, y_max]`.pitch: Pitch angle in degrees.+ yaw: Yaw angle in degrees.roll: Roll angle in degrees.- bbox: Bounding box as ``[x_min, y_min, x_max, y_max]``.size: Cube size in pixels. If None, uses the bounding box width.Example:>>> from uniface.draw import draw_head_pose_cube- >>> draw_head_pose_cube(image, yaw=10.0, pitch=-5.0, roll=2.0, bbox=[100, 100, 250, 280])+ >>> draw_head_pose_cube(image, [100, 100, 250, 280], pitch=-5.0, yaw=10.0, roll=2.0)"""x_min, y_min, x_max, y_max = map(int, bbox[:4])if size is None:@@ -458,10 +545,10 @@ def draw_head_pose_cube(def draw_head_pose_axis(image: np.ndarray,- yaw: float,+ bbox: list[int] | np.ndarray,pitch: float,+ yaw: float,roll: float,- bbox: list[int] | np.ndarray,size_ratio: float = 0.5,) -> None:"""Draw 3D coordinate axes representing head orientation on an image.@@ -473,15 +560,15 @@ def draw_head_pose_axis(Args:image: Input image to draw on (modified in-place).- yaw: Yaw angle in degrees.+ bbox: Bounding box as `[x_min, y_min, x_max, y_max]`.pitch: Pitch angle in degrees.+ yaw: Yaw angle in degrees.roll: Roll angle in degrees.- bbox: Bounding box as ``[x_min, y_min, x_max, y_max]``.size_ratio: Axis length as a fraction of bbox size. Defaults to 0.5.Example:>>> from uniface.draw import draw_head_pose_axis- >>> draw_head_pose_axis(image, yaw=10.0, pitch=-5.0, roll=2.0, bbox=[100, 100, 250, 280])+ >>> draw_head_pose_axis(image, [100, 100, 250, 280], pitch=-5.0, yaw=10.0, roll=2.0)"""x_min, y_min, x_max, y_max = map(int, bbox[:4])yaw_r, pitch_r, roll_r = np.radians([-yaw, pitch, roll])@@ -534,12 +621,12 @@ def draw_head_pose(Args:image: Input image to draw on (modified in-place).- bbox: Face bounding box in xyxy format ``[x1, y1, x2, y2]``.+ bbox: Face bounding box in xyxy format `[x1, y1, x2, y2]`.pitch: Pitch angle in degrees (rotation around X-axis).yaw: Yaw angle in degrees (rotation around Y-axis).roll: Roll angle in degrees (rotation around Z-axis).- draw_type: Visualization type, ``'cube'`` or ``'axis'``.- Defaults to ``'cube'``.+ draw_type: Visualization type, `'cube'` or `'axis'`.+ Defaults to `'cube'`.draw_bbox: Whether to draw the bounding box. Defaults to False.corner_bbox: Use corner-style bounding box. Defaults to True.draw_angles: Whether to display angle values as text. Defaults to True.@@ -563,9 +650,9 @@ def draw_head_pose(bbox_list = [x_min, y_min, x_max, y_max]if draw_type == 'axis':- draw_head_pose_axis(image, yaw, pitch, roll, bbox_list)+ draw_head_pose_axis(image, bbox_list, pitch, yaw, roll)else:- draw_head_pose_cube(image, yaw, pitch, roll, bbox_list)+ draw_head_pose_cube(image, bbox_list, pitch, yaw, roll)if draw_angles:font_scale = max(0.4, min(0.7, (y_max - y_min) / 200))@@ -601,7 +688,7 @@ def draw_quality_score(Args:image: Input image to draw on (modified in-place).- bbox: Face bounding box in xyxy format ``[x1, y1, x2, y2]``.+ bbox: Face bounding box in xyxy format `[x1, y1, x2, y2]`.score: Quality score in [0, 1]. Higher = better quality.draw_bbox: Whether to draw the bounding box. Defaults to True.corner_bbox: Use corner-style bounding box. Defaults to True.@@ -652,13 +739,13 @@ def draw_tracks("""Draw tracked faces with color-coded track IDs on an image.Each track ID is assigned a deterministic color for consistent visualization- across frames. Faces without a ``track_id`` are drawn in gray.+ across frames. Faces without a `track_id` are drawn in gray.Modifies the image in-place.Args:image: Input image to draw on (modified in-place).- faces: List of Face objects (with ``track_id`` assigned by BYTETracker).+ faces: List of Face objects (with `track_id` assigned by BYTETracker).draw_landmarks: Whether to draw facial landmarks. Defaults to True.draw_id: Whether to draw track ID labels. Defaults to True.corner_bbox: Use corner-style bounding boxes. Defaults to True.@@ -717,8 +804,8 @@ def vis_parsing_maps("""Visualize face parsing segmentation mask by overlaying colored regions.Args:- image: Input face image in BGR format with shape ``(H, W, 3)``.- segmentation_mask: Segmentation mask with shape ``(H, W)`` where each+ image: Input face image in BGR format with shape `(H, W, 3)`.+ segmentation_mask: Segmentation mask with shape `(H, W)` where eachpixel value represents a facial component class (0-18).save_image: Whether to save the visualization to disk. Defaults to False.save_path: Path to save the visualization if *save_image* is True.@@ -739,7 +826,8 @@ def vis_parsing_maps(image = np.array(image).copy().astype(np.uint8)segmentation_mask = segmentation_mask.copy().astype(np.uint8)- # Create a color mask in BGR format+ # Create a color mask in BGR; the palette is padded to max_class + 1 so class ids+ # beyond the color table map to black instead of raisingmax_class = int(segmentation_mask.max())palette = np.zeros((max(max_class + 1, len(FACE_PARSING_COLORS)), 3), dtype=np.uint8)palette[: len(FACE_PARSING_COLORS)] = FACE_PARSING_COLORSdiff --git a/uniface/face_utils.py b/uniface/face_utils.pyindex 2f5b583..701f14a 100644--- a/uniface/face_utils.py+++ b/uniface/face_utils.py@@ -36,7 +36,8 @@ def estimate_norm("""Estimate the normalization transformation matrix for facial landmarks.Args:- landmark: Array of shape (5, 2) representing the coordinates of the facial landmarks.+ landmark: Array of shape (5, 2) holding the alignment landmarks in the order+ left eye, right eye, nose, left mouth corner, right mouth corner.image_size: The size of the output image. Can be an integer (for square images)or a tuple (width, height). Default is 112.@@ -46,10 +47,15 @@ def estimate_norm(- The 2x3 inverse transformation matrix.Raises:- AssertionError: If the input landmark array does not have the shape (5, 2)+ ValueError: If the input landmark array does not have the shape (5, 2),or if image_size is not a multiple of 112 or 128."""- assert landmark.shape == (5, 2), 'Landmark array must have shape (5, 2).'+ if landmark.shape != (5, 2):+ raise ValueError(+ f'estimate_norm requires 5 alignment landmarks, got shape {landmark.shape}. '+ 'Detectors whose supports_alignment is False (e.g. BlazeFace) cannot be used '+ 'for alignment, recognition, quality scoring, or XSeg parsing.'+ )# Handle both int and tuple inputsif isinstance(image_size, tuple):@@ -57,7 +63,8 @@ def estimate_norm(else:size = image_size- assert size % 112 == 0 or size % 128 == 0, 'Image size must be a multiple of 112 or 128.'+ if size % 112 != 0 and size % 128 != 0:+ raise ValueError(f'image_size must be a multiple of 112 or 128, got {size}')if size % 112 == 0:ratio = float(size) / 112.0@@ -162,7 +169,7 @@ def bbox_center_alignment(# Convert rotation from degrees to radiansrot = float(rotation) * np.pi / 180.0- # Scale the image+ # Scaling transformt1 = SimilarityTransform(scale=scale)# Translate the center point to the origin (after scaling)@@ -170,7 +177,7 @@ def bbox_center_alignment(cy = center[1] * scalet2 = SimilarityTransform(translation=(-1 * cx, -1 * cy))- # Apply rotation around origin (center of face)+ # Rotation around the origin (the face center, after t2)t3 = SimilarityTransform(rotation=rot)# Translate origin to center of output image@@ -191,19 +198,19 @@ def bbox_center_alignment(def transform_points_2d(points: np.ndarray, transform: np.ndarray) -> np.ndarray:"""Apply a 2D affine transformation to an array of 2D points.- Both inputs are coerced to contiguous ``float32`` before the transform is- applied; the output dtype is ``float32`` regardless of the input dtypes.+ Both inputs are coerced to contiguous `float32` before the transform is+ applied; the output dtype is `float32` regardless of the input dtypes.Args:- points: An ``(N, 2)`` array of 2D points. When ``N == 0`` the function- short-circuits and returns an empty ``(0, 2)`` ``float32`` array- without touching ``transform``.- transform: A ``(2, 3)`` affine transformation matrix. ``(3, 3)``+ points: An `(N, 2)` array of 2D points. When `N == 0` the function+ short-circuits and returns an empty `(0, 2)` `float32` array+ without touching `transform`.+ transform: A `(2, 3)` affine transformation matrix. `(3, 3)`homogeneous matrices are **not** accepted — pass only the top tworows.Returns:- Transformed ``(N, 2)`` ``float32`` array of points.+ Transformed `(N, 2)` `float32` array of points."""if points.shape[0] == 0:return np.empty((0, 2), dtype=np.float32)diff --git a/uniface/gaze/__init__.py b/uniface/gaze/__init__.pyindex deb89ee..884ed71 100644--- a/uniface/gaze/__init__.py+++ b/uniface/gaze/__init__.py@@ -2,64 +2,9 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-from typing_extensions import deprecated-from uniface.types import GazeResultfrom .base import BaseGazeEstimatorfrom .models import MobileGaze--@deprecated(- 'create_gaze_estimator() is deprecated and will be removed in uniface 4.0. '- 'Instantiate the estimator class directly, e.g. '- '`from uniface.gaze import MobileGaze; MobileGaze(**kwargs)`.'-)-def create_gaze_estimator(method: str = 'mobilegaze', **kwargs) -> BaseGazeEstimator:- """- Factory function to create gaze estimators.-- .. deprecated:: 3.7.0- Use ``MobileGaze`` directly. This factory will be removed in uniface 4.0.-- This function initializes and returns a gaze estimator instance based on the- specified method. It acts as a high-level interface to the underlying- model classes.-- Args:- method (str): The gaze estimation method to use.- Options: 'mobilegaze' (default).- **kwargs: Model-specific parameters passed to the estimator's constructor.- For example, `model_name` can be used to select a specific- backbone from `GazeWeights` enum (RESNET18, RESNET34, RESNET50,- MOBILENET_V2, MOBILEONE_S0).-- Returns:- BaseGazeEstimator: An initialized gaze estimator instance ready for use.-- Raises:- ValueError: If the specified `method` is not supported.-- Examples:- >>> # Create the default MobileGaze estimator (ResNet34 backbone)- >>> from uniface.gaze import MobileGaze- >>> estimator = MobileGaze()-- >>> # Create with MobileNetV2 backbone- >>> from uniface.constants import GazeWeights- >>> estimator = MobileGaze(model_name=GazeWeights.MOBILENET_V2)-- >>> # Use the estimator- >>> result = estimator.estimate(face_crop)- >>> print(f'Pitch: {result.pitch}, Yaw: {result.yaw}')- """- method = method.lower()-- if method in ('mobilegaze', 'mobile_gaze', 'gaze'):- return MobileGaze(**kwargs)- else:- available = ['mobilegaze']- raise ValueError(f"Unsupported gaze estimation method: '{method}'. Available: {available}")---__all__ = ['BaseGazeEstimator', 'GazeResult', 'MobileGaze', 'create_gaze_estimator']+__all__ = ['BaseGazeEstimator', 'GazeResult', 'MobileGaze']diff --git a/uniface/gaze/base.py b/uniface/gaze/base.pyindex 85c2e52..d5a1919 100644--- a/uniface/gaze/base.py+++ b/uniface/gaze/base.py@@ -14,8 +14,7 @@ __all__ = ['BaseGazeEstimator', 'GazeResult']class BaseGazeEstimator(ABC):- """- Abstract base class for all gaze estimation models.+ """Abstract base class for all gaze estimation models.This class defines the common interface that all gaze estimators must implement,ensuring consistency across different gaze estimation methods. Gaze estimation@@ -28,22 +27,18 @@ class BaseGazeEstimator(ABC):@abstractmethoddef _initialize_model(self) -> None:- """- Initialize the underlying model for inference.+ """Initialize the underlying model for inference.This method should handle loading model weights, creating theinference session (e.g., ONNX Runtime), and any necessary- setup procedures to prepare the model for prediction.-- Raises:- RuntimeError: If the model fails to load or initialize.+ setup procedures to prepare the model for prediction. Implementations+ raise RuntimeError if the model fails to load or initialize."""raise NotImplementedError('Subclasses must implement the _initialize_model method.')@abstractmethoddef preprocess(self, face_image: np.ndarray) -> np.ndarray:- """- Preprocess the input face image for model inference.+ """Preprocess the input face image for model inference.This method should take a raw face crop and convert it into the formatexpected by the model's inference engine (e.g., normalized tensor).@@ -60,8 +55,7 @@ class BaseGazeEstimator(ABC):@abstractmethoddef postprocess(self, outputs: tuple[np.ndarray, np.ndarray]) -> GazeResult:- """- Postprocess raw model outputs into gaze angles.+ """Postprocess raw model outputs into gaze angles.This method takes the raw output from the model's inference andconverts it into pitch and yaw angles in radians.@@ -77,8 +71,7 @@ class BaseGazeEstimator(ABC):@abstractmethoddef estimate(self, face_image: np.ndarray) -> GazeResult:- """- Perform end-to-end gaze estimation on a face image.+ """Perform end-to-end gaze estimation on a face image.This method orchestrates the full pipeline: preprocessing the input,running inference, and postprocessing to return the gaze direction.@@ -94,15 +87,14 @@ class BaseGazeEstimator(ABC):- yaw: Horizontal gaze angle (positive = right, negative = left)Example:- >>> estimator = create_gaze_estimator()+ >>> estimator = MobileGaze()>>> result = estimator.estimate(face_crop)>>> print(f'Looking: pitch={np.degrees(result.pitch):.1f}°, yaw={np.degrees(result.yaw):.1f}°')"""raise NotImplementedError('Subclasses must implement the estimate method.')def __call__(self, face_image: np.ndarray) -> GazeResult:- """- Provides a convenient, callable shortcut for the `estimate` method.+ """Provides a convenient, callable shortcut for the `estimate` method.Args:face_image (np.ndarray): A cropped face image in BGR format.diff --git a/uniface/gaze/models.py b/uniface/gaze/models.pyindex 1f87147..4441102 100644--- a/uniface/gaze/models.py+++ b/uniface/gaze/models.py@@ -19,8 +19,7 @@ __all__ = ['MobileGaze']class MobileGaze(BaseGazeEstimator):- """- MobileGaze: Real-Time Gaze Estimation with ONNX Runtime.+ """MobileGaze: Real-Time Gaze Estimation with ONNX Runtime.MobileGaze is a gaze estimation model that predicts gaze direction from a singleface image. It supports multiple backbone architectures including ResNet 18/34/50,@@ -30,20 +29,22 @@ class MobileGaze(BaseGazeEstimator):The model outputs gaze direction as pitch (vertical) and yaw (horizontal) anglesin radians.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Reference:https://github.com/yakhyo/gaze-estimationArgs:model_name (GazeWeights): The enum specifying the gaze model backbone to load.Options: RESNET18, RESNET34, RESNET50, MOBILENET_V2, MOBILEONE_S0.- Defaults to `GazeWeights.RESNET18`.- input_size (Tuple[int, int]): The resolution (width, height) for the model's- input. Defaults to (448, 448).+ Defaults to `GazeWeights.RESNET34`.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.Attributes:- input_size (Tuple[int, int]): Model input dimensions.+ input_size (tuple[int, int]): Model input dimensions (width, height), read from the ONNX model.input_mean (list): Per-channel mean values for normalization (ImageNet).input_std (list): Per-channel std values for normalization (ImageNet).@@ -66,13 +67,12 @@ class MobileGaze(BaseGazeEstimator):def __init__(self,+ *,model_name: GazeWeights = GazeWeights.RESNET34,- input_size: tuple[int, int] = (448, 448),providers: list[str] | None = None,) -> None:- Logger.info(f'Initializing MobileGaze with model={model_name}, input_size={input_size}')+ Logger.info(f'Initializing MobileGaze with model={model_name}')- self.input_size = input_sizeself.input_mean = [0.485, 0.456, 0.406]self.input_std = [0.229, 0.224, 0.225]self.providers = providers@@ -87,8 +87,7 @@ class MobileGaze(BaseGazeEstimator):self._initialize_model()def _initialize_model(self) -> None:- """- Initialize the ONNX model from the stored model path.+ """Initialize the ONNX model from the stored model path.Raises:RuntimeError: If the model fails to load or initialize.@@ -116,8 +115,7 @@ class MobileGaze(BaseGazeEstimator):raise RuntimeError(f'Failed to initialize gaze model: {e}') from edef preprocess(self, face_image: np.ndarray) -> np.ndarray:- """- Preprocess a face crop for gaze estimation.+ """Preprocess a face crop for gaze estimation.Args:face_image (np.ndarray): A cropped face image in BGR format.@@ -144,8 +142,7 @@ class MobileGaze(BaseGazeEstimator):return imagedef postprocess(self, outputs: tuple[np.ndarray, np.ndarray]) -> GazeResult:- """- Postprocess raw model outputs into gaze angles.+ """Postprocess raw model outputs into gaze angles.This method takes the raw output from the model's inference andconverts it into pitch and yaw angles in radians.@@ -174,8 +171,7 @@ class MobileGaze(BaseGazeEstimator):return GazeResult(pitch=pitch, yaw=yaw)def estimate(self, face_image: np.ndarray) -> GazeResult:- """- Perform end-to-end gaze estimation on a face image.+ """Perform end-to-end gaze estimation on a face image.This method orchestrates the full pipeline: preprocessing the input,running inference, and postprocessing to return the gaze direction.@@ -184,8 +180,8 @@ class MobileGaze(BaseGazeEstimator):face_image (np.ndarray): A cropped face image in BGR format with shape (H, W, 3).Returns:- GazeResult: Estimated gaze direction containing ``pitch`` (vertical) and- ``yaw`` (horizontal) angles in radians.+ GazeResult: Estimated gaze direction containing `pitch` (vertical) and+ `yaw` (horizontal) angles in radians."""input_tensor = self.preprocess(face_image)outputs = self.session.run(self.output_names, {self.input_name: input_tensor})diff --git a/uniface/headpose/__init__.py b/uniface/headpose/__init__.pyindex ff3a72a..07304c0 100644--- a/uniface/headpose/__init__.py+++ b/uniface/headpose/__init__.py@@ -2,63 +2,9 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-from typing_extensions import deprecated-from uniface.types import HeadPoseResultfrom .base import BaseHeadPoseEstimatorfrom .models import HeadPose--@deprecated(- 'create_head_pose_estimator() is deprecated and will be removed in uniface 4.0. '- 'Instantiate the estimator class directly, e.g. '- '`from uniface.headpose import HeadPose; HeadPose(**kwargs)`.'-)-def create_head_pose_estimator(method: str = 'headpose', **kwargs) -> BaseHeadPoseEstimator:- """- Factory function to create head pose estimators.-- .. deprecated:: 3.7.0- Use ``HeadPose`` directly. This factory will be removed in uniface 4.0.-- This function initializes and returns a head pose estimator instance based on the- specified method. It acts as a high-level interface to the underlying model classes.-- Args:- method (str): The head pose estimation method to use.- Options: 'headpose' (default).- **kwargs: Model-specific parameters passed to the estimator's constructor.- For example, `model_name` can be used to select a specific- backbone from `HeadPoseWeights` enum (RESNET18, RESNET34, RESNET50,- MOBILENET_V2, MOBILENET_V3_SMALL, MOBILENET_V3_LARGE).-- Returns:- BaseHeadPoseEstimator: An initialized head pose estimator instance ready for use.-- Raises:- ValueError: If the specified `method` is not supported.-- Examples:- >>> # Create the default head pose estimator (ResNet18 backbone)- >>> from uniface.headpose import HeadPose- >>> estimator = HeadPose()-- >>> # Create with MobileNetV2 backbone- >>> from uniface.constants import HeadPoseWeights- >>> estimator = HeadPose(model_name=HeadPoseWeights.MOBILENET_V2)-- >>> # Use the estimator- >>> result = estimator.estimate(face_crop)- >>> print(f'Pitch: {result.pitch:.1f}°, Yaw: {result.yaw:.1f}°, Roll: {result.roll:.1f}°')- """- method = method.lower()-- if method in ('headpose', 'head_pose', '6drepnet'):- return HeadPose(**kwargs)- else:- available = ['headpose']- raise ValueError(f"Unsupported head pose estimation method: '{method}'. Available: {available}")---__all__ = ['BaseHeadPoseEstimator', 'HeadPose', 'HeadPoseResult', 'create_head_pose_estimator']+__all__ = ['BaseHeadPoseEstimator', 'HeadPose', 'HeadPoseResult']diff --git a/uniface/headpose/base.py b/uniface/headpose/base.pyindex fafdab5..a838d6e 100644--- a/uniface/headpose/base.py+++ b/uniface/headpose/base.py@@ -14,8 +14,7 @@ __all__ = ['BaseHeadPoseEstimator', 'HeadPoseResult']class BaseHeadPoseEstimator(ABC):- """- Abstract base class for all head pose estimation models.+ """Abstract base class for all head pose estimation models.This class defines the common interface that all head pose estimators must implement,ensuring consistency across different head pose estimation methods. Head pose estimation@@ -29,22 +28,18 @@ class BaseHeadPoseEstimator(ABC):@abstractmethoddef _initialize_model(self) -> None:- """- Initialize the underlying model for inference.+ """Initialize the underlying model for inference.This method should handle loading model weights, creating theinference session (e.g., ONNX Runtime), and any necessary- setup procedures to prepare the model for prediction.-- Raises:- RuntimeError: If the model fails to load or initialize.+ setup procedures to prepare the model for prediction. Implementations+ raise RuntimeError if the model fails to load or initialize."""raise NotImplementedError('Subclasses must implement the _initialize_model method.')@abstractmethoddef preprocess(self, face_image: np.ndarray) -> np.ndarray:- """- Preprocess the input face image for model inference.+ """Preprocess the input face image for model inference.This method should take a raw face crop and convert it into the formatexpected by the model's inference engine (e.g., normalized tensor).@@ -61,8 +56,7 @@ class BaseHeadPoseEstimator(ABC):@abstractmethoddef postprocess(self, rotation_matrix: np.ndarray) -> HeadPoseResult:- """- Postprocess a rotation matrix into Euler angles.+ """Postprocess a rotation matrix into Euler angles.This method takes the raw rotation matrix output from the model'sinference and converts it into pitch, yaw, and roll angles in degrees.@@ -78,8 +72,7 @@ class BaseHeadPoseEstimator(ABC):@abstractmethoddef estimate(self, face_image: np.ndarray) -> HeadPoseResult:- """- Perform end-to-end head pose estimation on a face image.+ """Perform end-to-end head pose estimation on a face image.This method orchestrates the full pipeline: preprocessing the input,running inference, and postprocessing to return the head orientation.@@ -96,15 +89,14 @@ class BaseHeadPoseEstimator(ABC):- roll: Rotation around Z-axis (positive = clockwise)Example:- >>> estimator = create_head_pose_estimator()+ >>> estimator = HeadPose()>>> result = estimator.estimate(face_crop)>>> print(f'Pose: pitch={result.pitch:.1f}°, yaw={result.yaw:.1f}°, roll={result.roll:.1f}°')"""raise NotImplementedError('Subclasses must implement the estimate method.')def __call__(self, face_image: np.ndarray) -> HeadPoseResult:- """- Provides a convenient, callable shortcut for the `estimate` method.+ """Provides a convenient, callable shortcut for the `estimate` method.Args:face_image (np.ndarray): A cropped face image in BGR format.diff --git a/uniface/headpose/models.py b/uniface/headpose/models.pyindex 6352c8a..94b064a 100644--- a/uniface/headpose/models.py+++ b/uniface/headpose/models.py@@ -17,8 +17,7 @@ __all__ = ['HeadPose']class HeadPose(BaseHeadPoseEstimator):- """- Head Pose Estimation with ONNX Runtime using 6D Rotation Representation.+ """Head Pose Estimation with ONNX Runtime using 6D Rotation Representation.This model estimates head orientation from a single face image by predictinga 3x3 rotation matrix (via continuous 6D representation) and converting it to@@ -27,6 +26,10 @@ class HeadPose(BaseHeadPoseEstimator):Supports multiple backbone architectures: ResNet-18/34/50, MobileNetV2,and MobileNetV3 (small/large).+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Reference:https://github.com/yakhyo/head-pose-estimation@@ -34,13 +37,11 @@ class HeadPose(BaseHeadPoseEstimator):model_name (HeadPoseWeights): The enum specifying the head pose model to load.Options: RESNET18, RESNET34, RESNET50, MOBILENET_V2, MOBILENET_V3_SMALL,MOBILENET_V3_LARGE. Defaults to `HeadPoseWeights.RESNET18`.- input_size (tuple[int, int]): The resolution (width, height) for the model's- input. Defaults to (224, 224).providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.Attributes:- input_size (tuple[int, int]): Model input dimensions.+ input_size (tuple[int, int]): Model input dimensions (width, height), read from the ONNX model.input_mean (np.ndarray): Per-channel mean values for normalization (ImageNet).input_std (np.ndarray): Per-channel std values for normalization (ImageNet).@@ -62,13 +63,12 @@ class HeadPose(BaseHeadPoseEstimator):def __init__(self,+ *,model_name: HeadPoseWeights = HeadPoseWeights.RESNET18,- input_size: tuple[int, int] = (224, 224),providers: list[str] | None = None,) -> None:- Logger.info(f'Initializing HeadPose with model={model_name}, input_size={input_size}')+ Logger.info(f'Initializing HeadPose with model={model_name}')- self.input_size = input_sizeself.input_mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)self.input_std = np.array([0.229, 0.224, 0.225], dtype=np.float32)self.providers = providers@@ -77,8 +77,7 @@ class HeadPose(BaseHeadPoseEstimator):self._initialize_model()def _initialize_model(self) -> None:- """- Initialize the ONNX model from the stored model path.+ """Initialize the ONNX model from the stored model path.Raises:RuntimeError: If the model fails to load or initialize.@@ -104,8 +103,7 @@ class HeadPose(BaseHeadPoseEstimator):raise RuntimeError(f'Failed to initialize head pose model: {e}') from edef preprocess(self, face_image: np.ndarray) -> np.ndarray:- """- Preprocess a face crop for head pose estimation.+ """Preprocess a face crop for head pose estimation.Args:face_image (np.ndarray): A cropped face image in BGR format.@@ -148,8 +146,7 @@ class HeadPose(BaseHeadPoseEstimator):return np.degrees(np.stack([x, y, z], axis=1))def postprocess(self, rotation_matrix: np.ndarray) -> HeadPoseResult:- """- Convert a rotation matrix into Euler angles.+ """Convert a rotation matrix into Euler angles.Args:rotation_matrix: Rotation matrix with shape (B, 3, 3).@@ -165,8 +162,7 @@ class HeadPose(BaseHeadPoseEstimator):)def estimate(self, face_image: np.ndarray) -> HeadPoseResult:- """- Perform end-to-end head pose estimation on a face image.+ """Perform end-to-end head pose estimation on a face image.This method orchestrates the full pipeline: preprocessing the input,running inference, and postprocessing to return the head orientation.@@ -175,8 +171,8 @@ class HeadPose(BaseHeadPoseEstimator):face_image (np.ndarray): A cropped face image in BGR format with shape (H, W, 3).Returns:- HeadPoseResult: Estimated head orientation containing ``pitch`` (vertical),- ``yaw`` (horizontal), and ``roll`` (in-plane) angles in degrees.+ HeadPoseResult: Estimated head orientation containing `pitch` (vertical),+ `yaw` (horizontal), and `roll` (in-plane) angles in degrees."""input_tensor = self.preprocess(face_image)outputs = self.session.run(self.output_names, {self.input_name: input_tensor})diff --git a/uniface/landmark/__init__.py b/uniface/landmark/__init__.pyindex 0a525f9..d12de2d 100644--- a/uniface/landmark/__init__.py+++ b/uniface/landmark/__init__.py@@ -2,48 +2,28 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-from typing_extensions import deprecated-+from ._tessellation import (+ FACEMESH_TESSELATION_FULL,+ FACEMESH_TESSELATION_PARTIAL,+ IRIS_LEFT,+ IRIS_RIGHT,+ NUM_MESH_LANDMARKS,+)from .base import BaseLandmarker+from .facemesh import FaceMesh, roi_from_box, warp_roifrom .models import Landmark106from .pipnet import PIPNet--@deprecated(- 'create_landmarker() is deprecated and will be removed in uniface 4.0. '- 'Instantiate the landmarker class directly, e.g. '- '`from uniface.landmark import Landmark106; Landmark106(**kwargs)`.'-)-def create_landmarker(method: str = '2d106det', **kwargs) -> BaseLandmarker:- """Factory function to create facial landmark predictors.-- .. deprecated:: 3.7.0- Use the landmarker class directly (``Landmark106``, ``PIPNet``).- This factory will be removed in uniface 4.0.-- Args:- method (str): Landmark prediction method.- Options:- - ``'2d106det'`` (default): InsightFace 2d106det 106-point model.- - ``'pipnet'``: PIPNet 98-point (WFLW) or 68-point (300W+CelebA)- model. Pass ``model_name=PIPNetWeights.DW300_CELEBA_68`` for- the 68-point variant.- **kwargs: Model-specific parameters forwarded to the underlying class.-- Returns:- Initialized landmarker instance.-- Raises:- ValueError: If ``method`` is not supported.- """- method = method.lower()- if method == '2d106det':- return Landmark106(**kwargs)- if method == 'pipnet':- return PIPNet(**kwargs)-- available = ['2d106det', 'pipnet']- raise ValueError(f"Unsupported method: '{method}'. Available: {available}")---__all__ = ['BaseLandmarker', 'Landmark106', 'PIPNet', 'create_landmarker']+__all__ = [+ 'FACEMESH_TESSELATION_FULL',+ 'FACEMESH_TESSELATION_PARTIAL',+ 'IRIS_LEFT',+ 'IRIS_RIGHT',+ 'NUM_MESH_LANDMARKS',+ 'BaseLandmarker',+ 'FaceMesh',+ 'Landmark106',+ 'PIPNet',+ 'roi_from_box',+ 'warp_roi',+]diff --git a/uniface/landmark/_meanface.py b/uniface/landmark/_meanface.pyindex b95b473..9928911 100644--- a/uniface/landmark/_meanface.py+++ b/uniface/landmark/_meanface.py@@ -142,10 +142,10 @@ def get_meanface_info(num_lms: int, num_nb: int = 10) -> tuple[np.ndarray, np.ndnum_nb: Neighbor count used at training time.Returns:- ``(reverse_index1, reverse_index2, max_len)``.+ `(reverse_index1, reverse_index2, max_len)`.Raises:- ValueError: If ``num_lms`` does not match a shipped meanface table.+ ValueError: If `num_lms` does not match a shipped meanface table."""if num_lms == 68:flat = MEANFACE_300W_68@@ -155,7 +155,8 @@ def get_meanface_info(num_lms: int, num_nb: int = 10) -> tuple[np.ndarray, np.ndraise ValueError(f'No meanface table available for num_lms={num_lms}; expected 68 or 98.')meanface = np.asarray(flat, dtype=np.float32).reshape(-1, 2)- assert meanface.shape[0] == num_lms, f'meanface mismatch: expected {num_lms} points, got {meanface.shape[0]}'+ if meanface.shape[0] != num_lms:+ raise ValueError(f'meanface table for num_lms={num_lms} holds {meanface.shape[0]} points')r1, r2, max_len = _build_neighbor_indices(meanface, num_nb)return np.asarray(r1, dtype=np.int64), np.asarray(r2, dtype=np.int64), max_lendiff --git a/uniface/landmark/_tessellation.py b/uniface/landmark/_tessellation.pynew file mode 100644index 0000000..34d3c66--- /dev/null+++ b/uniface/landmark/_tessellation.py@@ -0,0 +1,481 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo+#+# Face mesh edge lists vendored from PINTO0309/facemesh_onnx_tensorrt (Apache-2.0):+# https://github.com/PINTO0309/facemesh_onnx_tensorrt+# Original 468-point topology from Google MediaPipe (Apache-2.0):+# https://github.com/google-ai-edge/mediapipe+#+# Edges index into the 468-point mesh returned by `uniface.landmark.FaceMesh`.+# PARTIAL is a sparse contour set (124 edges); FULL is the dense tessellation+# (2556 edges) and is far heavier to draw.++from __future__ import annotations++#: Landmarks both FaceMesh models produce. `V2_478` appends the irises after these.+NUM_MESH_LANDMARKS = 468++#: Left iris in a 478-point result, ordered center, right, top, left, bottom.+IRIS_LEFT = slice(468, 473)++#: Right iris in a 478-point result, ordered center, right, top, left, bottom.+IRIS_RIGHT = slice(473, 478)++# fmt: off+FACEMESH_TESSELATION_PARTIAL: list[list[int]] = [+ [0, 267], [7, 163], [10, 338], [13, 312], [14, 317],+ [17, 314], [21, 54], [33, 7], [33, 246], [37, 0],+ [39, 37], [40, 39], [46, 53], [52, 65], [53, 52],+ [54, 103], [58, 132], [61, 146], [61, 185], [63, 105],+ [65, 55], [66, 107], [67, 109], [70, 63], [78, 95],+ [78, 191], [80, 81], [81, 82], [82, 13], [84, 17],+ [87, 14], [88, 178], [91, 181], [93, 234], [95, 88],+ [103, 67], [105, 66], [109, 10], [127, 162], [132, 93],+ [136, 172], [144, 145], [145, 153], [146, 91], [148, 176],+ [149, 150], [150, 136], [152, 148], [153, 154], [154, 155],+ [155, 133], [157, 173], [158, 157], [159, 158], [160, 159],+ [161, 160], [162, 21], [163, 144], [172, 58], [173, 133],+ [176, 149], [178, 87], [181, 84], [185, 40], [191, 80],+ [234, 127], [246, 161], [249, 390], [251, 389], [263, 249],+ [263, 466], [267, 269], [269, 270], [270, 409], [276, 283],+ [282, 295], [283, 282], [284, 251], [288, 397], [293, 334],+ [295, 285], [296, 336], [297, 332], [300, 293], [310, 415],+ [311, 310], [312, 311], [314, 405], [317, 402], [318, 324],+ [321, 375], [323, 361], [324, 308], [332, 284], [334, 296],+ [338, 297], [356, 454], [361, 288], [365, 379], [373, 374],+ [374, 380], [375, 291], [377, 152], [378, 400], [379, 378],+ [380, 381], [381, 382], [382, 362], [384, 398], [385, 384],+ [386, 385], [387, 386], [388, 387], [389, 356], [390, 373],+ [397, 365], [398, 362], [400, 377], [402, 318], [405, 321],+ [409, 291], [415, 308], [454, 323], [466, 388],+]+FACEMESH_TESSELATION_FULL: list[list[int]] = [+ [127, 34], [34, 139], [139, 127], [11, 0], [0, 37], [37, 11],+ [232, 231], [231, 120], [120, 232], [72, 37], [37, 39], [39, 72],+ [128, 121], [121, 47], [47, 128], [232, 121], [121, 128], [128, 232],+ [104, 69], [69, 67], [67, 104], [175, 171], [171, 148], [148, 175],+ [118, 50], [50, 101], [101, 118], [73, 39], [39, 40], [40, 73],+ [9, 151], [151, 108], [108, 9], [48, 115], [115, 131], [131, 48],+ [194, 204], [204, 211], [211, 194], [74, 40], [40, 185], [185, 74],+ [80, 42], [42, 183], [183, 80], [40, 92], [92, 186], [186, 40],+ [230, 229], [229, 118], [118, 230], [202, 212], [212, 214], [214, 202],+ [83, 18], [18, 17], [17, 83], [76, 61], [61, 146], [146, 76],+ [160, 29], [29, 30], [30, 160], [56, 157], [157, 173], [173, 56],+ [106, 204], [204, 194], [194, 106], [135, 214], [214, 192], [192, 135],+ [203, 165], [165, 98], [98, 203], [21, 71], [71, 68], [68, 21],+ [51, 45], [45, 4], [4, 51], [144, 24], [24, 23], [23, 144],+ [77, 146], [146, 91], [91, 77], [205, 50], [50, 187], [187, 205],+ [201, 200], [200, 18], [18, 201], [91, 106], [106, 182], [182, 91],+ [90, 91], [91, 181], [181, 90], [85, 84], [84, 17], [17, 85],+ [206, 203], [203, 36], [36, 206], [148, 171], [171, 140], [140, 148],+ [92, 40], [40, 39], [39, 92], [193, 189], [189, 244], [244, 193],+ [159, 158], [158, 28], [28, 159], [247, 246], [246, 161], [161, 247],+ [236, 3], [3, 196], [196, 236], [54, 68], [68, 104], [104, 54],+ [193, 168], [168, 8], [8, 193], [117, 228], [228, 31], [31, 117],+ [189, 193], [193, 55], [55, 189], [98, 97], [97, 99], [99, 98],+ [126, 47], [47, 100], [100, 126], [166, 79], [79, 218], [218, 166],+ [155, 154], [154, 26], [26, 155], [209, 49], [49, 131], [131, 209],+ [135, 136], [136, 150], [150, 135], [47, 126], [126, 217], [217, 47],+ [223, 52], [52, 53], [53, 223], [45, 51], [51, 134], [134, 45],+ [211, 170], [170, 140], [140, 211], [67, 69], [69, 108], [108, 67],+ [43, 106], [106, 91], [91, 43], [230, 119], [119, 120], [120, 230],+ [226, 130], [130, 247], [247, 226], [63, 53], [53, 52], [52, 63],+ [238, 20], [20, 242], [242, 238], [46, 70], [70, 156], [156, 46],+ [78, 62], [62, 96], [96, 78], [46, 53], [53, 63], [63, 46],+ [143, 34], [34, 227], [227, 143], [123, 117], [117, 111], [111, 123],+ [44, 125], [125, 19], [19, 44], [236, 134], [134, 51], [51, 236],+ [216, 206], [206, 205], [205, 216], [154, 153], [153, 22], [22, 154],+ [39, 37], [37, 167], [167, 39], [200, 201], [201, 208], [208, 200],+ [36, 142], [142, 100], [100, 36], [57, 212], [212, 202], [202, 57],+ [20, 60], [60, 99], [99, 20], [28, 158], [158, 157], [157, 28],+ [35, 226], [226, 113], [113, 35], [160, 159], [159, 27], [27, 160],+ [204, 202], [202, 210], [210, 204], [113, 225], [225, 46], [46, 113],+ [43, 202], [202, 204], [204, 43], [62, 76], [76, 77], [77, 62],+ [137, 123], [123, 116], [116, 137], [41, 38], [38, 72], [72, 41],+ [203, 129], [129, 142], [142, 203], [64, 98], [98, 240], [240, 64],+ [49, 102], [102, 64], [64, 49], [41, 73], [73, 74], [74, 41],+ [212, 216], [216, 207], [207, 212], [42, 74], [74, 184], [184, 42],+ [169, 170], [170, 211], [211, 169], [170, 149], [149, 176], [176, 170],+ [105, 66], [66, 69], [69, 105], [122, 6], [6, 168], [168, 122],+ [123, 147], [147, 187], [187, 123], [96, 77], [77, 90], [90, 96],+ [65, 55], [55, 107], [107, 65], [89, 90], [90, 180], [180, 89],+ [101, 100], [100, 120], [120, 101], [63, 105], [105, 104], [104, 63],+ [93, 137], [137, 227], [227, 93], [15, 86], [86, 85], [85, 15],+ [129, 102], [102, 49], [49, 129], [14, 87], [87, 86], [86, 14],+ [55, 8], [8, 9], [9, 55], [100, 47], [47, 121], [121, 100],+ [145, 23], [23, 22], [22, 145], [88, 89], [89, 179], [179, 88],+ [6, 122], [122, 196], [196, 6], [88, 95], [95, 96], [96, 88],+ [138, 172], [172, 136], [136, 138], [215, 58], [58, 172], [172, 215],+ [115, 48], [48, 219], [219, 115], [42, 80], [80, 81], [81, 42],+ [195, 3], [3, 51], [51, 195], [43, 146], [146, 61], [61, 43],+ [171, 175], [175, 199], [199, 171], [81, 82], [82, 38], [38, 81],+ [53, 46], [46, 225], [225, 53], [144, 163], [163, 110], [110, 144],+ [52, 65], [65, 66], [66, 52], [229, 228], [228, 117], [117, 229],+ [34, 127], [127, 234], [234, 34], [107, 108], [108, 69], [69, 107],+ [109, 108], [108, 151], [151, 109], [48, 64], [64, 235], [235, 48],+ [62, 78], [78, 191], [191, 62], [129, 209], [209, 126], [126, 129],+ [111, 35], [35, 143], [143, 111], [117, 123], [123, 50], [50, 117],+ [222, 65], [65, 52], [52, 222], [19, 125], [125, 141], [141, 19],+ [221, 55], [55, 65], [65, 221], [3, 195], [195, 197], [197, 3],+ [25, 7], [7, 33], [33, 25], [220, 237], [237, 44], [44, 220],+ [70, 71], [71, 139], [139, 70], [122, 193], [193, 245], [245, 122],+ [247, 130], [130, 33], [33, 247], [71, 21], [21, 162], [162, 71],+ [170, 169], [169, 150], [150, 170], [188, 174], [174, 196], [196, 188],+ [216, 186], [186, 92], [92, 216], [2, 97], [97, 167], [167, 2],+ [141, 125], [125, 241], [241, 141], [164, 167], [167, 37], [37, 164],+ [72, 38], [38, 12], [12, 72], [38, 82], [82, 13], [13, 38],+ [63, 68], [68, 71], [71, 63], [226, 35], [35, 111], [111, 226],+ [101, 50], [50, 205], [205, 101], [206, 92], [92, 165], [165, 206],+ [209, 198], [198, 217], [217, 209], [165, 167], [167, 97], [97, 165],+ [220, 115], [115, 218], [218, 220], [133, 112], [112, 243], [243, 133],+ [239, 238], [238, 241], [241, 239], [214, 135], [135, 169], [169, 214],+ [190, 173], [173, 133], [133, 190], [171, 208], [208, 32], [32, 171],+ [125, 44], [44, 237], [237, 125], [86, 87], [87, 178], [178, 86],+ [85, 86], [86, 179], [179, 85], [84, 85], [85, 180], [180, 84],+ [83, 84], [84, 181], [181, 83], [201, 83], [83, 182], [182, 201],+ [137, 93], [93, 132], [132, 137], [76, 62], [62, 183], [183, 76],+ [61, 76], [76, 184], [184, 61], [57, 61], [61, 185], [185, 57],+ [212, 57], [57, 186], [186, 212], [214, 207], [207, 187], [187, 214],+ [34, 143], [143, 156], [156, 34], [79, 239], [239, 237], [237, 79],+ [123, 137], [137, 177], [177, 123], [44, 1], [1, 4], [4, 44],+ [201, 194], [194, 32], [32, 201], [64, 102], [102, 129], [129, 64],+ [213, 215], [215, 138], [138, 213], [59, 166], [166, 219], [219, 59],+ [242, 99], [99, 97], [97, 242], [2, 94], [94, 141], [141, 2],+ [75, 59], [59, 235], [235, 75], [24, 110], [110, 228], [228, 24],+ [25, 130], [130, 226], [226, 25], [23, 24], [24, 229], [229, 23],+ [22, 23], [23, 230], [230, 22], [26, 22], [22, 231], [231, 26],+ [112, 26], [26, 232], [232, 112], [189, 190], [190, 243], [243, 189],+ [221, 56], [56, 190], [190, 221], [28, 56], [56, 221], [221, 28],+ [27, 28], [28, 222], [222, 27], [29, 27], [27, 223], [223, 29],+ [30, 29], [29, 224], [224, 30], [247, 30], [30, 225], [225, 247],+ [238, 79], [79, 20], [20, 238], [166, 59], [59, 75], [75, 166],+ [60, 75], [75, 240], [240, 60], [147, 177], [177, 215], [215, 147],+ [20, 79], [79, 166], [166, 20], [187, 147], [147, 213], [213, 187],+ [112, 233], [233, 244], [244, 112], [233, 128], [128, 245], [245, 233],+ [128, 114], [114, 188], [188, 128], [114, 217], [217, 174], [174, 114],+ [131, 115], [115, 220], [220, 131], [217, 198], [198, 236], [236, 217],+ [198, 131], [131, 134], [134, 198], [177, 132], [132, 58], [58, 177],+ [143, 35], [35, 124], [124, 143], [110, 163], [163, 7], [7, 110],+ [228, 110], [110, 25], [25, 228], [356, 389], [389, 368], [368, 356],+ [11, 302], [302, 267], [267, 11], [452, 350], [350, 349], [349, 452],+ [302, 303], [303, 269], [269, 302], [357, 343], [343, 277], [277, 357],+ [452, 453], [453, 357], [357, 452], [333, 332], [332, 297], [297, 333],+ [175, 152], [152, 377], [377, 175], [347, 348], [348, 330], [330, 347],+ [303, 304], [304, 270], [270, 303], [9, 336], [336, 337], [337, 9],+ [278, 279], [279, 360], [360, 278], [418, 262], [262, 431], [431, 418],+ [304, 408], [408, 409], [409, 304], [310, 415], [415, 407], [407, 310],+ [270, 409], [409, 410], [410, 270], [450, 348], [348, 347], [347, 450],+ [422, 430], [430, 434], [434, 422], [313, 314], [314, 17], [17, 313],+ [306, 307], [307, 375], [375, 306], [387, 388], [388, 260], [260, 387],+ [286, 414], [414, 398], [398, 286], [335, 406], [406, 418], [418, 335],+ [364, 367], [367, 416], [416, 364], [423, 358], [358, 327], [327, 423],+ [251, 284], [284, 298], [298, 251], [281, 5], [5, 4], [4, 281],+ [373, 374], [374, 253], [253, 373], [307, 320], [320, 321], [321, 307],+ [425, 427], [427, 411], [411, 425], [421, 313], [313, 18], [18, 421],+ [321, 405], [405, 406], [406, 321], [320, 404], [404, 405], [405, 320],+ [315, 16], [16, 17], [17, 315], [426, 425], [425, 266], [266, 426],+ [377, 400], [400, 369], [369, 377], [322, 391], [391, 269], [269, 322],+ [417, 465], [465, 464], [464, 417], [386, 257], [257, 258], [258, 386],+ [466, 260], [260, 388], [388, 466], [456, 399], [399, 419], [419, 456],+ [284, 332], [332, 333], [333, 284], [417, 285], [285, 8], [8, 417],+ [346, 340], [340, 261], [261, 346], [413, 441], [441, 285], [285, 413],+ [327, 460], [460, 328], [328, 327], [355, 371], [371, 329], [329, 355],+ [392, 439], [439, 438], [438, 392], [382, 341], [341, 256], [256, 382],+ [429, 420], [420, 360], [360, 429], [364, 394], [394, 379], [379, 364],+ [277, 343], [343, 437], [437, 277], [443, 444], [444, 283], [283, 443],+ [275, 440], [440, 363], [363, 275], [431, 262], [262, 369], [369, 431],+ [297, 338], [338, 337], [337, 297], [273, 375], [375, 321], [321, 273],+ [450, 451], [451, 349], [349, 450], [446, 342], [342, 467], [467, 446],+ [293, 334], [334, 282], [282, 293], [458, 461], [461, 462], [462, 458],+ [276, 353], [353, 383], [383, 276], [308, 324], [324, 325], [325, 308],+ [276, 300], [300, 293], [293, 276], [372, 345], [345, 447], [447, 372],+ [352, 345], [345, 340], [340, 352], [274, 1], [1, 19], [19, 274],+ [456, 248], [248, 281], [281, 456], [436, 427], [427, 425], [425, 436],+ [381, 256], [256, 252], [252, 381], [269, 391], [391, 393], [393, 269],+ [200, 199], [199, 428], [428, 200], [266, 330], [330, 329], [329, 266],+ [287, 273], [273, 422], [422, 287], [250, 462], [462, 328], [328, 250],+ [258, 286], [286, 384], [384, 258], [265, 353], [353, 342], [342, 265],+ [387, 259], [259, 257], [257, 387], [424, 431], [431, 430], [430, 424],+ [342, 353], [353, 276], [276, 342], [273, 335], [335, 424], [424, 273],+ [292, 325], [325, 307], [307, 292], [366, 447], [447, 345], [345, 366],+ [271, 303], [303, 302], [302, 271], [423, 266], [266, 371], [371, 423],+ [294, 455], [455, 460], [460, 294], [279, 278], [278, 294], [294, 279],+ [271, 272], [272, 304], [304, 271], [432, 434], [434, 427], [427, 432],+ [272, 407], [407, 408], [408, 272], [394, 430], [430, 431], [431, 394],+ [395, 369], [369, 400], [400, 395], [334, 333], [333, 299], [299, 334],+ [351, 417], [417, 168], [168, 351], [352, 280], [280, 411], [411, 352],+ [325, 319], [319, 320], [320, 325], [295, 296], [296, 336], [336, 295],+ [319, 403], [403, 404], [404, 319], [330, 348], [348, 349], [349, 330],+ [293, 298], [298, 333], [333, 293], [323, 454], [454, 447], [447, 323],+ [15, 16], [16, 315], [315, 15], [358, 429], [429, 279], [279, 358],+ [14, 15], [15, 316], [316, 14], [285, 336], [336, 9], [9, 285],+ [329, 349], [349, 350], [350, 329], [374, 380], [380, 252], [252, 374],+ [318, 402], [402, 403], [403, 318], [6, 197], [197, 419], [419, 6],+ [318, 319], [319, 325], [325, 318], [367, 364], [364, 365], [365, 367],+ [435, 367], [367, 397], [397, 435], [344, 438], [438, 439], [439, 344],+ [272, 271], [271, 311], [311, 272], [195, 5], [5, 281], [281, 195],+ [273, 287], [287, 291], [291, 273], [396, 428], [428, 199], [199, 396],+ [311, 271], [271, 268], [268, 311], [283, 444], [444, 445], [445, 283],+ [373, 254], [254, 339], [339, 373], [282, 334], [334, 296], [296, 282],+ [449, 347], [347, 346], [346, 449], [264, 447], [447, 454], [454, 264],+ [336, 296], [296, 299], [299, 336], [338, 10], [10, 151], [151, 338],+ [278, 439], [439, 455], [455, 278], [292, 407], [407, 415], [415, 292],+ [358, 371], [371, 355], [355, 358], [340, 345], [345, 372], [372, 340],+ [346, 347], [347, 280], [280, 346], [442, 443], [443, 282], [282, 442],+ [19, 94], [94, 370], [370, 19], [441, 442], [442, 295], [295, 441],+ [248, 419], [419, 197], [197, 248], [263, 255], [255, 359], [359, 263],+ [440, 275], [275, 274], [274, 440], [300, 383], [383, 368], [368, 300],+ [351, 412], [412, 465], [465, 351], [263, 467], [467, 466], [466, 263],+ [301, 368], [368, 389], [389, 301], [395, 378], [378, 379], [379, 395],+ [412, 351], [351, 419], [419, 412], [436, 426], [426, 322], [322, 436],+ [2, 164], [164, 393], [393, 2], [370, 462], [462, 461], [461, 370],+ [164, 0], [0, 267], [267, 164], [302, 11], [11, 12], [12, 302],+ [268, 12], [12, 13], [13, 268], [293, 300], [300, 301], [301, 293],+ [446, 261], [261, 340], [340, 446], [330, 266], [266, 425], [425, 330],+ [426, 423], [423, 391], [391, 426], [429, 355], [355, 437], [437, 429],+ [391, 327], [327, 326], [326, 391], [440, 457], [457, 438], [438, 440],+ [341, 382], [382, 362], [362, 341], [459, 457], [457, 461], [461, 459],+ [434, 430], [430, 394], [394, 434], [414, 463], [463, 362], [362, 414],+ [396, 369], [369, 262], [262, 396], [354, 461], [461, 457], [457, 354],+ [316, 403], [403, 402], [402, 316], [315, 404], [404, 403], [403, 315],+ [314, 405], [405, 404], [404, 314], [313, 406], [406, 405], [405, 313],+ [421, 418], [418, 406], [406, 421], [366, 401], [401, 361], [361, 366],+ [306, 408], [408, 407], [407, 306], [291, 409], [409, 408], [408, 291],+ [287, 410], [410, 409], [409, 287], [432, 436], [436, 410], [410, 432],+ [434, 416], [416, 411], [411, 434], [264, 368], [368, 383], [383, 264],+ [309, 438], [438, 457], [457, 309], [352, 376], [376, 401], [401, 352],+ [274, 275], [275, 4], [4, 274], [421, 428], [428, 262], [262, 421],+ [294, 327], [327, 358], [358, 294], [433, 416], [416, 367], [367, 433],+ [289, 455], [455, 439], [439, 289], [462, 370], [370, 326], [326, 462],+ [2, 326], [326, 370], [370, 2], [305, 460], [460, 455], [455, 305],+ [254, 449], [449, 448], [448, 254], [255, 261], [261, 446], [446, 255],+ [253, 450], [450, 449], [449, 253], [252, 451], [451, 450], [450, 252],+ [256, 452], [452, 451], [451, 256], [341, 453], [453, 452], [452, 341],+ [413, 464], [464, 463], [463, 413], [441, 413], [413, 414], [414, 441],+ [258, 442], [442, 441], [441, 258], [257, 443], [443, 442], [442, 257],+ [259, 444], [444, 443], [443, 259], [260, 445], [445, 444], [444, 260],+ [467, 342], [342, 445], [445, 467], [459, 458], [458, 250], [250, 459],+ [289, 392], [392, 290], [290, 289], [290, 328], [328, 460], [460, 290],+ [376, 433], [433, 435], [435, 376], [250, 290], [290, 392], [392, 250],+ [411, 416], [416, 433], [433, 411], [341, 463], [463, 464], [464, 341],+ [453, 464], [464, 465], [465, 453], [357, 465], [465, 412], [412, 357],+ [343, 412], [412, 399], [399, 343], [360, 363], [363, 440], [440, 360],+ [437, 399], [399, 456], [456, 437], [420, 456], [456, 363], [363, 420],+ [401, 435], [435, 288], [288, 401], [372, 383], [383, 353], [353, 372],+ [339, 255], [255, 249], [249, 339], [448, 261], [261, 255], [255, 448],+ [133, 243], [243, 190], [190, 133], [133, 155], [155, 112], [112, 133],+ [33, 246], [246, 247], [247, 33], [33, 130], [130, 25], [25, 33],+ [398, 384], [384, 286], [286, 398], [362, 398], [398, 414], [414, 362],+ [362, 463], [463, 341], [341, 362], [263, 359], [359, 467], [467, 263],+ [263, 249], [249, 255], [255, 263], [466, 467], [467, 260], [260, 466],+ [75, 60], [60, 166], [166, 75], [238, 239], [239, 79], [79, 238],+ [162, 127], [127, 139], [139, 162], [72, 11], [11, 37], [37, 72],+ [121, 232], [232, 120], [120, 121], [73, 72], [72, 39], [39, 73],+ [114, 128], [128, 47], [47, 114], [233, 232], [232, 128], [128, 233],+ [103, 104], [104, 67], [67, 103], [152, 175], [175, 148], [148, 152],+ [119, 118], [118, 101], [101, 119], [74, 73], [73, 40], [40, 74],+ [107, 9], [9, 108], [108, 107], [49, 48], [48, 131], [131, 49],+ [32, 194], [194, 211], [211, 32], [184, 74], [74, 185], [185, 184],+ [191, 80], [80, 183], [183, 191], [185, 40], [40, 186], [186, 185],+ [119, 230], [230, 118], [118, 119], [210, 202], [202, 214], [214, 210],+ [84, 83], [83, 17], [17, 84], [77, 76], [76, 146], [146, 77],+ [161, 160], [160, 30], [30, 161], [190, 56], [56, 173], [173, 190],+ [182, 106], [106, 194], [194, 182], [138, 135], [135, 192], [192, 138],+ [129, 203], [203, 98], [98, 129], [54, 21], [21, 68], [68, 54],+ [5, 51], [51, 4], [4, 5], [145, 144], [144, 23], [23, 145],+ [90, 77], [77, 91], [91, 90], [207, 205], [205, 187], [187, 207],+ [83, 201], [201, 18], [18, 83], [181, 91], [91, 182], [182, 181],+ [180, 90], [90, 181], [181, 180], [16, 85], [85, 17], [17, 16],+ [205, 206], [206, 36], [36, 205], [176, 148], [148, 140], [140, 176],+ [165, 92], [92, 39], [39, 165], [245, 193], [193, 244], [244, 245],+ [27, 159], [159, 28], [28, 27], [30, 247], [247, 161], [161, 30],+ [174, 236], [236, 196], [196, 174], [103, 54], [54, 104], [104, 103],+ [55, 193], [193, 8], [8, 55], [111, 117], [117, 31], [31, 111],+ [221, 189], [189, 55], [55, 221], [240, 98], [98, 99], [99, 240],+ [142, 126], [126, 100], [100, 142], [219, 166], [166, 218], [218, 219],+ [112, 155], [155, 26], [26, 112], [198, 209], [209, 131], [131, 198],+ [169, 135], [135, 150], [150, 169], [114, 47], [47, 217], [217, 114],+ [224, 223], [223, 53], [53, 224], [220, 45], [45, 134], [134, 220],+ [32, 211], [211, 140], [140, 32], [109, 67], [67, 108], [108, 109],+ [146, 43], [43, 91], [91, 146], [231, 230], [230, 120], [120, 231],+ [113, 226], [226, 247], [247, 113], [105, 63], [63, 52], [52, 105],+ [241, 238], [238, 242], [242, 241], [124, 46], [46, 156], [156, 124],+ [95, 78], [78, 96], [96, 95], [70, 46], [46, 63], [63, 70],+ [116, 143], [143, 227], [227, 116], [116, 123], [123, 111], [111, 116],+ [1, 44], [44, 19], [19, 1], [3, 236], [236, 51], [51, 3],+ [207, 216], [216, 205], [205, 207], [26, 154], [154, 22], [22, 26],+ [165, 39], [39, 167], [167, 165], [199, 200], [200, 208], [208, 199],+ [101, 36], [36, 100], [100, 101], [43, 57], [57, 202], [202, 43],+ [242, 20], [20, 99], [99, 242], [56, 28], [28, 157], [157, 56],+ [124, 35], [35, 113], [113, 124], [29, 160], [160, 27], [27, 29],+ [211, 204], [204, 210], [210, 211], [124, 113], [113, 46], [46, 124],+ [106, 43], [43, 204], [204, 106], [96, 62], [62, 77], [77, 96],+ [227, 137], [137, 116], [116, 227], [73, 41], [41, 72], [72, 73],+ [36, 203], [203, 142], [142, 36], [235, 64], [64, 240], [240, 235],+ [48, 49], [49, 64], [64, 48], [42, 41], [41, 74], [74, 42],+ [214, 212], [212, 207], [207, 214], [183, 42], [42, 184], [184, 183],+ [210, 169], [169, 211], [211, 210], [140, 170], [170, 176], [176, 140],+ [104, 105], [105, 69], [69, 104], [193, 122], [122, 168], [168, 193],+ [50, 123], [123, 187], [187, 50], [89, 96], [96, 90], [90, 89],+ [66, 65], [65, 107], [107, 66], [179, 89], [89, 180], [180, 179],+ [119, 101], [101, 120], [120, 119], [68, 63], [63, 104], [104, 68],+ [234, 93], [93, 227], [227, 234], [16, 15], [15, 85], [85, 16],+ [209, 129], [129, 49], [49, 209], [15, 14], [14, 86], [86, 15],+ [107, 55], [55, 9], [9, 107], [120, 100], [100, 121], [121, 120],+ [153, 145], [145, 22], [22, 153], [178, 88], [88, 179], [179, 178],+ [197, 6], [6, 196], [196, 197], [89, 88], [88, 96], [96, 89],+ [135, 138], [138, 136], [136, 135], [138, 215], [215, 172], [172, 138],+ [218, 115], [115, 219], [219, 218], [41, 42], [42, 81], [81, 41],+ [5, 195], [195, 51], [51, 5], [57, 43], [43, 61], [61, 57],+ [208, 171], [171, 199], [199, 208], [41, 81], [81, 38], [38, 41],+ [224, 53], [53, 225], [225, 224], [24, 144], [144, 110], [110, 24],+ [105, 52], [52, 66], [66, 105], [118, 229], [229, 117], [117, 118],+ [227, 34], [34, 234], [234, 227], [66, 107], [107, 69], [69, 66],+ [10, 109], [109, 151], [151, 10], [219, 48], [48, 235], [235, 219],+ [183, 62], [62, 191], [191, 183], [142, 129], [129, 126], [126, 142],+ [116, 111], [111, 143], [143, 116], [118, 117], [117, 50], [50, 118],+ [223, 222], [222, 52], [52, 223], [94, 19], [19, 141], [141, 94],+ [222, 221], [221, 65], [65, 222], [196, 3], [3, 197], [197, 196],+ [45, 220], [220, 44], [44, 45], [156, 70], [70, 139], [139, 156],+ [188, 122], [122, 245], [245, 188], [139, 71], [71, 162], [162, 139],+ [149, 170], [170, 150], [150, 149], [122, 188], [188, 196], [196, 122],+ [206, 216], [216, 92], [92, 206], [164, 2], [2, 167], [167, 164],+ [242, 141], [141, 241], [241, 242], [0, 164], [164, 37], [37, 0],+ [11, 72], [72, 12], [12, 11], [12, 38], [38, 13], [13, 12],+ [70, 63], [63, 71], [71, 70], [31, 226], [226, 111], [111, 31],+ [36, 101], [101, 205], [205, 36], [203, 206], [206, 165], [165, 203],+ [126, 209], [209, 217], [217, 126], [98, 165], [165, 97], [97, 98],+ [237, 220], [220, 218], [218, 237], [237, 239], [239, 241], [241, 237],+ [210, 214], [214, 169], [169, 210], [140, 171], [171, 32], [32, 140],+ [241, 125], [125, 237], [237, 241], [179, 86], [86, 178], [178, 179],+ [180, 85], [85, 179], [179, 180], [181, 84], [84, 180], [180, 181],+ [182, 83], [83, 181], [181, 182], [194, 201], [201, 182], [182, 194],+ [177, 137], [137, 132], [132, 177], [184, 76], [76, 183], [183, 184],+ [185, 61], [61, 184], [184, 185], [186, 57], [57, 185], [185, 186],+ [216, 212], [212, 186], [186, 216], [192, 214], [214, 187], [187, 192],+ [139, 34], [34, 156], [156, 139], [218, 79], [79, 237], [237, 218],+ [147, 123], [123, 177], [177, 147], [45, 44], [44, 4], [4, 45],+ [208, 201], [201, 32], [32, 208], [98, 64], [64, 129], [129, 98],+ [192, 213], [213, 138], [138, 192], [235, 59], [59, 219], [219, 235],+ [141, 242], [242, 97], [97, 141], [97, 2], [2, 141], [141, 97],+ [240, 75], [75, 235], [235, 240], [229, 24], [24, 228], [228, 229],+ [31, 25], [25, 226], [226, 31], [230, 23], [23, 229], [229, 230],+ [231, 22], [22, 230], [230, 231], [232, 26], [26, 231], [231, 232],+ [233, 112], [112, 232], [232, 233], [244, 189], [189, 243], [243, 244],+ [189, 221], [221, 190], [190, 189], [222, 28], [28, 221], [221, 222],+ [223, 27], [27, 222], [222, 223], [224, 29], [29, 223], [223, 224],+ [225, 30], [30, 224], [224, 225], [113, 247], [247, 225], [225, 113],+ [99, 60], [60, 240], [240, 99], [213, 147], [147, 215], [215, 213],+ [60, 20], [20, 166], [166, 60], [192, 187], [187, 213], [213, 192],+ [243, 112], [112, 244], [244, 243], [244, 233], [233, 245], [245, 244],+ [245, 128], [128, 188], [188, 245], [188, 114], [114, 174], [174, 188],+ [134, 131], [131, 220], [220, 134], [174, 217], [217, 236], [236, 174],+ [236, 198], [198, 134], [134, 236], [215, 177], [177, 58], [58, 215],+ [156, 143], [143, 124], [124, 156], [25, 110], [110, 7], [7, 25],+ [31, 228], [228, 25], [25, 31], [264, 356], [356, 368], [368, 264],+ [0, 11], [11, 267], [267, 0], [451, 452], [452, 349], [349, 451],+ [267, 302], [302, 269], [269, 267], [350, 357], [357, 277], [277, 350],+ [350, 452], [452, 357], [357, 350], [299, 333], [333, 297], [297, 299],+ [396, 175], [175, 377], [377, 396], [280, 347], [347, 330], [330, 280],+ [269, 303], [303, 270], [270, 269], [151, 9], [9, 337], [337, 151],+ [344, 278], [278, 360], [360, 344], [424, 418], [418, 431], [431, 424],+ [270, 304], [304, 409], [409, 270], [272, 310], [310, 407], [407, 272],+ [322, 270], [270, 410], [410, 322], [449, 450], [450, 347], [347, 449],+ [432, 422], [422, 434], [434, 432], [18, 313], [313, 17], [17, 18],+ [291, 306], [306, 375], [375, 291], [259, 387], [387, 260], [260, 259],+ [424, 335], [335, 418], [418, 424], [434, 364], [364, 416], [416, 434],+ [391, 423], [423, 327], [327, 391], [301, 251], [251, 298], [298, 301],+ [275, 281], [281, 4], [4, 275], [254, 373], [373, 253], [253, 254],+ [375, 307], [307, 321], [321, 375], [280, 425], [425, 411], [411, 280],+ [200, 421], [421, 18], [18, 200], [335, 321], [321, 406], [406, 335],+ [321, 320], [320, 405], [405, 321], [314, 315], [315, 17], [17, 314],+ [423, 426], [426, 266], [266, 423], [396, 377], [377, 369], [369, 396],+ [270, 322], [322, 269], [269, 270], [413, 417], [417, 464], [464, 413],+ [385, 386], [386, 258], [258, 385], [248, 456], [456, 419], [419, 248],+ [298, 284], [284, 333], [333, 298], [168, 417], [417, 8], [8, 168],+ [448, 346], [346, 261], [261, 448], [417, 413], [413, 285], [285, 417],+ [326, 327], [327, 328], [328, 326], [277, 355], [355, 329], [329, 277],+ [309, 392], [392, 438], [438, 309], [381, 382], [382, 256], [256, 381],+ [279, 429], [429, 360], [360, 279], [365, 364], [364, 379], [379, 365],+ [355, 277], [277, 437], [437, 355], [282, 443], [443, 283], [283, 282],+ [281, 275], [275, 363], [363, 281], [395, 431], [431, 369], [369, 395],+ [299, 297], [297, 337], [337, 299], [335, 273], [273, 321], [321, 335],+ [348, 450], [450, 349], [349, 348], [359, 446], [446, 467], [467, 359],+ [283, 293], [293, 282], [282, 283], [250, 458], [458, 462], [462, 250],+ [300, 276], [276, 383], [383, 300], [292, 308], [308, 325], [325, 292],+ [283, 276], [276, 293], [293, 283], [264, 372], [372, 447], [447, 264],+ [346, 352], [352, 340], [340, 346], [354, 274], [274, 19], [19, 354],+ [363, 456], [456, 281], [281, 363], [426, 436], [436, 425], [425, 426],+ [380, 381], [381, 252], [252, 380], [267, 269], [269, 393], [393, 267],+ [421, 200], [200, 428], [428, 421], [371, 266], [266, 329], [329, 371],+ [432, 287], [287, 422], [422, 432], [290, 250], [250, 328], [328, 290],+ [385, 258], [258, 384], [384, 385], [446, 265], [265, 342], [342, 446],+ [386, 387], [387, 257], [257, 386], [422, 424], [424, 430], [430, 422],+ [445, 342], [342, 276], [276, 445], [422, 273], [273, 424], [424, 422],+ [306, 292], [292, 307], [307, 306], [352, 366], [366, 345], [345, 352],+ [268, 271], [271, 302], [302, 268], [358, 423], [423, 371], [371, 358],+ [327, 294], [294, 460], [460, 327], [331, 279], [279, 294], [294, 331],+ [303, 271], [271, 304], [304, 303], [436, 432], [432, 427], [427, 436],+ [304, 272], [272, 408], [408, 304], [395, 394], [394, 431], [431, 395],+ [378, 395], [395, 400], [400, 378], [296, 334], [334, 299], [299, 296],+ [6, 351], [351, 168], [168, 6], [376, 352], [352, 411], [411, 376],+ [307, 325], [325, 320], [320, 307], [285, 295], [295, 336], [336, 285],+ [320, 319], [319, 404], [404, 320], [329, 330], [330, 349], [349, 329],+ [334, 293], [293, 333], [333, 334], [366, 323], [323, 447], [447, 366],+ [316, 15], [15, 315], [315, 316], [331, 358], [358, 279], [279, 331],+ [317, 14], [14, 316], [316, 317], [8, 285], [285, 9], [9, 8],+ [277, 329], [329, 350], [350, 277], [253, 374], [374, 252], [252, 253],+ [319, 318], [318, 403], [403, 319], [351, 6], [6, 419], [419, 351],+ [324, 318], [318, 325], [325, 324], [397, 367], [367, 365], [365, 397],+ [288, 435], [435, 397], [397, 288], [278, 344], [344, 439], [439, 278],+ [310, 272], [272, 311], [311, 310], [248, 195], [195, 281], [281, 248],+ [375, 273], [273, 291], [291, 375], [175, 396], [396, 199], [199, 175],+ [312, 311], [311, 268], [268, 312], [276, 283], [283, 445], [445, 276],+ [390, 373], [373, 339], [339, 390], [295, 282], [282, 296], [296, 295],+ [448, 449], [449, 346], [346, 448], [356, 264], [264, 454], [454, 356],+ [337, 336], [336, 299], [299, 337], [337, 338], [338, 151], [151, 337],+ [294, 278], [278, 455], [455, 294], [308, 292], [292, 415], [415, 308],+ [429, 358], [358, 355], [355, 429], [265, 340], [340, 372], [372, 265],+ [352, 346], [346, 280], [280, 352], [295, 442], [442, 282], [282, 295],+ [354, 19], [19, 370], [370, 354], [285, 441], [441, 295], [295, 285],+ [195, 248], [248, 197], [197, 195], [457, 440], [440, 274], [274, 457],+ [301, 300], [300, 368], [368, 301], [417, 351], [351, 465], [465, 417],+ [251, 301], [301, 389], [389, 251], [394, 395], [395, 379], [379, 394],+ [399, 412], [412, 419], [419, 399], [410, 436], [436, 322], [322, 410],+ [326, 2], [2, 393], [393, 326], [354, 370], [370, 461], [461, 354],+ [393, 164], [164, 267], [267, 393], [268, 302], [302, 12], [12, 268],+ [312, 268], [268, 13], [13, 312], [298, 293], [293, 301], [301, 298],+ [265, 446], [446, 340], [340, 265], [280, 330], [330, 425], [425, 280],+ [322, 426], [426, 391], [391, 322], [420, 429], [429, 437], [437, 420],+ [393, 391], [391, 326], [326, 393], [344, 440], [440, 438], [438, 344],+ [458, 459], [459, 461], [461, 458], [364, 434], [434, 394], [394, 364],+ [428, 396], [396, 262], [262, 428], [274, 354], [354, 457], [457, 274],+ [317, 316], [316, 402], [402, 317], [316, 315], [315, 403], [403, 316],+ [315, 314], [314, 404], [404, 315], [314, 313], [313, 405], [405, 314],+ [313, 421], [421, 406], [406, 313], [323, 366], [366, 361], [361, 323],+ [292, 306], [306, 407], [407, 292], [306, 291], [291, 408], [408, 306],+ [291, 287], [287, 409], [409, 291], [287, 432], [432, 410], [410, 287],+ [427, 434], [434, 411], [411, 427], [372, 264], [264, 383], [383, 372],+ [459, 309], [309, 457], [457, 459], [366, 352], [352, 401], [401, 366],+ [1, 274], [274, 4], [4, 1], [418, 421], [421, 262], [262, 418],+ [331, 294], [294, 358], [358, 331], [435, 433], [433, 367], [367, 435],+ [392, 289], [289, 439], [439, 392], [328, 462], [462, 326], [326, 328],+ [94, 2], [2, 370], [370, 94], [289, 305], [305, 455], [455, 289],+ [339, 254], [254, 448], [448, 339], [359, 255], [255, 446], [446, 359],+ [254, 253], [253, 449], [449, 254], [253, 252], [252, 450], [450, 253],+ [252, 256], [256, 451], [451, 252], [256, 341], [341, 452], [452, 256],+ [414, 413], [413, 463], [463, 414], [286, 441], [441, 414], [414, 286],+ [286, 258], [258, 441], [441, 286], [258, 257], [257, 442], [442, 258],+ [257, 259], [259, 443], [443, 257], [259, 260], [260, 444], [444, 259],+ [260, 467], [467, 445], [445, 260], [309, 459], [459, 250], [250, 309],+ [305, 289], [289, 290], [290, 305], [305, 290], [290, 460], [460, 305],+ [401, 376], [376, 435], [435, 401], [309, 250], [250, 392], [392, 309],+ [376, 411], [411, 433], [433, 376], [453, 341], [341, 464], [464, 453],+ [357, 453], [453, 465], [465, 357], [343, 357], [357, 412], [412, 343],+ [437, 343], [343, 399], [399, 437], [344, 360], [360, 440], [440, 344],+ [420, 437], [437, 456], [456, 420], [360, 420], [420, 363], [363, 360],+ [361, 401], [401, 288], [288, 361], [265, 372], [372, 353], [353, 265],+ [390, 339], [339, 249], [249, 390], [339, 448], [448, 255], [255, 339],+]+# fmt: ondiff --git a/uniface/landmark/base.py b/uniface/landmark/base.pyindex 4498ddb..4d844ff 100644--- a/uniface/landmark/base.py+++ b/uniface/landmark/base.py@@ -8,14 +8,11 @@ import numpy as npclass BaseLandmarker(ABC):- """- Abstract Base Class for all facial landmark models.- """+ """Abstract Base Class for all facial landmark models."""@abstractmethoddef get_landmarks(self, image: np.ndarray, bbox: np.ndarray) -> np.ndarray:- """- Predicts facial landmarks for a given face bounding box.+ """Predicts facial landmarks for a given face bounding box.This method defines the standard interface for all landmark predictors.It takes a full image and a bounding box for a single face and returnsdiff --git a/uniface/landmark/facemesh.py b/uniface/landmark/facemesh.pynew file mode 100644index 0000000..3add1af--- /dev/null+++ b/uniface/landmark/facemesh.py@@ -0,0 +1,335 @@+# Copyright 2025-2026 Yakhyokhuja Valikhujaev+# Author: Yakhyokhuja Valikhujaev+# GitHub: https://github.com/yakhyo+++from __future__ import annotations++from typing import TYPE_CHECKING++import cv2+import numpy as np++from uniface.common import validate_image+from uniface.constants import FaceMeshWeights+from uniface.log import Logger+from uniface.model_store import verify_model_weights+from uniface.onnx_utils import create_onnx_session+from uniface.types import FaceMeshResult++from .base import BaseLandmarker++if TYPE_CHECKING:+ from uniface.types import Face++__all__ = ['FaceMesh', 'roi_from_box', 'warp_roi']++# MediaPipe's detection_to_roi expands the detector box by 1.5x; as a per-side+# fraction of the box that is 0.25.+_DEFAULT_MARGIN = 0.25++#: An ROI is (center_x, center_y, side, angle_degrees) in full-image coordinates.+Roi = tuple[float, float, float, float]+++def roi_from_box(+ bbox: np.ndarray,+ keypoints: np.ndarray | None = None,+ margin: float = _DEFAULT_MARGIN,+) -> Roi:+ """Build a Face Mesh ROI from a detector box, following MediaPipe's rule.++ MediaPipe's `detection_to_roi` produces a *square* region, the long side of the box+ scaled, rotated so the eye line is horizontal. Only rows 0 and 1 of `keypoints` are+ read: those are the eyes in both the 5-point alignment layout and BlazeFace's+ 6-point layout, so landmarks from any UniFace detector work here.++ Args:+ bbox: Bounding box as [x1, y1, x2, y2].+ keypoints: Optional landmarks with shape (K, 2), K >= 2, whose first two+ rows are the eyes. They set the ROI rotation (roll). Without them the+ ROI is axis-aligned, which degrades the mesh on tilted heads.+ margin: Fraction of the box side to expand by on each side. The default+ 0.25 reproduces MediaPipe's 1.5x scale.++ Returns:+ A square, optionally rotated ROI as (center_x, center_y, side, angle).++ Raises:+ ValueError: If fewer than 2 keypoints are given.+ """+ x1, y1, x2, y2 = (float(v) for v in np.asarray(bbox).ravel()[:4])+ side = (1.0 + 2.0 * margin) * max(x2 - x1, y2 - y1)++ angle = 0.0+ if keypoints is not None:+ points = np.asarray(keypoints, dtype=np.float64)+ if points.shape[0] < 2:+ raise ValueError(f'roi_from_box needs at least 2 keypoints (the eyes), got {points.shape[0]}')+ dx, dy = (float(v) for v in points[1] - points[0])+ angle = float(np.degrees(np.arctan2(dy, dx)))++ return (x1 + x2) / 2.0, (y1 + y2) / 2.0, side, angle+++def warp_roi(image: np.ndarray, roi: Roi, size: int) -> tuple[np.ndarray, np.ndarray]:+ """Sample a rotated square ROI directly at the model's input resolution.++ A single bilinear resampling straight to the model size, mirroring MediaPipe's+ ImageToTensorCalculator; warp-then-resize would interpolate twice and quantize the+ crop side to whole pixels. Regions outside the image are zero-padded.++ Args:+ image: Full BGR image with shape (H, W, 3).+ roi: The (center_x, center_y, side, angle) region to cut.+ size: Output edge length in pixels; the model's input resolution.++ Returns:+ A tuple of the (size, size, 3) crop and the inverse 2x3 affine mapping+ crop-pixel coordinates back to full-image coordinates.+ """+ center_x, center_y, side, angle = roi+ matrix = cv2.getRotationMatrix2D((center_x, center_y), angle, size / side)+ matrix[0, 2] += size / 2.0 - center_x+ matrix[1, 2] += size / 2.0 - center_y++ crop = cv2.warpAffine(image, matrix, (size, size))+ return crop, cv2.invertAffineTransform(matrix)+++class FaceMesh(BaseLandmarker):+ """MediaPipe dense 3D face landmarks: 468 points, or 478 with irises.++ Paper: https://arxiv.org/abs/1907.06724+ Code: https://github.com/google-ai-edge/mediapipe++ Detector-agnostic. The crop follows MediaPipe's ROI recipe, a square region at 1.5x+ the detector box rotated so the eye line is horizontal, and the model runs once per+ face, matching MediaPipe's static-image flow (`static_image_mode=True`). Video-mode+ ROI-from-previous-frame tracking is not reproduced; `roi_from_box` and `warp_roi`+ are public so it can be built on top.++ Args:+ model_name (FaceMeshWeights): Which model to load. `V1_468` (the default) is the+ classic 468-point Face Mesh at 192x192; `V2_478` is MediaPipe's Face+ Landmarker at 256x256, which appends ten iris points to the same mesh for+ roughly 3x the compute.+ providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detects+ the best available provider. Example: ['CPUExecutionProvider'] to force CPU.++ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.++ Example:+ >>> from uniface import SCRFD, FaceMesh+ >>> from uniface.constants import FaceMeshWeights+ >>>+ >>> detector, mesher = SCRFD(), FaceMesh()+ >>> faces = detector.detect(image)+ >>> results = mesher.predict(image, faces)+ >>> results[0].landmarks.shape+ (468, 3)+ >>>+ >>> # Or one face at a time, 2D only, like any other landmarker+ >>> mesher.get_landmarks(image, faces[0].bbox).shape+ (468, 2)+ >>>+ >>> # The 478-point model appends irises; everything else is unchanged+ >>> from uniface.landmark import IRIS_LEFT+ >>> iris_mesher = FaceMesh(model_name=FaceMeshWeights.V2_478)+ >>> iris_mesher.predict(image, faces)[0].landmarks[IRIS_LEFT].shape+ (5, 3)+ """++ def __init__(+ self,+ *,+ model_name: FaceMeshWeights = FaceMeshWeights.V1_468,+ providers: list[str] | None = None,+ ) -> None:+ Logger.info(f'Initializing FaceMesh with model={model_name}')+ self.providers = providers+ self.model_path = verify_model_weights(model_name)+ self._initialize_model()++ def _initialize_model(self) -> None:+ """Initialize the ONNX session and read the model's geometry.++ Landmark count and input resolution come from the graph rather than being+ hardcoded, so a variant with a different point count (e.g. MediaPipe's+ 478-point iris model) needs no code change.++ Raises:+ RuntimeError: If the model fails to load or initialize.+ """+ try:+ self.session = create_onnx_session(self.model_path, providers=self.providers)++ input_meta = self.session.get_inputs()[0]+ self.input_name = input_meta.name+ self.input_size = int(input_meta.shape[2])++ outputs = self.session.get_outputs()+ self.output_names = [o.name for o in outputs]+ self._num_landmarks = int(outputs[0].shape[1])++ Logger.info(f'Model initialized with {self._num_landmarks} landmarks ({self.input_size}px input)')++ except Exception as e:+ Logger.error(f"Failed to load FaceMesh model from '{self.model_path}'", exc_info=True)+ raise RuntimeError(f'Failed to initialize FaceMesh model: {e}') from e++ @property+ def num_landmarks(self) -> int:+ """Number of landmarks this model predicts, read from the ONNX graph."""+ return self._num_landmarks++ def preprocess(self, crop: np.ndarray) -> np.ndarray:+ """Convert a BGR crop into a CHW float32 slice in [0, 1], RGB order.++ Args:+ crop: Face crop with shape (input_size, input_size, 3) in BGR.++ Returns:+ A (3, input_size, input_size) float32 array.+ """+ if crop.shape[:2] != (self.input_size, self.input_size):+ crop = cv2.resize(crop, (self.input_size, self.input_size))+ rgb = crop[:, :, ::-1].astype(np.float32) / 255.0+ return np.transpose(rgb, (2, 0, 1))++ def postprocess(+ self,+ landmarks: np.ndarray,+ logits: np.ndarray,+ rois: list[Roi],+ inverses: list[np.ndarray],+ ) -> tuple[np.ndarray, np.ndarray]:+ """Map raw crop-space predictions back to full-image coordinates.++ Args:+ landmarks: Raw (N, num_landmarks, 3) output in crop pixels.+ logits: Raw (N, 1) presence output. These are logits, not+ probabilities, and are sigmoided here.+ rois: The ROI used for each face, in order.+ inverses: The inverse affine for each face, from `warp_roi`.++ Returns:+ A tuple of (N, num_landmarks, 3) landmarks in full-image pixels and+ (N,) presence scores in [0, 1].+ """+ points = landmarks.astype(np.float64)+ for idx, (roi, inverse) in enumerate(zip(rois, inverses, strict=True)):+ points[idx, :, :2] = points[idx, :, :2] @ inverse[:, :2].T + inverse[:, 2]+ # Put z on the same pixel scale as x/y.+ points[idx, :, 2] *= roi[2] / self.input_size++ scores = 1.0 / (1.0 + np.exp(-logits.ravel().astype(np.float64)))+ return points.astype(np.float32), scores.astype(np.float32)++ def _run_rois(self, image: np.ndarray, rois: list[Roi]) -> tuple[np.ndarray, np.ndarray]:+ """Warp, batch, and run every ROI through a single session call."""+ blobs, inverses = [], []+ for roi in rois:+ crop, inverse = warp_roi(image, roi, self.input_size)+ blobs.append(self.preprocess(crop))+ inverses.append(inverse)++ landmarks, logits = self.session.run(self.output_names, {self.input_name: np.stack(blobs)})+ return self.postprocess(landmarks, logits, rois, inverses)++ def predict(+ self,+ image: np.ndarray,+ faces: list[Face] | None = None,+ *,+ bboxes: list[np.ndarray] | np.ndarray | None = None,+ keypoints: list[np.ndarray] | np.ndarray | None = None,+ margin: float = _DEFAULT_MARGIN,+ ) -> list[FaceMeshResult]:+ """Predict dense landmarks for every face in an image.++ Accepts either `Face` objects from any detector, or raw boxes. With `Face`+ objects the ROI is roll-normalized automatically from each face's landmarks.+ All faces run in one session call.++ Args:+ image: Full BGR image with shape (H, W, 3).+ faces: Detected faces, e.g. from `SCRFD().detect(image)`.+ bboxes: One [x1, y1, x2, y2] per face. Mutually exclusive with `faces`.+ keypoints: Optional landmarks per face, shape (K, 2) each and aligned+ with `bboxes`, whose first two rows are the eyes.+ margin: Fraction of the box side to expand each crop by on each side.++ Returns:+ One `FaceMeshResult` per input face, in input order.++ Raises:+ ValueError: If the image is empty, not 3-channel BGR, or not uint8; if+ both or neither of `faces` and `bboxes` are given; or if `keypoints`+ and `bboxes` have different lengths.++ Example:+ >>> results = mesher.predict(image, detector.detect(image))+ >>> results = mesher.predict(image, bboxes=[[10, 20, 110, 140]])+ """+ # `preprocess` rescales by 255, so a float [0, 1] image would be divided twice+ # and yield garbage landmarks that `get_landmarks` returns without a score.+ validate_image(image)++ if (faces is None) == (bboxes is None):+ raise ValueError('Provide either faces or bboxes, not both')++ if faces is not None:+ bboxes = [f.bbox for f in faces]+ keypoints = [f.landmarks for f in faces]+ elif keypoints is not None and len(keypoints) != len(bboxes):+ raise ValueError(f'Got {len(bboxes)} boxes but {len(keypoints)} keypoint sets')++ if len(bboxes) == 0:+ return []++ rois = [+ roi_from_box(bbox, None if keypoints is None else keypoints[idx], margin) for idx, bbox in enumerate(bboxes)+ ]+ landmarks, scores = self._run_rois(image, rois)+ return [FaceMeshResult(landmarks=landmarks[i], score=float(scores[i])) for i in range(len(rois))]++ def get_landmarks(+ self,+ image: np.ndarray,+ bbox: np.ndarray,+ keypoints: np.ndarray | None = None,+ ) -> np.ndarray:+ """Predict dense landmarks for a single face, without depth.++ Satisfies the `BaseLandmarker` interface, so this is a drop-in for `Landmark106`+ and `PIPNet`. Use `predict` when you need depth, the presence score, or more+ than one face at a time.++ Args:+ image: Full BGR image in BGR format.+ bbox: Face bounding box [x1, y1, x2, y2].+ keypoints: Optional landmarks whose first two rows are the eyes,+ used to roll-normalize the crop.++ Returns:+ Landmark points with shape (num_landmarks, 2), float32, in the+ original image's pixel coordinates.+ """+ results = self.predict(image, bboxes=[bbox], keypoints=None if keypoints is None else [keypoints])+ return results[0].points_2d++ def __call__(+ self,+ image: np.ndarray,+ bbox: np.ndarray,+ keypoints: np.ndarray | None = None,+ ) -> np.ndarray:+ """Callable shortcut for `get_landmarks`.++ Overrides `BaseLandmarker.__call__`, which forwards only (image, bbox) and+ would silently drop the roll normalization.+ """+ return self.get_landmarks(image, bbox, keypoints)diff --git a/uniface/landmark/models.py b/uniface/landmark/models.pyindex bc0a368..91dcc70 100644--- a/uniface/landmark/models.py+++ b/uniface/landmark/models.py@@ -29,11 +29,13 @@ class Landmark106(BaseLandmarker):Args:model_name (LandmarkWeights): The enum specifying the landmark model to load.Defaults to `LandmarkWeights.DEFAULT`.- input_size (Tuple[int, int]): The resolution (width, height) for the model's- input. Defaults to (192, 192).providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Example:>>> # Assume 'image' is a loaded image and 'bbox' is a face bounding box>>> # bbox = [x1, y1, x2, y2]@@ -46,12 +48,11 @@ class Landmark106(BaseLandmarker):def __init__(self,+ *,model_name: LandmarkWeights = LandmarkWeights.DEFAULT,- input_size: tuple[int, int] = (192, 192),providers: list[str] | None = None,) -> None:- Logger.info(f'Initializing Facial Landmark with model={model_name}, input_size={input_size}')- self.input_size = input_size+ Logger.info(f'Initializing Facial Landmark with model={model_name}')self.input_std = 1.0self.input_mean = 0.0self.providers = providers@@ -59,8 +60,7 @@ class Landmark106(BaseLandmarker):self._initialize_model()def _initialize_model(self) -> None:- """- Initialize the ONNX model from the stored model path.+ """Initialize the ONNX model from the stored model path.Raises:RuntimeError: If the model fails to load or initialize.@@ -100,7 +100,7 @@ class Landmark106(BaseLandmarker):bbox (np.ndarray): The bounding box of the face [x1, y1, x2, y2].Returns:- Tuple[np.ndarray, np.ndarray]: A tuple containing:+ tuple[np.ndarray, np.ndarray]: A tuple containing:- The preprocessed image blob ready for inference.- The affine transformation matrix used for alignment."""diff --git a/uniface/landmark/pipnet.py b/uniface/landmark/pipnet.pyindex 559fc5e..1bf51c6 100644--- a/uniface/landmark/pipnet.py+++ b/uniface/landmark/pipnet.py@@ -39,10 +39,14 @@ class PIPNet(BaseLandmarker):Args:model_name (PIPNetWeights): Which PIPNet ONNX model to load.- Defaults to ``PIPNetWeights.WFLW_98``.+ Defaults to `PIPNetWeights.WFLW_98`.providers (list[str] | None): ONNX Runtime execution providers. If None,auto-detects the best available provider.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Example:>>> from uniface.landmark import PIPNet>>> from uniface.constants import PIPNetWeights@@ -60,6 +64,7 @@ class PIPNet(BaseLandmarker):def __init__(self,+ *,model_name: PIPNetWeights = PIPNetWeights.WFLW_98,providers: list[str] | None = None,) -> None:@@ -114,19 +119,19 @@ class PIPNet(BaseLandmarker):def preprocess(self, image: np.ndarray, bbox: np.ndarray) -> tuple[np.ndarray, tuple[int, int, int, int]]:"""Crop the face region and produce the network input blob.- The crop follows the upstream PIPNet convention: pad ``+10%`` on the- left, right, and bottom of the bbox and ``-10%`` on the top, then+ The crop follows the upstream PIPNet convention: pad `+10%` on the+ left, right, and bottom of the bbox and `-10%` on the top, thenclamp to the image bounds. The crop is resized to the model's inputresolution, BGR->RGB converted, and ImageNet-normalized.Args:- image (np.ndarray): Full source image in BGR format, ``(H, W, 3)``.- bbox (np.ndarray): Face bounding box ``[x1, y1, x2, y2]``.+ image (np.ndarray): Full source image in BGR format, `(H, W, 3)`.+ bbox (np.ndarray): Face bounding box `[x1, y1, x2, y2]`.Returns:Tuple of:- - The preprocessed ``(1, 3, H, W)`` float32 blob.- - The crop metadata ``(x1, y1, crop_w, crop_h)`` used to+ - The preprocessed `(1, 3, H, W)` float32 blob.+ - The crop metadata `(x1, y1, crop_w, crop_h)` used torescale predictions back to original image coordinates."""crop, crop_meta = self._crop_face(image, bbox)@@ -166,18 +171,18 @@ class PIPNet(BaseLandmarker):"""Decode raw network outputs into original-image landmark coordinates.Combines each landmark's own (cls, offset) prediction with the- predictions made about it by its ``num_nb`` nearest meanface neighbors,+ predictions made about it by its `num_nb` nearest meanface neighbors,then maps the normalized result back to the original image using thecrop metadata.Args:outputs (tuple): The five raw ONNX outputs in order- ``(cls_map, offset_x, offset_y, nb_x, nb_y)``.- crop_meta (tuple): The ``(x1, y1, crop_w, crop_h)`` returned by- :meth:`preprocess`.+ `(cls_map, offset_x, offset_y, nb_x, nb_y)`.+ crop_meta (tuple): The `(x1, y1, crop_w, crop_h)` returned by+ `preprocess`.Returns:- np.ndarray: ``(num_lms, 2)`` float32 landmarks in original image space.+ np.ndarray: `(num_lms, 2)` float32 landmarks in original image space."""cls_map, offset_x, offset_y, nb_x, nb_y = outputsn = self.num_lms@@ -229,10 +234,10 @@ class PIPNet(BaseLandmarker):Args:image (np.ndarray): Full source image in BGR format.- bbox (np.ndarray): Face bounding box ``[x1, y1, x2, y2]``.+ bbox (np.ndarray): Face bounding box `[x1, y1, x2, y2]`.Returns:- np.ndarray: Landmark points as a ``(num_lms, 2)`` float32 array+ np.ndarray: Landmark points as a `(num_lms, 2)` float32 arrayin the original image's pixel coordinates."""blob, crop_meta = self.preprocess(image, bbox)diff --git a/uniface/matting/__init__.py b/uniface/matting/__init__.pyindex 2088b1a..50dc1b8 100644--- a/uniface/matting/__init__.py+++ b/uniface/matting/__init__.py@@ -4,61 +4,7 @@from __future__ import annotations-from typing_extensions import deprecated--from uniface.constants import MODNetWeights-from .base import BaseMattingfrom .modnet import MODNet-__all__ = ['BaseMatting', 'MODNet', 'create_matting_model']---@deprecated(- 'create_matting_model() is deprecated and will be removed in uniface 4.0. '- 'Instantiate MODNet directly, e.g. '- '`from uniface.matting import MODNet; MODNet(model_name=...)`.'-)-def create_matting_model(- model_name: str | MODNetWeights = MODNetWeights.PHOTOGRAPHIC,- **kwargs,-) -> BaseMatting:- """Factory function to create a portrait matting model.-- .. deprecated:: 3.7.0- Use ``MODNet`` directly. This factory will be removed in uniface 4.0.-- Args:- model_name: Model to create. Options: ``MODNetWeights.PHOTOGRAPHIC``- (high-quality photos), ``MODNetWeights.WEBCAM`` (real-time webcam).- Also accepts string values like ``"modnet_photographic"`` or- ``"modnet_webcam"``.- **kwargs: Additional arguments passed to the model constructor- (e.g. ``input_size``, ``providers``).-- Returns:- An instance of the requested matting model.-- Raises:- ValueError: If the model_name is not recognized.-- Example:- >>> from uniface.matting import MODNet- >>> matting = MODNet()- >>> matte = matting.predict(image)- """- if isinstance(model_name, MODNetWeights):- return MODNet(model_name=model_name, **kwargs)-- if isinstance(model_name, str):- try:- weights = MODNetWeights(model_name)- return MODNet(model_name=weights, **kwargs)- except ValueError:- pass-- valid_models = [m.value for m in MODNetWeights]- raise ValueError(f"Unknown matting model: '{model_name}'. Valid options are: {', '.join(valid_models)}")-- valid_models = [m.value for m in MODNetWeights]- raise ValueError(f"Unknown matting model: '{model_name}'. Valid options are: {', '.join(valid_models)}")+__all__ = ['BaseMatting', 'MODNet']diff --git a/uniface/matting/base.py b/uniface/matting/base.pyindex d196210..64d477d 100644--- a/uniface/matting/base.py+++ b/uniface/matting/base.py@@ -17,7 +17,7 @@ class BaseMatting(ABC):alpha matte (float32 in [0, 1]) separating foreground from background.Subclasses must implement the full pipeline: model initialization,- preprocessing, postprocessing, and the ``predict`` entry point.+ preprocessing, postprocessing, and the `predict` entry point."""@abstractmethod@@ -26,10 +26,8 @@ class BaseMatting(ABC):This method should handle loading model weights, creating theinference session (e.g., ONNX Runtime), and any necessary- setup procedures to prepare the model for prediction.-- Raises:- RuntimeError: If the model fails to load or initialize.+ setup procedures to prepare the model for prediction. Implementations+ raise RuntimeError if the model fails to load or initialize."""raise NotImplementedError('Subclasses must implement the _initialize_model method.')@@ -38,10 +36,10 @@ class BaseMatting(ABC):"""Preprocess the input image for model inference.Args:- image: An image in BGR format with shape ``(H, W, 3)``.+ image: An image in BGR format with shape `(H, W, 3)`.Returns:- A tuple of ``(tensor, orig_h, orig_w)`` where *tensor* is the+ A tuple of `(tensor, orig_h, orig_w)` where *tensor* is thepreprocessed image ready for inference."""raise NotImplementedError('Subclasses must implement the preprocess method.')@@ -52,10 +50,10 @@ class BaseMatting(ABC):Args:outputs: Raw outputs from the model inference.- original_size: Original image size as ``(width, height)``.+ original_size: Original image size as `(width, height)`.Returns:- Alpha matte with shape ``(H, W)`` and values in ``[0, 1]``.+ Alpha matte with shape `(H, W)` and values in `[0, 1]`."""raise NotImplementedError('Subclasses must implement the postprocess method.')@@ -64,25 +62,25 @@ class BaseMatting(ABC):"""Run end-to-end matting on an image.Args:- image: An image in BGR format with shape ``(H, W, 3)``.+ image: An image in BGR format with shape `(H, W, 3)`.Returns:- Alpha matte with shape ``(H, W)``, float32 in ``[0, 1]``.+ Alpha matte with shape `(H, W)`, float32 in `[0, 1]`.Example:- >>> matting = create_matting_model()+ >>> matting = MODNet()>>> matte = matting.predict(image)>>> print(f'Matte shape: {matte.shape}, dtype: {matte.dtype}')"""raise NotImplementedError('Subclasses must implement the predict method.')def __call__(self, image: np.ndarray) -> np.ndarray:- """Callable shortcut for :meth:`predict`.+ """Callable shortcut for `predict`.Args:- image: An image in BGR format with shape ``(H, W, 3)``.+ image: An image in BGR format with shape `(H, W, 3)`.Returns:- Alpha matte with shape ``(H, W)``, float32 in ``[0, 1]``.+ Alpha matte with shape `(H, W)`, float32 in `[0, 1]`."""return self.predict(image)diff --git a/uniface/matting/modnet.py b/uniface/matting/modnet.pyindex aa69e48..6a4f911 100644--- a/uniface/matting/modnet.py+++ b/uniface/matting/modnet.py@@ -28,8 +28,12 @@ class MODNet(BaseMatting):Two pretrained variants are available:- - ``PHOTOGRAPHIC``: optimized for high-quality portrait photos.- - ``WEBCAM``: optimized for real-time webcam feeds.+ - `PHOTOGRAPHIC`: optimized for high-quality portrait photos.+ - `WEBCAM`: optimized for real-time webcam feeds.++ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.Reference:Ke et al., "MODNet: Real-Time Trimap-Free Portrait Matting via@@ -38,12 +42,12 @@ class MODNet(BaseMatting):Args:model_name: The enum specifying the MODNet variant to load.- Defaults to ``MODNetWeights.PHOTOGRAPHIC``.+ Defaults to `MODNetWeights.PHOTOGRAPHIC`.input_size: Target size for the shorter side during preprocessing.The image is resized so its shorter side equals this value(aspect ratio preserved), then both dimensions are floored tomultiples of 32. Defaults to 512.- providers: ONNX Runtime execution providers. If ``None``, auto-detects+ providers: ONNX Runtime execution providers. If `None`, auto-detectsthe best available provider.Attributes:@@ -64,6 +68,7 @@ class MODNet(BaseMatting):def __init__(self,+ *,model_name: MODNetWeights = MODNetWeights.PHOTOGRAPHIC,input_size: int = 512,providers: list[str] | None = None,@@ -101,15 +106,15 @@ class MODNet(BaseMatting):"""Preprocess a BGR image for MODNet inference.The image is converted to RGB, resized so its shorter side matches- ``input_size`` (aspect ratio preserved), floored to multiples of 32,- and normalized to ``[-1, 1]``.+ `input_size` (aspect ratio preserved), floored to multiples of 32,+ and normalized to `[-1, 1]`.Args:- image: Input image in BGR format with shape ``(H, W, 3)``.+ image: Input image in BGR format with shape `(H, W, 3)`.Returns:- A tuple of ``(tensor, orig_h, orig_w)`` where *tensor* has shape- ``(1, 3, H', W')`` in float32.+ A tuple of `(tensor, orig_h, orig_w)` where *tensor* has shape+ `(1, 3, H', W')` in float32."""orig_h, orig_w = image.shape[:2]rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)@@ -138,11 +143,11 @@ class MODNet(BaseMatting):"""Postprocess raw model output into an alpha matte.Args:- outputs: Raw ONNX output with shape ``(1, 1, H', W')``.- original_size: Target size as ``(width, height)``.+ outputs: Raw ONNX output with shape `(1, 1, H', W')`.+ original_size: Target size as `(width, height)`.Returns:- Alpha matte with shape ``(H, W)``, float32 in ``[0, 1]``.+ Alpha matte with shape `(H, W)`, float32 in `[0, 1]`."""matte = outputs[0, 0]matte = cv2.resize(matte, original_size, interpolation=cv2.INTER_AREA)@@ -152,10 +157,10 @@ class MODNet(BaseMatting):"""Run portrait matting on a BGR image.Args:- image: Input image in BGR format with shape ``(H, W, 3)``.+ image: Input image in BGR format with shape `(H, W, 3)`.Returns:- Alpha matte with shape ``(H, W)``, float32 in ``[0, 1]``.+ Alpha matte with shape `(H, W)`, float32 in `[0, 1]`."""tensor, orig_h, orig_w = self.preprocess(image)outputs = self.session.run(self.output_names, {self.input_name: tensor})diff --git a/uniface/model_store.py b/uniface/model_store.pyindex d7ffd83..1530258 100644--- a/uniface/model_store.py+++ b/uniface/model_store.py@@ -27,8 +27,8 @@ def get_cache_dir() -> str:"""Get the current model cache directory path.Resolution order:- 1. ``UNIFACE_CACHE_DIR`` environment variable (set via :func:`set_cache_dir` or directly).- 2. Default: ``~/.uniface/models``.+ 1. `UNIFACE_CACHE_DIR` environment variable (set via `set_cache_dir` or directly).+ 2. Default: `~/.uniface/models`.Returns:Absolute, expanded path to the cache directory.@@ -44,7 +44,7 @@ def get_cache_dir() -> str:def set_cache_dir(path: str) -> None:"""Set the model cache directory.- This sets the ``UNIFACE_CACHE_DIR`` environment variable so that all+ This sets the `UNIFACE_CACHE_DIR` environment variable so that allsubsequent model downloads and lookups use the new path.Args:@@ -60,6 +60,22 @@ def set_cache_dir(path: str) -> None:Logger.info(f'Cache directory set to: {path}')+def _mirror_url(model_name: Enum, url: str) -> str:+ """Build the Hugging Face mirror URL for a model.++ Mirror files are keyed on the enum value, like the local cache, rather than on+ the primary URL's basename -- five basenames collide across the source repos.++ Args:+ model_name: Model weight identifier enum.+ url: Registered primary URL from `MODEL_REGISTRY`, used only for its extension.++ Returns:+ Download URL for the same weights on the Hugging Face mirror.+ """+ return f'{const.HF_MIRROR_URL}/{model_name.value}{os.path.splitext(url)[1]}'++def verify_model_weights(model_name: Enum,root: str | None = None,@@ -70,13 +86,15 @@ def verify_model_weights(Given a model identifier from an Enum class (e.g., `RetinaFaceWeights.MNET_V2`),this function checks if the corresponding weight file exists locally. If not,- it downloads the file from a predefined URL and verifies its integrity using- a SHA-256 hash.+ it downloads the file and verifies its integrity using a SHA-256 hash.++ Downloads try the registered GitHub Releases URL first, then the Hugging Face+ mirror, so a single unreachable host does not break model loading.Args:model_name: Model weight identifier enum (e.g., `RetinaFaceWeights.MNET_V2`).root: Directory to store or locate the model weights.- If None, uses the cache directory from :func:`get_cache_dir`.+ If None, uses the cache directory from `get_cache_dir`.timeout: Connection timeout in seconds. Defaults to 60.max_retries: Maximum number of download attempts. Defaults to 3.@@ -84,8 +102,9 @@ def verify_model_weights(Absolute path to the verified model weights file.Raises:- ValueError: If the model is unknown or SHA-256 verification fails.- ConnectionError: If downloading the file fails.+ ValueError: If the model is not present in `MODEL_REGISTRY`.+ ConnectionError: If every source fails, whether by network error or by+ SHA-256 mismatch.Example:>>> from uniface.constants import RetinaFaceWeights@@ -116,13 +135,32 @@ def verify_model_weights(os.remove(model_path)if not os.path.exists(model_path):- Logger.info(f"Downloading model '{model_name.value}' from {url}")- try:- download_file(url, model_path, expected_hash=expected_hash, timeout=timeout, max_retries=max_retries)+ sources = (('GH Releases', url), ('HF Mirror', _mirror_url(model_name, url)))+ last_error: Exception | None = None++ for index, (origin, source) in enumerate(sources):+ Logger.info(f"Downloading model '{model_name.value}' from {origin}: {source}")+ try:+ download_file(source, model_path, expected_hash=expected_hash, timeout=timeout, max_retries=max_retries)+ except ConnectionError as e:+ # Raised for hash mismatches too, so a corrupted source falls through.+ last_error = e+ if index + 1 < len(sources):+ Logger.warning(f"{origin} failed for '{model_name.value}' ({e}); trying {sources[index + 1][0]}.")+ continue++ if index:+ # The failure was reported at WARNING, so report the recovery there too --+ # otherwise the user is left looking at an unresolved warning.+ Logger.warning(f"Recovered '{model_name.value}' from {origin}.")Logger.info(f"Successfully downloaded '{model_name.value}' to {model_path}")- except Exception as e:- Logger.error(f"Failed to download model '{model_name.value}': {e}")- raise ConnectionError(f"Download failed for '{model_name.value}' after {max_retries} attempts") from e+ return model_path++ tried = ' and '.join(origin for origin, _ in sources)+ Logger.error(f"Failed to download '{model_name.value}' from {tried}: {last_error}")+ raise ConnectionError(+ f"Download failed for '{model_name.value}' from {tried}, {max_retries} attempts each"+ ) from last_errorreturn model_path@@ -137,7 +175,7 @@ def download_file("""Download a file with retries, streaming to a temp file and committing atomically.Bytes are written to a temp file, optionally hash-verified, then moved into- place with :func:`os.replace`, so ``dest_path`` is never left partial or corrupted.+ place with `os.replace`, so `dest_path` is never left partial or corrupted.Args:url: URL to download from.@@ -145,6 +183,11 @@ def download_file(expected_hash: Expected SHA-256 hash; if set, a mismatch triggers a retry.timeout: Connection timeout in seconds. Defaults to 60.max_retries: Maximum number of attempts. Defaults to 3.++ Raises:+ ConnectionError: If every attempt fails. A final-attempt hash mismatch is+ reported through this error too, as the underlying `ValueError` is+ retried internally and never propagates."""last_error = Nonedest_dir = os.path.dirname(dest_path) or '.'@@ -179,9 +222,11 @@ def download_file(os.replace(tmp_path, dest_path) # Atomic commitreturn # Successexcept (OSError, requests.RequestException, ValueError) as e:+ # Recoverable until the attempts run out, so this stays at INFO; the caller+ # decides how loudly to report the ConnectionError raised below.last_error = e- Logger.warning(f'Download attempt {attempt + 1} failed: {e}. Retrying...')if attempt < max_retries - 1:+ Logger.info(f'Attempt {attempt + 1}/{max_retries} failed for {url}: {e}. Retrying...')time.sleep(2**attempt) # Exponential backofffinally:if tmp_path and os.path.exists(tmp_path):@@ -213,8 +258,8 @@ def download_models(Args:model_names: List of model weight enum identifiers to download.max_workers: Maximum number of concurrent download threads. Defaults to- ``min(os.cpu_count() or 1, 8)`` (auto mode). Passing ``None`` or a- value ``< 1`` also selects auto mode and emits an info log line.+ `min(os.cpu_count() or 1, 8)` (auto mode). Passing `None` or a+ value `< 1` also selects auto mode and emits an info log line.timeout: Connection timeout in seconds. Defaults to 60.max_retries: Maximum number of attempts per model. Defaults to 3.@@ -222,11 +267,11 @@ def download_models(Mapping of each model enum to its local file path.Raises:- TypeError: If ``max_workers`` is a ``bool`` or a non-int / non-None+ TypeError: If `max_workers` is a `bool` or a non-int / non-Nonevalue.RuntimeError: If any model download or verification fails. The errormessage aggregates every failure into a single multi-line message- of the form ``"Failed to download N model(s):\\n<name>: <err>\\n..."``.+ of the form `"Failed to download N model(s):\\n<name>: <err>\\n..."`.Example:>>> from uniface import download_modelsdiff --git a/uniface/onnx_utils.py b/uniface/onnx_utils.pyindex 2af2b4e..2ef08fe 100644--- a/uniface/onnx_utils.py+++ b/uniface/onnx_utils.py@@ -102,7 +102,7 @@ def create_onnx_session(active_provider = session.get_providers()[0]Logger.debug(f'Session created with provider: {active_provider}')- # Show user-friendly message about which provider is being used+ # DEBUG level: only visible when the user opts in via enable_logging(logging.DEBUG)provider_names = {'CoreMLExecutionProvider': 'CoreML (Apple Silicon)','CUDAExecutionProvider': 'CUDA (NVIDIA GPU)',diff --git a/uniface/parsing/__init__.py b/uniface/parsing/__init__.pyindex 70ca200..d902cb1 100644--- a/uniface/parsing/__init__.py+++ b/uniface/parsing/__init__.py@@ -4,71 +4,8 @@from __future__ import annotations-from typing_extensions import deprecated--from uniface.constants import ParsingWeights, XSegWeights-from .base import BaseFaceParserfrom .bisenet import BiSeNetfrom .xseg import XSeg-__all__ = ['BaseFaceParser', 'BiSeNet', 'XSeg', 'create_face_parser']---@deprecated(- 'create_face_parser() is deprecated and will be removed in uniface 4.0. '- 'Instantiate the parser class directly, e.g. '- '`from uniface.parsing import BiSeNet; BiSeNet(model_name=...)`.'-)-def create_face_parser(- model_name: str | ParsingWeights | XSegWeights = ParsingWeights.RESNET18,- **kwargs,-) -> BaseFaceParser:- """Factory function to create a face parsing model.-- .. deprecated:: 3.7.0- Use the parser class directly (``BiSeNet``, ``XSeg``). This factory- will be removed in uniface 4.0.-- Args:- model_name: Model to create. Options: ParsingWeights.RESNET18/RESNET34 (BiSeNet),- XSegWeights.DEFAULT (XSeg, requires landmarks).- **kwargs: Additional arguments passed to the model constructor.-- Returns:- An instance of the requested face parsing model.-- Raises:- ValueError: If the model_name is not recognized.-- Example:- >>> from uniface.parsing import BiSeNet- >>> parser = BiSeNet(model_name=ParsingWeights.RESNET18)- >>> mask = parser.parse(face_crop)- """- # Handle XSegWeights- if isinstance(model_name, XSegWeights):- return XSeg(model_name=model_name, **kwargs)-- # Convert string to enum if necessary- if isinstance(model_name, str):- # Try XSegWeights first- try:- xseg_model = XSegWeights(model_name)- return XSeg(model_name=xseg_model, **kwargs)- except ValueError:- pass-- # Try ParsingWeights- try:- model_name = ParsingWeights(model_name)- except ValueError as e:- valid_parsing = [m.value for m in ParsingWeights]- valid_xseg = [m.value for m in XSegWeights]- valid_models = valid_parsing + valid_xseg- raise ValueError(- f"Unknown face parsing model: '{model_name}'. Valid options are: {', '.join(valid_models)}"- ) from e-- # BiSeNet models- return BiSeNet(model_name=model_name, **kwargs)+__all__ = ['BaseFaceParser', 'BiSeNet', 'XSeg']diff --git a/uniface/parsing/base.py b/uniface/parsing/base.pyindex 5cc7803..9638818 100644--- a/uniface/parsing/base.py+++ b/uniface/parsing/base.py@@ -16,10 +16,10 @@ class BaseFaceParser(ABC):ensuring consistency across different parsing methods. Face parsing segments a faceimage into semantic regions such as skin, eyes, nose, mouth, hair, etc.- Subclasses must define a ``mask_type`` class attribute to indicate output format:+ Subclasses must define a `mask_type` class attribute to indicate output format:- - ``"class_ids"``: uint8 mask with discrete class labels (e.g. BiSeNet: 0-18)- - ``"probability"``: float32 mask with continuous values in [0, 1] (e.g. XSeg)+ - `"class_ids"`: uint8 mask with discrete class labels (e.g. BiSeNet: 0-18)+ - `"probability"`: float32 mask with continuous values in [0, 1] (e.g. XSeg)Attributes:mask_type (str): Output format identifier. Must be set by subclasses.@@ -29,22 +29,18 @@ class BaseFaceParser(ABC):@abstractmethoddef _initialize_model(self) -> None:- """- Initialize the underlying model for inference.+ """Initialize the underlying model for inference.This method should handle loading model weights, creating theinference session (e.g., ONNX Runtime), and any necessary- setup procedures to prepare the model for prediction.-- Raises:- RuntimeError: If the model fails to load or initialize.+ setup procedures to prepare the model for prediction. Implementations+ raise RuntimeError if the model fails to load or initialize."""raise NotImplementedError('Subclasses must implement the _initialize_model method.')@abstractmethoddef preprocess(self, face_image: np.ndarray) -> np.ndarray:- """- Preprocess the input face image for model inference.+ """Preprocess the input face image for model inference.This method should take a raw face crop and convert it into the formatexpected by the model's inference engine (e.g., normalized tensor).@@ -61,15 +57,14 @@ class BaseFaceParser(ABC):@abstractmethoddef postprocess(self, outputs: np.ndarray, original_size: tuple[int, int]) -> np.ndarray:- """- Postprocess raw model outputs into a segmentation mask.+ """Postprocess raw model outputs into a segmentation mask.This method takes the raw output from the model's inference andconverts it into a segmentation mask at the original image size.Args:outputs (np.ndarray): Raw outputs from the model inference.- original_size (Tuple[int, int]): Original image size (width, height).+ original_size (tuple[int, int]): Original image size (width, height).Returns:np.ndarray: Segmentation mask with the same size as the original image.@@ -78,8 +73,7 @@ class BaseFaceParser(ABC):@abstractmethoddef parse(self, image: np.ndarray, *, landmarks: np.ndarray | None = None) -> np.ndarray:- """- Perform end-to-end face parsing on a face image.+ """Perform end-to-end face parsing on a face image.This method orchestrates the full pipeline: preprocessing the input,running inference, and postprocessing to return the segmentation mask.@@ -93,13 +87,13 @@ class BaseFaceParser(ABC):Returns:np.ndarray: Segmentation mask with the same size as input image.- Format depends on ``mask_type``:+ Format depends on `mask_type`:- - ``"class_ids"``: uint8 with discrete class labels- - ``"probability"``: float32 with values in [0, 1]+ - `"class_ids"`: uint8 with discrete class labels+ - `"probability"`: float32 with values in [0, 1]Example:- >>> parser = create_face_parser()+ >>> parser = BiSeNet()>>> mask = parser.parse(face_crop)>>> print(f'Mask type: {parser.mask_type}')>>> print(f'Mask shape: {mask.shape}, dtype: {mask.dtype}')@@ -107,8 +101,7 @@ class BaseFaceParser(ABC):raise NotImplementedError('Subclasses must implement the parse method.')def __call__(self, image: np.ndarray, *, landmarks: np.ndarray | None = None) -> np.ndarray:- """- Provides a convenient, callable shortcut for the `parse` method.+ """Provides a convenient, callable shortcut for the `parse` method.Args:image (np.ndarray): A face image in BGR format.diff --git a/uniface/parsing/bisenet.py b/uniface/parsing/bisenet.pyindex d72de06..67fd2f4 100644--- a/uniface/parsing/bisenet.py+++ b/uniface/parsing/bisenet.py@@ -28,6 +28,10 @@ class BiSeNet(BaseFaceParser):The model supports 19 facial component classes including:- Background, skin, eyebrows, eyes, nose, mouth, lips, ears, hair, etc.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Reference:https://github.com/yakhyo/face-parsing@@ -35,13 +39,11 @@ class BiSeNet(BaseFaceParser):model_name (ParsingWeights): The enum specifying the parsing model to load.Options: RESNET18, RESNET34.Defaults to `ParsingWeights.RESNET18`.- input_size (Tuple[int, int]): The resolution (width, height) for the model's- input. Defaults to (512, 512).providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.Attributes:- input_size (Tuple[int, int]): Model input dimensions.+ input_size (tuple[int, int]): Model input dimensions (width, height), read from the ONNX model.input_mean (np.ndarray): Per-channel mean values for normalization (ImageNet).input_std (np.ndarray): Per-channel std values for normalization (ImageNet).mask_type (str): Output type identifier - "class_ids" for BiSeNet.@@ -68,13 +70,12 @@ class BiSeNet(BaseFaceParser):def __init__(self,+ *,model_name: ParsingWeights = ParsingWeights.RESNET18,- input_size: tuple[int, int] = (512, 512),providers: list[str] | None = None,) -> None:- Logger.info(f'Initializing BiSeNet with model={model_name}, input_size={input_size}')+ Logger.info(f'Initializing BiSeNet with model={model_name}')- self.input_size = input_sizeself.input_mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)self.input_std = np.array([0.229, 0.224, 0.225], dtype=np.float32)self.providers = providers@@ -83,8 +84,7 @@ class BiSeNet(BaseFaceParser):self._initialize_model()def _initialize_model(self) -> None:- """- Initialize the ONNX model from the stored model path.+ """Initialize the ONNX model from the stored model path.Raises:RuntimeError: If the model fails to load or initialize.@@ -109,8 +109,7 @@ class BiSeNet(BaseFaceParser):raise RuntimeError(f'Failed to initialize parsing model: {e}') from edef preprocess(self, face_image: np.ndarray) -> np.ndarray:- """- Preprocess a face image for parsing.+ """Preprocess a face image for parsing.Args:face_image (np.ndarray): A face image in BGR format.@@ -135,12 +134,11 @@ class BiSeNet(BaseFaceParser):return imagedef postprocess(self, outputs: np.ndarray, original_size: tuple[int, int]) -> np.ndarray:- """- Postprocess model output to segmentation mask.+ """Postprocess model output to segmentation mask.Args:outputs (np.ndarray): Raw model output.- original_size (Tuple[int, int]): Original image size (width, height).+ original_size (tuple[int, int]): Original image size (width, height).Returns:np.ndarray: Segmentation mask resized to original dimensions.@@ -154,19 +152,18 @@ class BiSeNet(BaseFaceParser):return restored_maskdef parse(self, image: np.ndarray, *, landmarks: np.ndarray | None = None) -> np.ndarray:- """- Perform end-to-end face parsing on a face image.+ """Perform end-to-end face parsing on a face image.This method orchestrates the full pipeline: preprocessing the input,running inference, and postprocessing to return the segmentation mask.BiSeNet operates on face crops and does not require landmarks.- The ``landmarks`` parameter is accepted for API compatibility but ignored.+ The `landmarks` parameter is accepted for API compatibility but ignored.Args:image (np.ndarray): A face image in BGR format.landmarks (np.ndarray | None): Ignored. Accepted for interface- compatibility with :class:`BaseFaceParser`.+ compatibility with `BaseFaceParser`.Returns:np.ndarray: Segmentation mask with the same size as input image.diff --git a/uniface/parsing/xseg.py b/uniface/parsing/xseg.pyindex b657aa6..53b3414 100644--- a/uniface/parsing/xseg.py+++ b/uniface/parsing/xseg.py@@ -25,6 +25,10 @@ class XSeg(BaseFaceParser):on bbox crops, XSeg requires 5-point landmarks for face alignment. The modeluses NHWC input format and outputs values in [0, 1] range.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Reference:https://github.com/iperov/DeepFaceLab@@ -63,6 +67,7 @@ class XSeg(BaseFaceParser):def __init__(self,+ *,model_name: XSegWeights = XSegWeights.DEFAULT,align_size: int = 256,blur_sigma: float = 0,@@ -78,8 +83,7 @@ class XSeg(BaseFaceParser):self._initialize_model()def _initialize_model(self) -> None:- """- Initialize the ONNX model from the stored model path.+ """Initialize the ONNX model from the stored model path.Raises:RuntimeError: If the model fails to load or initialize.@@ -110,8 +114,7 @@ class XSeg(BaseFaceParser):raise RuntimeError(f'Failed to initialize XSeg model: {e}') from edef preprocess(self, face_crop: np.ndarray) -> np.ndarray:- """- Preprocess an aligned face crop for inference.+ """Preprocess an aligned face crop for inference.Args:face_crop (np.ndarray): An aligned face crop in BGR format.@@ -131,8 +134,7 @@ class XSeg(BaseFaceParser):return imagedef postprocess(self, outputs: np.ndarray, crop_size: tuple[int, int]) -> np.ndarray:- """- Postprocess model output to segmentation mask.+ """Postprocess model output to segmentation mask.Args:outputs (np.ndarray): Raw model output.@@ -147,7 +149,7 @@ class XSeg(BaseFaceParser):# Resize back to crop sizemask = cv2.resize(mask, crop_size, interpolation=cv2.INTER_LINEAR)- # Apply optional blur and threshold+ # Blur, then remap [0.5, 1] to [0, 1] so values below 0.5 drop to 0, re-sharpening the softened edgeif self.blur_sigma > 0:mask = cv2.GaussianBlur(mask, (0, 0), self.blur_sigma)mask = (mask.clip(0.5, 1) - 0.5) * 2@@ -155,11 +157,10 @@ class XSeg(BaseFaceParser):return maskdef parse(self, image: np.ndarray, *, landmarks: np.ndarray | None = None) -> np.ndarray:- """- Perform face segmentation using 5-point landmarks.+ """Perform face segmentation using 5-point landmarks.XSeg requires landmarks for face alignment. Unlike BiSeNet, calling- this method without landmarks will raise a :class:`ValueError`.+ this method without landmarks will raise a `ValueError`.Args:image (np.ndarray): Input image in BGR format.@@ -187,7 +188,6 @@ class XSeg(BaseFaceParser):input_tensor = self.preprocess(face_crop)outputs = self.session.run(self.output_names, {self.input_name: input_tensor})- # Postprocess maskmask = self.postprocess(outputs[0], crop_size)# Warp mask back to original image space@@ -204,8 +204,7 @@ class XSeg(BaseFaceParser):return warped_maskdef parse_aligned(self, face_crop: np.ndarray) -> np.ndarray:- """- Perform segmentation on an already aligned face crop.+ """Perform segmentation on an already aligned face crop.Args:face_crop (np.ndarray): An aligned face crop in BGR format.@@ -226,8 +225,7 @@ class XSeg(BaseFaceParser):image: np.ndarray,landmarks: np.ndarray,) -> tuple[np.ndarray, np.ndarray, np.ndarray]:- """- Parse face and return mask with inverse matrix for custom warping.+ """Parse face and return mask with inverse matrix for custom warping.Args:image (np.ndarray): Input image in BGR format.@@ -235,6 +233,9 @@ class XSeg(BaseFaceParser):Returns:Tuple of (mask, face_crop, inverse_matrix).++ Raises:+ ValueError: If `landmarks` does not have shape (5, 2)."""if landmarks.shape != (5, 2):raise ValueError(f'Landmarks must have shape (5, 2), got {landmarks.shape}')diff --git a/uniface/privacy/blur.py b/uniface/privacy/blur.pyindex 509109e..2394073 100644--- a/uniface/privacy/blur.py+++ b/uniface/privacy/blur.py@@ -53,7 +53,7 @@ class EllipticalBlur:margin (int): Extra pixels to extend ellipse beyond bbox. Defaults to 20."""- def __init__(self, blur_strength: float = 3.0, margin: int = 20):+ def __init__(self, *, blur_strength: float = 3.0, margin: int = 20):self.blur_strength = blur_strengthself.margin = margin@@ -94,8 +94,8 @@ class BlurFace:method (str): Blur method - 'gaussian', 'pixelate', 'blackout', 'elliptical', or 'median'.Defaults to 'pixelate'.blur_strength (float): Intensity for gaussian/elliptical/median. Defaults to 3.0.- pixel_blocks (int): Block count for pixelate. Defaults to 10.- color (Tuple[int, int, int]): Fill color (BGR) for blackout. Defaults to (0, 0, 0).+ pixel_blocks (int): Block count for pixelate. Defaults to 15.+ color (tuple[int, int, int]): Fill color (BGR) for blackout. Defaults to (0, 0, 0).margin (int): Edge margin for elliptical. Defaults to 20.Example:@@ -107,6 +107,7 @@ class BlurFace:def __init__(self,+ *,method: str = 'pixelate',blur_strength: float = 3.0,pixel_blocks: int = 15,@@ -123,7 +124,7 @@ class BlurFace:raise ValueError(f"Invalid blur method: '{method}'. Choose from: {sorted(self.VALID_METHODS)}")if self.method == 'elliptical':- self._elliptical = EllipticalBlur(blur_strength, margin)+ self._elliptical = EllipticalBlur(blur_strength=blur_strength, margin=margin)def _blur_region(self, region: np.ndarray) -> np.ndarray:"""Apply blur to a single region based on the configured method."""@@ -135,7 +136,7 @@ class BlurFace:return _pixelate_blur(region, self._pixel_blocks)elif self.method == 'blackout':return _blackout_blur(region, self._color)- return region # Fallback (should not reach here)+ return region # unreachable: blur_regions dispatches 'elliptical' before _blur_region is calleddef anonymize(self,@@ -147,7 +148,7 @@ class BlurFace:Args:image (np.ndarray): Input image (BGR format).- faces (List[Dict]): Face detections with 'bbox' key containing [x1, y1, x2, y2].+ faces (list[Face]): Face detections with 'bbox' key containing [x1, y1, x2, y2].inplace (bool): Modify image in-place if True. Defaults to False.Returns:diff --git a/uniface/quality/base.py b/uniface/quality/base.pyindex e1b2806..b6bf245 100644--- a/uniface/quality/base.py+++ b/uniface/quality/base.py@@ -14,8 +14,7 @@ __all__ = ['BaseQualityEstimator', 'QualityResult']class BaseQualityEstimator(ABC):- """- Abstract base class for face image quality assessment models.+ """Abstract base class for face image quality assessment models.Quality estimators predict a single scalar score from an aligned face crop,where higher values indicate better quality (sharpness, frontalness,@@ -25,22 +24,18 @@ class BaseQualityEstimator(ABC):@abstractmethoddef _initialize_model(self) -> None:- """- Initialize the underlying model for inference.+ """Initialize the underlying model for inference.This method should handle loading model weights, creating theinference session (e.g., ONNX Runtime), and any necessary- setup procedures to prepare the model for prediction.-- Raises:- RuntimeError: If the model fails to load or initialize.+ setup procedures to prepare the model for prediction. Implementations+ raise RuntimeError if the model fails to load or initialize."""raise NotImplementedError('Subclasses must implement the _initialize_model method.')@abstractmethoddef preprocess(self, aligned_face: np.ndarray) -> np.ndarray:- """- Preprocess an aligned face crop for model inference.+ """Preprocess an aligned face crop for model inference.Args:aligned_face: An aligned face crop in BGR format, sized to the@@ -54,8 +49,7 @@ class BaseQualityEstimator(ABC):@abstractmethoddef score_aligned(self, aligned_face: np.ndarray) -> QualityResult:- """- Score a pre-aligned face crop.+ """Score a pre-aligned face crop.Use this when the input is already aligned to the model's expectedlayout (e.g., from `uniface.face_alignment`).@@ -70,8 +64,7 @@ class BaseQualityEstimator(ABC):@abstractmethoddef predict(self, image: np.ndarray, landmarks: np.ndarray) -> QualityResult:- """- Perform end-to-end quality estimation from a full image and landmarks.+ """Perform end-to-end quality estimation from a full image and landmarks.Aligns the face using the provided 5-point landmarks, then scores it.@@ -85,5 +78,5 @@ class BaseQualityEstimator(ABC):raise NotImplementedError('Subclasses must implement the predict method.')def __call__(self, image: np.ndarray, landmarks: np.ndarray) -> QualityResult:- """Callable shortcut for :meth:`predict`."""+ """Callable shortcut for `predict`."""return self.predict(image, landmarks)diff --git a/uniface/quality/ediffiqa.py b/uniface/quality/ediffiqa.pyindex 6cc8eec..db45623 100644--- a/uniface/quality/ediffiqa.py+++ b/uniface/quality/ediffiqa.py@@ -20,8 +20,7 @@ __all__ = ['EDifFIQA']class EDifFIQA(BaseQualityEstimator):- """- eDifFIQA: Face Image Quality Assessment with ONNX Runtime.+ """eDifFIQA: Face Image Quality Assessment with ONNX Runtime.Predicts a single scalar quality score from an aligned 112x112 face crop.Higher score = better quality. Supports four backbones via the@@ -41,6 +40,10 @@ class EDifFIQA(BaseQualityEstimator):providers: ONNX Runtime execution providers. If None, auto-detectsthe best available provider.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Example:>>> from uniface.detection import SCRFD>>> from uniface.quality import EDifFIQA@@ -56,6 +59,7 @@ class EDifFIQA(BaseQualityEstimator):def __init__(self,+ *,model_name: EDifFIQAWeights = EDifFIQAWeights.T,providers: list[str] | None = None,) -> None:@@ -71,8 +75,7 @@ class EDifFIQA(BaseQualityEstimator):self._initialize_model()def _initialize_model(self) -> None:- """- Initialize the ONNX model from the stored model path.+ """Initialize the ONNX model from the stored model path.Raises:RuntimeError: If the model fails to load or initialize.@@ -94,8 +97,7 @@ class EDifFIQA(BaseQualityEstimator):raise RuntimeError(f'Failed to initialize EDifFIQA model: {e}') from edef preprocess(self, aligned_face: np.ndarray) -> np.ndarray:- """- Preprocess an aligned face crop for model inference.+ """Preprocess an aligned face crop for model inference.Converts BGR -> RGB, normalizes with mean=127.5/std=127.5, andreshapes to NCHW.@@ -115,8 +117,7 @@ class EDifFIQA(BaseQualityEstimator):)def score_aligned(self, aligned_face: np.ndarray) -> QualityResult:- """- Score a pre-aligned face crop.+ """Score a pre-aligned face crop.Args:aligned_face: Aligned face crop in BGR format.@@ -129,8 +130,7 @@ class EDifFIQA(BaseQualityEstimator):return QualityResult(score=float(np.squeeze(output)))def predict(self, image: np.ndarray, landmarks: np.ndarray) -> QualityResult:- """- Align the face using 5-point landmarks, then score it.+ """Align the face using 5-point landmarks, then score it.Args:image: Input image in BGR format containing the face.diff --git a/uniface/recognition/__init__.py b/uniface/recognition/__init__.pyindex 0482c2f..18e0618 100644--- a/uniface/recognition/__init__.py+++ b/uniface/recognition/__init__.py@@ -3,8 +3,6 @@# GitHub: https://github.com/yakhyo-from typing_extensions import deprecated-from .adaface import AdaFacefrom .arcface import ArcFacefrom .base import BaseRecognizer@@ -12,77 +10,4 @@ from .edgeface import EdgeFacefrom .mobileface import MobileFacefrom .sphereface import SphereFace--@deprecated(- 'create_recognizer() is deprecated and will be removed in uniface 4.0. '- 'Instantiate the recognizer class directly, e.g. '- '`from uniface.recognition import ArcFace; ArcFace(**kwargs)`.'-)-def create_recognizer(method: str = 'arcface', **kwargs) -> BaseRecognizer:- """- Factory function to create face recognizers.-- .. deprecated:: 3.7.0- Use the recognizer class directly (``ArcFace``, ``AdaFace``,- ``EdgeFace``, ``MobileFace``, ``SphereFace``). This factory will be- removed in uniface 4.0.-- This function initializes and returns a face recognizer instance based on the- specified method. It acts as a high-level interface to the underlying- model classes like ArcFace, AdaFace, MobileFace, etc.-- Args:- method (str): The recognition method to use.- Options: 'arcface' (default), 'adaface', 'edgeface', 'mobileface', 'sphereface'.- **kwargs: Model-specific parameters passed to the recognizer's constructor.- For example, `model_name` can be used to select a specific- pre-trained weight from the available enums (e.g., `ArcFaceWeights.MNET`).-- Returns:- BaseRecognizer: An initialized recognizer instance ready for use.-- Raises:- ValueError: If the specified `method` is not supported.-- Examples:- >>> # Create the default ArcFace recognizer- >>> from uniface.recognition import ArcFace- >>> recognizer = ArcFace()-- >>> # Create an AdaFace recognizer- >>> from uniface.recognition import AdaFace- >>> from uniface.constants import AdaFaceWeights- >>> recognizer = AdaFace(model_name=AdaFaceWeights.IR_101)-- >>> # Create a specific MobileFace recognizer- >>> from uniface.recognition import MobileFace- >>> from uniface.constants import MobileFaceWeights- >>> recognizer = MobileFace(model_name=MobileFaceWeights.MNET_V2)-- >>> # Create a SphereFace recognizer- >>> from uniface.recognition import SphereFace- >>> recognizer = SphereFace()-- >>> # Create an EdgeFace recognizer- >>> from uniface.recognition import EdgeFace- >>> from uniface.constants import EdgeFaceWeights- >>> recognizer = EdgeFace(model_name=EdgeFaceWeights.XXS)- """- method = method.lower()-- if method == 'arcface':- return ArcFace(**kwargs)- elif method == 'adaface':- return AdaFace(**kwargs)- elif method == 'edgeface':- return EdgeFace(**kwargs)- elif method == 'mobileface':- return MobileFace(**kwargs)- elif method == 'sphereface':- return SphereFace(**kwargs)- else:- available = ['arcface', 'adaface', 'edgeface', 'mobileface', 'sphereface']- raise ValueError(f"Unsupported method: '{method}'. Available: {available}")---__all__ = ['AdaFace', 'ArcFace', 'BaseRecognizer', 'EdgeFace', 'MobileFace', 'SphereFace', 'create_recognizer']+__all__ = ['AdaFace', 'ArcFace', 'BaseRecognizer', 'EdgeFace', 'MobileFace', 'SphereFace']diff --git a/uniface/recognition/adaface.py b/uniface/recognition/adaface.pyindex e9ebc67..70a94fb 100644--- a/uniface/recognition/adaface.py+++ b/uniface/recognition/adaface.py@@ -29,11 +29,15 @@ class AdaFace(BaseRecognizer):- IR_18: Smaller model trained on WebFace4M (92 MB)- IR_101: Larger model trained on WebFace12M (249 MB)Defaults to `AdaFaceWeights.IR_18`.- preprocessing (Optional[PreprocessConfig]): An optional custom preprocessing+ preprocessing (PreprocessConfig | None): An optional custom preprocessingconfiguration. If None, a default config for AdaFace is used.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Example:>>> from uniface.recognition import AdaFace>>> recognizer = AdaFace()@@ -46,6 +50,7 @@ class AdaFace(BaseRecognizer):def __init__(self,+ *,model_name: AdaFaceWeights = AdaFaceWeights.IR_18,preprocessing: PreprocessConfig | None = None,providers: list[str] | None = None,diff --git a/uniface/recognition/arcface.py b/uniface/recognition/arcface.pyindex c6ae256..b6dfd31 100644--- a/uniface/recognition/arcface.py+++ b/uniface/recognition/arcface.py@@ -22,11 +22,15 @@ class ArcFace(BaseRecognizer):Args:model_name (ArcFaceWeights): The specific ArcFace model variant to use.Defaults to `ArcFaceWeights.MNET`.- preprocessing (Optional[PreprocessConfig]): An optional custom preprocessing+ preprocessing (PreprocessConfig | None): An optional custom preprocessingconfiguration. If None, a default config for ArcFace is used.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Example:>>> from uniface.recognition import ArcFace>>> recognizer = ArcFace()@@ -39,6 +43,7 @@ class ArcFace(BaseRecognizer):def __init__(self,+ *,model_name: ArcFaceWeights = ArcFaceWeights.MNET,preprocessing: PreprocessConfig | None = None,providers: list[str] | None = None,diff --git a/uniface/recognition/base.py b/uniface/recognition/base.pyindex 3743541..d304810 100644--- a/uniface/recognition/base.py+++ b/uniface/recognition/base.py@@ -33,20 +33,20 @@ class PreprocessConfig:class BaseRecognizer(ABC):- """- Abstract Base Class for all face recognition models.+ """Abstract Base Class for all face recognition models.+It provides the core functionality for preprocessing, inference, and embedding extraction."""@abstractmethoddef __init__(self,+ *,model_path: str,preprocessing: PreprocessConfig,providers: list[str] | None = None,) -> None:- """- Initializes the model. Subclasses must call this.+ """Initializes the model. Subclasses must call this.Args:model_path (str): The direct path to the verified ONNX model.@@ -63,8 +63,7 @@ class BaseRecognizer(ABC):self._initialize_model()def _initialize_model(self) -> None:- """- Loads the ONNX model and prepares it for inference.+ """Loads the ONNX model and prepares it for inference.Raises:RuntimeError: If the model fails to load or initialize.@@ -87,7 +86,9 @@ class BaseRecognizer(ABC):self.output_names = [output.name for output in self.session.get_outputs()]self.output_shape = self.session.get_outputs()[0].shape- assert len(self.output_names) == 1, 'Expected only one output node.'+ if len(self.output_names) != 1:+ raise ValueError(f'Expected exactly one output node, got {len(self.output_names)}: {self.output_names}')+Logger.info(f'Successfully initialized face encoder from {self.model_path}')except Exception as e:@@ -98,8 +99,7 @@ class BaseRecognizer(ABC):raise RuntimeError(f"Failed to initialize model session for '{self.model_path}'") from edef preprocess(self, face_img: np.ndarray) -> np.ndarray:- """- Preprocess the image: resize, normalize, and convert it to a blob.+ """Preprocess the image: resize, normalize, and convert it to a blob.Args:face_img: Input image in BGR format.diff --git a/uniface/recognition/edgeface.py b/uniface/recognition/edgeface.pyindex de161a7..cd86cb8 100644--- a/uniface/recognition/edgeface.py+++ b/uniface/recognition/edgeface.py@@ -29,11 +29,15 @@ class EdgeFace(BaseRecognizer):- S_GAMMA_05: Small with LoRA (3.65M params, ~14 MB)- BASE: Full-size model (18.2M params, ~70 MB)Defaults to `EdgeFaceWeights.XXS`.- preprocessing (Optional[PreprocessConfig]): An optional custom preprocessing+ preprocessing (PreprocessConfig | None): An optional custom preprocessingconfiguration. If None, a default config for EdgeFace is used.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Example:>>> from uniface.recognition import EdgeFace>>> recognizer = EdgeFace()@@ -47,6 +51,7 @@ class EdgeFace(BaseRecognizer):def __init__(self,+ *,model_name: EdgeFaceWeights = EdgeFaceWeights.XXS,preprocessing: PreprocessConfig | None = None,providers: list[str] | None = None,diff --git a/uniface/recognition/mobileface.py b/uniface/recognition/mobileface.pyindex e5ce092..b9ef43a 100644--- a/uniface/recognition/mobileface.py+++ b/uniface/recognition/mobileface.py@@ -22,11 +22,15 @@ class MobileFace(BaseRecognizer):Args:model_name (MobileFaceWeights): The specific MobileFaceNet model variant to use.Defaults to `MobileFaceWeights.MNET_V2`.- preprocessing (Optional[PreprocessConfig]): An optional custom preprocessing+ preprocessing (PreprocessConfig | None): An optional custom preprocessingconfiguration. If None, a default config for MobileFaceNet is used.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Example:>>> from uniface.recognition import MobileFace>>> recognizer = MobileFace()@@ -39,6 +43,7 @@ class MobileFace(BaseRecognizer):def __init__(self,+ *,model_name: MobileFaceWeights = MobileFaceWeights.MNET_V2,preprocessing: PreprocessConfig | None = None,providers: list[str] | None = None,diff --git a/uniface/recognition/sphereface.py b/uniface/recognition/sphereface.pyindex 8766441..4e44683 100644--- a/uniface/recognition/sphereface.py+++ b/uniface/recognition/sphereface.py@@ -22,11 +22,15 @@ class SphereFace(BaseRecognizer):Args:model_name (SphereFaceWeights): The specific SphereFace model variant to use.Defaults to `SphereFaceWeights.SPHERE20`.- preprocessing (Optional[PreprocessConfig]): An optional custom preprocessing+ preprocessing (PreprocessConfig | None): An optional custom preprocessingconfiguration. If None, a default config for SphereFace is used.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detectsthe best available provider. Example: ['CPUExecutionProvider'] to force CPU.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Example:>>> from uniface.recognition import SphereFace>>> recognizer = SphereFace()@@ -39,6 +43,7 @@ class SphereFace(BaseRecognizer):def __init__(self,+ *,model_name: SphereFaceWeights = SphereFaceWeights.SPHERE20,preprocessing: PreprocessConfig | None = None,providers: list[str] | None = None,diff --git a/uniface/spoofing/__init__.py b/uniface/spoofing/__init__.pyindex 85f9e8b..8fbc471 100644--- a/uniface/spoofing/__init__.py+++ b/uniface/spoofing/__init__.py@@ -4,10 +4,6 @@from __future__ import annotations-from typing import Any--from typing_extensions import deprecated-from uniface.constants import MiniFASNetWeightsfrom uniface.types import SpoofingResult@@ -19,44 +15,4 @@ __all__ = ['MiniFASNet','MiniFASNetWeights','SpoofingResult',- 'create_spoofer',]---@deprecated(- 'create_spoofer() is deprecated and will be removed in uniface 4.0. '- 'Instantiate MiniFASNet directly, e.g. '- '`from uniface.spoofing import MiniFASNet; MiniFASNet(model_name=...)`.'-)-def create_spoofer(- model_name: MiniFASNetWeights = MiniFASNetWeights.V2,- scale: float | None = None,- **kwargs: Any,-) -> MiniFASNet:- """Factory function to create a face anti-spoofing model.-- .. deprecated:: 3.7.0- Use ``MiniFASNet`` directly. This factory will be removed in uniface 4.0.-- This is a convenience function that creates a MiniFASNet instance- with the specified model variant and optional custom scale.-- Args:- model_name: The model variant to use. Options:- - MiniFASNetWeights.V2: Improved version (default), uses scale=2.7- - MiniFASNetWeights.V1SE: Squeeze-and-excitation version, uses scale=4.0- scale: Custom crop scale factor for face region. If None, uses the- default scale for the selected model variant.- **kwargs: Additional keyword arguments forwarded to MiniFASNet- (e.g. ``providers=['CUDAExecutionProvider']``).-- Returns:- An initialized face anti-spoofing model.-- Example:- >>> from uniface.spoofing import MiniFASNet, MiniFASNetWeights- >>> spoofer = MiniFASNet(model_name=MiniFASNetWeights.V2)- >>> result = spoofer.predict(image, face.bbox)- >>> print(f'Is real: {result.is_real}, Confidence: {result.confidence:.2%}')- """- return MiniFASNet(model_name=model_name, scale=scale, **kwargs)diff --git a/uniface/spoofing/base.py b/uniface/spoofing/base.pyindex 52ad5bf..008115e 100644--- a/uniface/spoofing/base.py+++ b/uniface/spoofing/base.py@@ -14,8 +14,7 @@ __all__ = ['BaseSpoofer', 'SpoofingResult']class BaseSpoofer(ABC):- """- Abstract base class for all face anti-spoofing models.+ """Abstract base class for all face anti-spoofing models.This class defines the common interface that all anti-spoofing models must implement,ensuring consistency across different spoofing detection methods. Anti-spoofing models@@ -24,22 +23,18 @@ class BaseSpoofer(ABC):@abstractmethoddef _initialize_model(self) -> None:- """- Initialize the underlying model for inference.+ """Initialize the underlying model for inference.This method should handle loading model weights, creating theinference session (e.g., ONNX Runtime), and any necessary- setup procedures to prepare the model for prediction.-- Raises:- RuntimeError: If the model fails to load or initialize.+ setup procedures to prepare the model for prediction. Implementations+ raise RuntimeError if the model fails to load or initialize."""raise NotImplementedError('Subclasses must implement the _initialize_model method.')@abstractmethoddef preprocess(self, image: np.ndarray, bbox: list | np.ndarray) -> np.ndarray:- """- Preprocess the input image for model inference.+ """Preprocess the input image for model inference.This method should crop the face region using the bounding box,resize it to the model's expected input size, and normalize@@ -47,7 +42,7 @@ class BaseSpoofer(ABC):Args:image (np.ndarray): Input image in BGR format with shape (H, W, C).- bbox (Union[List, np.ndarray]): Face bounding box in [x1, y1, x2, y2] format.+ bbox (list | np.ndarray): Face bounding box in [x1, y1, x2, y2] format.Returns:np.ndarray: The preprocessed image tensor ready for inference,@@ -57,8 +52,7 @@ class BaseSpoofer(ABC):@abstractmethoddef postprocess(self, outputs: np.ndarray) -> SpoofingResult:- """- Postprocess raw model outputs into prediction result.+ """Postprocess raw model outputs into prediction result.This method takes the raw output from the model's inference andconverts it into a SpoofingResult.@@ -73,15 +67,14 @@ class BaseSpoofer(ABC):@abstractmethoddef predict(self, image: np.ndarray, bbox: list | np.ndarray) -> SpoofingResult:- """- Perform end-to-end anti-spoofing prediction on a face.+ """Perform end-to-end anti-spoofing prediction on a face.This method orchestrates the full pipeline: preprocessing the input,running inference, and postprocessing to return the prediction.Args:image (np.ndarray): Input image in BGR format containing the face.- bbox (Union[List, np.ndarray]): Face bounding box in [x1, y1, x2, y2] format.+ bbox (list | np.ndarray): Face bounding box in [x1, y1, x2, y2] format.This is typically obtained from a face detector.Returns:@@ -99,12 +92,11 @@ class BaseSpoofer(ABC):raise NotImplementedError('Subclasses must implement the predict method.')def __call__(self, image: np.ndarray, bbox: list | np.ndarray) -> SpoofingResult:- """- Provides a convenient, callable shortcut for the `predict` method.+ """Provides a convenient, callable shortcut for the `predict` method.Args:image (np.ndarray): Input image in BGR format.- bbox (Union[List, np.ndarray]): Face bounding box in [x1, y1, x2, y2] format.+ bbox (list | np.ndarray): Face bounding box in [x1, y1, x2, y2] format.Returns:SpoofingResult: Result containing is_real flag and confidence score.diff --git a/uniface/spoofing/minifasnet.py b/uniface/spoofing/minifasnet.pyindex 3af6613..f80e5a3 100644--- a/uniface/spoofing/minifasnet.py+++ b/uniface/spoofing/minifasnet.py@@ -25,8 +25,7 @@ DEFAULT_SCALES = {class MiniFASNet(BaseSpoofer):- """- MiniFASNet: Lightweight Face Anti-Spoofing with ONNX Runtime.+ """MiniFASNet: Lightweight Face Anti-Spoofing with ONNX Runtime.MiniFASNet is a face anti-spoofing model that detects whether a face is real(live person) or fake (photo, video replay, mask, etc.). It supports two model@@ -35,6 +34,10 @@ class MiniFASNet(BaseSpoofer):The model takes a face region cropped from the image using a bounding boxand predicts whether it's a real or spoofed face.+ Raises:+ ValueError: If the model weights are invalid or not found.+ RuntimeError: If the ONNX model fails to load or initialize.+Reference:https://github.com/yakhyo/face-anti-spoofing@@ -42,7 +45,7 @@ class MiniFASNet(BaseSpoofer):model_name (MiniFASNetWeights): The enum specifying the model variant to load.Options: V1SE (scale=4.0), V2 (scale=2.7).Defaults to `MiniFASNetWeights.V2`.- scale (Optional[float]): Custom crop scale factor for face region.+ scale (float | None): Custom crop scale factor for face region.If None, uses the default scale for the selected model variant.V1SE uses 4.0, V2 uses 2.7.providers (list[str] | None): ONNX Runtime execution providers. If None, auto-detects@@ -50,7 +53,7 @@ class MiniFASNet(BaseSpoofer):Attributes:scale (float): Crop scale factor for face region extraction.- input_size (Tuple[int, int]): Model input dimensions (width, height).+ input_size (tuple[int, int]): Model input dimensions (width, height).Example:>>> from uniface.spoofing import MiniFASNet@@ -69,6 +72,7 @@ class MiniFASNet(BaseSpoofer):def __init__(self,+ *,model_name: MiniFASNetWeights = MiniFASNetWeights.V2,scale: float | None = None,providers: list[str] | None = None,@@ -83,8 +87,7 @@ class MiniFASNet(BaseSpoofer):self._initialize_model()def _initialize_model(self) -> None:- """- Initialize the ONNX model from the stored model path.+ """Initialize the ONNX model from the stored model path.Raises:RuntimeError: If the model fails to load or initialize.@@ -114,8 +117,7 @@ class MiniFASNet(BaseSpoofer):return [int(x1), int(y1), int(x2 - x1), int(y2 - y1)]def _crop_face(self, image: np.ndarray, bbox_xywh: list[int]) -> np.ndarray:- """- Crop and resize face region from image using scale factor.+ """Crop and resize face region from image using scale factor.The crop is centered on the face bounding box and scaled to capturemore context around the face, which is important for anti-spoofing.@@ -152,8 +154,7 @@ class MiniFASNet(BaseSpoofer):return resizeddef preprocess(self, image: np.ndarray, bbox: list | np.ndarray) -> np.ndarray:- """- Preprocess the input image for model inference.+ """Preprocess the input image for model inference.Crops the face region, converts to float32, and arrangesdimensions for the model (NCHW format).@@ -181,8 +182,7 @@ class MiniFASNet(BaseSpoofer):return facedef postprocess(self, outputs: np.ndarray) -> SpoofingResult:- """- Postprocess raw model outputs into prediction result.+ """Postprocess raw model outputs into prediction result.Applies softmax to convert logits to probabilities andreturns the SpoofingResult with is_real flag and confidence score.@@ -200,8 +200,7 @@ class MiniFASNet(BaseSpoofer):return SpoofingResult(is_real=(label_idx == 1), confidence=confidence)def predict(self, image: np.ndarray, bbox: list | np.ndarray) -> SpoofingResult:- """- Perform end-to-end anti-spoofing prediction on a face.+ """Perform end-to-end anti-spoofing prediction on a face.Args:image: Input image in BGR format containing the face.@@ -210,7 +209,6 @@ class MiniFASNet(BaseSpoofer):Returns:SpoofingResult: Result containing is_real flag and confidence score."""- # Preprocessinput_tensor = self.preprocess(image, bbox)# Run inferencediff --git a/uniface/stores/base.py b/uniface/stores/base.pyindex 9db77f7..3350a75 100644--- a/uniface/stores/base.py+++ b/uniface/stores/base.py@@ -48,13 +48,13 @@ class BaseStore(ABC):threshold: Minimum similarity to accept a match.Returns:- ``(metadata, similarity)`` for the best match, or- ``(None, similarity)`` when below *threshold* or empty.+ `(metadata, similarity)` for the best match, or+ `(None, similarity)` when below *threshold* or empty."""@abstractmethoddef remove(self, key: str, value: Any) -> int:- """Remove all entries where ``metadata[key] == value``.+ """Remove all entries where `metadata[key] == value`.Args:key: Metadata key to match against.diff --git a/uniface/stores/faiss.py b/uniface/stores/faiss.pyindex f631021..9ce3ec1 100644--- a/uniface/stores/faiss.py+++ b/uniface/stores/faiss.py@@ -59,6 +59,7 @@ class FAISS(BaseStore):def __init__(self,+ *,embedding_size: int = 512,db_path: str = './vector_index',) -> None:@@ -97,8 +98,8 @@ class FAISS(BaseStore):threshold: Minimum cosine similarity to accept a match.Returns:- ``(metadata, similarity)`` for the best match, or- ``(None, similarity)`` when below *threshold* or the+ `(metadata, similarity)` for the best match, or+ `(None, similarity)` when below *threshold* or theindex is empty."""if self.index.ntotal == 0:@@ -115,7 +116,7 @@ class FAISS(BaseStore):return None, similaritydef remove(self, key: str, value: Any) -> int:- """Remove all entries where ``metadata[key] == value``.+ """Remove all entries where `metadata[key] == value`.Args:key: Metadata key to match against.@@ -155,7 +156,7 @@ class FAISS(BaseStore):"""Load a previously saved index and metadata from disk.Returns:- ``True`` if loaded successfully, ``False`` if files are missing.+ `True` if loaded successfully, `False` if files are missing.Raises:RuntimeError: If files exist but cannot be read.diff --git a/uniface/tracking/bytetrack/tracker.py b/uniface/tracking/bytetrack/tracker.pyindex 4724d2d..11894cb 100644--- a/uniface/tracking/bytetrack/tracker.py+++ b/uniface/tracking/bytetrack/tracker.py@@ -166,6 +166,7 @@ class BYTETracker:def __init__(self,+ *,track_thresh: float = 0.5,track_buffer: int = 30,match_thresh: float = 0.8,diff --git a/uniface/types.py b/uniface/types.pyindex f75e509..87f9f18 100644--- a/uniface/types.py+++ b/uniface/types.py@@ -8,7 +8,7 @@ This module centralizes all result dataclasses used across the library,providing consistent and immutable return types for model predictions.Note on mutability:-- Result dataclasses (GazeResult, SpoofingResult, EmotionResult, AttributeResult)+- Result dataclasses (GazeResult, SpoofingResult, EmotionResult, DemographyResult)are frozen (immutable) since they represent computation outputs that shouldn't change.- Face dataclass is mutable because FaceAnalyzer enriches it with additionalattributes (embedding, age, gender, etc.) after initial detection.@@ -24,9 +24,11 @@ import numpy as npfrom uniface.face_utils import compute_similarity__all__ = [- 'AttributeResult',+ 'DemographyResult','EmotionResult','Face',+ 'FaceMeshResult',+ 'FaceStateResult','GazeResult','HeadPoseResult','QualityResult',@@ -116,11 +118,11 @@ class EmotionResult:@dataclass(slots=True, frozen=True)-class AttributeResult:- """Unified result structure for face attribute prediction.+class DemographyResult:+ """Unified result structure for demographic attribute prediction.- This dataclass provides a consistent return type across different attribute- prediction models (e.g., AgeGender, FairFace), enabling interoperability+ This dataclass provides a consistent return type across demographic+ prediction models (AgeGender, FairFace), enabling interoperabilityand unified handling of results.Attributes:@@ -128,18 +130,16 @@ class AttributeResult:age: Exact age in years. Provided by AgeGender model, None for FairFace.age_group: Age range string like "20-29". Provided by FairFace, None for AgeGender.race: Race/ethnicity label. Provided by FairFace only.+ sex: Read-only. Gender as a human-readable string ("Female" or "Male").- Properties:- sex: Gender as a human-readable string ("Female" or "Male").-- Examples:+ Example:>>> # AgeGender result- >>> result = AttributeResult(gender=1, age=25)+ >>> result = DemographyResult(gender=1, age=25)>>> result.sex'Male'>>> # FairFace result- >>> result = AttributeResult(gender=0, age_group='20-29', race='East Asian')+ >>> result = DemographyResult(gender=0, age_group='20-29', race='East Asian')>>> result.sex'Female'"""@@ -162,7 +162,81 @@ class AttributeResult:parts.append(f'age_group={self.age_group}')if self.race is not None:parts.append(f'race={self.race}')- return f'AttributeResult({", ".join(parts)})'+ return f'DemographyResult({", ".join(parts)})'+++@dataclass(slots=True, frozen=True)+class FaceStateResult:+ """Result of face state prediction (FaceAttribNet).++ Five independent binary probabilities in [0, 1], in the model's output+ order. Each value comes from its own classifier head, so the values do not+ sum to 1 and several can be high at once (a face can wear both sunglasses+ and a mask). Threshold each attribute separately; never argmax.++ Attributes:+ left_eye_open: Probability the left eye is open.+ right_eye_open: Probability the right eye is open.+ eyeglasses: Probability eyeglasses are present.+ mask: Probability a face mask is present.+ sunglasses: Probability sunglasses are present.+ """++ left_eye_open: float+ right_eye_open: float+ eyeglasses: float+ mask: float+ sunglasses: float++ def as_dict(self) -> dict[str, float]:+ """Return the attributes as a name -> probability mapping."""+ return {f.name: getattr(self, f.name) for f in fields(self)}++ def labels(self, threshold: float = 0.5) -> list[str]:+ """Return the names of attributes whose probability exceeds `threshold`."""+ return [name for name, value in self.as_dict().items() if value > threshold]++ def __repr__(self) -> str:+ body = ', '.join(f'{name}={value:.4f}' for name, value in self.as_dict().items())+ return f'FaceStateResult({body})'+++@dataclass(slots=True, frozen=True, eq=False)+class FaceMeshResult:+ """Result of dense facial landmark prediction (Face Mesh).++ Note on `eq=False`: this dataclass holds a numpy array, and the generated+ `__eq__`/`__hash__` would raise (`ValueError` on `==`, `TypeError`+ on `hash`). Identity comparison is used instead; compare `landmarks`+ directly with `np.allclose` if you need value semantics.++ Attributes:+ landmarks: Dense landmarks with shape (468, 3) or (478, 3), float32, depending+ on which `FaceMeshWeights` model produced them. `x`/`y` are in full-image+ pixel coordinates; `z` is relative depth on the same pixel scale (smaller is+ closer to the camera). Google trains `z` on synthetic data and excludes it+ from their own accuracy evaluation, so treat it as weaker than `x`/`y`.++ With the 478-point model the first 468 are the mesh, in the same order the+ 468-point model produces, and 468-477 are the irises.+ score: Face-presence score in [0, 1].++ This value saturates. The network emits a raw logit that is typically+ 20-40 for any plausible face, so after the sigmoid it is ~1.0 almost+ always. Treat it as confirmation that the model ran, not as a+ discriminative confidence, and do not threshold on it.+ """++ landmarks: np.ndarray+ score: float++ @property+ def points_2d(self) -> np.ndarray:+ """Get the landmarks without the depth component, shape (N, 2)."""+ return self.landmarks[:, :2]++ def __repr__(self) -> str:+ return f'FaceMeshResult(landmarks={self.landmarks.shape}, score={self.score:.4f})'@dataclass(slots=True)@@ -186,13 +260,16 @@ class Face:race: Predicted race/ethnicity (optional, from FairFace).emotion: Predicted emotion label (optional, from Emotion model).emotion_confidence: Confidence score for emotion prediction (optional).+ left_eye_open: Probability the left eye is open (optional, from FaceAttribNet).+ right_eye_open: Probability the right eye is open (optional, from FaceAttribNet).+ eyeglasses: Probability eyeglasses are present (optional, from FaceAttribNet).+ mask: Probability a face mask is present (optional, from FaceAttribNet).+ sunglasses: Probability sunglasses are present (optional, from FaceAttribNet).quality: Face image quality score in [0, 1] (optional, from eDifFIQA).track_id: Persistent track ID assigned by BYTETracker (optional).-- Properties:- sex: Gender as a human-readable string ("Female" or "Male").- bbox_xyxy: Bounding box in (x1, y1, x2, y2) format.- bbox_xywh: Bounding box in (x1, y1, width, height) format.+ sex: Read-only. Gender as a human-readable string ("Female" or "Male").+ bbox_xyxy: Read-only. Bounding box in (x1, y1, x2, y2) format.+ bbox_xywh: Read-only. Bounding box in (x1, y1, width, height) format."""# Required attributes (from detection)@@ -208,11 +285,20 @@ class Face:race: str | None = Noneemotion: str | None = Noneemotion_confidence: float | None = None+ left_eye_open: float | None = None+ right_eye_open: float | None = None+ eyeglasses: float | None = None+ mask: float | None = None+ sunglasses: float | None = Nonequality: float | None = Nonetrack_id: int | None = Nonedef compute_similarity(self, other: Face) -> float:- """Compute cosine similarity with another face."""+ """Compute cosine similarity with another face.++ Raises:+ ValueError: If either face has no embedding.+ """if self.embedding is None or other.embedding is None:raise ValueError('Both faces must have embeddings for similarity computation')return float(compute_similarity(self.embedding, other.embedding))@@ -280,6 +366,15 @@ class Face:parts.append(f'race={self.race}')if self.emotion is not None:parts.append(f'emotion={self.emotion}')+ # Gated per field: a predictor may fill only some of the five, and __repr__ is+ # what you reach for when something has already gone wrong.+ states = [+ f'{name}={value:.2f}'+ for name in ('left_eye_open', 'right_eye_open', 'eyeglasses', 'mask', 'sunglasses')+ if (value := getattr(self, name)) is not None+ ]+ if states:+ parts.append(', '.join(states))if self.quality is not None:parts.append(f'quality={self.quality:.4f}')if self.embedding is not None:diff --git a/uv.lock b/uv.lockindex 5d56e77..0acc40b 100644--- a/uv.lock+++ b/uv.lock@@ -178,7 +178,7 @@ name = "coloredlogs"version = "15.0.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "humanfriendly", marker = "python_full_version < '3.11'" },+ { name = "humanfriendly" },]sdist = { url = "https://files.pythonhosted.org/packages/cc/c7/eed8f27100517e8c0e6b923d5f0845d0cb99763da6fdee00478f91db7325/coloredlogs-15.0.1.tar.gz", hash = "sha256:7c991aa71a4577af2f82600d8f8f3a89f936baeaf9b50a9c197da014e5bf16b0", size = 278520, upload-time = "2021-06-11T10:22:45.202Z" }wheels = [@@ -199,7 +199,7 @@ name = "exceptiongroup"version = "1.3.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "typing-extensions", marker = "python_full_version < '3.11'" },+ { name = "typing-extensions" },]sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }wheels = [@@ -264,7 +264,7 @@ name = "humanfriendly"version = "10.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "pyreadline3", marker = "python_full_version < '3.11' and sys_platform == 'win32'" },+ { name = "pyreadline3", marker = "sys_platform == 'win32'" },]sdist = { url = "https://files.pythonhosted.org/packages/cc/3f/2c29224acb2e2df4d2046e4c73ee2662023c58ff5b113c4c1adac0886c43/humanfriendly-10.0.tar.gz", hash = "sha256:6b0b831ce8f15f7300721aa49829fc4e83921a9a301cc7f606be6686a2288ddc", size = 360702, upload-time = "2021-09-17T21:40:43.31Z" }wheels = [@@ -736,12 +736,12 @@ resolution-markers = ["python_full_version < '3.11'",]dependencies = [- { name = "coloredlogs", marker = "python_full_version < '3.11'" },- { name = "flatbuffers", marker = "python_full_version < '3.11'" },- { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },- { name = "packaging", marker = "python_full_version < '3.11'" },- { name = "protobuf", marker = "python_full_version < '3.11'" },- { name = "sympy", marker = "python_full_version < '3.11'" },+ { name = "coloredlogs" },+ { name = "flatbuffers" },+ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },+ { name = "packaging" },+ { name = "protobuf" },+ { name = "sympy" },]wheels = [{ url = "https://files.pythonhosted.org/packages/35/d6/311b1afea060015b56c742f3531168c1644650767f27ef40062569960587/onnxruntime-1.23.2-cp310-cp310-macosx_13_0_arm64.whl", hash = "sha256:a7730122afe186a784660f6ec5807138bf9d792fa1df76556b27307ea9ebcbe3", size = 17195934, upload-time = "2025-10-27T23:06:14.143Z" },@@ -777,10 +777,10 @@ resolution-markers = ["python_full_version == '3.11.*'",]dependencies = [- { name = "flatbuffers", marker = "python_full_version >= '3.11'" },- { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },- { name = "packaging", marker = "python_full_version >= '3.11'" },- { name = "protobuf", marker = "python_full_version >= '3.11'" },+ { name = "flatbuffers" },+ { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" } },+ { name = "packaging" },+ { name = "protobuf" },]wheels = [{ url = "https://files.pythonhosted.org/packages/c1/00/dccf702195572df51a40784fc939304595a0ae3577537d3b5be79273151a/onnxruntime-1.25.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:5cf58ec7601120bb4370f0b868f794d3e3626db7b1b1dba366c27874b224e9de", size = 17762805, upload-time = "2026-04-27T22:00:45.336Z" },@@ -817,12 +817,12 @@ resolution-markers = ["python_full_version < '3.11'",]dependencies = [- { name = "coloredlogs", marker = "python_full_version < '3.11'" },- { name = "flatbuffers", marker = "python_full_version < '3.11'" },- { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },- { name = "packaging", marker = "python_full_version < '3.11'" },- { name = "protobuf", marker = "python_full_version < '3.11'" },- { name = "sympy", marker = "python_full_version < '3.11'" },+ { name = "coloredlogs" },+ { name = "flatbuffers" },+ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },+ { name = "packaging" },+ { name = "protobuf" },+ { name = "sympy" },]wheels = [{ url = "https://files.pythonhosted.org/packages/cb/ae/39283748c68a96be4f5f8a9561e0e3ca92af1eae6c2b1c07fb1da5f65cd1/onnxruntime_gpu-1.23.2-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:18de50c6c8eea50acc405ea13d299aec593e46478d7a22cd32cdbbdf7c42899d", size = 300525411, upload-time = "2025-10-22T16:56:08.415Z" },@@ -845,10 +845,10 @@ resolution-markers = ["python_full_version == '3.11.*'",]dependencies = [- { name = "flatbuffers", marker = "python_full_version >= '3.11'" },- { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },- { name = "packaging", marker = "python_full_version >= '3.11'" },- { name = "protobuf", marker = "python_full_version >= '3.11'" },+ { name = "flatbuffers" },+ { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" } },+ { name = "packaging" },+ { name = "protobuf" },]wheels = [{ url = "https://files.pythonhosted.org/packages/bc/bb/d0aeb0910beee46d34568af9ba07d40bf9c5f94f188bf43c0ff47388f6de/onnxruntime_gpu-1.25.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fcdd93f7a74659e08137b5d9c705390e57b37ac86e6956ec0d7ccd81001afe0c", size = 271246304, upload-time = "2026-04-27T22:06:00.753Z" },@@ -1254,14 +1254,14 @@ resolution-markers = ["python_full_version < '3.11'",]dependencies = [- { name = "imageio", marker = "python_full_version < '3.11'" },- { name = "lazy-loader", marker = "python_full_version < '3.11'" },- { name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },- { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },- { name = "packaging", marker = "python_full_version < '3.11'" },- { name = "pillow", marker = "python_full_version < '3.11'" },- { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },- { name = "tifffile", version = "2025.5.10", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },+ { name = "imageio" },+ { name = "lazy-loader" },+ { name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" } },+ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },+ { name = "packaging" },+ { name = "pillow" },+ { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" } },+ { name = "tifffile", version = "2025.5.10", source = { registry = "https://pypi.org/simple" } },]sdist = { url = "https://files.pythonhosted.org/packages/c7/a8/3c0f256012b93dd2cb6fda9245e9f4bff7dc0486880b248005f15ea2255e/scikit_image-0.25.2.tar.gz", hash = "sha256:e5a37e6cd4d0c018a7a55b9d601357e3382826d3888c10d0213fc63bff977dde", size = 22693594, upload-time = "2025-02-18T18:05:24.538Z" }wheels = [@@ -1297,14 +1297,14 @@ resolution-markers = ["python_full_version == '3.11.*'",]dependencies = [- { name = "imageio", marker = "python_full_version >= '3.11'" },- { name = "lazy-loader", marker = "python_full_version >= '3.11'" },- { name = "networkx", version = "3.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },- { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },- { name = "packaging", marker = "python_full_version >= '3.11'" },- { name = "pillow", marker = "python_full_version >= '3.11'" },- { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },- { name = "tifffile", version = "2026.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },+ { name = "imageio" },+ { name = "lazy-loader" },+ { name = "networkx", version = "3.6.1", source = { registry = "https://pypi.org/simple" } },+ { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" } },+ { name = "packaging" },+ { name = "pillow" },+ { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" } },+ { name = "tifffile", version = "2026.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },{ name = "tifffile", version = "2026.4.11", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },]sdist = { url = "https://files.pythonhosted.org/packages/a1/b4/2528bb43c67d48053a7a649a9666432dc307d66ba02e3a6d5c40f46655df/scikit_image-0.26.0.tar.gz", hash = "sha256:f5f970ab04efad85c24714321fcc91613fcb64ef2a892a13167df2f3e59199fa", size = 22729739, upload-time = "2025-12-20T17:12:21.824Z" }@@ -1367,7 +1367,7 @@ resolution-markers = ["python_full_version < '3.11'",]dependencies = [- { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },+ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },]sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214, upload-time = "2025-05-08T16:13:05.955Z" }wheels = [@@ -1427,7 +1427,7 @@ resolution-markers = ["python_full_version == '3.11.*'",]dependencies = [- { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },+ { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" } },]sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" }wheels = [@@ -1516,7 +1516,7 @@ name = "sympy"version = "1.14.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "mpmath", marker = "python_full_version < '3.11'" },+ { name = "mpmath" },]sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" }wheels = [@@ -1531,7 +1531,7 @@ resolution-markers = ["python_full_version < '3.11'",]dependencies = [- { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },+ { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },]sdist = { url = "https://files.pythonhosted.org/packages/44/d0/18fed0fc0916578a4463f775b0fbd9c5fed2392152d039df2fb533bfdd5d/tifffile-2025.5.10.tar.gz", hash = "sha256:018335d34283aa3fd8c263bae5c3c2b661ebc45548fde31504016fcae7bf1103", size = 365290, upload-time = "2025-05-10T19:22:34.386Z" }wheels = [@@ -1546,7 +1546,7 @@ resolution-markers = ["python_full_version == '3.11.*'",]dependencies = [- { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },+ { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" } },]sdist = { url = "https://files.pythonhosted.org/packages/c5/cb/2f6d79c7576e22c116352a801f4c3c8ace5957e9aced862012430b62e14f/tifffile-2026.3.3.tar.gz", hash = "sha256:d9a1266bed6f2ee1dd0abde2018a38b4f8b2935cb843df381d70ac4eac5458b7", size = 388745, upload-time = "2026-03-03T19:14:38.134Z" }wheels = [@@ -1561,7 +1561,7 @@ resolution-markers = ["python_full_version >= '3.12'",]dependencies = [- { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },+ { name = "numpy", version = "2.4.4", source = { registry = "https://pypi.org/simple" } },]sdist = { url = "https://files.pythonhosted.org/packages/d7/4a/e687f5957fead200faad58dbf9c9431a2bbb118040e96f5fb8a55f7ebc50/tifffile-2026.4.11.tar.gz", hash = "sha256:17758ff0c0d4db385792a083ad3ca51fcb0f4d942642f4d8f8bc1287fdcf17bc", size = 394956, upload-time = "2026-04-12T01:57:28.793Z" }wheels = [@@ -1654,7 +1654,7 @@ wheels = [[[package]]name = "uniface"-version = "3.7.1"+version = "4.0.0rc1"source = { editable = "." }dependencies = [{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },@@ -1666,7 +1666,6 @@ dependencies = [{ name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },{ name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },{ name = "tqdm" },- { name = "typing-extensions" },][package.optional-dependencies]@@ -1709,7 +1708,6 @@ requires-dist = [{ name = "scikit-image", specifier = ">=0.22.0" },{ name = "scipy", specifier = ">=1.7.0" },{ name = "tqdm", specifier = ">=4.64.0" },- { name = "typing-extensions", specifier = ">=4.5.0" },]provides-extras = ["cpu", "gpu", "dev", "docs"]