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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -22
app.py CHANGED
@@ -1,9 +1,10 @@
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
 
@@ -12,34 +13,29 @@ 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))
 
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))