Janeka commited on
Commit
7ab6643
·
verified ·
1 Parent(s): aa4568b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -94
app.py CHANGED
@@ -1,99 +1,40 @@
1
  import gradio as gr
2
- import numpy as np
3
  from PIL import Image
4
- import torch
5
- import warnings
6
 
7
- # Suppress warnings for cleaner output
8
- warnings.filterwarnings("ignore")
9
-
10
- # Initialize models dictionary to cache loaded models
11
- models = {}
12
-
13
- def load_bria_model():
14
- from transformers import AutoModelForImageSegmentation, AutoImageProcessor
15
- model = AutoModelForImageSegmentation.from_pretrained("briaai/RMBG-1.4", trust_remote_code=True)
16
- processor = AutoImageProcessor.from_pretrained("briaai/RMBG-1.4")
17
- return model, processor
18
-
19
- def load_rembg_model(model_name):
20
- from rembg import new_session
21
- return new_session(model_name)
22
-
23
- def load_isnet_model(model_url):
24
- # Placeholder - you would implement proper ISNet loading here
25
- return None
26
-
27
- def apply_bria(image, model, processor):
28
- inputs = processor(images=image, return_tensors="pt")
29
- with torch.no_grad():
30
- outputs = model(**inputs)
31
- mask = outputs.logits.squeeze().cpu().numpy()
32
- mask = (mask - mask.min()) / (mask.max() - mask.min())
33
- mask = (mask * 255).astype(np.uint8)
34
- return Image.fromarray(mask)
35
-
36
- def apply_rembg(image, session):
37
- from rembg import remove
38
- return remove(image, session=session)
39
-
40
- def apply_isnet(image, model):
41
- # Placeholder for ISNet implementation
42
- return image
43
-
44
- def remove_background(image):
45
  try:
46
- # Convert input to PIL Image
47
- if isinstance(image, np.ndarray):
48
- image = Image.fromarray(image)
49
-
50
- # Initialize models if not already loaded
51
- if "bria" not in models:
52
- bria_model, bria_processor = load_bria_model()
53
- models["bria"] = (bria_model, bria_processor)
54
-
55
- if "u2net" not in models:
56
- models["u2net"] = load_rembg_model("u2net")
57
-
58
- if "isnet" not in models:
59
- models["isnet"] = load_isnet_model("https://example.com/isnet.pth")
60
-
61
- # Apply models in sequence
62
- results = []
63
-
64
- # BRIA
65
- bria_model, bria_processor = models["bria"]
66
- bria_result = apply_bria(image, bria_model, bria_processor)
67
- results.append(bria_result)
68
-
69
- # U2Net
70
- u2net_result = apply_rembg(image, models["u2net"])
71
- results.append(u2net_result)
72
-
73
- # Combine results (simple average for demonstration)
74
- combined = np.zeros_like(np.array(results[0]), dtype=np.float32)
75
- for res in results:
76
- combined += np.array(res).astype(np.float32) / len(results)
77
- combined = np.clip(combined, 0, 255).astype(np.uint8)
78
-
79
- # Apply mask to original image
80
- final = image.copy()
81
- final.putalpha(Image.fromarray(combined))
82
-
83
- return final
84
-
85
  except Exception as e:
86
- print(f"Error: {e}")
87
- return image # Return original image on error
88
-
89
- # Create Gradio interface
90
- interface = gr.Interface(
91
- fn=remove_background,
92
- inputs=gr.Image(label="Input Image"),
93
- outputs=gr.Image(label="Result with Transparent Background"),
94
- title="Advanced Background Removal",
95
- description="Combines multiple state-of-the-art models for high-quality background removal"
96
- )
97
-
98
- if __name__ == "__main__":
99
- interface.launch(share=True) # Set share=True for public link
 
 
 
1
  import gradio as gr
 
2
  from PIL import Image
3
+ from rembg import remove
4
+ import io
5
 
6
+ # Lightweight background removal (works on CPU)
7
+ def remove_background(input_image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  try:
9
+ # Convert Gradio input to PIL Image
10
+ if isinstance(input_image, dict): # Handle paste/drop events
11
+ img = Image.open(io.BytesIO(input_image["bytes"]))
12
+ else:
13
+ img = Image.fromarray(input_image)
14
+
15
+ # Process with optimized settings
16
+ result = remove(
17
+ img,
18
+ session=new_session("u2net"), # Smallest working model
19
+ alpha_matting=False, # Disable memory-heavy feature
20
+ only_mask=False
21
+ )
22
+
23
+ return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  except Exception as e:
25
+ print(f"Error: {str(e)}")
26
+ return input_image # Return original if fails
27
+
28
+ # Simple interface
29
+ with gr.Blocks(title="Free BG Remover") as demo:
30
+ gr.Markdown("""### 🆓 Free Background Remover (Works on CPU)""")
31
+ with gr.Row():
32
+ gr.Image(type="pil", label="Upload").style(height=400) >> input_img
33
+ gr.Image(type="pil", label="Result").style(height=400) << output_img
34
+ gr.Button("Remove Background").click(
35
+ remove_background,
36
+ inputs=input_img,
37
+ outputs=output_img
38
+ )
39
+
40
+ demo.launch(show_error=True)