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
chore: Change import order and style changes by Ruff
yakhyo15947eb6053d
diff --git a/uniface/__init__.py b/uniface/__init__.pyindex b494472..1e2a2d8 100644--- a/uniface/__init__.py+++ b/uniface/__init__.py@@ -22,6 +22,7 @@ from uniface.model_store import verify_model_weightsfrom uniface.visualization import draw_detectionsfrom .attribute import AgeGender+try:from .attribute import Emotionexcept ImportError:diff --git a/uniface/attribute/__init__.py b/uniface/attribute/__init__.pyindex 62bb82d..24e9bb7 100644--- a/uniface/attribute/__init__.py+++ b/uniface/attribute/__init__.py@@ -2,7 +2,8 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-from typing import Dict, Any, List, Union+from typing import Any, Dict, List, Union+import numpy as npfrom uniface.attribute.age_gender import AgeGenderdiff --git a/uniface/attribute/base.py b/uniface/attribute/base.pyindex f3697da..33b548a 100644--- a/uniface/attribute/base.py+++ b/uniface/attribute/base.py@@ -4,6 +4,7 @@from abc import ABC, abstractmethodfrom typing import Any+import numpy as npdiff --git a/uniface/attribute/emotion.py b/uniface/attribute/emotion.pyindex 8602b60..b82ffb8 100644--- a/uniface/attribute/emotion.py+++ b/uniface/attribute/emotion.py@@ -2,15 +2,16 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo+from typing import List, Tuple, Union+import cv2-import torchimport numpy as np-from typing import Tuple, Union, List+import torchfrom uniface.attribute.base import Attribute-from uniface.log import Loggerfrom uniface.constants import DDAMFNWeightsfrom uniface.face_utils import face_alignment+from uniface.log import Loggerfrom uniface.model_store import verify_model_weights__all__ = ["Emotion"]@@ -77,7 +78,7 @@ class Emotion(Attribute):torch.Tensor: The preprocessed image tensor ready for inference."""landmark = np.asarray(landmark)-+aligned_image, _ = face_alignment(image, landmark)# Convert BGR to RGB, resize, normalize, and convert to a CHW tensor@@ -151,7 +152,7 @@ if __name__ == "__main__":# Predict attributes using the landmarkemotion, confidence = emotion_predictor.predict(frame, landmark)-+# Prepare text and draw on the framelabel = f"{emotion} ({confidence:.2f})"cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)@@ -167,4 +168,4 @@ if __name__ == "__main__":# Release resourcescap.release()cv2.destroyAllWindows()- print("Inference stopped.")\ No newline at end of file+ print("Inference stopped.")diff --git a/uniface/common.py b/uniface/common.pyindex 9133203..4c3064c 100644--- a/uniface/common.py+++ b/uniface/common.py@@ -2,12 +2,12 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-import cv2-import mathimport itertools-import numpy as np+import math+from typing import List, Tuple-from typing import Tuple, List+import cv2+import numpy as npdef resize_image(frame, target_shape: Tuple[int, int] = (640, 640)) -> Tuple[np.ndarray, float]:diff --git a/uniface/constants.py b/uniface/constants.pyindex de6b806..dcd4857 100644--- a/uniface/constants.py+++ b/uniface/constants.py@@ -5,6 +5,7 @@from enum import Enumfrom typing import Dict+# fmt: offclass SphereFaceWeights(str, Enum):"""diff --git a/uniface/detection/__init__.py b/uniface/detection/__init__.pyindex 95ce09d..24be71c 100644--- a/uniface/detection/__init__.py+++ b/uniface/detection/__init__.py@@ -3,12 +3,13 @@# GitHub: https://github.com/yakhyo+from typing import Any, Dict, List+import numpy as np-from typing import Tuple, Dict, Any, List-from .scrfd import SCRFDfrom .base import BaseDetectorfrom .retinaface import RetinaFace+from .scrfd import SCRFD# Global cache for detector instances_detector_cache: Dict[str, BaseDetector] = {}@@ -38,7 +39,7 @@ def detect_faces(image: np.ndarray, method: str = 'retinaface', **kwargs) -> Lis... print(f"BBox: {face['bbox']}")"""method_name = method.lower()-+sorted_kwargs = sorted(kwargs.items())cache_key = f"{method_name}_{str(sorted_kwargs)}"diff --git a/uniface/detection/base.py b/uniface/detection/base.pyindex 509a06d..18f3893 100644--- a/uniface/detection/base.py+++ b/uniface/detection/base.py@@ -6,9 +6,10 @@Base classes for face detection."""-import numpy as npfrom abc import ABC, abstractmethod-from typing import Tuple, Dict, Any+from typing import Any, Dict, Tuple++import numpy as npclass BaseDetector(ABC):diff --git a/uniface/detection/retinaface.py b/uniface/detection/retinaface.pyindex 659c0e4..f1fcbef 100644--- a/uniface/detection/retinaface.py+++ b/uniface/detection/retinaface.py@@ -2,23 +2,17 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-import numpy as np+from typing import Any, Dict, List, Literal, Tuple-from typing import Tuple, List, Literal, Dict, Any+import numpy as np+from uniface.constants import RetinaFaceWeightsfrom uniface.log import Loggerfrom uniface.model_store import verify_model_weights-from uniface.constants import RetinaFaceWeightsfrom uniface.onnx_utils import create_onnx_sessionfrom .base import BaseDetector-from .utils import (- non_max_supression,- resize_image,- decode_boxes,- generate_anchors,- decode_landmarks-)+from .utils import decode_boxes, decode_landmarks, generate_anchors, non_max_supression, resize_imageclass RetinaFace(BaseDetector):diff --git a/uniface/detection/utils.py b/uniface/detection/utils.pyindex f93eeca..af89c43 100644--- a/uniface/detection/utils.py+++ b/uniface/detection/utils.py@@ -2,12 +2,12 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-import cv2-import mathimport itertools-import numpy as np+import math+from typing import List, Tuple-from typing import Tuple, List+import cv2+import numpy as npdef resize_image(frame, target_shape: Tuple[int, int] = (640, 640)) -> Tuple[np.ndarray, float]:diff --git a/uniface/face_utils.py b/uniface/face_utils.pyindex d50a95d..6e5a357 100644--- a/uniface/face_utils.py+++ b/uniface/face_utils.py@@ -2,11 +2,11 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo+from typing import Tuple, Union+import cv2import numpy as npfrom skimage.transform import SimilarityTransform-from typing import Tuple, Union-__all__ = ["face_alignment", "compute_similarity", "bbox_center_alignment", "transform_points_2d"]diff --git a/uniface/landmark/__init__.py b/uniface/landmark/__init__.pyindex fcc3953..ad81c70 100644--- a/uniface/landmark/__init__.py+++ b/uniface/landmark/__init__.py@@ -2,8 +2,8 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-from .models import Landmark106from .base import BaseLandmarker+from .models import Landmark106def create_landmarker(method: str = '2d106det', **kwargs) -> BaseLandmarker:diff --git a/uniface/landmark/base.py b/uniface/landmark/base.pyindex ade7710..98e30f4 100644--- a/uniface/landmark/base.py+++ b/uniface/landmark/base.py@@ -3,6 +3,7 @@# GitHub: https://github.com/yakhyofrom abc import ABC, abstractmethod+import numpy as npdiff --git a/uniface/landmark/models.py b/uniface/landmark/models.pyindex 40c3cf8..a31c592 100644--- a/uniface/landmark/models.py+++ b/uniface/landmark/models.py@@ -2,15 +2,17 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo+from typing import Tuple+import cv2import numpy as np-from typing import Tuple-from uniface.log import Loggerfrom uniface.constants import LandmarkWeights-from uniface.model_store import verify_model_weightsfrom uniface.face_utils import bbox_center_alignment, transform_points_2d+from uniface.log import Logger+from uniface.model_store import verify_model_weightsfrom uniface.onnx_utils import create_onnx_session+from .base import BaseLandmarker__all__ = ['Landmark']diff --git a/uniface/model_store.py b/uniface/model_store.pyindex 615c850..8d0a02a 100644--- a/uniface/model_store.py+++ b/uniface/model_store.py@@ -2,14 +2,14 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-import osimport hashlib+import os+import requestsfrom tqdm import tqdm-from uniface.log import Loggerimport uniface.constants as const-+from uniface.log import Logger__all__ = ['verify_model_weights']diff --git a/uniface/recognition/__init__.py b/uniface/recognition/__init__.pyindex 9f13e32..6de7fcd 100644--- a/uniface/recognition/__init__.py+++ b/uniface/recognition/__init__.py@@ -2,12 +2,12 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo-from typing import Dict-from .models import ArcFace, MobileFace, SphereFace+from .base import BaseRecognizer-from uniface.constants import ArcFaceWeights, MobileFaceWeights, SphereFaceWeights+from .models import ArcFace, MobileFace, SphereFace-def create_recognizer(method: str = 'arcface', **kwargs) -> BaseRecognizer:++def create_recognizer(method: str = "arcface", **kwargs) -> BaseRecognizer:"""Factory function to create face recognizers.@@ -44,20 +44,21 @@ def create_recognizer(method: str = 'arcface', **kwargs) -> BaseRecognizer:"""method = method.lower()- if method == 'arcface':+ if method == "arcface":return ArcFace(**kwargs)- elif method == 'mobileface':+ elif method == "mobileface":return MobileFace(**kwargs)- elif method == 'sphereface':+ elif method == "sphereface":return SphereFace(**kwargs)else:- available = ['arcface', 'mobileface', 'sphereface']+ available = ["arcface", "mobileface", "sphereface"]raise ValueError(f"Unsupported method: '{method}'. Available: {available}")+__all__ = ["create_recognizer","ArcFace","MobileFace","SphereFace","BaseRecognizer",-]\ No newline at end of file+]diff --git a/uniface/recognition/base.py b/uniface/recognition/base.pyindex e38cbca..2829e30 100644--- a/uniface/recognition/base.py+++ b/uniface/recognition/base.py@@ -3,13 +3,14 @@# GitHub: https://github.com/yakhyofrom abc import ABC, abstractmethod+from dataclasses import dataclass+from typing import List, Tuple, Union+import cv2import numpy as np-from dataclasses import dataclass-from typing import Tuple, Union, List-from uniface.log import Loggerfrom uniface.face_utils import face_alignment+from uniface.log import Loggerfrom uniface.onnx_utils import create_onnx_sessiondiff --git a/uniface/recognition/models.py b/uniface/recognition/models.pyindex e1e0e3c..58aed89 100644--- a/uniface/recognition/models.py+++ b/uniface/recognition/models.py@@ -6,6 +6,7 @@ from typing import Optionalfrom uniface.constants import ArcFaceWeights, MobileFaceWeights, SphereFaceWeightsfrom uniface.model_store import verify_model_weights+from .base import BaseRecognizer, PreprocessConfig__all__ = ["ArcFace", "MobileFace", "SphereFace"]diff --git a/uniface/visualization.py b/uniface/visualization.pyindex d7a8068..2a5f192 100644--- a/uniface/visualization.py+++ b/uniface/visualization.py@@ -2,9 +2,10 @@# Author: Yakhyokhuja Valikhujaev# GitHub: https://github.com/yakhyo+from typing import List, Union+import cv2import numpy as np-from typing import List, Uniondef draw_detections(@@ -12,7 +13,7 @@ def draw_detections(bboxes: Union[np.ndarray, List[List[float]]],scores: Union[np.ndarray, List[float]],landmarks: Union[np.ndarray, List[List[List[float]]]],- vis_threshold: float = 0.6+ vis_threshold: float = 0.6,):"""Draws bounding boxes, scores, and landmarks from separate lists onto an image.@@ -42,8 +43,9 @@ def draw_detections(cv2.rectangle(image, tuple(bbox[:2]), tuple(bbox[2:]), (0, 0, 255), thickness)# Draw score- cv2.putText(image, f"{score:.2f}", (bbox[0], bbox[1] - 10),- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), thickness)+ cv2.putText(+ image, f"{score:.2f}", (bbox[0], bbox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), thickness+ )# Draw landmarksfor j, point in enumerate(landmark_set):