chore: Change import order and style changes by Ruff

This commit is contained in:
yakhyo
2025-11-25 23:35:00 +09:00
parent 1ccc4f6b77
commit 15947eb605
19 changed files with 67 additions and 58 deletions

View File

@@ -22,6 +22,7 @@ from uniface.model_store import verify_model_weights
from uniface.visualization import draw_detections from uniface.visualization import draw_detections
from .attribute import AgeGender from .attribute import AgeGender
try: try:
from .attribute import Emotion from .attribute import Emotion
except ImportError: except ImportError:

View File

@@ -2,7 +2,8 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
from typing import Dict, Any, List, Union from typing import Any, Dict, List, Union
import numpy as np import numpy as np
from uniface.attribute.age_gender import AgeGender from uniface.attribute.age_gender import AgeGender

View File

@@ -4,6 +4,7 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import Any from typing import Any
import numpy as np import numpy as np

View File

@@ -2,15 +2,16 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
from typing import List, Tuple, Union
import cv2 import cv2
import torch
import numpy as np import numpy as np
from typing import Tuple, Union, List import torch
from uniface.attribute.base import Attribute from uniface.attribute.base import Attribute
from uniface.log import Logger
from uniface.constants import DDAMFNWeights from uniface.constants import DDAMFNWeights
from uniface.face_utils import face_alignment from uniface.face_utils import face_alignment
from uniface.log import Logger
from uniface.model_store import verify_model_weights from uniface.model_store import verify_model_weights
__all__ = ["Emotion"] __all__ = ["Emotion"]
@@ -77,7 +78,7 @@ class Emotion(Attribute):
torch.Tensor: The preprocessed image tensor ready for inference. torch.Tensor: The preprocessed image tensor ready for inference.
""" """
landmark = np.asarray(landmark) landmark = np.asarray(landmark)
aligned_image, _ = face_alignment(image, landmark) aligned_image, _ = face_alignment(image, landmark)
# Convert BGR to RGB, resize, normalize, and convert to a CHW tensor # Convert BGR to RGB, resize, normalize, and convert to a CHW tensor
@@ -151,7 +152,7 @@ if __name__ == "__main__":
# Predict attributes using the landmark # Predict attributes using the landmark
emotion, confidence = emotion_predictor.predict(frame, landmark) emotion, confidence = emotion_predictor.predict(frame, landmark)
# Prepare text and draw on the frame # Prepare text and draw on the frame
label = f"{emotion} ({confidence:.2f})" label = f"{emotion} ({confidence:.2f})"
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2) cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)
@@ -167,4 +168,4 @@ if __name__ == "__main__":
# Release resources # Release resources
cap.release() cap.release()
cv2.destroyAllWindows() cv2.destroyAllWindows()
print("Inference stopped.") print("Inference stopped.")

View File

@@ -2,12 +2,12 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
import cv2
import math
import itertools import itertools
import numpy as np import math
from typing import List, Tuple
from typing import Tuple, List import cv2
import numpy as np
def resize_image(frame, target_shape: Tuple[int, int] = (640, 640)) -> Tuple[np.ndarray, float]: def resize_image(frame, target_shape: Tuple[int, int] = (640, 640)) -> Tuple[np.ndarray, float]:

View File

@@ -5,6 +5,7 @@
from enum import Enum from enum import Enum
from typing import Dict from typing import Dict
# fmt: off # fmt: off
class SphereFaceWeights(str, Enum): class SphereFaceWeights(str, Enum):
""" """

View File

@@ -3,12 +3,13 @@
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
import numpy as np from typing import Any, Dict, List
from typing import Tuple, Dict, Any, List
import numpy as np
from .scrfd import SCRFD
from .base import BaseDetector from .base import BaseDetector
from .retinaface import RetinaFace from .retinaface import RetinaFace
from .scrfd import SCRFD
# Global cache for detector instances # Global cache for detector instances
_detector_cache: Dict[str, BaseDetector] = {} _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']}") ... print(f"BBox: {face['bbox']}")
""" """
method_name = method.lower() method_name = method.lower()
sorted_kwargs = sorted(kwargs.items()) sorted_kwargs = sorted(kwargs.items())
cache_key = f"{method_name}_{str(sorted_kwargs)}" cache_key = f"{method_name}_{str(sorted_kwargs)}"

View File

@@ -6,9 +6,10 @@
Base classes for face detection. Base classes for face detection.
""" """
import numpy as np
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import Tuple, Dict, Any from typing import Any, Dict, Tuple
import numpy as np
class BaseDetector(ABC): class BaseDetector(ABC):

View File

@@ -2,23 +2,17 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
from typing import Any, Dict, List, Literal, Tuple
import numpy as np import numpy as np
from typing import Tuple, List, Literal, Dict, Any from uniface.constants import RetinaFaceWeights
from uniface.log import Logger from uniface.log import Logger
from uniface.model_store import verify_model_weights from uniface.model_store import verify_model_weights
from uniface.constants import RetinaFaceWeights
from uniface.onnx_utils import create_onnx_session from uniface.onnx_utils import create_onnx_session
from .base import BaseDetector from .base import BaseDetector
from .utils import ( from .utils import decode_boxes, decode_landmarks, generate_anchors, non_max_supression, resize_image
non_max_supression,
resize_image,
decode_boxes,
generate_anchors,
decode_landmarks
)
class RetinaFace(BaseDetector): class RetinaFace(BaseDetector):

View File

@@ -2,12 +2,12 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
import cv2
import math
import itertools import itertools
import numpy as np import math
from typing import List, Tuple
from typing import Tuple, List import cv2
import numpy as np
def resize_image(frame, target_shape: Tuple[int, int] = (640, 640)) -> Tuple[np.ndarray, float]: def resize_image(frame, target_shape: Tuple[int, int] = (640, 640)) -> Tuple[np.ndarray, float]:

