ShadowHunter222 commited on
Commit
9c5779b
·
verified ·
1 Parent(s): 150fd74

Delete main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -413
main.py DELETED
@@ -1,413 +0,0 @@
1
- """
2
- BRIA RMBG-2.0 ONNX Background Removal API
3
- ===========================================
4
- High-performance CPU-only background removal using the INT8 quantized
5
- ONNX variant of BRIA's RMBG-2.0 (BiRefNet architecture).
6
-
7
- Key optimisations:
8
- • INT8 quantized model (~365 MB) — faster CPU inference than FP32.
9
- • ONNX Runtime graph optimisations (ORT_ENABLE_ALL).
10
- • Configurable intra/inter-op thread parallelism.
11
- • Tiling + stitching for large images without OOM.
12
- • Direct NumPy / OpenCV pipeline — zero PyTorch dependency.
13
-
14
- Model source: https://huggingface.co/baby2008/RMBG-2.0-ONNX
15
- """
16
-
17
- from __future__ import annotations
18
-
19
- import io
20
- import os
21
- import time
22
- import math
23
- import logging
24
- from contextlib import asynccontextmanager
25
- from typing import Optional
26
-
27
- import cv2
28
- import numpy as np
29
- from PIL import Image
30
- from fastapi import FastAPI, Request, HTTPException, Query, Response
31
- from fastapi.responses import StreamingResponse
32
- from fastapi.middleware.cors import CORSMiddleware
33
- from fastapi.concurrency import run_in_threadpool
34
-
35
- # ---------------------------------------------------------------------------
36
- # Configuration
37
- # ---------------------------------------------------------------------------
38
- MODEL_REPO = os.getenv("RMBG_MODEL_REPO", "baby2008/RMBG-2.0-ONNX")
39
- MODEL_FILE = os.getenv("RMBG_MODEL_FILE", "onnx/model_int8.onnx")
40
- MODEL_INPUT_SIZE = int(os.getenv("RMBG_INPUT_SIZE", "1024"))
41
-
42
- # ONNX Runtime threading — tune for your CPU core count
43
- ORT_INTRA_THREADS = int(os.getenv("ORT_INTRA_THREADS", "0")) # 0 = auto
44
- ORT_INTER_THREADS = int(os.getenv("ORT_INTER_THREADS", "1"))
45
-
46
- # Tiling config
47
- TILE_THRESHOLD = int(os.getenv("TILE_THRESHOLD", "2048")) # px — images above this get tiled
48
- TILE_SIZE = int(os.getenv("TILE_SIZE", "1024")) # px — tile dimensions
49
- TILE_OVERLAP = int(os.getenv("TILE_OVERLAP", "128")) # px — overlap for seamless blending
50
-
51
- # ImageNet stats used by RMBG-2.0 preprocessing
52
- IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(1, 1, 3)
53
- IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(1, 1, 3)
54
-
55
- logger = logging.getLogger("bria-onnx")
56
- logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(name)s] %(levelname)s %(message)s")
57
-
58
- # ---------------------------------------------------------------------------
59
- # Shared state
60
- # ---------------------------------------------------------------------------
61
- engine: dict = {}
62
-
63
-
64
- # =========================================================================
65
- # Model loader
66
- # =========================================================================
67
- def _load_onnx_session():
68
- """Download (if needed) and create the ONNX Runtime InferenceSession."""
69
- import onnxruntime as ort
70
- from huggingface_hub import hf_hub_download
71
-
72
- logger.info("Downloading / locating ONNX model %s :: %s …", MODEL_REPO, MODEL_FILE)
73
- model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
74
- logger.info("Model path: %s", model_path)
75
-
76
- opts = ort.SessionOptions()
77
- opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
78
- opts.intra_op_num_threads = ORT_INTRA_THREADS
79
- opts.inter_op_num_threads = ORT_INTER_THREADS
80
- opts.enable_mem_pattern = True
81
- opts.enable_cpu_mem_arena = True
82
- # ORT optimized model caching — speeds up subsequent loads
83
- opts.optimized_model_filepath = model_path + ".optimized"
84
-
85
- providers = ["CPUExecutionProvider"]
86
- session = ort.InferenceSession(model_path, sess_options=opts, providers=providers)
87
-
88
- input_meta = session.get_inputs()[0]
89
- output_meta = session.get_outputs()
90
-
91
- logger.info("ONNX session ready | input: %s %s | outputs: %d",
92
- input_meta.name, input_meta.shape, len(output_meta))
93
- return session, input_meta.name, [o.name for o in output_meta]
94
-
95
-
96
- # =========================================================================
97
- # Preprocessing / postprocessing (pure NumPy + OpenCV)
98
- # =========================================================================
99
- def _preprocess(img_rgb: np.ndarray, target_size: int = MODEL_INPUT_SIZE) -> np.ndarray:
100
- """
101
- Resize, normalise, and reshape for ONNX Runtime.
102
- Returns float32 tensor of shape (1, 3, H, W).
103
- """
104
- # Bilinear resize
105
- resized = cv2.resize(img_rgb, (target_size, target_size), interpolation=cv2.INTER_LINEAR)
106
- # Normalise to [0,1] then ImageNet stats
107
- normed = (resized.astype(np.float32) / 255.0 - IMAGENET_MEAN) / IMAGENET_STD
108
- # HWC -> CHW, add batch dim
109
- return np.transpose(normed, (2, 0, 1))[np.newaxis].astype(np.float32)
110
-
111
-
112
- def _sigmoid(x: np.ndarray) -> np.ndarray:
113
- """Numerically stable sigmoid."""
114
- return np.where(
115
- x >= 0,
116
- 1.0 / (1.0 + np.exp(-x)),
117
- np.exp(x) / (1.0 + np.exp(x)),
118
- )
119
-
120
-
121
- def _postprocess(raw_output: np.ndarray, original_hw: tuple[int, int]) -> np.ndarray:
122
- """
123
- Take the raw logits from the last decoder stage, sigmoid, resize to
124
- original dims, and return a uint8 alpha mask (0-255).
125
- """
126
- # raw_output shape: (1, 1, H, W) or (1, H, W)
127
- mask = raw_output.squeeze() # (H, W)
128
- mask = _sigmoid(mask).astype(np.float32)
129
- # Resize back to original (H, W)
130
- mask = cv2.resize(mask, (original_hw[1], original_hw[0]), interpolation=cv2.INTER_LINEAR)
131
- return (mask * 255).clip(0, 255).astype(np.uint8)
132
-
133
-
134
- # =========================================================================
135
- # Single-shot inference
136
- # =========================================================================
137
- def _run_inference(img_rgb: np.ndarray) -> np.ndarray:
138
- """Run the ONNX model on a single image and return uint8 alpha mask."""
139
- session = engine["session"]
140
- inp_name = engine["input_name"]
141
- out_names = engine["output_names"]
142
-
143
- tensor = _preprocess(img_rgb)
144
- outputs = session.run(out_names, {inp_name: tensor})
145
- # RMBG-2.0 returns multiple decoder outputs — last one is the final mask
146
- raw_mask = outputs[-1]
147
- return _postprocess(raw_mask, (img_rgb.shape[0], img_rgb.shape[1]))
148
-
149
-
150
- # =========================================================================
151
- # Tiling engine — for large images
152
- # =========================================================================
153
- def _create_blend_mask(tile_h: int, tile_w: int, overlap: int) -> np.ndarray:
154
- """Create a soft feathering mask for seamless tile blending."""
155
- mask = np.ones((tile_h, tile_w), dtype=np.float32)
156
- if overlap <= 0:
157
- return mask
158
- # Feather all four edges
159
- for i in range(overlap):
160
- alpha = i / overlap
161
- mask[i, :] *= alpha # top
162
- mask[-(i+1), :] *= alpha # bottom
163
- mask[:, i] *= alpha # left
164
- mask[:, -(i+1)] *= alpha # right
165
- return mask
166
-
167
-
168
- def _run_tiled_inference(img_rgb: np.ndarray,
169
- tile_size: int = TILE_SIZE,
170
- overlap: int = TILE_OVERLAP) -> np.ndarray:
171
- """
172
- Split a large image into overlapping tiles, infer each tile, and
173
- blend the alpha masks back together with soft feathering.
174
- """
175
- H, W = img_rgb.shape[:2]
176
- stride = tile_size - overlap
177
-
178
- # Calculate grid
179
- ny = max(1, math.ceil((H - overlap) / stride))
180
- nx = max(1, math.ceil((W - overlap) / stride))
181
-
182
- accum = np.zeros((H, W), dtype=np.float32)
183
- weight = np.zeros((H, W), dtype=np.float32)
184
-
185
- logger.info("Tiling: %dx%d image → %d×%d grid (tile=%d, overlap=%d)",
186
- W, H, nx, ny, tile_size, overlap)
187
-
188
- for iy in range(ny):
189
- for ix in range(nx):
190
- y0 = min(iy * stride, H - tile_size) if H > tile_size else 0
191
- x0 = min(ix * stride, W - tile_size) if W > tile_size else 0
192
- y1 = min(y0 + tile_size, H)
193
- x1 = min(x0 + tile_size, W)
194
-
195
- tile = img_rgb[y0:y1, x0:x1]
196
- tile_mask = _run_inference(tile).astype(np.float32)
197
-
198
- blend = _create_blend_mask(y1 - y0, x1 - x0, overlap)
199
- accum[y0:y1, x0:x1] += tile_mask * blend
200
- weight[y0:y1, x0:x1] += blend
201
-
202
- # Normalise by accumulated weights
203
- weight = np.maximum(weight, 1e-6)
204
- final = (accum / weight).clip(0, 255).astype(np.uint8)
205
- return final
206
-
207
-
208
- # =========================================================================
209
- # Main processing pipeline
210
- # =========================================================================
211
- def _remove_background(
212
- img_bytes: bytes,
213
- output_format: str = "png",
214
- quality: int = 90,
215
- enable_tiling: Optional[bool] = None,
216
- ) -> tuple[bytes, str]:
217
- """
218
- Full pipeline: decode → infer (with optional tiling) → composite RGBA → encode.
219
- Returns (output_bytes, media_type).
220
- """
221
- # Decode
222
- arr = np.frombuffer(img_bytes, dtype=np.uint8)
223
- img_bgr = cv2.imdecode(arr, cv2.IMREAD_COLOR)
224
- if img_bgr is None:
225
- raise ValueError("Failed to decode image — unsupported or corrupt data.")
226
- img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
227
- H, W = img_rgb.shape[:2]
228
-
229
- t0 = time.perf_counter()
230
-
231
- # Decide whether to tile
232
- should_tile = enable_tiling if enable_tiling is not None else (max(H, W) > TILE_THRESHOLD)
233
-
234
- if should_tile and max(H, W) > TILE_SIZE:
235
- alpha = _run_tiled_inference(img_rgb)
236
- else:
237
- alpha = _run_inference(img_rgb)
238
-
239
- elapsed = time.perf_counter() - t0
240
- logger.info("Inference done in %.3fs | %dx%d | tiled=%s", elapsed, W, H, should_tile)
241
-
242
- # Composite RGBA
243
- rgba = np.dstack([img_rgb, alpha]) # (H, W, 4)
244
-
245
- # Encode output
246
- pil_img = Image.fromarray(rgba, "RGBA")
247
- buf = io.BytesIO()
248
-
249
- if output_format == "webp":
250
- pil_img.save(buf, format="WEBP", quality=quality)
251
- media_type = "image/webp"
252
- else:
253
- pil_img.save(buf, format="PNG", optimize=True)
254
- media_type = "image/png"
255
-
256
- return buf.getvalue(), media_type
257
-
258
-
259
- # =========================================================================
260
- # FastAPI application
261
- # =========================================================================
262
- @asynccontextmanager
263
- async def lifespan(app: FastAPI):
264
- """Load model on startup, release on shutdown."""
265
- logger.info("🔧 Starting BRIA RMBG-2.0 ONNX engine …")
266
- session, inp_name, out_names = _load_onnx_session()
267
- engine["session"] = session
268
- engine["input_name"] = inp_name
269
- engine["output_names"] = out_names
270
-
271
- # Warm-up run
272
- logger.info("🔥 Warm-up inference …")
273
- dummy = np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8)
274
- _run_inference(dummy)
275
- logger.info("✅ Engine ready.")
276
- yield
277
- engine.clear()
278
- logger.info("🛑 Engine shut down.")
279
-
280
-
281
- app = FastAPI(
282
- title="BRIA RMBG-2.0 ONNX — Background Removal API",
283
- description=(
284
- "High-performance CPU-only background removal powered by BRIA's RMBG-2.0 "
285
- "(BiRefNet) in INT8 ONNX. Supports tiling for large images and "
286
- "PNG / WebP output."
287
- ),
288
- version="1.0.0",
289
- lifespan=lifespan,
290
- )
291
-
292
- origins = [
293
- "http://127.0.0.1:5500",
294
- "http://localhost:5500",
295
- "http://localhost:3000",
296
- "http://localhost:8080",
297
- "*", # open for dev — tighten in production
298
- ]
299
-
300
- app.add_middleware(
301
- CORSMiddleware,
302
- allow_origins=origins,
303
- allow_credentials=True,
304
- allow_methods=["*"],
305
- allow_headers=["*"],
306
- )
307
-
308
-
309
- # ───────────────────────── Routes ─────────────────────────
310
-
311
- @app.post(
312
- "/api/remove-background",
313
- summary="Remove image background (INT8 ONNX)",
314
- responses={
315
- 200: {"content": {"image/png": {}, "image/webp": {}}},
316
- 400: {"description": "Invalid input."},
317
- 500: {"description": "Processing error."},
318
- },
319
- )
320
- async def remove_background(
321
- request: Request,
322
- format: str = Query("png", regex="^(png|webp)$", description="Output format"),
323
- quality: int = Query(90, ge=1, le=100, description="WebP quality (1-100)"),
324
- tiling: Optional[bool] = Query(None, description="Force tiling on/off (auto if omitted)"),
325
- ):
326
- """
327
- POST raw image bytes with ``Content-Type: image/*``.
328
-
329
- Query parameters:
330
- - **format** — ``png`` (default) or ``webp``
331
- - **quality** — WebP quality, 1-100 (default 90)
332
- - **tiling** — ``true`` forces tiling, ``false`` disables it, omit for auto-detect
333
- """
334
- content_type = request.headers.get("content-type", "")
335
- if not content_type.startswith("image/"):
336
- raise HTTPException(400, "Content-Type must be image/* (e.g. image/png, image/jpeg).")
337
-
338
- img_bytes = await request.body()
339
- if not img_bytes:
340
- raise HTTPException(400, "Empty request body — no image data received.")
341
-
342
- try:
343
- output_bytes, media_type = await run_in_threadpool(
344
- _remove_background, img_bytes, format, quality, tiling
345
- )
346
- except ValueError as exc:
347
- raise HTTPException(400, str(exc))
348
- except Exception as exc:
349
- logger.exception("Processing failed")
350
- raise HTTPException(500, f"Processing failed: {exc}")
351
-
352
- ext = "webp" if format == "webp" else "png"
353
- return StreamingResponse(
354
- io.BytesIO(output_bytes),
355
- media_type=media_type,
356
- headers={"Content-Disposition": f"attachment; filename=bg_removed.{ext}"},
357
- )
358
-
359
-
360
- @app.get("/health", summary="Health check + warm-up")
361
- async def health_check():
362
- """Returns model status and runs a micro warm-up to keep the session hot."""
363
- if not engine.get("session"):
364
- return Response(
365
- content='{"status":"unhealthy","model_loaded":false}',
366
- media_type="application/json",
367
- status_code=503,
368
- )
369
-
370
- def _warmup():
371
- dummy = np.random.randint(0, 255, (64, 64, 3), dtype=np.uint8)
372
- _run_inference(dummy)
373
- return True
374
-
375
- try:
376
- warmed = await run_in_threadpool(_warmup)
377
- except Exception:
378
- warmed = False
379
-
380
- return {"status": "healthy", "model_loaded": True, "model_warmed": warmed}
381
-
382
-
383
- @app.get("/ping")
384
- def ping():
385
- return Response(content="pong", media_type="text/plain")
386
-
387
-
388
- @app.get("/info", summary="Engine information")
389
- def info():
390
- """Return current engine configuration."""
391
- import onnxruntime as ort
392
- return {
393
- "model_repo": MODEL_REPO,
394
- "model_file": MODEL_FILE,
395
- "model_input_size": MODEL_INPUT_SIZE,
396
- "ort_version": ort.__version__,
397
- "ort_providers": engine["session"].get_providers() if engine.get("session") else [],
398
- "tiling": {
399
- "threshold_px": TILE_THRESHOLD,
400
- "tile_size_px": TILE_SIZE,
401
- "overlap_px": TILE_OVERLAP,
402
- },
403
- "threading": {
404
- "intra_op": ORT_INTRA_THREADS,
405
- "inter_op": ORT_INTER_THREADS,
406
- },
407
- }
408
-
409
-
410
- # ---------------------------------------------------------------------------
411
- if __name__ == "__main__":
412
- import uvicorn
413
- uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)