freebg commited on
Commit
5d2383e
Β·
verified Β·
1 Parent(s): 5c8e87a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -77
app.py CHANGED
@@ -1,20 +1,18 @@
1
  """
2
  FreeBG.site β€” Production Background Removal API
3
- HuggingFace Space | Gradio 6.x
4
 
5
- Architecture: Pure Gradio app with FastAPI routes added via custom_app
6
- No gr.mount_gradio_app (that causes double-execution crash)
7
  """
8
 
9
  import os, io, time, json, logging
10
  from datetime import datetime, timezone, timedelta
11
  from typing import Optional
12
 
13
- import gradio as gr
14
  import numpy as np
15
  from PIL import Image
16
 
17
- # ── Logging ───────────────────────────────────────────────────────────────────
18
  logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(name)s:%(message)s")
19
  logger = logging.getLogger("freebg")
20
 
@@ -28,7 +26,9 @@ if HF_TOKEN:
28
  login(token=HF_TOKEN, add_to_git_credential=False)
29
  logger.info("βœ… HF login OK")
30
  except Exception as e:
31
- logger.warning(f"HF login warning: {e}")
 
 
32
 
33
  # ── API Keys ──────────────────────────────────────────────────────────────────
34
  API_KEYS: dict = {}
@@ -65,7 +65,7 @@ def load_u2net():
65
  logger.info("βœ… U2-Net ready")
66
  return _cache["u2net"]
67
  except Exception as e:
68
- logger.error(f"U2-Net load failed: {e}")
69
  return None
70
 
71
  def load_birefnet():
@@ -85,7 +85,7 @@ def load_birefnet():
85
  logger.info("βœ… BiRefNet ready")
86
  return m
87
  except Exception as e:
88
- logger.error(f"BiRefNet load failed: {e}")
89
  return None
90
 
91
  def load_rmbg():
@@ -106,7 +106,7 @@ def load_rmbg():
106
  logger.info("βœ… RMBG-2.0 ready")
107
  return m
108
  except Exception as e:
109
- logger.error(f"RMBG-2.0 load failed: {e}")
110
  return None
111
 
112
  # ── Inference ─────────────────────────────────────────────────────────────────
@@ -134,29 +134,31 @@ def infer_fast(img):
134
  return Image.open(io.BytesIO(remove(buf.read(), session=_cache["u2net"]))).convert("RGBA")
135
 
136
  def infer_quality(img):
137
- if not load_birefnet(): raise RuntimeError("BiRefNet not available")
 
 
138
  return _seg("birefnet", img)
139
 
140
  def infer_best(img):
141
- if not load_rmbg():
142
- raise RuntimeError(
143
- "BRIA RMBG-2.0 not available. "
144
- "Set HF_TOKEN secret and accept license at huggingface.co/briaai/RMBG-2.0")
145
  return _seg("rmbg", img)
146
 
147
  MODEL_FN = {"fast": infer_fast, "quality": infer_quality, "best": infer_best}
148
  MODEL_INFO = {
149
  "fast": {"name":"U2-Net", "desc":"Fastest (~1s)"},
150
  "quality": {"name":"BiRefNet", "desc":"High quality (~4s)"},
151
- "best": {"name":"BRIA RMBG-2.0", "desc":"Best quality (~3s), needs HF_TOKEN"},
152
  }
153
 
154
  # ── Auth ──────────────────────────────────────────────────────────────────────
155
 
156
  def validate_key(api_key, model):
157
- if not api_key: return False, "API key required. Get one at freebg.site"
158
  if api_key not in API_KEYS: return False, "Invalid API key"
159
- kd = API_KEYS[api_key]
160
  plan = kd.get("plan","free")
161
  cfg = PLAN_LIMITS.get(plan, PLAN_LIMITS["free"])
162
  if utcnow().timestamp() > kd.get("reset_at",0):
@@ -174,10 +176,10 @@ def inc_usage(k):
174
 
175
  def get_usage(k):
176
  if k not in API_KEYS: return {"error":"Invalid key"}
