Explicite/api-test
0
1# app/services/insightface_engine.py2import numpy as np3import cv24from insightface.app import FaceAnalysis5 6_face_app = None7 8def get_face_app():9 global _face_app10 if _face_app is None:11 # name="buffalo_l" es un pack popular (detector+recognition)12 _face_app = FaceAnalysis(name="buffalo_l")13 # ctx_id=-1 => CPU. (Si tuvieras GPU CUDA sería 0)14 _face_app.prepare(ctx_id=-1, det_size=(640, 640))15 return _face_app16 17def pick_best_face(faces):18 """19 Si hay varias caras, escogemos la de mayor área (lo más común).20 """21 if not faces:22 return None23 def area(face):24 x1, y1, x2, y2 = face.bbox.astype(int)25 return max(0, x2-x1) * max(0, y2-y1)26 return max(faces, key=area)27 28def to_bbox_dict(face):29 x1, y1, x2, y2 = face.bbox.astype(int)30 # tu esquema anterior usa top/right/bottom/left31 return {"top": int(y1), "right": int(x2), "bottom": int(y2), "left": int(x1)}32 33def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:34 a = a.astype("float32")35 b = b.astype("float32")36 a = a / (np.linalg.norm(a) + 1e-12)37 b = b / (np.linalg.norm(b) + 1e-12)38 return float(np.dot(a, b))39 40def augment_rgb(np_rgb: np.ndarray, seed: int) -> np.ndarray:41 """42 Variantes suaves: brillo/contraste + rotación leve.43 Esto ayuda cuando hay barba, luz distinta, etc.44 """45 rng = np.random.default_rng(seed)46 img = np_rgb.copy()47 48 # Brillo/contraste49 alpha = float(rng.uniform(0.90, 1.10)) # contraste50 beta = float(rng.uniform(-12, 12)) # brillo51 img = cv2.convertScaleAbs(img, alpha=alpha, beta=beta)52 53 # Rotación leve54 h, w = img.shape[:2]55 angle = float(rng.uniform(-3.0, 3.0))56 M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)57 img = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)58 59 return img60 