VINU NAYAK commited on
Commit
31a275e
·
verified ·
1 Parent(s): fe4b535

Upload main.py

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