177
- kd = API_KEYS[k]; plan = kd.get("plan","free")
178
- cfg = PLAN_LIMITS.get(plan, PLAN_LIMITS["free"])
179
- return {"plan":plan, "calls_today":kd.get("calls_today",0),
180
- "daily_limit":cfg["daily"], "available_models":cfg["models"],
181
  "owner":kd.get("owner","")}
182
 
183
  # ── Core ──────────────────────────────────────────────────────────────────────
@@ -200,9 +202,13 @@ def run_removal(api_key, img_data, model="fast", max_size=0):
200
  result = MODEL_FN[model](img)
201
  inc_usage(api_key)
202
  elapsed = round(time.time()-t0, 2)
203
- meta = {"model":MODEL_INFO[model]["name"], "model_key":model,
204
- "original_size":f"{ow}x{oh}", "output_size":f"{result.size[0]}x{result.size[1]}",
205
- "processing_time_sec":elapsed, "calls_today":API_KEYS[api_key]["calls_today"]}
 
 
 
 
206
  logger.info(f"βœ… {model} {ow}x{oh} {elapsed}s key=...{api_key[-6:]}")
207
  return result, meta, ""
208
  except Exception as e:
@@ -210,9 +216,14 @@ def run_removal(api_key, img_data, model="fast", max_size=0):
210
  return None, {}, str(e)
211
 
212
  # ── Gradio UI ─────────────────────────────────────────────────────────────────
 
213
 
214
  _CHOICES = ["πŸš€ Fast (U2-Net)","⚑ High Quality (BiRefNet)","πŸ† Best (BRIA RMBG-2.0)"]
215
- _CMAP = {"πŸš€ Fast (U2-Net)":"fast","⚑ High Quality (BiRefNet)":"quality","πŸ† Best (BRIA RMBG-2.0)":"best"}
 
 
 
 
216
 
217
  def ui_remove(api_key, image, choice):
218
  model = _CMAP.get(choice, "fast")
@@ -233,15 +244,20 @@ with gr.Blocks(title="FreeBG API") as demo:
233
  gr.HTML("""<div style="text-align:center;padding:16px 0 4px">
234
  <h1 style="font-size:24px;margin:0">🎨 FreeBG β€” Background Removal API</h1>
235
  <p style="color:#888;font-size:13px;margin:6px 0 0">
236
- 3 AI models Β· API key auth Β· <a href="https://freebg.site">freebg.site</a>
 
237
  </p></div>""")
238
 
239
  with gr.Tabs():
240
  with gr.TabItem("πŸ–ΌοΈ Remove Background"):
241
  with gr.Row():
242
  with gr.Column():
243
- i_key = gr.Textbox(label="πŸ”‘ API Key", placeholder="freebg-xxxx-xxxx", type="password")
244
- i_model = gr.Dropdown(label="Model", choices=_CHOICES, value=_CHOICES[0])
 
 
 
 
245
  i_img = gr.Image(label="Upload image", type="pil")
246
  i_btn = gr.Button("✨ Remove Background", variant="primary")
247
  with gr.Column():
@@ -261,32 +277,44 @@ with gr.Blocks(title="FreeBG API") as demo:
261
 
262
  **Base URL:** `https://freebg-background-remover.hf.space`
263
 
264
- ### POST `/api/remove-bg`
265
  ```
266
  Header: X-API-Key: your-key
267
  Body: image=<file> model=fast|quality|best max_size=0
268
- Return: image/png (transparent)
 
 
 
 
 
269
  ```
270
 
271
- ### GET `/api/usage` Β· `/api/models` Β· `/health`
 
 
272
 
273
  ### JavaScript
274
- ```js
275
  const fd = new FormData();
276
- fd.append('image', file);
277
  fd.append('model', 'fast');
278
- const r = await fetch('https://freebg-background-remover.hf.space/api/remove-bg',
279
- { method:'POST', headers:{'X-API-Key':'your-key'}, body:fd });
280
- const blob = await r.blob();
 
 
 
281
  ```
282
 
283
  ### Python
284
  ```python
285
  import requests
286
- r = requests.post('https://freebg-background-remover.hf.space/api/remove-bg',
 
287
  headers={'X-API-Key':'your-key'},
288
  files={'image': open('photo.jpg','rb')},
289
- data={'model':'fast'})
 
290
  open('out.png','wb').write(r.content)
291
  ```
