ultrazcode commited on
Commit
437844c
·
verified ·
1 Parent(s): 8da42f0

Upload 5 files

Browse files
Files changed (5) hide show
  1. README.md +11 -8
  2. app.py +32 -0
  3. main.py +61 -0
  4. packages.txt +2 -0
  5. requirements.txt +6 -0
README.md CHANGED
@@ -1,14 +1,17 @@
1
  ---
2
- title: Face Service
3
- emoji: 👁
4
- colorFrom: blue
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
- license: mit
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
1
  ---
2
+ title: Face Embedding Service
3
+ emoji: 🧑
4
+ colorFrom: green
5
+ colorTo: blue
6
  sdk: gradio
7
+ python_version: "3.11"
 
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
+ Service ekstraksi vektor wajah (InsightFace buffalo_l) untuk FaceID Presensi.
13
+
14
+ - `GET /health`
15
+ - `POST /extract` body `{"image_url": "https://..."}` dengan header `X-Face-Key`.
16
+
17
+ Set secret `FACE_SERVICE_KEY` di Settings → Variables and secrets.
app.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Entrypoint untuk Hugging Face Spaces (SDK Gradio / ZeroGPU gratis).
3
+
4
+ Space menjalankan `python app.py` dan mengharapkan server di port 7860.
5
+ API sebenarnya adalah FastAPI di main.py (ekstraksi jalan di CPU). ZeroGPU hanya
6
+ mensyaratkan adanya satu fungsi @spaces.GPU saat start; fungsi ini tidak pernah
7
+ dipanggil sehingga kuota GPU tidak terpakai.
8
+ """
9
+ import gradio as gr
10
+ import uvicorn
11
+
12
+ try:
13
+ import spaces
14
+
15
+ gpu = spaces.GPU
16
+ except ImportError: # menjalankan di luar Hugging Face
17
+ def gpu(fn):
18
+ return fn
19
+
20
+ from main import app
21
+
22
+
23
+ @gpu
24
+ def _ping() -> str:
25
+ return "ok"
26
+
27
+
28
+ demo = gr.Interface(fn=_ping, inputs=None, outputs="text", title="Face Embedding Service")
29
+ app = gr.mount_gradio_app(app, demo, path="/ui")
30
+
31
+ if __name__ == "__main__":
32
+ uvicorn.run(app, host="0.0.0.0", port=7860)
main.py ADDED
@@ -0,0 +1,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
+ @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]}
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ build-essential
2
+ libglib2.0-0
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ insightface
4
+ onnxruntime
5
+ opencv-python-headless
6
+ numpy