rembg-as / app.py
JerryCoder's picture
Create app.py
3256c1e verified
# credit to kaido on tg
# Import libraries
import gradio as gr
from rembg import remove
from PIL import Image
import io, requests
# Background remover function with tempfile upload
def remove_background(image: Image.Image) -> str:
try:
# Convert input image to bytes
with io.BytesIO() as buffered:
image.save(buffered, format="PNG", optimize=True)
img_bytes = buffered.getvalue()
# Process image
output_bytes = remove(
img_bytes,
alpha_matting=True,
alpha_matting_foreground_threshold=240,
alpha_matting_background_threshold=10,
alpha_matting_erode_size=10
)
# Upload to tmpfiles.org
files = {"file": ("output.png", output_bytes, "image/png")}
r = requests.post("https://tmpfiles.org/api/v1/upload", files=files)
r.raise_for_status()
data = r.json()
# If upload succeeded, return the temporary URL
if "data" in data and "url" in data["data"]:
return data["data"]["url"]
raise gr.Error("Upload failed. Please try again.")
except Exception as e:
print(f"Error: {str(e)}")
raise gr.Error("Failed to process image.")
# Example Images
examples = [
["https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Cat_August_2010-4.jpg/480px-Cat_August_2010-4.jpg"],
["https://upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Cat_November_2010-1a.jpg/480px-Cat_November_2010-1a.jpg"],
["https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Internet1.jpg/640px-Internet1.jpg"]
]
# Custom CSS for professional look
custom_css = """
:root {
--primary: #4f46e5;
--secondary: #f9fafb;
}
body {
font-family: 'Inter', sans-serif;
}
.gradio-container {
max-width: 900px !important;
margin: auto !important;
}
.dark {
--primary: #6366f1;
--secondary: #1e293b;
}
footer {
display: none !important;
}
"""
# Social Media & Credits
socials = """
<div class="social-container">
<h3>About AI ClearCut</h3>
<p>Professional background removal tool powered by AI computer vision.</p>
<div class="credits">
<h4>Technical Details</h4>
<p>Powered by <a href="https://github.com/danielgatis/rembg" target="_blank">Rembg</a> • UI by Gradio</p>
<p>Model: u2net • Processing: CPU optimized</p>
</div>
<div class="developer">
<h4>Developer</h4>
<div class="links">
<a href="https://github.com/prokaiiddo" target="_blank">GitHub</a> •
<a href="https://linkedin.com/in/kaiiddo" target="_blank">LinkedIn</a> •
<a href="https://twitter.com/kaiiddo" target="_blank">Twitter</a>
</div>
</div>
</div>
"""
# Gradio Interface
with gr.Blocks(title="AI ClearCut - Professional Background Remover", css=custom_css) as interface:
gr.Markdown("""
# <center>AI ClearCut</center>
### <center>Professional Background Removal Tool</center>
""")
with gr.Row():
with gr.Column():
input_image = gr.Image(label="Upload Image", type="pil", elem_id="input-image")
with gr.Row():
submit_btn = gr.Button("Remove & Upload", variant="primary")
clear_btn = gr.Button("Clear", variant="secondary")
gr.Examples(
examples=examples,
inputs=[input_image],
label="Example Images",
examples_per_page=3
)
with gr.Column():
result_url = gr.Textbox(label="Temporary File URL", interactive=False)
with gr.Accordion("About & Credits", open=False):
gr.Markdown(socials)
# Process & upload
submit_btn.click(
fn=remove_background,
inputs=[input_image],
outputs=[result_url],
api_name="remove_bg"
)
# Clear button
clear_btn.click(
fn=lambda: [None, ""],
outputs=[input_image, result_url]
)
# Simplified launch for Hugging Face Spaces
interface.launch()