292
 
@@ -300,58 +328,74 @@ open('out.png','wb').write(r.content)
300
  gr.HTML('<div style="text-align:center;padding:10px;font-size:11px;color:#555">'
301
  'U2-Net Β· BiRefNet Β· BRIA RMBG-2.0 Β· freebg.site</div>')
302
 
303
- # ── FastAPI routes injected into Gradio's internal app ───────────────────────
304
- # This is the CORRECT pattern for HuggingFace Spaces Gradio 6:
305
- # Use demo.app (the underlying FastAPI app that Gradio manages)
306
- # instead of creating our own FastAPI and mounting Gradio on it.
307
 
308
- from fastapi import File, UploadFile, Header, Form
309
  from fastapi.responses import Response, JSONResponse
310
  from fastapi.middleware.cors import CORSMiddleware
311
- from starlette.routing import Route
312
 
313
- # Add CORS to Gradio's internal app
314
  demo.app.add_middleware(
315
  CORSMiddleware,
316
  allow_origins=["*"],
317
- allow_methods=["POST","GET","OPTIONS"],
318
  allow_headers=["*"],
319
- expose_headers=["X-Model","X-Processing-Time","X-Original-Size","X-Output-Size","X-Calls-Today"],
 
 
 
320
  )
321
 
322
  @demo.app.post("/api/remove-bg")
323
- async def api_remove_bg(
324
- image: UploadFile = File(...),
325
- model: str = Form("fast"),
326
- max_size: int = Form(0),
327
- x_api_key: Optional[str] = Header(None),
328
- ):
329
  if not x_api_key:
330
  return JSONResponse({"success":False,"error":"X-API-Key header required"}, status_code=401)
331
- if model not in MODEL_FN:
332
- return JSONResponse({"success":False,"error":f"Invalid model. Choose: {list(MODEL_FN)}"}, status_code=400)
333
  try:
334
- pil = Image.open(io.BytesIO(await image.read())).convert("RGB")
335
- except Exception:
336
- return JSONResponse({"success":False,"error":"Cannot read image"}, status_code=400)
 
 
 
 
 
 
 
 
 
 
 
 
337
  result, meta, err = run_removal(x_api_key, pil, model, max_size)
338
  if err:
339
  code = 401 if any(w in err.lower() for w in ("key","limit","plan","upgrade")) else 500
340
  return JSONResponse({"success":False,"error":err}, status_code=code)
341
- buf = io.BytesIO(); result.save(buf,"PNG",optimize=True); buf.seek(0)
342
- return Response(buf.read(), media_type="image/png", headers={
343
- "X-Model": meta["model"],
344
- "X-Processing-Time": str(meta["processing_time_sec"]),
345
- "X-Original-Size": meta["original_size"],
346
- "X-Output-Size": meta["output_size"],
347
- "X-Calls-Today": str(meta["calls_today"]),
348
- })
 
 
 
 
 
 
 
349
 
350
  @demo.app.get("/api/usage")
351
- async def api_usage(x_api_key: Optional[str] = Header(None)):
352
- if not x_api_key:
 
353
  return JSONResponse({"error":"X-API-Key header required"}, status_code=401)
354
- info = get_usage(x_api_key)
355
  return JSONResponse({"success":"error" not in info, **info},
356
  status_code=200 if "error" not in info else 401)
357
 
@@ -361,13 +405,20 @@ async def api_models():
361
 
362
  @demo.app.get("/health")
363
  async def health():
364
- return {"status":"ok","hf_token_set":bool(HF_TOKEN),
365
- "models_loaded":[k for k in _cache if not k.endswith("_tf")],
366
- "timestamp":utcnow().isoformat()}
367
-
368
- # ── Launch ────────────────────────────────────────────────────────────────────
 
 
 
369
  if __name__ == "__main__":
370
- # Preload fast model
371
- logger.info("Preloading U2-Net...")
372
  load_u2net()
