Subham9126 commited on
Commit
31a3de4
·
verified ·
1 Parent(s): 1eee953

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -93
app.py CHANGED
@@ -1,105 +1,114 @@
1
  import os
 
2
  import gradio as gr
3
  from gradio_imageslider import ImageSlider
4
- from loadimg import load_img
5
- import spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from transformers import AutoModelForImageSegmentation
7
- import torch
8
  from torchvision import transforms
9
 
10
- torch.set_float32_matmul_precision(["high", "highest"][0])
11
-
12
- birefnet = AutoModelForImageSegmentation.from_pretrained(
13
- "briaai/RMBG-2.0", trust_remote_code=True
14
- )
15
- birefnet.to("cuda")
16
- transform_image = transforms.Compose(
17
- [
18
- transforms.Resize((1024, 1024)),
19
- transforms.ToTensor(),
20
- transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
21
- ]
22
  )
 
 
23
 
24
- output_folder = 'output_images'
25
- if not os.path.exists(output_folder):
26
- os.makedirs(output_folder)
 
 
 
27
 
28
- def fn(image):
29
- im = load_img(image, output_type="pil")
30
- im = im.convert("RGB")
31
- origin = im.copy()
32
- image = process(im)
33
- image_path = os.path.join(output_folder, "no_bg_image.png")
34
- image.save(image_path)
35
- return (image, origin), image_path
36
-
37
- @spaces.GPU
38
- def process(image):
39
- image_size = image.size
40
- input_images = transform_image(image).unsqueeze(0).to("cuda")
41
- # Prediction
 
 
 
 
 
42
  with torch.no_grad():
43
- preds = birefnet(input_images)[-1].sigmoid().cpu()
44
- pred = preds[0].squeeze()
45
- pred_pil = transforms.ToPILImage()(pred)
46
- mask = pred_pil.resize(image_size)
47
- image.putalpha(mask)
48
- return image
49
-
50
- def process_file(f):
51
- name_path = f.rsplit(".",1)[0]+".png"
52
- im = load_img(f, output_type="pil")
53
- im = im.convert("RGB")
54
- transparent = process(im)
55
- transparent.save(name_path)
56
- return name_path
57
-
58
- slider1 = ImageSlider(label="RMBG-2.0", type="pil")
59
- slider2 = ImageSlider(label="RMBG-2.0", type="pil")
60
- image = gr.Image(label="Upload an image")
61
- image2 = gr.Image(label="Upload an image",type="filepath")
62
- text = gr.Textbox(label="Paste an image URL")
63
- png_file = gr.File(label="output png file")
64
-
65
-
66
- chameleon = load_img("giraffe.jpg", output_type="pil")
67
-
68
- url = "http://farm9.staticflickr.com/8488/8228323072_76eeddfea3_z.jpg"
69
-
70
- tab1 = gr.Interface(
71
- fn, inputs=image, outputs=[slider1, gr.File(label="output png file")], examples=[chameleon], api_name="image"
72
- )
73
-
74
- tab2 = gr.Interface(fn, inputs=text, outputs=[slider2, gr.File(label="output png file")], examples=[url], api_name="text")
75
- tab3 = gr.Interface(process_file, inputs=image2, outputs=png_file, examples=["giraffe.jpg"], api_name="png")
76
-
77
-
78
- demo = gr.TabbedInterface(
79
- [tab1, tab2], ["input image", "input url"], title = (
80
- "RMBG-2.0 for background removal <br>"
81
- "<span style='font-size:16px; font-weight:300;'>"
82
- "Background removal model developed by "
83
- "<a href='https://bria.ai' target='_blank'>BRIA.AI</a>, trained on a carefully selected dataset,<br> "
84
- "and is available as an open-source model for non-commercial use.</span><br>"
85
- "<span style='font-size:16px; font-weight:500;'> For testing upload your image and wait.<br>"
86
- "<a href='https://huggingface.co/briaai/RMBG-2.0' target='_blank'>Model card</a> | "
87
- "<a href='https://blog.bria.ai/brias-new-state-of-the-art-remove-background-2.0-outperforms-the-competition' target='_blank'>Blog</a>"
88
- "</span><br>"
89
- "<span style='font-size:16px; font-weight:300;'>"
90
- "API Endpoint available on: "
91
- "<a href='https://docs.bria.ai/image-editing/v2-endpoints/background-remove' target='_blank'>Bria.ai</a>, "
92
- "<a href='https://fal.ai/models/fal-ai/bria/background/remove' target='_blank'>fal.ai</a><br>"
93
- "ComfyUI node is available here: "
94
- "<a href='https://github.com/Bria-AI/ComfyUI-BRIA-API' target='_blank'>ComfyUI Node</a><br>"
95
- "Purchase weigths for commercial use: "
96
- "<a href='https://share-eu1.hsforms.com/2sj9FVZTGSFmFRibDLhr_ZAf4e04' target='_blank'>here</a>"
97
- "</span>"
98
- )
99
-
100
-
101
-
102
- )
103
 
