GulbaharAI commited on
Commit
036811a
Β·
verified Β·
1 Parent(s): a86e315

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -25
app.py CHANGED
@@ -1,39 +1,83 @@
1
  import gradio as gr
2
- import requests
3
  import io
 
 
4
  from PIL import Image
 
 
5
 
6
- def remove_background(image):
7
- try:
8
- # Convert image to bytes
9
- img_bytes = io.BytesIO()
10
- image.save(img_bytes, format="PNG")
11
- img_bytes = img_bytes.getvalue()
12
-
13
- # Call your local API (will change to HF URL later)
14
- response = requests.post(
15
- "http://localhost:8001/api/v1/background-removal/remove-background",
16
- files={"file": ("image.png", img_bytes, "image/png")}
17
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- if response.status_code == 200:
20
- # Get the response and return image
21
- result_data = response.json()
22
- download_url = result_data["download_url"]
 
 
 
 
 
 
 
 
 
23
 
24
- # Download the processed image
25
- result_response = requests.get(f"http://localhost:8001{download_url}")
26
- result_bytes = io.BytesIO(result_response.content)
27
- return Image.open(result_bytes)
28
- else:
29
- raise Exception(f"API call failed: {response.status_code}")
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  except Exception as e:
32
- raise gr.Error(f"Background removal failed: {str(e)}")
33
 
34
  # Create Gradio interface
35
  demo = gr.Interface(
36
- fn=remove_background,
37
  inputs=gr.Image(type="pil", label="πŸ“· Upload Image"),
38
  outputs=gr.Image(type="pil", label="🎨 Background Removed"),
39
  title="🎨 Professional Background Remover",
 
1
  import gradio as gr
 
2
  import io
3
+ import torch
4
+ import numpy as np
5
  from PIL import Image
6
+ import os
7
+ import sys
8
 
9
+ # Add current directory to path for model files
10
+ sys.path.append("/app")
11
+
12
+ # Import model components
13
+ from briarmbg import BriaRMBG
14
+ from utilities import preprocess_image, postprocess_image
15
+
16
+ class BackgroundRemover:
17
+ def __init__(self):
18
+ self.model = None
19
+ self.device = None
20
+ self.load_model()
21
+
22
+ def load_model(self):
23
+ """Load the RMBG-1.4 model"""
24
+ try:
25
+ print("πŸ”„ Loading background removal model...")
26
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
+ self.model = BriaRMBG.from_pretrained("/app")
28
+ self.model.to(self.device)
29
+ self.model.eval()
30
+ print("βœ… Model loaded successfully!")
31
+ except Exception as e:
32
+ print(f"❌ Error loading model: {e}")
33
+ self.model = None
34
+
35
+ def remove_background(self, image):
36
+ """Remove background from image"""
37
+ if self.model is None:
38
+ raise Exception("Model not loaded")
39
 
40
+ try:
41
+ # Convert to RGB if needed
42
+ input_image = image.convert("RGB")
43
+
44
+ # Preprocess
45
+ model_input_size = [1024, 1024]
46
+ orig_im = np.array(input_image)
47
+ orig_im_size = orig_im.shape[0:2]
48
+ processed_image = preprocess_image(orig_im, model_input_size).to(self.device)
49
+
50
+ # Inference
51
+ with torch.no_grad():
52
+ result = self.model(processed_image)
53
 
54
+ # Postprocess
55
+ result_image = postprocess_image(result[0][0], orig_im_size)
 
 
 
 
56
 
57
+ # Create transparent image
58
+ pil_mask = Image.fromarray(result_image)
59
+ no_bg_image = input_image.copy()
60
+ no_bg_image.putalpha(pil_mask)
61
+
62
+ return no_bg_image
63
+
64
+ except Exception as e:
65
+ raise Exception(f"Background removal failed: {str(e)}")
66
+
67
+ # Initialize the remover
68
+ remover = BackgroundRemover()
69
+
70
+ def process_image(image):
71
+ """Gradio interface function"""
72
+ try:
73
+ result = remover.remove_background(image)
74
+ return result
75
  except Exception as e:
76
+ raise gr.Error(str(e))
77
 
78
  # Create Gradio interface
79
  demo = gr.Interface(
80
+ fn=process_image,
81
  inputs=gr.Image(type="pil", label="πŸ“· Upload Image"),
82
  outputs=gr.Image(type="pil", label="🎨 Background Removed"),
83
  title="🎨 Professional Background Remover",