373
- demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)
 
 
 
 
 
 
1
  """
2
  FreeBG.site β€” Production Background Removal API
3
+ HuggingFace Space | Gradio 4.x (pinned, stable)
4
 
5
+ Architecture: Gradio launch() with FastAPI routes via app.add_api_route()
6
+ This avoids all mounting conflicts and double-execution issues.
7
  """
8
 
9
  import os, io, time, json, logging
10
  from datetime import datetime, timezone, timedelta
11
  from typing import Optional
12
 
 
13
  import numpy as np
14
  from PIL import Image
15
 
 
16
  logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(name)s:%(message)s")
17
  logger = logging.getLogger("freebg")
18
 
 
26
  login(token=HF_TOKEN, add_to_git_credential=False)
27
  logger.info("βœ… HF login OK")
28
  except Exception as e:
29
+ logger.warning(f"HF login: {e}")
30
+ else:
31
+ logger.warning("⚠️ HF_TOKEN not set β€” RMBG-2.0 will not load")
32
 
33
  # ── API Keys ──────────────────────────────────────────────────────────────────
34
  API_KEYS: dict = {}
 
65
  logger.info("βœ… U2-Net ready")
66
  return _cache["u2net"]
67
  except Exception as e:
68
+ logger.error(f"U2-Net failed: {e}")
69
  return None
70
 
71
  def load_birefnet():
 
85
  logger.info("βœ… BiRefNet ready")
86
  return m
87
  except Exception as e:
88
+ logger.error(f"BiRefNet failed: {e}")
89
  return None
90
 
91
  def load_rmbg():
 
106
  logger.info("βœ… RMBG-2.0 ready")
107
  return m
108
  except Exception as e:
109
+ logger.error(f"RMBG-2.0 failed: {e}")
110
  return None
111
 
112
  # ── Inference ─────────────────────────────────────────────────────────────────
 
134
  return Image.open(io.BytesIO(remove(buf.read(), session=_cache["u2net"]))).convert("RGBA")
135
 
136
  def infer_quality(img):
137
+ if not load_birefnet(): raise RuntimeError(
138
+ "BiRefNet not available β€” packages missing (einops, kornia, timm). "
139
+ "Check requirements.txt")
140
  return _seg("birefnet", img)
141
 
142
  def infer_best(img):
143
+ if not load_rmbg(): raise RuntimeError(
144
+ "BRIA RMBG-2.0 not available. "
145
+ "1) Move HF_TOKEN from Variables to Secrets. "
146
+ "2) Accept license at huggingface.co/briaai/RMBG-2.0")
147
  return _seg("rmbg", img)
148
 
149
  MODEL_FN = {"fast": infer_fast, "quality": infer_quality, "best": infer_best}
150
  MODEL_INFO = {
151
  "fast": {"name":"U2-Net", "desc":"Fastest (~1s)"},
152
  "quality": {"name":"BiRefNet", "desc":"High quality (~4s)"},
153
+ "best": {"name":"BRIA RMBG-2.0", "desc":"Best quality (~3s)"},
154
  }
155
 
156
  # ── Auth ──────────────────────────────────────────────────────────────────────
157
 
158
  def validate_key(api_key, model):
159
+ if not api_key: return False, "API key required"
160
  if api_key not in API_KEYS: return False, "Invalid API key"
161
+ kd = API_KEYS[api_key]
162
  plan = kd.get("plan","free")
163
  cfg = PLAN_LIMITS.get(plan, PLAN_LIMITS["free"])
164
  if utcnow().timestamp() > kd.get("reset_at",0):
 
176
 
177
  def get_usage(k):
178
  if k not in API_KEYS: return {"error":"Invalid key"}
179
+ kd = API_KEYS[k]; plan = kd.get("plan","free")
180
+ cfg = PLAN_LIMITS.get(plan, PLAN_LIMITS["free"])
181
+ return {"plan":plan,"calls_today":kd.get("calls_today",0),
182
+ "daily_limit":cfg["daily"],"available_models":cfg["models"],
183
  "owner":kd.get("owner","")}
184
 
185
  # ── Core ──────────────────────────────────────────────────────────────────────
 
202
  result = MODEL_FN[model](img)
