Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,545 +1,925 @@
|
|
| 1 |
"""
|
| 2 |
-
Logo
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
|
| 10 |
from __future__ import annotations
|
| 11 |
|
| 12 |
-
import os
|
| 13 |
-
import gc
|
| 14 |
-
import io
|
| 15 |
-
import time
|
| 16 |
-
import base64
|
| 17 |
-
import logging
|
| 18 |
from contextlib import asynccontextmanager
|
| 19 |
from typing import Optional
|
|
|
|
| 20 |
|
| 21 |
-
import cv2
|
| 22 |
-
import
|
| 23 |
-
|
| 24 |
from fastapi.middleware.cors import CORSMiddleware
|
| 25 |
-
from fastapi.responses import JSONResponse
|
| 26 |
import onnxruntime as ort
|
| 27 |
from PIL import Image
|
| 28 |
|
| 29 |
# βββ Logging ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 30 |
-
logging.basicConfig(
|
| 31 |
-
|
| 32 |
-
format="%(asctime)s | %(levelname)s | %(message)s",
|
| 33 |
-
)
|
| 34 |
log = logging.getLogger("logo-extractor")
|
| 35 |
|
| 36 |
-
# βββ Config βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
-
MODEL_PATH
|
| 38 |
-
MODEL_URL
|
| 39 |
-
APP_SECRET_KEY
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
# βββ Model
|
| 51 |
def ensure_model() -> None:
|
| 52 |
-
"""
|
| 53 |
-
Make sure logo_detector.onnx exists.
|
| 54 |
-
Priority order:
|
| 55 |
-
1. Already present on disk (Space mein upload kiya hua)
|
| 56 |
-
2. MODEL_URL env var β kisi bhi direct HTTP link se download
|
| 57 |
-
3. HF Hub se best logo detection model download (openfoodfacts/universal-logo-detector)
|
| 58 |
-
4. Fallback: yolov8n.pt export (general object detection, logo class nahi)
|
| 59 |
-
"""
|
| 60 |
if os.path.exists(MODEL_PATH):
|
| 61 |
log.info("Model found: %s (%.1f MB)", MODEL_PATH,
|
| 62 |
os.path.getsize(MODEL_PATH) / 1e6)
|
| 63 |
return
|
| 64 |
-
|
| 65 |
-
# ββ Option 2: Direct URL download ββββββββββββββββββββββββββββββββββββββ
|
| 66 |
if MODEL_URL:
|
| 67 |
-
log.info("Downloading model from MODEL_URL: %s", MODEL_URL)
|
| 68 |
import urllib.request
|
|
|
|
| 69 |
urllib.request.urlretrieve(MODEL_URL, MODEL_PATH)
|
| 70 |
-
log.info("Downloaded β %s (%.1f MB)", MODEL_PATH,
|
| 71 |
-
os.path.getsize(MODEL_PATH) / 1e6)
|
| 72 |
return
|
| 73 |
-
|
| 74 |
-
# ββ Option 3: HF Hub β openfoodfacts universal logo detector (BEST) βββ
|
| 75 |
-
# ultralytics YOLO("hf_user/repo") syntax se .pt download + ONNX export
|
| 76 |
-
log.info("Downloading openfoodfacts/universal-logo-detector from HF Hub...")
|
| 77 |
try:
|
| 78 |
-
import shutil
|
| 79 |
-
import onnx # noqa β must be importable before export
|
| 80 |
from ultralytics import YOLO
|
| 81 |
-
|
| 82 |
-
exported =
|
| 83 |
-
|
| 84 |
-
simplify=True, dynamic=False,
|
| 85 |
-
)
|
| 86 |
-
# ultralytics returns path or saves as <modelname>.onnx
|
| 87 |
found = None
|
| 88 |
-
for
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
found = candidate
|
| 93 |
-
break
|
| 94 |
if not found:
|
| 95 |
-
# walk /app looking for any fresh .onnx
|
| 96 |
for root, _, files in os.walk("/app"):
|
| 97 |
for f in files:
|
| 98 |
if f.endswith(".onnx") and f != "logo_detector.onnx":
|
| 99 |
-
found = os.path.join(root, f)
|
| 100 |
-
break
|
| 101 |
if found:
|
| 102 |
shutil.move(found, MODEL_PATH)
|
| 103 |
-
log.info("HF Hub model ready β %s
|
| 104 |
-
MODEL_PATH, os.path.getsize(MODEL_PATH) / 1e6)
|
| 105 |
-
return
|
| 106 |
-
raise FileNotFoundError("No .onnx found after export")
|
| 107 |
except Exception as exc:
|
| 108 |
-
log.warning("HF Hub
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
opset=17,
|
| 120 |
-
simplify=True,
|
| 121 |
-
dynamic=False,
|
| 122 |
-
)
|
| 123 |
-
# Ultralytics saves as yolov8n.onnx in cwd
|
| 124 |
-
for candidate in ["yolov8n.onnx", "yolov8n/yolov8n.onnx"]:
|
| 125 |
-
if os.path.exists(candidate):
|
| 126 |
-
os.rename(candidate, MODEL_PATH)
|
| 127 |
-
log.info("Fallback export saved β %s", MODEL_PATH)
|
| 128 |
-
return
|
| 129 |
-
raise FileNotFoundError("Export produced no .onnx file")
|
| 130 |
-
except Exception as exc:
|
| 131 |
-
log.error("All model acquisition methods failed: %s", exc)
|
| 132 |
-
log.error(
|
| 133 |
-
"Manual fix: Set MODEL_URL env var in HF Space secrets "
|
| 134 |
-
"pointing to your .onnx file direct download link."
|
| 135 |
-
)
|
| 136 |
-
|
| 137 |
-
# βββ Model (loaded once at startup) βββββββββββββββββββββββββββββββββββββββββ
|
| 138 |
-
ort_session: Optional[ort.InferenceSession] = None
|
| 139 |
-
|
| 140 |
|
| 141 |
def load_model() -> ort.InferenceSession:
|
| 142 |
-
"""Load ONNX model with CPU optimizations."""
|
| 143 |
opts = ort.SessionOptions()
|
| 144 |
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 145 |
-
opts.intra_op_num_threads = 2
|
| 146 |
opts.inter_op_num_threads = 1
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
sess_options=opts,
|
| 153 |
-
providers=["CPUExecutionProvider"],
|
| 154 |
-
)
|
| 155 |
-
log.info("ONNX model loaded: %s", MODEL_PATH)
|
| 156 |
-
log.info("Input: %s", session.get_inputs()[0].shape)
|
| 157 |
-
log.info("Output: %s", session.get_outputs()[0].shape)
|
| 158 |
-
return session
|
| 159 |
|
|
|
|
| 160 |
|
| 161 |
-
# βββ Lifespan (startup / shutdown) ββββββββββββββββββββββββββββββββββββββββββ
|
| 162 |
@asynccontextmanager
|
| 163 |
async def lifespan(app: FastAPI):
|
| 164 |
global ort_session
|
| 165 |
-
log.info("Starting up
|
| 166 |
ensure_model()
|
| 167 |
-
log.info("Loading ONNX session...")
|
| 168 |
try:
|
| 169 |
ort_session = load_model()
|
| 170 |
-
except Exception as
|
| 171 |
-
log.error("Model load failed: %s",
|
| 172 |
yield
|
| 173 |
-
|
| 174 |
-
del ort_session
|
| 175 |
-
gc.collect()
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
# βββ App βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 179 |
-
app = FastAPI(
|
| 180 |
-
title="Logo Extractor API",
|
| 181 |
-
description="YOLOv8 Nano logo detection β Hugging Face Space Worker",
|
| 182 |
-
version="1.0.0",
|
| 183 |
-
lifespan=lifespan,
|
| 184 |
-
docs_url="/docs",
|
| 185 |
-
redoc_url=None,
|
| 186 |
-
)
|
| 187 |
-
|
| 188 |
-
app.add_middleware(
|
| 189 |
-
CORSMiddleware,
|
| 190 |
-
allow_origins=["*"], # Restrict in production to your domain
|
| 191 |
-
allow_methods=["POST", "GET"],
|
| 192 |
-
allow_headers=["*"],
|
| 193 |
-
)
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
"""Raise 401 if secret doesn't match APP_SECRET_KEY."""
|
| 199 |
-
if not APP_SECRET_KEY:
|
| 200 |
-
raise HTTPException(
|
| 201 |
-
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
| 202 |
-
detail="Service not configured β APP_SECRET_KEY missing",
|
| 203 |
-
)
|
| 204 |
-
if secret != APP_SECRET_KEY:
|
| 205 |
-
log.warning("Unauthorized request β invalid secret")
|
| 206 |
-
raise HTTPException(
|
| 207 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 208 |
-
detail="Invalid secret key",
|
| 209 |
-
)
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
# βββ Image preprocessing βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 213 |
-
def preprocess(img_bgr: np.ndarray) -> tuple[np.ndarray, float, int, int]:
|
| 214 |
-
"""
|
| 215 |
-
Resize + normalize image for YOLOv8 input.
|
| 216 |
-
Returns (input_tensor, scale, pad_x, pad_y)
|
| 217 |
-
"""
|
| 218 |
-
h, w = img_bgr.shape[:2]
|
| 219 |
-
|
| 220 |
-
# Letterbox resize to INPUT_SIZE x INPUT_SIZE
|
| 221 |
scale = min(INPUT_SIZE / w, INPUT_SIZE / h)
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
pad_x = (INPUT_SIZE - new_w) // 2
|
| 229 |
-
pad_y = (INPUT_SIZE - new_h) // 2
|
| 230 |
-
padded = cv2.copyMakeBorder(
|
| 231 |
-
resized,
|
| 232 |
-
pad_y, INPUT_SIZE - new_h - pad_y,
|
| 233 |
-
pad_x, INPUT_SIZE - new_w - pad_x,
|
| 234 |
-
cv2.BORDER_CONSTANT,
|
| 235 |
-
value=(114, 114, 114),
|
| 236 |
-
)
|
| 237 |
-
|
| 238 |
-
# BGR β RGB, HWC β CHW, normalize 0-1
|
| 239 |
rgb = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB)
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
keep = []
|
| 255 |
-
while order.size > 0:
|
| 256 |
-
i = order[0]
|
| 257 |
-
keep.append(int(i))
|
| 258 |
-
xx1 = np.maximum(x1[i], x1[order[1:]])
|
| 259 |
-
yy1 = np.maximum(y1[i], y1[order[1:]])
|
| 260 |
-
xx2 = np.minimum(x2[i], x2[order[1:]])
|
| 261 |
-
yy2 = np.minimum(y2[i], y2[order[1:]])
|
| 262 |
-
inter = np.maximum(0, xx2 - xx1) * np.maximum(0, yy2 - yy1)
|
| 263 |
-
iou = inter / (areas[i] + areas[order[1:]] - inter + 1e-6)
|
| 264 |
-
order = order[1:][iou <= iou_thresh]
|
| 265 |
return keep
|
| 266 |
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
iou_thresh: float,
|
| 278 |
-
) -> list[dict]:
|
| 279 |
-
"""
|
| 280 |
-
Parse YOLOv8 output β list of {x1,y1,x2,y2,confidence} in original coords.
|
| 281 |
-
YOLOv8 ONNX output shape: [1, num_classes+4, num_anchors]
|
| 282 |
-
"""
|
| 283 |
-
# raw shape: (1, 5, 8400) for single-class or (1, 4+nc, 8400)
|
| 284 |
-
pred = raw[0] # (5, 8400) or (4+nc, 8400)
|
| 285 |
-
pred = pred.T # (8400, 5)
|
| 286 |
-
|
| 287 |
-
# cx, cy, w, h, conf (single-class logo model)
|
| 288 |
-
cx, cy, bw, bh = pred[:, 0], pred[:, 1], pred[:, 2], pred[:, 3]
|
| 289 |
-
|
| 290 |
-
# Multi-class: take max confidence across class scores
|
| 291 |
-
if pred.shape[1] > 5:
|
| 292 |
-
class_scores = pred[:, 4:]
|
| 293 |
-
conf = class_scores.max(axis=1)
|
| 294 |
-
else:
|
| 295 |
-
conf = pred[:, 4]
|
| 296 |
-
|
| 297 |
-
mask = conf >= conf_thresh
|
| 298 |
-
if not mask.any():
|
| 299 |
-
return []
|
| 300 |
-
|
| 301 |
-
cx, cy, bw, bh, conf = cx[mask], cy[mask], bw[mask], bh[mask], conf[mask]
|
| 302 |
-
|
| 303 |
-
# xywh β xyxy (still in letterboxed space)
|
| 304 |
-
x1 = cx - bw / 2
|
| 305 |
-
y1 = cy - bh / 2
|
| 306 |
-
x2 = cx + bw / 2
|
| 307 |
-
y2 = cy + bh / 2
|
| 308 |
-
|
| 309 |
-
boxes_lb = np.stack([x1, y1, x2, y2], axis=1)
|
| 310 |
-
|
| 311 |
-
# NMS
|
| 312 |
-
keep = nms(boxes_lb, conf, iou_thresh)
|
| 313 |
-
boxes_lb = boxes_lb[keep]
|
| 314 |
-
conf = conf[keep]
|
| 315 |
-
|
| 316 |
results = []
|
| 317 |
-
for box, score in zip(
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
# Clamp to image bounds
|
| 325 |
-
ox1 = max(0, ox1)
|
| 326 |
-
oy1 = max(0, oy1)
|
| 327 |
-
ox2 = min(orig_w, ox2)
|
| 328 |
-
oy2 = min(orig_h, oy2)
|
| 329 |
-
|
| 330 |
-
if ox2 <= ox1 or oy2 <= oy1:
|
| 331 |
-
continue
|
| 332 |
-
|
| 333 |
-
results.append({
|
| 334 |
-
"x1": ox1, "y1": oy1, "x2": ox2, "y2": oy2,
|
| 335 |
-
"confidence": round(float(score), 4),
|
| 336 |
-
})
|
| 337 |
-
|
| 338 |
return results
|
| 339 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
-
# βββ
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
|
| 384 |
# βββ Routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 385 |
-
@app.get("/")
|
| 386 |
-
async def root():
|
| 387 |
-
"""Root β HF Space App tab mein show hoga."""
|
| 388 |
-
model_ok = ort_session is not None
|
| 389 |
-
return {
|
| 390 |
-
"service": "Logo Extractor API",
|
| 391 |
-
"version": "1.0.0",
|
| 392 |
-
"status": "ok" if model_ok else "degraded",
|
| 393 |
-
"model_loaded": model_ok,
|
| 394 |
-
"endpoints": {
|
| 395 |
-
"health": "GET /health",
|
| 396 |
-
"extract": "POST /extract-logo (header: X-Custom-Secret)",
|
| 397 |
-
"docs": "GET /docs",
|
| 398 |
-
},
|
| 399 |
-
}
|
| 400 |
|
|
|
|
|
|
|
|
|
|
| 401 |
|
| 402 |
@app.get("/health")
|
| 403 |
async def health():
|
| 404 |
-
"""
|
| 405 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
return {
|
| 407 |
-
"
|
| 408 |
-
"
|
| 409 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
}
|
| 411 |
|
| 412 |
-
|
| 413 |
@app.post("/extract-logo")
|
| 414 |
async def extract_logo(
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
output_format: str = "PNG",
|
| 418 |
max_logos: int = 20,
|
|
|
|
|
|
|
| 419 |
):
|
| 420 |
"""
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
Headers required:
|
| 424 |
-
X-Custom-Secret: <APP_SECRET_KEY>
|
| 425 |
-
|
| 426 |
-
Returns:
|
| 427 |
-
{ logos: [{ base64, width, height, confidence, bbox }], count, elapsed_ms }
|
| 428 |
"""
|
| 429 |
-
|
| 430 |
|
| 431 |
-
#
|
| 432 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
|
| 434 |
-
# ββ 2. Model check βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 435 |
if ort_session is None:
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
if img_bgr is None:
|
| 460 |
-
raise HTTPException(
|
| 461 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 462 |
-
detail="Could not decode image",
|
| 463 |
-
)
|
| 464 |
-
|
| 465 |
-
orig_h, orig_w = img_bgr.shape[:2]
|
| 466 |
-
log.info("Image received: %dx%d px", orig_w, orig_h)
|
| 467 |
-
|
| 468 |
-
# Resize very large images to prevent memory spikes
|
| 469 |
-
if max(orig_w, orig_h) > MAX_IMAGE_SIZE:
|
| 470 |
-
ratio = MAX_IMAGE_SIZE / max(orig_w, orig_h)
|
| 471 |
-
img_bgr = cv2.resize(img_bgr, None, fx=ratio, fy=ratio)
|
| 472 |
-
orig_h, orig_w = img_bgr.shape[:2]
|
| 473 |
-
log.info("Resized to: %dx%d px", orig_w, orig_h)
|
| 474 |
-
|
| 475 |
-
# ββ 4. Preprocess ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 476 |
-
tensor, scale, pad_x, pad_y = preprocess(img_bgr)
|
| 477 |
-
|
| 478 |
-
# ββ 5. Inference βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 479 |
-
input_name = ort_session.get_inputs()[0].name
|
| 480 |
-
t_inf = time.perf_counter()
|
| 481 |
-
raw_output = ort_session.run(None, {input_name: tensor})
|
| 482 |
-
log.info("Inference: %.1f ms", (time.perf_counter() - t_inf) * 1000)
|
| 483 |
-
|
| 484 |
-
# ββ 6. Postprocess βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 485 |
-
detections = postprocess(
|
| 486 |
-
raw_output[0],
|
| 487 |
-
orig_w, orig_h,
|
| 488 |
-
scale, pad_x, pad_y,
|
| 489 |
-
CONF_THRESHOLD, IOU_THRESHOLD,
|
| 490 |
-
)
|
| 491 |
-
log.info("Detections: %d logos found", len(detections))
|
| 492 |
-
|
| 493 |
-
# Limit results
|
| 494 |
-
detections = detections[:max_logos]
|
| 495 |
-
|
| 496 |
-
# ββ 7. Crop + encode βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 497 |
logos = []
|
| 498 |
-
fmt
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
"base64": b64,
|
| 517 |
-
"mime_type": mime,
|
| 518 |
-
"width": cw,
|
| 519 |
-
"height": ch,
|
| 520 |
-
"confidence": det["confidence"],
|
| 521 |
-
"bbox": {
|
| 522 |
-
"x1": det["x1"], "y1": det["y1"],
|
| 523 |
-
"x2": det["x2"], "y2": det["y2"],
|
| 524 |
-
},
|
| 525 |
-
})
|
| 526 |
-
|
| 527 |
-
# ββ 8. Cleanup (important on free tier) ββββββββββββββββββββββββββββββββββ
|
| 528 |
-
del img_bgr, tensor, raw_output, nparr, raw_bytes
|
| 529 |
-
gc.collect()
|
| 530 |
-
|
| 531 |
-
elapsed_ms = round((time.perf_counter() - t_start) * 1000, 1)
|
| 532 |
-
log.info("Total elapsed: %.1f ms | Logos returned: %d", elapsed_ms, len(logos))
|
| 533 |
-
|
| 534 |
-
return JSONResponse(content={
|
| 535 |
-
"success": True,
|
| 536 |
-
"count": len(logos),
|
| 537 |
-
"elapsed_ms": elapsed_ms,
|
| 538 |
-
"logos": logos,
|
| 539 |
-
})
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
# βββ Entry point (local testing) βββββββββββββββββββββββββββββββββββββββββββββ
|
| 543 |
if __name__ == "__main__":
|
| 544 |
import uvicorn
|
| 545 |
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)
|
|
|
|
| 1 |
"""
|
| 2 |
+
Logo Extractor β Full Stack App
|
| 3 |
+
================================
|
| 4 |
+
FastAPI backend + Built-in HTML UI + Admin Panel
|
| 5 |
+
All-in-one HF Space deployment
|
| 6 |
+
|
| 7 |
+
Secrets to set in HF Space Settings β Variables and secrets:
|
| 8 |
+
APP_SECRET_KEY β master backend secret (for your own server β HF calls)
|
| 9 |
+
ADMIN_PASSWORD β password for /admin panel
|
| 10 |
+
API_KEYS_JSON β JSON array of active user API keys
|
| 11 |
+
e.g. ["logo-abc123", "logo-xyz999"]
|
| 12 |
+
HF_TOKEN β your HF token (for model downloads)
|
| 13 |
"""
|
| 14 |
|
| 15 |
from __future__ import annotations
|
| 16 |
|
| 17 |
+
import os, gc, io, time, base64, json, logging, secrets, hashlib
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
from contextlib import asynccontextmanager
|
| 19 |
from typing import Optional
|
| 20 |
+
from datetime import datetime
|
| 21 |
|
| 22 |
+
import cv2, numpy as np
|
| 23 |
+
from fastapi import (FastAPI, File, Header, HTTPException, UploadFile,
|
| 24 |
+
Request, status, Form)
|
| 25 |
from fastapi.middleware.cors import CORSMiddleware
|
| 26 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 27 |
import onnxruntime as ort
|
| 28 |
from PIL import Image
|
| 29 |
|
| 30 |
# βββ Logging ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 31 |
+
logging.basicConfig(level=logging.INFO,
|
| 32 |
+
format="%(asctime)s | %(levelname)s | %(message)s")
|
|
|
|
|
|
|
| 33 |
log = logging.getLogger("logo-extractor")
|
| 34 |
|
| 35 |
+
# βββ Config from HF Secrets βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 36 |
+
MODEL_PATH = os.getenv("MODEL_PATH", "logo_detector.onnx")
|
| 37 |
+
MODEL_URL = os.getenv("MODEL_URL", "")
|
| 38 |
+
APP_SECRET_KEY = os.getenv("APP_SECRET_KEY", "") # serverβHF auth
|
| 39 |
+
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin123")
|
| 40 |
+
CONF_THRESHOLD = float(os.getenv("CONF_THRESHOLD", "0.35"))
|
| 41 |
+
IOU_THRESHOLD = float(os.getenv("IOU_THRESHOLD", "0.45"))
|
| 42 |
+
CROP_PADDING = int(os.getenv("CROP_PADDING", "10"))
|
| 43 |
+
MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "1920"))
|
| 44 |
+
INPUT_SIZE = 640
|
| 45 |
+
|
| 46 |
+
# API_KEYS_JSON β list of valid user-facing API keys (stored as HF Secret)
|
| 47 |
+
def _load_api_keys() -> set:
|
| 48 |
+
raw = os.getenv("API_KEYS_JSON", "[]")
|
| 49 |
+
try:
|
| 50 |
+
keys = json.loads(raw)
|
| 51 |
+
return set(keys) if isinstance(keys, list) else set()
|
| 52 |
+
except Exception:
|
| 53 |
+
return set()
|
| 54 |
+
|
| 55 |
+
VALID_API_KEYS: set = _load_api_keys()
|
| 56 |
+
|
| 57 |
+
# In-memory usage stats (resets on restart β Phase 3 mein DB add karna)
|
| 58 |
+
_stats: dict = {"total_requests": 0, "total_logos": 0, "errors": 0,
|
| 59 |
+
"start_time": datetime.utcnow().isoformat()}
|
| 60 |
+
|
| 61 |
+
# βββ Auth helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 62 |
+
def verify_api_key(key: str) -> None:
|
| 63 |
+
"""User-facing API key check."""
|
| 64 |
+
if not VALID_API_KEYS:
|
| 65 |
+
raise HTTPException(status_code=503,
|
| 66 |
+
detail="No API keys configured β set API_KEYS_JSON in Space secrets")
|
| 67 |
+
if key not in VALID_API_KEYS:
|
| 68 |
+
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 69 |
+
|
| 70 |
+
def verify_backend_secret(secret: str) -> None:
|
| 71 |
+
"""ServerβHF secret check (your backend uses this)."""
|
| 72 |
+
if not APP_SECRET_KEY:
|
| 73 |
+
raise HTTPException(status_code=503,
|
| 74 |
+
detail="APP_SECRET_KEY not configured")
|
| 75 |
+
if secret != APP_SECRET_KEY:
|
| 76 |
+
raise HTTPException(status_code=401, detail="Invalid backend secret")
|
| 77 |
|
| 78 |
+
def verify_admin(password: str) -> None:
|
| 79 |
+
if password != ADMIN_PASSWORD:
|
| 80 |
+
raise HTTPException(status_code=401, detail="Wrong admin password")
|
| 81 |
|
| 82 |
+
# βββ Model helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
def ensure_model() -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
if os.path.exists(MODEL_PATH):
|
| 85 |
log.info("Model found: %s (%.1f MB)", MODEL_PATH,
|
| 86 |
os.path.getsize(MODEL_PATH) / 1e6)
|
| 87 |
return
|
|
|
|
|
|
|
| 88 |
if MODEL_URL:
|
|
|
|
| 89 |
import urllib.request
|
| 90 |
+
log.info("Downloading from MODEL_URL...")
|
| 91 |
urllib.request.urlretrieve(MODEL_URL, MODEL_PATH)
|
|
|
|
|
|
|
| 92 |
return
|
| 93 |
+
log.info("Trying HF Hub: openfoodfacts/universal-logo-detector...")
|
|
|
|
|
|
|
|
|
|
| 94 |
try:
|
| 95 |
+
import shutil, onnx # noqa
|
|
|
|
| 96 |
from ultralytics import YOLO
|
| 97 |
+
m = YOLO("hf_hub:openfoodfacts/universal-logo-detector")
|
| 98 |
+
exported = m.export(format="onnx", imgsz=INPUT_SIZE, opset=17,
|
| 99 |
+
simplify=True, dynamic=False)
|
|
|
|
|
|
|
|
|
|
| 100 |
found = None
|
| 101 |
+
for c in [str(exported) if exported else "",
|
| 102 |
+
"universal-logo-detector.onnx", "best.onnx"]:
|
| 103 |
+
if c and os.path.exists(c):
|
| 104 |
+
found = c; break
|
|
|
|
|
|
|
| 105 |
if not found:
|
|
|
|
| 106 |
for root, _, files in os.walk("/app"):
|
| 107 |
for f in files:
|
| 108 |
if f.endswith(".onnx") and f != "logo_detector.onnx":
|
| 109 |
+
found = os.path.join(root, f); break
|
|
|
|
| 110 |
if found:
|
| 111 |
shutil.move(found, MODEL_PATH)
|
| 112 |
+
log.info("HF Hub model ready β %s", MODEL_PATH); return
|
|
|
|
|
|
|
|
|
|
| 113 |
except Exception as exc:
|
| 114 |
+
log.warning("HF Hub failed: %s", exc)
|
| 115 |
+
log.warning("Falling back to YOLOv8n...")
|
| 116 |
+
import shutil, onnx # noqa
|
| 117 |
+
from ultralytics import YOLO
|
| 118 |
+
m = YOLO("yolov8n.pt")
|
| 119 |
+
m.export(format="onnx", imgsz=INPUT_SIZE, opset=17,
|
| 120 |
+
simplify=True, dynamic=False)
|
| 121 |
+
for c in ["yolov8n.onnx", "yolov8n/yolov8n.onnx"]:
|
| 122 |
+
if os.path.exists(c):
|
| 123 |
+
os.rename(c, MODEL_PATH)
|
| 124 |
+
log.info("Fallback saved β %s", MODEL_PATH); return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
def load_model() -> ort.InferenceSession:
|
|
|
|
| 127 |
opts = ort.SessionOptions()
|
| 128 |
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 129 |
+
opts.intra_op_num_threads = 2
|
| 130 |
opts.inter_op_num_threads = 1
|
| 131 |
+
sess = ort.InferenceSession(MODEL_PATH, sess_options=opts,
|
| 132 |
+
providers=["CPUExecutionProvider"])
|
| 133 |
+
log.info("Model loaded | in=%s out=%s",
|
| 134 |
+
sess.get_inputs()[0].shape, sess.get_outputs()[0].shape)
|
| 135 |
+
return sess
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
ort_session: Optional[ort.InferenceSession] = None
|
| 138 |
|
|
|
|
| 139 |
@asynccontextmanager
|
| 140 |
async def lifespan(app: FastAPI):
|
| 141 |
global ort_session
|
| 142 |
+
log.info("Starting up...")
|
| 143 |
ensure_model()
|
|
|
|
| 144 |
try:
|
| 145 |
ort_session = load_model()
|
| 146 |
+
except Exception as e:
|
| 147 |
+
log.error("Model load failed: %s", e)
|
| 148 |
yield
|
| 149 |
+
del ort_session; gc.collect()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
+
# βββ Image processing ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 152 |
+
def preprocess(img):
|
| 153 |
+
h, w = img.shape[:2]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
scale = min(INPUT_SIZE / w, INPUT_SIZE / h)
|
| 155 |
+
nw, nh = int(w * scale), int(h * scale)
|
| 156 |
+
resized = cv2.resize(img, (nw, nh))
|
| 157 |
+
px, py = (INPUT_SIZE - nw) // 2, (INPUT_SIZE - nh) // 2
|
| 158 |
+
padded = cv2.copyMakeBorder(resized, py, INPUT_SIZE-nh-py,
|
| 159 |
+
px, INPUT_SIZE-nw-px,
|
| 160 |
+
cv2.BORDER_CONSTANT, value=(114,114,114))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
rgb = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB)
|
| 162 |
+
t = rgb.astype(np.float32) / 255.0
|
| 163 |
+
return np.expand_dims(np.transpose(t, (2,0,1)), 0), scale, px, py
|
| 164 |
+
|
| 165 |
+
def nms(boxes, scores, thresh):
|
| 166 |
+
if not len(boxes): return []
|
| 167 |
+
x1,y1,x2,y2 = boxes[:,0],boxes[:,1],boxes[:,2],boxes[:,3]
|
| 168 |
+
areas = (x2-x1)*(y2-y1); order = scores.argsort()[::-1]; keep = []
|
| 169 |
+
while order.size:
|
| 170 |
+
i = order[0]; keep.append(int(i))
|
| 171 |
+
xx1=np.maximum(x1[i],x1[order[1:]]); yy1=np.maximum(y1[i],y1[order[1:]])
|
| 172 |
+
xx2=np.minimum(x2[i],x2[order[1:]]); yy2=np.minimum(y2[i],y2[order[1:]])
|
| 173 |
+
inter=np.maximum(0,xx2-xx1)*np.maximum(0,yy2-yy1)
|
| 174 |
+
iou=inter/(areas[i]+areas[order[1:]]-inter+1e-6)
|
| 175 |
+
order=order[1:][iou<=thresh]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
return keep
|
| 177 |
|
| 178 |
+
def postprocess(raw, ow, oh, scale, px, py):
|
| 179 |
+
pred = raw[0].T
|
| 180 |
+
cx,cy,bw,bh = pred[:,0],pred[:,1],pred[:,2],pred[:,3]
|
| 181 |
+
conf = pred[:,4:].max(1) if pred.shape[1]>5 else pred[:,4]
|
| 182 |
+
mask = conf >= CONF_THRESHOLD
|
| 183 |
+
if not mask.any(): return []
|
| 184 |
+
cx,cy,bw,bh,conf = cx[mask],cy[mask],bw[mask],bh[mask],conf[mask]
|
| 185 |
+
x1,y1,x2,y2 = cx-bw/2,cy-bh/2,cx+bw/2,cy+bh/2
|
| 186 |
+
boxes = np.stack([x1,y1,x2,y2],1)
|
| 187 |
+
keep = nms(boxes, conf, IOU_THRESHOLD)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
results = []
|
| 189 |
+
for box, score in zip(boxes[keep], conf[keep]):
|
| 190 |
+
ox1=max(0,int((box[0]-px)/scale)); oy1=max(0,int((box[1]-py)/scale))
|
| 191 |
+
ox2=min(ow,int((box[2]-px)/scale)); oy2=min(oh,int((box[3]-py)/scale))
|
| 192 |
+
if ox2>ox1 and oy2>oy1:
|
| 193 |
+
results.append({"x1":ox1,"y1":oy1,"x2":ox2,"y2":oy2,
|
| 194 |
+
"confidence":round(float(score),4)})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
return results
|
| 196 |
|
| 197 |
+
def crop_to_b64(img, box, fmt="PNG"):
|
| 198 |
+
h,w = img.shape[:2]
|
| 199 |
+
x1=max(0,box["x1"]-CROP_PADDING); y1=max(0,box["y1"]-CROP_PADDING)
|
| 200 |
+
x2=min(w,box["x2"]+CROP_PADDING); y2=min(h,box["y2"]+CROP_PADDING)
|
| 201 |
+
crop = img[y1:y2, x1:x2]
|
| 202 |
+
if fmt=="TRANSPARENT":
|
| 203 |
+
rgb=cv2.cvtColor(crop,cv2.COLOR_BGR2RGB)
|
| 204 |
+
mask=np.all(rgb>240,2).astype(np.uint8)*255
|
| 205 |
+
rgba=np.dstack([rgb,255-mask])
|
| 206 |
+
pil=Image.fromarray(rgba,"RGBA")
|
| 207 |
+
else:
|
| 208 |
+
pil=Image.fromarray(cv2.cvtColor(crop,cv2.COLOR_BGR2RGB))
|
| 209 |
+
buf=io.BytesIO(); pil.save(buf,format="PNG" if fmt!="JPEG" else "JPEG")
|
| 210 |
+
return base64.b64encode(buf.getvalue()).decode(), x2-x1, y2-y1
|
| 211 |
|
| 212 |
+
# βββ App βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 213 |
+
app = FastAPI(title="Logo Extractor", version="1.0.0", lifespan=lifespan,
|
| 214 |
+
docs_url="/api/docs", redoc_url=None)
|
| 215 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
| 216 |
+
allow_methods=["*"], allow_headers=["*"])
|
| 217 |
+
|
| 218 |
+
# βββ HTML UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 219 |
+
HTML_UI = """<!DOCTYPE html>
|
| 220 |
+
<html lang="en">
|
| 221 |
+
<head>
|
| 222 |
+
<meta charset="UTF-8">
|
| 223 |
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 224 |
+
<title>Logo Extractor API</title>
|
| 225 |
+
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
|
| 226 |
+
<style>
|
| 227 |
+
:root{
|
| 228 |
+
--bg:#0a0a0f;--surface:#13131a;--surface2:#1c1c28;--border:#2a2a3a;
|
| 229 |
+
--accent:#7c5cfc;--accent2:#a78bfa;--green:#22d3a0;--red:#ff4f6d;
|
| 230 |
+
--text:#f0f0f8;--muted:#8888aa;--font:'Syne',sans-serif;--mono:'DM Mono',monospace;
|
| 231 |
+
}
|
| 232 |
+
*{box-sizing:border-box;margin:0;padding:0}
|
| 233 |
+
body{background:var(--bg);color:var(--text);font-family:var(--font);min-height:100vh;overflow-x:hidden}
|
| 234 |
+
/* noise overlay */
|
| 235 |
+
body::before{content:'';position:fixed;inset:0;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.04'/%3E%3C/svg%3E");pointer-events:none;z-index:0;opacity:.5}
|
| 236 |
+
|
| 237 |
+
.wrap{max-width:1100px;margin:0 auto;padding:0 24px;position:relative;z-index:1}
|
| 238 |
+
|
| 239 |
+
/* ββ Header ββ */
|
| 240 |
+
header{padding:28px 0 0;display:flex;align-items:center;justify-content:space-between}
|
| 241 |
+
.logo{display:flex;align-items:center;gap:10px}
|
| 242 |
+
.logo-icon{width:36px;height:36px;background:var(--accent);border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:18px}
|
| 243 |
+
.logo-text{font-size:18px;font-weight:800;letter-spacing:-.5px}
|
| 244 |
+
.logo-text span{color:var(--accent2)}
|
| 245 |
+
.status-pill{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);font-family:var(--mono);border:1px solid var(--border);padding:6px 14px;border-radius:20px}
|
| 246 |
+
.status-dot{width:7px;height:7px;border-radius:50%;background:var(--green);animation:pulse 2s infinite}
|
| 247 |
+
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}
|
| 248 |
+
|
| 249 |
+
/* ββ Tabs ββ */
|
| 250 |
+
.tabs{display:flex;gap:0;border-bottom:1px solid var(--border);margin-top:32px}
|
| 251 |
+
.tab{padding:12px 22px;font-size:14px;font-weight:600;cursor:pointer;color:var(--muted);border-bottom:2px solid transparent;transition:all .2s;background:none;border-top:none;border-left:none;border-right:none;font-family:var(--font);letter-spacing:.3px}
|
| 252 |
+
.tab:hover{color:var(--text)}
|
| 253 |
+
.tab.active{color:var(--accent2);border-bottom-color:var(--accent)}
|
| 254 |
+
.panel{display:none;padding:32px 0}
|
| 255 |
+
.panel.active{display:block}
|
| 256 |
+
|
| 257 |
+
/* ββ Cards ββ */
|
| 258 |
+
.card{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:24px}
|
| 259 |
+
.grid-2{display:grid;grid-template-columns:1fr 1fr;gap:20px}
|
| 260 |
+
@media(max-width:700px){.grid-2{grid-template-columns:1fr}}
|
| 261 |
+
|
| 262 |
+
/* ββ Form elements ββ */
|
| 263 |
+
label{display:block;font-size:12px;font-weight:600;color:var(--muted);letter-spacing:.8px;text-transform:uppercase;margin-bottom:8px}
|
| 264 |
+
input[type=text],input[type=password],select,textarea{
|
| 265 |
+
width:100%;background:var(--surface2);border:1px solid var(--border);border-radius:8px;
|
| 266 |
+
padding:11px 14px;color:var(--text);font-family:var(--mono);font-size:13px;
|
| 267 |
+
outline:none;transition:border-color .2s}
|
| 268 |
+
input[type=text]:focus,input[type=password]:focus,select:focus{border-color:var(--accent)}
|
| 269 |
+
select option{background:var(--surface2)}
|
| 270 |
+
|
| 271 |
+
/* ββ Upload zone ββ */
|
| 272 |
+
.upload-zone{border:2px dashed var(--border);border-radius:12px;padding:40px;text-align:center;cursor:pointer;transition:all .2s;position:relative;overflow:hidden}
|
| 273 |
+
.upload-zone:hover,.upload-zone.dragover{border-color:var(--accent);background:rgba(124,92,252,.05)}
|
| 274 |
+
.upload-zone input{position:absolute;inset:0;opacity:0;cursor:pointer}
|
| 275 |
+
.upload-icon{font-size:32px;margin-bottom:12px;opacity:.5}
|
| 276 |
+
.upload-text{font-size:14px;color:var(--muted)}
|
| 277 |
+
.upload-text strong{color:var(--accent2)}
|
| 278 |
+
.preview-img{max-width:100%;max-height:220px;border-radius:8px;margin-top:12px;display:none}
|
| 279 |
+
|
| 280 |
+
/* ββ Buttons ββ */
|
| 281 |
+
.btn{display:inline-flex;align-items:center;gap:8px;padding:12px 24px;border-radius:9px;font-family:var(--font);font-size:14px;font-weight:700;cursor:pointer;border:none;transition:all .18s;letter-spacing:.3px}
|
| 282 |
+
.btn-primary{background:var(--accent);color:#fff}
|
| 283 |
+
.btn-primary:hover{background:#6a4ee8;transform:translateY(-1px)}
|
| 284 |
+
.btn-primary:active{transform:translateY(0)}
|
| 285 |
+
.btn-primary:disabled{opacity:.5;cursor:not-allowed;transform:none}
|
| 286 |
+
.btn-outline{background:transparent;color:var(--accent2);border:1px solid var(--accent)}
|
| 287 |
+
.btn-outline:hover{background:rgba(124,92,252,.1)}
|
| 288 |
+
.btn-danger{background:transparent;color:var(--red);border:1px solid var(--red)}
|
| 289 |
+
.btn-danger:hover{background:rgba(255,79,109,.1)}
|
| 290 |
+
.btn-full{width:100%;justify-content:center;margin-top:16px}
|
| 291 |
+
|
| 292 |
+
/* ββ API Key input ββ */
|
| 293 |
+
.key-wrap{position:relative}
|
| 294 |
+
.key-wrap input{padding-right:44px;font-size:13px;letter-spacing:1px}
|
| 295 |
+
.key-eye{position:absolute;right:12px;top:50%;transform:translateY(-50%);cursor:pointer;color:var(--muted);font-size:18px;background:none;border:none;color:var(--muted)}
|
| 296 |
+
|
| 297 |
+
/* ββ Result area ββ */
|
| 298 |
+
.result-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}
|
| 299 |
+
.result-title{font-size:14px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.8px}
|
| 300 |
+
.result-area{background:var(--surface2);border:1px solid var(--border);border-radius:12px;min-height:200px;display:flex;align-items:center;justify-content:center;overflow:hidden;position:relative}
|
| 301 |
+
.result-placeholder{text-align:center;color:var(--muted);font-size:14px}
|
| 302 |
+
.result-placeholder .icon{font-size:36px;margin-bottom:12px;opacity:.3}
|
| 303 |
+
.logos-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:12px;padding:16px;width:100%}
|
| 304 |
+
.logo-thumb{background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:8px;text-align:center;animation:fadeIn .3s ease}
|
| 305 |
+
@keyframes fadeIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}
|
| 306 |
+
.logo-thumb img{max-width:100%;max-height:80px;object-fit:contain;border-radius:4px}
|
| 307 |
+
.logo-thumb .conf{font-size:11px;color:var(--green);font-family:var(--mono);margin-top:6px}
|
| 308 |
+
.logo-thumb .dl{font-size:11px;color:var(--accent2);cursor:pointer;text-decoration:underline;margin-top:2px}
|
| 309 |
+
|
| 310 |
+
/* ββ Stats ββ */
|
| 311 |
+
.stats-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin-bottom:24px}
|
| 312 |
+
.stat-box{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:16px}
|
| 313 |
+
.stat-num{font-size:26px;font-weight:800;color:var(--accent2)}
|
| 314 |
+
.stat-lbl{font-size:12px;color:var(--muted);margin-top:4px;font-family:var(--mono)}
|
| 315 |
+
|
| 316 |
+
/* ββ Code block ββ */
|
| 317 |
+
pre{background:var(--surface2);border:1px solid var(--border);border-radius:10px;padding:18px;font-family:var(--mono);font-size:12px;overflow-x:auto;line-height:1.7;color:#c9d1d9}
|
| 318 |
+
.code-label{font-size:11px;font-weight:600;color:var(--muted);letter-spacing:.8px;text-transform:uppercase;margin-bottom:6px}
|
| 319 |
+
.hl-green{color:var(--green)}
|
| 320 |
+
.hl-purple{color:var(--accent2)}
|
| 321 |
+
.hl-yellow{color:#fbbf24}
|
| 322 |
+
|
| 323 |
+
/* ββ Admin table ββ */
|
| 324 |
+
table{width:100%;border-collapse:collapse;font-size:13px}
|
| 325 |
+
th{text-align:left;padding:10px 14px;font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.8px;border-bottom:1px solid var(--border)}
|
| 326 |
+
td{padding:12px 14px;border-bottom:1px solid rgba(42,42,58,.5);font-family:var(--mono);font-size:12px}
|
| 327 |
+
tr:last-child td{border-bottom:none}
|
| 328 |
+
.badge{display:inline-block;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
|
| 329 |
+
.badge-active{background:rgba(34,211,160,.15);color:var(--green);border:1px solid rgba(34,211,160,.3)}
|
| 330 |
+
.badge-inactive{background:rgba(255,79,109,.1);color:var(--red);border:1px solid rgba(255,79,109,.3)}
|
| 331 |
+
|
| 332 |
+
/* ββ Toast ββ */
|
| 333 |
+
#toast{position:fixed;bottom:28px;right:28px;background:var(--surface);border:1px solid var(--border);padding:14px 22px;border-radius:10px;font-size:13px;z-index:999;transform:translateY(80px);opacity:0;transition:all .3s;max-width:320px}
|
| 334 |
+
#toast.show{transform:translateY(0);opacity:1}
|
| 335 |
+
#toast.success{border-color:var(--green);color:var(--green)}
|
| 336 |
+
#toast.error{border-color:var(--red);color:var(--red)}
|
| 337 |
+
|
| 338 |
+
/* ββ Spinner ββ */
|
| 339 |
+
.spinner{display:inline-block;width:18px;height:18px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite}
|
| 340 |
+
@keyframes spin{to{transform:rotate(360deg)}}
|
| 341 |
+
|
| 342 |
+
/* ββ Progress ββ */
|
| 343 |
+
.progress{height:3px;background:var(--border);border-radius:2px;overflow:hidden;margin-top:8px}
|
| 344 |
+
.progress-bar{height:100%;background:linear-gradient(90deg,var(--accent),var(--accent2));width:0;transition:width .4s;border-radius:2px}
|
| 345 |
+
|
| 346 |
+
footer{padding:32px 0;text-align:center;font-size:12px;color:var(--muted);border-top:1px solid var(--border);margin-top:48px;font-family:var(--mono)}
|
| 347 |
+
</style>
|
| 348 |
+
</head>
|
| 349 |
+
<body>
|
| 350 |
+
<div class="wrap">
|
| 351 |
+
|
| 352 |
+
<!-- Header -->
|
| 353 |
+
<header>
|
| 354 |
+
<div class="logo">
|
| 355 |
+
<div class="logo-icon">β</div>
|
| 356 |
+
<div class="logo-text">Logo<span>Ex</span></div>
|
| 357 |
+
</div>
|
| 358 |
+
<div class="status-pill">
|
| 359 |
+
<div class="status-dot"></div>
|
| 360 |
+
<span id="status-text">checking...</span>
|
| 361 |
+
</div>
|
| 362 |
+
</header>
|
| 363 |
+
|
| 364 |
+
<!-- Tabs -->
|
| 365 |
+
<div class="tabs">
|
| 366 |
+
<button class="tab active" onclick="switchTab('extract')">β Extract Logo</button>
|
| 367 |
+
<button class="tab" onclick="switchTab('usage')">π My Usage</button>
|
| 368 |
+
<button class="tab" onclick="switchTab('docs')">π API Docs</button>
|
| 369 |
+
<button class="tab" onclick="switchTab('admin')">π Admin</button>
|
| 370 |
+
</div>
|
| 371 |
+
|
| 372 |
+
<!-- ββ TAB: Extract ββ -->
|
| 373 |
+
<div id="tab-extract" class="panel active">
|
| 374 |
+
<div class="grid-2">
|
| 375 |
+
<!-- Left: Input -->
|
| 376 |
+
<div style="display:flex;flex-direction:column;gap:16px">
|
| 377 |
+
<div class="card">
|
| 378 |
+
<label>π API Key</label>
|
| 379 |
+
<div class="key-wrap">
|
| 380 |
+
<input type="password" id="api-key" placeholder="logo-xxxx-xxxx" autocomplete="off">
|
| 381 |
+
<button class="key-eye" onclick="toggleKeyVis()">π</button>
|
| 382 |
+
</div>
|
| 383 |
+
</div>
|
| 384 |
+
<div class="card">
|
| 385 |
+
<label>π Upload Image</label>
|
| 386 |
+
<div class="upload-zone" id="drop-zone">
|
| 387 |
+
<input type="file" id="file-input" accept="image/*" onchange="onFileChange(this)">
|
| 388 |
+
<div class="upload-icon">πΌ</div>
|
| 389 |
+
<div class="upload-text">Drop image here β or <strong>click to upload</strong></div>
|
| 390 |
+
<div class="upload-text" style="font-size:12px;margin-top:6px">JPEG Β· PNG Β· WEBP Β· max 15MB</div>
|
| 391 |
+
<img id="preview" class="preview-img">
|
| 392 |
+
</div>
|
| 393 |
+
<div class="progress" id="prog-wrap" style="display:none"><div class="progress-bar" id="prog-bar"></div></div>
|
| 394 |
+
</div>
|
| 395 |
+
<div class="card">
|
| 396 |
+
<label>β Output Format</label>
|
| 397 |
+
<select id="fmt-select">
|
| 398 |
+
<option value="PNG">PNG (recommended)</option>
|
| 399 |
+
<option value="JPEG">JPEG (smaller)</option>
|
| 400 |
+
<option value="TRANSPARENT">Transparent PNG (remove white bg)</option>
|
| 401 |
+
</select>
|
| 402 |
+
</div>
|
| 403 |
+
<button class="btn btn-primary btn-full" id="extract-btn" onclick="doExtract()">
|
| 404 |
+
<span id="btn-inner">β Extract Logos</span>
|
| 405 |
+
</button>
|
| 406 |
+
</div>
|
| 407 |
+
<!-- Right: Results -->
|
| 408 |
+
<div>
|
| 409 |
+
<div class="result-header">
|
| 410 |
+
<div class="result-title" id="result-title">Result</div>
|
| 411 |
+
<button class="btn btn-outline" id="dl-all-btn" style="display:none;padding:8px 14px;font-size:12px" onclick="downloadAll()">β¬ Download All</button>
|
| 412 |
+
</div>
|
| 413 |
+
<div class="result-area" id="result-area">
|
| 414 |
+
<div class="result-placeholder">
|
| 415 |
+
<div class="icon">β</div>
|
| 416 |
+
<div>Upload an image and click<br><strong>Extract Logos</strong></div>
|
| 417 |
+
</div>
|
| 418 |
+
</div>
|
| 419 |
+
<div id="result-meta" style="margin-top:12px;font-size:12px;color:var(--muted);font-family:var(--mono)"></div>
|
| 420 |
+
</div>
|
| 421 |
+
</div>
|
| 422 |
+
</div>
|
| 423 |
+
|
| 424 |
+
<!-- ββ TAB: Usage ββ -->
|
| 425 |
+
<div id="tab-usage" class="panel">
|
| 426 |
+
<div class="stats-row" id="usage-stats">
|
| 427 |
+
<div class="stat-box"><div class="stat-num" id="u-total">β</div><div class="stat-lbl">Total Requests</div></div>
|
| 428 |
+
<div class="stat-box"><div class="stat-num" id="u-logos">β</div><div class="stat-lbl">Logos Extracted</div></div>
|
| 429 |
+
<div class="stat-box"><div class="stat-num" id="u-errors">β</div><div class="stat-lbl">Errors</div></div>
|
| 430 |
+
<div class="stat-box"><div class="stat-num" id="u-uptime">β</div><div class="stat-lbl">Uptime</div></div>
|
| 431 |
+
</div>
|
| 432 |
+
<div class="card">
|
| 433 |
+
<label>Your API Key Status</label>
|
| 434 |
+
<div style="display:flex;gap:10px;margin-top:4px">
|
| 435 |
+
<input type="text" id="check-key" placeholder="Enter your API key to verify">
|
| 436 |
+
<button class="btn btn-outline" onclick="checkKey()" style="flex-shrink:0">Verify</button>
|
| 437 |
+
</div>
|
| 438 |
+
<div id="key-status" style="margin-top:12px;font-size:13px;font-family:var(--mono)"></div>
|
| 439 |
+
</div>
|
| 440 |
+
</div>
|
| 441 |
+
|
| 442 |
+
<!-- ββ TAB: Docs ββ -->
|
| 443 |
+
<div id="tab-docs" class="panel">
|
| 444 |
+
<div style="display:flex;flex-direction:column;gap:24px">
|
| 445 |
+
<div class="card">
|
| 446 |
+
<div style="font-size:20px;font-weight:800;margin-bottom:8px">Logo Extractor API</div>
|
| 447 |
+
<div style="color:var(--muted);font-size:14px;line-height:1.7">
|
| 448 |
+
Extract logos from any image with a single POST request. Returns cropped logos as base64 PNG/JPEG/Transparent.
|
| 449 |
+
</div>
|
| 450 |
+
</div>
|
| 451 |
+
<div class="card">
|
| 452 |
+
<div class="code-label">Base URL</div>
|
| 453 |
+
<pre><span class="hl-green">https://YOUR-HF-USERNAME-logo-extractor.hf.space</span></pre>
|
| 454 |
+
</div>
|
| 455 |
+
<div class="card">
|
| 456 |
+
<div class="code-label">Authentication</div>
|
| 457 |
+
<div style="font-size:13px;color:var(--muted);margin-bottom:12px;line-height:1.7">
|
| 458 |
+
All requests require an <code style="background:var(--surface2);padding:2px 6px;border-radius:4px">X-API-Key</code> header with a valid API key.
|
| 459 |
+
</div>
|
| 460 |
+
<pre><span class="hl-purple">POST</span> <span class="hl-yellow">/extract-logo</span>
|
| 461 |
+
<span class="hl-green">X-API-Key:</span> logo-xxxx-xxxx
|
| 462 |
+
<span class="hl-green">Content-Type:</span> multipart/form-data
|
| 463 |
+
|
| 464 |
+
<span class="hl-green">Body:</span>
|
| 465 |
+
image file Image file (JPEG/PNG/WEBP, max 15MB)
|
| 466 |
+
output_format string PNG | JPEG | TRANSPARENT (default: PNG)
|
| 467 |
+
max_logos int Max results (default: 20)</pre>
|
| 468 |
+
</div>
|
| 469 |
+
<div class="card">
|
| 470 |
+
<div class="code-label">Response</div>
|
| 471 |
+
<pre>{
|
| 472 |
+
<span class="hl-green">"success"</span>: true,
|
| 473 |
+
<span class="hl-green">"count"</span>: 2,
|
| 474 |
+
<span class="hl-green">"elapsed_ms"</span>: 312.5,
|
| 475 |
+
<span class="hl-green">"logos"</span>: [
|
| 476 |
+
{
|
| 477 |
+
<span class="hl-green">"base64"</span>: <span class="hl-yellow">"iVBORw0KGgo..."</span>,
|
| 478 |
+
<span class="hl-green">"mime_type"</span>: <span class="hl-yellow">"image/png"</span>,
|
| 479 |
+
<span class="hl-green">"width"</span>: 180,
|
| 480 |
+
<span class="hl-green">"height"</span>: 90,
|
| 481 |
+
<span class="hl-green">"confidence"</span>: 0.8923,
|
| 482 |
+
<span class="hl-green">"bbox"</span>: {<span class="hl-green">"x1"</span>:45,<span class="hl-green">"y1"</span>:12,<span class="hl-green">"x2"</span>:225,<span class="hl-green">"y2"</span>:102}
|
| 483 |
+
}
|
| 484 |
+
]
|
| 485 |
+
}</pre>
|
| 486 |
+
</div>
|
| 487 |
+
<div class="card">
|
| 488 |
+
<div class="code-label">Python example</div>
|
| 489 |
+
<pre>import requests, base64
|
| 490 |
+
from pathlib import Path
|
| 491 |
+
|
| 492 |
+
resp = requests.post(
|
| 493 |
+
<span class="hl-yellow">"https://YOUR-SPACE.hf.space/extract-logo"</span>,
|
| 494 |
+
headers={<span class="hl-yellow">"X-API-Key"</span>: <span class="hl-yellow">"logo-xxxx-xxxx"</span>},
|
| 495 |
+
files={<span class="hl-yellow">"image"</span>: open(<span class="hl-yellow">"image.jpg"</span>, <span class="hl-yellow">"rb"</span>)},
|
| 496 |
+
params={<span class="hl-yellow">"output_format"</span>: <span class="hl-yellow">"PNG"</span>}
|
| 497 |
+
)
|
| 498 |
+
for i, logo in enumerate(resp.json()[<span class="hl-yellow">"logos"</span>]):
|
| 499 |
+
Path(f<span class="hl-yellow">"logo_{i}.png"</span>).write_bytes(
|
| 500 |
+
base64.b64decode(logo[<span class="hl-yellow">"base64"</span>]))</pre>
|
| 501 |
+
</div>
|
| 502 |
+
<div class="card">
|
| 503 |
+
<div style="font-weight:700;margin-bottom:12px">Plans & Limits</div>
|
| 504 |
+
<table>
|
| 505 |
+
<tr><th>Plan</th><th>Daily Limit</th><th>Access</th><th>Price</th></tr>
|
| 506 |
+
<tr><td>Free</td><td>50 images/day</td><td>API Key required</td><td style="color:var(--green)">$0</td></tr>
|
| 507 |
+
<tr><td>Starter</td><td>500 images/day</td><td>API Key required</td><td>$9/mo</td></tr>
|
| 508 |
+
<tr><td>Pro</td><td>Unlimited</td><td>API Key required</td><td>$29/mo</td></tr>
|
| 509 |
+
</table>
|
| 510 |
+
<div style="margin-top:14px;font-size:13px;color:var(--muted)">
|
| 511 |
+
π§ Email <strong style="color:var(--accent2)">support@yourdomain.com</strong> to get your API key, or check Admin tab.
|
| 512 |
+
</div>
|
| 513 |
+
</div>
|
| 514 |
+
</div>
|
| 515 |
+
</div>
|
| 516 |
+
|
| 517 |
+
<!-- ββ TAB: Admin ββ -->
|
| 518 |
+
<div id="tab-admin" class="panel">
|
| 519 |
+
<div id="admin-login" class="card" style="max-width:400px">
|
| 520 |
+
<div style="font-size:18px;font-weight:800;margin-bottom:16px">π Admin Login</div>
|
| 521 |
+
<label>Admin Password</label>
|
| 522 |
+
<input type="password" id="admin-pass" placeholder="Enter admin password" onkeyup="if(event.key==='Enter')adminLogin()">
|
| 523 |
+
<button class="btn btn-primary btn-full" onclick="adminLogin()">Login</button>
|
| 524 |
+
<div id="admin-login-err" style="margin-top:10px;font-size:13px;color:var(--red)"></div>
|
| 525 |
+
</div>
|
| 526 |
+
<div id="admin-panel" style="display:none">
|
| 527 |
+
<div class="stats-row">
|
| 528 |
+
<div class="stat-box"><div class="stat-num" id="a-reqs">0</div><div class="stat-lbl">Total Requests</div></div>
|
| 529 |
+
<div class="stat-box"><div class="stat-num" id="a-logos">0</div><div class="stat-lbl">Logos Extracted</div></div>
|
| 530 |
+
<div class="stat-box"><div class="stat-num" id="a-errs">0</div><div class="stat-lbl">Errors</div></div>
|
| 531 |
+
<div class="stat-box"><div class="stat-num" id="a-keys">0</div><div class="stat-lbl">Active Keys</div></div>
|
| 532 |
+
</div>
|
| 533 |
+
<div class="card" style="margin-bottom:20px">
|
| 534 |
+
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px">
|
| 535 |
+
<div style="font-weight:700">API Keys</div>
|
| 536 |
+
<button class="btn btn-outline" onclick="genKey()" style="padding:8px 14px;font-size:12px">+ Generate Key</button>
|
| 537 |
+
</div>
|
| 538 |
+
<table id="keys-table">
|
| 539 |
+
<tr><th>Key</th><th>Status</th><th>Note</th></tr>
|
| 540 |
+
</table>
|
| 541 |
+
<div style="margin-top:16px;font-size:12px;color:var(--muted);line-height:1.7;font-family:var(--mono)">
|
| 542 |
+
β Keys are loaded from <strong>API_KEYS_JSON</strong> secret.<br>
|
| 543 |
+
To add/remove keys: HF Space β Settings β Secrets β Replace API_KEYS_JSON<br>
|
| 544 |
+
Format: <code>["logo-key1","logo-key2"]</code>
|
| 545 |
+
</div>
|
| 546 |
+
</div>
|
| 547 |
+
<div class="card">
|
| 548 |
+
<div style="font-weight:700;margin-bottom:12px">Model Info</div>
|
| 549 |
+
<div id="model-info" style="font-family:var(--mono);font-size:12px;color:var(--muted);line-height:2"></div>
|
| 550 |
+
</div>
|
| 551 |
+
</div>
|
| 552 |
+
</div>
|
| 553 |
+
|
| 554 |
+
</div><!-- /wrap -->
|
| 555 |
+
<footer>Logo Extractor API Β· v1.0.0 Β· Powered by YOLOv8 + ONNX Runtime</footer>
|
| 556 |
+
<div id="toast"></div>
|
| 557 |
+
|
| 558 |
+
<script>
|
| 559 |
+
let adminToken = null;
|
| 560 |
+
let extractedLogos = [];
|
| 561 |
+
|
| 562 |
+
// ββ Tab switching ββ
|
| 563 |
+
function switchTab(name) {
|
| 564 |
+
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
| 565 |
+
document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
|
| 566 |
+
document.getElementById('tab-'+name).classList.add('active');
|
| 567 |
+
event.target.classList.add('active');
|
| 568 |
+
if(name==='usage') loadUsage();
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
// ββ Toast ββ
|
| 572 |
+
function toast(msg, type='success') {
|
| 573 |
+
const t = document.getElementById('toast');
|
| 574 |
+
t.textContent = msg; t.className = 'show ' + type;
|
| 575 |
+
setTimeout(() => t.className = '', 3000);
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
// ββ Status check ββ
|
| 579 |
+
async function checkStatus() {
|
| 580 |
+
try {
|
| 581 |
+
const r = await fetch('/health');
|
| 582 |
+
const d = await r.json();
|
| 583 |
+
document.getElementById('status-text').textContent =
|
| 584 |
+
d.model_loaded ? 'API Running Β· Model Ready' : 'API Running Β· Model Loading...';
|
| 585 |
+
} catch(e) {
|
| 586 |
+
document.getElementById('status-text').textContent = 'connecting...';
|
| 587 |
+
}
|
| 588 |
+
}
|
| 589 |
+
checkStatus(); setInterval(checkStatus, 30000);
|
| 590 |
+
|
| 591 |
+
// ββ File upload ββ
|
| 592 |
+
function onFileChange(inp) {
|
| 593 |
+
const f = inp.files[0]; if(!f) return;
|
| 594 |
+
const reader = new FileReader();
|
| 595 |
+
reader.onload = e => {
|
| 596 |
+
const img = document.getElementById('preview');
|
| 597 |
+
img.src = e.target.result; img.style.display = 'block';
|
| 598 |
+
document.querySelector('.upload-icon').style.display = 'none';
|
| 599 |
+
document.querySelectorAll('.upload-text').forEach(el => el.style.display = 'none');
|
| 600 |
+
};
|
| 601 |
+
reader.readAsDataURL(f);
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
// Drag & drop
|
| 605 |
+
const dz = document.getElementById('drop-zone');
|
| 606 |
+
dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('dragover'); });
|
| 607 |
+
dz.addEventListener('dragleave', () => dz.classList.remove('dragover'));
|
| 608 |
+
dz.addEventListener('drop', e => {
|
| 609 |
+
e.preventDefault(); dz.classList.remove('dragover');
|
| 610 |
+
const dt = e.dataTransfer; if(dt.files[0]) {
|
| 611 |
+
document.getElementById('file-input').files = dt.files;
|
| 612 |
+
onFileChange(document.getElementById('file-input'));
|
| 613 |
+
}
|
| 614 |
+
});
|
| 615 |
+
|
| 616 |
+
// ββ Key visibility toggle ββ
|
| 617 |
+
function toggleKeyVis() {
|
| 618 |
+
const inp = document.getElementById('api-key');
|
| 619 |
+
inp.type = inp.type === 'password' ? 'text' : 'password';
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
// ββ Extract ββ
|
| 623 |
+
async function doExtract() {
|
| 624 |
+
const key = document.getElementById('api-key').value.trim();
|
| 625 |
+
const fileInp = document.getElementById('file-input');
|
| 626 |
+
const fmt = document.getElementById('fmt-select').value;
|
| 627 |
+
if(!key) { toast('Please enter your API key', 'error'); return; }
|
| 628 |
+
if(!fileInp.files[0]) { toast('Please upload an image', 'error'); return; }
|
| 629 |
+
|
| 630 |
+
const btn = document.getElementById('extract-btn');
|
| 631 |
+
const inner = document.getElementById('btn-inner');
|
| 632 |
+
btn.disabled = true;
|
| 633 |
+
inner.innerHTML = '<span class="spinner"></span> Extracting...';
|
| 634 |
+
|
| 635 |
+
// Progress animation
|
| 636 |
+
const prog = document.getElementById('prog-wrap');
|
| 637 |
+
const bar = document.getElementById('prog-bar');
|
| 638 |
+
prog.style.display = 'block'; bar.style.width = '0';
|
| 639 |
+
let pv = 0;
|
| 640 |
+
const pint = setInterval(() => { pv = Math.min(pv+8, 85); bar.style.width = pv+'%'; }, 200);
|
| 641 |
+
|
| 642 |
+
const fd = new FormData();
|
| 643 |
+
fd.append('image', fileInp.files[0]);
|
| 644 |
+
|
| 645 |
+
try {
|
| 646 |
+
const r = await fetch(`/extract-logo?output_format=${fmt}`, {
|
| 647 |
+
method: 'POST',
|
| 648 |
+
headers: { 'X-API-Key': key },
|
| 649 |
+
body: fd
|
| 650 |
+
});
|
| 651 |
+
clearInterval(pint); bar.style.width = '100%';
|
| 652 |
+
setTimeout(() => { prog.style.display='none'; bar.style.width='0'; }, 600);
|
| 653 |
+
|
| 654 |
+
const data = await r.json();
|
| 655 |
+
if(!r.ok) { toast(data.detail || 'Error occurred', 'error'); return; }
|
| 656 |
+
|
| 657 |
+
extractedLogos = data.logos || [];
|
| 658 |
+
renderResults(data);
|
| 659 |
+
toast(`β Found ${data.count} logo${data.count!==1?'s':''}!`);
|
| 660 |
+
} catch(e) {
|
| 661 |
+
clearInterval(pint);
|
| 662 |
+
toast('Network error β check console', 'error');
|
| 663 |
+
console.error(e);
|
| 664 |
+
} finally {
|
| 665 |
+
btn.disabled = false;
|
| 666 |
+
inner.textContent = 'β Extract Logos';
|
| 667 |
+
}
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
+
function renderResults(data) {
|
| 671 |
+
const area = document.getElementById('result-area');
|
| 672 |
+
const title = document.getElementById('result-title');
|
| 673 |
+
const meta = document.getElementById('result-meta');
|
| 674 |
+
const dlBtn = document.getElementById('dl-all-btn');
|
| 675 |
+
|
| 676 |
+
if(!data.logos || data.logos.length === 0) {
|
| 677 |
+
area.innerHTML = '<div class="result-placeholder"><div class="icon">π</div><div>No logos detected<br><small style="color:var(--muted)">Try lowering confidence or a different image</small></div></div>';
|
| 678 |
+
title.textContent = 'Result β 0 logos'; dlBtn.style.display='none'; return;
|
| 679 |
+
}
|
| 680 |
+
|
| 681 |
+
title.textContent = `Result β ${data.count} logo${data.count!==1?'s':''}`;
|
| 682 |
+
dlBtn.style.display = '';
|
| 683 |
+
meta.textContent = `β‘ ${data.elapsed_ms}ms Β· Model: ONNX CPU`;
|
| 684 |
+
|
| 685 |
+
area.innerHTML = '';
|
| 686 |
+
const grid = document.createElement('div'); grid.className = 'logos-grid';
|
| 687 |
+
data.logos.forEach((logo, i) => {
|
| 688 |
+
const div = document.createElement('div'); div.className = 'logo-thumb';
|
| 689 |
+
div.innerHTML = `<img src="data:${logo.mime_type};base64,${logo.base64}" alt="logo ${i+1}">
|
| 690 |
+
<div class="conf">β‘ ${(logo.confidence*100).toFixed(1)}%</div>
|
| 691 |
+
<div class="dl" onclick="downloadLogo(${i})">β¬ Download</div>`;
|
| 692 |
+
grid.appendChild(div);
|
| 693 |
+
});
|
| 694 |
+
area.appendChild(grid);
|
| 695 |
+
}
|
| 696 |
+
|
| 697 |
+
function downloadLogo(i) {
|
| 698 |
+
const logo = extractedLogos[i]; if(!logo) return;
|
| 699 |
+
const a = document.createElement('a');
|
| 700 |
+
a.href = `data:${logo.mime_type};base64,${logo.base64}`;
|
| 701 |
+
a.download = `logo_${i+1}.png`; a.click();
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
function downloadAll() {
|
| 705 |
+
extractedLogos.forEach((_, i) => setTimeout(() => downloadLogo(i), i * 100));
|
| 706 |
+
}
|
| 707 |
+
|
| 708 |
+
// ββ Usage tab ββ
|
| 709 |
+
async function loadUsage() {
|
| 710 |
+
try {
|
| 711 |
+
const r = await fetch('/api/stats');
|
| 712 |
+
const d = await r.json();
|
| 713 |
+
document.getElementById('u-total').textContent = d.total_requests;
|
| 714 |
+
document.getElementById('u-logos').textContent = d.total_logos;
|
| 715 |
+
document.getElementById('u-errors').textContent = d.errors;
|
| 716 |
+
const up = Math.floor((Date.now()/1000) -
|
| 717 |
+
new Date(d.start_time).getTime()/1000);
|
| 718 |
+
const h = Math.floor(up/3600), m = Math.floor((up%3600)/60);
|
| 719 |
+
document.getElementById('u-uptime').textContent = `${h}h ${m}m`;
|
| 720 |
+
} catch(e) {}
|
| 721 |
+
}
|
| 722 |
+
|
| 723 |
+
async function checkKey() {
|
| 724 |
+
const key = document.getElementById('check-key').value.trim();
|
| 725 |
+
if(!key) return;
|
| 726 |
+
try {
|
| 727 |
+
const r = await fetch('/api/verify-key', {
|
| 728 |
+
method:'POST', headers:{'Content-Type':'application/json'},
|
| 729 |
+
body: JSON.stringify({key})
|
| 730 |
+
});
|
| 731 |
+
const d = await r.json();
|
| 732 |
+
document.getElementById('key-status').innerHTML = d.valid
|
| 733 |
+
? '<span style="color:var(--green)">β Valid API key β active</span>'
|
| 734 |
+
: '<span style="color:var(--red)">β Invalid or inactive key</span>';
|
| 735 |
+
} catch(e) {}
|
| 736 |
+
}
|
| 737 |
+
|
| 738 |
+
// ββ Admin ββ
|
| 739 |
+
async function adminLogin() {
|
| 740 |
+
const pass = document.getElementById('admin-pass').value;
|
| 741 |
+
try {
|
| 742 |
+
const r = await fetch('/admin/login', {
|
| 743 |
+
method:'POST', headers:{'Content-Type':'application/json'},
|
| 744 |
+
body: JSON.stringify({password: pass})
|
| 745 |
+
});
|
| 746 |
+
const d = await r.json();
|
| 747 |
+
if(d.token) {
|
| 748 |
+
adminToken = d.token;
|
| 749 |
+
document.getElementById('admin-login').style.display = 'none';
|
| 750 |
+
document.getElementById('admin-panel').style.display = 'block';
|
| 751 |
+
loadAdminData();
|
| 752 |
+
} else {
|
| 753 |
+
document.getElementById('admin-login-err').textContent = 'Wrong password';
|
| 754 |
+
}
|
| 755 |
+
} catch(e) {
|
| 756 |
+
document.getElementById('admin-login-err').textContent = 'Error connecting';
|
| 757 |
+
}
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
async function loadAdminData() {
|
| 761 |
+
try {
|
| 762 |
+
const r = await fetch('/admin/data', {
|
| 763 |
+
headers:{'X-Admin-Token': adminToken}
|
| 764 |
+
});
|
| 765 |
+
const d = await r.json();
|
| 766 |
+
document.getElementById('a-reqs').textContent = d.stats.total_requests;
|
| 767 |
+
document.getElementById('a-logos').textContent = d.stats.total_logos;
|
| 768 |
+
document.getElementById('a-errs').textContent = d.stats.errors;
|
| 769 |
+
document.getElementById('a-keys').textContent = d.keys.length;
|
| 770 |
+
|
| 771 |
+
const tbl = document.getElementById('keys-table');
|
| 772 |
+
tbl.innerHTML = '<tr><th>Key</th><th>Status</th><th>Action</th></tr>';
|
| 773 |
+
d.keys.forEach(k => {
|
| 774 |
+
const tr = document.createElement('tr');
|
| 775 |
+
tr.innerHTML = `<td>${k.substring(0,8)}...${k.slice(-4)}</td>
|
| 776 |
+
<td><span class="badge badge-active">Active</span></td>
|
| 777 |
+
<td><button class="btn btn-danger" onclick="copyKey('${k}')" style="padding:4px 10px;font-size:11px">Copy</button></td>`;
|
| 778 |
+
tbl.appendChild(tr);
|
| 779 |
+
});
|
| 780 |
+
|
| 781 |
+
const mi = document.getElementById('model-info');
|
| 782 |
+
mi.innerHTML = `Model Path: ${d.model_info.path}<br>
|
| 783 |
+
Model Loaded: ${d.model_info.loaded ? 'β Yes' : 'β No'}<br>
|
| 784 |
+
Input Shape: ${d.model_info.input_shape}<br>
|
| 785 |
+
Output Shape: ${d.model_info.output_shape}`;
|
| 786 |
+
} catch(e) { toast('Failed to load admin data', 'error'); }
|
| 787 |
+
}
|
| 788 |
+
|
| 789 |
+
function copyKey(k) {
|
| 790 |
+
navigator.clipboard.writeText(k).then(() => toast('Key copied!'));
|
| 791 |
+
}
|
| 792 |
+
|
| 793 |
+
function genKey() {
|
| 794 |
+
const k = 'logo-' + Math.random().toString(36).slice(2,8) +
|
| 795 |
+
'-' + Math.random().toString(36).slice(2,8);
|
| 796 |
+
navigator.clipboard.writeText(k).then(() =>
|
| 797 |
+
toast('Generated & copied: ' + k + ' β Add to API_KEYS_JSON secret'));
|
| 798 |
+
}
|
| 799 |
+
</script>
|
| 800 |
+
</body></html>"""
|
| 801 |
|
| 802 |
# βββ Routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 803 |
|
| 804 |
+
@app.get("/", response_class=HTMLResponse)
|
| 805 |
+
async def ui():
|
| 806 |
+
return HTML_UI
|
| 807 |
|
| 808 |
@app.get("/health")
|
| 809 |
async def health():
|
| 810 |
+
return {"status": "ok" if ort_session else "degraded",
|
| 811 |
+
"model_loaded": ort_session is not None, "version": "1.0.0"}
|
| 812 |
+
|
| 813 |
+
@app.get("/api/stats")
|
| 814 |
+
async def stats():
|
| 815 |
+
return _stats
|
| 816 |
+
|
| 817 |
+
@app.post("/api/verify-key")
|
| 818 |
+
async def verify_key(request: Request):
|
| 819 |
+
body = await request.json()
|
| 820 |
+
key = body.get("key", "")
|
| 821 |
+
return {"valid": key in VALID_API_KEYS, "key_prefix": key[:8] if key else ""}
|
| 822 |
+
|
| 823 |
+
# ββ Admin routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 824 |
+
_admin_tokens: set = set()
|
| 825 |
+
|
| 826 |
+
@app.post("/admin/login")
|
| 827 |
+
async def admin_login(request: Request):
|
| 828 |
+
body = await request.json()
|
| 829 |
+
if body.get("password") != ADMIN_PASSWORD:
|
| 830 |
+
raise HTTPException(401, "Wrong password")
|
| 831 |
+
token = secrets.token_hex(24)
|
| 832 |
+
_admin_tokens.add(token)
|
| 833 |
+
return {"token": token}
|
| 834 |
+
|
| 835 |
+
def _check_admin(token: str):
|
| 836 |
+
if token not in _admin_tokens:
|
| 837 |
+
raise HTTPException(401, "Invalid admin token")
|
| 838 |
+
|
| 839 |
+
@app.get("/admin/data")
|
| 840 |
+
async def admin_data(x_admin_token: str = Header(...)):
|
| 841 |
+
_check_admin(x_admin_token)
|
| 842 |
+
input_shape = output_shape = "N/A"
|
| 843 |
+
if ort_session:
|
| 844 |
+
input_shape = str(ort_session.get_inputs()[0].shape)
|
| 845 |
+
output_shape = str(ort_session.get_outputs()[0].shape)
|
| 846 |
return {
|
| 847 |
+
"stats": _stats,
|
| 848 |
+
"keys": list(VALID_API_KEYS),
|
| 849 |
+
"model_info": {
|
| 850 |
+
"path": MODEL_PATH,
|
| 851 |
+
"loaded": ort_session is not None,
|
| 852 |
+
"input_shape": input_shape,
|
| 853 |
+
"output_shape": output_shape,
|
| 854 |
+
}
|
| 855 |
}
|
| 856 |
|
| 857 |
+
# ββ Main extract endpoint ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 858 |
@app.post("/extract-logo")
|
| 859 |
async def extract_logo(
|
| 860 |
+
request: Request,
|
| 861 |
+
image: UploadFile = File(...),
|
| 862 |
+
output_format: str = "PNG",
|
| 863 |
max_logos: int = 20,
|
| 864 |
+
x_api_key: Optional[str] = Header(None, alias="X-API-Key"),
|
| 865 |
+
x_custom_secret: Optional[str] = Header(None, alias="X-Custom-Secret"),
|
| 866 |
):
|
| 867 |
"""
|
| 868 |
+
Accept EITHER X-API-Key (user-facing) OR X-Custom-Secret (backend server).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 869 |
"""
|
| 870 |
+
t0 = time.perf_counter()
|
| 871 |
|
| 872 |
+
# Auth β one of the two must be valid
|
| 873 |
+
if x_api_key:
|
| 874 |
+
verify_api_key(x_api_key)
|
| 875 |
+
elif x_custom_secret:
|
| 876 |
+
verify_backend_secret(x_custom_secret)
|
| 877 |
+
else:
|
| 878 |
+
raise HTTPException(401, "Provide X-API-Key or X-Custom-Secret header")
|
| 879 |
|
|
|
|
| 880 |
if ort_session is None:
|
| 881 |
+
_stats["errors"] += 1
|
| 882 |
+
raise HTTPException(503, "Model not loaded")
|
| 883 |
+
|
| 884 |
+
raw = await image.read()
|
| 885 |
+
if len(raw) > 15 * 1024 * 1024:
|
| 886 |
+
raise HTTPException(413, "Image too large β max 15MB")
|
| 887 |
+
|
| 888 |
+
nparr = np.frombuffer(raw, np.uint8)
|
| 889 |
+
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
| 890 |
+
if img is None:
|
| 891 |
+
raise HTTPException(400, "Cannot decode image")
|
| 892 |
+
|
| 893 |
+
oh, ow = img.shape[:2]
|
| 894 |
+
if max(ow, oh) > MAX_IMAGE_SIZE:
|
| 895 |
+
r = MAX_IMAGE_SIZE / max(ow, oh)
|
| 896 |
+
img = cv2.resize(img, None, fx=r, fy=r)
|
| 897 |
+
oh, ow = img.shape[:2]
|
| 898 |
+
|
| 899 |
+
tensor, scale, px, py = preprocess(img)
|
| 900 |
+
inp_name = ort_session.get_inputs()[0].name
|
| 901 |
+
raw_out = ort_session.run(None, {inp_name: tensor})
|
| 902 |
+
dets = postprocess(raw_out[0], ow, oh, scale, px, py)[:max_logos]
|
| 903 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 904 |
logos = []
|
| 905 |
+
fmt = output_format.upper()
|
| 906 |
+
for det in dets:
|
| 907 |
+
b64, cw, ch = crop_to_b64(img, det, fmt)
|
| 908 |
+
mime = "image/jpeg" if fmt == "JPEG" else "image/png"
|
| 909 |
+
logos.append({"base64": b64, "mime_type": mime,
|
| 910 |
+
"width": cw, "height": ch,
|
| 911 |
+
"confidence": det["confidence"],
|
| 912 |
+
"bbox": {k: det[k] for k in ("x1","y1","x2","y2")}})
|
| 913 |
+
|
| 914 |
+
del img, tensor, raw_out, nparr, raw; gc.collect()
|
| 915 |
+
elapsed = round((time.perf_counter() - t0) * 1000, 1)
|
| 916 |
+
|
| 917 |
+
_stats["total_requests"] += 1
|
| 918 |
+
_stats["total_logos"] += len(logos)
|
| 919 |
+
|
| 920 |
+
return JSONResponse({"success": True, "count": len(logos),
|
| 921 |
+
"elapsed_ms": elapsed, "logos": logos})
|
| 922 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 923 |
if __name__ == "__main__":
|
| 924 |
import uvicorn
|
| 925 |
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)
|