Harzis commited on
Commit
a275fd7
·
verified ·
1 Parent(s): d09062d

Upload folder using huggingface_hub

Browse files
.github/workflows/update_space.yml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Python script
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ env:
12
+ HUGGINGFACE_TOKEN: ${{ secrets.HUGGINGFACE_TOKEN }}
13
+ steps:
14
+ - name: Checkout
15
+ uses: actions/checkout@v2
16
+
17
+ - name: Set up Python
18
+ uses: actions/setup-python@v2
19
+ with:
20
+ python-version: '3.9'
21
+
22
+ - name: Install dependencies
23
+ run: |
24
+ python -m pip install gradio huggingface_hub
25
+
26
+ - name: Log in to Hugging Face
27
+ run: huggingface-cli login --token $HUGGINGFACE_TOKEN
28
+
29
+ - name: Deploy to Spaces
30
+ run: gradio deploy
.gitignore ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore all files in the Input_images folder
2
+ Input_images/*
3
+
4
+ # Ignore all files in the Output_images folder
5
+ Output_images/*
6
+
7
+ # Gradio local files
8
+ .gradio/
9
+ *.pem
10
+
11
+ processed_images.zip
12
+
13
+ # Other common Python ignores (if not already present)
14
+ __pycache__/
15
+ *.pyc
16
+ *.pyo
17
+ *.egg-info/
18
+ .env
19
+ .venv/
20
+ venv/
LICENSE ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 2-Clause License
2
+
3
+ Copyright (c) 2025, Harri-Mi
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Background Removal
3
- emoji:
4
- colorFrom: green
5
- colorTo: gray
6
  sdk: gradio
7
  sdk_version: 5.38.2
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Background_removal
3
+ app_file: remove-backround-gradio.py
 
 
4
  sdk: gradio
5
  sdk_version: 5.38.2
 
 
6
  ---
 
 
remove-backround-gradio.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from rembg import remove
4
+ from PIL import Image
5
+ import io
6
+ import zipfile
7
+ from typing import List, Tuple
8
+
9
+ def remove_background_single(image_file) -> Image.Image:
10
+ """Remove background from a single image file"""
11
+ if image_file is None:
12
+ return None
13
+
14
+ # Read the image data
15
+ if hasattr(image_file, 'read'):
16
+ input_data = image_file.read()
17
+ else:
18
+ with open(image_file, 'rb') as f:
19
+ input_data = f.read()
20
+
21
+ # Remove background
22
+ output_data = remove(input_data)
23
+
24
+ # Convert to PIL Image
25
+ output_image = Image.open(io.BytesIO(output_data))
26
+ return output_image
27
+
28
+ def remove_background_multiple(image_files) -> Tuple[str, List[Image.Image]]:
29
+ """Remove background from multiple image files and return as zip + preview images"""
30
+ if not image_files:
31
+ return None, []
32
+
33
+ processed_images = []
34
+ preview_images = []
35
+
36
+ # Create a zip file in memory
37
+ zip_buffer = io.BytesIO()
38
+
39
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
40
+ for i, image_file in enumerate(image_files):
41
+ try:
42
+ # Get original filename or create one
43
+ if hasattr(image_file, 'name') and image_file.name:
44
+ original_name = os.path.basename(image_file.name)
45
+ name_without_ext = os.path.splitext(original_name)[0]
46
+ else:
47
+ name_without_ext = f"image_{i+1}"
48
+
49
+ # Remove background
50
+ processed_image = remove_background_single(image_file)
51
+
52
+ if processed_image:
53
+ # Save to zip file
54
+ img_buffer = io.BytesIO()
55
+ processed_image.save(img_buffer, format='PNG')
56
+ img_buffer.seek(0)
57
+
58
+ zip_file.writestr(f"{name_without_ext}_no_bg.png", img_buffer.getvalue())
59
+
60
+ # Add to preview (limit to first 5 images for display)
61
+ if len(preview_images) < 5:
62
+ preview_images.append(processed_image)
63
+
64
+ except Exception as e:
65
+ print(f"Error processing image {i+1}: {str(e)}")
66
+ continue
67
+
68
+ zip_buffer.seek(0)
69
+
70
+ # Save zip file temporarily
71
+ zip_path = "processed_images.zip"
72
+ with open(zip_path, 'wb') as f:
73
+ f.write(zip_buffer.getvalue())
74
+
75
+ return zip_path, preview_images
76
+
77
+ def process_images(single_image, multiple_images, processing_mode):
78
+ """Main processing function based on selected mode"""
79
+ if processing_mode == "Single Image":
80
+ if single_image is None:
81
+ return None, None, None, "Please upload an image first."
82
+
83
+ try:
84
+ result = remove_background_single(single_image)
85
+ return result, None, None, "Background removed successfully!"
86
+ except Exception as e:
87
+ return None, None, None, f"Error processing image: {str(e)}"
88
+
89
+ else: # Multiple Images
90
+ if not multiple_images:
91
+ return None, None, None, "Please upload at least one image."
92
+
93
+ try:
94
+ zip_file, preview_images = remove_background_multiple(multiple_images)
95
+ if zip_file and preview_images:
96
+ return None, preview_images, zip_file, f"Processed {len(multiple_images)} images successfully! Download the zip file to get all results."
97
+ else:
98
+ return None, None, None, "No images were processed successfully."
99
+ except Exception as e:
100
+ return None, None, None, f"Error processing images: {str(e)}"
101
+
102
+ # Create Gradio interface
103
+ with gr.Blocks(title="Background Removal Tool", theme=gr.themes.Default()) as app:
104
+ gr.Markdown(
105
+ """
106
+ # 🖼️ Background Removal Tool
107
+
108
+ Upload your images and get them back with transparent backgrounds!
109
+
110
+ **Choose your mode:**
111
+ - **Single Image**: Upload one image and preview the result
112
+ - **Multiple Images**: Upload multiple images and download them as a zip file
113
+ """
114
+ )
115
+
116
+ with gr.Row():
117
+ processing_mode = gr.Radio(
118
+ choices=["Single Image", "Multiple Images"],
119
+ value="Single Image",
120
+ label="Processing Mode"
121
+ )
122
+
123
+ with gr.Row():
124
+ with gr.Column():
125
+ # Single image input (visible by default)
126
+ single_image_input = gr.File(
127
+ label="Upload Single Image",
128
+ file_types=["image"],
129
+ visible=True
130
+ )
131
+
132
+ # Multiple images input (hidden by default)
133
+ multiple_images_input = gr.File(
134
+ label="Upload Multiple Images",
135
+ file_count="multiple",
136
+ file_types=["image"],
137
+ visible=False
138
+ )
139
+
140
+ process_btn = gr.Button("Remove Background", variant="primary", size="lg")
141
+
142
+ with gr.Column():
143
+ # Output for single image
144
+ single_output = gr.Image(
145
+ label="Result",
146
+ visible=True
147
+ )
148
+
149
+ # Output for multiple images
150
+ multiple_output_gallery = gr.Gallery(
151
+ label="Preview (first 5 images)",
152
+ visible=False,
153
+ columns=3,
154
+ rows=2,
155
+ height="auto"
156
+ )
157
+
158
+ download_file = gr.File(
159
+ label="Download All Processed Images",
160
+ visible=False
161
+ )
162
+
163
+ status_message = gr.Textbox(label="Status", interactive=False)
164
+
165
+ # Function to toggle visibility based on mode
166
+ def toggle_inputs(mode):
167
+ if mode == "Single Image":
168
+ return (
169
+ gr.update(visible=True), # single_image_input
170
+ gr.update(visible=False), # multiple_images_input
171
+ gr.update(visible=True), # single_output
172
+ gr.update(visible=False), # multiple_output_gallery
173
+ gr.update(visible=False) # download_file
174
+ )
175
+ else:
176
+ return (
177
+ gr.update(visible=False), # single_image_input
178
+ gr.update(visible=True), # multiple_images_input
179
+ gr.update(visible=False), # single_output
180
+ gr.update(visible=True), # multiple_output_gallery
181
+ gr.update(visible=True) # download_file
182
+ )
183
+
184
+ # Toggle inputs when mode changes
185
+ processing_mode.change(
186
+ fn=toggle_inputs,
187
+ inputs=[processing_mode],
188
+ outputs=[single_image_input, multiple_images_input, single_output, multiple_output_gallery, download_file]
189
+ )
190
+
191
+ # Process images when button is clicked
192
+ process_btn.click(
193
+ fn=process_images,
194
+ inputs=[single_image_input, multiple_images_input, processing_mode],
195
+ outputs=[single_output, multiple_output_gallery, download_file, status_message]
196
+ )
197
+
198
+ # Remove the separate gallery update function since we're handling it directly now
199
+
200
+ gr.Markdown(
201
+ """
202
+ ### 📝 Instructions:
203
+ 1. Choose your processing mode (Single or Multiple images)
204
+ 2. Upload your image(s) - supports PNG, JPG, JPEG formats
205
+ 3. Click "Remove Background" to process
206
+ 4. For single images: preview the result directly
207
+ 5. For multiple images: download the zip file containing all processed images
208
+
209
+ ### ⚡ Features:
210
+ - Automatic background removal using AI
211
+ - Support for batch processing
212
+ - Transparent PNG output
213
+ - Easy download of results
214
+ """
215
+ )
216
+
217
+ if __name__ == "__main__":
218
+ app.launch(share=True)
remove_background.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from rembg import remove
3
+ from PIL import Image
4
+
5
+ input_folder = 'Input_images' # Your folder with images with white background
6
+ output_folder = 'Output_images' # Folder where images without background will be saved
7
+
8
+ os.makedirs(output_folder, exist_ok=True)
9
+
10
+ for filename in os.listdir(input_folder):
11
+ if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
12
+ input_path = os.path.join(input_folder, filename)
13
+ output_path = os.path.join(output_folder, filename)
14
+
15
+ with open(input_path, 'rb') as i:
16
+ input_data = i.read()
17
+ output_data = remove(input_data)
18
+
19
+ with open(output_path, 'wb') as o:
20
+ o.write(output_data)
21
+
22
+ print(f'Processed images saved to {output_folder}')
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ rembg>=2.0.0
3
+ pillow>=9.0.0
4
+ numpy>=1.21.0
5
+ onnxruntime>=1.12.0