Felguk commited on
Commit
915cfe7
·
verified ·
1 Parent(s): cf1aafb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -114
app.py CHANGED
@@ -5,9 +5,6 @@ import numpy as np
5
  import time
6
  import requests
7
  from io import BytesIO
8
- import json
9
- import os
10
- from datetime import datetime
11
 
12
  def washing_machine(image):
13
  # Convert to PIL Image if it's a numpy array
@@ -28,8 +25,7 @@ def washing_machine(image):
28
  yield "Spin cycle complete!", rotated
29
 
30
  # Final clean image
31
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
32
- yield "Your image is clean and background-free!", (result, timestamp)
33
 
34
  def load_image_from_url(url):
35
  try:
@@ -39,7 +35,7 @@ def load_image_from_url(url):
39
  except Exception as e:
40
  raise gr.Error(f"Failed to load image from URL: {str(e)}")
41
 
42
- # Custom CSS and JS for the app
43
  css = """
44
  #wash-btn {background-color: #00a8ff; color: white; border: none; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 12px;}
45
  #wash-btn:hover {background-color: #0095e6;}
@@ -48,29 +44,9 @@ css = """
48
  #output-image {border: 5px dashed #00a8ff; border-radius: 10px;}
49
  #input-image {border: 5px dashed #ccc; border-radius: 10px;}
50
  .tab {padding: 20px;}
51
- .history-item {margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 5px;}
52
- .history-img {max-width: 200px; max-height: 200px;}
53
  """
54
 
55
- js = """
56
- function saveToHistory(imageData, timestamp) {
57
- let history = JSON.parse(localStorage.getItem('bgWashHistory') || '[]');
58
- history.unshift({image: imageData, timestamp: timestamp});
59
- localStorage.setItem('bgWashHistory', JSON.stringify(history));
60
- return history;
61
- }
62
-
63
- function loadHistory() {
64
- return JSON.parse(localStorage.getItem('bgWashHistory') || '[]');
65
- }
66
-
67
- function clearHistory() {
68
- localStorage.removeItem('bgWashHistory');
69
- return [];
70
- }
71
- """
72
-
73
- with gr.Blocks(css=css, js=js) as demo:
74
  gr.Markdown("<h1 class='title'>🚀 Background Washing Machine 🧼</h1>")
75
  gr.Markdown("<p class='description'>Upload your image and we'll wash the background right off!</p>")
76
 
@@ -84,7 +60,6 @@ with gr.Blocks(css=css, js=js) as demo:
84
  with gr.Column():
85
  file_status = gr.Textbox(label="Washing Status")
86
  file_output = gr.Image(label="Clean Image (no background)")
87
- file_timestamp = gr.Textbox(visible=False)
88
 
89
  with gr.TabItem("From URL"):
90
  with gr.Row():
@@ -97,19 +72,6 @@ with gr.Blocks(css=css, js=js) as demo:
97
  with gr.Column():
98
  url_status = gr.Textbox(label="Washing Status")
99
  url_output = gr.Image(label="Clean Image (no background)")
100
- url_timestamp = gr.Textbox(visible=False)
101
-
102
- with gr.TabItem("History"):
103
- with gr.Row():
104
- with gr.Column():
105
- history_html = gr.HTML("<div id='history-container'></div>")
106
- clear_btn = gr.Button("Clear History", elem_id="wash-btn")
107
- with gr.Column():
108
- history_output = gr.Image(label="Selected Image")
109
-
110
- # Hidden components for JS communication
111
- history_data = gr.JSON(visible=False)
112
- update_history = gr.Textbox(visible=False)
113
 
114
  gr.Markdown("### How it works:")
115
  gr.Markdown("1. Upload your image 🖼️ or paste a URL\n2. Click the washing button 🧼\n3. Wait while we wash away the background 🫧\n4. Get your clean, background-free image! ✅")
@@ -118,20 +80,16 @@ with gr.Blocks(css=css, js=js) as demo:
118
  file_btn.click(
119
  washing_machine,
120
  inputs=file_input,
121
- outputs=[file_status, file_output, file_timestamp]
122
- ).then(
123
- None,
124
- [file_output, file_timestamp],
125
- None,
126
- _js="(img, ts) => saveToHistory(img, ts)"
127
- ).then(
128
- None,
129
- None,
130
- update_history,
131
- _js="() => loadHistory()"
132
  )
133
 
134
  # URL tab functionality
 
 
 
 
 
 
135
  url_fetch.click(
136
  fetch_image,
137
  inputs=url_input,
@@ -141,68 +99,7 @@ with gr.Blocks(css=css, js=js) as demo:
141
  url_btn.click(
142
  washing_machine,
143
  inputs=url_preview,
144
- outputs=[url_status, url_output, url_timestamp]
145
- ).then(
146
- None,
147
- [url_output, url_timestamp],
148
- None,
149
- _js="(img, ts) => saveToHistory(img, ts)"
150
- ).then(
151
- None,
152
- None,
153
- update_history,
154
- _js="() => loadHistory()"
155
- )
156
-
157
- # History tab functionality
158
- clear_btn.click(
159
- None,
160
- None,
161
- [history_data, update_history],
162
- _js="() => [clearHistory(), '']"
163
- )
164
-
165
- update_history.change(
166
- None,
167
- update_history,
168
- None,
169
- _js="""
170
- (history) => {
171
- const container = document.getElementById('history-container');
172
- if (!history || history.length === 0) {
173
- container.innerHTML = '<p>No history yet. Process some images first!</p>';
174
- return;
175
- }
176
-
177
- let html = '<h3>Your Washed Images:</h3>';
178
- history.forEach((item, index) => {
179
- html += `
180
- <div class="history-item">
181
- <p>${item.timestamp}</p>
182
- <img class="history-img" src="${item.image}" onclick="displaySelectedImage(${index})" />
183
- </div>
184
- `;
185
- });
186
- container.innerHTML = html;
187
- }
188
-
189
- function displaySelectedImage(index) {
190
- const history = JSON.parse(localStorage.getItem('bgWashHistory') || '[]');
191
- if (history[index]) {
192
- const imgElement = document.querySelector('#history-container img.selected');
193
- if (imgElement) imgElement.classList.remove('selected');
194
- document.querySelectorAll('#history-container img')[index].classList.add('selected');
195
- window.selectedImage = history[index].image;
196
- }
197
- }
198
- """
199
- )
200
-
201
- demo.load(
202
- None,
203
- None,
204
- update_history,
205
- _js="() => loadHistory()"
206
  )
207
 
208
  demo.launch()
 
5
  import time
6
  import requests
7
  from io import BytesIO
 
 
 
8
 
9
  def washing_machine(image):
10
  # Convert to PIL Image if it's a numpy array
 
25
  yield "Spin cycle complete!", rotated
26
 
27
  # Final clean image
28
+ yield "Your image is clean and background-free!", result
 
29
 
30
  def load_image_from_url(url):
31
  try:
 
35
  except Exception as e:
36
  raise gr.Error(f"Failed to load image from URL: {str(e)}")
37
 
38
+ # Custom CSS for washing machine theme
39
  css = """
