-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui.py
257 lines (223 loc) · 11.2 KB
/
gui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""
Name: GUI
Description: This file contains the GUI interface.
Version: [release][3.2]
Source url: https://github.com/OPHoperHPO/image-background-remove-tool
Authors: Munawwar [https://github.com/Munawwar], Anodev (OPHoperHPO)[https://github.com/OPHoperHPO].
License: Apache License 2.0
License:
Copyright 2020 OPHoperHPO
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import logging
import platform
import subprocess
import webview
import threading
from main import process
import multiprocessing
from libs.strings import MODELS_NAMES, PREPROCESS_METHODS, POSTPROCESS_METHODS
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def show_error(w, e):
"""
Shows error
@param w: Window obj
@param e: Error text
"""
w.evaluate_js("""
var err_label = document.querySelector('.error_label');
err_label.style.visibility = "";
err_label.textContent = 'REPLACE';
""".replace("REPLACE", "An error has occurred! ERROR: " + str(e)))
# noinspection PyMissingOrEmptyDocstring
def worker_thread(win, input_files, model, preprocessing_method, postprocessing_method):
logger.debug('Processing started ...')
for i, file in enumerate(input_files):
(file_path, file_name) = os.path.split(file)
output_file = os.path.join(
file_path,
'bg-removed',
# only support PNG files as of now
os.path.splitext(file_name)[0] + '.png'
)
win.evaluate_js(
"window.app.fileUploadButton.textContent = 'Processing "
+ str(i + 1) + ' of ' + str(len(input_files)) + " ...'"
)
try:
proc = multiprocessing.Process(target=process,
args=(file, output_file, model,
preprocessing_method, postprocessing_method,))
proc.start()
proc.join()
except BaseException as e:
show_error(win, e)
win.evaluate_js("window.app.fileUploadButton.textContent = 'Select photos'")
logger.debug('Processing complete')
# noinspection PyUnboundLocalVariable
open_folder(os.path.join(file_path, 'bg-removed'))
def onWindowStart(win2):
"""
Window Start Event listener
@param win2: Window object
"""
# TODO: Make a universal function for adding parameters to the settings page.
def addPostprocessingMethods():
"""
Adds postprocessing methods to the postprocessing methods selection list.
"""
def __add_method__(method: str):
if not method == POSTPROCESS_METHODS[0]:
win2.evaluate_js("""
function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes
return div.firstChild;
}
var models = document.querySelector('.postprocessing_methods');
var rbut = createElementFromHTML('<label style="margin-left:16;" class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="MODELD"><input id="MODELD" class="mdl-radio__button MODELD" type="radio" name="postprocessing_method" value="MODELD" /><span class="mdl-radio__label">MODELD</span></label>')
models.appendChild(rbut)
componentHandler.upgradeDom()
""".replace("MODELD", method))
else:
win2.evaluate_js("""
function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes
return div.firstChild;
}
var models = document.querySelector('.postprocessing_methods');
var rbut = createElementFromHTML('<label style="margin-left:16;" class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="MODELD"><input id="MODELD" class="mdl-radio__button MODELD" type="radio" name="postprocessing_method" value="MODELD" checked /><span class="mdl-radio__label">MODELD</span></label>')
models.appendChild(rbut)
componentHandler.upgradeDom()
""".replace("MODELD", method))
for i in POSTPROCESS_METHODS:
__add_method__(i)
def addPreprocessingMethods():
"""
Adds preprocessing methods to the preprocessing methods selection list.
"""
def __add_method__(method: str):
if not method == PREPROCESS_METHODS[0]:
win2.evaluate_js("""
function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes
return div.firstChild;
}
var models = document.querySelector('.preprocessing_methods');
var rbut = createElementFromHTML('<label style="margin-left:16;" class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="MODELD"><input id="MODELD" class="mdl-radio__button MODELD" type="radio" name="preprocessing_method" value="MODELD" /><span class="mdl-radio__label">MODELD</span></label>')
models.appendChild(rbut)
componentHandler.upgradeDom()
""".replace("MODELD", method))
else:
win2.evaluate_js("""
function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes
return div.firstChild;
}
var models = document.querySelector('.preprocessing_methods');
var rbut = createElementFromHTML('<label style="margin-left:16;" class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="MODELD"><input id="MODELD" class="mdl-radio__button MODELD" type="radio" name="preprocessing_method" value="MODELD" checked /><span class="mdl-radio__label">MODELD</span></label>')
models.appendChild(rbut)
componentHandler.upgradeDom()
""".replace("MODELD", method))
for i in PREPROCESS_METHODS:
__add_method__(i)
def addModels():
"""
Adds models to the model selection list.
"""
def __add_model__(model: str):
if not model == MODELS_NAMES[0]:
win2.evaluate_js("""
function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes
return div.firstChild;
}
var models = document.querySelector('.models');
var rbut = createElementFromHTML('<label style="margin-left:16;" class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="MODELD"><input id="MODELD" class="mdl-radio__button MODELD" type="radio" name="model" value="MODELD" /><span class="mdl-radio__label">MODELD</span></label>')
models.appendChild(rbut)
componentHandler.upgradeDom()
""".replace("MODELD", model))
else:
win2.evaluate_js("""
function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes
return div.firstChild;
}
var models = document.querySelector('.models');
var rbut = createElementFromHTML('<label style="margin-left:16;" class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="MODELD"><input id="MODELD" class="mdl-radio__button MODELD" type="radio" name="model" value="MODELD" checked /><span class="mdl-radio__label">MODELD</span></label>')
models.appendChild(rbut)
componentHandler.upgradeDom()
""".replace("MODELD", model))
for i in MODELS_NAMES:
__add_model__(i)
def openFileDialog():
"""
Opens a file selection dialog
"""
file_types = ('Image Files (*.png;*.jpg;*.jpeg)', 'All files (*.*)')
input_files = win2.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=True, file_types=file_types)
logger.debug(input_files)
preprocessing_method = win2.evaluate_js("window.app.getPreprocessingMethod()")
postprocessing_method = win2.evaluate_js("window.app.getPostprocessingMethod()")
model = win2.evaluate_js("window.app.getModel()")
logger.debug('Use model: {}'.format(model))
if input_files is not None:
win2.evaluate_js("window.app.fileUploadButton.disabled = true")
w_th = threading.Thread(target=worker_thread, args=(win2, input_files, model,
preprocessing_method, postprocessing_method,))
w_th.start()
w_th.join()
win2.evaluate_js("window.app.fileUploadButton.disabled = false")
# expose a function during the runtime
win2.expose(openFileDialog)
if win2.loaded:
addModels()
addPreprocessingMethods()
addPostprocessingMethods()
def open_folder(path):
"""
Opens a output folder in file explorer.
@param path: Path to folder
"""
if platform.system() == "Windows":
os.startfile(path)
elif platform.system() == "Darwin":
subprocess.Popen(["open", path])
else:
subprocess.Popen(["xdg-open", path])
def getfile(filename: str):
"""
Opens html file
@param filename: filename
@return: file content
"""
dir1 = os.path.dirname(__file__)
path = os.path.join(dir1, filename)
with open(path) as f:
content = f.read()
return content
if __name__ == '__main__':
html = getfile('gui/index.html')
window = webview.create_window('Automated BG Removal Tool', html=html)
webview.start(onWindowStart, window)