AkashKumarave commited on
Commit
f5fdac6
·
verified ·
1 Parent(s): d4c0d72

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -18
app.py CHANGED
@@ -1,31 +1,45 @@
1
- from fastapi import FastAPI, File, UploadFile
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from transformers import pipeline
 
 
4
  import io
5
- from PIL import Image
6
 
7
  app = FastAPI()
8
 
9
- # Allow CORS for Figma plugin
10
  app.add_middleware(
11
  CORSMiddleware,
12
- allow_origins=["*"], # Update to specific origins in production
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
- # Load the RMBG-1.4 model
21
- pipe = pipeline('image-segmentation', 'briaai/RMBG-1.4')
22
- # Read image
23
- image_data = await file.read()
24
- image = Image.open(io.BytesIO(image_data))
25
- # Process image
26
- output = pipe(image)
27
- # Convert output to bytes
28
- output_image = Image.fromarray(output.data)
29
- output_bytes = io.BytesIO()
30
- output_image.save(output_bytes, format='PNG')
31
- return {"image": output_bytes.getvalue()}
 
 
 
 
 
 
 
 
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))