203
  inc_usage(api_key)
204
  elapsed = round(time.time()-t0, 2)
205
+ meta = {
206
+ "model": MODEL_INFO[model]["name"], "model_key": model,
207
+ "original_size": f"{ow}x{oh}",
208
+ "output_size": f"{result.size[0]}x{result.size[1]}",
209
+ "processing_time_sec": elapsed,
210
+ "calls_today": API_KEYS[api_key]["calls_today"],
211
+ }
212
  logger.info(f"βœ… {model} {ow}x{oh} {elapsed}s key=...{api_key[-6:]}")
213
  return result, meta, ""
214
  except Exception as e:
 
216
  return None, {}, str(e)
217
 
218
  # ── Gradio UI ─────────────────────────────────────────────────────────────────
219
+ import gradio as gr
220
 
221
  _CHOICES = ["πŸš€ Fast (U2-Net)","⚑ High Quality (BiRefNet)","πŸ† Best (BRIA RMBG-2.0)"]
222
+ _CMAP = {
223
+ "πŸš€ Fast (U2-Net)": "fast",
224
+ "⚑ High Quality (BiRefNet)":"quality",
225
+ "πŸ† Best (BRIA RMBG-2.0)": "best",
226
+ }
227
 
228
  def ui_remove(api_key, image, choice):
229
  model = _CMAP.get(choice, "fast")
 
244
  gr.HTML("""<div style="text-align:center;padding:16px 0 4px">
245
  <h1 style="font-size:24px;margin:0">🎨 FreeBG β€” Background Removal API</h1>
246
  <p style="color:#888;font-size:13px;margin:6px 0 0">
247
+ 3 AI models Β· API key auth Β·
248
+ <a href="https://freebg.site" target="_blank">freebg.site</a>
249
  </p></div>""")
250
 
251
  with gr.Tabs():
252
  with gr.TabItem("πŸ–ΌοΈ Remove Background"):
253
  with gr.Row():
254
  with gr.Column():
255
+ i_key = gr.Textbox(label="πŸ”‘ API Key",
256
+ placeholder="freebg-xxxx-xxxx",
257
+ type="password")
258
+ i_model = gr.Dropdown(label="Model",
259
+ choices=_CHOICES,
260
+ value=_CHOICES[0])
261
  i_img = gr.Image(label="Upload image", type="pil")
262
  i_btn = gr.Button("✨ Remove Background", variant="primary")
263
  with gr.Column():
 
277
 
278
  **Base URL:** `https://freebg-background-remover.hf.space`
279
 
280
+ ### `POST /api/remove-bg`
281
  ```
282
  Header: X-API-Key: your-key
283
  Body: image=<file> model=fast|quality|best max_size=0
284
+ Return: image/png (transparent background)
285
+ ```
286
+
287
+ ### `GET /api/usage`
288
+ ```
289
+ Header: X-API-Key: your-key
290
  ```
291
 
292
+ ### `GET /api/models` Β· `GET /health`
293
+
294
+ ---
295
 
296
  ### JavaScript
297
+ ```javascript
298
  const fd = new FormData();
299
+ fd.append('image', imageFile);
300
  fd.append('model', 'fast');
301
+
302
+ const res = await fetch(
303
+ 'https://freebg-background-remover.hf.space/api/remove-bg',
304
+ { method:'POST', headers:{'X-API-Key':'your-key'}, body:fd }
305
+ );
306
+ const blob = await res.blob(); // transparent PNG
307
  ```
308
 
309
  ### Python
310
  ```python
311
  import requests
312
+ r = requests.post(
313
+ 'https://freebg-background-remover.hf.space/api/remove-bg',
314
  headers={'X-API-Key':'your-key'},
315
  files={'image': open('photo.jpg','rb')},
316
+ data={'model':'fast'}
317
+ )
318
  open('out.png','wb').write(r.content)
319
  ```
320
 
 
328
  gr.HTML('<div style="text-align:center;padding:10px;font-size:11px;color:#555">'
329
  'U2-Net Β· BiRefNet Β· BRIA RMBG-2.0 Β· freebg.site</div>')
330
 
