-
Notifications
You must be signed in to change notification settings - Fork 16
/
mpReview.py
executable file
·2968 lines (2407 loc) · 122 KB
/
mpReview.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
from __future__ import division
import os, json, xml.dom.minidom, string, glob, re, math
import vtk, qt, ctk, slicer
import logging
import CompareVolumes
import SimpleITK as sitk
import sitkUtils
import datetime
from slicer.ScriptedLoadableModule import *
from mpReviewPreprocessor import mpReviewPreprocessorLogic
from qSlicerMultiVolumeExplorerModuleWidget import qSlicerMultiVolumeExplorerSimplifiedModuleWidget
from qSlicerMultiVolumeExplorerModuleHelper import qSlicerMultiVolumeExplorerModuleHelper as MVHelper
from SlicerDevelopmentToolboxUtils.mixins import ModuleWidgetMixin, ModuleLogicMixin
from SlicerDevelopmentToolboxUtils.helpers import WatchBoxAttribute
from SlicerDevelopmentToolboxUtils.widgets import TargetCreationWidget, XMLBasedInformationWatchBox
from SlicerDevelopmentToolboxUtils.icons import Icons
from DICOMLib import DICOMPlugin
import DICOMSegmentationPlugin
import DICOMwebBrowser
from DICOMwebBrowser import GoogleCloudPlatform
import hashlib
import pydicom
import shutil
class GoogleCloudPlatform(object):
'''Class for setting up GCP and for listing projects, datasets, datastores'''
def gcloud(self, subcommand):
import shutil
args = [shutil.which('gcloud')]
if (None in args):
logging.error(f"Unable to locate gcloud, please install the Google Cloud SDK")
args.extend(subcommand.split())
process = slicer.util.launchConsoleProcess(args)
process.wait()
return process.stdout.read()
def projects(self):
return sorted(self.gcloud("projects list --sort-by=projectId --format=value(PROJECT_ID)").split("\n"), key=str.lower)
def datasets(self, project):
return sorted(self.gcloud(f"--project {project} healthcare datasets list --format=value(ID,LOCATION)").split("\n"), key=str.lower)
def dicomStores(self, project, dataset):
return sorted(self.gcloud(f"--project {project} healthcare dicom-stores list --dataset {dataset} --format=value(ID)").split("\n"), key=str.lower)
def token(self):
return self.gcloud("auth print-access-token").strip()
def copy_from_bucket_to_dicomStore(self, project, location, dataset, dicomStore, bucket_name):
return self.gcloud(f"--project {project} healthcare dicom-stores import gcs {dicomStore} --dataset {dataset} --location {location} --gcs-uri gs://{bucket_name}/**.dcm")
def datasetsOnly(self, project):
return self.gcloud(f"--project {project} healthcare datasets list --format=value(ID)").split("\n")
def locations(self):
return self.gcloud(f"compute regions list --format=value(NAME)").split("\n")
def create_dicomStore(self, project, location, dataset, dicomStore):
return sorted(self.gcloud(f"--project {project} healthcare dicom-stores create {dicomStore} --dataset {dataset} --format=value(ID)").split("\n"), key=str.lower)
class mpReview(ScriptedLoadableModule, ModuleWidgetMixin):
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
parent.title = "mpReview"
parent.categories = ["Informatics"]
parent.dependencies = ["SlicerDevelopmentToolbox"]
parent.contributors = ["Andrey Fedorov (SPL)", "Robin Weiss (U. of Chicago)", "Alireza Mehrtash (SPL)",
"Christian Herz (SPL)"]
parent.helpText = """
Multiparametric Image Review (mpReview) module is intended to support review and annotation of multiparametric
image data. The driving use case for the development of this module was review and segmentation of the regions of
interest in prostate cancer multiparametric MRI.
"""
parent.acknowledgementText = """
Supported by NIH U24 CA180918 (PIs Fedorov & Kikinis) and U01CA151261 (PI Fennessy)
""" # replace with organization, grant and thanks.
self.parent = parent
# Add this test to the SelfTest module's list for discovery when the module
# is created. Since this module may be discovered before SelfTests itself,
# create the list if it doesn't already exist.
try:
slicer.selfTests
except AttributeError:
slicer.selfTests = {}
def runTest(self):
return
class mpReviewWidget(ScriptedLoadableModuleWidget, ModuleWidgetMixin):
# PIRADS_VIEWFORM_URL = 'https://docs.google.com/forms/d/1Xwhvjn_HjRJAtgV5VruLCDJ_eyj1C-txi8HWn8VyXa4/viewform'
# QA_VIEWFORM_URL = 'https://docs.google.com/forms/d/18Ni2rcooi60fev5mWshJA0yaCzHYvmXPhcG2-jMF-uw/viewform'
@property
def inputDataDir(self):
return self.dataDirButton.directory
@inputDataDir.setter
def inputDataDir(self, directory):
logging.debug('Directory selected: %s' % directory)
if not os.path.exists(directory):
directory = None
self.dataDirButton.text = "Choose data directory"
truncatedPath = None
else:
truncatedPath = ModuleLogicMixin.truncatePath(directory)
self.dataDirButton.text = truncatedPath
self.dataDirButton.caption = directory
self.setSetting('InputLocation', directory)
self.checkAndSetLUT()
self.updateStudyTable()
self.informationWatchBox.setInformation("CurrentDataDir", truncatedPath, toolTip=directory)
def __init__(self, parent = None):
ScriptedLoadableModuleWidget.__init__(self, parent)
self.resourcesPath = os.path.join(slicer.modules.mpreview.path.replace(self.moduleName+".py",""), 'Resources')
# self.qaFormURL = ''
# self.piradsFormURL = ''
# mrml node for invoking command line modules
self.CLINode = None
self.logic = mpReviewLogic()
self.multiVolumeExplorer = None
# set up temporary directory
self.tempDir = os.path.join(slicer.app.temporaryPath, 'mpReview-tmp')
self.logic.createDirectory(self.tempDir, message='Temporary directory location: ' + self.tempDir)
self.modulePath = os.path.dirname(slicer.util.modulePath(self.moduleName))
def getAllSliceWidgets(self):
widgetNames = self.layoutManager.sliceViewNames()
return [self.layoutManager.sliceWidget(wn) for wn in widgetNames]
def setOffsetOnAllSliceWidgets(self, offset):
for widget in self.getAllSliceWidgets():
node = widget.mrmlSliceNode()
node.SetSliceOffset(offset)
def linkAllSliceWidgets(self, link):
for widget in self.getAllSliceWidgets():
sc = widget.mrmlSliceCompositeNode()
sc.SetLinkedControl(link)
sc.SetInteractionFlagsModifier(4+8+16)
def setOpacityOnAllSliceWidgets(self, opacity):
for widget in self.getAllSliceWidgets():
sc = widget.mrmlSliceCompositeNode()
sc.SetForegroundOpacity(opacity)
def updateViewRenderer (self):
for widget in self.getAllSliceWidgets():
view = widget.sliceView()
view.scheduleRender()
def setupIcons(self):
self.databaseSelectionIcon = self.createIcon('icon-databaseselection_fit.png') # fix later
self.studySelectionIcon = self.createIcon('icon-studyselection_fit.png')
self.segmentationIcon = self.createIcon('icon-segmentation_fit.png')
self.completionIcon = self.createIcon('icon-completion_fit.png')
def setupTabBarNavigation(self):
self.tabWidget = qt.QTabWidget()
self.layout.addWidget(self.tabWidget)
self.databaseSelectionWidget = qt.QWidget() # added
self.studyAndSeriesSelectionWidget = qt.QWidget()
self.segmentationWidget = qt.QWidget()
self.completionWidget = qt.QWidget()
self.databaseSelectionWidgetLayout = qt.QGridLayout() # added
self.studyAndSeriesSelectionWidgetLayout = qt.QGridLayout()
self.segmentationWidgetLayout = qt.QVBoxLayout()
self.completionWidgetLayout = qt.QFormLayout()
self.databaseSelectionWidget.setLayout(self.databaseSelectionWidgetLayout) # added
self.studyAndSeriesSelectionWidget.setLayout(self.studyAndSeriesSelectionWidgetLayout)
self.segmentationWidget.setLayout(self.segmentationWidgetLayout)
self.completionWidget.setLayout(self.completionWidgetLayout)
self.tabWidget.setIconSize(qt.QSize(85, 30))
self.tabWidget.addTab(self.databaseSelectionWidget, self.databaseSelectionIcon, '')
self.tabWidget.addTab(self.studyAndSeriesSelectionWidget, self.studySelectionIcon, '')
self.tabWidget.addTab(self.segmentationWidget, self.segmentationIcon, '')
self.tabWidget.addTab(self.completionWidget, self.completionIcon, '')
# self.setTabsEnabled([1,2], False)
self.setTabsEnabled([1,2,3], False)
def onTabWidgetClicked(self, currentIndex):
if self.currentTabIndex == currentIndex:
return
setNewIndex = False
if currentIndex == 0:
setNewIndex = self.onStep0Selected() # database
if currentIndex == 1:
setNewIndex = self.onStep1Selected() # studies
if currentIndex == 2:
setNewIndex = self.onStep2Selected() # series
if currentIndex == 3:
setNewIndex = self.onStep3Selected() # segmentation tab
if setNewIndex:
self.currentTabIndex = currentIndex
if currentIndex == 3: # if series selected, can view segmentation tab
self.editorWidget.installKeyboardShortcuts()
else:
self.editorWidget.setActiveEffect(None)
self.editorWidget.uninstallKeyboardShortcuts()
self.editorWidget.removeViewObservations()
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
self.setupIcons()
self.setupInformationFrame()
self.setupTabBarNavigation()
self.parameters = {}
self.crosshairNode = slicer.mrmlScene.GetNthNodeByClass(0, 'vtkMRMLCrosshairNode')
self.setupDatabaseSelectionUI()
self.setupDataAndStudySelectionUI()
self.setupSeriesSelectionView()
self.setupSegmentationToolsUI()
self.setupCompletionUI()
self.setupConnections()
# self.layout.addStretch(1)
self.volumesLogic = slicer.modules.volumes.logic()
# these are the PK maps that should be loaded
self.pkMaps = ['Ktrans','Ve','Auc','TTP','MaxSlope']
self.volumeNodes = {}
self.refSelectorIgnoreUpdates = False
self.selectedStudyName = None
# self.dataDirButton.directory = self.getSetting('InputLocation')
self.currentTabIndex = 0
self.checkAndSetLUT() # I added
def setupInformationFrame(self):
watchBoxInformation = [WatchBoxAttribute('StudyID', 'Study ID:'),
WatchBoxAttribute('PatientName', 'Name:', 'PatientName'),
WatchBoxAttribute('StudyDate', 'Study Date:', 'StudyDate'),
WatchBoxAttribute('PatientID', 'PID:', 'PatientID'),
WatchBoxAttribute('CurrentDataDir', 'Current Data Dir:'),
WatchBoxAttribute('PatientBirthDate', 'DOB:', 'PatientBirthDate')]
self.informationWatchBox = XMLBasedInformationWatchBox(watchBoxInformation, columns=2)
self.layout.addWidget(self.informationWatchBox)
def setupDatabaseSelectionUI(self):
self.setupDatabaseSelectionView()
def setupDatabaseSelectionView(self):
self.databaseGroupBox = qt.QGroupBox("Databases")
databaseGroupBoxLayout = qt.QFormLayout()
self.selectLocalDatabaseButton = qt.QRadioButton('Use local database')
self.selectRemoteDatabaseButton = qt.QRadioButton('Use GCP remote server')
self.selectOtherRemoteDatabaseButton = qt.QRadioButton('Use other remote server')
# self.gcp = DICOMwebBrowser.GoogleCloudPlatform() # this doesn't work, why?
# self.gcp = GoogleCloudPlatform() # this works
databaseGroupBoxLayout.addRow(self.selectLocalDatabaseButton)
databaseGroupBoxLayout.addRow(self.selectRemoteDatabaseButton)
self.projectSelectorCombobox = qt.QComboBox()
databaseGroupBoxLayout.addRow("Project: ", self.projectSelectorCombobox)
self.projectSelectorCombobox.connect("currentIndexChanged(int)", self.onProjectSelected)
self.projectSelectorCombobox.setEnabled(False)
self.datasetSelectorCombobox = qt.QComboBox()
databaseGroupBoxLayout.addRow("Dataset: ", self.datasetSelectorCombobox)
self.datasetSelectorCombobox.connect("currentIndexChanged(int)", self.onDatasetSelected)
self.datasetSelectorCombobox.setEnabled(False)
self.dicomStoreSelectorCombobox = qt.QComboBox()
databaseGroupBoxLayout.addRow("DICOM Store: ", self.dicomStoreSelectorCombobox)
self.dicomStoreSelectorCombobox.connect("currentIndexChanged(int)", self.onDICOMStoreSelected)
self.dicomStoreSelectorCombobox.setEnabled(False)
self.serverUrlLineEdit = qt.QLineEdit()
databaseGroupBoxLayout.addRow("GCP Server URL: ", self.serverUrlLineEdit)
self.serverUrlLineEdit.setText('')
self.serverUrlLineEdit.setReadOnly(True)
self.selectDatabaseOKButton = qt.QPushButton("OK")
self.selectDatabaseOKButton.setEnabled(False)
databaseGroupBoxLayout.addRow(self.selectDatabaseOKButton)
# Other remote
# databaseGroupBoxLayout.setVerticalSpacing(10) # this sets for all.
databaseGroupBoxLayout.addRow(self.selectOtherRemoteDatabaseButton)
self.OtherserverUrlLineEdit = qt.QLineEdit()
databaseGroupBoxLayout.addRow("Other Server URL: ", self.OtherserverUrlLineEdit)
self.OtherserverUrlLineEdit.setText('')
self.OtherserverUrlLineEdit.setReadOnly(True)
self.selectOtherRemoteDatabaseOKButton = qt.QPushButton("OK")
self.selectOtherRemoteDatabaseOKButton.setEnabled(False)
databaseGroupBoxLayout.addRow(self.selectOtherRemoteDatabaseOKButton)
self.databaseGroupBox.setLayout(databaseGroupBoxLayout)
self.databaseSelectionWidgetLayout.addWidget(self.databaseGroupBox, 3, 0, 1, 3)
###############################
### Select terminology file ###
###############################
self.terminologyGroupBox = qt.QGroupBox("Terminology")
terminologyGroupBoxLayout = qt.QFormLayout()
# self.selectTerminologyFileButton = qt.QPushButton("Select Segmentation JSON Terminology file")
# self.selectTerminologyFileButton.setEnabled(True)
# terminologyGroupBoxLayout.addRow(self.selectTerminologyFileButton)
self.terminologyFilePathLineEdit = ctk.ctkPathLineEdit()
self.terminologyFilePathLineEdit.filters = ctk.ctkPathLineEdit.Files
self.terminologyFilePathLineEdit.nameFilters = ['*.json']
self.terminologyFilePathLineEdit.settingKey = 'Segmentation JSON Terminology file'
terminologyGroupBoxLayout.addRow("Segmentation JSON Terminology file:", self.terminologyFilePathLineEdit)
#self.checkAndSetLUT()
# print('self.terminologyFilePathLineEdit.currentPath: ' + str(self.terminologyFilePathLineEdit.currentPath))
# if not self.terminologyFilePathLineEdit.currentPath:
# self.terminologyFile = os.path.join(self.resourcesPath, "SegmentationCategoryTypeModifier-mpReview.json")
# else:
# self.checkAndSetLUT()
self.terminologyGroupBox.setLayout(terminologyGroupBoxLayout)
self.databaseSelectionWidgetLayout.addWidget(self.terminologyGroupBox, 4, 0, 1, 3)
def getTerminologyFile(self):
""" load the selected terminology file """
if self.terminologyFilePathLineEdit.currentPath:
self.terminologyFile = self.terminologyFilePathLineEdit.currentPath
self.checkAndSetLUT()
def selectTerminologyFile(self):
""" open a QFileDialog box where the user can optionally choose a segmentation JSON terminology file """
segJsonPrompt = qt.QFileDialog()
# self.terminologyFile = segJsonPrompt.getOpenFileName(None,"Select File", "", "JSON Files (*.json)")# "All Files (*);;JSON Files (*.json)"
jsonFilenameSelected = segJsonPrompt.getOpenFileName(None,"Select File", "", "JSON Files (*.json)")# "All Files (*);;JSON Files (*.json)"
jsonFilenames = segJsonPrompt.selectedFiles()
print('jsonFilenameSelected: ' + str(jsonFilenameSelected))
print('jsonFilenames: ' + str(jsonFilenames))
if jsonFilenameSelected:
self.terminologyFile = jsonFilenameSelected
print('new self.terminologyFile: ' + str(self.terminologyFile))
self.checkAndSetLUT()
def getServerUrl(self):
if hasattr(self,'dicomStore'):
url = "https://healthcare.googleapis.com/v1beta1"
url += f"/projects/{self.project}"
url += f"/locations/{self.location}"
url += f"/datasets/{self.dataset}"
url += f"/dicomStores/{self.dicomStore}"
url += "/dicomWeb"
else:
# url = ''
url = self.serverUrlLineEdit.text
self.serverUrl = url
def onProjectSelected(self):
currentText = self.projectSelectorCombobox.currentText
if currentText != "":
self.project = currentText.split()[0]
self.datasetSelectorCombobox.clear()
self.dicomStoreSelectorCombobox.clear()
qt.QTimer.singleShot(0, lambda : self.datasetSelectorCombobox.addItems(self.gcp.datasets(self.project)))
self.datasetSelectorCombobox.setEditable(True)
dataset_list = self.gcp.datasets(self.project)
self.datasetCompleter = qt.QCompleter(dataset_list)
self.datasetCompleter.setCaseSensitivity(0)
self.datasetCompleter.setCompletionColumn(0)
self.datasetSelectorCombobox.setCompleter(self.datasetCompleter)
def onDatasetSelected(self):
currentText = self.datasetSelectorCombobox.currentText
if currentText != "":
datasetTextList = currentText.split()
self.dataset = datasetTextList[0]
self.location = datasetTextList[1]
self.dicomStoreSelectorCombobox.clear()
qt.QTimer.singleShot(0, lambda : self.dicomStoreSelectorCombobox.addItems(self.gcp.dicomStores(self.project, self.dataset)))
self.dicomStoreSelectorCombobox.setEditable(True)
dicomStore_list = self.gcp.dicomStores(self.project, self.dataset)
self.dicomStoreCompleter = qt.QCompleter(dicomStore_list)
self.dicomStoreCompleter.setCaseSensitivity(0)
self.dicomStoreCompleter.setCompletionColumn(0)
self.dicomStoreSelectorCombobox.setCompleter(self.dicomStoreCompleter)
def onDICOMStoreSelected(self):
currentText = self.dicomStoreSelectorCombobox.currentText
if currentText != "":
self.dicomStore = currentText.split()[0]
# populate the server url here
self.getServerUrl()
self.serverUrlLineEdit.setText(self.serverUrl)
self.selectDatabaseOKButton.setEnabled(True)
def onDICOMStoreChangedMessageBox(self):
mbox = qt.QMessageBox()
mbox.text = self.messageBoxText
okButton = mbox.addButton(qt.QMessageBox.Ok)
mbox.exec_()
selectedButton = mbox.clickedButton()
# if selectedButton in [okButton]:
def checkIfProjectExists(self):
projectList = self.gcp.projects()
if not self.project in projectList:
return False
else:
return True
def checkIfLocationExists(self):
locationList = self.gcp.locations()
if not self.location in locationlist:
return False
else:
return True
def checkIfDatasetExists(self):
# datasetList = self.gcp.datasets(self.project)
datasetList = self.gcp.datasetsOnly(self.project)
if not self.dataset in datasetList:
return False
else:
return True
def checkIfDicomStoreExists(self):
dicomStoreList = self.gcp.dicomStores(self.project, self.dataset)
if not self.dicomStore in dicomStoreList:
return False
else:
return True
def checkserverURLIsValid(self):
# set to True at beginning
self.serverURLIsValid = True
# get the current text
currentText = self.serverUrlLineEdit.text
textparts = currentText.split('/')
# Need to check if first part of url is also valid. https://healthcare.googleapis.com/v1beta1
startStr = r"https://healthcare.googleapis.com/v1beta1"
if not startStr in currentText:
self.messageBoxText = 'Beginning of serverURL must be set to https://healthcare.googleapis.com/v1beta1'
self.serverURLIsValid = False
return
# If 'project' is in the serverURL
if 'projects' in textparts:
project_ind = textparts.index('projects')
self.project = textparts[project_ind+1]
# Check if the project exists
if not self.checkIfProjectExists():
self.messageBoxText = 'Project ' + self.project + ' does not exist, please specify another one.'
self.serverURLIsValid = False
return
else:
self.messageBoxText = 'Keyword project must exist in the serverURL.'
self.serverURLIsValid = False
return
# If 'location' is in serverURL
if 'location' in textparts:
location_ind = textparts.index('location')
self.location = textparts[location_ind+1]
# Check if location is valid
if not self.checkIfLocationExists():
self.messageBox = 'Location ' + self.location + ' is not a valid location, please specify another one.'
self.serverURLIsValid = False
return
else:
self.messageBoxText = 'Keyword location must exist in the serverURL.'
self.serverURLIsValid = False
return
# If 'dataset' is in serverURL
if 'datasets' in textparts:
dataset_ind = textparts.index('datasets')
self.dataset = textparts[dataset_ind+1]
# Check if dataset exists in the project
if not self.checkIfDatasetExists():
self.messageBoxText = 'Dataset ' + self.dataset + ' does not exist within project ' + self.project + ', please specify another one.'
self.serverURLIsValid = False
return
else:
self.messageBoxText = 'Keyword dataset must exist in the serverURL.'
self.serverURLIsValid = False
return
# If 'dicomStores' is in serverURL
if 'dicomStores' in textparts:
dicomStore_ind = textparts.index('dicomStores')
self.dicomStore = textparts[dicomStore_ind+1]
# Check if dicomStore exists in the project and dataset
if not self.checkIfDicomStoreExists():
self.messageBoxText = 'dicomStore ' + self.dicomStore + ' does not exist within project ' + self.project + ' nor within dataset ' + self.dataset + ', please specify another one.'
self.serverURLIsValid = False
return
else:
self.messageBoxText = 'Keyword dicomStores must exist in the serverURL. '
self.serverURLIsValid = False
return
def onDICOMStoreChanged(self):
# get error message
errorMessage = self.checkserverURLIsValid() # this sets the self.serverURLIsValid field
# If valid, set the new serverURL so we can get the updated studies
# And then update the study table remote
if self.serverURLIsValid:
self.getServerUrl()
self.updateStudyTableRemote()
# If not valid, display an error message
else:
self.onDICOMStoreChangedMessageBox()
self.setTabsEnabled([1,2], False) # set the study tab and segmentation tab to false.
return
def onURLEdited(self):
print ('server url text changed')
self.serverUrl = self.serverUrlLineEdit.text
print (self.serverUrl)
return
def onOtherURLEdited(self):
print ('other server url text changed')
self.otherserverUrl = self.OtherserverUrlLineEdit.text
print (self.otherserverUrl)
return
def updateStudiesAndSeriesTabAvailability(self):
self.setTabsEnabled([1], True)
# Will add in more error checking for importing packages later
def dicomwebAuthorize(self):
import dicomweb_client.log
dicomweb_client.log.configure_logging(2)
from dicomweb_client.api import DICOMwebClient
effectiveServerUrl = self.serverUrl
session = None
headers = {}
headers["Authorization"] = f"Bearer {GoogleCloudPlatform().token()}"
self.DICOMwebClient = DICOMwebClient(url=effectiveServerUrl, session=session, headers=headers)
def dicomwebOtherAuthorize(self):
import dicomweb_client.log
dicomweb_client.log.configure_logging(2)
from dicomweb_client.api import DICOMwebClient
effectiveServerUrl = self.otherserverUrl
session = None
self.DICOMwebClient = DICOMwebClient(url=effectiveServerUrl, session=session)
def setupGoogleCloudPlatform(self):
self.gcp = GoogleCloudPlatform()
print('projects: ' + str(self.gcp.projects()))
self.projectSelectorCombobox.addItems(self.gcp.projects())
project_list = self.gcp.projects()
self.projectCompleter = qt.QCompleter(project_list)
self.projectCompleter.setCaseSensitivity(0)
self.projectCompleter.setCompletionColumn(0)
self.projectSelectorCombobox.setCompleter(self.projectCompleter)
def onCancel(self):
self.projectSelectorCombobox.clear()
self.datasetSelectorCombobox.clear()
self.dicomStoreSelectorCombobox.clear()
def setupDataAndStudySelectionUI(self):
self.customLUTInfoIcon = self.createHelperLabel()
self.studyAndSeriesSelectionWidgetLayout.addWidget(self.customLUTInfoIcon, 0, 2, 1, 1, qt.Qt.AlignRight)
self.customLUTInfoIcon.hide()
self.setupStudySelectionView()
def createHelperLabel(self, toolTipText=""):
label = self.createLabel("", pixmap=Icons.info.pixmap(qt.QSize(23, 20)), toolTip=toolTipText)
label.setCursor(qt.Qt.PointingHandCursor)
return label
def setupStudySelectionView(self):
self.studiesGroupBox = ctk.ctkCollapsibleGroupBox()
self.studiesGroupBox.title = "Studies"
studiesGroupBoxLayout = qt.QGridLayout()
self.studiesGroupBox.setLayout(studiesGroupBoxLayout)
self.studiesView, self.studiesModel = self.createListView('StudiesTable', ['Study ID'])
self.studiesView.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding)
filter_proxy_model = qt.QSortFilterProxyModel()
filter_proxy_model.setSourceModel(self.studiesModel)
# filter_proxy_model.setSourceModel(self.studiesView.selectionModel())
filter_proxy_model.setFilterKeyColumn(1)
self.studiesFilterLine = qt.QLineEdit()
self.studiesFilterLine.textChanged.connect(filter_proxy_model.setFilterRegExp)
studiesGroupBoxLayout.addWidget(self.studiesFilterLine)
studiesGroupBoxLayout.addWidget(self.studiesView)
self.studyAndSeriesSelectionWidgetLayout.addWidget(self.studiesGroupBox, 2, 0, 1, 3)
def setupSeriesSelectionView(self):
self.seriesGroupBox = qt.QGroupBox("Series")
seriesGroupBoxLayout = qt.QGridLayout()
self.seriesGroupBox.setLayout(seriesGroupBoxLayout)
self.seriesView, self.seriesModel = self.createListView('SeriesTable', ['Series ID'])
self.seriesView.setSelectionMode(qt.QAbstractItemView.ExtendedSelection)
self.selectAllSeriesButton = self.createButton('Select All')
self.deselectAllSeriesButton = self.createButton('Deselect All')
self.selectAllSeriesButton.setEnabled(False)
self.deselectAllSeriesButton.setEnabled(False)
seriesGroupBoxLayout.addWidget(self.seriesView, 0, 0, 1, 2)
seriesGroupBoxLayout.addWidget(self.createHLayout([self.selectAllSeriesButton, self.deselectAllSeriesButton]),
1, 0, 1, 2)
self.studyAndSeriesSelectionWidgetLayout.addWidget(self.seriesGroupBox, 3, 0, 1, 3)
def setupSegmentationToolsUI(self):
self.refSelector = qt.QComboBox()
self.segmentationWidgetLayout.addWidget(self.createHLayout([qt.QLabel("Reference image: "), self.refSelector]))
self.setupMultiVolumeExplorerUI()
self.setupLabelMapEditorUI()
self.setupAdvancedSegmentationSettingsUI()
# self.setupFiducialsUI()
# keep here names of the views created by CompareVolumes logic
self.viewNames = []
self.segmentationWidgetLayout.addStretch(1)
def setupMultiVolumeExplorerUI(self):
self.multiVolumeExplorerArea = ctk.ctkCollapsibleButton()
self.multiVolumeExplorerArea.text = "MultiVolumeExplorer"
self.multiVolumeExplorerArea.collapsed = True
self.multiVolumeExplorer = mpReviewMultiVolumeExplorer(qt.QFormLayout(self.multiVolumeExplorerArea))
self.multiVolumeExplorer.setup()
self.segmentationWidgetLayout.addWidget(self.multiVolumeExplorerArea)
def setupLabelMapEditorUI(self):
self.editorWidget = slicer.qMRMLSegmentEditorWidget()
self.editorWidget.defaultTerminologyEntrySettingsKey = "mpReview/DefaultTerminologyEntry"
self.editorWidget.setMaximumNumberOfUndoStates(10)
self.editorWidget.setMRMLScene(slicer.mrmlScene)
self.editorWidget.unorderedEffectsVisible = False
self.editorWidget.setEffectNameOrder(["Paint", "Draw", "Erase", "Fill between slices", "Margin"])
self.editorWidget.jumpToSelectedSegmentEnabled = True
self.editorWidget.switchToSegmentationsButtonVisible = False
# added
self.editorWidget.setMasterVolumeNodeSelectorVisible(False)
self.editorWidget.setSegmentationNodeSelectorVisible(False)
# Select parameter set node if one is found in the scene, and create one otherwise
segmentEditorSingletonTag = "mpReviewSegmentEditor"
segmentEditorNode = slicer.mrmlScene.GetSingletonNode(segmentEditorSingletonTag, "vtkMRMLSegmentEditorNode")
if segmentEditorNode is None:
segmentEditorNode = slicer.vtkMRMLSegmentEditorNode()
segmentEditorNode.SetSingletonTag(segmentEditorSingletonTag)
# Set overwrite mode: 0/1/2 -> overwrite all/visible/none
segmentEditorNode.SetOverwriteMode(2) # allow overlap
segmentEditorNode = slicer.mrmlScene.AddNode(segmentEditorNode)
if self.editorWidget.mrmlSegmentEditorNode() != segmentEditorNode:
self.editorWidget.setMRMLSegmentEditorNode(segmentEditorNode)
self.segmentationWidgetLayout.addWidget(self.editorWidget)
self.modelsVisibilityButton = self.createButton('Hide', checkable=True)
self.labelMapVisibilityButton = self.createButton('Hide', checkable=True)
self.labelMapOutlineButton = self.createButton('Outline', checkable=True)
self.enableJumpToROI = qt.QCheckBox("Jump to ROI")
self.enableJumpToROI.checked = self.editorWidget.jumpToSelectedSegmentEnabled
modelsFrame = self.createHLayout([qt.QLabel('Structure Models: '),
self.modelsVisibilityButton, self.labelMapVisibilityButton,
self.labelMapOutlineButton, self.enableJumpToROI])
# added
self.modelsVisibilityButton.hide()
self.segmentationWidgetLayout.addWidget(modelsFrame)
def setupAdvancedSegmentationSettingsUI(self):
self.advancedSettingsArea = ctk.ctkCollapsibleButton()
self.advancedSettingsArea.text = "Advanced Settings"
self.advancedSettingsArea.collapsed = True
self.setupSingleMultiViewSettingsUI()
self.setupViewerOrientationSettingsUI()
advancedSettingsLayout = qt.QFormLayout(self.advancedSettingsArea)
advancedSettingsLayout.addRow("Show series: ", self.groupWidget)
advancedSettingsLayout.addRow('View orientation: ', self.orientationBox)
self.segmentationWidgetLayout.addWidget(self.advancedSettingsArea)
def setupSingleMultiViewSettingsUI(self):
self.multiView = qt.QRadioButton('All')
self.singleView = qt.QRadioButton('Reference only')
self.multiView.setChecked(True)
self.groupWidget = qt.QGroupBox()
self.groupLayout = qt.QFormLayout(self.groupWidget)
self.groupLayout.addRow(self.multiView, self.singleView)
self.viewButtonGroup = qt.QButtonGroup()
self.viewButtonGroup.addButton(self.multiView, 1)
self.viewButtonGroup.addButton(self.singleView, 2)
def setupViewerOrientationSettingsUI(self):
self.orientationBox = qt.QGroupBox()
orientationBoxLayout = qt.QFormLayout()
self.orientationBox.setLayout(orientationBoxLayout)
self.orientationButtons = {}
self.orientations = ("Axial", "Sagittal", "Coronal")
for orientation in self.orientations:
self.orientationButtons[orientation] = self.createRadioButton(orientation, checked=orientation=="Axial")
orientationBoxLayout.addWidget(self.orientationButtons[orientation])
self.currentOrientation = 'Axial'
def setupFiducialsUI(self):
self.fiducialsArea = ctk.ctkCollapsibleButton()
self.fiducialsArea.text = "Fiducials"
self.fiducialsArea.collapsed = True
self.fiducialsWidget = TargetCreationWidget()
self.fiducialsWidget.targetListSelectorVisible = True
self.segmentationWidgetLayout.addWidget(self.fiducialsWidget)
def setupCompletionUI(self):
# self.piradsButton = qt.QPushButton("PI-RADS v2 review form")
# self.completionWidgetLayout.addWidget(self.piradsButton)
# self.qaButton = qt.QPushButton("Quality Assurance form")
# self.completionWidgetLayout.addWidget(self.qaButton)
self.saveButton = qt.QPushButton("Save")
self.completionWidgetLayout.addWidget(self.saveButton)
'''
self.piradsButton = qt.QPushButton("PI-RADS review")
self.layout.addWidget(self.piradsButton)
# self.piradsButton.connect('clicked()',self.onPiradsClicked)
'''
def setupConnections(self):
# self.dataDirButton.directorySelected.connect(lambda: setattr(self, "inputDataDir", self.dataDirButton.directory))
self.selectAllSeriesButton.connect('clicked()', lambda: self.selectAllSeries(True))
self.deselectAllSeriesButton.connect('clicked()', lambda: self.selectAllSeries(False))
self.modelsVisibilityButton.connect("toggled(bool)", self.onModelsVisibilityButton)
self.labelMapVisibilityButton.connect("toggled(bool)", self.onLabelMapVisibilityButton)
self.labelMapOutlineButton.connect('toggled(bool)', self.setLabelOutline)
# self.piradsButton.connect('clicked()', self.onPIRADSFormClicked)
# self.qaButton.connect('clicked()', self.onQAFormClicked)
self.saveButton.connect('clicked()', self.onSaveClicked)
for orientation in self.orientations:
self.orientationButtons[orientation].connect("clicked()", lambda o=orientation: self.setOrientation(o))
self.viewButtonGroup.connect('buttonClicked(int)', self.onViewUpdateRequested)
self.enableJumpToROI.connect('toggled(bool)', self.editorWidget.setJumpToSelectedSegmentEnabled)
self.multiVolumeExplorer.frameSlider.connect('valueChanged(double)', self.onSliderChanged)
self.studiesView.selectionModel().connect('currentChanged(QModelIndex, QModelIndex)', self.onStudySelected)
self.seriesView.connect('clicked(QModelIndex)', self.onSeriesSelected)
self.editorWidget.connect("currentSegmentIDChanged(QString)", self.onStructureClicked)
self.refSelector.connect('currentIndexChanged(int)', self.onReferenceChanged)
self.tabWidget.connect('currentChanged(int)',self.onTabWidgetClicked)
self.selectLocalDatabaseButton.clicked.connect(lambda: self.checkWhichDatabaseSelected())
self.selectRemoteDatabaseButton.clicked.connect(lambda : [self.setTabsEnabled([1], False),
self.setupGoogleCloudPlatform(),
self.selectDatabaseOKButton.setEnabled(True),
self.updateSelectorAvailability(set=True),
self.selectOtherRemoteDatabaseOKButton.setEnabled(False),
])
self.selectOtherRemoteDatabaseButton.clicked.connect(lambda : [self.setTabsEnabled([1], False),
self.OtherserverUrlLineEdit.setReadOnly(False),
self.selectOtherRemoteDatabaseOKButton.setEnabled(True),
self.updateSelectorAvailability(set=False),
self.selectDatabaseOKButton.setEnabled(False)])
self.selectDatabaseOKButton.clicked.connect(lambda: self.checkWhichDatabaseSelected())
self.selectOtherRemoteDatabaseOKButton.clicked.connect(lambda: self.checkWhichDatabaseSelected())
self.serverUrlLineEdit.textChanged.connect(lambda: self.onURLEdited())
self.OtherserverUrlLineEdit.textChanged.connect(lambda: self.onOtherURLEdited())
# self.selectTerminologyFileButton.clicked.connect(lambda: self.selectTerminologyFile())
self.terminologyFilePathLineEdit.currentPathChanged.connect(lambda: self.getTerminologyFile())
# def enter(self):
# userName = self.getSetting('UserName')
# self.piradsFormURL = self.getSetting('piradsFormURL')
# self.qaFormURL = self.getSetting('qaFormURL')
#
# if userName is None or userName == '':
# # prompt the user for ID (last name)
# self.namePrompt = qt.QDialog()
# self.namePromptLayout = qt.QVBoxLayout()
# self.namePrompt.setLayout(self.namePromptLayout)
# self.nameLabel = qt.QLabel('Enter your last name:', self.namePrompt)
# import getpass
# self.nameText = qt.QLineEdit(getpass.getuser(), self.namePrompt)
# self.nameButton = qt.QPushButton('OK', self.namePrompt)
# self.nameButton.connect('clicked()', self.onNameEntered)
# self.namePromptLayout.addWidget(self.nameLabel)
# self.namePromptLayout.addWidget(self.nameText)
# self.namePromptLayout.addWidget(self.nameButton)
# self.namePrompt.exec_()
# else:
# self.parameters['UserName'] = userName
#
# if self.piradsFormURL is None or self.piradsFormURL == '':
# # prompt the user for the review form
# # Note: it is expected that the module uses the form of the structure as
# # in http://goo.gl/nT1z4L. The known structure of the form is used to
# # pre-populate the fields corresponding to readerName, studyName and
# # lesionID.
# self.URLPrompt = qt.QDialog()
# self.URLPromptLayout = qt.QVBoxLayout()
# self.URLPrompt.setLayout(self.URLPromptLayout)
# self.URLLabel = qt.QLabel('Enter PI-RADS review form URL:', self.URLPrompt)
# # replace this if you are using a different form
# self.URLText = qt.QLineEdit(self.PIRADS_VIEWFORM_URL)
# self.URLButton = qt.QPushButton('OK', self.URLPrompt)
# self.URLButton.connect('clicked()', self.onPIRADSURLEntered)
# self.URLPromptLayout.addWidget(self.URLLabel)
# self.URLPromptLayout.addWidget(self.URLText)
# self.URLPromptLayout.addWidget(self.URLButton)
# self.URLPrompt.exec_()
#
# if self.qaFormURL is None or self.qaFormURL == '':
# # prompt the user for the review form
# # Note: it is expected that the module uses the form of the structure as
# # in http://goo.gl/nT1z4L. The known structure of the form is used to
# # pre-populate the fields corresponding to readerName, studyName and
# # lesionID.
# self.URLPrompt = qt.QDialog()
# self.URLPromptLayout = qt.QVBoxLayout()
# self.URLPrompt.setLayout(self.URLPromptLayout)
# self.URLLabel = qt.QLabel('Enter QA review form URL:', self.URLPrompt)
# # replace this if you are using a different form
# self.URLText = qt.QLineEdit(self.QA_VIEWFORM_URL)
# self.URLButton = qt.QPushButton('OK', self.URLPrompt)
# self.URLButton.connect('clicked()', self.onQAURLEntered)
# self.URLPromptLayout.addWidget(self.URLLabel)
# self.URLPromptLayout.addWidget(self.URLText)
# self.URLPromptLayout.addWidget(self.URLButton)
# self.URLPrompt.exec_()
#
# '''
# # ask where is the input
# if inputLocation == None or inputLocation == '':
# self.dirPrompt = qt.QDialog()
# self.dirPromptLayout = qt.QVBoxLayout()
# self.dirPrompt.setLayout(self.dirPromptLayout)
# self.dirLabel = qt.QLabel('Choose the directory with the input data:', self.dirPrompt)
# self.dirButton = ctk.ctkDirectoryButton(self.dirPrompt)
# self.dirButtonDone = qt.QPushButton('OK', self.dirPrompt)
# self.dirButtonDone.connect('clicked()', self.onInputDirEntered)
# self.dirPromptLayout.addWidget(self.dirLabel)
# self.dirPromptLayout.addWidget(self.dirButton)
# self.dirPromptLayout.addWidget(self.dirButtonDone)
# self.dirPrompt.exec_()
# else:
# self.parameters['InputLocation'] = inputLocation
# logging.debug('Setting inputlocation in settings to '+inputLocation)
# # ask where to keep the results
# if resultsLocation == None or resultsLocation == '':
# self.dirPrompt = qt.QDialog()
# self.dirPromptLayout = qt.QVBoxLayout()
# self.dirPrompt.setLayout(self.dirPromptLayout)
# self.dirLabel = qt.QLabel('Choose the directory to store the results:', self.dirPrompt)
# self.dirButton = ctk.ctkDirectoryButton(self.dirPrompt)
# self.dirButtonDone = qt.QPushButton('OK', self.dirPrompt)
# self.dirButtonDone.connect('clicked()', self.onResultsDirEntered)
# self.dirPromptLayout.addWidget(self.dirLabel)
# self.dirPromptLayout.addWidget(self.dirButton)
# self.dirPromptLayout.addWidget(self.dirButtonDone)
# self.dirPrompt.exec_()
# else:
# self.parameters['ResultsLocation'] = resultsLocation
# '''
def checkAndSetLUT(self):
# Default to module color table
# self.terminologyFile = os.path.join(self.resourcesPath, "SegmentationCategoryTypeModifier-mpReview.json")
# if self.terminologyFile is None:
if not hasattr(self,'terminologyFile'):
self.terminologyFile = os.path.join(self.resourcesPath, "SegmentationCategoryTypeModifier-mpReview.json")
else:
print('self.terminologyFilePathLineEdit.currentPath: ' + str(self.terminologyFilePathLineEdit.currentPath))
if not self.terminologyFilePathLineEdit.currentPath:
self.terminologyFile = os.path.join(self.resourcesPath, "SegmentationCategoryTypeModifier-mpReview.json")
print('self.terminologyFile: ' + str(self.terminologyFile))
self.customLUTInfoIcon.show()
self.customLUTInfoIcon.toolTip = 'Using Default Terminology'
# # Check for custom LUT
# terminologyFileLoc = os.path.join(self.inputDataDir, 'SETTINGS', self.inputDataDir.split(os.sep)[-1] + '-terminology.json')
# logging.debug('Checking for lookup table at : ' + terminologyFileLoc)
# if os.path.isfile(terminologyFileLoc):
# # use custom color table
# self.terminologyFile = terminologyFileLoc
# self.customLUTInfoIcon.toolTip = 'Project-Specific terminology Found'
# Do some basic checking on the terminology file, if specific fields exist
f = open(self.terminologyFile)
jsonData = json.load(f)
# check that
if ("SegmentationCategoryTypeContextName" not in jsonData):
print('Field SegmentationCategoryTypeContextName does not exist in json file, using default terminology')
self.terminologyFile = os.path.join(self.resourcesPath, "SegmentationCategoryTypeModifier-mpReview.json")
f = open(self.terminologyFile)
jsonData = json.load(f)
if ("SegmentationCodes" not in jsonData):
print('Field SegmentationCodes does not exist in json file, using default terminology')
self.terminologyFile = os.path.join(self.resourcesPath, "SegmentationCategoryTypeModifier-mpReview.json")
f = open(self.terminologyFile)
jsonData = json.load(f)
jsonData2 = jsonData['SegmentationCodes']
if ("Category" not in jsonData2):
print("Field Category does not exist in the SegmentationCodes, using default terminology")
self.terminologyFile = os.path.join(self.resourcesPath, "SegmentationCategoryTypeModifier-mpReview.json")
f = open(self.terminologyFile)
jsonData = json.load(f)
jsonData2 = jsonData['SegmentationCodes']
jsonData3 = jsonData2['Category'][0]['Type']
# check that each dictionary has the four fields: "CodeMeaning", "CodingSchemeDesignator", "CodeValue" and
# "recommendedDisplayRGBValue"
for m in range(0,len(jsonData3)):
if (("CodeMeaning" not in jsonData3[m]) or
("CodingSchemeDesignator" not in jsonData3[m]) or
("CodeValue" not in jsonData3[m]) or
("recommendedDisplayRGBValue" not in jsonData3[m])):
print("One or more of the four required fields CodeMeaning, CodingSchemeDesignator, CodeValue and recommendedDisplayRGBValue missing from an entry, using default terminology")
self.terminologyFile = os.path.join(self.resourcesPath, "SegmentationCategoryTypeModifier-mpReview.json")