Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,31 +1,45 @@
|
|
| 1 |
-
from fastapi import FastAPI, File, UploadFile
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
-
from
|
|
|
|
|
|
|
| 4 |
import io
|
| 5 |
-
from PIL import Image
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
-
#
|
| 10 |
app.add_middleware(
|
| 11 |
CORSMiddleware,
|
| 12 |
-
allow_origins=["
|
| 13 |
allow_credentials=True,
|
| 14 |
-
allow_methods=["
|
| 15 |
allow_headers=["*"],
|
| 16 |
)
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
@app.post("/remove-background")
|
| 19 |
async def remove_background(file: UploadFile = File(...)):
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.responses import FileResponse
|
| 4 |
+
import os
|
| 5 |
+
import base64
|
| 6 |
import io
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
+
# Enable CORS for Figma
|
| 11 |
app.add_middleware(
|
| 12 |
CORSMiddleware,
|
| 13 |
+
allow_origins=["https://*.figma.com"],
|
| 14 |
allow_credentials=True,
|
| 15 |
+
allow_methods=["POST", "GET"],
|
| 16 |
allow_headers=["*"],
|
| 17 |
)
|
| 18 |
|
| 19 |
+
# Serve static files (index.html, assets)
|
| 20 |
+
@app.get("/")
|
| 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 |
+
# Save uploaded image temporarily
|
| 29 |
+
contents = await file.read()
|
| 30 |
+
temp_path = "temp_image.png"
|
| 31 |
+
with open(temp_path, "wb") as f:
|
| 32 |
+
f.write(contents)
|
| 33 |
+
|
| 34 |
+
# The client-side JS (index-E_M5nW8h.js) handles processing
|
| 35 |
+
# This endpoint assumes the processed image is saved by JS
|
| 36 |
+
# For simplicity, return the uploaded image as base64
|
| 37 |
+
# In practice, you'd need a way to trigger JS and get the result
|
| 38 |
+
with open(temp_path, "rb") as f:
|
| 39 |
+
img_data = f.read()
|
| 40 |
+
os.remove(temp_path)
|
| 41 |
+
|
| 42 |
+
img_base64 = base64.b64encode(img_data).decode("utf-8")
|
| 43 |
+
return {"image": img_base64}
|
| 44 |
+
except Exception as e:
|
| 45 |
+
raise HTTPException(status_code=500, detail=str(e))
|