View File

@@ -2,11 +2,11 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
from typing import Tuple, Union
import cv2 import cv2
import numpy as np import numpy as np
from skimage.transform import SimilarityTransform from skimage.transform import SimilarityTransform
from typing import Tuple, Union
__all__ = ["face_alignment", "compute_similarity", "bbox_center_alignment", "transform_points_2d"] __all__ = ["face_alignment", "compute_similarity", "bbox_center_alignment", "transform_points_2d"]

View File

@@ -2,8 +2,8 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
from .models import Landmark106
from .base import BaseLandmarker from .base import BaseLandmarker
from .models import Landmark106
def create_landmarker(method: str = '2d106det', **kwargs) -> BaseLandmarker: def create_landmarker(method: str = '2d106det', **kwargs) -> BaseLandmarker:

View File

@@ -3,6 +3,7 @@
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
import numpy as np import numpy as np

View File

@@ -2,15 +2,17 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
import cv2
import numpy as np
from typing import Tuple from typing import Tuple
from uniface.log import Logger import cv2
import numpy as np
from uniface.constants import LandmarkWeights from uniface.constants import LandmarkWeights
from uniface.model_store import verify_model_weights
from uniface.face_utils import bbox_center_alignment, transform_points_2d from uniface.face_utils import bbox_center_alignment, transform_points_2d
from uniface.log import Logger
from uniface.model_store import verify_model_weights
from uniface.onnx_utils import create_onnx_session from uniface.onnx_utils import create_onnx_session
from .base import BaseLandmarker from .base import BaseLandmarker
__all__ = ['Landmark'] __all__ = ['Landmark']

View File

@@ -2,14 +2,14 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
import os
import hashlib import hashlib
import os
import requests import requests
from tqdm import tqdm from tqdm import tqdm
from uniface.log import Logger
import uniface.constants as const import uniface.constants as const
from uniface.log import Logger
__all__ = ['verify_model_weights'] __all__ = ['verify_model_weights']

View File

@@ -2,12 +2,12 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # 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
def create_recognizer(method: str = 'arcface', **kwargs) -> BaseRecognizer: from .base import BaseRecognizer
from .models import ArcFace, MobileFace, SphereFace
def create_recognizer(method: str = "arcface", **kwargs) -> BaseRecognizer:
""" """
Factory function to create face recognizers. Factory function to create face recognizers.
@@ -44,20 +44,21 @@ def create_recognizer(method: str = 'arcface', **kwargs) -> BaseRecognizer:
""" """
method = method.lower() method = method.lower()
if method == 'arcface': if method == "arcface":
return ArcFace(**kwargs) return ArcFace(**kwargs)
elif method == 'mobileface': elif method == "mobileface":
return MobileFace(**kwargs) return MobileFace(**kwargs)
elif method == 'sphereface': elif method == "sphereface":
return SphereFace(**kwargs) return SphereFace(**kwargs)
else: else:
available = ['arcface', 'mobileface', 'sphereface'] available = ["arcface", "mobileface", "sphereface"]
raise ValueError(f"Unsupported method: '{method}'. Available: {available}") raise ValueError(f"Unsupported method: '{method}'. Available: {available}")
__all__ = [ __all__ = [
"create_recognizer", "create_recognizer",
"ArcFace", "ArcFace",
"MobileFace", "MobileFace",
"SphereFace", "SphereFace",
"BaseRecognizer", "BaseRecognizer",
] ]

View File

@@ -3,13 +3,14 @@
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import List, Tuple, Union
import cv2 import cv2
import numpy as np import numpy as np
from dataclasses import dataclass
from typing import Tuple, Union, List
from uniface.log import Logger
from uniface.face_utils import face_alignment from uniface.face_utils import face_alignment
from uniface.log import Logger
from uniface.onnx_utils import create_onnx_session from uniface.onnx_utils import create_onnx_session

View File

@@ -6,6 +6,7 @@ from typing import Optional
from uniface.constants import ArcFaceWeights, MobileFaceWeights, SphereFaceWeights from uniface.constants import ArcFaceWeights, MobileFaceWeights, SphereFaceWeights
from uniface.model_store import verify_model_weights from uniface.model_store import verify_model_weights
from .base import BaseRecognizer, PreprocessConfig from .base import BaseRecognizer, PreprocessConfig
__all__ = ["ArcFace", "MobileFace", "SphereFace"] __all__ = ["ArcFace", "MobileFace", "SphereFace"]

View File

@@ -2,9 +2,10 @@
# Author: Yakhyokhuja Valikhujaev # Author: Yakhyokhuja Valikhujaev
# GitHub: https://github.com/yakhyo # GitHub: https://github.com/yakhyo
from typing import List, Union
import cv2 import cv2
import numpy as np import numpy as np
from typing import List, Union
def draw_detections( def draw_detections(
@@ -12,7 +13,7 @@ def draw_detections(
bboxes: Union[np.ndarray, List[List[float]]], bboxes: Union[np.ndarray, List[List[float]]],
scores: Union[np.ndarray, List[float]], scores: Union[np.ndarray, List[float]],
landmarks: Union[np.ndarray, List[List[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. 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) cv2.rectangle(image, tuple(bbox[:2]), tuple(bbox[2:]), (0, 0, 255), thickness)
# Draw score # Draw score
cv2.putText(image, f"{score:.2f}", (bbox[0], bbox[1] - 10), cv2.putText(
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), thickness) image, f"{score:.2f}", (bbox[0], bbox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), thickness
)
# Draw landmarks # Draw landmarks
for j, point in enumerate(landmark_set): for j, point in enumerate(landmark_set):