innoai commited on
Commit
e064a40
·
verified ·
1 Parent(s): fe14308

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -51
app.py CHANGED
@@ -1,11 +1,6 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
  AI Background Remover – Hugging Face Space
4
- Features
5
- ---------
6
- 1. Upload an image and get a transparent‑background PNG.
7
- 2. A “Save Image” button (base64 Data‑URI) appears right below the result.
8
- 3. A ZIP file containing the PNG is created automatically for download.
9
  """
10
 
11
  import spaces
@@ -13,7 +8,6 @@ import gradio as gr
13
  from transparent_background import Remover
14
  from PIL import Image
15
  import numpy as np
16
- import io
17
  import base64
18
  import tempfile
19
  import zipfile
@@ -21,44 +15,29 @@ import zipfile
21
  # --------------------------------------------------------------------------- #
22
  # Core processing #
23
  # --------------------------------------------------------------------------- #
24
- @spaces.GPU # Drop this decorator if you want to force CPU only
25
  def remove_background(image: Image.Image | np.ndarray):
26
- """
27
- Parameters
28
- ----------
29
- image : PIL.Image or np.ndarray
30
- Input image from the Gradio uploader.
31
-
32
- Returns
33
- -------
34
- png_path : str
35
- Path to the processed PNG (for gr.Image).
36
- download_link_html : str
37
- An <a> tag with an embedded base64 data URI so users can save the PNG.
38
- zip_path : str
39
- Path to a ZIP file containing the PNG (for gr.File).
40
- """
41
- # 1. Background removal
42
  remover = Remover()
43
- if isinstance(image, Image.Image):
44
- output = remover.process(image)
45
- elif isinstance(image, np.ndarray):
46
- output = remover.process(Image.fromarray(image))
47
- else:
48
  raise TypeError("Unsupported image type")
49
 
50
- # 2. Save PNG to a temporary file
 
 
 
51
  png_tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
52
  output.save(png_tmp, format="PNG")
53
  png_tmp.close()
54
  png_path = png_tmp.name
55
 
56
- # 3. Build base64 download link
57
  with open(png_path, "rb") as f:
58
- base64_image = base64.b64encode(f.read()).decode("utf-8")
59
-
60
  download_link_html = f"""
61
- <a href="data:application/octet-stream;base64,{base64_image}"
62
  download="background_removed.png"
63
  style="
64
  display:inline-block;
@@ -74,56 +53,59 @@ def remove_background(image: Image.Image | np.ndarray):
74
  </a>
75
  """
76
 
77
- # 4. Package PNG into a ZIP archive
78
  zip_tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
79
  with zipfile.ZipFile(zip_tmp.name, "w", zipfile.ZIP_DEFLATED) as zf:
80
  zf.write(png_path, arcname="background_removed.png")
81
  zip_tmp.close()
82
- zip_path = zip_tmp.name
83
 
84
- return png_path, download_link_html, zip_path
85
 
86
 
87
  # --------------------------------------------------------------------------- #
88
- # Gradio UI #
89
  # --------------------------------------------------------------------------- #
90
  TITLE = "AI Background Remover – Automatically Remove Image Backgrounds"
91
- DESCRIPTION = """
 
92
  Upload an image and our AI‑powered background remover will return a PNG with a transparent background.
93
 
94
  ### How to Use
95
  1. Click **Upload Image** or drag & drop a picture.
96
  2. Press **Start Processing** and wait a moment.
97
  3. The processed image appears on the right.
98
- 4. Click **📥Save Image** to download the PNG, or download the ZIP below.
99
 
100
  ### Application Scenarios
101
  - **E‑commerce** – Clean product photos with transparent backgrounds.
102
- - **Graphic Design** – Quick cutouts for composites or layouts.
103
  - **Social Media** – Avatars and icons that blend perfectly anywhere.
104
 
105
  Our tool leverages state‑of‑the‑art AI to remove backgrounds quickly and accurately—saving you time and effort.
106
  """
107
 
108
  with gr.Blocks(title=TITLE) as demo:
109
- gr.Markdown(f"# {TITLE}\n{DESCRIPTION}")
110
 
 
 
 
 
 
111
  with gr.Row():
112
- inp = gr.Image(label="Upload Image", type="numpy")
113
- btn = gr.Button("Start Processing", variant="primary")
114
 
115
- out_img = gr.Image(label="Output Image (PNG)", type="filepath", height=350)
116
- out_dl = gr.HTML()
117
- out_zip = gr.File(label="Download ZIP")
118
 
119
- btn.click(
120
  fn=remove_background,
121
- inputs=inp,
122
- outputs=[out_img, out_dl, out_zip],
123
  )
124
 
125
- # --------------------------------------------------------------------------- #
126
- # Entry point #
127
  # --------------------------------------------------------------------------- #
128
  if __name__ == "__main__":
129
  demo.launch(show_error=True, show_api=False)
 
1
  # -*- coding: utf-8 -*-
2
  """
