Skip to content

Commit a11945f

Browse files
committed
Log more messages to catch better possible errors
1 parent 5e418b7 commit a11945f

File tree

6 files changed

+69
-58
lines changed

6 files changed

+69
-58
lines changed

biapy_check_configuration.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import requests
66
from pathlib import Path
77

8-
def check_configuration(cfg, jobname, check_data_paths=True):
8+
def check_configuration(cfg, jobname, check_data_paths=True, logger=None):
99
"""
1010
Check if the configuration is good.
1111
"""
@@ -156,7 +156,8 @@ def check_configuration(cfg, jobname, check_data_paths=True):
156156
"PROBLEM.TYPE not in ['SEMANTIC_SEG', 'INSTANCE_SEG', 'CLASSIFICATION', 'DETECTION', 'DENOISING', 'SUPER_RESOLUTION', 'SELF_SUPERVISED', 'IMAGE_TO_IMAGE']"
157157

158158
if cfg.PROBLEM.NDIM == '3D' and cfg.TEST.FULL_IMG:
159-
print("WARNING: TEST.FULL_IMG == True while using PROBLEM.NDIM == '3D'. As 3D images are usually 'huge'"
159+
if logger is not None:
160+
logger.warning("TEST.FULL_IMG == True while using PROBLEM.NDIM == '3D'. As 3D images are usually 'huge'"
160161
", full image statistics will be disabled to avoid GPU memory overflow")
161162

162163
if cfg.LOSS.TYPE != "CE" and cfg.PROBLEM.TYPE not in ['SEMANTIC_SEG', 'DETECTION']:
@@ -178,15 +179,17 @@ def check_configuration(cfg, jobname, check_data_paths=True):
178179
url = 'http://www.doi.org/'+cfg.MODEL.BMZ.SOURCE_MODEL_DOI
179180
r = requests.get(url, stream=True, verify=True)
180181
if r.status_code >= 200 and r.status_code < 400:
181-
print(f'BMZ model DOI: {cfg.MODEL.BMZ.SOURCE_MODEL_DOI} found')
182+
if logger is not None:
183+
logger.info(f'BMZ model DOI: {cfg.MODEL.BMZ.SOURCE_MODEL_DOI} found')
182184
else:
183185
raise ValueError(f'BMZ model DOI: {cfg.MODEL.BMZ.SOURCE_MODEL_DOI} not found. Aborting!')
184186

185187
elif cfg.MODEL.SOURCE == "torchvision":
186188
if cfg.MODEL.TORCHVISION_MODEL_NAME == "":
187189
raise ValueError("'MODEL.TORCHVISION_MODEL_NAME' needs to be configured when 'MODEL.SOURCE' is 'torchvision'")
188190
if cfg.TEST.AUGMENTATION:
189-
print("WARNING: 'TEST.AUGMENTATION' is not available using TorchVision models")
191+
if logger is not None:
192+
logger.info("WARNING: 'TEST.AUGMENTATION' is not available using TorchVision models")
190193

191194
if cfg.TEST.AUGMENTATION and cfg.TEST.REDUCE_MEMORY:
192195
raise ValueError("'TEST.AUGMENTATION' and 'TEST.REDUCE_MEMORY' are incompatible as the function used to make the rotation "
@@ -406,7 +409,8 @@ def check_configuration(cfg, jobname, check_data_paths=True):
406409
raise ValueError('To use preprocessing DATA.TRAIN.IN_MEMORY needs to be True.')
407410
if not cfg.DATA.VAL.IN_MEMORY and cfg.DATA.PREPROCESS.VAL:
408411
if cfg.DATA.VAL.FROM_TRAIN:
409-
print("WARNING: validation preprocessing will be done based on 'DATA.PREPROCESS.TRAIN', as 'DATA.VAL.FROM_TRAIN' is selected")
412+
if logger is not None:
413+
logger.info("WARNING: validation preprocessing will be done based on 'DATA.PREPROCESS.TRAIN', as 'DATA.VAL.FROM_TRAIN' is selected")
410414
else:
411415
raise ValueError('To use preprocessing DATA.VAL.IN_MEMORY needs to be True.')
412416
if not cfg.DATA.TEST.IN_MEMORY and cfg.DATA.PREPROCESS.TEST:
@@ -525,11 +529,13 @@ def check_configuration(cfg, jobname, check_data_paths=True):
525529
if cfg.DATA.VAL.CROSS_VAL_NFOLD < cfg.DATA.VAL.CROSS_VAL_FOLD:
526530
raise ValueError("'DATA.VAL.CROSS_VAL_NFOLD' can not be less than 'DATA.VAL.CROSS_VAL_FOLD'")
527531
if not cfg.DATA.VAL.IN_MEMORY:
528-
print("WARNING: ignoring 'DATA.VAL.IN_MEMORY' as it is always True when 'DATA.VAL.CROSS_VAL' is enabled")
532+
if logger is not None:
533+
logger.info("WARNING: ignoring 'DATA.VAL.IN_MEMORY' as it is always True when 'DATA.VAL.CROSS_VAL' is enabled")
529534
if cfg.DATA.TEST.USE_VAL_AS_TEST and not cfg.DATA.VAL.CROSS_VAL:
530535
raise ValueError("'DATA.TEST.USE_VAL_AS_TEST' can only be used when 'DATA.VAL.CROSS_VAL' is selected")
531536
if cfg.DATA.TEST.USE_VAL_AS_TEST and not cfg.TRAIN.ENABLE and cfg.DATA.TEST.IN_MEMORY:
532-
print("WARNING: 'DATA.TEST.IN_MEMORY' is disabled when 'DATA.TEST.USE_VAL_AS_TEST' is enabled")
537+
if logger is not None:
538+
logger.warning("'DATA.TEST.IN_MEMORY' is disabled when 'DATA.TEST.USE_VAL_AS_TEST' is enabled")
533539
if len(cfg.DATA.TRAIN.RESOLUTION) != 1 and len(cfg.DATA.TRAIN.RESOLUTION) != dim_count:
534540
raise ValueError("When PROBLEM.NDIM == {} DATA.TRAIN.RESOLUTION tuple must be length {}, given {}."
535541
.format(cfg.PROBLEM.NDIM, dim_count, cfg.DATA.TRAIN.RESOLUTION))
@@ -588,7 +594,8 @@ def check_configuration(cfg, jobname, check_data_paths=True):
588594
if cfg.DATA.TRAIN.REPLICATE:
589595
if cfg.PROBLEM.TYPE == 'CLASSIFICATION' or \
590596
(cfg.PROBLEM.TYPE == 'SELF_SUPERVISED' and cfg.PROBLEM.SELF_SUPERVISED.PRETEXT_TASK == "masking"):
591-
print("WARNING: 'DATA.TRAIN.REPLICATE' has no effect in the selected workflow")
597+
if logger is not None:
598+
logger.warning("'DATA.TRAIN.REPLICATE' has no effect in the selected workflow")
592599

593600
### Model ###
594601
if cfg.MODEL.SOURCE == "biapy":

main.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,23 +21,23 @@
2121
os.environ['QT_MAC_WANTS_LAYER'] = '1'
2222

2323
class MainWindow(QMainWindow):
24-
def __init__(self, log_file, log_dir):
24+
def __init__(self, logger, log_dir):
2525
"""
2626
Main window constructor.
2727
2828
Parameters
2929
----------
30-
log_file : str
31-
File to log the output.
32-
30+
logger : str
31+
Logger to log the file to log all the information.
32+
3333
log_dir : str
3434
Logging directory for the current BiaPy GUI execution.
3535
"""
3636
super(MainWindow, self).__init__()
3737
self.ui = Ui_MainWindow()
3838
self.ui.setupUi(self)
3939

40-
self.log_file = log_file
40+
self.logger = logger
4141
self.log_dir = log_dir
4242
self.cfg = Settings()
4343

@@ -839,7 +839,7 @@ def closeEvent(self, event):
839839
if self.yes_no.answer:
840840
# Kill all run windows
841841
for x in self.cfg.settings['running_workers']:
842-
print("Killing subprocess . . .")
842+
self.logger.info("Killing subprocess . . .")
843843
x.gui.forcing_close = True
844844
x.gui.close()
845845

@@ -848,7 +848,7 @@ def closeEvent(self, event):
848848
try:
849849
self.thread_spin.quit()
850850
except Exception as e:
851-
print(f"Possible expected error during thread_spin deletion: {e}")
851+
self.logger.error(f"Possible expected error during thread_spin deletion: {e}")
852852
# Finally close the main window
853853
self.close()
854854
else:
@@ -857,9 +857,9 @@ def closeEvent(self, event):
857857
def check_new_gui_version(self):
858858
# Changed version
859859
sha, vtag = get_git_revision_short_hash(self)
860-
print(f"Local GUI version: {self.cfg.settings['biapy_gui_version']}")
861-
print(f"Remote last version's hash: {sha}")
862-
print(f"Remote last version: {vtag}")
860+
self.logger.info(f"Local GUI version: {self.cfg.settings['biapy_gui_version']}")
861+
self.logger.info(f"Remote last version's hash: {sha}")
862+
self.logger.info(f"Remote last version: {vtag}")
863863
if sha is not None and vtag is not None and vtag != self.cfg.settings['biapy_gui_version']:
864864
self.dialog_exec("There is a new version of BiaPy's graphical user interface available. Please, "
865865
"download it <a href='https://biapyx.github.io'>here</a>", reason="inform_user")
@@ -878,10 +878,12 @@ def center_window(widget, geometry):
878878
if __name__ == "__main__":
879879
window = None
880880
log_dir = os.path.join(tempfile._get_default_tempdir(), "BiaPy")
881-
log_file = os.path.join(log_dir, "BiaPy_"+next(tempfile._get_candidate_names()))
881+
random_str = next(tempfile._get_candidate_names())
882+
log_file = os.path.join(log_dir, f"BiaPy_{random_str}")
882883
os.makedirs(log_dir, exist_ok=True)
883-
logger = logging.getLogger('BiaPy')
884-
logging.basicConfig(filename=log_file, level=logging.ERROR)
884+
logging.basicConfig(filename=log_file, format='%(asctime)s %(message)s', filemode='w')
885+
logger = logging.getLogger()
886+
logger.setLevel(logging.DEBUG)
885887
StyleSheet = """
886888
QComboBox {
887889
selection-background-color: rgb(64,144,253);
@@ -906,7 +908,7 @@ def eventFilter(self, obj, ev):
906908
filter = WheelEventFilter()
907909
app.installEventFilter(filter)
908910

909-
window = MainWindow(log_file, log_dir)
911+
window = MainWindow(logger, log_dir)
910912
window.show()
911913

912914
# Center the main GUI in the middle of the first screen
@@ -918,7 +920,7 @@ def eventFilter(self, obj, ev):
918920

919921
def excepthook(exc_type, exc_value, exc_tb):
920922
tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
921-
print("error message:\n", tb)
923+
logger.info("error message:\n", tb)
922924
tb += f"\nYou can also provide the log error here: \n{log_file}\n"
923925
tb += "\nExiting BiaPy as its functionality may be damaged!\n"
924926

run_functions.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def kill_all_processes(self):
7979
try:
8080
self.parent_worker.finished_signal.emit()
8181
except Exception as e:
82-
print(f"Possible expected error during BiaPy's running thread deletion: {e}")
82+
self.parent_worker.main_gui.logger.error(f"Possible expected error during BiaPy's running thread deletion: {e}")
8383
self.close()
8484

8585
def init_log(self, container_info):
@@ -93,7 +93,7 @@ def update_gui(self, signal):
9393
elif signal == 1:
9494
self.update_log()
9595
else:
96-
print("Nothing")
96+
self.parent_worker.main_gui.logger.info("Nothing")
9797

9898
def update_log(self):
9999
finished_good = False
@@ -116,7 +116,7 @@ def update_cont_state(self, svalue):
116116
try:
117117
self.parent_worker.biapy_container.reload()
118118
except Exception as e:
119-
print(f"Possible expected error during container status reload(): {e}")
119+
self.parent_worker.main_gui.logger.error(f"Possible expected error during container status reload(): {e}")
120120

121121
st = self.parent_worker.biapy_container.status
122122
if st == "running":
@@ -208,13 +208,13 @@ def __init__(self, main_gui, config, container_name, worker_id, output_folder, u
208208
self.break_pulling = False
209209

210210
def stop_worker(self):
211-
print("Stopping the container . . . ")
211+
self.main_gui.logger.info("Stopping the container . . . ")
212212
if self.biapy_container is not None:
213213
self.biapy_container.stop(timeout=1)
214214
try:
215215
self.update_cont_state_signal.emit(1)
216216
except Exception as e:
217-
print(f"Possible expected error during BiaPy's running thread deletion: {e}")
217+
self.main_gui.logger.error(f"Possible expected error during BiaPy's running thread deletion: {e}")
218218
self.gui.run_window.stop_container_bn.setEnabled(False)
219219
self.gui.run_window.test_progress_label.setEnabled(False)
220220
self.gui.run_window.test_progress_bar.setEnabled(False)
@@ -223,7 +223,7 @@ def stop_worker(self):
223223
self.gui.run_window.train_progress_bar.setEnabled(False)
224224
self.gui.run_window.train_epochs_label.setEnabled(False)
225225
else:
226-
print("Container not running yet")
226+
self.main_gui.logger.info("Container not running yet")
227227
# To kill pulling process if it is running
228228
self.break_pulling = True
229229

@@ -251,7 +251,7 @@ def run(self):
251251
# Collect the output of the container and update the GUI
252252
self.total_layers = {}
253253
for item in self.docker_client.api.pull(self.main_gui.cfg.settings['biapy_container_name'], stream=True, decode=True):
254-
print(item)
254+
self.main_gui.logger.info(item)
255255
if item["status"] == 'Pulling fs layer':
256256
self.total_layers[item["id"]+"_download"] = 0
257257
self.total_layers[item["id"]+"_extract"] = 0
@@ -264,7 +264,7 @@ def run(self):
264264
self.total_layers[item["id"]+"_extract"] = 1
265265

266266
if self.break_pulling:
267-
print("Stopping pulling process . . .")
267+
self.main_gui.logger.info("Stopping pulling process . . .")
268268
return
269269
# Update GUI
270270
steps = np.sum([int(float(x)*10) for x in self.total_layers.values()])
@@ -296,7 +296,7 @@ def run(self):
296296
try:
297297
temp_cfg = yaml.safe_load(stream)
298298
except yaml.YAMLError as exc:
299-
print(exc)
299+
self.main_gui.logger.error(exc)
300300

301301
dist_backend = "gloo" if self.windows_os else "nccl"
302302
command = ["--config", "/BiaPy_files/input.yaml", "--result_dir", "{}".format(self.output_folder_in_container),
@@ -418,7 +418,7 @@ def run(self):
418418
self.test_files = len(sorted(next(os.walk(self.config['DATA']['TEST']['PATH']))[2]))
419419
self.gui.run_window.test_progress_bar.setMaximum(self.test_files)
420420

421-
print("Creating temporal input YAML file")
421+
self.main_gui.logger.info("Creating temporal input YAML file")
422422
with open(real_cfg_input, 'w') as outfile:
423423
yaml.dump(temp_cfg, outfile, default_flow_style=False)
424424

@@ -429,11 +429,11 @@ def run(self):
429429

430430
# Run container
431431
# check_command = [ "python3", "-u", "-c", "'import torch; print(torch.cuda.is_available())'"]
432-
print(f"Command: {command}")
433-
print(f"Volumes: {volumes}")
434-
print(f"GPU (IDs): {gpus}")
435-
print(f"CPUs: {cpu_count}")
436-
print(f"GUI version: {self.main_gui.cfg.settings['biapy_gui_version']}")
432+
self.main_gui.logger.info(f"Command: {command}")
433+
self.main_gui.logger.info(f"Volumes: {volumes}")
434+
self.main_gui.logger.info(f"GPU (IDs): {gpus}")
435+
self.main_gui.logger.info(f"CPUs: {cpu_count}")
436+
self.main_gui.logger.info(f"GUI version: {self.main_gui.cfg.settings['biapy_gui_version']}")
437437
nofile_limit = docker.types.Ulimit(name='nofile', soft=10000, hard=10000)
438438
self.biapy_container = self.docker_client.containers.run(
439439
self.container_name,
@@ -449,7 +449,7 @@ def run(self):
449449
cpu_count=cpu_count,
450450
)
451451
self.process_steps = "running"
452-
print("Container created!")
452+
self.main_gui.logger.info("Container created!")
453453

454454
# Set the window header
455455
self.container_info = \
@@ -497,7 +497,7 @@ def run(self):
497497
for log in self.biapy_container.logs(stream=True):
498498
l = log.decode("utf-8")
499499
try:
500-
print(l.encode("utf-8") if self.windows_os else l, end="")
500+
self.main_gui.logger.info(l.encode("utf-8") if self.windows_os else l, end="")
501501
except:
502502
pass
503503
try:
@@ -543,7 +543,7 @@ def run(self):
543543
f.close()
544544
except:
545545
# Print first the traceback (only visible through terminal)
546-
print(traceback.format_exc())
546+
self.main_gui.logger.error(traceback.format_exc())
547547

548548
# Try to log the error in the error file
549549
ferr = open(self.container_stderr_file, "w")

ui_function.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1518,7 +1518,7 @@ def run_biapy(main_window):
15181518
if len(old_biapy_images) > 0:
15191519
main_window.yes_no_exec("Seems that there is one or more old BiaPy containers. Do yo want to remove them to save disk space?")
15201520
if main_window.yes_no.answer:
1521-
print("Removing old containers")
1521+
main_window.logger.info("Removing old containers")
15221522
for i in range(len(old_biapy_images)):
15231523
main_window.docker_client.images.remove(old_biapy_images[i], force=True)
15241524

@@ -1527,7 +1527,7 @@ def run_biapy(main_window):
15271527
if dockerhub_image_tag != local_biapy_image_tag:
15281528
main_window.yes_no_exec("There is another BiaPy container. Do yo want to remove the current one to save disk space?")
15291529
if main_window.yes_no.answer:
1530-
print("Removing last valid container")
1530+
main_window.logger.info("Removing last valid container")
15311531
main_window.docker_client.images.remove(main_window.cfg.settings['biapy_container_name'], force=True)
15321532

15331533
# Firs time

0 commit comments

Comments
 (0)