Update app.py
Browse files
app.py
CHANGED
|
@@ -1,48 +1,42 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from rembg import remove
|
| 3 |
from PIL import Image
|
| 4 |
-
import io
|
| 5 |
-
|
|
|
|
| 6 |
|
| 7 |
def remove_bg_auto_download(image):
|
| 8 |
-
# Remove background
|
| 9 |
output = remove(image)
|
| 10 |
-
|
| 11 |
-
# Save output to bytes
|
| 12 |
buf = io.BytesIO()
|
| 13 |
output.save(buf, format="PNG")
|
| 14 |
buf.seek(0)
|
| 15 |
-
|
| 16 |
-
# Encode as base64 for auto-download link
|
| 17 |
b64 = base64.b64encode(buf.read()).decode()
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
with gr.Blocks() as demo:
|
| 22 |
-
gr.Markdown("## Drag & Drop
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
link = remove_bg_auto_download(image)
|
| 32 |
-
filename = "no-bg.png"
|
| 33 |
-
# Auto-download using JS
|
| 34 |
-
html_code = f"""
|
| 35 |
-
<script>
|
| 36 |
-
var a = document.createElement('a');
|
| 37 |
-
a.href = '{link}';
|
| 38 |
-
a.download = '{filename}';
|
| 39 |
-
document.body.appendChild(a);
|
| 40 |
-
a.click();
|
| 41 |
-
a.remove();
|
| 42 |
-
</script>
|
| 43 |
-
"""
|
| 44 |
-
return html_code
|
| 45 |
-
|
| 46 |
-
image_input.change(fn=update_download, inputs=image_input, outputs=html_output)
|
| 47 |
|
| 48 |
-
demo.launch(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from rembg import remove
|
| 3 |
from PIL import Image
|
| 4 |
+
import io, base64, os
|
| 5 |
+
|
| 6 |
+
PORT = int(os.environ.get("PORT", 7860))
|
| 7 |
|
| 8 |
def remove_bg_auto_download(image):
|
|
|
|
| 9 |
output = remove(image)
|
| 10 |
+
|
|
|
|
| 11 |
buf = io.BytesIO()
|
| 12 |
output.save(buf, format="PNG")
|
| 13 |
buf.seek(0)
|
| 14 |
+
|
|
|
|
| 15 |
b64 = base64.b64encode(buf.read()).decode()
|
| 16 |
+
return f"""
|
| 17 |
+
<script>
|
| 18 |
+
const a = document.createElement('a');
|
| 19 |
+
a.href = "data:image/png;base64,{b64}";
|
| 20 |
+
a.download = "no-bg.png";
|
| 21 |
+
document.body.appendChild(a);
|
| 22 |
+
a.click();
|
| 23 |
+
a.remove();
|
| 24 |
+
</script>
|
| 25 |
+
"""
|
| 26 |
|
| 27 |
with gr.Blocks() as demo:
|
| 28 |
+
gr.Markdown("## Drag & Drop → Auto background removal & download")
|
| 29 |
+
image = gr.Image(type="pil", label="Drop image")
|
| 30 |
+
html = gr.HTML()
|
| 31 |
+
|
| 32 |
+
image.change(
|
| 33 |
+
fn=remove_bg_auto_download,
|
| 34 |
+
inputs=image,
|
| 35 |
+
outputs=html
|
| 36 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
demo.launch(
|
| 39 |
+
server_name="0.0.0.0",
|
| 40 |
+
server_port=PORT,
|
| 41 |
+
show_error=True
|
| 42 |
+
)
|