Spaces:
Paused
Paused
File size: 1,661 Bytes
31a275e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
import io
from PIL import Image
from rembg import remove
app = FastAPI(title="Background Removal API")
# Add CORS middleware to allow requests from any origin
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {"message": "Background Removal API is running. Use POST /remove-bg to remove background from an image."}
@app.post("/remove-bg")
async def remove_background(file: UploadFile = File(...)):
# Check if the file is an image
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image")
try:
# Read the image
contents = await file.read()
input_image = Image.open(io.BytesIO(contents))
# Remove the background
output_image = remove(input_image)
# Convert to bytes
img_byte_arr = io.BytesIO()
output_image.save(img_byte_arr, format="PNG")
img_byte_arr.seek(0)
# Return the processed image
return StreamingResponse(
content=img_byte_arr,
media_type="image/png"
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860) |