""" Service ekstraksi vektor wajah (InsightFace) untuk Laravel. Jalankan: pip install -r requirements.txt uvicorn main:app --host 127.0.0.1 --port 8001 Laravel memanggil POST /extract {"image_url": "..."} dan menerima {"embedding": [512 float]}. """ import hmac import os import urllib.request import cv2 import numpy as np from fastapi import FastAPI, Header, HTTPException from insightface.app import FaceAnalysis from pydantic import BaseModel app = FastAPI(title="Face Embedding Service") # Model dimuat sekali saat start (download otomatis pertama kali, ~300MB) engine = FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"]) engine.prepare(ctx_id=-1, det_size=(640, 640)) class ExtractRequest(BaseModel): image_url: str @app.get("/health") def health(): return {"status": "ok"} def embed_from_url(image_url: str) -> list: """Unduh foto lalu kembalikan vektor wajah. Raise ValueError(pesan) kalau gagal.""" if not image_url.lower().startswith(("http://", "https://")): raise ValueError("image_url harus http(s).") try: with urllib.request.urlopen(image_url, timeout=20) as resp: data = np.frombuffer(resp.read(), dtype=np.uint8) except Exception as e: raise ValueError(f"Foto tidak bisa diunduh: {e}") img = cv2.imdecode(data, cv2.IMREAD_COLOR) if img is None: raise ValueError("File bukan gambar yang valid.") faces = engine.get(img) if not faces: raise ValueError("Wajah tidak terdeteksi pada foto.") # Kalau ada banyak wajah, ambil yang paling besar face = max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1])) return [float(x) for x in face.normed_embedding] def key_ok(key: str) -> bool: expected = os.environ.get("FACE_SERVICE_KEY", "") return not expected or hmac.compare_digest(expected, key or "") @app.post("/extract") def extract(req: ExtractRequest, x_face_key: str = Header(default="")): if not key_ok(x_face_key): raise HTTPException(status_code=401, detail="Face key tidak valid.") try: return {"embedding": embed_from_url(req.image_url)} except ValueError as e: raise HTTPException(status_code=422, detail=str(e))