ultrazcode commited on
Commit
88a2a7d
·
verified ·
1 Parent(s): 0e9f065

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +19 -12
  2. main.py +72 -61
app.py CHANGED
@@ -1,9 +1,10 @@
1
  """
2
  Entrypoint untuk Hugging Face Spaces (SDK Gradio / ZeroGPU gratis).
3
 
4
- ZeroGPU mensyaratkan Gradio dijalankan lewat demo.launch() dan ada fungsi @spaces.GPU.
5
- Fungsi itu tidak pernah dipanggil (kuota GPU tidak terpakai); ekstraksi jalan di CPU.
6
- Endpoint /health dan /extract dari main.py ditempelkan ke server Gradio.
 
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 app as api
19
 
20
 
21
  @gpu
22
- def _ping() -> str:
23
  return "ok"
24
 
25
 
26
- demo = gr.Interface(fn=_ping, inputs=None, outputs="text", title="Face Embedding Service")
 
 
 
 
 
 
27
 
28
- if __name__ == "__main__":
29
- server, _, _ = demo.launch(server_name="0.0.0.0", server_port=7860, prevent_thread_lock=True)
30
 
31
- # Taruh route kita di depan agar tidak tertutup route bawaan Gradio
32
- ours = [r for r in api.routes if getattr(r, "path", "") in ("/health", "/extract")]
33
- server.router.routes[0:0] = ours
 
34
 
35
- demo.block_thread()
 
 
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
- @app.post("/extract")
37
- def extract(req: ExtractRequest, x_face_key: str = Header(default="")):
38
- expected = os.environ.get("FACE_SERVICE_KEY", "")
39
- if expected and not hmac.compare_digest(expected, x_face_key):
40
- raise HTTPException(status_code=401, detail="Face key tidak valid.")
41
-
42
- if not req.image_url.lower().startswith(("http://", "https://")):
43
- raise HTTPException(status_code=400, detail="image_url harus http(s).")
44
-
45
- try:
46
- with urllib.request.urlopen(req.image_url, timeout=20) as resp:
47
- data = np.frombuffer(resp.read(), dtype=np.uint8)
48
- except Exception as e:
49
- raise HTTPException(status_code=400, detail=f"Foto tidak bisa diunduh: {e}")
50
-
51
- img = cv2.imdecode(data, cv2.IMREAD_COLOR)
52
- if img is None:
53
- raise HTTPException(status_code=422, detail="File bukan gambar yang valid.")
54
-
55
- faces = engine.get(img)
56
- if not faces:
57
- raise HTTPException(status_code=422, detail="Wajah tidak terdeteksi pada foto.")
58
-
59
- # Kalau ada banyak wajah, ambil yang paling besar
60
- face = max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
61
- return {"embedding": [float(x) for x in face.normed_embedding]}
 
 
 
 
 
 
 
 
 
 
 
 
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))