Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
-
from
|
| 4 |
-
import os
|
| 5 |
-
import base64
|
| 6 |
import io
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
@@ -12,34 +13,29 @@ app.add_middleware(
|
|
| 12 |
CORSMiddleware,
|
| 13 |
allow_origins=["https://*.figma.com"],
|
| 14 |
allow_credentials=True,
|
| 15 |
-
allow_methods=["POST"
|
| 16 |
allow_headers=["*"],
|
| 17 |
)
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
async def serve_index():
|
| 22 |
-
return FileResponse("index.html")
|
| 23 |
|
| 24 |
-
# API endpoint for background removal
|
| 25 |
@app.post("/remove-background")
|
| 26 |
async def remove_background(file: UploadFile = File(...)):
|
| 27 |
try:
|
| 28 |
-
#
|
| 29 |
contents = await file.read()
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
with open(temp_path, "rb") as f:
|
| 39 |
-
img_data = f.read()
|
| 40 |
-
os.remove(temp_path)
|
| 41 |
|
| 42 |
-
|
| 43 |
-
return {"image": img_base64}
|
| 44 |
except Exception as e:
|
| 45 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 1 |
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from PIL import Image
|
|
|
|
|
|
|
| 4 |
import io
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
import base64
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
|
|
|
| 13 |
CORSMiddleware,
|
| 14 |
allow_origins=["https://*.figma.com"],
|
| 15 |
allow_credentials=True,
|
| 16 |
+
allow_methods=["POST"],
|
| 17 |
allow_headers=["*"],
|
| 18 |
)
|
| 19 |
|
| 20 |
+
# Load the model
|
| 21 |
+
pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True)
|
|
|
|
|
|
|
| 22 |
|
|
|
|
| 23 |
@app.post("/remove-background")
|
| 24 |
async def remove_background(file: UploadFile = File(...)):
|
| 25 |
try:
|
| 26 |
+
# Read image
|
| 27 |
contents = await file.read()
|
| 28 |
+
image = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 29 |
+
|
| 30 |
+
# Process image
|
| 31 |
+
result = pipe(image)
|
| 32 |
+
output = result["output"]
|
| 33 |
|
| 34 |
+
# Convert to base64
|
| 35 |
+
buffered = io.BytesIO()
|
| 36 |
+
output.save(buffered, format="PNG")
|
| 37 |
+
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
return {"image": img_str}
|
|
|
|
| 40 |
except Exception as e:
|
| 41 |
raise HTTPException(status_code=500, detail=str(e))
|