-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathALI.py
1617 lines (1205 loc) · 56.7 KB
/
ALI.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
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
import os
import logging
import glob
import time
import vtk, qt, slicer
from slicer.ScriptedLoadableModule import *
from slicer.util import VTKObservationMixin
import webbrowser
import textwrap
import importlib.metadata
import platform
import slicer
from slicer.util import pip_install, pip_uninstall
from CondaSetUp import CondaSetUpCall,CondaSetUpCallWsl
import time
import threading
from multiprocessing import Process, Value
import subprocess
from CondaSetUp import CondaSetUpCall,CondaSetUpCallWsl
import time
import threading
import sys
def check_lib_installed(lib_name, required_version=None):
try:
installed_version =importlib.metadata.version(lib_name)
if required_version and installed_version != required_version:
return False
return True
except importlib.metadata.PackageNotFoundError:
return False
# import csv
def install_function():
if platform.system() == "Windows":
libs = [('itk', None), ('dicom2nifti', None), ('monai', '0.7.0')]
else :
libs = [('itk', None), ('dicom2nifti', None), ('monai', '0.7.0'),('pytorch3d', '0.6.2')]
if platform.system() == "Windows":
libs.append(('torch', None))
libs.append(('torchvision', None))
libs.append(('torchaudio', None))
else:
libs.append(('torch', None))
libs.append(('torchvision', None))
libs.append(('torchaudio', None))
libs_to_install = []
for lib, version in libs:
if not check_lib_installed(lib, version):
libs_to_install.append((lib, version))
if libs_to_install:
message = "The following libraries are not installed or need updating:\n"
message += "\n".join([f"{lib}=={version}" if version else lib for lib, version in libs_to_install])
message += "\n\nDo you want to install/update these libraries?\n Doing it could break other modules"
user_choice = slicer.util.confirmYesNoDisplay(message)
if user_choice:
for lib, version in libs_to_install:
if lib in ['torch', 'torchvision', 'torchaudio']:
extra_url = 'https://download.pytorch.org/whl/cu118' if platform.system() == "Windows" else 'https://download.pytorch.org/whl/cu113'
pip_install(f'{lib} --extra-index-url {extra_url}')
if lib=="pytorch3d":
try :
import torch
pyt_version_str = torch.__version__.split("+")[0].replace(".", "")
version_str = "".join([f"py3{sys.version_info.minor}_cu", torch.version.cuda.replace(".", ""), f"_pyt{pyt_version_str}"])
pip_install('--upgrade pip')
pip_install('fvcore==0.1.5.post20220305')
pip_install(f'--no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html')
except:
pip_install('--no-cache-dir torch==1.11.0+cu113 torchvision==0.12.0+cu113 torchaudio==0.11.0+cu113 --extra-index-url https://download.pytorch.org/whl/cu113')
pip_install('--no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/py39_cu113_pyt1110/download.html')
else:
lib_version = f'{lib}=={version}' if version else lib
pip_install(lib_version)
else :
return False
return True
#region ========== FUNCTIONS ==========
def PathFromNode(node):
storageNode=node.GetStorageNode()
if storageNode is not None:
filepath=storageNode.GetFullNameFromFileName()
else:
filepath=None
return filepath
TEST_SCAN = {
"CBCT": 'https://github.com/Maxlo24/AMASSS_CBCT/releases/download/v1.0.1/MG_test_scan.nii.gz',
"IOS" : 'https://github.com/baptistebaquero/ALIDDM/releases/tag/v1.0.4',
}
MODELS_LINK = {
"CBCT": [
'https://github.com/DCBIA-OrthoLab/SlicerAutomatedDentalTools/releases/tag/v0.1-v2.0_models',
],
"IOS" : [
'https://github.com/baptistebaquero/ALIDDM/releases/tag/v1.0.3',
],
}
GROUPS_LANDMARKS = {
'Impacted canine' : ['UR3OI','UL3OI','UR3RI','UL3RI'],
'Cranial base' : ['Ba', 'S', 'N', 'RPo', 'LPo', 'RFZyg', 'LFZyg', 'C2', 'C3', 'C4'],
'Lower' : ['RCo', 'RGo', 'Me', 'Gn', 'Pog', 'PogL', 'B', 'LGo', 'LCo', 'LR1O', 'LL6MB', 'LL6DB', 'LR6MB', 'LR6DB', 'LAF', 'LAE', 'RAF', 'RAE', 'LMCo', 'LLCo', 'RMCo', 'RLCo', 'RMeF', 'LMeF', 'RSig', 'RPRa', 'RARa', 'LSig', 'LARa', 'LPRa', 'LR7R', 'LR5R', 'LR4R', 'LR3R', 'LL3R', 'LL4R', 'LL5R', 'LL7R', 'LL7O', 'LL5O', 'LL4O', 'LL3O', 'LL2O', 'LL1O', 'LR2O', 'LR3O', 'LR4O', 'LR5O', 'LR7O', 'LL6R', 'LR6R', 'LL6O', 'LR6O', 'LR1R', 'LL1R', 'LL2R', 'LR2R'],
'Upper' : ['RInfOr', 'LInfOr', 'LMZyg', 'RPF', 'LPF', 'PNS', 'ANS', 'A', 'UR3O', 'UR1O', 'UL3O', 'UR6DB', 'UR6MB', 'UL6MB', 'UL6DB', 'IF', 'ROr', 'LOr', 'RMZyg', 'RNC', 'LNC', 'UR7O', 'UR5O', 'UR4O', 'UR2O', 'UL1O', 'UL2O', 'UL4O', 'UL5O', 'UL7O', 'UL7R', 'UL5R', 'UL4R', 'UL2R', 'UL1R', 'UR2R', 'UR4R', 'UR5R', 'UR7R', 'UR6MP', 'UL6MP', 'UL6R', 'UR6R', 'UR6O', 'UL6O', 'UL3R', 'UR3R', 'UR1R'],
}
TEETH = {
'Upper teeth' : ['UL7','UL6','UL5','UL4','UL3','UL2','UL1','UR1','UR2','UR3','UR4','UR5','UR6','UR7'],
'Lower teeth' : ['LL7','LL6','LL5','LL4','LL3','LL2','LL1','LR1','LR2','LR3','LR4','LR5','LR6','LR7'],
}
SURFACE_LANDMARKS = {
'Cervical' : ['CL','CB','R','RIP','OIP'],
'Occlusal' : ['O','DB','MB'],
}
SURFACE_NETWORK = {
'_O_' : 'Occlusal',
'_C_' : 'Cervical'
}
# "Dental" : ['LL7','LL6','LL5','LL4','LL3','LL2','LL1','LR1','LR2','LR3','LR4','LR5','LR6','LR7','UL7','UL6','UL5','UL4','UL3','UL2','UL1','UR1','UR2','UR3','UR4','UR5','UR6','UR7'] ,
# "Landmarks type" : ['CL','CB','O','DB','MB','R','RIP','OIP']
import json
class ALI(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "ALI" # TODO: make this more human readable by adding spaces
self.parent.categories = ["Automated Dental Tools"] # set categories (folders where the module shows up in the module selector)
self.parent.dependencies = ["CondaSetUp"] # TODO: add here list of module names that this module requires
self.parent.contributors = ["Maxime Gillot (UoM), Baptiste Baquero (UoM)"] # TODO: replace with "Firstname Lastname (Organization)"
# TODO: update with short description of the module and a link to online module documentation
self.parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
See more information in <a href="https://github.com/organization/projectname#ALI">module documentation</a>.
"""
# TODO: replace with organization, grant and thanks
self.parent.acknowledgementText = """
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc., Andras Lasso, PerkLab,
and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
"""
# Additional initialization step after application startup is complete
slicer.app.connect("startupCompleted()", registerSampleData)
#
# Register sample data sets in Sample Data module
#
def registerSampleData():
"""
Add data sets to Sample Data module.
"""
# It is always recommended to provide sample data for users to make it easy to try the module,
# but if no sample data is available then this method (and associated startupCompeted signal connection) can be removed.
import SampleData
iconsPath = os.path.join(os.path.dirname(__file__), 'Resources/Icons')
# To ensure that the source code repository remains small (can be downloaded and installed quickly)
# it is recommended to store data sets that are larger than a few MB in a Github release.
# ALI1
SampleData.SampleDataLogic.registerCustomSampleDataSource(
# Category and sample name displayed in Sample Data module
category='ALI',
sampleName='ALI1',
# Thumbnail should have size of approximately 260x280 pixels and stored in Resources/Icons folder.
# It can be created by Screen Capture module, "Capture all views" option enabled, "Number of images" set to "Single".
thumbnailFileName=os.path.join(iconsPath, 'ALI1.png'),
# Download URL and target file name
uris="https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/998cb522173839c78657f4bc0ea907cea09fd04e44601f17c82ea27927937b95",
fileNames='ALI1.nrrd',
# Checksum to ensure file integrity. Can be computed by this command:
# import hashlib; print(hashlib.sha256(open(filename, "rb").read()).hexdigest())
checksums = 'SHA256:998cb522173839c78657f4bc0ea907cea09fd04e44601f17c82ea27927937b95',
# This node name will be used when the data set is loaded
nodeNames='ALI1'
)
# ALI2
SampleData.SampleDataLogic.registerCustomSampleDataSource(
# Category and sample name displayed in Sample Data module
category='ALI',
sampleName='ALI2',
thumbnailFileName=os.path.join(iconsPath, 'ALI2.png'),
# Download URL and target file name
uris="https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/1a64f3f422eb3d1c9b093d1a18da354b13bcf307907c66317e2463ee530b7a97",
fileNames='ALI2.nrrd',
checksums = 'SHA256:1a64f3f422eb3d1c9b093d1a18da354b13bcf307907c66317e2463ee530b7a97',
# This node name will be used when the data set is loaded
nodeNames='ALI2'
)
class PopupWindow(qt.QWidget):
def __init__(self, start_time):
super().__init__()
self.initUI(start_time)
def initUI(self, start_time):
self.setWindowTitle('Compte à rebours')
self.timer_label = qt.QLabel('Temps écoulé: 0 secondes', self)
layout = qt.QVBoxLayout()
layout.addWidget(self.timer_label)
self.setLayout(layout)
# Mise à jour du temps toutes les secondes
self.timer = qt.QTimer(self)
self.timer.timeout.connect(lambda: self.updateTime(start_time))
self.timer.start(1000)
self.show()
def updateTime(self, start_time):
elapsed_time = int(time.time() - start_time)
self.timer_label.setText(f'Temps écoulé: {elapsed_time} secondes')
#
# ALIWidget
#
class ALIWidget(ScriptedLoadableModuleWidget, VTKObservationMixin):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent=None):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
ScriptedLoadableModuleWidget.__init__(self, parent)
VTKObservationMixin.__init__(self) # needed for parameter node observation
self.logic = None
self._parameterNode = None
self._updatingGUIFromParameterNode = False
self.CBCT_as_input = True # True : CBCT image, False : surface IOS
self.folder_as_input = False # If use a folder as input
self.MRMLNode_scan = None # MRML node of the selected scan
self.input_path = None # path to the folder containing the scans
self.model_folder = None
self.available_landmarks = [] # list of available landmarks to predict
self.output_folder = None # If save the output in a folder
self.goup_output_files = False
self.scan_count = 0 # number of scans in the input folder
self.landmark_cout = 0 # number of landmark to identify
def setup(self):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
self.conda_wsl = CondaSetUpCallWsl()
ScriptedLoadableModuleWidget.setup(self)
# Load widget from .ui file (created by Qt Designer).
# Additional widgets can be instantiated manually and added to self.layout.
uiWidget = slicer.util.loadUI(self.resourcePath('UI/ALI.ui'))
self.layout.addWidget(uiWidget)
self.ui = slicer.util.childWidgetVariables(uiWidget)
# Set scene in MRML widgets. Make sure that in Qt designer the top-level qMRMLWidget's
# "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's.
# "setMRMLScene(vtkMRMLScene*)" slot.
uiWidget.setMRMLScene(slicer.mrmlScene)
# Create logic class. Logic implements all computations that should be possible to run
# in batch mode, without a graphical user interface.
self.logic = ALILogic()
# Connections
# These connections ensure that we update parameter node when scene is closed
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.StartCloseEvent, self.onSceneStartClose)
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.EndCloseEvent, self.onSceneEndClose)
# These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene
# (in the selected parameter node).
self.lm_selection_area = qt.QWidget()
self.lm_selection_layout = qt.QHBoxLayout(self.lm_selection_area)
self.ui.OptionVLayout.addWidget(self.lm_selection_area)
self.tooth_lm = LMTab()
self.tooth_lm.Clear()
self.tooth_lm.FillTab(TEETH,True)
self.lm_selection_layout.addWidget(self.tooth_lm.widget)
self.lm_tab = LMTab()
# LM_tab_widget,LM_buttons_dic = GenLandmarkTab(Landmarks_group)
self.lm_selection_layout.addWidget(self.lm_tab.widget)
#region ===== INPUTS =====
self.ui.InputTypeComboBox.currentIndexChanged.connect(self.SwitchInputType)
self.SwitchInputType(0)
self.ui.ExtensioncomboBox.currentIndexChanged.connect(self.SwitchInputExtension)
self.SwitchInputExtension(0)
self.ui.MRMLNodeComboBox.setMRMLScene(slicer.mrmlScene)
self.ui.MRMLNodeComboBox.currentNodeChanged.connect(self.onNodeChanged)
self.MRMLNode_scan = slicer.mrmlScene.GetNodeByID(self.ui.MRMLNodeComboBox.currentNodeID)
self.ui.InputComboBox.currentIndexChanged.connect(self.SwitchInput)
self.SwitchInput(0)
self.ui.DownloadTestPushButton.connect('clicked(bool)',self.onTestDownloadButton)
self.ui.DownloadModelPushButton.connect('clicked(bool)',self.onModelDownloadButton)
#endregion
self.ui.SavePredictCheckBox.connect("toggled(bool)", self.UpdateSaveType)
self.ui.SearchSaveFolder.setHidden(True)
self.ui.SaveFolderLineEdit.setHidden(True)
self.ui.PredictFolderLabel.setHidden(True)
# Buttons
self.ui.SearchScanFolder.connect('clicked(bool)',self.onSearchScanButton)
self.ui.SearchModelFolder.connect('clicked(bool)',self.onSearchModelButton)
self.ui.SearchSaveFolder.connect('clicked(bool)',self.onSearchSaveButton)
self.ui.PredictionButton.connect('clicked(bool)', self.onPredictButton)
self.ui.CancelButton.connect('clicked(bool)', self.onCancel)
self.RunningUI(False)
# Make sure parameter node is initialized (needed for module reload)
self.initializeParameterNode()
#region ===== FUNCTIONS =====
#region ===== INPUTS =====
def SwitchInputType(self,index):
self.lm_tab.Clear()
if index == 1:
self.SwitchInputExtension(0)
self.CBCT_as_input = False
self.ui.MRMLNodeComboBox.nodeTypes = ['vtkMRMLModelNode']
self.lm_tab.FillTab(SURFACE_LANDMARKS)
self.ui.ExtensionLabel.setVisible(False)
self.ui.ExtensioncomboBox.setVisible(False)
else:
self.CBCT_as_input = True
self.ui.MRMLNodeComboBox.nodeTypes = ['vtkMRMLVolumeNode']
self.lm_tab.FillTab(GROUPS_LANDMARKS)
self.ui.ExtensionLabel.setVisible(True)
self.ui.ExtensioncomboBox.setVisible(True)
self.ui.lineEditModelPath.setText("")
self.model_folder = None
self.tooth_lm.widget.setHidden(self.CBCT_as_input)
# print()
def SwitchInputExtension(self,index):
if index == 0: # NIFTI, NRRD, GIPL Files
self.SwitchInput(0)
self.isDCMInput = False
self.ui.label_11.setVisible(True)
self.ui.InputComboBox.setVisible(True)
if index == 1: # DICOM Files
self.SwitchInput(1)
self.ui.label_11.setVisible(False)
self.ui.InputComboBox.setVisible(False)
self.ui.ScanPathLabel.setText('DICOM\'s Folder')
self.isDCMInput = True
def SwitchInput(self,index):
if index == 1:
self.folder_as_input = True
self.input_path = None
else:
self.folder_as_input = False
self.onNodeChanged()
# print("Input type : ", index)
self.ui.ScanPathLabel.setVisible(self.folder_as_input)
self.ui.lineEditScanPath.setVisible(self.folder_as_input)
self.ui.SearchScanFolder.setVisible(self.folder_as_input)
self.ui.SelectNodeLabel.setVisible(not self.folder_as_input)
self.ui.MRMLNodeComboBox.setVisible(not self.folder_as_input)
self.ui.FillNodeLlabel.setVisible(not self.folder_as_input)
def onNodeChanged(self):
selected = False
self.MRMLNode_scan = slicer.mrmlScene.GetNodeByID(self.ui.MRMLNodeComboBox.currentNodeID)
if self.MRMLNode_scan is not None:
print(PathFromNode(self.MRMLNode_scan))
self.input_path = PathFromNode(self.MRMLNode_scan)
self.scan_count = 1
self.ui.PrePredInfo.setText("Number of scans to process : 1")
selected = True
return selected
def onTestDownloadButton(self):
if self.CBCT_as_input:
webbrowser.open(TEST_SCAN["CBCT"])
else:
webbrowser.open(TEST_SCAN["IOS"])
def onModelDownloadButton(self):
if self.CBCT_as_input:
for link in MODELS_LINK["CBCT"]:
webbrowser.open(link)
else:
for link in MODELS_LINK["IOS"]:
webbrowser.open(link)
def updateProgressBare(self,caller=None, event=None):
self.ui.progressBar.value = 50
# print(self.ui.horizontalSlider.value)
# print(self.ui.inputSelector.currentNode())
def UpdateSaveType(self,caller=None, event=None):
# print(caller,event)
self.ui.SearchSaveFolder.setHidden(caller)
self.ui.SaveFolderLineEdit.setHidden(caller)
self.ui.PredictFolderLabel.setHidden(caller)
if caller:
self.output_folder = None
# self.ui.SearchSaveFolder.setEnabled(not caller)
# self.ui.SaveFolderLineEdit.setEnabled(not caller)
self.save_scan_folder = caller
def CountFileWithExtention(self,path,extentions = [".nrrd", ".nrrd.gz", ".nii", ".nii.gz", ".gipl", ".gipl.gz"], exception = ["Seg", "seg", "Pred"]):
count = 0
normpath = os.path.normpath("/".join([path, '**', '']))
for img_fn in sorted(glob.iglob(normpath, recursive=True)):
# print(img_fn)
basename = os.path.basename(img_fn)
if True in [ext in basename for ext in extentions]:
if not True in [ex in basename for ex in exception]:
count += 1
return count
def onSearchScanButton(self):
scan_folder = qt.QFileDialog.getExistingDirectory(self.parent, "Select a scan folder")
if scan_folder != '':
if self.CBCT_as_input:
if self.isDCMInput:
print("DICOM")
nbr_scans = len(os.listdir(scan_folder))
else:
nbr_scans = self.CountFileWithExtention(scan_folder, [".nrrd", ".nrrd.gz", ".nii", ".nii.gz", ".gipl", ".gipl.gz"],[])
else:
nbr_scans = self.CountFileWithExtention(scan_folder, [".vtk"],[])
if nbr_scans == 0:
qt.QMessageBox.warning(self.parent, 'Warning', 'No scans found in the selected folder')
else:
self.input_path = scan_folder
self.ui.lineEditScanPath.setText(self.input_path)
self.ui.PrePredInfo.setText("Number of scans to process : " + str(nbr_scans))
self.scan_count = nbr_scans
def onSearchModelButton(self):
model_folder = qt.QFileDialog.getExistingDirectory(self.parent, "Select a model folder")
if model_folder != '':
if self.CBCT_as_input:
lm_group = GetLandmarkGroup(GROUPS_LANDMARKS)
available_lm,brain_dic = GetAvailableLm(model_folder,lm_group)
if len(available_lm.keys()) == 0:
qt.QMessageBox.warning(self.parent, 'Warning', 'No models found in the selected folder\nPlease select a folder containing .pth files\nYou can download the latest models with\n "Download latest models" button')
return
else:
self.model_folder = model_folder
self.ui.lineEditModelPath.setText(self.model_folder)
self.available_landmarks = available_lm.keys()
self.lm_tab.Clear()
self.lm_tab.FillTab(available_lm, enable = True)
# print(available_lm)
# print(brain_dic)
else:
available_lm = self.GetAvailableSurfLm(model_folder)
if len(available_lm.keys()) == 0:
qt.QMessageBox.warning(self.parent, 'Warning', 'No models found in the selected folder\nPlease select a folder containing .pth files\nYou can download the latest models with\n "Download latest models" button')
return
else:
self.model_folder = model_folder
self.ui.lineEditModelPath.setText(self.model_folder)
self.available_landmarks = available_lm.keys()
self.lm_tab.Clear()
self.lm_tab.FillTab(available_lm, enable = True)
def GetAvailableSurfLm(self,model_folder):
available_lm = {}
networks = self.GetNetworks(model_folder)
for net in networks:
available_lm[net] = SURFACE_LANDMARKS[net]
return available_lm
def GetNetworks(self,dir_path):
networks = []
normpath = os.path.normpath("/".join([dir_path, '**', '']))
for img_fn in sorted(glob.iglob(normpath, recursive=True)):
# print(img_fn)
if os.path.isfile(img_fn) and ".pth" in img_fn:
for id, group in SURFACE_NETWORK.items():
if id in os.path.basename(img_fn):
networks.append(group)
return networks
def onSearchSaveButton(self):
save_folder = qt.QFileDialog.getExistingDirectory(self.parent, "Select a scan folder")
if save_folder != '':
self.output_folder = save_folder
self.ui.SaveFolderLineEdit.setText(save_folder)
def onPredictButton(self):
if platform.system()=="Windows" and not self.CBCT_as_input :
# qt.QMessageBox.warning(self.parent, 'Warning', 'ALI_IOS is currently not available on Windows')
lib_ok = True
else :
lib_ok = install_function()
if lib_ok :
ready = True
if self.folder_as_input:
if self.input_path == None:
qt.QMessageBox.warning(self.parent, 'Warning', 'Please select a scan folder')
ready = False
else:
if not self.onNodeChanged():
qt.QMessageBox.warning(self.parent, 'Warning', 'Please select an input file')
ready = False
if self.model_folder == None:
qt.QMessageBox.warning(self.parent, 'Warning', 'Please select a model folder')
ready = False
if not ready:
return
# print("Selected landmarks : ", selected_lm_lst)
if self.output_folder == None:
if os.path.isfile(self.input_path):
outPath = os.path.dirname(self.input_path)
else:
outPath = self.input_path
else:
outPath = self.output_folder
self.output_folder = outPath
param = {}
if self.CBCT_as_input:
selected_lm_lst = self.lm_tab.GetSelected()
self.landmark_cout = len(selected_lm_lst)
if len(selected_lm_lst) == 0:
qt.QMessageBox.warning(self.parent, 'Warning', 'Please select at least one landmark')
return
selected_lm = " ".join(selected_lm_lst)
param["input"] = self.input_path
param["dir_models"] = self.model_folder
param["landmarks"] = selected_lm
self.goup_output_files = self.ui.GroupInFolderCheckBox.isChecked()
param["save_in_folder"] = self.goup_output_files
param["output_dir"] = outPath
documentsLocation = qt.QStandardPaths.DocumentsLocation
documents = qt.QStandardPaths.writableLocation(documentsLocation)
temp_dir = os.path.join(documents, slicer.app.applicationName+"_temp_ALI")
param["temp_fold"] = temp_dir
param["DCMInput"] = self.isDCMInput
else:
selected_lm_lst = self.lm_tab.GetSelected()
selected_tooth_lst = self.tooth_lm.GetSelected()
if len(selected_lm_lst) == 0:
qt.QMessageBox.warning(self.parent, 'Warning', 'Please select at least one landmark')
return
if len(selected_tooth_lst) == 0:
qt.QMessageBox.warning(self.parent, 'Warning', 'Please select at least one tooth')
return
selected_lm = " ".join(selected_lm_lst)
selected_tooth = " ".join(selected_tooth_lst)
param["input"] = self.input_path
param["dir_models"] = self.model_folder
param["landmarks"] = selected_lm
param["teeth"] = selected_tooth
self.goup_output_files = self.ui.GroupInFolderCheckBox.isChecked()
param["save_in_folder"] = self.goup_output_files
param["output_dir"] = outPath
print(param)
ready = True
system = platform.system()
if system=="Windows" and not self.CBCT_as_input :
# If on windows and running ios
self.ui.PredictionButton.setEnabled(False)
self.ui.PredScanLabel.setVisible(True)
self.ui.PredScanLabel.setText(f"Verification of WSL, this step can take few minutes")
wsl = self.conda_wsl.testWslAvailable()
if wsl : # check if wsl is available
lib = self.check_lib_wsl()
if not lib : # check if the lib required are installed
messageBox = qt.QMessageBox()
text = "Code can't be launch. \nWSL doen't have all the necessary libraries, please download the installer and follow the instructin here : https://github.com/DCBIA-OrthoLab/SlicerAutomatedDentalTools/releases/download/wsl2_windows/installer_wsl2.zip\nDownloading may be blocked by Chrome, this is normal, just authorize it."
ready = False
messageBox.information(None, "Information", text)
else :
messageBox = qt.QMessageBox()
text = "Code can't be launch. \nWSL is not installed, please download the installer and follow the instructin here : https://github.com/DCBIA-OrthoLab/SlicerAutomatedDentalTools/releases/download/wsl2_windows/installer_wsl2.zip\nDownloading may be blocked by Chrome, this is normal, just authorize it."
ready = False
messageBox.information(None, "Information", text)
if ready :
if "Error" in self.conda_wsl.condaRunCommand([self.conda_wsl.getCondaExecutable(),"--version"]): # check if miniconda is install in wsl and is setup in SlicerConda
messageBox = qt.QMessageBox()
text = "Code can't be launch. \nConda is not setup in WSL. Please go the extension CondaSetUp in SlicerConda to do it."
ready = False
messageBox.information(None, "Information", text)
if ready :
self.RunningUIWindows(True)
if not self.conda_wsl.condaTestEnv('ali_ios') : # check if the environnement exist
userResponse = slicer.util.confirmYesNoDisplay("The environnement to run the landmarks identification doesn't exist, do you want to create it ? ", windowTitle="Env doesn't exist") # ask the persimission to create it
if userResponse : #create it in parallele to not blocking slicer
process = threading.Thread(target=self.creation_env_wsl, args=())
process.start()
start_time = time.time()
previous_time = start_time
current_time = start_time
self.ui.PredScanLabel.setText(f"The environnement doesn't exist, creation of the environnement")
self.ui.TimerLabel.setText(f"time: : {current_time-start_time:.2f}s")
while process.is_alive():
slicer.app.processEvents()
current_time = time.time()
if current_time - previous_time > 0.3 :
previous_time = current_time
self.ui.TimerLabel.setText(f"time: : {current_time-start_time:.2f}s")
else :
self.ui.PredScanLabel.setText(f"The environnement doesn't exist, code can't be launch")
ready = False
if ready : # if everything is setup, launch ali_ios_wsl in parallele on the environnement in wsl. Launch in parallele to not block slicer
process = threading.Thread(target=self.process_wsl, args=(param,))
process.start()
start_time = time.time()
previous_time = start_time
current_time = start_time
self.ui.PredScanLabel.setText(f"Files in process")
self.ui.TimerLabel.setText(f"time: : {current_time-start_time:.2f}s")
while process.is_alive():
slicer.app.processEvents()
current_time = time.time()
if current_time - previous_time > 0.3 :
previous_time = current_time
self.ui.TimerLabel.setText(f"time: : {current_time-start_time:.2f}s")
else : #running ali as before without wsl
self.RunningUIWindows(False)
script_path = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_path,"tempo.txt")
with open(file_path, 'a') as file:
file.write("Beginning of the process" + '\n') # Écrire le message suivi d'une nouvelle ligne
self.logic = ALILogic()
self.logic.process(param, self.CBCT_as_input)
self.processObserver = self.logic.cliNode.AddObserver('ModifiedEvent',self.onProcessUpdate)
self.onProcessStarted()
def windows_to_linux_path(self,windows_path):
'''
convert a windows path to a wsl path
'''
windows_path = windows_path.strip()
path = windows_path.replace('\\', '/')
if ':' in path:
drive, path_without_drive = path.split(':', 1)
path = "/mnt/" + drive.lower() + path_without_drive
return path
def check_pythonpath_windows(self,name_env,file):
conda_exe = self.conda_wsl.getCondaExecutable()
command = [conda_exe, "run", "-n", name_env, "python" ,"-c", f"\"import {file} as check;import os; print(os.path.isfile(check.__file__))\""]
print("command : ",command)
result = self.conda_wsl.condaRunCommand(command)
print("result = ",result)
if "True" in result :
return True
return False
def give_pythonpath_windows(self,name_env):
paths = slicer.app.moduleManager().factoryManager().searchPaths
mnt_paths = []
for path in paths :
mnt_paths.append(f"\"{self.windows_to_linux_path(path)}\"")
pythonpath_arg = 'PYTHONPATH=' + ':'.join(mnt_paths)
conda_exe = self.conda_wsl.getCondaExecutable()
# print("Conda_exe : ",conda_exe)
argument = [conda_exe, 'env', 'config', 'vars', 'set', '-n', name_env, pythonpath_arg]
print("arguments : ",argument)
self.conda_wsl.condaRunCommand(argument)
def process_wsl(self,param):
'''
Function to launch ali_ios_wsl.
Launch requirement.py in the environnement to be sure every librairy are well install with the good version
Convert all the windows path to wsl path before launching the code
'''
name_env = "ali_ios"
result_pythonpath = self.check_pythonpath_windows(name_env,"ALI_IOS_utils.ALI_IOS_WSL")
if not result_pythonpath :
self.give_pythonpath_windows(name_env)
result_pythonpath = self.check_pythonpath_windows(name_env,"ALI_IOS_utils.ALI_IOS_WSL")
if result_pythonpath:
param["input"] = self.windows_to_linux_path(param["input"])
param["dir_models"] = self.windows_to_linux_path(param["dir_models"])
param["output_dir"] = self.windows_to_linux_path(param["output_dir"])
print("param : ",param)
conda_exe = self.conda_wsl.getCondaExecutable()
command = [conda_exe, "run", "-n", name_env, "python" ,"-m", f"ALI_IOS_utils.ALI_IOS_WSL"]
for key,value in param.items() :
command.append("\""+str(value)+"\"")
print("command : ",command)
result = self.conda_wsl.condaRunCommand(command)
print("RESULT DE ALI IOS WSL : ",result)
def creation_env_wsl(self):
'''
Create the environnement on wsl to run landmarks identification of ios files
'''
librairies = ["torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113",
"monai==0.7.0",
"--no-cache-dir torch==1.11.0+cu113 torchvision==0.12.0+cu113 torchaudio==0.11.0+cu113 --extra-index-url https://download.pytorch.org/whl/cu113",
"fvcore==0.1.5.post20220305",
"--no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/py39_cu113_pyt1110/download.html",
"rpyc",
"vtk",
"scipy"]
name_env = "ali_ios"
self.conda_wsl.condaCreateEnv(name_env,'3.9')
result_pythonpath = self.check_pythonpath_windows(name_env,"ALI_IOS_utils.requirement")
print("result_pythonpath : ",result_pythonpath)
if not result_pythonpath :
self.give_pythonpath_windows(name_env)
# result_pythonpath = self.check_pythonpath_windows(name_env,"ALI_IOS_utils.requirement") # THIS LINE IS WORKING
result_pythonpath = self.check_pythonpath_windows(name_env,"ALI_IOS_utils.requirement")
print("result_pythonpath : ",result_pythonpath)
if result_pythonpath :
conda_exe = self.conda_wsl.getCondaExecutable()
path_pip = self.conda_wsl.getCondaPath()+f"/envs/{name_env}/bin/pip"
# command = [conda_exe, "run", "-n", name_env, "python" ,"-m", f"ALI_IOS_utils.requirement",path_pip] # THIS LINE IS WORKING
command = [conda_exe, "run", "-n", name_env, "python" ,"-m", f"ALI_IOS_utils.requirement",path_pip]
print("command : ",command)
result = self.conda_wsl.condaRunCommand(command)
print("RESULT OF ALI IOS WSL REQUIREMENT : ",result)
# for lib in librairies :
# self.conda_wsl.condaInstallLibEnv('ali_ios',[lib])
def check_lib_wsl(self)->bool:
'''
Check if wsl contains the require librairies
'''
result1 = subprocess.run("wsl -- bash -c \"dpkg -l | grep libxrender1\"", capture_output=True, text=True)
output1 = result1.stdout.encode('utf-16-le').decode('utf-8')
clean_output1 = output1.replace('\x00', '')
result2 = subprocess.run("wsl -- bash -c \"dpkg -l | grep libgl1-mesa-glx\"", capture_output=True, text=True)
output2 = result2.stdout.encode('utf-16-le').decode('utf-8')
clean_output2 = output2.replace('\x00', '')
return "libxrender1" in clean_output1 and "libgl1-mesa-glx" in clean_output2
def onProcessStarted(self):
self.startTime = time.time()
system = platform.system()
if system=="Windows" and not self.CBCT_as_input:
pass
self.ui.PredScanLabel.setText(f"Beginning of the process")
self.RunningUIWindows(True)
else :
self.ui.PredScanProgressBar.setMaximum(self.scan_count)
self.ui.PredScanProgressBar.setValue(0)
self.ui.PredSegProgressBar.setValue(0)
if self.CBCT_as_input:
self.ui.PredScanLabel.setText(f"Scan ready: 0 / {self.scan_count}")
self.total_seg_progress = self.scan_count * self.landmark_cout
self.ui.PredSegProgressBar.setMaximum(self.total_seg_progress)
self.ui.PredSegLabel.setText(f"Landmarks found : 0 / {self.total_seg_progress}")
else:
self.ui.PredScanLabel.setText(f"Scan : 0 / {self.scan_count}")
model_used = []
for lm in self.lm_tab.GetSelected():
for model in SURFACE_LANDMARKS.keys():
if lm in SURFACE_LANDMARKS[model]:
if model not in model_used:
model_used.append(model)
self.total_seg_progress = len(self.tooth_lm.GetSelected()) * len(model_used)
self.ui.PredSegProgressBar.setMaximum(self.total_seg_progress)
self.ui.PredSegLabel.setText(f"Identified : 0 / {self.total_seg_progress}")
self.prediction_step = 0
self.progress = 0
self.RunningUI(True)
def UpdateALICBCT(self,progress):
# print(progress)
if progress == 200:
self.prediction_step += 1
if self.prediction_step == 1:
self.progress = 0
# self.progressBar.maximum = self.scan_count
# self.progressBar.windowTitle = "Correcting contrast..."
# self.progressBar.setValue(0)
if self.prediction_step == 2:
self.progress = 0
self.ui.PredScanProgressBar.setValue(self.scan_count)
self.ui.PredScanLabel.setText(f"Scan ready: {self.scan_count} / {self.scan_count}")
# self.progressBar.maximum = self.total_seg_progress
# self.progressBar.windowTitle = "Segmenting scans..."
# self.progressBar.setValue(0)
if progress == 100:
if self.prediction_step == 1:
# self.progressBar.setValue(self.progress)
self.ui.PredScanProgressBar.setValue(self.progress)
self.ui.PredScanLabel.setText(f"Scan ready: {self.progress} / {self.scan_count}")
if self.prediction_step == 2:
# self.progressBar.setValue(self.progress)
self.ui.PredSegProgressBar.setValue(self.progress)
self.ui.PredSegLabel.setText(f"Landmarks found : {self.progress} / {self.total_seg_progress}")
self.progress += 1
def UpdateALIIOS(self,progress):
if progress == 200: