"""Utilities for image processing and face detection""" import logging from typing import Optional, Tuple, List import numpy as np from PIL import Image import io import hashlib import base64 logger = logging.getLogger(__name__) class ImageUtils: """Image processing utilities""" @staticmethod def load_image_from_bytes(image_bytes: bytes) -> Image.Image: """Load PIL Image from bytes""" return Image.open(io.BytesIO(image_bytes)) @staticmethod def load_image_from_base64(base64_str: str) -> Image.Image: """Load PIL Image from base64 string""" if base64_str.startswith("data:"): base64_str = base64_str.split(",")[1] image_bytes = base64.b64decode(base64_str) return Image.open(io.BytesIO(image_bytes)) @staticmethod def image_to_bytes(image: Image.Image, format: str = "PNG") -> bytes: """Convert PIL Image to bytes""" byte_arr = io.BytesIO() image.save(byte_arr, format=format) byte_arr.seek(0) return byte_arr.getvalue() @staticmethod def compute_image_hash(image_bytes: bytes) -> str: """Compute SHA256 hash of image for duplicate detection""" return hashlib.sha256(image_bytes).hexdigest() @staticmethod def resize_image(image: Image.Image, max_size: int = 640) -> Image.Image: """Resize image while maintaining aspect ratio""" image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS) return image @staticmethod def validate_image(image_bytes: bytes, max_size_mb: int = 10) -> bool: """Validate image""" # Check file size if len(image_bytes) > max_size_mb * 1024 * 1024: logger.error(f"Image too large: {len(image_bytes)} bytes") return False try: # Try to open image Image.open(io.BytesIO(image_bytes)) return True except Exception as e: logger.error(f"Invalid image: {str(e)}") return False class FaceUtils: """Face detection and processing utilities""" # Placeholder for InsightFace initialization (will be done in service layer) _detector = None @classmethod def init_detector(cls): """Initialize InsightFace detector (lazy loading)""" if cls._detector is None: try: from insightface.app import FaceAnalysis from app.core.config import settings import onnxruntime # insightface==0.2.1: FaceAnalysis(name, root) only — no 'providers' kwarg. # GPU vs CPU is controlled via ctx_id in prepare(): # ctx_id=0 → CUDA GPU # ctx_id=-1 → CPU ctx_id = -1 # default: CPU if settings.INSIGHTFACE_GPU_AUTO: available = onnxruntime.get_available_providers() if "CUDAExecutionProvider" in available: ctx_id = 0 elif settings.INSIGHTFACE_GPU: ctx_id = 0 cls._detector = FaceAnalysis(name=settings.INSIGHTFACE_MODEL) cls._detector.prepare(ctx_id=ctx_id) logger.info( f"Face detector initialized: model={settings.INSIGHTFACE_MODEL}, " f"ctx_id={ctx_id} ({'GPU' if ctx_id == 0 else 'CPU'})" ) except Exception as e: logger.error(f"Failed to initialize face detector: {str(e)}") raise @classmethod def detect_faces(cls, image: np.ndarray) -> List[dict]: """Detect faces in image using InsightFace""" if cls._detector is None: cls.init_detector() try: faces = cls._detector.get(image) return faces except Exception as e: logger.error(f"Face detection failed: {str(e)}") return [] @classmethod def get_face_embedding(cls, image: np.ndarray, face) -> np.ndarray: """Extract embedding for a detected face""" if cls._detector is None: cls.init_detector() try: embedding = face.embedding return embedding except Exception as e: logger.error(f"Embedding extraction failed: {str(e)}") raise @staticmethod def get_face_quality(face) -> float: """Get quality score for a face (0-1)""" # This is a placeholder - actual quality can be computed from face landmarks try: if hasattr(face, 'det_score'): return float(face.det_score) except Exception: pass return 0.9 # Default high quality @staticmethod def get_face_angle(face) -> str: """Determine face angle (frontal, profile, etc.)""" try: if hasattr(face, 'pose'): pose = face.pose # [pitch, roll, yaw] yaw = float(pose[2]) if len(pose) > 2 else 0 abs_yaw = abs(yaw) if abs_yaw < 20: return "frontal" elif abs_yaw < 55: return "left-half-profile" if yaw < 0 else "right-half-profile" else: return "left-profile" if yaw < 0 else "right-profile" except Exception: pass return "unknown" @staticmethod def get_face_bbox(face) -> Optional[Tuple[float, float, float, float]]: """Get bounding box for face [x1, y1, x2, y2]""" try: if hasattr(face, 'bbox'): bbox = face.bbox return tuple(bbox) except Exception: pass return None class ValidationUtils: """Validation utilities""" @staticmethod def validate_email(email: str) -> bool: """Validate email format""" import re pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return re.match(pattern, email) is not None @staticmethod def validate_person_id(person_id: str) -> bool: """Validate person_id format""" # Can contain alphanumeric, underscore, hyphen import re pattern = r'^[a-zA-Z0-9_-]+$' return len(person_id) > 0 and re.match(pattern, person_id) is not None @staticmethod def validate_password(password: str) -> Tuple[bool, str]: """Validate password strength""" if len(password) < 8: return False, "Password must be at least 8 characters" if not any(c.isupper() for c in password): return False, "Password must contain at least one uppercase letter" if not any(c.islower() for c in password): return False, "Password must contain at least one lowercase letter" if not any(c.isdigit() for c in password): return False, "Password must contain at least one digit" return True, "Password is valid"