Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,25 +2,45 @@ import gradio as gr
|
|
| 2 |
from rembg import remove, new_session
|
| 3 |
from PIL import Image
|
| 4 |
|
|
|
|
|
|
|
| 5 |
session = new_session("isnet-general-use")
|
| 6 |
|
|
|
|
| 7 |
def process_image(input_img):
|
| 8 |
if input_img is None:
|
| 9 |
return None
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
with gr.Blocks() as demo:
|
| 14 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
with gr.Row():
|
| 16 |
-
img_input = gr.Image(type="pil")
|
| 17 |
-
img_output = gr.Image(type="pil")
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
btn.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
ssr_mode=False
|
| 26 |
-
)
|
|
|
|
| 2 |
from rembg import remove, new_session
|
| 3 |
from PIL import Image
|
| 4 |
|
| 5 |
+
# 1. Load the AI Model into memory ONCE at startup
|
| 6 |
+
# 'isnet-general-use' is highly accurate for products, people, and objects
|
| 7 |
session = new_session("isnet-general-use")
|
| 8 |
|
| 9 |
+
# 2. Define the core function
|
| 10 |
def process_image(input_img):
|
| 11 |
if input_img is None:
|
| 12 |
return None
|
| 13 |
+
try:
|
| 14 |
+
# Remove background using the pre-loaded session
|
| 15 |
+
output = remove(input_img, session=session)
|
| 16 |
+
return output
|
| 17 |
+
except Exception as e:
|
| 18 |
+
print(f"Error processing image: {e}")
|
| 19 |
+
return None
|
| 20 |
|
| 21 |
+
# 3. Build the User Interface
|
| 22 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 23 |
+
gr.Markdown(
|
| 24 |
+
"""
|
| 25 |
+
# ✨ AI Background Remover
|
| 26 |
+
Optimized for high-speed API access via CPU.
|
| 27 |
+
"""
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
with gr.Row():
|
| 31 |
+
img_input = gr.Image(type="pil", label="Upload Image")
|
| 32 |
+
img_output = gr.Image(type="pil", label="Transparent Result")
|
| 33 |
+
|
| 34 |
+
btn = gr.Button("Remove Background", variant="primary")
|
| 35 |
|
| 36 |
+
# 4. Connect the button and declare the API name for the blog
|
| 37 |
+
btn.click(
|
| 38 |
+
fn=process_image,
|
| 39 |
+
inputs=img_input,
|
| 40 |
+
outputs=img_output,
|
| 41 |
+
api_name="remove_bg"
|
| 42 |
+
)
|
| 43 |
|
| 44 |
+
# 5. Launch the app with strict queuing to protect the CPU
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
demo.queue(default_concurrency_limit=1).launch(ssr_mode=False)
|
|
|
|
|
|