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
docs: Update UniFace library documentation and README.md (#78)
Yakhyokhuja Valikhujaev9991fae62ac5
diff --git a/README.md b/README.mdindex 92e92b1..02fcaab 100644--- a/README.md+++ b/README.md@@ -13,22 +13,20 @@</div><div align="center">- <img src="https://raw.githubusercontent.com/yakhyo/uniface/main/.github/logos/new/uniface_rounded_q80.webp" width="80%">+ <img src="https://raw.githubusercontent.com/yakhyo/uniface/main/.github/logos/new/uniface_rounded_q80.webp" width="90%"></div>-##+---**UniFace** is a lightweight, production-ready face analysis library built on ONNX Runtime. It provides high-performance face detection, recognition, landmark detection, face parsing, gaze estimation, and attribute analysis with hardware acceleration support across platforms.-> π¬ **Have questions?** [Chat with this codebase on DeepWiki](https://deepwiki.com/yakhyo/uniface) - AI-powered docs that let you ask anything about UniFace.----## Features- **Face Detection** β RetinaFace, SCRFD, YOLOv5-Face, and YOLOv8-Face with 5-point landmarks- **Face Recognition** β ArcFace, MobileFace, and SphereFace embeddings-- **Facial Landmarks** β 106-point landmark localization+- **Facial Landmarks** β 106-point landmark localization module (separate from 5-point detector landmarks)- **Face Parsing** β BiSeNet semantic segmentation (19 classes), XSeg face masking- **Gaze Estimation** β Real-time gaze direction with MobileGaze- **Attribute Analysis** β Age, gender, race (FairFace), and emotion@@ -40,31 +38,55 @@## Installation+**Standard installation**+```bash-# Standard installationpip install uniface+```-# GPU support (CUDA)+**GPU support (CUDA)**++```bashpip install uniface[gpu]+```-# From source+**From source (latest version)**++```bashgit clone https://github.com/yakhyo/uniface.gitcd uniface && pip install -e .```+**Optional dependencies**+- Emotion model uses TorchScript and requires `torch`:+ `pip install torch` (choose the correct build for your OS/CUDA)+- YOLOv5-Face and YOLOv8-Face support faster NMS with `torchvision`:+ `pip install torch torchvision` then use `nms_mode='torchvision'`++---++## Model Downloads and Cache++Models are downloaded automatically on first use and verified via SHA-256.++Default cache location: `~/.uniface/models`++You can override it with `UNIFACE_CACHE_DIR=/your/cache/path`+----## Quick Example+## Quick Example (Detection)```pythonimport cv2from uniface import RetinaFace-# Initialize detector (models auto-download on first use)detector = RetinaFace()-# Detect facesimage = cv2.imread("photo.jpg")+if image is None:+ raise ValueError("Failed to load image. Check the path to 'photo.jpg'.")+faces = detector.detect(image)for face in faces:@@ -74,14 +96,52 @@ for face in faces:```<div align="center">- <img src="assets/test_result.png">+ <img src="https://raw.githubusercontent.com/yakhyo/uniface/main/assets/test_result.png" width="90%">+ <p>Face Detection Model Output</p></div>---+## Example (Face Analyzer)++```python+import cv2+from uniface import RetinaFace, ArcFace, FaceAnalyzer++detector = RetinaFace()+recognizer = ArcFace()++analyzer = FaceAnalyzer(detector, recognizer=recognizer)++image = cv2.imread("photo.jpg")+if image is None:+ raise ValueError("Failed to load image. Check the path to 'photo.jpg'.")++faces = analyzer.analyze(image)++for face in faces:+ print(face.bbox, face.embedding.shape if face.embedding is not None else None)+```++---++## Execution Providers (ONNX Runtime)++```python+from uniface import RetinaFace++# Force CPU-only inference+detector = RetinaFace(providers=["CPUExecutionProvider"])+```++See more in the docs:+https://yakhyo.github.io/uniface/concepts/execution-providers/++---+## Documentation-π **Full documentation**: [yakhyo.github.io/uniface](https://yakhyo.github.io/uniface/)+Full documentation: https://yakhyo.github.io/uniface/| Resource | Description ||----------|-------------|@@ -91,7 +151,9 @@ for face in faces:| [Tutorials](https://yakhyo.github.io/uniface/recipes/image-pipeline/) | Step-by-step workflow examples || [Guides](https://yakhyo.github.io/uniface/concepts/overview/) | Architecture and design principles |-### Jupyter Notebooks+---++## Jupyter Notebooks| Example | Colab | Description ||---------|:-----:|-------------|@@ -107,17 +169,30 @@ for face in faces:---+## Licensing and Model Usage++UniFace is MIT-licensed, but several pretrained models carry their own licenses.+Review: https://yakhyo.github.io/uniface/license-attribution/++Notable examples:+- YOLOv5-Face and YOLOv8-Face weights are GPL-3.0+- FairFace weights are CC BY 4.0++If you plan commercial use, verify model license compatibility.++---+## References| Feature | Repository | Training | Description ||---------|------------|:--------:|-------------|-| Detection | [retinaface-pytorch](https://github.com/yakhyo/retinaface-pytorch) | [x] | RetinaFace PyTorch Training & Export |+| 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 |-| Recognition | [face-recognition](https://github.com/yakhyo/face-recognition) | [x] | MobileFace, SphereFace Training |-| Parsing | [face-parsing](https://github.com/yakhyo/face-parsing) | [x] | BiSeNet Face Parsing |+| Recognition | [face-recognition](https://github.com/yakhyo/face-recognition) | β | MobileFace, SphereFace Training |+| 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) | [x] | MobileGaze Training |+| Gaze | [gaze-estimation](https://github.com/yakhyo/gaze-estimation) | β | MobileGaze Training || Anti-Spoofing | [face-anti-spoofing](https://github.com/yakhyo/face-anti-spoofing) | - | MiniFASNet Inference || Attributes | [fairface-onnx](https://github.com/yakhyo/fairface-onnx) | - | FairFace ONNX Inference |@@ -127,7 +202,15 @@ for face in faces:## Contributing-Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.+Contributions are welcome. Please see [CONTRIBUTING.md](CONTRIBUTING.md).++## Support++If you find this project useful, consider giving it a β on GitHub β it helps others discover it!++Questions or feedback:+- GitHub Issues: https://github.com/yakhyo/uniface/issues+- DeepWiki Q&A: https://deepwiki.com/yakhyo/uniface## Licensediff --git a/docs/concepts/execution-providers.md b/docs/concepts/execution-providers.mdindex f66777d..92e0f3d 100644--- a/docs/concepts/execution-providers.md+++ b/docs/concepts/execution-providers.md@@ -17,8 +17,8 @@ detector = RetinaFace()**Priority order:**-1. **CUDAExecutionProvider** - NVIDIA GPU-2. **CoreMLExecutionProvider** - Apple Silicon+1. **CoreMLExecutionProvider** - Apple Silicon+2. **CUDAExecutionProvider** - NVIDIA GPU3. **CPUExecutionProvider** - Fallback---diff --git a/docs/concepts/inputs-outputs.md b/docs/concepts/inputs-outputs.mdindex 7a2f68b..4cddd51 100644--- a/docs/concepts/inputs-outputs.md+++ b/docs/concepts/inputs-outputs.md@@ -199,16 +199,16 @@ print(f"Classes: {np.unique(mask)}") # [0, 1, 2, ...]| ID | Class | ID | Class ||----|-------|----|-------|-| 0 | Background | 10 | Ear Ring |-| 1 | Skin | 11 | Nose |-| 2 | Left Eyebrow | 12 | Mouth |-| 3 | Right Eyebrow | 13 | Upper Lip |-| 4 | Left Eye | 14 | Lower Lip |-| 5 | Right Eye | 15 | Neck |-| 6 | Eye Glasses | 16 | Neck Lace |-| 7 | Left Ear | 17 | Cloth |-| 8 | Right Ear | 18 | Hair |-| 9 | Hat | | |+| 0 | Background | 10 | Nose |+| 1 | Skin | 11 | Mouth |+| 2 | Left Eyebrow | 12 | Upper Lip |+| 3 | Right Eyebrow | 13 | Lower Lip |+| 4 | Left Eye | 14 | Neck |+| 5 | Right Eye | 15 | Necklace |+| 6 | Eyeglasses | 16 | Cloth |+| 7 | Left Ear | 17 | Hair |+| 8 | Right Ear | 18 | Hat |+| 9 | Earring | | |---diff --git a/docs/concepts/model-cache-offline.md b/docs/concepts/model-cache-offline.mdindex b341b3c..d9c1f16 100644--- a/docs/concepts/model-cache-offline.md+++ b/docs/concepts/model-cache-offline.md@@ -32,9 +32,9 @@ Default cache directory:```~/.uniface/models/-βββ retinaface_mv2.onnx-βββ w600k_mbf.onnx-βββ 2d106det.onnx+βββ retinaface_mnet_v2.onnx+βββ arcface_mnet.onnx+βββ 2d_106.onnxβββ gaze_resnet34.onnxβββ parsing_resnet18.onnxβββ ...diff --git a/docs/concepts/overview.md b/docs/concepts/overview.mdindex 05d425a..50b41fd 100644--- a/docs/concepts/overview.md+++ b/docs/concepts/overview.md@@ -151,12 +151,18 @@ for face in faces:For convenience, `FaceAnalyzer` combines multiple modules:```python-from uniface import FaceAnalyzer+from uniface import FaceAnalyzer, RetinaFace, ArcFace, AgeGender, FairFace++detector = RetinaFace()+recognizer = ArcFace()+age_gender = AgeGender()+fairface = FairFace()analyzer = FaceAnalyzer(- detect=True,- recognize=True,- attributes=True+ detector,+ recognizer=recognizer,+ age_gender=age_gender,+ fairface=fairface,)faces = analyzer.analyze(image)diff --git a/docs/installation.md b/docs/installation.mdindex 3ab056b..002a582 100644--- a/docs/installation.md+++ b/docs/installation.md@@ -107,7 +107,9 @@ UniFace has minimal dependencies:|---------|---------|| `numpy` | Array operations || `opencv-python` | Image processing |+| `onnx` | ONNX model format support || `onnxruntime` | Model inference |+| `scikit-image` | Geometric transforms || `requests` | Model download || `tqdm` | Progress bars |diff --git a/docs/models.md b/docs/models.mdindex 5377dcd..df3947c 100644--- a/docs/models.md+++ b/docs/models.md@@ -22,7 +22,7 @@ RetinaFace models are trained on the WIDER FACE dataset.!!! info "Accuracy & Benchmarks"**Accuracy**: WIDER FACE validation set (Easy/Medium/Hard subsets) - from [RetinaFace paper](https://arxiv.org/abs/1905.00641)- **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image> --iterations 100`+ **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image>`---@@ -32,13 +32,13 @@ SCRFD (Sample and Computation Redistribution for Efficient Face Detection) model| Model Name | Params | Size | Easy | Medium | Hard || ---------------- | ------ | ----- | ------ | ------ | ------ |-| `SCRFD_500M` | 0.6M | 2.5MB | 90.57% | 88.12% | 68.51% |-| `SCRFD_10G` :material-check-circle: | 4.2M | 17MB | 95.16% | 93.87% | 83.05% |+| `SCRFD_500M_KPS` | 0.6M | 2.5MB | 90.57% | 88.12% | 68.51% |+| `SCRFD_10G_KPS` :material-check-circle: | 4.2M | 17MB | 95.16% | 93.87% | 83.05% |!!! info "Accuracy & Benchmarks"**Accuracy**: WIDER FACE validation set - from [SCRFD paper](https://arxiv.org/abs/2105.04714)- **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image> --iterations 100`+ **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image>`---@@ -55,7 +55,7 @@ YOLOv5-Face models provide detection with 5-point facial landmarks, trained on W!!! info "Accuracy & Benchmarks"**Accuracy**: WIDER FACE validation set - from [YOLOv5-Face paper](https://arxiv.org/abs/2105.12931)- **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image> --iterations 100`+ **Speed**: Benchmark on your own hardware using `python tools/detection.py --source <image>`!!! note "Fixed Input Size"All YOLOv5-Face models use a fixed input size of 640Γ640.diff --git a/docs/modules/attributes.md b/docs/modules/attributes.mdindex 87dfd76..f726f26 100644--- a/docs/modules/attributes.md+++ b/docs/modules/attributes.md@@ -125,7 +125,7 @@ from uniface.attribute import Emotionfrom uniface.constants import DDAMFNWeightsdetector = RetinaFace()-emotion = Emotion(model_name=DDAMFNWeights.AFFECNET7)+emotion = Emotion(model_weights=DDAMFNWeights.AFFECNET7)faces = detector.detect(image)@@ -169,10 +169,10 @@ from uniface.attribute import Emotionfrom uniface.constants import DDAMFNWeights# 7-class emotion-emotion = Emotion(model_name=DDAMFNWeights.AFFECNET7)+emotion = Emotion(model_weights=DDAMFNWeights.AFFECNET7)# 8-class emotion-emotion = Emotion(model_name=DDAMFNWeights.AFFECNET8)+emotion = Emotion(model_weights=DDAMFNWeights.AFFECNET8)```---@@ -206,12 +206,11 @@ for face in faces:### Using FaceAnalyzer```python-from uniface import FaceAnalyzer+from uniface import FaceAnalyzer, RetinaFace, AgeGenderanalyzer = FaceAnalyzer(- detect=True,- recognize=False,- attributes=True # Uses AgeGender+ RetinaFace(),+ age_gender=AgeGender(),)faces = analyzer.analyze(image)diff --git a/docs/modules/detection.md b/docs/modules/detection.mdindex ec276fb..1475333 100644--- a/docs/modules/detection.md+++ b/docs/modules/detection.md@@ -296,7 +296,7 @@ cv2.imwrite("result.jpg", image)Benchmark on your hardware:```bash-python tools/detection.py --source image.jpg --iterations 100+python tools/detection.py --source image.jpg```---diff --git a/docs/modules/parsing.md b/docs/modules/parsing.mdindex be07d6b..80fc7c5 100644--- a/docs/modules/parsing.md+++ b/docs/modules/parsing.md@@ -46,16 +46,16 @@ cv2.imwrite("parsed.jpg", vis_bgr)| ID | Class | ID | Class ||----|-------|----|-------|-| 0 | Background | 10 | Ear Ring |-| 1 | Skin | 11 | Nose |-| 2 | Left Eyebrow | 12 | Mouth |-| 3 | Right Eyebrow | 13 | Upper Lip |-| 4 | Left Eye | 14 | Lower Lip |-| 5 | Right Eye | 15 | Neck |-| 6 | Eye Glasses | 16 | Neck Lace |-| 7 | Left Ear | 17 | Cloth |-| 8 | Right Ear | 18 | Hair |-| 9 | Hat | | |+| 0 | Background | 10 | Nose |+| 1 | Skin | 11 | Mouth |+| 2 | Left Eyebrow | 12 | Upper Lip |+| 3 | Right Eyebrow | 13 | Lower Lip |+| 4 | Left Eye | 14 | Neck |+| 5 | Right Eye | 15 | Necklace |+| 6 | Eyeglasses | 16 | Cloth |+| 7 | Left Ear | 17 | Hair |+| 8 | Right Ear | 18 | Hat |+| 9 | Earring | | |---@@ -126,7 +126,7 @@ mask = parser.parse(face_image)# Extract specific componentSKIN = 1-HAIR = 18+HAIR = 17LEFT_EYE = 4RIGHT_EYE = 5@@ -149,10 +149,10 @@ mask = parser.parse(face_image)component_names = {0: 'Background', 1: 'Skin', 2: 'L-Eyebrow', 3: 'R-Eyebrow',- 4: 'L-Eye', 5: 'R-Eye', 6: 'Glasses', 7: 'L-Ear', 8: 'R-Ear',- 9: 'Hat', 10: 'Earring', 11: 'Nose', 12: 'Mouth',- 13: 'U-Lip', 14: 'L-Lip', 15: 'Neck', 16: 'Necklace',- 17: 'Cloth', 18: 'Hair'+ 4: 'L-Eye', 5: 'R-Eye', 6: 'Eyeglasses', 7: 'L-Ear', 8: 'R-Ear',+ 9: 'Earring', 10: 'Nose', 11: 'Mouth',+ 12: 'U-Lip', 13: 'L-Lip', 14: 'Neck', 15: 'Necklace',+ 16: 'Cloth', 17: 'Hair', 18: 'Hat'}for class_id in np.unique(mask):@@ -219,7 +219,7 @@ def replace_background(image, mask, background):```pythondef get_hair_mask(mask):"""Extract clean hair mask."""- hair_mask = (mask == 18).astype(np.uint8) * 255+ hair_mask = (mask == 17).astype(np.uint8) * 255# Clean up with morphological operationskernel = np.ones((5, 5), np.uint8)diff --git a/docs/modules/privacy.md b/docs/modules/privacy.mdindex 3130eef..1cf31cc 100644--- a/docs/modules/privacy.md+++ b/docs/modules/privacy.md@@ -64,7 +64,7 @@ blurrer = BlurFace(method='pixelate', pixel_blocks=10)| Parameter | Default | Description ||-----------|---------|-------------|-| `pixel_blocks` | 10 | Number of blocks (lower = more pixelated) |+| `pixel_blocks` | 15 | Number of blocks (lower = more pixelated) |### Gaussiandiff --git a/docs/modules/spoofing.md b/docs/modules/spoofing.mdindex d420599..2f3be90 100644--- a/docs/modules/spoofing.md+++ b/docs/modules/spoofing.md@@ -69,20 +69,21 @@ spoofer = MiniFASNet(model_name=MiniFASNetWeights.V1SE)## Confidence Thresholds-The default threshold is 0.5. Adjust for your use case:+`result.is_real` is based on the model's top predicted class (argmax). If you want stricter behavior,+apply your own confidence threshold:```pythonresult = spoofer.predict(image, face.bbox)# High security (fewer false accepts)HIGH_THRESHOLD = 0.7-if result.confidence > HIGH_THRESHOLD:+if result.is_real and result.confidence > HIGH_THRESHOLD:print("Real (high confidence)")else:print("Suspicious")-# Balanced-if result.is_real: # Uses default 0.5 threshold+# Balanced (argmax decision)+if result.is_real:print("Real")else:print("Fake")diff --git a/docs/recipes/custom-models.md b/docs/recipes/custom-models.mdindex 4158300..94cce5b 100644--- a/docs/recipes/custom-models.md+++ b/docs/recipes/custom-models.md@@ -27,29 +27,29 @@ import numpy as npclass MyDetector(BaseDetector):def __init__(self, model_path: str, confidence_threshold: float = 0.5):+ super().__init__(confidence_threshold=confidence_threshold)self.session = create_onnx_session(model_path)self.threshold = confidence_threshold+ def preprocess(self, image: np.ndarray) -> np.ndarray:+ # Your preprocessing logic+ # e.g., resize, normalize, transpose+ raise NotImplementedError++ def postprocess(self, outputs, shape) -> list[Face]:+ # Your postprocessing logic+ # e.g., decode boxes, apply NMS, create Face objects+ raise NotImplementedError+def detect(self, image: np.ndarray) -> list[Face]:# 1. Preprocess image- input_tensor = self._preprocess(image)+ input_tensor = self.preprocess(image)# 2. Run inferenceoutputs = self.session.run(None, {'input': input_tensor})# 3. Postprocess outputs to Face objects- faces = self._postprocess(outputs, image.shape)- return faces-- def _preprocess(self, image):- # Your preprocessing logic- # e.g., resize, normalize, transpose- pass-- def _postprocess(self, outputs, shape):- # Your postprocessing logic- # e.g., decode boxes, apply NMS, create Face objects- pass+ return self.postprocess(outputs, image.shape)```---@@ -57,36 +57,14 @@ class MyDetector(BaseDetector):## Add Custom Recognition Model```python-from uniface.recognition.base import BaseRecognizer-from uniface.onnx_utils import create_onnx_session-from uniface import face_alignment-import numpy as np+from uniface.recognition.base import BaseRecognizer, PreprocessConfigclass MyRecognizer(BaseRecognizer):- def __init__(self, model_path: str):- self.session = create_onnx_session(model_path)+ 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)- def get_normalized_embedding(- self,- image: np.ndarray,- landmarks: np.ndarray- ) -> np.ndarray:- # 1. Align face- aligned = face_alignment(image, landmarks)-- # 2. Preprocess- input_tensor = self._preprocess(aligned)-- # 3. Run inference- embedding = self.session.run(None, {'input': input_tensor})[0]-- # 4. Normalize- embedding = embedding / np.linalg.norm(embedding)- return embedding-- def _preprocess(self, image):- # Your preprocessing logic- pass+ # Optional: override preprocess() if your model expects custom normalization.```---diff --git a/docs/recipes/image-pipeline.md b/docs/recipes/image-pipeline.mdindex b80dbc1..538d626 100644--- a/docs/recipes/image-pipeline.md+++ b/docs/recipes/image-pipeline.md@@ -67,14 +67,18 @@ cv2.imwrite("result.jpg", result_image)For convenience, use the built-in `FaceAnalyzer`:```python-from uniface import FaceAnalyzer+from uniface import FaceAnalyzer, RetinaFace, ArcFace, AgeGenderimport cv2# Initialize with desired modules+detector = RetinaFace()+recognizer = ArcFace()+age_gender = AgeGender()+analyzer = FaceAnalyzer(- detect=True,- recognize=True,- attributes=True+ detector,+ recognizer=recognizer,+ age_gender=age_gender,)# Process image