Skip to content

Commit

Permalink
Mark MONAILabel Extension
Browse files Browse the repository at this point in the history
Signed-off-by: Douglas Samuel Gonçalves <[email protected]>
  • Loading branch information
DouSam committed Nov 20, 2023
1 parent d367422 commit a525f33
Showing 1 changed file with 53 additions and 56 deletions.
109 changes: 53 additions & 56 deletions plugins/slicer/MONAILabel/MONAILabel.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,11 @@ def __init__(self, parent):

askForUserNameCheckBox = qt.QCheckBox()
askForUserNameCheckBox.checked = False
askForUserNameCheckBox.toolTip = (
_("""Enable this option to ask for the user name every time the MONAILabel
extension is loaded for the first time""")
)
askForUserNameCheckBox.toolTip = _(
"Enable this option to ask for the user name every time the MONAILabel"
"extension is loaded for the first time"
)

groupLayout.addRow(_("Ask For User Name:"), askForUserNameCheckBox)
parent.registerProperty(
"MONAILabel/askForUserName",
Expand Down Expand Up @@ -192,8 +193,8 @@ def onUpdateAllowOverlap(self):
if slicer.util.settingsValue("MONAILabel/allowOverlappingSegments", True, converter=slicer.util.toBool):
if slicer.util.settingsValue("MONAILabel/fileExtension", None) != ".seg.nrrd":
slicer.util.warningDisplay(
_("""Overlapping segmentations are only available with the '.seg.nrrd' file extension!
Consider changing MONAILabel file extension.""")
_("Overlapping segmentations are only available with the '.seg.nrrd' file extension!"
"Consider changing MONAILabel file extension.")
)


Expand Down Expand Up @@ -290,13 +291,13 @@ def setup(self):
self.ui.importLabelButton.setIcon(self.icon("download.png"))

self.ui.dgPositiveControlPointPlacementWidget.setMRMLScene(slicer.mrmlScene)
self.ui.dgPositiveControlPointPlacementWidget.placeButton().toolTip = _("Select +ve points")
self.ui.dgPositiveControlPointPlacementWidget.placeButton().toolTip = _("Select positive points")
self.ui.dgPositiveControlPointPlacementWidget.buttonsVisible = False
self.ui.dgPositiveControlPointPlacementWidget.placeButton().show()
self.ui.dgPositiveControlPointPlacementWidget.deleteButton().show()

self.ui.dgNegativeControlPointPlacementWidget.setMRMLScene(slicer.mrmlScene)
self.ui.dgNegativeControlPointPlacementWidget.placeButton().toolTip = _("Select -ve points")
self.ui.dgNegativeControlPointPlacementWidget.placeButton().toolTip = _("Select negative points")
self.ui.dgNegativeControlPointPlacementWidget.buttonsVisible = False
self.ui.dgNegativeControlPointPlacementWidget.placeButton().show()
self.ui.dgNegativeControlPointPlacementWidget.deleteButton().show()
Expand Down Expand Up @@ -364,10 +365,10 @@ def setup(self):
self.ui.embeddedSegmentEditorWidget.setMRMLSegmentEditorNode(self.logic.get_segment_editor_node())

# options section
self.ui.optionsSection.addItem(_("infer"))
self.ui.optionsSection.addItem(_("train"))
self.ui.optionsSection.addItem(_("activelearning"))
self.ui.optionsSection.addItem(_("scoring"))
self.ui.optionsSection.addItem(_("infer"), INFER)
self.ui.optionsSection.addItem(_("train"), TRAIN)
self.ui.optionsSection.addItem(_("activelearning"), ACTIVELEARNING)
self.ui.optionsSection.addItem(_("scoring"), SCORING)

self.initializeParameterNode()
self.updateServerUrlGUIFromSettings()
Expand Down Expand Up @@ -487,8 +488,7 @@ def monitorTraining(self):
self.updateAccuracyBar(dice)
return

logging.info("Training completed")
#print("Training completed")
print("Training completed")
self.ui.trainingProgressBar.setValue(100)
self.timer.stop()
self.timer = None
Expand Down Expand Up @@ -862,7 +862,7 @@ def updateAccuracyBar(self, dice):
"QProgressBar::chunk {background-color: "
"qlineargradient(x0: 0, x2: 1, " + ",".join(css) + ")}"
)
self.ui.accuracyProgressBar.setToolTip(_("Accuracy: {dice:.4f}").format(dice=dice))
self.ui.accuracyProgressBar.setToolTip(_("Accuracy: {value}").format(value=f"{dice:.4f}"))

