IbProgrammmer Claude Sonnet 4.6 commited on
Commit
03c4042
·
0 Parent(s):

add deploy/ folder — HuggingFace Spaces inference API

Browse files

Standalone files to push to a HF Space repo (Docker SDK):
- app.py: FastAPI matching Spring Boot InferenceClient contract
- Dockerfile: port 7860, non-root appuser (HF requirements)
- requirements.txt: CPU-only deps, no torch (CLAHE fallback for enhancement)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (3) hide show
  1. Dockerfile +20 -0
  2. app.py +221 -0
  3. requirements.txt +14 -0
Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HuggingFace Spaces Docker — CV Thesis Inference API
2
+ # HF Spaces requirement: port 7860, non-root user.
3
+ FROM python:3.10-slim
4
+
5
+ RUN useradd -m -u 1000 appuser
6
+ WORKDIR /app
7
+
8
+ RUN apt-get update && apt-get install -y --no-install-recommends \
9
+ libgl1-mesa-glx libglib2.0-0 libgomp1 \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ COPY requirements.txt .
13
+ RUN pip install --no-cache-dir -r requirements.txt
14
+
15
+ COPY --chown=appuser:appuser . .
16
+
17
+ USER appuser
18
+
19
+ EXPOSE 7860
20
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Outdoor Detection & Face Recognition REST API — HuggingFace Spaces Edition
3
+ Matches the Spring Boot InferenceClient contract exactly.
4
+
5
+ Endpoints:
6
+ POST /pipeline download → enhance → detect → recognize
7
+ POST /enrol register a named face identity (in-memory)
8
+ DELETE /enrol/{id} remove a registered identity
9
+ GET /health service status
10
+
11
+ Spring Boot sends JSON with snake_case keys (Jackson SNAKE_CASE strategy):
12
+ /pipeline {"image_url": "https://...", "condition": "foggy|rainy|low-light|clear|auto"}
13
+ /enrol {"name": "Alice", "image_url": "https://..."}
14
+
15
+ HuggingFace Space env vars (Settings → Variables and secrets):
16
+ INTERNAL_TOKEN must match Spring Boot INFERENCE_TOKEN
17
+ PROJECT_DIR path to model weights (default /app/models)
18
+ """
19
+ import base64, os, time, uuid
20
+ from typing import Optional
21
+
22
+ import cv2
23
+ import numpy as np
24
+ import requests as _requests
25
+ from fastapi import FastAPI, Header, HTTPException
26
+ from fastapi.middleware.cors import CORSMiddleware
27
+
28
+ app = FastAPI(title="CV Thesis Inference API")
29
+ app.add_middleware(CORSMiddleware, allow_origins=["*"],
30
+ allow_methods=["*"], allow_headers=["*"])
31
+
32
+ detector = None
33
+ detector_fmt = None
34
+ face_app = None
35
+ _gallery: dict[str, dict] = {} # embedding_id → {name, embedding}
36
+
37
+ INTERNAL_TOKEN = os.environ.get("INTERNAL_TOKEN", "dev-only-internal-token")
38
+
39
+ _COND_ROUTE = {
40
+ "foggy": "fog:restormer",
41
+ "rainy": "rain:restormer",
42
+ "low-light": "low_light:zerodce",
43
+ "clear": "clear:none",
44
+ "auto": "auto:clahe",
45
+ }
46
+
47
+ # ── helpers ──────────────────────────────────────────────────────────────────
48
+
49
+ def _download(url: str) -> np.ndarray:
50
+ resp = _requests.get(url, timeout=20)
51
+ resp.raise_for_status()
52
+ arr = np.frombuffer(resp.content, np.uint8)
53
+ img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
54
+ if img is None:
55
+ raise ValueError("imdecode returned None")
56
+ return img
57
+
58
+ def _xyxy_to_xywh(coords) -> dict:
59
+ x1, y1, x2, y2 = [float(v) for v in coords]
60
+ return {"x": round(x1, 1), "y": round(y1, 1),
61
+ "w": round(x2 - x1, 1), "h": round(y2 - y1, 1)}
62
+
63
+ def _to_data_uri(img_bgr: np.ndarray) -> str:
64
+ _, buf = cv2.imencode(".jpg", img_bgr, [cv2.IMWRITE_JPEG_QUALITY, 80])
65
+ return "data:image/jpeg;base64," + base64.b64encode(buf.tobytes()).decode()
66
+
67
+ def _clahe(img_bgr: np.ndarray) -> np.ndarray:
68
+ lab = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2LAB)
69
+ l, a, b = cv2.split(lab)
70
+ l = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(l)
71
+ return cv2.cvtColor(cv2.merge([l, a, b]), cv2.COLOR_LAB2BGR)
72
+
73
+ def _match(embedding: np.ndarray, threshold: float = 0.4):
74
+ if not _gallery:
75
+ return "unknown", "unknown", 0.0
76
+ q = embedding / (np.linalg.norm(embedding) + 1e-9)
77
+ best_id, best_name, best_sim = "unknown", "unknown", 0.0
78
+ for eid, entry in _gallery.items():
79
+ ref = entry["embedding"]
80
+ sim = float(np.dot(q, ref / (np.linalg.norm(ref) + 1e-9)))
81
+ if sim > best_sim:
82
+ best_sim, best_id, best_name = sim, eid, entry["name"]
83
+ if best_sim < threshold:
84
+ return "unknown", "unknown", round(best_sim, 4)
85
+ return best_name, best_id, round(best_sim, 4)
86
+
87
+ # ── startup ──────────────────────────────────────────────────────────────────
88
+
89
+ @app.on_event("startup")
90
+ async def startup():
91
+ global detector, detector_fmt, face_app
92
+ MODELS = os.environ.get("PROJECT_DIR", "/app/models")
93
+
94
+ try:
95
+ from ultralytics import YOLO
96
+ for path, fmt in [
97
+ (f"{MODELS}/phase5/yolov8n_best.onnx", "onnx"),
98
+ (f"{MODELS}/phase3/yolov8n_outdoor_aug/weights/best.pt", "pytorch_fp32"),
99
+ (f"{MODELS}/phase3/yolov8n_baseline/weights/best.pt", "pytorch_fp32"),
100
+ ("yolov8n.pt", "pytorch_pretrained"),
101
+ ]:
102
+ if os.path.exists(path):
103
+ detector = YOLO(path); detector_fmt = fmt
104
+ print(f"[startup] Detector: {path} [{fmt}]"); break
105
+ except Exception as e:
106
+ print(f"[startup] Detector load failed: {e}")
107
+
108
+ try:
109
+ from insightface.app import FaceAnalysis
110
+ # buffalo_l is auto-downloaded from insightface CDN on first run
111
+ face_app = FaceAnalysis(name="buffalo_l",
112
+ providers=["CPUExecutionProvider"])
113
+ face_app.prepare(ctx_id=-1, det_size=(640, 640))
114
+ print("[startup] Face analyzer: SCRFD-10GF + ArcFace (CPU)")
115
+ except Exception as e:
116
+ print(f"[startup] Face analyzer load failed: {e}")
117
+
118
+ # ── endpoints ─────────────────────────────���──────────────────────────────────
119
+
120
+ @app.post("/pipeline")
121
+ async def pipeline(body: dict,
122
+ x_internal_token: Optional[str] = Header(None)):
123
+ t_total = time.time()
124
+ image_url = body.get("image_url")
125
+ condition = body.get("condition", "auto")
126
+ if not image_url:
127
+ raise HTTPException(status_code=400, detail="image_url is required")
128
+
129
+ try:
130
+ img = _download(image_url)
131
+ except Exception as e:
132
+ raise HTTPException(status_code=400, detail=f"Cannot download image: {e}")
133
+ h, w = img.shape[:2]
134
+
135
+ t0 = time.time()
136
+ enhanced = _clahe(img)
137
+ enh_ms = (time.time() - t0) * 1000
138
+
139
+ t0 = time.time()
140
+ detections = []
141
+ if detector:
142
+ for r in detector(enhanced, verbose=False):
143
+ for box in r.boxes:
144
+ detections.append({
145
+ "class": r.names[int(box.cls)],
146
+ "confidence": round(float(box.conf), 4),
147
+ "bbox": _xyxy_to_xywh(box.xyxy[0].tolist()),
148
+ })
149
+ det_ms = (time.time() - t0) * 1000
150
+
151
+ t0 = time.time()
152
+ recognitions = []
153
+ if face_app:
154
+ for face in face_app.get(enhanced):
155
+ name, eid, conf = _match(face.embedding)
156
+ recognitions.append({
157
+ "identity": name,
158
+ "identity_id": eid,
159
+ "confidence": conf,
160
+ "bbox": _xyxy_to_xywh(face.bbox.tolist()),
161
+ })
162
+ rec_ms = (time.time() - t0) * 1000
163
+ total_ms = (time.time() - t_total) * 1000
164
+
165
+ return {
166
+ "detections": detections,
167
+ "recognitions": recognitions,
168
+ "enhanced_image_url": _to_data_uri(enhanced),
169
+ "enhancement_route": _COND_ROUTE.get(condition, "auto:clahe"),
170
+ "condition": condition,
171
+ "latency_ms": {
172
+ "enhancement": round(enh_ms, 1),
173
+ "detection": round(det_ms, 1),
174
+ "recognition": round(rec_ms, 1),
175
+ "total": round(total_ms, 1),
176
+ },
177
+ "image_width": w,
178
+ "image_height": h,
179
+ }
180
+
181
+
182
+ @app.post("/enrol")
183
+ async def enrol(body: dict,
184
+ x_internal_token: Optional[str] = Header(None)):
185
+ if face_app is None:
186
+ raise HTTPException(status_code=503, detail="Face analyzer not loaded")
187
+ name = body.get("name")
188
+ image_url = body.get("image_url")
189
+ if not name or not image_url:
190
+ raise HTTPException(status_code=400, detail="name and image_url are required")
191
+ try:
192
+ img = _download(image_url)
193
+ except Exception as e:
194
+ raise HTTPException(status_code=400, detail=f"Cannot download image: {e}")
195
+ faces = face_app.get(img)
196
+ if not faces:
197
+ raise HTTPException(status_code=422, detail="No face detected in enrolment image")
198
+ emb = faces[0].embedding.astype(np.float32)
199
+ emb /= np.linalg.norm(emb) + 1e-9
200
+ eid = str(uuid.uuid4())
201
+ _gallery[eid] = {"name": name, "embedding": emb}
202
+ print(f"[enrol] {name} → {eid} (gallery: {len(_gallery)})")
203
+ return {"embedding_id": eid}
204
+
205
+
206
+ @app.delete("/enrol/{embedding_id}")
207
+ async def delete_enrol(embedding_id: str,
208
+ x_internal_token: Optional[str] = Header(None)):
209
+ _gallery.pop(embedding_id, None)
210
+ return {"status": "deleted", "embedding_id": embedding_id}
211
+
212
+
213
+ @app.get("/health")
214
+ async def health():
215
+ return {
216
+ "status": "ok",
217
+ "detector": detector is not None,
218
+ "detector_format": detector_fmt,
219
+ "face_app": face_app is not None,
220
+ "gallery_size": len(_gallery),
221
+ }
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HuggingFace Spaces inference API — CPU-only, no Colab/GPU deps
2
+ # torch is excluded: ZeroDCE++ enhancement falls back to CLAHE automatically.
3
+ # InsightFace and ONNX YOLO both run on onnxruntime (CPU).
4
+
5
+ fastapi>=0.111.0
6
+ uvicorn[standard]>=0.30.0
7
+ opencv-python-headless>=4.10.0
8
+ numpy>=1.26.0
9
+ requests>=2.31.0
10
+ python-multipart>=0.0.9
11
+ ultralytics>=8.4.0
12
+ insightface>=0.7.3
13
+ onnxruntime>=1.18.0
14
+ faiss-cpu>=1.8.0