3
  AI Background Remover – Hugging Face Space
 
 
 
 
 
4
  """
5
 
6
  import spaces
 
8
  from transparent_background import Remover
9
  from PIL import Image
10
  import numpy as np
 
11
  import base64
12
  import tempfile
13
  import zipfile
 
15
  # --------------------------------------------------------------------------- #
16
  # Core processing #
17
  # --------------------------------------------------------------------------- #
18
+ @spaces.GPU # Remove if you prefer CPU‑only execution
19
  def remove_background(image: Image.Image | np.ndarray):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  remover = Remover()
21
+
22
+ if isinstance(image, np.ndarray):
23
+ image = Image.fromarray(image)
24
+ elif not isinstance(image, Image.Image):
 
25
  raise TypeError("Unsupported image type")
26
 
27
+ # 1) Remove background
28
+ output = remover.process(image)
29
+
30
+ # 2) Save PNG
31
  png_tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
32
  output.save(png_tmp, format="PNG")
33
  png_tmp.close()
34
  png_path = png_tmp.name
35
 
36
+ # 3) Build base64 download button
37
  with open(png_path, "rb") as f:
38
+ b64 = base64.b64encode(f.read()).decode()
 
39
  download_link_html = f"""
40
+ <a href="data:application/octet-stream;base64,{b64}"
41
  download="background_removed.png"
42
  style="
43
  display:inline-block;
 
53
  </a>
54
  """
55
 
56
+ # 4) Zip
57
  zip_tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
58
  with zipfile.ZipFile(zip_tmp.name, "w", zipfile.ZIP_DEFLATED) as zf:
59
  zf.write(png_path, arcname="background_removed.png")
60
  zip_tmp.close()
 
61
 
62
+ return png_path, download_link_html, zip_tmp.name
63
 
64
 
65
  # --------------------------------------------------------------------------- #
66
+ # UI #
67
  # --------------------------------------------------------------------------- #
68
  TITLE = "AI Background Remover – Automatically Remove Image Backgrounds"
69
+
70
+ DESCRIPTION_MD = """
71
  Upload an image and our AI‑powered background remover will return a PNG with a transparent background.
72
 
73
  ### How to Use
74
  1. Click **Upload Image** or drag & drop a picture.
75
  2. Press **Start Processing** and wait a moment.
76
  3. The processed image appears on the right.
77
+ 4. Click **📥 Save Image** to download the PNG, or download the ZIP below.
78
 
79
  ### Application Scenarios
80
  - **E‑commerce** – Clean product photos with transparent backgrounds.
81
+ - **Graphic Design** – Quick cut‑outs for composites or layouts.
82
  - **Social Media** – Avatars and icons that blend perfectly anywhere.
83
 
84
  Our tool leverages state‑of‑the‑art AI to remove backgrounds quickly and accurately—saving you time and effort.
85
  """
86
 
87
  with gr.Blocks(title=TITLE) as demo:
88
+ gr.Markdown(f"# {TITLE}")
89
 
90
+ # -------- Accordion with instructions (default open) -------- #
91
+ with gr.Accordion("Instructions & Scenarios (click to collapse)", open=True):
92
+ gr.Markdown(DESCRIPTION_MD)
93
+
94
+ # -------- I/O widgets -------- #
95
  with gr.Row():
96
+ input_img = gr.Image(label="Upload Image", type="numpy")
97
+ process_btn = gr.Button("Start Processing", variant="primary")
98
 
99
+ output_img = gr.Image(label="Output Image (PNG)", type="filepath", height=350)
100
+ download_html = gr.HTML()
101
+ zip_file = gr.File(label="Download ZIP")
102
 
103
+ process_btn.click(
104
  fn=remove_background,
105
+ inputs=input_img,
106
+ outputs=[output_img, download_html, zip_file]
107
  )
108
 
 
 
109
  # --------------------------------------------------------------------------- #
110
  if __name__ == "__main__":
111
  demo.launch(show_error=True, show_api=False)