def getParamsFromConfig(self, section, name):
self.invalidateConfigTable()
Expand Down Expand Up @@ -1085,7 +1085,7 @@ def fetchInfo(self, showInfo=False):
slicer.util.errorDisplay(
_("Failed to fetch models from remote server. "
"Make sure server address is correct and <server_uri>/info/ "
"is accessible in browser.\n{msg}").format(msg=msg),
"is accessible in browser.\n{message}").format(message=msg),
detailedText=traceback.format_exc(),
)
return
Expand Down Expand Up @@ -1155,17 +1155,17 @@ def onTraining(self):
except BaseException as e:
msg = f"Message:: {e.msg}" if hasattr(e, "msg") else ""
slicer.util.errorDisplay(
_("Failed to run training in MONAI Label Server.\n{msg}").format(msg=msg),
_("Failed to run training in MONAI Label Server.\n{message}").format(message=msg),
detailedText=traceback.format_exc(),
)
finally:
qt.QApplication.restoreOverrideCursor()

if status:
msg = _("ID: {}\nStatus: {}\nStart Time: {}\n").format(
status.get("id"),
status.get("status"),
status.get("start_ts"),
msg = _("ID: {id}\nStatus: {status}\nStart Time: {start_time}\n").format(
id=status.get("id"),
status=status.get("status"),
start_time=status.get("start_ts"),
)
# slicer.util.infoDisplay(msg, detailedText=json.dumps(status, indent=2))
logging.info(msg)
Expand All @@ -1187,18 +1187,18 @@ def onStopTraining(self):
except BaseException as e:
msg = f"Message:: {e.msg}" if hasattr(e, "msg") else ""
slicer.util.errorDisplay(
_("Failed to stop Training Task.\n{msg}").format(msg=msg),
_("Failed to stop Training Task.\n{message}").format(message=msg),
detailedText=traceback.format_exc(),
)
finally:
qt.QApplication.restoreOverrideCursor()

if status:
msg = _("Status: {}\nStart Time: {}\nEnd Time: {}\nResult: {}").format(
status.get("status"),
status.get("start_ts"),
status.get("end_ts"),
status.get("result", status.get("details", [])[-1]),
msg = _("Status: {status}\nStart Time: {start_time}\nEnd Time: {end_time}\nResult: {result}").format(
status=status.get("status"),
start_time=status.get("start_ts"),
end_time=status.get("end_ts"),
result=status.get("result", status.get("details", [])[-1]),
)
# slicer.util.infoDisplay(msg, detailedText=json.dumps(status, indent=2))
logging.info(msg)
Expand Down Expand Up @@ -1232,7 +1232,7 @@ def onNextSampleButton(self):
self.updateServerSettings()
strategy = self.ui.strategyBox.currentText
if not strategy:
slicer.util.errorDisplay(_("No Strategy Found/Selected\t"))
slicer.util.errorDisplay(_("No Strategy Found/Selected"))
return

sample = self.logic.next_sample(strategy, self.getParamsFromConfig("activelearning", strategy))
Expand Down Expand Up @@ -1289,19 +1289,17 @@ def onNextSampleButton(self):
# ext = datastore['objects'][image_id]['labels']['original']['ext']
maskFile = self.logic.download_label(image_id, "original")
self.updateSegmentationMask(maskFile, list(labels))
#print("Original label uploaded! ")
logging.info("Original label uploaded! ")
print("Original label uploaded! ")

except:
#print("Original label not found ... ")
logging.error("Original label not found ... ")
print("Original label not found ... ")

self.initSample(sample)

except BaseException as e:
msg = f"Message:: {e.msg}" if hasattr(e, "msg") else ""
slicer.util.errorDisplay(
_("Failed to fetch Sample from MONAI Label Server.\n{msg}").format(msg=msg),
_("Failed to fetch Sample from MONAI Label Server.\n{message}").format(message=msg),
detailedText=traceback.format_exc(),
)
finally:
Expand Down Expand Up @@ -1347,7 +1345,7 @@ def initSample(self, sample, autosegment=True):
def getPermissionForImageDataUpload(self):
return slicer.util.confirmOkCancelDisplay(
_("Source volume - without any additional patient information -"
" will be sent to remote data processing server: {}.\n\n"
" will be sent to remote data processing server: {server_url}.\n\n"
"Click 'OK' to proceed with the segmentation.\n"
"Click 'Cancel' to not upload any data and cancel segmentation.\n").format(self.serverUrl()),
dontShowAgainSettingsKey="MONAILabel/showImageDataSendWarning",
Expand Down Expand Up @@ -1390,13 +1388,13 @@ def onUploadImage(self, init_sample=True, session=False):
qt.QApplication.restoreOverrideCursor()
if session:
slicer.util.errorDisplay(
_("Server Error:: Session creation Failed\nPlease upgrade to latest monailable version (> 0.2.0)"),
_("Server Error:: Session creation Failed\nPlease upgrade to latest monailabel version (> 0.2.0)"),
detailedText=traceback.format_exc(),
)
self.current_sample["session"] = None
else:
slicer.util.errorDisplay(
_("Failed to upload volume to Server.\n{msg}").format(msg=msg),
_("Failed to upload volume to Server.\n{message}").format(message=msg),
detailedText=traceback.format_exc(),
)
return False
Expand Down Expand Up @@ -1477,12 +1475,12 @@ def onSaveLabel(self):
if self.isTrainingRunning(check_only=True):
self.logic.train_stop()
except:
logging.error("Failed to stop training; or already stopped")
logging.info("Failed to stop training; or already stopped")
self.onTraining()
except BaseException as e:
msg = f"Message:: {e.msg}" if hasattr(e, "msg") else ""
slicer.util.errorDisplay(
_("Failed to save Label to MONAI Label Server.\n{msg}").format(msg=msg),
_("Failed to save Label to MONAI Label Server.\n{message}").format(message=msg),
detailedText=traceback.format_exc(),
)
finally:
Expand All @@ -1493,7 +1491,7 @@ def onSaveLabel(self):
slicer.mrmlScene.RemoveNode(labelmapVolumeNode)
if result:
slicer.util.infoDisplay(
_("Label-Mask saved into MONAI Label Server\t\t"), detailedText=json.dumps(result, indent=2)
_("Label-Mask saved into MONAI Label Server"), detailedText=json.dumps(result, indent=2)
)

if slicer.util.settingsValue("MONAILabel/autoFetchNextSample", False, converter=slicer.util.toBool):
Expand Down Expand Up @@ -1527,8 +1525,7 @@ def onClickSegmentation(self):
params = self.getParamsFromConfig("infer", model)

result_file, params = self.logic.infer(model, image_file, params, session_id=self.getSessionId())
#print(f"Result Params for Segmentation: {params}")
logging.info(f"Result Params for Segmentation: {params}")
print(f"Result Params for Segmentation: {params}")

labels = (
params.get("label_names") if params and params.get("label_names") else self.models[model].get("labels")
Expand All @@ -1539,7 +1536,7 @@ def onClickSegmentation(self):
except BaseException as e:
msg = f"Message:: {e.msg}" if hasattr(e, "msg") else ""
slicer.util.errorDisplay(
_("Failed to run inference in MONAI Label Server.\n{msg}").format(msg=msg),
_("Failed to run inference in MONAI Label Server.\n{message}").format(message=msg),
detailedText=traceback.format_exc(),
)
finally:
Expand Down Expand Up @@ -1574,12 +1571,11 @@ def onClickDeepgrow(self, current_point, skip_infer=False):

# use model info "deepgrow" to determine
deepgrow_3d = False if self.models[model].get("dimension", 3) == 2 else True
#print(f"Is DeepGrow 3D: {deepgrow_3d}")
logging.info(f"Is DeepGrow 3D: {deepgrow_3d}")
print(f"Is DeepGrow 3D: {deepgrow_3d}")
start = time.time()

label = segment.GetName()
operationDescription = _("Run Deepgrow for segment: {label}; model: {model}; 3d {deepgrow_3d}").format(label=label, model=model, deepgrow_3d=deepgrow_3d)
operationDescription = _("Run Deepgrow for segment: {label}; model: {model}; 3d {in3d}").format(label=label, model=model, in3d=_("enabled") if deepgrow_3d else _("disabled"))
logging.debug(operationDescription)

if not current_point:
Expand All @@ -1603,8 +1599,7 @@ def onClickDeepgrow(self, current_point, skip_infer=False):
fPosStr = vtk.mutable("")
segment.GetTag("MONAILabel.ForegroundPoints", fPosStr)
pointset = str(fPosStr)
#print(f"{segmentId} => {name} Control points are: {pointset}")
logging.info(f"{segmentId} => {name} Control points are: {pointset}")
print(f"{segmentId} => {name} Control points are: {pointset}")
if fPosStr is not None and len(pointset) > 0:
points = json.loads(pointset)

Expand All @@ -1613,8 +1608,7 @@ def onClickDeepgrow(self, current_point, skip_infer=False):
labels = None
else:
sliceIndex = current_point[2] if current_point else None
#print(f"Slice Index: {sliceIndex}")
logging.info(f"Slice Index: {sliceIndex}")
print(f"Slice Index: {sliceIndex}")

if deepgrow_3d or not sliceIndex:
foreground = foreground_all
Expand All @@ -1636,13 +1630,11 @@ def onClickDeepgrow(self, current_point, skip_infer=False):

params["label"] = label
params.update(self.getParamsFromConfig("infer", model))
#print(f"Request Params for Deepgrow/Deepedit: {params}")
logging.info(f"Request Params for Deepgrow/Deepedit: {params}")
print(f"Request Params for Deepgrow/Deepedit: {params}")

image_file = self.current_sample["id"]
result_file, params = self.logic.infer(model, image_file, params, session_id=self.getSessionId())
#print(f"Result Params for Deepgrow/Deepedit: {params}")
logging.info(f"Result Params for Deepgrow/Deepedit: {params}")
print(f"Result Params for Deepgrow/Deepedit: {params}")
if labels is None:
labels = (
params.get("label_names")
Expand Down Expand Up @@ -1964,7 +1956,7 @@ def onUpdateScribbles(self):
except BaseException as e:
msg = f"Message:: {e.msg}" if hasattr(e, "msg") else ""
slicer.util.errorDisplay(
_("Failed to post process label on MONAI Label Server using {scribblesMethod}.\n{msg}").format(scribblesMethod, msg),
_("Failed to post process label on MONAI Label Server using {scribbles_method}.\n{message}").format(scribbles_method=scribblesMethod, message=msg),
detailedText=traceback.format_exc(),
)
finally:
Expand Down Expand Up @@ -2261,8 +2253,7 @@ def _client(self):
# TODO:: JWT token can be validated (with additional py dependencies) to avoid further calls to server
if not self.auth_token or not mc.auth_valid_token():
try:
#print(f"Fetching new Token for: {self.username}")
logging.info(f"Fetching new Token for: {self.username}")
print(f"Fetching new Token for: {self.username}")
self.auth_token = mc.auth_token(self.username, self.password)
mc.update_auth(self.auth_token)
except:
Expand Down Expand Up @@ -2352,3 +2343,9 @@ def runTest(self):

def test_MONAILabel1(self):
self.delayDisplay("Test passed")


INFER = 'INFER'
TRAIN = 'TRAIN'
ACTIVELEARNING = 'ACTIVELEARNING'
SCORING = 'SCORING'

0 comments on commit a525f33

Please sign in to comment.