AkashKumarave commited on
Commit
62a094b
·
verified ·
1 Parent(s): 44579ae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -17
app.py CHANGED
@@ -1,10 +1,11 @@
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,29 +14,61 @@ app.add_middleware(
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))
 
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import FileResponse
4
+ from playwright.async_api import async_playwright
5
+ import os
 
6
  import base64
7
+ import io
8
+ import time
9
 
10
  app = FastAPI()
11
 
 
14
  CORSMiddleware,
15
  allow_origins=["https://*.figma.com"],
16
  allow_credentials=True,
17
+ allow_methods=["POST", "GET"],
18
  allow_headers=["*"],
19
  )
20
 
21
+ # Serve static files (index.html, assets)
22
+ @app.get("/")
23
+ async def serve_index():
24
+ return FileResponse("index.html")
25
 
26
+ # API endpoint for background removal
27
  @app.post("/remove-background")
28
  async def remove_background(file: UploadFile = File(...)):
29
  try:
30
+ # Save uploaded image
31
  contents = await file.read()
32
+ temp_path = "temp_image.png"
33
+ with open(temp_path, "wb") as f:
34
+ f.write(contents)
35
+
36
+ # Use Playwright to process image via index.html
37
+ async with async_playwright() as p:
38
+ browser = await p.chromium.launch()
39
+ page = await browser.new_page()
40
+
41
+ # Load the Space's frontend
42
+ await page.goto("http://localhost:7860/")
43
+
44
+ # Upload image
45
+ await page.set_input_files("#upload", temp_path)
46
+
47
+ # Wait for processing (adjust based on JS behavior)
48
+ await page.wait_for_timeout(5000) # Adjust if needed
49
+
50
+ # Extract processed image (assumes JS sets it in #status or similar)
51
+ # This depends on index-E_M5nW8h.js output (e.g., canvas or img)
52
+ processed_image = await page.evaluate("""
53
+ () => {
54
+ const canvas = document.querySelector('canvas'); // Adjust selector
55
+ if (canvas) {
56
+ return canvas.toDataURL('image/png').split(',')[1];
57
+ }
58
+ return null;
59
+ }
60
+ """)
61
+
62
+ await browser.close()
63
 
64
+ # Clean up
65
+ os.remove(temp_path)
 
66
 
67
+ if not processed_image:
68
+ raise HTTPException(status_code=500, detail="Failed to process image")
 
 
69
 
70
+ return {"image": processed_image}
71
  except Exception as e:
72
+ if os.path.exists(temp_path):
73
+ os.remove(temp_path)
74
  raise HTTPException(status_code=500, detail=str(e))