Muhammad8815 commited on
Commit
fc406a2
·
verified ·
1 Parent(s): 8ac35d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -67
app.py CHANGED
@@ -1,67 +1,55 @@
1
- import gradio as gr
2
- from briarmbg import BriaRMBG
3
- from PIL import Image
4
- import torch
5
- import torchvision.transforms as T
6
- import os
7
- import json
8
- from fastapi import Request, HTTPException
9
-
10
- # ===== Load API key from Hugging Face secret or fallback =====
11
- API_KEY = os.getenv("API_KEY", "sk_muhammad8815_Z4gXr93nPqT2LwV8")
12
-
13
- # ===== Load model =====
14
- model = BriaRMBG.from_pretrained("./")
15
- model.load_state_dict(torch.load("model.pth", map_location="cpu"))
16
- model.eval()
17
-
18
- # ===== Define preprocessing =====
19
- transform = T.Compose([
20
- T.Resize((512, 512)),
21
- T.ToTensor()
22
- ])
23
-
24
- # ===== Background removal function with API key check =====
25
- def remove_background(image, request: Request = None):
26
- # Check for API key in Authorization header
27
- if request is not None:
28
- auth = request.headers.get("authorization")
29
- if not auth or not auth.startswith("Bearer ") or auth.split(" ")[1] != API_KEY:
30
- raise HTTPException(status_code=401, detail="Invalid or missing API key")
31
-
32
- # Preprocess image
33
- img = transform(image).unsqueeze(0)
34
-
35
- with torch.no_grad():
36
- result = model(img)
37
-
38
- # Handle different result formats
39
- if isinstance(result, dict) and "pred" in result:
40
- result = result["pred"]
41
- elif isinstance(result, (tuple, list)):
42
- result = result[0]
43
- if isinstance(result, list):
44
- result = result[0]
45
-
46
- result = result.squeeze().numpy()
47
-
48
- # Apply transparency mask
49
- image = image.resize((result.shape[1], result.shape[0]))
50
- image = image.convert("RGBA")
51
- pixels = image.load()
52
-
53
- for y in range(image.height):
54
- for x in range(image.width):
55
- if result[y][x] < 0.5:
56
- pixels[x, y] = (255, 255, 255, 0)
57
-
58
- return image
59
-
60
- # ===== Launch Gradio app with secure FastAPI request passthrough =====
61
- gr.Interface(
62
- fn=remove_background,
63
- inputs=gr.Image(type="pil"),
64
- outputs=gr.Image(type="pil"),
65
- title="Background Remover",
66
- allow_flagging="never"
67
- ).launch()
 
1
+ import gradio as gr
2
+ from briarmbg import BriaRMBG
3
+ from PIL import Image
4
+ import torch
5
+ import torchvision.transforms as T
6
+
7
+ # ===== Load model =====
8
+ model = BriaRMBG.from_pretrained("./")
9
+ model.load_state_dict(torch.load("model.pth", map_location="cpu"))
10
+ model.eval()
11
+
12
+ # ===== Define preprocessing =====
13
+ transform = T.Compose([
14
+ T.Resize((512, 512)),
15
+ T.ToTensor()
16
+ ])
17
+
18
+ # ===== Background removal function (no auth needed) =====
19
+ def remove_background(image):
20
+ # Preprocess image
21
+ img = transform(image).unsqueeze(0)
22
+
23
+ with torch.no_grad():
24
+ result = model(img)
25
+
26
+ # Handle different result formats
27
+ if isinstance(result, dict) and "pred" in result:
28
+ result = result["pred"]
29
+ elif isinstance(result, (tuple, list)):
30
+ result = result[0]
31
+ if isinstance(result, list):
32
+ result = result[0]
33
+
34
+ result = result.squeeze().numpy()
35
+
36
+ # Apply transparency mask
37
+ image = image.resize((result.shape[1], result.shape[0]))
38
+ image = image.convert("RGBA")
39
+ pixels = image.load()
40
+
41
+ for y in range(image.height):
42
+ for x in range(image.width):
43
+ if result[y][x] < 0.5:
44
+ pixels[x, y] = (255, 255, 255, 0)
45
+
46
+ return image
47
+
48
+ # ===== Launch Gradio app (public access) =====
49
+ gr.Interface(
50
+ fn=remove_background,
51
+ inputs=gr.Image(type="pil"),
52
+ outputs=gr.Image(type="pil"),
53
+ title="Background Remover",
54
+ allow_flagging="never"
55
+ ).launch()