Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,43 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from PIL import Image
|
| 3 |
-
from rembg import remove
|
| 4 |
import io
|
| 5 |
|
| 6 |
-
#
|
|
|
|
|
|
|
| 7 |
def remove_background(input_image):
|
| 8 |
try:
|
| 9 |
# Convert Gradio input to PIL Image
|
| 10 |
-
if isinstance(input_image, dict): # Handle paste/drop
|
| 11 |
img = Image.open(io.BytesIO(input_image["bytes"]))
|
| 12 |
else:
|
| 13 |
img = Image.fromarray(input_image)
|
| 14 |
|
| 15 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
result = remove(
|
| 17 |
img,
|
| 18 |
-
session=
|
| 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 |
-
#
|
| 29 |
with gr.Blocks(title="Free BG Remover") as demo:
|
| 30 |
-
gr.Markdown("
|
|
|
|
| 31 |
with gr.Row():
|
| 32 |
-
gr.Image(
|
| 33 |
-
gr.Image(
|
|
|
|
| 34 |
gr.Button("Remove Background").click(
|
| 35 |
remove_background,
|
| 36 |
inputs=input_img,
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from PIL import Image
|
| 3 |
+
from rembg import remove, new_session
|
| 4 |
import io
|
| 5 |
|
| 6 |
+
# Initialize session once (saves memory)
|
| 7 |
+
session = new_session("u2net") # Smallest working model
|
| 8 |
+
|
| 9 |
def remove_background(input_image):
|
| 10 |
try:
|
| 11 |
# Convert Gradio input to PIL Image
|
| 12 |
+
if isinstance(input_image, dict): # Handle paste/drop
|
| 13 |
img = Image.open(io.BytesIO(input_image["bytes"]))
|
| 14 |
else:
|
| 15 |
img = Image.fromarray(input_image)
|
| 16 |
|
| 17 |
+
# Auto-resize to prevent OOM errors
|
| 18 |
+
if max(img.size) > 1024:
|
| 19 |
+
img = img.resize((1024, 1024))
|
| 20 |
+
|
| 21 |
+
# Process with memory-efficient settings
|
| 22 |
result = remove(
|
| 23 |
img,
|
| 24 |
+
session=session,
|
| 25 |
alpha_matting=False, # Disable memory-heavy feature
|
| 26 |
only_mask=False
|
| 27 |
)
|
|
|
|
| 28 |
return result
|
| 29 |
except Exception as e:
|
| 30 |
print(f"Error: {str(e)}")
|
| 31 |
return input_image # Return original if fails
|
| 32 |
|
| 33 |
+
# Updated Gradio interface (compatible with latest version)
|
| 34 |
with gr.Blocks(title="Free BG Remover") as demo:
|
| 35 |
+
gr.Markdown("## 🆓 Free Background Remover (Works on CPU)")
|
| 36 |
+
|
| 37 |
with gr.Row():
|
| 38 |
+
input_img = gr.Image(label="Upload", type="pil", height=400)
|
| 39 |
+
output_img = gr.Image(label="Result", type="pil", height=400)
|
| 40 |
+
|
| 41 |
gr.Button("Remove Background").click(
|
| 42 |
remove_background,
|
| 43 |
inputs=input_img,
|