File size: 7,169 Bytes
4854e2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
"""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"