-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy path__init__.py
More file actions
executable file
·827 lines (722 loc) · 25.2 KB
/
Copy path__init__.py
File metadata and controls
executable file
·827 lines (722 loc) · 25.2 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
import os
import sys
import subprocess
def is_conda_env():
python_exec_path = sys.exec_prefix
is_conda_python = (
python_exec_path.find('conda') != -1
or python_exec_path.find('mambaforge') != -1
or python_exec_path.find('miniforge') != -1
)
if not is_conda_python:
return False
stdout = subprocess.DEVNULL
try:
args = ['conda', '-V']
is_conda_present = subprocess.check_call(
args, shell=True, stdout=stdout) == 0
return True
except Exception as err:
pass
try:
args = ['conda -V']
is_conda_present = subprocess.check_call(
args, shell=True, stdout=stdout) == 0
return True
except Exception as err:
return False
return True
def import_torch():
if is_conda_env():
return
try:
import torch
except ModuleNotFoundError:
return
import_torch()
import shutil
import importlib
import inspect
import platform
import traceback
import time
from datetime import datetime
from pprint import pprint
from functools import wraps
import pathlib
import numpy as np
from typing import Iterable
KNOWN_EXTENSIONS = (
'.tif', '.npz', '.npy', '.h5', '.json', '.csv', '.txt'
)
IMAGE_EXTENSIONS = (
'.tif', '.tiff', '.png', '.jpg', '.jpeg', '.bmp', '.gif',
)
VIDEO_EXTENSIONS = (
'.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv',
)
ACDC_IMAGE_EXTENSIONS = (
*IMAGE_EXTENSIONS, '.h5', '.npy', '.npz'
)
def _warn_ask_install_package(
commands: Iterable[str], note_txt='', caller='SpotMAX'
):
open_str = '='*100
sep_str = '-'*100
commands_txt = '\n'.join([f' {command}' for command in commands])
text = (
f'{caller} needs to run the following commands{note_txt}:\n\n'
f'{commands_txt}\n\n'
)
question = (
'How do you want to proceed?: '
'1) Run the commands now. '
'q) Quit, I will run the commands myself (1/q): '
)
print(open_str)
print(text)
message_on_exit = (
'[WARNING]: Execution aborted. Run the following commands before '
f'running spotMAX again:\n\n{commands_txt}\n'
)
msg_on_invalid = (
'$answer is not a valid answer. '
'Type "1" to run the commands now or "q" to quit.'
)
try:
while True:
answer = input(question)
if answer == 'q':
print(open_str)
exit(message_on_exit)
elif answer == '1':
break
else:
print(sep_str)
print(msg_on_invalid.replace('$answer', answer))
print(sep_str)
except Exception as err:
traceback.print_exc()
print(open_str)
print(message_on_exit)
def _run_pip_commands(commands: Iterable[str]):
import subprocess
for command in commands:
try:
subprocess.check_call([sys.executable, '-m', *command.split()])
except Exception as err:
pass
try:
import requests
except Exception as err:
import traceback
traceback.print_exc()
print('We detected a corrupted library, fixing it now...')
commands = (
'pip uninstall -y charset-normalizer',
'pip install --upgrade charset-normalizer'
)
_warn_ask_install_package(
commands, note_txt=' (fixing charset-normalizer package)',
caller='Cell-ACDC'
)
_run_pip_commands(commands)
try:
import sympy
except Exception as err:
import traceback
traceback.print_exc()
print('Since Cell-ACDC v1.7.2, the sympy library is required.')
commands = (
'pip install --upgrade sympy',
)
_warn_ask_install_package(
commands,
note_txt=' (installing sympy)',
caller='Cell-ACDC'
)
_run_pip_commands(commands)
def user_data_dir():
r"""
Get OS specific data directory path for Cell-ACDC.
Typical user data directories are:
macOS: ~/Library/Application Support/
Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined
Win 10: C:\Users\<username>\AppData\Local\
For Unix, we follow the XDG spec and support $XDG_DATA_HOME if defined.
:return: full path to the user-specific data dir
"""
# get os specific path
if sys.platform.startswith("win"):
os_path = os.getenv("LOCALAPPDATA")
elif sys.platform.startswith("darwin"):
os_path = "~/Library/Application Support"
else:
# linux
os_path = os.getenv("XDG_DATA_HOME", "~/.local/share")
os_path = os.path.expanduser(os_path)
return os.path.join(os_path, 'Cell_ACDC')
cellacdc_path = os.path.dirname(os.path.abspath(__file__))
debug_true_filepath = os.path.join(cellacdc_path, '.debug_true')
qrc_resources_path = os.path.join(cellacdc_path, 'qrc_resources.py')
qrc_resources_light_path = os.path.join(cellacdc_path, 'qrc_resources_light.py')
qrc_resources_dark_path = os.path.join(cellacdc_path, 'qrc_resources_dark.py')
old_temp_path = os.path.join(cellacdc_path, 'temp')
tooltips_rst_filepath = os.path.join(
cellacdc_path, "docs", "source", "tooltips.rst"
)
user_data_folderpath = user_data_dir()
user_profile_path_txt = os.path.join(
user_data_folderpath, 'acdc_user_profile_location.txt'
)
user_home_path = str(pathlib.Path.home())
user_profile_path = os.path.join(user_home_path, 'acdc-appdata')
if os.path.exists(user_profile_path_txt):
try:
with open(user_profile_path_txt, 'r') as txt:
user_profile_path = fr'{txt.read()}'
except Exception as e:
pass
qrc_resources_user_path = os.path.join(user_profile_path, 'qrc_resources.py')
try:
os.makedirs(user_profile_path, exist_ok=True)
except Exception as e:
print(
f'[WARNING]: User profile path was not found "{user_profile_path}". '
f'Resetting back to default path "{user_home_path}".'
)
user_profile_path = user_home_path
# print(f'User profile path: "{user_profile_path}"')
import site
sitepackages = site.getsitepackages()
site_packages = [p for p in sitepackages if p.endswith('-packages')][0]
cellacdc_path = os.path.dirname(os.path.abspath(__file__))
cellacdc_installation_path = os.path.dirname(cellacdc_path)
if cellacdc_installation_path != site_packages:
IS_CLONED = True
settings_folderpath = os.path.join(cellacdc_installation_path, '.acdc-settings')
else:
IS_CLONED = False
settings_folderpath = os.path.join(user_profile_path, '.acdc-settings')
fiji_location_filepath = os.path.join(settings_folderpath, 'fiji_location.txt')
bioio_sample_data_folderpath = os.path.join(
user_profile_path, 'acdc_dataStruct_temp'
)
def copytree(src, dst):
os.makedirs(dst, exist_ok=True)
for name in os.listdir(old_temp_path):
src_filepath = os.path.join(src, name)
dst_filepath = os.path.join(dst, name)
if os.path.isdir(src_filepath):
copytree(src_filepath, dst_filepath)
elif os.path.isfile(src_filepath):
shutil.copy2(src_filepath, dst_filepath)
if not os.path.exists(settings_folderpath):
os.makedirs(settings_folderpath, exist_ok=True)
if os.path.exists(old_temp_path):
try:
copytree(old_temp_path, settings_folderpath)
shutil.rmtree(old_temp_path)
except Exception as e:
print('*'*60)
print(
'[WARNING]: could not copy settings from previous location. '
f'Please manually copy the folder "{old_temp_path}" to "{settings_folderpath}"')
print('^'*60)
import pandas as pd
# Disable pandas 3.0 strict string dtype to maintain backward compatibility
# with code that assigns non-string values to DataFrames
if hasattr(pd.options, 'future') and hasattr(pd.options.future, 'infer_string'):
pd.options.future.infer_string = False
settings_csv_path = os.path.join(settings_folderpath, 'settings.csv')
if not os.path.exists(settings_csv_path):
df_settings = pd.DataFrame(
{'setting': [], 'value': []}).set_index('setting')
df_settings.to_csv(settings_csv_path)
# Get color scheme
if not os.path.exists(settings_csv_path):
scheme = 'light'
try:
df_settings = pd.read_csv(settings_csv_path, index_col='setting')
except Exception as err:
# Overwrite corrupted setttings file
df_settings = pd.DataFrame(
{'setting': [], 'value': []}).set_index('setting')
df_settings.to_csv(settings_csv_path)
if 'colorScheme' not in df_settings.index:
scheme = 'light'
else:
scheme = df_settings.at['colorScheme', 'value']
does_qrc_resources_exists = (
os.path.exists(qrc_resources_path)
or os.path.exists(qrc_resources_user_path)
)
def _copy_qrc_resources_file(
src_qrc_resources_scheme_path: os.PathLike,
dst_qrc_resources_path: os.PathLike,
user_dst_qrc_resources_path: os.PathLike = qrc_resources_user_path
):
try:
shutil.copyfile(src_qrc_resources_scheme_path, dst_qrc_resources_path)
return True
except Exception as err:
# Copy to user folder because copying to cell-acdc location failed
# possibly PermissionError --> return False to stop application
# and prompt the user to restart Cell-ACDC
shutil.copyfile(
src_qrc_resources_scheme_path, user_dst_qrc_resources_path
)
return False
# Set default qrc resources
if not does_qrc_resources_exists:
if scheme == 'light':
qrc_resources_scheme_path = qrc_resources_light_path
else:
qrc_resources_scheme_path = qrc_resources_dark_path
# Load default light mode
has_admin_rights = _copy_qrc_resources_file(
qrc_resources_scheme_path, qrc_resources_path
)
if not has_admin_rights:
qrc_resources_path = qrc_resources_user_path
elif os.path.exists(qrc_resources_user_path):
qrc_resources_path = qrc_resources_user_path
# Replace 'from PyQt5' with 'from qtpy' in qrc_resources.py file
try:
save_qrc = False
with open(qrc_resources_path, 'r') as qrc_py:
text = qrc_py.read()
if text.find('from PyQt5') != -1:
text = text.replace('from PyQt5', 'from qtpy')
save_qrc = True
if save_qrc:
with open(qrc_resources_path, 'w') as qrc_py:
qrc_py.write(text)
except Exception as err:
raise err
try:
# Import qrc_resources explicitly so that "from . import acdc_qrc_resources" imports
# the variable defined here. Use importlib in case qrc_resouces.py is in
# user folder
qrc_resouces_spec = importlib.util.spec_from_file_location(
'qrc_resources', qrc_resources_path
)
acdc_qrc_resources = importlib.util.module_from_spec(qrc_resouces_spec)
qrc_resouces_spec.loader.exec_module(acdc_qrc_resources)
except ModuleNotFoundError as err:
# Cellacdc in the cli might not have qtpy --> ignore error
pass
def try_input_install_package(pkg_name, install_command, question=None):
if question is None:
question = 'Do you want to install it now ([y]/n)? '
try:
answer = input(f'\n{question}')
return answer
except Exception as err:
raise ModuleNotFoundError(
f'The module "{pkg_name}" is not installed. '
f'Install it with the command `{install_command}`.'
)
try:
# Force PyQt6 if available
try:
from PyQt6 import QtCore
os.environ["QT_API"] = "pyqt6"
except Exception as e:
pass
from qtpy import QtCore
import pyqtgraph
import matplotlib
GUI_INSTALLED = True
except Exception as e:
GUI_INSTALLED = False
import pandas as pd
np.random.seed(3548784512)
pd.set_option("display.max_columns", 20)
pd.set_option("display.max_rows", 200)
pd.set_option('display.expand_frame_repr', False)
open_printl_str = '*'*100
close_printl_str = '='*100
def printl(*objects, pretty=False, is_decorator=False, idx=1, **kwargs):
timestap = datetime.now().strftime('%H:%M:%S')
currentframe = inspect.currentframe()
outerframes = inspect.getouterframes(currentframe)
idx = idx+1 if is_decorator else idx
callingframe = outerframes[idx].frame
callingframe_info = inspect.getframeinfo(callingframe)
filepath = callingframe_info.filename
fileinfo_str = (
f'File "{filepath}", line {callingframe_info.lineno} - {timestap}:'
)
if pretty:
print(open_printl_str)
print(fileinfo_str)
for o, object in enumerate(objects):
text = str(object)
pprint(text, **kwargs)
print(close_printl_str)
else:
sep = kwargs.get('sep', ', ')
text = sep.join([str(object) for object in objects])
text = f'{open_printl_str}\n{fileinfo_str}\n{text}\n{close_printl_str}'
print(text)
parent_path = os.path.dirname(cellacdc_path)
html_path = os.path.join(cellacdc_path, '_html')
models_path = os.path.join(cellacdc_path, 'models')
promptable_models_path = os.path.join(cellacdc_path, 'promptable_models')
data_path = os.path.join(parent_path, 'data')
resources_folderpath = os.path.join(cellacdc_path, 'resources')
resources_filepath = os.path.join(cellacdc_path, 'resources_light.qrc')
logs_path = os.path.join(user_profile_path, '.acdc-logs')
acdc_fiji_path = os.path.join(user_profile_path, 'acdc-fiji')
acdc_ffmpeg_path = os.path.join(user_profile_path, 'acdc-ffmpeg')
resources_path = os.path.join(cellacdc_path, 'resources_light.qrc')
models_list_file_path = os.path.join(settings_folderpath, 'custom_models_paths.ini')
promptable_models_list_file_path = os.path.join(
settings_folderpath, 'custom_promptable_models_paths.ini'
)
favourite_func_metrics_csv_path = os.path.join(
settings_folderpath, 'favourite_func_metrics.csv'
)
recentPaths_path = os.path.join(settings_folderpath, 'recentPaths.csv')
preproc_recipes_path = os.path.join(settings_folderpath, 'preprocessing_recipes')
combine_channels_recipes_path = os.path.join(settings_folderpath, 'combine_channels')
segm_recipes_path = os.path.join(settings_folderpath, 'segmentation_recipes')
user_manual_url = 'https://github.com/SchmollerLab/Cell_ACDC/blob/main/UserManual/Cell-ACDC_User_Manual.pdf'
github_home_url = 'https://github.com/SchmollerLab/Cell_ACDC'
data_structure_docs_url = 'https://cell-acdc.readthedocs.io/en/latest/data-structure.html'
moth_bud_tot_selected_columns_filepath = os.path.join(
settings_folderpath, 'mother_bud_total_columns_selection.json'
)
saved_measurements_selections_folderpath = os.path.join(
settings_folderpath, 'saved_measurements_selections'
)
# Use to get the acdc_output file name from `segm_filename` as
# `m = re.sub(segm_re_pattern, '_acdc_output', segm_filename)`
segm_re_pattern = r'_segm(?!.*_segm)'
try:
from setuptools_scm import get_version
__version__ = get_version(root='..', relative_to=__file__)
except Exception as e:
try:
from ._version import version as __version__
except ImportError:
__version__ = "not-installed"
__author__ = 'Francesco Padovani and Benedikt Mairhoermann'
cite_url = 'https://bmcbiol.biomedcentral.com/articles/10.1186/s12915-022-01372-6'
issues_url = 'https://github.com/SchmollerLab/Cell_ACDC/issues'
# Initialize variables that need to be globally accessible
base_cca_dict = {
'cell_cycle_stage': 'G1',
'generation_num': 2,
'relative_ID': -1,
'relationship': 'mother',
'emerg_frame_i': -1,
'division_frame_i': -1,
'is_history_known': False,
'corrected_on_frame_i': -1,
'will_divide': 0,
'daughter_disappears_before_division': 0,
'disappears_before_division': 0
}
cca_df_colnames = list(base_cca_dict.keys())
base_cca_tree_dict = {
'Cell_ID_tree': -1,
'generation_num_tree': 1,
'parent_ID_tree': -1,
'root_ID_tree': -1,
'sister_ID_tree': -1
}
lineage_tree_cols = list(base_cca_tree_dict.keys())
# lineage_tree_cols = [
# # 'Cell_ID_tree',
# 'generation_num_tree',
# 'parent_ID_tree',
# 'root_ID_tree',
# 'sister_ID_tree'
# ]
lineage_tree_cols_std_val = [
-1,
-1,
-1,
-1,
-1
]
default_annot_df = {
'is_cell_dead': False,
'is_cell_excluded': False,
}
base_acdc_df = {
**default_annot_df,
'was_manually_edited': 0
}
base_acdc_df_cols = list(base_acdc_df.keys())
sorted_cols = ['time_seconds', 'time_minutes', 'time_hours']
sorted_cols = [
*sorted_cols, *cca_df_colnames, *lineage_tree_cols, *base_acdc_df_cols
]
cca_df_colnames_with_tree = [*cca_df_colnames, *lineage_tree_cols]
all_non_metrics_cols = [*base_acdc_df_cols, *cca_df_colnames, *lineage_tree_cols]
is_linux = sys.platform.startswith('linux')
is_mac = sys.platform == 'darwin'
is_win = sys.platform.startswith("win")
is_win64 = (is_win and (os.environ["PROCESSOR_ARCHITECTURE"] == "AMD64"))
is_mac_arm64 = is_mac and platform.machine() == 'arm64'
if is_linux and GUI_INSTALLED:
from pathlib import Path
acdc_exec_path = shutil.which("acdc")
logo_path = os.path.join(resources_folderpath, 'logo_square_v2.png')
txt = f"""
[Desktop Entry]
Name=Cell-ACDC
Comment=Cell-Analysis of Cell Division Cycle
Exec={acdc_exec_path}
Icon=cell-acdc
Type=Application
Categories=Science;
StartupNotify=true
StartupWMClass=Cell-ACDC
"""
apps_dir = Path.home() / ".local/share/applications"
icons_dir = Path.home() / ".local/share/icons"
desktop_file = apps_dir / "cell-acdc.desktop"
if not os.path.exists(desktop_file):
apps_dir.mkdir(parents=True, exist_ok=True)
icons_dir.mkdir(parents=True, exist_ok=True)
acdc_icon_dst_path = icons_dir / "cell-acdc.png"
shutil.copy2(logo_path, str(acdc_icon_dst_path))
# Write the .desktop file
desktop_file.write_text(txt)
# Make the .desktop file executable (equivalent to chmod +x)
import stat
mode = os.stat(desktop_file).st_mode
os.chmod(
desktop_file, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
)
# 🔄 Refresh the desktop database
try:
subprocess.run(
["update-desktop-database", str(apps_dir)],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
exit(
'Cell-ACDC had to update the desktop database. '
'Please re-start the software, thanks!'
)
except FileNotFoundError:
print("⚠️ 'update-desktop-database' not found. It’s part of the 'desktop-file-utils' package.")
except subprocess.CalledProcessError as e:
print(f"⚠️ Error updating desktop database:\n{e.stderr.decode()}")
yeaz_weights_filenames = [
'unet_weights_batchsize_25_Nepochs_100_SJR0_10.hdf5',
'weights_budding_BF_multilab_0_1.hdf5'
]
yeaz_v2_weights_filenames = [
'weights_budding_BF_multilab_0_1',
'weights_budding_PhC_multilab_0_1',
'weights_fission_multilab_0_2'
]
segment_anything_weights_filenames = [
'sam_vit_h_4b8939.pth',
'sam_vit_l_0b3195.pth',
'sam_vit_b_01ec64.pth'
]
sam2_weights_filenames = [
'sam2.1_hiera_large.pt',
'sam2.1_hiera_base_plus.pt',
'sam2.1_hiera_small.pt',
'sam2.1_hiera_tiny.pt'
]
deepsea_weights_filenames = [
'segmentation.pth',
'tracker.pth'
]
yeastmate_weights_filenames = [
'yeastmate_advanced.yaml',
'yeastmate_weights.pth',
'yeastmate.yaml'
]
tapir_weights_filenames = [
'tapir_checkpoint.npy'
]
graphLayoutBkgrColor = (235, 235, 235)
darkBkgrColor = [255-v for v in graphLayoutBkgrColor]
def _critical_exception_gui(self, func_name):
from . import widgets, html_utils
result = None
traceback_str = traceback.format_exc()
if hasattr(self, 'is_error_state') and self.is_error_state:
printl(traceback_str)
return
if hasattr(self, 'logger'):
self.logger.error(traceback_str)
else:
printl(traceback_str)
try:
self.cleanUpOnError()
except Exception as e:
pass
msg = widgets.myMessageBox(wrapText=False, showCentered=False)
if hasattr(self, 'logs_path'):
msg.addShowInFileManagerButton(
self.logs_path, txt='Show log file...'
)
if not hasattr(self, 'log_path'):
log_path = 'NULL'
else:
log_path = self.log_path
self.is_error_state = True
msg.setDetailedText(traceback_str, visible=True)
href = f'<a href="{issues_url}">GitHub page</a>'
err_msg = html_utils.paragraph(f"""
Error in function <code>{func_name}</code>.<br><br>
More details below or in the terminal/console.<br><br>
You can <b>report</b> this error by opening an issue
on our {href}.<br><br>
Please <b>send the log file</b> when reporting the error, thanks!<br><br>
<b>Please restart Cell-ACDC, we apologise for any inconvenience.</b><br><br>
NOTE: the <b>log file</b> with the <b>error details</b> can be found
here:
""")
msg.critical(self, 'Critical error', err_msg, commands=(log_path,))
def exception_handler_cli(func):
@wraps(func)
def inner_function(self, *args, **kwargs):
try:
if func.__code__.co_argcount==1 and func.__defaults__ is None:
result = func(self)
elif func.__code__.co_argcount>1 and func.__defaults__ is None:
result = func(self, *args)
else:
result = func(self, *args, **kwargs)
except Exception as err:
result = None
if self.is_cli:
self.quit(error=err)
else:
raise err
return result
return inner_function
def exec_time(func):
@wraps(func)
def inner_function(self, *args, **kwargs):
t0 = time.perf_counter()
if func.__code__.co_argcount==1 and func.__defaults__ is None:
result = func(self)
elif func.__code__.co_argcount>1 and func.__defaults__ is None:
result = func(self, *args)
else:
result = func(self, *args, **kwargs)
t1 = time.perf_counter()
s = f'{func.__name__} execution time = {(t1-t0)*1000:.3f} ms'
printl(s, is_decorator=True)
return result
return inner_function
def _exception_handler_clean_progress(self):
try:
if self.progressWin is not None:
self.progressWin.workerFinished = True
self.progressWin.close()
except AttributeError:
pass
def exception_handler(func):
"""Decorator to handle class methods exceptions and show a critical error message."""
@wraps(func)
def inner_function(self, *args, **kwargs):
try:
result = func(self, *args, **kwargs)
except TypeError as e:
# Only handle the specific Qt slot error
msg = str(e)
if (
"takes 1 positional argument but 2 were given" in msg
and len(args) > 0
):
try:
# Remove only the last argument (assumed to be from Qt)
filtered_args = args[:-1]
result = func(self, *filtered_args, **kwargs)
except Exception:
_exception_handler_clean_progress(self)
result = _critical_exception_gui(self, func.__name__)
else:
_exception_handler_clean_progress(self)
result = _critical_exception_gui(self, func.__name__)
except Exception:
_exception_handler_clean_progress(self)
result = _critical_exception_gui(self, func.__name__)
return result
return inner_function
def disableWindow(func):
@wraps(func)
def inner_function(self, *args, **kwargs):
self.setDisabled(True)
try:
try:
result = func(self, *args, **kwargs)
except TypeError as e:
msg = str(e)
if (
"takes 1 positional argument but 2 were given" in msg
and len(args) > 0
):
filtered_args = args[:-1]
result = func(self, *filtered_args, **kwargs)
else:
raise e
return result
except Exception as err:
raise err
finally:
self.setDisabled(False)
self.activateWindow()
return inner_function
def ignore_exception(func):
@wraps(func)
def inner_function(self, *args, **kwargs):
try:
if func.__code__.co_argcount==1 and func.__defaults__ is None:
result = func(self)
elif func.__code__.co_argcount>1 and func.__defaults__ is None:
result = func(self, *args)
else:
result = func(self, *args, **kwargs)
except Exception as e:
pass
return result
return inner_function
error_below = f"\n{'*'*50} ERROR {'*'*50}\n"
error_close = f"\n{'^'*(len(error_below)-1)}"
error_up_str = '^'*100
error_up_str = f'\n{error_up_str}'
error_down_str = '^'*100
error_down_str = f'\n{error_down_str}'
binary_file_extensions = (
".png", ".pdf"
)
default_index_cols = (
'experiment_folderpath',
'experiment_foldername',
'Position_n',
'frame_i',
'Cell_ID'
)
single_pos_index_cols = (
'experiment_folderpath',
'Position_n'
)
valid_image_data_ends = (
'_aligned.npz',
'_aligned.h5',
'.h5',
'.tif',
'.npz',
'_symlink.ini'
)
if GUI_INSTALLED:
try:
from cellacdc.volume_renderer.canvas import VolumeRendererWindow
except ModuleNotFoundError:
pass