104
  if __name__ == "__main__":
105
- demo.launch(show_error=True)
 
1
  import os
2
+ import torch
3
  import gradio as gr
4
  from gradio_imageslider import ImageSlider
5
+ # Ensure loadimg.py is in your directory.
6
+ # If not, we use a fallback to PIL.
7
+ try:
8
+ from loadimg import load_img
9
+ except ImportError:
10
+ def load_img(path, output_type="pil"):
11
+ from PIL import Image
12
+ import requests
13
+ from io import BytesIO
14
+ if path.startswith('http'):
15
+ response = requests.get(path)
16
+ img = Image.open(BytesIO(response.content))
17
+ else:
18
+ img = Image.open(path)
19
+ return img
20
+
21
  from transformers import AutoModelForImageSegmentation
 
22
  from torchvision import transforms
23
 
24
+ # --- Hardware Setup ---
25
+ # Force CPU if CUDA is not available
26
+ device = "cuda" if torch.cuda.is_available() else "cpu"
27
+ print(f"Current Hardware: {device.upper()}")
28
+
29
+ # --- Model Initialization ---
30
+ # RMBG-2.0 is heavy; we use trust_remote_code=True for the BiRefNet architecture
31
+ print("Loading model... this may take a minute on CPU.")
32
+ model = AutoModelForImageSegmentation.from_pretrained(
33
+ "briaai/RMBG-2.0",
34
+ trust_remote_code=True
 
35
  )
36
+ model.to(device)
37
+ model.eval()
38
 
39
+ # Standard ImageNet normalization used by BiRefNet
40
+ preprocess = transforms.Compose([
41
+ transforms.Resize((1024, 1024)),
42
+ transforms.ToTensor(),
43
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
44
+ ])
45
 
46
+ output_folder = 'output_images'
47
+ os.makedirs(output_folder, exist_ok=True)
48
+
49
+ def remove_background(image_input):
50
+ if image_input is None:
51
+ return None, None
52
+
53
+ # Handle both filepath (str) and PIL Image inputs
54
+ if isinstance(image_input, str):
55
+ orig_img = load_img(image_input, output_type="pil").convert("RGB")
56
+ else:
57
+ orig_img = image_input.convert("RGB")
58
+
59
+ w, h = orig_img.size
60
+
61
+ # Preprocess
62
+ input_tensor = preprocess(orig_img).unsqueeze(0).to(device)
63
+
64
+ # Inference
65
  with torch.no_grad():
66
+ # BiRefNet returns a list of preds; we take the last one
67
+ result = model(input_tensor)[-1].sigmoid().cpu()
68
+
69
+ # Post-process Mask
70
+ mask = transforms.ToPILImage()(result[0].squeeze())
71
+ mask = mask.resize((w, h))
72
+
73
+ # Create Final Transparent Image
74
+ no_bg_img = orig_img.copy()
75
+ no_bg_img.putalpha(mask)
76
+
77
+ save_path = os.path.join(output_folder, "result.png")
78
+ no_bg_img.save(save_path)
79
+
80
+ return (no_bg_img, orig_img), save_path
81
+
82
+ # --- UI Setup ---
83
+ with gr.Blocks(title="RMBG 2.0 CPU") as demo:
84
+ gr.Markdown("# RMBG-2.0 Background Remover")
85
+ gr.Markdown("Optimized for CPU/GPU deployment.")
86
+
87
+ with gr.Tab("Image Upload"):
88
+ with gr.Row():
89
+ in_img = gr.Image(label="Upload Image", type="pil")
90
+ out_slider = ImageSlider(label="Comparison", type="pil")
91
+
92
+ out_file = gr.File(label="Download PNG")
93
+ submit_btn = gr.Button("Remove Background", variant="primary")
94
+
95
+ submit_btn.click(
96
+ fn=remove_background,
97
+ inputs=in_img,
98
+ outputs=[out_slider, out_file]
99
+ )
100
+
101
+ with gr.Tab("URL / Batch"):
102
+ url_input = gr.Textbox(label="Paste Image URL")
103
+ url_slider = ImageSlider(label="Comparison", type="pil")
104
+ url_file = gr.File(label="Download PNG")
105
+ url_btn = gr.Button("Process URL")
106
+
107
+ url_btn.click(
108
+ fn=remove_background,
109
+ inputs=url_input,
110
+ outputs=[url_slider, url_file]
111
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  if __name__ == "__main__":
114
+ demo.launch()