-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathui_utils.py
More file actions
2552 lines (2219 loc) · 106 KB
/
ui_utils.py
File metadata and controls
2552 lines (2219 loc) · 106 KB
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import os
import errno
import sys
import traceback
import yaml
import queue
import subprocess
import re
import json
import numpy as np
import certifi
import ssl
import tempfile
from pathlib import PurePath, Path, PureWindowsPath
from packaging.version import Version
from bs4 import BeautifulSoup
from urllib.request import urlopen
import collections.abc
from logging import Logger
from typing import (
Tuple,
Dict,
Optional,
List,
)
from PySide6.QtCore import QObject, QThread, Signal, QRect, Qt
from PySide6.QtWidgets import QFileDialog, QComboBox, QLineEdit, QLabel, QWidget, QFrame, QStyle
from PySide6.QtGui import QColor
import main
from biapy.biapy_config import Config
from biapy.biapy_check_configuration import (
check_configuration,
check_torchvision_available_models,
convert_old_model_cfg_to_current_version,
)
from biapy.biapy_aux_functions import (
check_bmz_model_compatibility,
check_images,
check_csv_files,
check_classification_images,
find_bmz_models,
)
def examine(_window: QWidget, save_in_obj_tag: Optional[str] = None, is_file: bool = True) -> str:
"""
Find an item in disk. Can be a file or a directory.
Parameters
----------
_window : MainWindow
Window of the application.
save_in_obj_tag : str
Name of the widget to set the item's name into.
is_file : bool, optional
Whether the item to find is a file or a directory.
"""
if not is_file:
out = QFileDialog.getExistingDirectory(_window, "Select a directory")
else:
out = QFileDialog.getOpenFileName()[0]
if out == "":
return out # If no file was selected
if save_in_obj_tag is not None:
getattr(_window.ui, save_in_obj_tag).setText(os.path.normpath(out))
return out
def wizard_path_changed(main_window: main.MainWindow, save_in_obj_tag: Optional[str] = None, is_file: bool = True):
"""
Request a path for the user and advice the user that they need to check the paths again.
Parameters
----------
main_window : MainWindow
Main window of the application.
save_in_obj_tag : str
Name of the widget to set the item's name into.
is_file : bool, optional
Whether the item to find is a file or a directory.
"""
# Reset path check
if examine(main_window, save_in_obj_tag, is_file) != "":
# Reset again colors and checks so the user must check again the folder
key = next(
iter(
main_window.cfg.settings["wizard_variable_to_map"][
"Q" + str(main_window.cfg.settings["wizard_question_index"] + 1)
]
)
)
if f"CHECKED {key}" in main_window.cfg.settings["wizard_answers"]:
main_window.cfg.settings["wizard_answers"][f"CHECKED {key}"] = -1
set_text(
main_window.ui.wizard_data_checked_label,
"<span style='color:#ff3300'><span style='font-size:16pt;'>←</span> Data not checked yet!</span>",
)
index = main_window.cfg.settings["wizard_from_question_index_to_toc"][
main_window.cfg.settings["wizard_question_index"]
]
main_window.wizard_toc_model.item(index[0]).child(index[1]).setForeground(QColor(0, 0, 0))
def check_data_from_path(main_window: main.MainWindow):
"""
Checks available model compatible with BiaPy from external sources such as BioImage Model Zoo (BMZ)
and Torchvision.
Parameters
----------
main_window : MainWindow
Main window of the application.
"""
if (
main_window.cfg.settings["wizard_question_answered_index"][main_window.cfg.settings["wizard_question_index"]]
== -1
):
main_window.dialog_exec("Please select first a folder to check", reason="error")
else:
main_window.yes_no_exec(
"This process may take a while as all images will be checked one by one. Are you sure you want to proceed?"
)
assert main_window.yes_no
if main_window.yes_no.answer:
def set_folder_checked(data_constraints, key, sample_info):
main_window.logger.info(f"Data {key} checked!")
if "data_constraints" not in main_window.cfg.settings["wizard_answers"]:
main_window.cfg.settings["wizard_answers"]["data_constraints"] = data_constraints
else:
main_window.cfg.settings["wizard_answers"]["data_constraints"] = update_dict(
main_window.cfg.settings["wizard_answers"]["data_constraints"], data_constraints
)
main_window.cfg.settings["wizard_answers"][f"CHECKED {key}"] = 1
set_text(main_window.ui.wizard_data_checked_label, "<span style='color:#04aa6d'>Data checked!</span>")
if "sample_info" not in main_window.cfg.settings["wizard_answers"]:
main_window.cfg.settings["wizard_answers"]["sample_info"] = {}
main_window.cfg.settings["wizard_answers"]["sample_info"][sample_info["dir_name"]] = sample_info
main_window.logger.info("Checking data from path")
dir_name = next(
iter(
main_window.cfg.settings["wizard_variable_to_map"][
"Q" + str(main_window.cfg.settings["wizard_question_index"] + 1)
]
)
)
main_window.thread_spin = QThread()
main_window.worker_spin = check_data_from_path_engine(main_window, dir_name)
main_window.worker_spin.moveToThread(main_window.thread_spin)
main_window.thread_spin.started.connect(main_window.worker_spin.run)
# Set up signals
main_window.worker_spin.state_signal.connect(main_window.loading_phase)
main_window.worker_spin.update_var_signal.connect(main_window.update_variable_in_GUI)
main_window.worker_spin.error_signal.connect(main_window.dialog_exec)
main_window.worker_spin.add_model_card_signal.connect(main_window.add_model_card)
main_window.worker_spin.report_path_check_result.connect(set_folder_checked)
main_window.worker_spin.finished_signal.connect(main_window.thread_spin.quit)
main_window.worker_spin.finished_signal.connect(main_window.worker_spin.deleteLater)
main_window.thread_spin.finished.connect(main_window.thread_spin.deleteLater)
# Start thread
main_window.thread_spin.start()
class check_data_from_path_engine(QObject):
# Signal to indicate the state of the process
state_signal = Signal(int)
# Signal to update variables in GUI
update_var_signal = Signal(str, str)
# Signal to indicate the main thread that there was an error
error_signal = Signal(str, str)
# Signal to send a message to the user about the result of model checking
add_model_card_signal = Signal(int, dict)
# Signal to send a message to the user about the result of model checking
report_path_check_result = Signal(dict, str, dict)
# Signal to indicate the main thread that the worker has finished
finished_signal = Signal()
def __init__(self, main_window, dir_name):
"""
Class to check available model compatible with BiaPy from external sources such as BioImage Model Zoo (BMZ)
and Torchvision.
Parameters
----------
main_window : MainWindow
Main window of the application.
"""
super(check_data_from_path_engine, self).__init__()
self.main_window = main_window
self.dir_name = dir_name
def run(self):
"""
Checks possible model available in BioImage Model Zoo and Torchivision for the workflow specified by Wizards form.
Parameters
----------
main_window : MainWindow
Main window of the application.
"""
try:
self.state_signal.emit(0)
folder = self.main_window.cfg.settings["wizard_question_answered_index"][
self.main_window.cfg.settings["wizard_question_index"]
]
if self.main_window.cfg.settings["wizard_answers"]["PROBLEM.TYPE"] == -1:
self.error_signal.emit(
f"You need to answer 'Workflow' question before checking the data.", "inform_user"
)
elif self.main_window.cfg.settings["wizard_answers"]["PROBLEM.NDIM"] == -1:
self.error_signal.emit(
"You need to answer 'Dimensions' question before checking the data.", "inform_user"
)
else:
workflow = self.main_window.cfg.settings["wizard_answers"]["PROBLEM.TYPE"]
ndim = self.main_window.cfg.settings["wizard_answers"]["PROBLEM.NDIM"]
key = next(
iter(
self.main_window.cfg.settings["wizard_variable_to_map"][
"Q" + str(self.main_window.cfg.settings["wizard_question_index"] + 1)
]
)
)
is_3d = ndim == "3D"
if workflow == "SEMANTIC_SEG":
mask_type = "semantic_mask" if ("GT_PATH" in key) else ""
error, error_message, data_constraints, sample_info = check_images(
folder, is_mask=("GT_PATH" in key), mask_type=mask_type, is_3d=is_3d, dir_name=self.dir_name
)
elif workflow == "INSTANCE_SEG":
mask_type = "instance_mask" if ("GT_PATH" in key) else ""
error, error_message, data_constraints, sample_info = check_images(
folder, is_mask=("GT_PATH" in key), mask_type=mask_type, is_3d=is_3d, dir_name=self.dir_name
)
elif workflow == "DETECTION":
if "GT_PATH" not in key:
error, error_message, data_constraints, sample_info = check_images(
folder, is_3d=is_3d, dir_name=self.dir_name
)
else:
error, error_message, data_constraints, sample_info = check_csv_files(
folder, is_3d=is_3d, dir_name=self.dir_name
)
elif workflow == "CLASSIFICATION":
error, error_message, data_constraints, sample_info = check_classification_images(
folder, is_3d=is_3d, dir_name=self.dir_name
)
elif workflow in ["DENOISING", "SUPER_RESOLUTION", "SELF_SUPERVISED", "IMAGE_TO_IMAGE"]:
error, error_message, data_constraints, sample_info = check_images(
folder, is_3d=is_3d, dir_name=self.dir_name
)
self.main_window.logger.info(f"data_constraints: {data_constraints}")
if error:
self.main_window.logger.info(f"Error: {error}")
self.main_window.logger.info(f"Message: {error_message}")
self.error_signal.emit(
f"Following error found when checking the folder: \n{error_message}", "error"
)
else:
self.report_path_check_result.emit(data_constraints, key, sample_info)
except:
exc = traceback.format_exc()
self.main_window.logger.error(exc)
self.error_signal.emit(f"Error checking the data:\n{exc}", "unexpected_error")
self.state_signal.emit(1)
self.finished_signal.emit()
self.state_signal.emit(1)
self.finished_signal.emit()
def mark_syntax_error(main_window: main.MainWindow, gui_widget_name: str, validator_type: List[str] = ["empty"]):
"""
Functionality for the advanced option button (Down/UP arrows in GUI).
Parameters
----------
main_window : MainWindow
Main window of the application.
gui_widget_name : str
Name of the button that triggers the function.
validator_type : List of str
Constraints that ``gui_widget_name`` needs to satisfy in order to not have an
error. Options avaiable: ['empty', 'exists']. 'empty' means that the value can
not be empty, i.e. '' being an string, and 'exists' means that its value
represents a path and it needs to exist.
"""
# Check constraints
error = False
for v in validator_type:
if v == "empty" and get_text(getattr(main_window.ui, gui_widget_name)) == "":
error = True
elif v == "exists" and not os.path.exists(get_text(getattr(main_window.ui, gui_widget_name))):
error = True
# Tell the user if there was an error
if error:
getattr(main_window.ui, gui_widget_name).setStyleSheet("border: 2px solid red;")
else:
getattr(main_window.ui, gui_widget_name).setStyleSheet("")
out = get_text(getattr(main_window.ui, gui_widget_name), strip=False)
if gui_widget_name == "select_yaml_name_label":
out_write = os.path.basename(out)
main_window.cfg.settings["yaml_config_filename"] = out_write
main_window.cfg.settings["yaml_config_file_path"] = os.path.dirname(out)
if get_text(main_window.ui.job_name_input) == "":
main_window.ui.job_name_input.setPlainText(os.path.splitext(out_write)[0])
elif gui_widget_name == "output_folder_input":
main_window.cfg.settings["output_folder"] = out
if gui_widget_name in ["job_name_input", "output_folder_input"]:
path = get_text(main_window.ui.output_folder_input)
if path != "":
main_window.cfg.settings["job_real_output_path"] = os.path.join(
path, get_text(main_window.ui.job_name_input)
)
m = "Job results folder: <strong>{}</strong>".format(main_window.cfg.settings["job_real_output_path"])
main_window.ui.output_final_directory_label.setText(m)
def resource_path(relative_path: str) -> str:
"""
Gets absolute path to resource. Needed for Pyinstaller so the resources are found in every OS.
Parameters
----------
relative_path : str
Relative path of an item.
Returns
-------
path : str
Absolute path of the item.
"""
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def change_page(main_window: main.MainWindow, buttonName: str, to_page: int):
"""
Move between pages.
Parameters
----------
main_window : MainWindow
Main window of the application.
buttonName : str
Name of the button that triggers the movement.
to_page : int
Number of the page moving to.
"""
for each in main_window.ui.frame_bottom_west.findChildren(QFrame):
if "biapy" not in each.objectName() or "frame_run_biapy" == each.objectName():
each.setStyleSheet("background:rgb(64,144,253)")
# Use global page_number to move as the user selected continue button
if to_page == -1:
move = True
# if page_number != 1:
# move = UIFunction.check_input(main_window, page_number)
# Do not move until the errors are corrected
if not move:
return
if buttonName == "up":
main_window.cfg.settings["page_number"] += 1
else:
main_window.cfg.settings["page_number"] -= 1
to_page = main_window.cfg.settings["page_number"]
if buttonName == "bn_home" or (buttonName == "down" and to_page == 0):
main_window.ui.stackedWidget.setCurrentWidget(main_window.ui.page_home)
main_window.ui.frame_home.setStyleSheet("background:rgb(255,255,255)")
main_window.cfg.settings["page_number"] = 0
elif buttonName == "bn_wizard" or (buttonName == "down" and to_page == 1):
main_window.ui.stackedWidget.setCurrentWidget(main_window.ui.page_wizard)
main_window.ui.frame_wizard.setStyleSheet("background:rgb(255,255,255)")
main_window.cfg.settings["page_number"] = 1
elif buttonName == "bn_run_biapy" or ("bn_" not in buttonName and to_page == 6):
main_window.ui.stackedWidget.setCurrentWidget(main_window.ui.page_run_biapy)
main_window.ui.frame_run_biapy.setStyleSheet("background:rgb(255,255,255)")
main_window.cfg.settings["page_number"] = 6
def eval_wizard_answer(main_window: main.MainWindow):
"""
Stores the answer given for the current question and mark it to advice the user.
Parameters
----------
main_window : MainWindow
Main window of the application.
"""
if not main_window.allow_change_wizard_question_answer:
return
mark_as_answered = False
# Remember current answer
if main_window.ui.wizard_question_answer_frame.isVisible():
changed_answer = False
if main_window.ui.wizard_question_answer.currentIndex() != -1:
mark_as_answered = True
if (
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
]
!= main_window.ui.wizard_question_answer.currentIndex()
):
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
] = main_window.ui.wizard_question_answer.currentIndex()
changed_answer = True
for key, values in main_window.cfg.settings["wizard_variable_to_map"][
"Q" + str(main_window.cfg.settings["wizard_question_index"] + 1)
].items():
main_window.cfg.settings["wizard_answers"][key] = values[
main_window.ui.wizard_question_answer.currentIndex()
]
elif main_window.ui.wizard_path_input_frame.isVisible():
te = get_text(main_window.ui.wizard_path_input)
if te != "":
key = next(
iter(
main_window.cfg.settings["wizard_variable_to_map"][
"Q" + str(main_window.cfg.settings["wizard_question_index"] + 1)
]
)
)
main_window.cfg.settings["wizard_answers"][key] = te
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
] = te
set_text(main_window.ui.wizard_path_input, te)
# Check if the data was checked
if main_window.cfg.settings["wizard_answers"][f"CHECKED {key}"] == -1:
mark_as_answered = False
else:
mark_as_answered = True
elif main_window.ui.wizard_model_input_frame.isVisible():
te = get_text(main_window.ui.wizard_model_input)
if te != "":
key = next(
iter(
main_window.cfg.settings["wizard_variable_to_map"][
"Q" + str(main_window.cfg.settings["wizard_question_index"] + 1)
]
)
)
if key == "MODEL.BMZ.SOURCE_MODEL_ID":
te = te.replace(" (BioImage Model Zoo)", "")
elif key == "MODEL.TORCHVISION.SOURCE_MODEL_ID":
te = te.replace(" (Torchvision)", "")
main_window.cfg.settings["wizard_answers"][key] = te
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
] = te
set_text(main_window.ui.wizard_model_input, te)
mark_as_answered = True
if mark_as_answered:
# Mark section as answered in TOC
index = main_window.cfg.settings["wizard_from_question_index_to_toc"][
main_window.cfg.settings["wizard_question_index"]
]
main_window.wizard_toc_model.item(index[0]).child(index[1]).setForeground(QColor(64, 144, 253))
# Check the questions that need to hide/appear
for question in main_window.cfg.settings["wizard_question_condition"]:
make_visible = True
set_default_value = True
# AND conditions
if len(main_window.cfg.settings["wizard_question_condition"][question]["and_cond"]) > 0:
for cond in main_window.cfg.settings["wizard_question_condition"][question]["and_cond"]:
if main_window.cfg.settings["wizard_answers"][cond[0]] != -1:
set_default_value = False
if main_window.cfg.settings["wizard_answers"][cond[0]] != cond[1]:
make_visible = False
break
else:
make_visible = False
break
if make_visible:
# OR conditions
if len(main_window.cfg.settings["wizard_question_condition"][question]["or_cond"]) > 0:
for cond in main_window.cfg.settings["wizard_question_condition"][question]["or_cond"]:
if main_window.cfg.settings["wizard_answers"][cond[0]] != -1:
set_default_value = False
if main_window.cfg.settings["wizard_answers"][cond[0]] not in cond[1]:
make_visible = False
break
else:
make_visible = False
break
if not set_default_value:
question_number = int(question.replace("Q", "")) - 1
if make_visible:
if not main_window.cfg.settings["wizard_question_visible"][question_number]:
main_window.cfg.settings["wizard_question_visible"][question_number] = True
index_in_toc = main_window.cfg.settings["wizard_from_question_index_to_toc"][question_number]
main_window.ui.wizard_treeView.setRowHidden(
index_in_toc[1], main_window.wizard_toc_model.index(index_in_toc[0], 0), False
)
else:
if main_window.cfg.settings["wizard_question_visible"][question_number]:
main_window.cfg.settings["wizard_question_visible"][question_number] = False
index_in_toc = main_window.cfg.settings["wizard_from_question_index_to_toc"][question_number]
main_window.ui.wizard_treeView.setRowHidden(
index_in_toc[1], main_window.wizard_toc_model.index(index_in_toc[0], 0), True
)
# Reset data checks if dimensionality or workflow changed, as the data check is different
if main_window.ui.wizard_question_answer_frame.isVisible() and changed_answer:
main_window.pretrained_model_need_to_check = None
key = next(
iter(
main_window.cfg.settings["wizard_variable_to_map"][
"Q" + str(main_window.cfg.settings["wizard_question_index"] + 1)
]
)
)
if "PROBLEM.NDIM" == key or "PROBLEM.TYPE" == key:
for key, val in main_window.cfg.settings["wizard_answers"].items():
if "CHECKED" in key:
main_window.cfg.settings["wizard_answers"][key] = -1
for i in range(main_window.cfg.settings["wizard_number_of_questions"]):
if main_window.cfg.settings["wizard_possible_answers"][i][0] == "PATH":
index = main_window.cfg.settings["wizard_from_question_index_to_toc"][i]
main_window.wizard_toc_model.item(index[0]).child(index[1]).setForeground(QColor(0, 0, 0))
elif main_window.cfg.settings["wizard_possible_answers"][i][0] in ["MODEL_BIAPY", "MODEL_OTHERS"]:
index = main_window.cfg.settings["wizard_from_question_index_to_toc"][i]
main_window.wizard_toc_model.item(index[0]).child(index[1]).setForeground(QColor(0, 0, 0))
main_window.cfg.settings["wizard_question_answered_index"][i] = -1
def change_wizard_page(main_window: main.MainWindow, val: int, based_on_toc: bool = False, added_val=0):
"""
Changes wizard page.
Parameters
----------
main_window : MainWindow
Main window of the application.
val : int
Number of question to move to. If ``based_on_toc`` is provided it needs to be calculated internally.
based_on_toc : bool, optional
If the call was triggered from QTreeView that represents the TOC. It advices the function that needs to
recalculated ``val`` value according to the selected index in TOC.
added_val : bool, optional
The value to be added to ``val`` in order to calculate where to continue: next or previous question.
"""
if based_on_toc:
if main_window.not_allow_change_question:
return
index = main_window.ui.wizard_treeView.selectionModel().selectedIndexes()
if len(index) == 0:
return
if len(index) > 1:
raise ValueError(f"Found internal error in indexes: {index}. Contact BiaPy team!")
index = index[0]
if index.parent().row() != -1:
val = main_window.cfg.settings["wizard_from_toc_to_question_index"][index.parent().row()][index.row()]
eval_wizard_answer(main_window)
# Calculate valid next/previous question
if not based_on_toc:
if added_val > 0:
val += 1
for i in range(val, len(main_window.cfg.settings["wizard_question_visible"])):
if main_window.cfg.settings["wizard_question_visible"][i]:
val = i
break
if added_val < 0:
val -= 1
for i in range(val, 0, -1):
if main_window.cfg.settings["wizard_question_visible"][i]:
val = i
break
# Go to the first view of the wizard
last_shown = (
len(main_window.cfg.settings["wizard_question_visible"])
- main_window.cfg.settings["wizard_question_visible"][::-1].index(True)
- 1
)
if val == -1 and main_window.cfg.settings["wizard_question_index"] == 0:
main_window.ui.wizard_main_frame.setCurrentWidget(main_window.ui.wizard_start_page)
elif val == last_shown + 1:
main_window.ui.wizard_main_frame.setCurrentWidget(main_window.ui.summary_page)
# Only visualice those questions that were answered and visible
for i in range(len(main_window.cfg.settings["wizard_questions"])):
if (
main_window.cfg.settings["wizard_question_visible"][i]
and main_window.cfg.settings["wizard_question_answered_index"][i] != -1
):
main_window.question_cards[i][f"summary_question_frame_{i}"].setVisible(True)
set_text(
main_window.question_cards[i][f"summary_question_text{i}"],
main_window.cfg.settings["wizard_questions"][i],
)
if isinstance(main_window.cfg.settings["wizard_question_answered_index"][i], str):
set_text(
main_window.question_cards[i][f"summary_question_text_answer_{i}"],
main_window.cfg.settings["wizard_question_answered_index"][i],
)
else:
set_text(
main_window.question_cards[i][f"summary_question_text_answer_{i}"],
str(
main_window.cfg.settings["wizard_possible_answers"][i][
main_window.cfg.settings["wizard_question_answered_index"][i]
]
),
)
else:
main_window.question_cards[i][f"summary_question_frame_{i}"].setVisible(False)
# Visualice the yaml_file name
set_text(
main_window.ui.wizard_config_file_label,
os.path.join(
get_text(main_window.ui.wizard_browse_yaml_path_input), get_text(main_window.ui.wizard_yaml_name_input)
),
)
else:
main_window.ui.wizard_main_frame.setCurrentWidget(main_window.ui.questionary_page)
main_window.cfg.settings["wizard_question_index"] = val
main_window.cfg.settings["wizard_question_index"] = max(0, main_window.cfg.settings["wizard_question_index"])
main_window.cfg.settings["wizard_question_index"] = min(
len(main_window.cfg.settings["wizard_from_question_index_to_toc"]) - 1,
main_window.cfg.settings["wizard_question_index"],
)
prepare_question(main_window)
# Change TOC index
if not based_on_toc:
index_in_toc = main_window.cfg.settings["wizard_from_question_index_to_toc"][
main_window.cfg.settings["wizard_question_index"]
]
index = main_window.wizard_toc_model.item(index_in_toc[0]).child(index_in_toc[1])
if index is not None:
# As wizard_treeView is triggered when changing it's index we use this flag to block change_wizard_page functionality,
# as it has been done already
main_window.not_allow_change_question = True
main_window.ui.wizard_treeView.setCurrentIndex(index.index())
# Activate again possible triggers of wizard_treeView
main_window.not_allow_change_question = False
def prepare_question(main_window: main.MainWindow):
"""
Prepare current question.
"""
# Change question
set_text(
main_window.ui.wizard_question,
main_window.cfg.settings["wizard_questions"][main_window.cfg.settings["wizard_question_index"]],
)
set_text(
main_window.ui.wizard_question_label,
"Question {}".format(main_window.cfg.settings["wizard_question_index"] + 1),
)
# Set bottom part of the question. Depeding on the question type different things must be done
if (
main_window.cfg.settings["wizard_possible_answers"][main_window.cfg.settings["wizard_question_index"]][0]
== "PATH"
):
main_window.ui.wizard_path_input_frame.setVisible(True)
main_window.ui.wizard_question_answer_frame.setVisible(False)
main_window.ui.wizard_model_input_frame.setVisible(False)
# Remember the answer if the question was previously answered
if (
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
]
!= -1
):
set_text(
main_window.ui.wizard_path_input,
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
],
)
key = next(
iter(
main_window.cfg.settings["wizard_variable_to_map"][
"Q" + str(main_window.cfg.settings["wizard_question_index"] + 1)
]
)
)
if main_window.cfg.settings["wizard_answers"][f"CHECKED {key}"] == -1:
set_text(
main_window.ui.wizard_data_checked_label,
"<span style='color:#ff3300'><span style='font-size:16pt;'>←</span> Data not checked yet!</span>",
)
else:
set_text(main_window.ui.wizard_data_checked_label, "<span style='color:#04aa6d'>Data checked!</span>")
else:
set_text(main_window.ui.wizard_path_input, "")
set_text(
main_window.ui.wizard_data_checked_label,
"<span style='color:#ff3300'><span style='font-size:16pt;'>←</span> Data not checked yet!</span>",
)
elif main_window.cfg.settings["wizard_possible_answers"][main_window.cfg.settings["wizard_question_index"]][0] in [
"MODEL_BIAPY",
"MODEL_OTHERS",
]:
main_window.ui.wizard_path_input_frame.setVisible(False)
main_window.ui.wizard_question_answer_frame.setVisible(False)
main_window.ui.wizard_model_input_frame.setVisible(True)
if (
main_window.cfg.settings["wizard_possible_answers"][main_window.cfg.settings["wizard_question_index"]][0]
== "MODEL_BIAPY"
):
main_window.ui.wizard_model_check_bn.setVisible(False)
main_window.ui.wizard_model_browse_bn.setVisible(True)
else: # "MODEL_OTHERS"
main_window.ui.wizard_model_check_bn.setVisible(True)
main_window.ui.wizard_model_browse_bn.setVisible(False)
# Remember the answer if the question was previously answered
if (
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
]
!= -1
):
set_text(
main_window.ui.wizard_model_input,
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
],
)
else:
set_text(main_window.ui.wizard_model_input, "")
else:
main_window.ui.wizard_path_input_frame.setVisible(False)
main_window.ui.wizard_question_answer_frame.setVisible(True)
main_window.ui.wizard_model_input_frame.setVisible(False)
# Prevent eval_wizard_answer functionality during wizard_question_answer's currentIndexChanged trigger. It triggers a few times
# when clearing and inserting new data
main_window.allow_change_wizard_question_answer = False
# Prepare combobox with the answers of the new question
main_window.ui.wizard_question_answer.clear()
for ans in main_window.cfg.settings["wizard_possible_answers"][
main_window.cfg.settings["wizard_question_index"]
]:
main_window.ui.wizard_question_answer.addItem(ans)
# Remember the answer if the question was previously answered
if (
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
]
!= -1
):
main_window.ui.wizard_question_answer.setCurrentIndex(
main_window.cfg.settings["wizard_question_answered_index"][
main_window.cfg.settings["wizard_question_index"]
]
)
else:
main_window.ui.wizard_question_answer.setCurrentIndex(-1)
# Enable eval_wizard_answer calls again
main_window.allow_change_wizard_question_answer = True
def clear_answers(main_window: main.MainWindow, ask_user: bool = True):
"""
Clear all answers.
Parameters
----------
main_window : MainWindow
Main window of the application.
ask_user : bool, optional
Whether to ask the user before proceed.
"""
continue_clearing = True
if ask_user:
main_window.yes_no_exec("Are you sure you want to clear all answers?")
assert main_window.yes_no
if not main_window.yes_no.answer:
continue_clearing = False
if continue_clearing:
main_window.cfg.settings["wizard_question_answered_index"] = [
-1,
] * main_window.cfg.settings["wizard_number_of_questions"]
# Reset TOC colors
for i in range(main_window.wizard_toc_model.rowCount()):
main_window.wizard_toc_model.item(i).setForeground(QColor(0, 0, 0))
for j in range(main_window.wizard_toc_model.item(i).rowCount()):
main_window.wizard_toc_model.item(i).child(j).setForeground(QColor(0, 0, 0))
# Rewrite all keys
main_window.cfg.settings["wizard_answers"] = main_window.cfg.settings["original_wizard_answers"].copy()
if main_window.ui.wizard_path_input_frame.isVisible():
set_text(main_window.ui.wizard_path_input, "")
elif main_window.ui.wizard_model_input_frame.isVisible():
set_text(main_window.ui.wizard_model_input, "")
def have_internet(main_window: main.MainWindow, timeout: int = 3) -> bool:
"""
Checks whether there is internet connection or not.
Parameters
----------
main_window : MainWindow
Main window of the application.
timeout : int, optional
Timeout seconds to wait.
"""
try:
urlopen("https://biapyx.github.io", timeout=timeout, context=ssl.create_default_context(cafile=certifi.where()))
return True
except Exception:
exc = traceback.format_exc()
main_window.logger.error(exc)
return False
def check_models_from_other_sources(main_window: main.MainWindow):
"""
Check available model compatible with BiaPy from external sources such as BioImage Model Zoo (BMZ)
and Torchvision.
Parameters
----------
main_window : MainWindow
Main window of the application.
"""
if main_window.pretrained_model_need_to_check is not None:
main_window.external_model_list_built(main_window.pretrained_model_need_to_check)
return
if not have_internet(main_window):
main_window.dialog_exec("There is no internet connection. Check aborted!", reason="error")
return
main_window.thread_spin = QThread()
main_window.worker_spin = check_models_from_other_sources_engine(main_window)
main_window.worker_spin.moveToThread(main_window.thread_spin)
main_window.thread_spin.started.connect(main_window.worker_spin.run)
# Set up signals
main_window.worker_spin.state_signal.connect(main_window.loading_phase)
main_window.worker_spin.update_var_signal.connect(main_window.update_variable_in_GUI)
main_window.worker_spin.error_signal.connect(main_window.dialog_exec)
main_window.worker_spin.add_model_card_signal.connect(main_window.add_model_card)
main_window.worker_spin.report_yaml_model_check_result.connect(main_window.external_model_list_built)
main_window.worker_spin.finished_signal.connect(main_window.thread_spin.quit)
main_window.worker_spin.finished_signal.connect(main_window.worker_spin.deleteLater)
main_window.thread_spin.finished.connect(main_window.thread_spin.deleteLater)
# Start thread
main_window.thread_spin.start()
class check_models_from_other_sources_engine(QObject):
# Signal to indicate the state of the process
state_signal = Signal(int)
# Signal to update variables in GUI
update_var_signal = Signal(str, str)
# Signal to indicate the main thread that there was an error
error_signal = Signal(str, str)
# Signal to send a message to the user about the result of model checking
add_model_card_signal = Signal(int, dict)
# Signal to send a message to the user about the result of model checking
report_yaml_model_check_result = Signal(int)
# Signal to indicate the main thread that the worker has finished
finished_signal = Signal()
def __init__(self, main_window):
"""
Class to check available model compatible with BiaPy from external sources such as BioImage Model Zoo (BMZ)
and Torchvision.
Parameters
----------
main_window : MainWindow
Main window of the application.
"""
super(check_models_from_other_sources_engine, self).__init__()
self.main_window = main_window
# self.COLLECTION_URL = "https://raw.githubusercontent.com/bioimage-io/collection-bioimage-io/gh-pages/collection.json"
self.COLLECTION_URL = "https://uk1s3.embassy.ebi.ac.uk/public-datasets/bioimage.io/collection.json"
def run(self):
"""
Checks possible model available in BioImage Model Zoo and Torchivision for the workflow specified by Wizards form.
"""
## Functionality copied from BiaPy commit: 0ed2222869300316839af7202ce1d55761c6eb88 (3.5.1) - (check_bmz_args function)
self.state_signal.emit(0)
model_name = ""
problem_type = self.main_window.cfg.settings["wizard_answers"]["PROBLEM.TYPE"]
problem_ndim = self.main_window.cfg.settings["wizard_answers"]["PROBLEM.NDIM"]
workflow_specs = {}
workflow_specs["workflow_type"] = problem_type
workflow_specs["ndim"] = problem_ndim
workflow_specs["nclasses"] = "all"
try:
# Check the models that BiaPy can consume
models = find_bmz_models()
# Check each model compatibility
model_count = 0
for model in models:
nickname = "Nick not found"
if 'nickname' in model:
nickname = model['nickname']
elif 'alias' in model:
nickname = model['alias']
self.main_window.logger.info("Checking entry: {}".format(nickname))
try:
(
_,
error,
error_message,
biapy_imposed_vars
) = check_bmz_model_compatibility(model, workflow_specs=workflow_specs)
except:
error = True
if not error:
self.main_window.logger.info("Compatible model")
nickname_icon = "Emoji not found"
if 'id_emoji' in model["raw"]["manifest"]:
nickname_icon = model["raw"]["manifest"]['id_emoji']
cover_url = "https://hypha.aicell.io/bioimage-io/artifacts/{}/files/{}".format(nickname, model["raw"]["manifest"]['covers'][0])
model_info = {
"name": model_name,
"source": "BioImage Model Zoo",
"description": model["raw"]["manifest"]['description'],