import numpy as np import cv2 from insightface.app import FaceAnalysis _app = None def _get_app(): global _app if _app is None: _app = FaceAnalysis(providers=["CPUExecutionProvider"]) _app.prepare(ctx_id=0, det_size=(640, 640)) return _app def _cosine_sim(a, b): a, b = np.array(a, dtype=float), np.array(b, dtype=float) return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))) def _to_pct(sim): return round(max(0.0, min(1.0, (sim + 1) / 2)) * 100, 1) def _get_face(app, path): img = cv2.imread(path) if img is None: raise ValueError(f"Could not read image: {path}") img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) faces = app.get(img_rgb) if not faces: raise ValueError(f"No face detected in image: {path}") return faces[0] def analyze(father_path, mother_path, child_path): app = _get_app() child_face = _get_face(app, child_path) father_face = _get_face(app, father_path) mother_face = _get_face(app, mother_path) return { "age": int(child_face.age), "father_score": _to_pct(_cosine_sim(child_face.embedding, father_face.embedding)), "mother_score": _to_pct(_cosine_sim(child_face.embedding, mother_face.embedding)), }