AkashKumarave commited on
Commit
dee0003
·
verified ·
1 Parent(s): 7ec9e2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -72
app.py CHANGED
@@ -1,74 +1,36 @@
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
-
12
- # Enable CORS for Figma
13
- app.add_middleware(
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))
 
1
+ from transformers import pipeline
2
+ import gradio as gr
3
+ from PIL import Image
4
+ import numpy as np
5
+
6
+ # Initialize the image segmentation pipeline with the DIS-based model
7
+ pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True)
8
+
9
+ # Function to remove background
10
+ def remove_background(input_image):
11
+ # Ensure input is a PIL Image
12
+ if isinstance(input_image, np.ndarray):
13
+ input_image = Image.fromarray(input_image)
14
+
15
+ # Get the mask and the processed image
16
+ pillow_mask = pipe(input_image, return_mask=True) # Returns a binary mask
17
+ no_bg_image = pipe(input_image) # Returns the image with background removed
18
+
19
+ # Ensure the output is a PIL Image with transparency
20
+ if isinstance(no_bg_image, np.ndarray):
21
+ no_bg_image = Image.fromarray(no_bg_image)
22
+
23
+ return no_bg_image
24
+
25
+ # Set up Gradio interface
26
+ demo = gr.Interface(
27
+ fn=remove_background,
28
+ inputs=gr.Image(type="pil", label="Upload Image"),
29
+ outputs=gr.Image(type="pil", label="Image with Background Removed"),
30
+ title="Background Remover using DIS (IS-Net)",
31
+ description="Upload an image to remove its background using the briaai/RMBG-1.4 model."
32
  )
33
 
34
+ # Launch the app
35
+ if __name__ == "__main__":
36
+ demo.launch()