Skip to content

UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.

feat: Deprecate factory function and pre-commit update (#121)

Yakhyokhuja Valikhujaev5af87dcd56de
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 9f2df4e..fe45338 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -42,6 +42,12 @@ repos:
additional_dependencies: ['bandit[toml]']
exclude: ^tests/
+ # Keep uv.lock in sync with pyproject.toml
+ - repo: https://github.com/astral-sh/uv-pre-commit
+ rev: 0.9.0
+ hooks:
+ - id: uv-lock
+
# Configuration
ci:
autofix_commit_msg: 'style: auto-fix by pre-commit hooks'
diff --git a/docs/concepts/overview.md b/docs/concepts/overview.md
index 8f42309..d67115b 100644
--- a/docs/concepts/overview.md
+++ b/docs/concepts/overview.md
@@ -86,17 +86,14 @@ tqdm # Progress bars
### 3. Simple API
-Factory functions and direct instantiation:
+Direct class instantiation:
```python
-from uniface.detection import RetinaFace
+from uniface.detection import RetinaFace, SCRFD
detector = RetinaFace()
-
-# Or via factory function
-from uniface.detection import create_detector
-
-detector = create_detector('retinaface')
+# or
+detector = SCRFD()
```
### 4. Type Safety
diff --git a/docs/modules/attributes.md b/docs/modules/attributes.md
index c947ead..e4afb20 100644
--- a/docs/modules/attributes.md
+++ b/docs/modules/attributes.md
@@ -186,20 +186,16 @@ emotion = Emotion(model_name=DDAMFNWeights.AFFECNET8)
---
-## Factory Function
-
-Use `create_attribute_predictor()` for dynamic model selection:
+## Available Attribute Models
```python
-from uniface import create_attribute_predictor
+from uniface.attribute import AgeGender, Emotion, FairFace
-age_gender = create_attribute_predictor('age_gender')
-fairface = create_attribute_predictor('fairface')
-emotion = create_attribute_predictor('emotion')
+age_gender = AgeGender()
+fairface = FairFace()
+emotion = Emotion() # requires the optional `torch` dependency
```
-Available model names: `'age_gender'`, `'fairface'`, `'emotion'`.
-
---
## Combining Models
diff --git a/docs/modules/detection.md b/docs/modules/detection.md
index d28730f..c476aaa 100644
--- a/docs/modules/detection.md
+++ b/docs/modules/detection.md
@@ -225,20 +225,20 @@ detector = YOLOv8Face(
---
-## Factory Function
+## Available Detectors
-Create detectors dynamically:
+Import the detector class you need:
```python
-from uniface.detection import create_detector
+from uniface.detection import RetinaFace, SCRFD, YOLOv5Face, YOLOv8Face
-detector = create_detector('retinaface')
+detector = RetinaFace()
# or
-detector = create_detector('scrfd')
+detector = SCRFD()
# or
-detector = create_detector('yolov5face')
+detector = YOLOv5Face()
# or
-detector = create_detector('yolov8face')
+detector = YOLOv8Face()
```
---
diff --git a/docs/modules/gaze.md b/docs/modules/gaze.md
index 44d7a1c..9fb16b6 100644
--- a/docs/modules/gaze.md
+++ b/docs/modules/gaze.md
@@ -260,12 +260,12 @@ print(f"Looking: {direction}")
---
-## Factory Function
+## Available Estimators
```python
-from uniface.gaze import create_gaze_estimator
+from uniface.gaze import MobileGaze
-gaze = create_gaze_estimator() # Returns MobileGaze
+gaze = MobileGaze()
```
---
diff --git a/docs/modules/headpose.md b/docs/modules/headpose.md
index feb31e9..2ff5e46 100644
--- a/docs/modules/headpose.md
+++ b/docs/modules/headpose.md
@@ -220,12 +220,12 @@ else:
---
-## Factory Function
+## Available Estimators
```python
-from uniface.headpose import create_head_pose_estimator
+from uniface.headpose import HeadPose
-hp = create_head_pose_estimator() # Returns HeadPose
+hp = HeadPose()
```
---
diff --git a/docs/modules/landmarks.md b/docs/modules/landmarks.md
index 8ad2bbc..a0ecc9f 100644
--- a/docs/modules/landmarks.md
+++ b/docs/modules/landmarks.md
@@ -283,20 +283,20 @@ def estimate_head_pose(landmarks, image_shape):
---
-## Factory Function
+## Available Landmarkers
```python
from uniface.constants import PIPNetWeights
-from uniface.landmark import create_landmarker
+from uniface.landmark import Landmark106, PIPNet
# Default: 106-point InsightFace model
-landmarker = create_landmarker()
+landmarker = Landmark106()
# 98-point PIPNet (WFLW)
-landmarker = create_landmarker('pipnet')
+landmarker = PIPNet()
# 68-point PIPNet (300W+CelebA)
-landmarker = create_landmarker('pipnet', model_name=PIPNetWeights.DW300_CELEBA_68)
+landmarker = PIPNet(model_name=PIPNetWeights.DW300_CELEBA_68)
```
---
diff --git a/docs/modules/matting.md b/docs/modules/matting.md
index e2a6896..7bd6909 100644
--- a/docs/modules/matting.md
+++ b/docs/modules/matting.md
@@ -132,20 +132,17 @@ cv2.destroyAllWindows()
---
-## Factory Function
+## Available Matting Models
```python
-from uniface.matting import create_matting_model
from uniface.constants import MODNetWeights
+from uniface.matting import MODNet
# Default (Photographic)
-matting = create_matting_model()
-
-# With enum
-matting = create_matting_model(MODNetWeights.WEBCAM)
+matting = MODNet()
-# With string
-matting = create_matting_model("modnet_webcam")
+# Webcam variant
+matting = MODNet(model_name=MODNetWeights.WEBCAM)
```
---
diff --git a/docs/modules/parsing.md b/docs/modules/parsing.md
index f05192d..3848a46 100644
--- a/docs/modules/parsing.md
+++ b/docs/modules/parsing.md
@@ -41,13 +41,11 @@ face_image = cv2.imread("face.jpg")
mask = parser.parse(face_image)
print(f"Mask shape: {mask.shape}") # (H, W)
-# Visualize
-face_rgb = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)
-vis_result = vis_parsing_maps(face_rgb, mask, save_image=False)
+# Visualize (BGR in, BGR out — same convention as cv2)
+vis_result = vis_parsing_maps(face_image, mask, save_image=False)
# Save result
-vis_bgr = cv2.cvtColor(vis_result, cv2.COLOR_RGB2BGR)
-cv2.imwrite("parsed.jpg", vis_bgr)
+cv2.imwrite("parsed.jpg", vis_result)
```
---
@@ -113,13 +111,11 @@ for i, face in enumerate(faces):
# Parse
mask = parser.parse(face_crop)
- # Visualize
- face_rgb = cv2.cvtColor(face_crop, cv2.COLOR_BGR2RGB)
- vis_result = vis_parsing_maps(face_rgb, mask, save_image=False)
+ # Visualize (BGR in, BGR out)
+ vis_result = vis_parsing_maps(face_crop, mask, save_image=False)
# Save
- vis_bgr = cv2.cvtColor(vis_result, cv2.COLOR_RGB2BGR)
- cv2.imwrite(f"face_{i}_parsed.jpg", vis_bgr)
+ cv2.imwrite(f"face_{i}_parsed.jpg", vis_result)
```
---
@@ -242,12 +238,12 @@ def get_hair_mask(mask):
```python
from uniface.draw import vis_parsing_maps
-# Default visualization
-vis_result = vis_parsing_maps(face_rgb, mask)
+# Default visualization (BGR in, BGR out)
+vis_result = vis_parsing_maps(face_image, mask)
# With different parameters
vis_result = vis_parsing_maps(
- face_rgb,
+ face_image,
mask,
save_image=False, # Don't save to file
)
@@ -321,17 +317,17 @@ mask, face_crop, inverse_matrix = parser.parse_with_inverse(image, landmarks)
---
-## Factory Function
+## Available Parsers
```python
-from uniface.parsing import create_face_parser
from uniface.constants import ParsingWeights, XSegWeights
+from uniface.parsing import BiSeNet, XSeg
# BiSeNet (default)
-parser = create_face_parser()
+parser = BiSeNet(model_name=ParsingWeights.RESNET18)
# XSeg
-parser = create_face_parser(XSegWeights.DEFAULT)
+parser = XSeg(model_name=XSegWeights.DEFAULT)
```
---
diff --git a/docs/modules/recognition.md b/docs/modules/recognition.md
index d333b36..02ef19f 100644
--- a/docs/modules/recognition.md
+++ b/docs/modules/recognition.md
@@ -346,15 +346,16 @@ else:
---
-## Factory Function
+## Available Recognizers
```python
-from uniface.recognition import create_recognizer
+from uniface.recognition import ArcFace, AdaFace, EdgeFace, MobileFace, SphereFace
-# Available methods: 'arcface', 'adaface', 'edgeface', 'mobileface', 'sphereface'
-recognizer = create_recognizer('arcface')
-recognizer = create_recognizer('adaface')
-recognizer = create_recognizer('edgeface')
+recognizer = ArcFace()
+# or
+recognizer = AdaFace()
+# or
+recognizer = EdgeFace()
```
---
diff --git a/docs/modules/spoofing.md b/docs/modules/spoofing.md
index 5ff874c..87624d4 100644
--- a/docs/modules/spoofing.md
+++ b/docs/modules/spoofing.md
@@ -250,12 +250,12 @@ python tools/spoofing.py --source 0
---
-## Factory Function
+## Available Spoofers
```python
-from uniface.spoofing import create_spoofer
+from uniface.spoofing import MiniFASNet
-spoofer = create_spoofer() # Returns MiniFASNet
+spoofer = MiniFASNet()
```
---
diff --git a/docs/quickstart.md b/docs/quickstart.md
index 22bed52..ce586d4 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -288,9 +288,8 @@ face_image = cv2.imread("face.jpg")
# Parse face into 19 components
mask = parser.parse(face_image)
-# Visualize with overlay
-face_rgb = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)
-vis_result = vis_parsing_maps(face_rgb, mask, save_image=False)
+# Visualize with overlay (BGR in, BGR out — same convention as cv2)
+vis_result = vis_parsing_maps(face_image, mask, save_image=False)
print(f"Detected {len(np.unique(mask))} facial components")
```
diff --git a/pyproject.toml b/pyproject.toml
index 6a87391..6077b60 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -48,6 +48,7 @@ dependencies = [
"scipy>=1.7.0",
"requests>=2.28.0",
"tqdm>=4.64.0",
+ "typing_extensions>=4.5.0",
]
[project.optional-dependencies]
diff --git a/tests/test_factory.py b/tests/test_factory.py
deleted file mode 100644
index ce680af..0000000
--- a/tests/test_factory.py
+++ /dev/null
@@ -1,292 +0,0 @@
-# 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 import (
- create_attribute_predictor,
- create_detector,
- create_landmarker,
- create_recognizer,
- list_available_detectors,
-)
-from uniface.attribute import AgeGender, FairFace
-from uniface.constants import AgeGenderWeights, FairFaceWeights, RetinaFaceWeights, SCRFDWeights
-from uniface.spoofing import MiniFASNet, create_spoofer
-
-
-# create_detector tests
-def test_create_detector_retinaface():
- """
- Test creating a RetinaFace detector using factory function.
- """
- detector = create_detector('retinaface')
- assert detector is not None, 'Failed to create RetinaFace detector'
-
-
-def test_create_detector_scrfd():
- """
- Test creating a SCRFD detector using factory function.
- """
- detector = create_detector('scrfd')
- assert detector is not None, 'Failed to create SCRFD detector'
-
-
-def test_create_detector_with_config():
- """
- Test creating detector with custom configuration.
- """
- detector = create_detector(
- 'retinaface',
- model_name=RetinaFaceWeights.MNET_V2,
- confidence_threshold=0.8,
- nms_threshold=0.3,
- )
- assert detector is not None, 'Failed to create detector with custom config'
-
-
-def test_create_detector_invalid_method():
- """
- Test that invalid detector method raises an error.
- """
- with pytest.raises((ValueError, KeyError)):
- create_detector('invalid_method')
-
-
-def test_create_detector_scrfd_with_model():
- """
- Test creating SCRFD detector with specific model.
- """
- detector = create_detector('scrfd', model_name=SCRFDWeights.SCRFD_10G_KPS, confidence_threshold=0.5)
- assert detector is not None, 'Failed to create SCRFD with specific model'
-
-
-# create_recognizer tests
-def test_create_recognizer_arcface():
- """
- Test creating an ArcFace recognizer using factory function.
- """
- recognizer = create_recognizer('arcface')
- assert recognizer is not None, 'Failed to create ArcFace recognizer'
-
-
-def test_create_recognizer_mobileface():
- """
- Test creating a MobileFace recognizer using factory function.
- """
- recognizer = create_recognizer('mobileface')
- assert recognizer is not None, 'Failed to create MobileFace recognizer'
-
-
-def test_create_recognizer_sphereface():
- """
- Test creating a SphereFace recognizer using factory function.
- """
- recognizer = create_recognizer('sphereface')
- assert recognizer is not None, 'Failed to create SphereFace recognizer'
-
-
-def test_create_recognizer_edgeface():
- """Test creating an EdgeFace recognizer using factory function."""
- recognizer = create_recognizer('edgeface')
- assert recognizer is not None, 'Failed to create EdgeFace recognizer'
-
-
-def test_create_recognizer_invalid_method():
- """
- Test that invalid recognizer method raises an error.
- """
- with pytest.raises((ValueError, KeyError)):
- create_recognizer('invalid_method')
-
-
-# create_landmarker tests
-def test_create_landmarker():
- """
- Test creating a Landmark106 detector using factory function.
- """
- landmarker = create_landmarker('2d106det')
- assert landmarker is not None, 'Failed to create Landmark106 detector'
-
-
-def test_create_landmarker_default():
- """
- Test creating landmarker with default parameters.
- """
- landmarker = create_landmarker()
- assert landmarker is not None, 'Failed to create default landmarker'
-
-
-def test_create_landmarker_invalid_method():
- """
- Test that invalid landmarker method raises an error.
- """
- with pytest.raises((ValueError, KeyError)):
- create_landmarker('invalid_method')
-
-
-def test_create_landmarker_pipnet_default():
- """create_landmarker('pipnet') returns a PIPNet (98 points by default)."""
- from uniface.landmark import PIPNet
-
- landmarker = create_landmarker('pipnet')
- assert isinstance(landmarker, PIPNet), 'Should return PIPNet instance'
- assert landmarker.num_lms == 98
-
-
-def test_create_landmarker_pipnet_68():
- """create_landmarker('pipnet', model_name=...) selects the 68-point variant."""
- from uniface.constants import PIPNetWeights
- from uniface.landmark import PIPNet
-
- landmarker = create_landmarker('pipnet', model_name=PIPNetWeights.DW300_CELEBA_68)
- assert isinstance(landmarker, PIPNet), 'Should return PIPNet instance'
- assert landmarker.num_lms == 68
-
-
-# list_available_detectors tests
-def test_list_available_detectors():
- """
- Test that list_available_detectors returns a dictionary.
- """
- detectors = list_available_detectors()
-
- assert isinstance(detectors, dict), 'Should return a dictionary of detectors'
- assert len(detectors) > 0, 'Should have at least one detector available'
-
-
-def test_list_available_detectors_contents():
- """
- Test that list includes known detectors.
- """
- detectors = list_available_detectors()
-
- # Should include at least these detectors
- assert 'retinaface' in detectors, "Should include 'retinaface'"
- assert 'scrfd' in detectors, "Should include 'scrfd'"
-
-
-# Integration tests
-def test_detector_inference_from_factory():
- """
- Test that detector created from factory can perform inference.
- """
- detector = create_detector('retinaface')
- mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
-
- faces = detector.detect(mock_image)
- assert isinstance(faces, list), 'Detector should return list of faces'
-
-
-def test_recognizer_inference_from_factory():
- """
- Test that recognizer created from factory can perform inference.
- """
- recognizer = create_recognizer('arcface')
- mock_image = np.random.randint(0, 255, (112, 112, 3), dtype=np.uint8)
-
- embedding = recognizer.get_embedding(mock_image)
- assert embedding is not None, 'Recognizer should return embedding'
- assert embedding.shape == (1, 512), 'get_embedding should return (1, 512) with batch dimension'
-
-
-def test_landmarker_inference_from_factory():
- """
- Test that landmarker created from factory can perform inference.
- """
- landmarker = create_landmarker('2d106det')
- mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
- mock_bbox = [100, 100, 300, 300]
-
- landmarks = landmarker.get_landmarks(mock_image, mock_bbox)
- assert landmarks is not None, 'Landmarker should return landmarks'
- assert landmarks.shape == (106, 2), 'Should return 106 landmarks'
-
-
-def test_pipnet_landmarker_inference_from_factory():
- """PIPNet landmarker created from factory can perform inference."""
- landmarker = create_landmarker('pipnet')
- mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
- mock_bbox = [100, 100, 300, 300]
-
- landmarks = landmarker.get_landmarks(mock_image, mock_bbox)
- assert landmarks is not None, 'Landmarker should return landmarks'
- assert landmarks.shape == (98, 2), 'Should return 98 landmarks'
-
-
-def test_multiple_detector_creation():
- """
- Test that multiple detectors can be created independently.
- """
- detector1 = create_detector('retinaface')
- detector2 = create_detector('scrfd')
-
- assert detector1 is not None
- assert detector2 is not None
- assert detector1 is not detector2, 'Should create separate instances'
-
-
-def test_detector_with_different_configs():
- """
- Test creating multiple detectors with different configurations.
- """
- detector_high_thresh = create_detector('retinaface', confidence_threshold=0.9)
- detector_low_thresh = create_detector('retinaface', confidence_threshold=0.3)
-
- mock_image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
-
- faces_high = detector_high_thresh.detect(mock_image)
- faces_low = detector_low_thresh.detect(mock_image)
-
- # Both should work
- assert isinstance(faces_high, list)
- assert isinstance(faces_low, list)
-
-
-def test_factory_returns_correct_types():
- """
- Test that factory functions return instances of the correct types.
- """
- from uniface import ArcFace, Landmark106, RetinaFace
-
- detector = create_detector('retinaface')
- recognizer = create_recognizer('arcface')
- landmarker = create_landmarker('2d106det')
-
- assert isinstance(detector, RetinaFace), 'Should return RetinaFace instance'
- assert isinstance(recognizer, ArcFace), 'Should return ArcFace instance'
- assert isinstance(landmarker, Landmark106), 'Should return Landmark106 instance'
-
-
-# create_spoofer tests
-def test_create_spoofer_default():
- """Test creating a spoofer with default parameters."""
- spoofer = create_spoofer()
- assert isinstance(spoofer, MiniFASNet), 'Should return MiniFASNet instance'
-
-
-def test_create_spoofer_with_providers():
- """Test that create_spoofer forwards providers kwarg without TypeError."""
- spoofer = create_spoofer(providers=['CPUExecutionProvider'])
- assert isinstance(spoofer, MiniFASNet), 'Should return MiniFASNet instance'
-
-
-# create_attribute_predictor tests
-def test_create_attribute_predictor_age_gender():
- predictor = create_attribute_predictor(AgeGenderWeights.DEFAULT)
- assert isinstance(predictor, AgeGender), 'Should return AgeGender instance'
-
-
-def test_create_attribute_predictor_fairface():
- predictor = create_attribute_predictor(FairFaceWeights.DEFAULT)
- assert isinstance(predictor, FairFace), 'Should return FairFace instance'
-
-
-def test_create_attribute_predictor_invalid():
- with pytest.raises(ValueError, match='Unsupported attribute model'):
- create_attribute_predictor('invalid_model')
diff --git a/tests/test_headpose.py b/tests/test_headpose.py
index be5c126..01c9e54 100644
--- a/tests/test_headpose.py
+++ b/tests/test_headpose.py
@@ -8,30 +8,10 @@ from __future__ import annotations
import numpy as np
import pytest
-from uniface import HeadPose, HeadPoseResult, create_head_pose_estimator
-from uniface.headpose import BaseHeadPoseEstimator
+from uniface import HeadPose, HeadPoseResult
from uniface.headpose.models import HeadPose as HeadPoseModel
-def test_create_head_pose_estimator_default():
- """Test creating a head pose estimator with default parameters."""
- estimator = create_head_pose_estimator()
- assert isinstance(estimator, HeadPose), 'Should return HeadPose instance'
-
-
-def test_create_head_pose_estimator_aliases():
- """Test that factory accepts all documented aliases."""
- for alias in ('headpose', 'head_pose', '6drepnet'):
- estimator = create_head_pose_estimator(alias)
- assert isinstance(estimator, HeadPose), f"Alias '{alias}' should return HeadPose"
-
-
-def test_create_head_pose_estimator_invalid():
- """Test that invalid method raises ValueError."""
- with pytest.raises(ValueError, match='Unsupported head pose estimation method'):
- create_head_pose_estimator('invalid_method')
-
-
def test_head_pose_inference():
"""Test that HeadPose can run inference on a mock image."""
estimator = HeadPose()
@@ -103,12 +83,6 @@ def test_rotation_matrix_to_euler_batch():
np.testing.assert_allclose(euler, 0.0, atol=1e-5)
-def test_factory_returns_correct_type():
- """Test that factory function returns BaseHeadPoseEstimator subclass."""
- estimator = create_head_pose_estimator()
- assert isinstance(estimator, BaseHeadPoseEstimator), 'Should be BaseHeadPoseEstimator subclass'
-
-
def test_head_pose_with_providers():
"""Test that HeadPose accepts providers kwarg."""
estimator = HeadPose(providers=['CPUExecutionProvider'])
diff --git a/tests/test_matting.py b/tests/test_matting.py
index a3e7ace..6cf7582 100644
--- a/tests/test_matting.py
+++ b/tests/test_matting.py
@@ -6,10 +6,9 @@
from __future__ import annotations
import numpy as np
-import pytest
from uniface.constants import MODNetWeights
-from uniface.matting import MODNet, create_matting_model
+from uniface.matting import MODNet
def test_modnet_initialization():
@@ -122,37 +121,3 @@ def test_modnet_different_input_sizes():
assert matte.shape == (h, w), f'Failed for size {h}x{w}'
assert matte.dtype == np.float32
-
-
-# Factory tests
-
-
-def test_create_matting_model_default():
- """Test factory with default parameters."""
- matting = create_matting_model()
- assert matting is not None
- assert isinstance(matting, MODNet)
-
-
-def test_create_matting_model_with_enum():
- """Test factory with enum."""
- matting = create_matting_model(MODNetWeights.WEBCAM)
- assert isinstance(matting, MODNet)
-
-
-def test_create_matting_model_with_string():
- """Test factory with string model name."""
- matting = create_matting_model('modnet_photographic')
- assert isinstance(matting, MODNet)
-
-
-def test_create_matting_model_webcam_string():
- """Test factory with webcam string model name."""
- matting = create_matting_model('modnet_webcam')
- assert isinstance(matting, MODNet)
-
-
-def test_create_matting_model_invalid():
- """Test factory with invalid model name."""
- with pytest.raises(ValueError, match='Unknown matting model'):
- create_matting_model('invalid_model')
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index 273a740..ab24b7e 100644
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -8,8 +8,8 @@ from __future__ import annotations
import numpy as np
import pytest
-from uniface.constants import ParsingWeights, XSegWeights
-from uniface.parsing import BiSeNet, XSeg, create_face_parser
+from uniface.constants import ParsingWeights
+from uniface.parsing import BiSeNet, XSeg
def test_bisenet_initialization():
@@ -86,26 +86,6 @@ def test_bisenet_callable():
assert mask.dtype == np.uint8
-def test_create_face_parser_with_enum():
- """Test factory function with enum."""
- parser = create_face_parser(ParsingWeights.RESNET18)
- assert parser is not None
- assert isinstance(parser, BiSeNet)
-
-
-def test_create_face_parser_with_string():
- """Test factory function with string."""
- parser = create_face_parser('parsing_resnet18')
- assert parser is not None
- assert isinstance(parser, BiSeNet)
-
-
-def test_create_face_parser_invalid_model():
- """Test factory function with invalid model name."""
- with pytest.raises(ValueError, match='Unknown face parsing model'):
- create_face_parser('invalid_model')
-
-
def test_bisenet_different_input_sizes():
"""Test parsing with different input image sizes."""
parser = BiSeNet()
@@ -253,17 +233,3 @@ def test_xseg_parse_with_inverse():
assert mask.shape == (256, 256)
assert face_crop.shape == (256, 256, 3)
assert inverse_matrix.shape == (2, 3)
-
-
-def test_create_face_parser_xseg_enum():
- """Test factory function with XSeg enum."""
- parser = create_face_parser(XSegWeights.DEFAULT)
- assert parser is not None
- assert isinstance(parser, XSeg)
-
-
-def test_create_face_parser_xseg_string():
- """Test factory function with XSeg string."""
- parser = create_face_parser('xseg')
- assert parser is not None
- assert isinstance(parser, XSeg)
diff --git a/tools/faiss_search.py b/tools/faiss_search.py
index 8055b82..044ec96 100644
--- a/tools/faiss_search.py
+++ b/tools/faiss_search.py
@@ -22,7 +22,7 @@ from pathlib import Path
from _common import IMAGE_EXTENSIONS, get_source_type
import cv2
-from uniface import create_detector, create_recognizer
+from uniface import ArcFace, RetinaFace
from uniface.draw import draw_corner_bbox, draw_text_label
from uniface.stores import FAISS
@@ -117,8 +117,8 @@ def build(args: argparse.Namespace) -> None:
print(f"Error: '{faces_dir}' is not a directory")
return
- detector = create_detector()
- recognizer = create_recognizer()
+ detector = RetinaFace()
+ recognizer = ArcFace()
store = FAISS(db_path=args.db_path)
persons = sorted(p.name for p in faces_dir.iterdir() if p.is_dir())
@@ -160,8 +160,8 @@ def build(args: argparse.Namespace) -> None:
def run(args: argparse.Namespace) -> None:
- detector = create_detector()
- recognizer = create_recognizer()
+ detector = RetinaFace()
+ recognizer = ArcFace()
store = FAISS(db_path=args.db_path)
if not store.load():
diff --git a/tools/parse.py b/tools/parse.py
index bd0d873..a96f9ba 100644
--- a/tools/parse.py
+++ b/tools/parse.py
@@ -87,8 +87,7 @@ def process_image(detector, parser, image_path: str, save_dir: str = 'outputs',
mask = parser.parse(face_crop)
print(f' Face {i + 1}: parsed with {len(set(mask.flatten()))} unique classes')
- face_crop_rgb = cv2.cvtColor(face_crop, cv2.COLOR_BGR2RGB)
- vis_result = vis_parsing_maps(face_crop_rgb, mask, save_image=False)
+ vis_result = vis_parsing_maps(face_crop, mask, save_image=False)
result_image[y1:y2, x1:x2] = vis_result
cv2.rectangle(result_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
@@ -135,8 +134,7 @@ def process_video(detector, parser, video_path: str, save_dir: str = 'outputs',
continue
mask = parser.parse(face_crop)
- face_crop_rgb = cv2.cvtColor(face_crop, cv2.COLOR_BGR2RGB)
- vis_result = vis_parsing_maps(face_crop_rgb, mask, save_image=False)
+ vis_result = vis_parsing_maps(face_crop, mask, save_image=False)
frame[y1:y2, x1:x2] = vis_result
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
@@ -177,8 +175,7 @@ def run_camera(detector, parser, camera_id: int = 0, expand_ratio: float = 0.2):
continue
mask = parser.parse(face_crop)
- face_crop_rgb = cv2.cvtColor(face_crop, cv2.COLOR_BGR2RGB)
- vis_result = vis_parsing_maps(face_crop_rgb, mask, save_image=False)
+ vis_result = vis_parsing_maps(face_crop, mask, save_image=False)
frame[y1:y2, x1:x2] = vis_result
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
diff --git a/tools/search.py b/tools/search.py
index b5a9b87..9597e2a 100644
--- a/tools/search.py
+++ b/tools/search.py
@@ -22,7 +22,7 @@ from _common import get_source_type
import cv2
import numpy as np
-from uniface import create_detector, create_recognizer
+from uniface import ArcFace, RetinaFace
from uniface.draw import draw_corner_bbox, draw_text_label
from uniface.face_utils import compute_similarity
@@ -135,8 +135,8 @@ def main():
print(f'Error: Reference image not found: {args.reference}')
return
- detector = create_detector()
- recognizer = create_recognizer()
+ detector = RetinaFace()
+ recognizer = ArcFace()
print(f'Loading reference: {args.reference}')
ref_embedding = extract_reference_embedding(detector, recognizer, args.reference)
diff --git a/tools/spoofing.py b/tools/spoofing.py
index d65707d..e8f32d8 100644
--- a/tools/spoofing.py
+++ b/tools/spoofing.py
@@ -22,7 +22,7 @@ import numpy as np
from uniface.constants import MiniFASNetWeights
from uniface.detection import RetinaFace
-from uniface.spoofing import create_spoofer
+from uniface.spoofing import MiniFASNet
def draw_spoofing_result(
@@ -173,7 +173,7 @@ def main():
# Initialize models
print(f'Initializing models (MiniFASNet {args.model.upper()})...')
detector = RetinaFace()
- spoofer = create_spoofer(model_name=model_name, scale=args.scale)
+ spoofer = MiniFASNet(model_name=model_name, scale=args.scale)
source_type = get_source_type(args.source)
diff --git a/uniface/analyzer.py b/uniface/analyzer.py
index dd350e3..3f425cc 100644
--- a/uniface/analyzer.py
+++ b/uniface/analyzer.py
@@ -105,16 +105,14 @@ class FaceAnalyzer:
attr_name = attr.__class__.__name__
try:
attr.predict(image, face)
- Logger.debug(f'Face {idx + 1}: {attr_name} prediction succeeded')
except Exception as e:
Logger.warning(f'Face {idx + 1}: {attr_name} prediction failed: {e}')
- Logger.info(f'Analysis complete: {len(faces)} face(s) processed')
return faces
def __repr__(self) -> str:
parts = [f'detector={self.detector.__class__.__name__}']
- if self.recognizer:
+ 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)
diff --git a/uniface/attribute/__init__.py b/uniface/attribute/__init__.py
index 3cb1b72..be77efb 100644
--- a/uniface/attribute/__init__.py
+++ b/uniface/attribute/__init__.py
@@ -7,6 +7,7 @@ from __future__ import annotations
from typing import Any
import numpy as np
+from typing_extensions import deprecated
from uniface.attribute.age_gender import AgeGender
from uniface.attribute.base import Attribute
@@ -51,11 +52,20 @@ 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,
diff --git a/uniface/detection/__init__.py b/uniface/detection/__init__.py
index 71f0f78..051ed03 100644
--- a/uniface/detection/__init__.py
+++ b/uniface/detection/__init__.py
@@ -6,6 +6,8 @@ from __future__ import annotations
from typing import Any
+from typing_extensions import deprecated
+
from uniface.constants import (
RetinaFaceWeights,
SCRFDWeights,
@@ -20,9 +22,19 @@ from .yolov5 import YOLOv5Face
from .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)
@@ -39,17 +51,18 @@ def create_detector(method: str = 'retinaface', **kwargs: Any) -> BaseDetector:
Example:
>>> # Basic usage
- >>> detector = create_detector('retinaface')
+ >>> from uniface.detection import RetinaFace
+ >>> detector = RetinaFace()
>>> # SCRFD detector with custom parameters
+ >>> from uniface.detection import SCRFD
>>> from uniface.constants import SCRFDWeights
- >>> detector = create_detector(
- ... 'scrfd', model_name=SCRFDWeights.SCRFD_10G_KPS, confidence_threshold=0.8, input_size=(640, 640)
- ... )
+ >>> 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 = create_detector('yolov8face', model_name=YOLOv8FaceWeights.YOLOV8N, confidence_threshold=0.5)
+ >>> detector = YOLOv8Face(model_name=YOLOv8FaceWeights.YOLOV8N, confidence_threshold=0.5)
"""
method = method.lower()
@@ -70,9 +83,18 @@ def create_detector(method: str = 'retinaface', **kwargs: Any) -> BaseDetector:
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.
diff --git a/uniface/draw.py b/uniface/draw.py
index 22c8d36..7b92cdb 100644
--- a/uniface/draw.py
+++ b/uniface/draw.py
@@ -52,26 +52,28 @@ FACE_PARSING_LABELS = [
'hat',
]
-# Color palette for face parsing visualization
+# Color palette for face parsing visualization (BGR).
+# Element-reversed from the standard CelebAMask-HQ RGB palette so the visual
+# class→color mapping matches what users saw with the original implementation.
FACE_PARSING_COLORS = [
[0, 0, 0],
- [255, 85, 0],
- [255, 170, 0],
- [255, 0, 85],
- [255, 0, 170],
+ [0, 85, 255],
+ [0, 170, 255],
+ [85, 0, 255],
+ [170, 0, 255],
[0, 255, 0],
- [85, 255, 0],
- [170, 255, 0],
[0, 255, 85],
[0, 255, 170],
- [0, 0, 255],
- [85, 0, 255],
- [170, 0, 255],
- [0, 85, 255],
- [0, 170, 255],
- [255, 255, 0],
- [255, 255, 85],
- [255, 255, 170],
+ [85, 255, 0],
+ [170, 255, 0],
+ [255, 0, 0],
+ [255, 0, 85],
+ [255, 0, 170],
+ [255, 85, 0],
+ [255, 170, 0],
+ [0, 255, 255],
+ [85, 255, 255],
+ [170, 255, 255],
[255, 0, 255],
]
@@ -653,7 +655,7 @@ def vis_parsing_maps(
"""Visualize face parsing segmentation mask by overlaying colored regions.
Args:
- image: Input face image in RGB format with shape ``(H, W, 3)``.
+ image: Input face image in BGR format with shape ``(H, W, 3)``.
segmentation_mask: Segmentation mask with shape ``(H, W)`` where each
pixel value represents a facial component class (0-18).
save_image: Whether to save the visualization to disk. Defaults to False.
@@ -669,22 +671,20 @@ def vis_parsing_maps(
>>> parser = BiSeNet()
>>> face_image = cv2.imread('face.jpg')
>>> mask = parser.parse(face_image)
- >>> face_rgb = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)
- >>> result = vis_parsing_maps(face_rgb, mask)
+ >>> result = vis_parsing_maps(face_image, mask)
>>> cv2.imwrite('parsed_face.jpg', result)
"""
image = np.array(image).copy().astype(np.uint8)
segmentation_mask = segmentation_mask.copy().astype(np.uint8)
- # Create a color mask
+ # Create a color mask in BGR format
max_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_COLORS
segmentation_mask_color = palette[segmentation_mask]
- # Convert image to BGR format for blending
- bgr_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
- blended_image = cv2.addWeighted(bgr_image, 0.6, segmentation_mask_color, 0.4, 0)
+ # Blend image and color mask directly (both in BGR format)
+ blended_image = cv2.addWeighted(image, 0.6, segmentation_mask_color, 0.4, 0)
if save_image:
cv2.imwrite(save_path, blended_image, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
diff --git a/uniface/face_utils.py b/uniface/face_utils.py
index af6a01b..2f5b583 100644
--- a/uniface/face_utils.py
+++ b/uniface/face_utils.py
@@ -191,17 +191,30 @@ 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.
+
Args:
- points: An (N, 2) array of 2D points.
- transform: A (2, 3) affine transformation matrix.
+ 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 two
+ rows.
Returns:
- Transformed (N, 2) array of points.
+ Transformed ``(N, 2)`` ``float32`` array of points.
"""
- transformed = np.zeros_like(points, dtype=np.float32)
- for i in range(points.shape[0]):
- point = np.array([points[i, 0], points[i, 1], 1.0], dtype=np.float32)
- result = np.dot(transform, point)
- transformed[i] = result[:2]
+ if points.shape[0] == 0:
+ return np.empty((0, 2), dtype=np.float32)
+
+ # Standardize inputs to float32
+ points = np.ascontiguousarray(points, dtype=np.float32)
+ transform = np.ascontiguousarray(transform, dtype=np.float32)
+
+ # Append a column of ones for homogeneous coordinates (N, 3)
+ ones = np.ones((points.shape[0], 1), dtype=np.float32)
+ points_homogeneous = np.hstack([points, ones])
- return transformed
+ # Apply transformation: (N, 3) dot (3, 2) -> (N, 2)
+ return np.dot(points_homogeneous, transform.T)
diff --git a/uniface/gaze/__init__.py b/uniface/gaze/__init__.py
index 3718c50..deb89ee 100644
--- a/uniface/gaze/__init__.py
+++ b/uniface/gaze/__init__.py
@@ -2,16 +2,26 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
+from typing_extensions import deprecated
+
from uniface.types import GazeResult
from .base import BaseGazeEstimator
from .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.
@@ -32,11 +42,12 @@ def create_gaze_estimator(method: str = 'mobilegaze', **kwargs) -> BaseGazeEstim
Examples:
>>> # Create the default MobileGaze estimator (ResNet34 backbone)
- >>> estimator = create_gaze_estimator()
+ >>> from uniface.gaze import MobileGaze
+ >>> estimator = MobileGaze()
>>> # Create with MobileNetV2 backbone
>>> from uniface.constants import GazeWeights
- >>> estimator = create_gaze_estimator('mobilegaze', model_name=GazeWeights.MOBILENET_V2)
+ >>> estimator = MobileGaze(model_name=GazeWeights.MOBILENET_V2)
>>> # Use the estimator
>>> result = estimator.estimate(face_crop)
diff --git a/uniface/headpose/__init__.py b/uniface/headpose/__init__.py
index 117bf69..ff3a72a 100644
--- a/uniface/headpose/__init__.py
+++ b/uniface/headpose/__init__.py
@@ -2,16 +2,26 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
+from typing_extensions import deprecated
+
from uniface.types import HeadPoseResult
from .base import BaseHeadPoseEstimator
from .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.
@@ -31,11 +41,12 @@ def create_head_pose_estimator(method: str = 'headpose', **kwargs) -> BaseHeadPo
Examples:
>>> # Create the default head pose estimator (ResNet18 backbone)
- >>> estimator = create_head_pose_estimator()
+ >>> from uniface.headpose import HeadPose
+ >>> estimator = HeadPose()
>>> # Create with MobileNetV2 backbone
>>> from uniface.constants import HeadPoseWeights
- >>> estimator = create_head_pose_estimator('headpose', model_name=HeadPoseWeights.MOBILENET_V2)
+ >>> estimator = HeadPose(model_name=HeadPoseWeights.MOBILENET_V2)
>>> # Use the estimator
>>> result = estimator.estimate(face_crop)
diff --git a/uniface/landmark/__init__.py b/uniface/landmark/__init__.py
index c61d62e..0a525f9 100644
--- a/uniface/landmark/__init__.py
+++ b/uniface/landmark/__init__.py
@@ -2,14 +2,25 @@
# Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo
+from typing_extensions import deprecated
+
from .base import BaseLandmarker
from .models import Landmark106
from .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:
diff --git a/uniface/matting/__init__.py b/uniface/matting/__init__.py
index 53217c5..2088b1a 100644
--- a/uniface/matting/__init__.py
+++ b/uniface/matting/__init__.py
@@ -4,6 +4,8 @@
from __future__ import annotations
+from typing_extensions import deprecated
+
from uniface.constants import MODNetWeights
from .base import BaseMatting
@@ -12,12 +14,20 @@ from .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).
@@ -33,7 +43,8 @@ def create_matting_model(
ValueError: If the model_name is not recognized.
Example:
- >>> matting = create_matting_model()
+ >>> from uniface.matting import MODNet
+ >>> matting = MODNet()
>>> matte = matting.predict(image)
"""
if isinstance(model_name, MODNetWeights):
diff --git a/uniface/model_store.py b/uniface/model_store.py
index 2bd1df5..56deb25 100644
--- a/uniface/model_store.py
+++ b/uniface/model_store.py
@@ -190,7 +190,9 @@ def download_models(
Args:
model_names: List of model weight enum identifiers to download.
- max_workers: Maximum number of concurrent download threads. Defaults to 4.
+ 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.
timeout: Connection timeout in seconds. Defaults to 60.
max_retries: Maximum number of attempts per model. Defaults to 3.
@@ -198,7 +200,11 @@ def download_models(
Mapping of each model enum to its local file path.
Raises:
- RuntimeError: If any model download or verification fails.
+ TypeError: If ``max_workers`` is a ``bool`` or a non-int / non-None
+ value.
+ RuntimeError: If any model download or verification fails. The error
+ message aggregates every failure into a single multi-line message
+ of the form ``"Failed to download N model(s):\\n<name>: <err>\\n..."``.
Example:
>>> from uniface import download_models
@@ -211,13 +217,11 @@ def download_models(
if isinstance(max_workers, bool) or not isinstance(max_workers, int | None):
raise TypeError(f'max_workers must be int or None, got {type(max_workers).__name__}')
- if max_workers is None or max_workers < 1:
- if max_workers < 1:
- Logger.info(f'max_workers must be >= 1, got {max_workers}; falling back to auto mode')
- max_workers = min(os.cpu_count(), 8) # at most 8
-
- if max_workers < 1:
- raise ValueError(f'max_workers must be >= 1, got {max_workers}')
+ if max_workers is None:
+ max_workers = min(os.cpu_count() or 1, 8)
+ elif max_workers < 1:
+ Logger.info(f'max_workers must be >= 1, got {max_workers}; falling back to auto mode')
+ max_workers = min(os.cpu_count() or 1, 8)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_model = {
diff --git a/uniface/parsing/__init__.py b/uniface/parsing/__init__.py
index eb5a3cb..70ca200 100644
--- a/uniface/parsing/__init__.py
+++ b/uniface/parsing/__init__.py
@@ -4,6 +4,8 @@
from __future__ import annotations
+from typing_extensions import deprecated
+
from uniface.constants import ParsingWeights, XSegWeights
from .base import BaseFaceParser
@@ -13,12 +15,21 @@ from .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).
@@ -31,7 +42,8 @@ def create_face_parser(
ValueError: If the model_name is not recognized.
Example:
- >>> parser = create_face_parser(ParsingWeights.RESNET18)
+ >>> from uniface.parsing import BiSeNet
+ >>> parser = BiSeNet(model_name=ParsingWeights.RESNET18)
>>> mask = parser.parse(face_crop)
"""
# Handle XSegWeights
diff --git a/uniface/recognition/__init__.py b/uniface/recognition/__init__.py
index 02bb22b..0482c2f 100644
--- a/uniface/recognition/__init__.py
+++ b/uniface/recognition/__init__.py
@@ -3,6 +3,8 @@
# GitHub: https://github.com/yakhyo
+from typing_extensions import deprecated
+
from .adaface import AdaFace
from .arcface import ArcFace
from .base import BaseRecognizer
@@ -11,10 +13,20 @@ from .mobileface import MobileFace
from .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.
@@ -34,22 +46,27 @@ def create_recognizer(method: str = 'arcface', **kwargs) -> BaseRecognizer:
Examples:
>>> # Create the default ArcFace recognizer
- >>> recognizer = create_recognizer()
+ >>> from uniface.recognition import ArcFace
+ >>> recognizer = ArcFace()
>>> # Create an AdaFace recognizer
+ >>> from uniface.recognition import AdaFace
>>> from uniface.constants import AdaFaceWeights
- >>> recognizer = create_recognizer('adaface', model_name=AdaFaceWeights.IR_101)
+ >>> recognizer = AdaFace(model_name=AdaFaceWeights.IR_101)
>>> # Create a specific MobileFace recognizer
+ >>> from uniface.recognition import MobileFace
>>> from uniface.constants import MobileFaceWeights
- >>> recognizer = create_recognizer('mobileface', model_name=MobileFaceWeights.MNET_V2)
+ >>> recognizer = MobileFace(model_name=MobileFaceWeights.MNET_V2)
>>> # Create a SphereFace recognizer
- >>> recognizer = create_recognizer('sphereface')
+ >>> from uniface.recognition import SphereFace
+ >>> recognizer = SphereFace()
>>> # Create an EdgeFace recognizer
+ >>> from uniface.recognition import EdgeFace
>>> from uniface.constants import EdgeFaceWeights
- >>> recognizer = create_recognizer('edgeface', model_name=EdgeFaceWeights.XXS)
+ >>> recognizer = EdgeFace(model_name=EdgeFaceWeights.XXS)
"""
method = method.lower()
diff --git a/uniface/spoofing/__init__.py b/uniface/spoofing/__init__.py
index 625820d..85f9e8b 100644
--- a/uniface/spoofing/__init__.py
+++ b/uniface/spoofing/__init__.py
@@ -6,6 +6,8 @@ from __future__ import annotations
from typing import Any
+from typing_extensions import deprecated
+
from uniface.constants import MiniFASNetWeights
from uniface.types import SpoofingResult
@@ -21,6 +23,11 @@ __all__ = [
]
+@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,
@@ -28,6 +35,9 @@ def create_spoofer(
) -> 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.
@@ -44,8 +54,8 @@ def create_spoofer(
An initialized face anti-spoofing model.
Example:
- >>> from uniface.spoofing import create_spoofer, MiniFASNetWeights
- >>> spoofer = create_spoofer()
+ >>> 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%}')
"""
diff --git a/uv.lock b/uv.lock
index c1e548c..cd0dce1 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1666,6 +1666,7 @@ 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]
@@ -1708,6 +1709,7 @@ 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"]