331
+ # ── FastAPI routes via Gradio's internal app ──────────────────────────────────
332
+ # Gradio 4.x exposes demo.app as the underlying FastAPI instance.
333
+ # We add our custom routes directly here BEFORE launch().
 
334
 
335
+ from fastapi import Request
336
  from fastapi.responses import Response, JSONResponse
337
  from fastapi.middleware.cors import CORSMiddleware
 
338
 
 
339
  demo.app.add_middleware(
340
  CORSMiddleware,
341
  allow_origins=["*"],
342
+ allow_methods=["GET","POST","OPTIONS"],
343
  allow_headers=["*"],
344
+ expose_headers=[
345
+ "X-Model","X-Processing-Time",
346
+ "X-Original-Size","X-Output-Size","X-Calls-Today"
347
+ ],
348
  )
349
 
350
  @demo.app.post("/api/remove-bg")
351
+ async def api_remove_bg(request: Request):
352
+ # Parse multipart manually (works with any Gradio version)
353
+ x_api_key = request.headers.get("x-api-key") or request.headers.get("X-API-Key")
 
 
 
354
  if not x_api_key:
355
  return JSONResponse({"success":False,"error":"X-API-Key header required"}, status_code=401)
356
+
 
357
  try:
358
+ form = await request.form()
359
+ model = str(form.get("model", "fast"))
360
+ max_size = int(form.get("max_size", 0))
361
+ img_file = form.get("image")
362
+ if img_file is None:
363
+ return JSONResponse({"success":False,"error":"'image' field required"}, status_code=400)
364
+ img_bytes = await img_file.read()
365
+ pil = Image.open(io.BytesIO(img_bytes)).convert("RGB")
366
+ except Exception as e:
367
+ return JSONResponse({"success":False,"error":f"Bad request: {e}"}, status_code=400)
368
+
369
+ if model not in MODEL_FN:
370
+ return JSONResponse({"success":False,
371
+ "error":f"Invalid model '{model}'. Choose: {list(MODEL_FN)}"}, status_code=400)
372
+
373
  result, meta, err = run_removal(x_api_key, pil, model, max_size)
374
  if err:
375
  code = 401 if any(w in err.lower() for w in ("key","limit","plan","upgrade")) else 500
376
  return JSONResponse({"success":False,"error":err}, status_code=code)
377
+
378
+ buf = io.BytesIO()
379
+ result.save(buf, "PNG", optimize=True)
380
+ buf.seek(0)
381
+ return Response(
382
+ content=buf.read(),
383
+ media_type="image/png",
384
+ headers={
385
+ "X-Model": meta["model"],
386
+ "X-Processing-Time": str(meta["processing_time_sec"]),
387
+ "X-Original-Size": meta["original_size"],
388
+ "X-Output-Size": meta["output_size"],
389
+ "X-Calls-Today": str(meta["calls_today"]),
390
+ }
391
+ )
392
 
393
  @demo.app.get("/api/usage")
394
+ async def api_usage(request: Request):
395
+ key = request.headers.get("x-api-key") or request.headers.get("X-API-Key")
396
+ if not key:
397
  return JSONResponse({"error":"X-API-Key header required"}, status_code=401)
398
+ info = get_usage(key)
399
  return JSONResponse({"success":"error" not in info, **info},
400
  status_code=200 if "error" not in info else 401)
401
 
 
405
 
406
  @demo.app.get("/health")
407
  async def health():
408
+ return {
409
+ "status": "ok",
410
+ "hf_token": "set" if HF_TOKEN else "missing",
411
+ "models_ready": [k for k in _cache if not k.endswith("_tf")],
412
+ "timestamp": utcnow().isoformat(),
413
+ }
414
+
415
+ # ── Entry point ───────────────────────────────────────────────────────────────
416
  if __name__ == "__main__":
417
+ logger.info("Preloading U2-Net (fast model)...")
 
418
  load_u2net()
419
+ demo.launch(
420
+ server_name="0.0.0.0",
421
+ server_port=7860,
422
+ show_error=True,
423
+ ssr_mode=False, # disable SSR to avoid port conflicts
424
+ )