-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
295 lines (256 loc) · 10.6 KB
/
main.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
from argparse import ArgumentParser
import sys
from collections import OrderedDict
import json
import logging
from decimal import Decimal
from enum import Enum
import os
from copy import deepcopy
import multiprocessing
from tqdm import tqdm
import toga
from config import Config
from utils import is_standalone, exception_to_str, EnumActionLowerCase, dirs
def var_to_label(var: str):
return " ".join(w[0].upper() + w[1:] for w in var.lower().split("_"))
def build_config_inputs(config, container, on_config_change):
inputs = []
for var in dir(config):
if var.startswith("_") or var == "data_dir":
continue
value = getattr(config, var)
value_type = type(value)
if value_type is float:
input = toga.NumberInput(default=value, step=Decimal("0.01"), on_change=lambda input, var=var: on_config_change(var, float(input.value)))
elif value_type is int:
input = toga.NumberInput(default=value, step=1, on_change=lambda input, var=var: on_config_change(var, int(input.value)))
elif value_type is bool:
input = toga.Switch("", is_on=value, on_toggle=lambda input, var=var: on_config_change(var, input.is_on))
elif issubclass(value_type, Enum):
input = toga.Selection(items=[e for e in dir(type(value)) if not e.startswith("_")], on_select=lambda input, var=var, default_type=value_type: on_config_change(var, getattr(default_type, input.value)))
input.value = value.name
else:
continue
box = toga.Box()
label = toga.Label(var_to_label(var))
label.style.flex = 1
box.add(label)
inputs.append(input)
input_box = toga.Box()
input_box.add(input)
input_box.style.flex = 0
input_box.style.padding_left = input_box.style.padding_right = 75
box.add(input_box)
box.style.padding_left = box.style.padding_right = 15
box.style.padding_top = box.style.padding_bottom = 2
box.style.flex = 1
container.add(box)
return inputs
def build(app: toga.App):
sleep_duration = 0.01
os.makedirs(dirs.user_config_dir, exist_ok=True)
os.makedirs(dirs.user_log_dir, exist_ok=True)
config_path = os.path.join(dirs.user_config_dir, "config.json")
log_path = os.path.join(dirs.user_log_dir, "log.txt")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(log_path),
logging.StreamHandler()
]
)
def persist_config(config, config_path):
obj = OrderedDict()
for var in dir(config):
if var.startswith("_"):
continue
value = getattr(config, var)
if issubclass(type(value), Enum):
value = value.name
obj[var] = value
try:
with open(config_path, "w") as f:
json.dump(obj, f)
except Exception as e:
logging.info(f"Unable to persist config: {str(e)}")
def load_config(config_path):
try:
with open(config_path) as f:
obj = json.load(f)
for k, v in obj.copy().items():
if not hasattr(Config, k):
continue
if issubclass(type(getattr(Config, k)), Enum):
obj[k] = getattr(type(getattr(Config, k)), v)
config = Config(**obj)
except Exception as e:
logging.info(f"Unable to load config: {str(e)}")
config = Config()
return config
config = load_config(config_path)
main_box = toga.Box()
main_box.style.direction = "column"
config_box = toga.Box()
config_box.style.direction = "column"
data_dir_box = toga.Box()
data_dir_box.style.padding = 15
data_dir_label = toga.TextInput(readonly=True, initial=config.data_dir)
data_dir_label.style.flex = 1
data_dir_label.style.padding_left = 15
async def update_data_dir(_):
data_dir = await app.main_window.select_folder_dialog(
"Select Data Directory",
# on_result=on_result,
initial_directory=os.path.realpath(config.data_dir) if os.path.isdir(config.data_dir) and config.data_dir != "" else None,
)
if data_dir is not None:
data_dir_label.value = str(data_dir)
config.data_dir = str(data_dir)
persist_config(config, config_path)
update_data_dir_button = toga.Button("Select Data Directory", on_press=update_data_dir)
data_dir_box.add(update_data_dir_button)
data_dir_box.add(data_dir_label)
config_box.add(data_dir_box)
def enable_inputs(inputs, enable):
for input in inputs:
input.enabled = enable
def on_config_change(var, value):
setattr(config, var, value)
persist_config(config, config_path)
inputs = build_config_inputs(config, config_box, on_config_change) + [update_data_dir_button, data_dir_label]
config_box.style.flex = 1
config_box_container = toga.ScrollContainer(content=config_box)
config_box_container.style.flex = 1
main_box.add(config_box_container)
status_box = toga.Box()
status_box.style.padding = 15
terminate_run = False
last_status_update = None
def run_wrapper(*args, **kwargs):
from run import run
nonlocal terminate_run, last_status_update
try:
yield sleep_duration
for status_update in run(*args, **kwargs):
if terminate_run:
break
if status_update is not None:
progressbar.value = int(progressbar.max * status_update.current_transect_idx / status_update.total_transects)
last_status_update = status_update
yield sleep_duration
if not terminate_run:
progressbar.value = progressbar.max
except Exception as e:
exception_str = exception_to_str(e)
logging.error(exception_str)
status_str = ""
if last_status_update is not None:
status_str += f" at transect '{last_status_update.current_transect_id}'"
status_str += f" and detection '{last_status_update.current_detection_id}'" if last_status_update.current_detection_id is not None else ""
app.main_window.info_dialog("Error", f"An error occured{status_str}: {str(e)}\nDetails:\n{exception_str}")
finally:
run_button.text = "Start"
enable_inputs(inputs, True)
terminate_run = False
last_status_update = None
def on_run(_):
nonlocal terminate_run
if run_button.text == "Start":
run_button.text = "Stop"
enable_inputs(inputs, False)
app.add_background_task(lambda _: run_wrapper(deepcopy(config)))
elif run_button.text == "Stop":
terminate_run = True
run_button.text = "Start"
progressbar.value = 0
enable_inputs(inputs, True)
run_button = toga.Button("Start", on_press=on_run)
progressbar_box = toga.Box()
progressbar_box.style.flex = 1
progressbar_box.style.direction = "row"
progressbar_box.style.alignment = "center"
progressbar = toga.ProgressBar(max=int(1e6))
progressbar.style.flex = 1
progressbar.style.padding_left = 15
progressbar_box.add(progressbar)
status_box.add(run_button)
status_box.add(progressbar_box)
main_box.add(status_box)
return main_box
def cli(args):
from run import run
args = {k: v for k, v in args.__dict__.items() if not k.startswith("_") and k != "cli"}
config = Config(**args)
last_total = None
last_idx = 0
with tqdm() as progressbar:
for status_update in run(config):
if status_update is not None:
if last_total != status_update.total_transects:
last_total = status_update.total_transects
progressbar.reset(status_update.total_transects)
progressbar.update(status_update.current_transect_idx - last_idx)
last_idx = status_update.current_transect_idx
if last_total is not None:
progressbar.update(last_total - last_idx)
def main():
try:
# Close the splash screen.
import pyi_splash
pyi_splash.close()
except ImportError:
# Otherwise do nothing.
pass
argparser = ArgumentParser()
argparser.add_argument("--cli", action="store_true", help="Enables CLI operation and disables GUI")
default_config = Config()
for var in dir(Config):
value_type = type(getattr(default_config, var))
default_value = getattr(default_config, var)
if var.startswith("_"):
continue
if issubclass(value_type, Enum):
argparser.add_argument(f"--{var}", type=value_type, default=default_value, action=EnumActionLowerCase)
elif value_type is bool:
if default_value is True:
argparser.add_argument(f"--no_{var}", dest=var, action="store_false")
else:
argparser.add_argument(f"--{var}", dest=var, action="store_true")
else:
argparser.add_argument(f"--{var}", type=value_type, default=default_value)
args = argparser.parse_args()
if args.cli:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.StreamHandler()
]
)
cli(args)
else:
# workaround for sys.stdout and sys.stderr being None on Windows without attached console.
# see https://pyinstaller.org/en/v6.10.0/common-issues-and-pitfalls.html#sys-stdin-sys-stdout-and-sys-stderr-in-noconsole-windowed-applications-windows-only
if sys.stdout is None:
sys.stdout = open(os.devnull, "w")
if sys.stderr is None:
sys.stderr = open(os.devnull, "w")
if is_standalone():
icon = os.path.join(sys._MEIPASS, "assets", "icon.png")
else:
icon = os.path.join("assets", "icon.png")
toga.App(
"Distance Estimation",
"xyz.haucke.distance_estimation",
icon=icon,
home_page="https://timm.haucke.xyz/publications/distance-estimation-animal-abundance",
description="An application for estimating distances to animals in camera trap footage",
author="Timm Haucke",
startup=build,
).main_loop()
if __name__ == '__main__':
multiprocessing.freeze_support()
if multiprocessing.parent_process() is None:
main()