Spaces:
Running on Zero
Running on Zero
File size: 2,316 Bytes
88a2a7d | 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 | """
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))
|