Spaces:
Running on Zero
Running on Zero
Upload 2 files
Browse files
app.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
"""
|
| 2 |
Entrypoint untuk Hugging Face Spaces (SDK Gradio / ZeroGPU gratis).
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
| 7 |
"""
|
| 8 |
import gradio as gr
|
| 9 |
|
|
@@ -15,21 +16,27 @@ except ImportError: # menjalankan di luar Hugging Face
|
|
| 15 |
def gpu(fn):
|
| 16 |
return fn
|
| 17 |
|
| 18 |
-
from main import
|
| 19 |
|
| 20 |
|
| 21 |
@gpu
|
| 22 |
-
def
|
| 23 |
return "ok"
|
| 24 |
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
if __name__ == "__main__":
|
| 29 |
-
server, _, _ = demo.launch(server_name="0.0.0.0", server_port=7860, prevent_thread_lock=True)
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
| 34 |
|
| 35 |
-
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
Entrypoint untuk Hugging Face Spaces (SDK Gradio / ZeroGPU gratis).
|
| 3 |
|
| 4 |
+
Space gratis hanya menyediakan ZeroGPU, yang mensyaratkan Gradio dijalankan lewat
|
| 5 |
+
demo.launch() dan ada fungsi @spaces.GPU. Fungsi GPU itu tidak pernah dipanggil
|
| 6 |
+
(kuota GPU tidak terpakai); ekstraksi wajah jalan di CPU lewat endpoint Gradio
|
| 7 |
+
`extract`, yang dipanggil Laravel via /gradio_api/call/extract.
|
| 8 |
"""
|
| 9 |
import gradio as gr
|
| 10 |
|
|
|
|
| 16 |
def gpu(fn):
|
| 17 |
return fn
|
| 18 |
|
| 19 |
+
from main import embed_from_url, key_ok
|
| 20 |
|
| 21 |
|
| 22 |
@gpu
|
| 23 |
+
def ping() -> str:
|
| 24 |
return "ok"
|
| 25 |
|
| 26 |
|
| 27 |
+
def extract(image_url: str, key: str) -> dict:
|
| 28 |
+
if not key_ok(key):
|
| 29 |
+
return {"error": "Face key tidak valid."}
|
| 30 |
+
try:
|
| 31 |
+
return {"embedding": embed_from_url(image_url)}
|
| 32 |
+
except ValueError as e:
|
| 33 |
+
return {"error": str(e)}
|
| 34 |
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
with gr.Blocks(title="Face Embedding Service") as demo:
|
| 37 |
+
gr.Markdown("Face Embedding Service - API: `extract`")
|
| 38 |
+
gr.api(extract, api_name="extract")
|
| 39 |
+
gr.api(ping, api_name="ping")
|
| 40 |
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
main.py
CHANGED
|
@@ -1,61 +1,72 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Service ekstraksi vektor wajah (InsightFace) untuk Laravel.
|
| 3 |
-
|
| 4 |
-
Jalankan:
|
| 5 |
-
pip install -r requirements.txt
|
| 6 |
-
uvicorn main:app --host 127.0.0.1 --port 8001
|
| 7 |
-
|
| 8 |
-
Laravel memanggil POST /extract {"image_url": "..."} dan menerima {"embedding": [512 float]}.
|
| 9 |
-
"""
|
| 10 |
-
import hmac
|
| 11 |
-
import os
|
| 12 |
-
import urllib.request
|
| 13 |
-
|
| 14 |
-
import cv2
|
| 15 |
-
import numpy as np
|
| 16 |
-
from fastapi import FastAPI, Header, HTTPException
|
| 17 |
-
from insightface.app import FaceAnalysis
|
| 18 |
-
from pydantic import BaseModel
|
| 19 |
-
|
| 20 |
-
app = FastAPI(title="Face Embedding Service")
|
| 21 |
-
|
| 22 |
-
# Model dimuat sekali saat start (download otomatis pertama kali, ~300MB)
|
| 23 |
-
engine = FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
|
| 24 |
-
engine.prepare(ctx_id=-1, det_size=(640, 640))
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
class ExtractRequest(BaseModel):
|
| 28 |
-
image_url: str
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
@app.get("/health")
|
| 32 |
-
def health():
|
| 33 |
-
return {"status": "ok"}
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
raise
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
if
|
| 53 |
-
raise
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Service ekstraksi vektor wajah (InsightFace) untuk Laravel.
|
| 3 |
+
|
| 4 |
+
Jalankan:
|
| 5 |
+
pip install -r requirements.txt
|
| 6 |
+
uvicorn main:app --host 127.0.0.1 --port 8001
|
| 7 |
+
|
| 8 |
+
Laravel memanggil POST /extract {"image_url": "..."} dan menerima {"embedding": [512 float]}.
|
| 9 |
+
"""
|
| 10 |
+
import hmac
|
| 11 |
+
import os
|
| 12 |
+
import urllib.request
|
| 13 |
+
|
| 14 |
+
import cv2
|
| 15 |
+
import numpy as np
|
| 16 |
+
from fastapi import FastAPI, Header, HTTPException
|
| 17 |
+
from insightface.app import FaceAnalysis
|
| 18 |
+
from pydantic import BaseModel
|
| 19 |
+
|
| 20 |
+
app = FastAPI(title="Face Embedding Service")
|
| 21 |
+
|
| 22 |
+
# Model dimuat sekali saat start (download otomatis pertama kali, ~300MB)
|
| 23 |
+
engine = FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
|
| 24 |
+
engine.prepare(ctx_id=-1, det_size=(640, 640))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ExtractRequest(BaseModel):
|
| 28 |
+
image_url: str
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@app.get("/health")
|
| 32 |
+
def health():
|
| 33 |
+
return {"status": "ok"}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def embed_from_url(image_url: str) -> list:
|
| 37 |
+
"""Unduh foto lalu kembalikan vektor wajah. Raise ValueError(pesan) kalau gagal."""
|
| 38 |
+
if not image_url.lower().startswith(("http://", "https://")):
|
| 39 |
+
raise ValueError("image_url harus http(s).")
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
with urllib.request.urlopen(image_url, timeout=20) as resp:
|
| 43 |
+
data = np.frombuffer(resp.read(), dtype=np.uint8)
|
| 44 |
+
except Exception as e:
|
| 45 |
+
raise ValueError(f"Foto tidak bisa diunduh: {e}")
|
| 46 |
+
|
| 47 |
+
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
|
| 48 |
+
if img is None:
|
| 49 |
+
raise ValueError("File bukan gambar yang valid.")
|
| 50 |
+
|
| 51 |
+
faces = engine.get(img)
|
| 52 |
+
if not faces:
|
| 53 |
+
raise ValueError("Wajah tidak terdeteksi pada foto.")
|
| 54 |
+
|
| 55 |
+
# Kalau ada banyak wajah, ambil yang paling besar
|
| 56 |
+
face = max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
|
| 57 |
+
return [float(x) for x in face.normed_embedding]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def key_ok(key: str) -> bool:
|
| 61 |
+
expected = os.environ.get("FACE_SERVICE_KEY", "")
|
| 62 |
+
return not expected or hmac.compare_digest(expected, key or "")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@app.post("/extract")
|
| 66 |
+
def extract(req: ExtractRequest, x_face_key: str = Header(default="")):
|
| 67 |
+
if not key_ok(x_face_key):
|
| 68 |
+
raise HTTPException(status_code=401, detail="Face key tidak valid.")
|
| 69 |
+
try:
|
| 70 |
+
return {"embedding": embed_from_url(req.image_url)}
|
| 71 |
+
except ValueError as e:
|
| 72 |
+
raise HTTPException(status_code=422, detail=str(e))
|