Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from rembg import remove
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 5 |
+
from fastapi.responses import StreamingResponse
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# Background removal function
|
| 11 |
+
def remove_background(image_bytes):
|
| 12 |
+
try:
|
| 13 |
+
output_bytes = remove(image_bytes)
|
| 14 |
+
return output_bytes
|
| 15 |
+
except Exception as e:
|
| 16 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 17 |
+
|
| 18 |
+
# Gradio interface
|
| 19 |
+
def gradio_interface(input_image):
|
| 20 |
+
if input_image is None:
|
| 21 |
+
return None
|
| 22 |
+
output_bytes = remove_background(input_image)
|
| 23 |
+
return output_bytes
|
| 24 |
+
|
| 25 |
+
# API endpoint
|
| 26 |
+
@app.post("/api/remove-bg")
|
| 27 |
+
async def api_remove_bg(file: UploadFile = File(...)):
|
| 28 |
+
if not file.content_type.startswith('image/'):
|
| 29 |
+
raise HTTPException(status_code=400, detail="File must be an image")
|
| 30 |
+
|
| 31 |
+
input_image = await file.read()
|
| 32 |
+
output_bytes = remove_background(input_image)
|
| 33 |
+
|
| 34 |
+
return StreamingResponse(BytesIO(output_bytes), media_type="image/png")
|
| 35 |
+
|
| 36 |
+
# Gradio app
|
| 37 |
+
gr_app = gr.Interface(
|
| 38 |
+
fn=gradio_interface,
|
| 39 |
+
inputs=gr.Image(type="filepath", label="Input Image"),
|
| 40 |
+
outputs=gr.Image(type="numpy", label="Output Image"),
|
| 41 |
+
title="Background Remover",
|
| 42 |
+
description="Upload an image to remove the background"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# Mount Gradio app
|
| 46 |
+
app = gr.mount_gradio_app(app, gr_app, path="/")
|