40
  #wash-btn {background-color: #00a8ff; color: white; border: none; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 12px;}
41
  #wash-btn:hover {background-color: #0095e6;}
 
44
  #output-image {border: 5px dashed #00a8ff; border-radius: 10px;}
45
  #input-image {border: 5px dashed #ccc; border-radius: 10px;}
46
  .tab {padding: 20px;}
 
 
47
  """
48
 
49
+ with gr.Blocks(css=css) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  gr.Markdown("<h1 class='title'>🚀 Background Washing Machine 🧼</h1>")
51
  gr.Markdown("<p class='description'>Upload your image and we'll wash the background right off!</p>")
52
 
 
60
  with gr.Column():
61
  file_status = gr.Textbox(label="Washing Status")
62
  file_output = gr.Image(label="Clean Image (no background)")
 
63
 
64
  with gr.TabItem("From URL"):
65
  with gr.Row():
 
72
  with gr.Column():
73
  url_status = gr.Textbox(label="Washing Status")
74
  url_output = gr.Image(label="Clean Image (no background)")
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  gr.Markdown("### How it works:")
77
  gr.Markdown("1. Upload your image 🖼️ or paste a URL\n2. Click the washing button 🧼\n3. Wait while we wash away the background 🫧\n4. Get your clean, background-free image! ✅")
 
80
  file_btn.click(
81
  washing_machine,
82
  inputs=file_input,
83
+ outputs=[file_status, file_output]
 
 
 
 
 
 
 
 
 
 
84
  )
85
 
86
  # URL tab functionality
87
+ def fetch_image(url):
88
+ if not url:
89
+ raise gr.Error("Please enter a valid URL")
90
+ img = load_image_from_url(url)
91
+ return img, gr.Button(visible=True)
92
+
93
  url_fetch.click(
94
  fetch_image,
95
  inputs=url_input,
 
99
  url_btn.click(
100
  washing_machine,
101
  inputs=url_preview,
102
+ outputs=[url_status, url_output]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  )
104
 
105
  demo.launch()