Xlnk commited on
Commit
c0ad71a
·
verified ·
1 Parent(s): a069653

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -8
app.py CHANGED
@@ -1,18 +1,36 @@
1
  import gradio as gr
2
  from rembg import remove
 
3
  from PIL import Image
4
  import io, base64, os
5
 
6
  PORT = int(os.environ.get("PORT", 7860))
7
 
 
 
 
8
  def remove_bg_auto_download(image):
9
- output = remove(image)
 
10
 
 
11
  buf = io.BytesIO()
12
- output.save(buf, format="PNG")
13
- buf.seek(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- b64 = base64.b64encode(buf.read()).decode()
16
  return f"""
17
  <script>
18
  const a = document.createElement('a');
@@ -25,13 +43,13 @@ def remove_bg_auto_download(image):
25
  """
26
 
27
  with gr.Blocks() as demo:
28
- gr.Markdown("## Drag & Drop Auto background removal & download")
29
- image = gr.Image(type="pil", label="Drop image")
30
  html = gr.HTML()
31
 
32
- image.change(
33
  fn=remove_bg_auto_download,
34
- inputs=image,
35
  outputs=html
36
  )
37
 
 
1
  import gradio as gr
2
  from rembg import remove
3
+ from rembg.session_factory import new_session
4
  from PIL import Image
5
  import io, base64, os
6
 
7
  PORT = int(os.environ.get("PORT", 7860))
8
 
9
+ # ⚡ Preload U²-Net Lite
10
+ session = new_session("u2netp")
11
+
12
  def remove_bg_auto_download(image):
13
+ if image is None:
14
+ return ""
15
 
16
+ # Convert PIL → bytes
17
  buf = io.BytesIO()
18
+ image.save(buf, format="PNG")
19
+ input_bytes = buf.getvalue()
20
+
21
+ # 🔥 REAL background removal
22
+ output_bytes = remove(input_bytes, session=session)
23
+
24
+ # Ensure PIL image w/ alpha
25
+ output_img = Image.open(io.BytesIO(output_bytes)).convert("RGBA")
26
+
27
+ # Back to bytes
28
+ out_buf = io.BytesIO()
29
+ output_img.save(out_buf, format="PNG")
30
+ out_buf.seek(0)
31
+
32
+ b64 = base64.b64encode(out_buf.read()).decode()
33
 
 
34
  return f"""
35
  <script>
36
  const a = document.createElement('a');
 
43
  """
44
 
45
  with gr.Blocks() as demo:
46
+ gr.Markdown("## Fast Background Removal (U²-Net Lite)")
47
+ img = gr.Image(type="pil", label="Drag & drop image")
48
  html = gr.HTML()
49
 
50
+ img.change(
51
  fn=remove_bg_auto_download,
52
+ inputs=img,
53
  outputs=html
54
  )
55