From 055fdc2427d6313e4b1c11cff067a6f9e4d97fa2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Douglas=20Samuel=20Gon=C3=A7alves?= Date: Mon, 20 Nov 2023 22:02:41 -0300 Subject: [PATCH] Mark translatable strings MONAILabel 3D Slicer Extension (#1595) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Mark MONAILabel Extension Signed-off-by: Douglas Samuel Gonçalves * Fix pre commit errors. Signed-off-by: Douglas Samuel Gonçalves --------- Signed-off-by: Douglas Samuel Gonçalves --- plugins/slicer/MONAILabel/MONAILabel.py | 219 ++++++++++++++---------- 1 file changed, 125 insertions(+), 94 deletions(-) diff --git a/plugins/slicer/MONAILabel/MONAILabel.py b/plugins/slicer/MONAILabel/MONAILabel.py index 5c232171b..df0ee1620 100644 --- a/plugins/slicer/MONAILabel/MONAILabel.py +++ b/plugins/slicer/MONAILabel/MONAILabel.py @@ -28,6 +28,8 @@ import vtk import vtkSegmentationCore from MONAILabelLib import GenericAnatomyColors, MONAILabelClient +from slicer.i18n import tr as _ +from slicer.i18n import translate from slicer.ScriptedLoadableModule import * from slicer.util import VTKObservationMixin @@ -35,17 +37,21 @@ class MONAILabel(ScriptedLoadableModule): def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) - self.parent.title = "MONAILabel" - self.parent.categories = ["Active Learning"] + self.parent.title = _("MONAILabel") + self.parent.categories = [translate("qSlicerAbstractCoreModule", "Active Learning")] self.parent.dependencies = [] self.parent.contributors = ["NVIDIA, KCL"] - self.parent.helpText = """ + self.parent.helpText = _( + """ Active Learning solution. See more information in module documentation. """ - self.parent.acknowledgementText = """ + ) + self.parent.acknowledgementText = _( + """ Developed by NVIDIA, KCL """ + ) # Additional initialization step after application startup is complete slicer.app.connect("startupCompleted()", self.initializeAfterStartup) @@ -62,39 +68,39 @@ def __init__(self, parent): # settings groupBox = ctk.ctkCollapsibleGroupBox() - groupBox.title = "MONAI Label Server" + groupBox.title = _("MONAI Label Server") groupLayout = qt.QFormLayout(groupBox) serverUrl = qt.QLineEdit() - groupLayout.addRow("Server address:", serverUrl) + groupLayout.addRow(_("Server address:"), serverUrl) parent.registerProperty("MONAILabel/serverUrl", serverUrl, "text", str(qt.SIGNAL("textChanged(QString)"))) serverUrlHistory = qt.QLineEdit() - groupLayout.addRow("Server address history:", serverUrlHistory) + groupLayout.addRow(_("Server address history:"), serverUrlHistory) parent.registerProperty( "MONAILabel/serverUrlHistory", serverUrlHistory, "text", str(qt.SIGNAL("textChanged(QString)")) ) fileExtension = qt.QLineEdit() fileExtension.setText(".nii.gz") - fileExtension.toolTip = "Default extension for uploading images/labels" - groupLayout.addRow("File Extension:", fileExtension) + fileExtension.toolTip = _("Default extension for uploading images/labels") + groupLayout.addRow(_("File Extension:"), fileExtension) parent.registerProperty( "MONAILabel/fileExtension", fileExtension, "text", str(qt.SIGNAL("textChanged(QString)")) ) clientId = qt.QLineEdit() - clientId.setText("user-xyz") - clientId.toolTip = "Client/User ID that will be sent to MONAI Label server for reference" - groupLayout.addRow("Client/User-ID:", clientId) + clientId.setText(_("user-xyz")) + clientId.toolTip = _("Client/User ID that will be sent to MONAI Label server for reference") + groupLayout.addRow(_("Client/User-ID:"), clientId) parent.registerProperty("MONAILabel/clientId", clientId, "text", str(qt.SIGNAL("textChanged(QString)"))) autoRunSegmentationCheckBox = qt.QCheckBox() autoRunSegmentationCheckBox.checked = False - autoRunSegmentationCheckBox.toolTip = ( + autoRunSegmentationCheckBox.toolTip = _( "Enable this option to auto run segmentation if pre-trained model exists when Next Sample is fetched" ) - groupLayout.addRow("Auto-Run Pre-Trained Model:", autoRunSegmentationCheckBox) + groupLayout.addRow(_("Auto-Run Pre-Trained Model:"), autoRunSegmentationCheckBox) parent.registerProperty( "MONAILabel/autoRunSegmentationOnNextSample", ctk.ctkBooleanMapper(autoRunSegmentationCheckBox, "checked", str(qt.SIGNAL("toggled(bool)"))), @@ -104,8 +110,8 @@ def __init__(self, parent): autoFetchNextSampleCheckBox = qt.QCheckBox() autoFetchNextSampleCheckBox.checked = False - autoFetchNextSampleCheckBox.toolTip = "Enable this option to fetch Next Sample after saving the label" - groupLayout.addRow("Auto-Fetch Next Sample:", autoFetchNextSampleCheckBox) + autoFetchNextSampleCheckBox.toolTip = _("Enable this option to fetch Next Sample after saving the label") + groupLayout.addRow(_("Auto-Fetch Next Sample:"), autoFetchNextSampleCheckBox) parent.registerProperty( "MONAILabel/autoFetchNextSample", ctk.ctkBooleanMapper(autoFetchNextSampleCheckBox, "checked", str(qt.SIGNAL("toggled(bool)"))), @@ -115,8 +121,8 @@ def __init__(self, parent): autoUpdateModelCheckBox = qt.QCheckBox() autoUpdateModelCheckBox.checked = False - autoUpdateModelCheckBox.toolTip = "Enable this option to auto update model after submitting the label" - groupLayout.addRow("Auto-Update Model:", autoUpdateModelCheckBox) + autoUpdateModelCheckBox.toolTip = _("Enable this option to auto update model after submitting the label") + groupLayout.addRow(_("Auto-Update Model:"), autoUpdateModelCheckBox) parent.registerProperty( "MONAILabel/autoUpdateModelV2", ctk.ctkBooleanMapper(autoUpdateModelCheckBox, "checked", str(qt.SIGNAL("toggled(bool)"))), @@ -126,11 +132,12 @@ 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) + + groupLayout.addRow(_("Ask For User Name:"), askForUserNameCheckBox) parent.registerProperty( "MONAILabel/askForUserName", ctk.ctkBooleanMapper(askForUserNameCheckBox, "checked", str(qt.SIGNAL("toggled(bool)"))), @@ -140,8 +147,8 @@ def __init__(self, parent): allowOverlapCheckBox = qt.QCheckBox() allowOverlapCheckBox.checked = False - allowOverlapCheckBox.toolTip = "Enable this option to allow overlapping segmentations" - groupLayout.addRow("Allow Overlapping Segmentations:", allowOverlapCheckBox) + allowOverlapCheckBox.toolTip = _("Enable this option to allow overlapping segmentations") + groupLayout.addRow(_("Allow Overlapping Segmentations:"), allowOverlapCheckBox) parent.registerProperty( "MONAILabel/allowOverlappingSegments", ctk.ctkBooleanMapper(allowOverlapCheckBox, "checked", str(qt.SIGNAL("toggled(bool)"))), @@ -152,8 +159,8 @@ def __init__(self, parent): originalLabelCheckBox = qt.QCheckBox() originalLabelCheckBox.checked = True - originalLabelCheckBox.toolTip = "Enable this option to first read original label (predictions)" - groupLayout.addRow("Original Labels:", originalLabelCheckBox) + originalLabelCheckBox.toolTip = _("Enable this option to first read original label (predictions)") + groupLayout.addRow(_("Original Labels:"), originalLabelCheckBox) parent.registerProperty( "MONAILabel/originalLabel", ctk.ctkBooleanMapper(originalLabelCheckBox, "checked", str(qt.SIGNAL("toggled(bool)"))), @@ -163,8 +170,8 @@ def __init__(self, parent): developerModeCheckBox = qt.QCheckBox() developerModeCheckBox.checked = True - developerModeCheckBox.toolTip = "Enable this option to find options tab etc..." - groupLayout.addRow("Developer Mode:", developerModeCheckBox) + developerModeCheckBox.toolTip = _("Enable this option to find options tab etc...") + groupLayout.addRow(_("Developer Mode:"), developerModeCheckBox) parent.registerProperty( "MONAILabel/developerMode", ctk.ctkBooleanMapper(developerModeCheckBox, "checked", str(qt.SIGNAL("toggled(bool)"))), @@ -174,8 +181,8 @@ def __init__(self, parent): showSegmentsIn3DCheckBox = qt.QCheckBox() showSegmentsIn3DCheckBox.checked = False - showSegmentsIn3DCheckBox.toolTip = "Enable this option to show segments in 3D (slow) after mask update..." - groupLayout.addRow("Show Segments In 3D:", showSegmentsIn3DCheckBox) + showSegmentsIn3DCheckBox.toolTip = _("Enable this option to show segments in 3D (slow) after mask update...") + groupLayout.addRow(_("Show Segments In 3D:"), showSegmentsIn3DCheckBox) parent.registerProperty( "MONAILabel/showSegmentsIn3D", ctk.ctkBooleanMapper(showSegmentsIn3DCheckBox, "checked", str(qt.SIGNAL("toggled(bool)"))), @@ -190,8 +197,10 @@ 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." + ) ) @@ -288,13 +297,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() @@ -324,18 +333,18 @@ def setup(self): # brush and eraser icon from: https://tablericons.com/ self.ui.scribblesMethodSelector.connect("currentIndexChanged(int)", self.updateParameterNodeFromGUI) self.ui.paintScribblesButton.setIcon(self.icon("paint.png")) - self.ui.paintScribblesButton.setToolTip("Paint scribbles for selected scribble layer") + self.ui.paintScribblesButton.setToolTip(_("Paint scribbles for selected scribble layer")) self.ui.eraseScribblesButton.setIcon(self.icon("eraser.png")) - self.ui.eraseScribblesButton.setToolTip("Erase scribbles for selected scribble layer") + self.ui.eraseScribblesButton.setToolTip(_("Erase scribbles for selected scribble layer")) self.ui.updateScribblesButton.setIcon(self.icon("segment.png")) self.ui.updateScribblesButton.setToolTip( - "Update label by sending scribbles to server to apply selected post processing method" + _("Update label by sending scribbles to server to apply selected post processing method") ) self.ui.brushSizeSlider.connect("valueChanged(double)", self.updateBrushSize) - self.ui.brushSizeSlider.setToolTip("Change brush size for scribbles tool") + self.ui.brushSizeSlider.setToolTip(_("Change brush size for scribbles tool")) self.ui.brush3dCheckbox.stateChanged.connect(self.on3dBrushCheckbox) - self.ui.brush3dCheckbox.setToolTip("Use 3D brush to paint/erase in multiple slices in 3D") + self.ui.brush3dCheckbox.setToolTip(_("Use 3D brush to paint/erase in multiple slices in 3D")) self.ui.updateScribblesButton.clicked.connect(self.onUpdateScribbles) self.ui.paintScribblesButton.clicked.connect(self.onPaintScribbles) self.ui.eraseScribblesButton.clicked.connect(self.onEraseScribbles) @@ -362,10 +371,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() @@ -374,8 +383,8 @@ def setup(self): if slicer.util.settingsValue("MONAILabel/askForUserName", False, converter=slicer.util.toBool): text = qt.QInputDialog().getText( self.parent, - "User Name", - "Please enter your name:", + _("User Name"), + _("Please enter your name:"), qt.QLineEdit.Normal, slicer.util.settingsValue("MONAILabel/clientId", None), ) @@ -479,7 +488,9 @@ def monitorTraining(self): percent = max(1, 100 * current / total) if self.ui.trainingProgressBar.value != percent: self.ui.trainingProgressBar.setValue(percent) - self.ui.trainingProgressBar.setToolTip(f"{current}/{total} epoch is completed") + self.ui.trainingProgressBar.setToolTip( + _("{current}/{total} epoch is completed").format(current=current, total=total) + ) dice = train_stats.get("best_metric", 0) self.updateAccuracyBar(dice) @@ -489,7 +500,7 @@ def monitorTraining(self): self.ui.trainingProgressBar.setValue(100) self.timer.stop() self.timer = None - self.ui.trainingProgressBar.setToolTip(f"Training: {status.get('status', 'DONE')}") + self.ui.trainingProgressBar.setToolTip(_("Training: {status}").format(status=status.get("status", "DONE"))) self.ui.trainingButton.setEnabled(True) self.ui.stopTrainingButton.setEnabled(False) @@ -587,7 +598,9 @@ def updateGUIFromParameterNode(self, caller=None, event=None): current = datastore_stats.get("completed", 0) total = datastore_stats.get("total", 0) self.ui.activeLearningProgressBar.setValue(current / max(total, 1) * 100) - self.ui.activeLearningProgressBar.setToolTip(f"{current}/{total} samples are labeled") + self.ui.activeLearningProgressBar.setToolTip( + _("{current}/{total} samples are labeled").format(current=current, total=total) + ) train_stats = self.info.get("train_stats", {}) train_stats = next(iter(train_stats.values())) if train_stats else train_stats @@ -859,7 +872,7 @@ def updateAccuracyBar(self, dice): "QProgressBar::chunk {background-color: " "qlineargradient(x0: 0, x2: 1, " + ",".join(css) + ")}" ) - self.ui.accuracyProgressBar.setToolTip(f"Accuracy: {dice:.4f}") + self.ui.accuracyProgressBar.setToolTip(_("Accuracy: {value}").format(value=f"{dice:.4f}")) def getParamsFromConfig(self, section, name): self.invalidateConfigTable() @@ -1002,7 +1015,7 @@ def onSelectOptionsName(self, index, caller=None, event=None): def onSelectScribLabel(self, caller=None, event=None): if self.scribblesLayersPresent() and not self.ignoreScribblesLabelChangeEvent: if not slicer.util.confirmOkCancelDisplay( - "This will clear current scribbles session.\n" "Are you sure to continue?" + _("This will clear current scribbles session.\n" "Are you sure to continue?") ): # undo changes to combobox currentScribLabel = self._parameterNode.GetParameter("CurrentScribLabel") @@ -1073,16 +1086,18 @@ def fetchInfo(self, showInfo=False): self.info = info if self.info.get("config"): slicer.util.errorDisplay( - "Please upgrade the monai server to latest version", + _("Please upgrade the monai server to latest version"), detailedText=traceback.format_exc(), ) return except BaseException as e: msg = f"Message:: {e.msg}" if hasattr(e, "msg") else "" slicer.util.errorDisplay( - "Failed to fetch models from remote server. " - "Make sure server address is correct and /info/ " - f"is accessible in browser.\n{msg}", + _( + "Failed to fetch models from remote server. " + "Make sure server address is correct and /info/ " + "is accessible in browser.\n{message}" + ).format(message=msg), detailedText=traceback.format_exc(), ) return @@ -1116,12 +1131,12 @@ def fetchInfo(self, showInfo=False): def setProgressBarLabelText(self, label): if not self.progressBar: - self.progressBar = slicer.util.createProgressDialog(windowTitle="Wait...", maximum=100) + self.progressBar = slicer.util.createProgressDialog(windowTitle=_("Wait..."), maximum=100) self.progressBar.labelText = label def reportProgress(self, progressPercentage): if not self.progressBar: - self.progressBar = slicer.util.createProgressDialog(windowTitle="Wait...", maximum=100) + self.progressBar = slicer.util.createProgressDialog(windowTitle=_("Wait..."), maximum=100) self.progressBar.show() self.progressBar.activateWindow() self.progressBar.setValue(progressPercentage) @@ -1137,7 +1152,7 @@ def onTraining(self): model = self.ui.trainerBox.currentText if not model: slicer.util.errorDisplay( - "No Model selected is to run the training", detailedText=traceback.format_exc() + _("No Model selected is to run the training"), detailedText=traceback.format_exc() ) return @@ -1145,24 +1160,24 @@ def onTraining(self): status = self.logic.train_start(model, params) self.ui.trainingProgressBar.setValue(1) - self.ui.trainingProgressBar.setToolTip("Training: STARTED") + self.ui.trainingProgressBar.setToolTip(_("Training: STARTED")) time.sleep(1) self.updateGUIFromParameterNode() except BaseException as e: msg = f"Message:: {e.msg}" if hasattr(e, "msg") else "" slicer.util.errorDisplay( - f"Failed to run training in MONAI Label Server.\n{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) @@ -1173,7 +1188,7 @@ def onStopTraining(self): start = time.time() status = None if not slicer.util.confirmOkCancelDisplay( - "This will kill/stop current Training task. Are you sure to continue?" + _("This will kill/stop current Training task. Are you sure to continue?") ): return @@ -1184,18 +1199,18 @@ def onStopTraining(self): except BaseException as e: msg = f"Message:: {e.msg}" if hasattr(e, "msg") else "" slicer.util.errorDisplay( - f"Failed to stop Training Task.\n{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) @@ -1215,8 +1230,10 @@ def onNextSampleButton(self): if self._volumeNode or len(slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode")): if not slicer.util.confirmOkCancelDisplay( - "This will close current scene. Please make sure you have saved your current work.\n" - "Are you sure to continue?" + _( + "This will close current scene. Please make sure you have saved your current work.\n" + "Are you sure to continue?" + ) ): return self.onResetScribbles() @@ -1229,15 +1246,17 @@ 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)) logging.debug(sample) if not sample.get("id"): slicer.util.warningDisplay( - "Unlabeled samples or images not found at server.\n" - "Instead please go to File -> Add Data to load image." + _( + "Unlabeled samples or images not found at server.\n" + "Instead please go to File -> Add Data to load image." + ) ) return @@ -1296,7 +1315,7 @@ def onNextSampleButton(self): except BaseException as e: msg = f"Message:: {e.msg}" if hasattr(e, "msg") else "" slicer.util.errorDisplay( - f"Failed to fetch Sample from MONAI Label Server.\n{msg}", + _("Failed to fetch Sample from MONAI Label Server.\n{message}").format(message=msg), detailedText=traceback.format_exc(), ) finally: @@ -1341,10 +1360,12 @@ 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" - "Click 'OK' to proceed with the segmentation.\n" - "Click 'Cancel' to not upload any data and cancel segmentation.\n".format(self.serverUrl()), + _( + "Source volume - without any additional patient information -" + " 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", ) @@ -1385,20 +1406,20 @@ 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( - f"Failed to upload volume to Server.\n{msg}", + _("Failed to upload volume to Server.\n{message}").format(message=msg), detailedText=traceback.format_exc(), ) return False def onImportLabel(self): if not self.ui.labelPathLineEdit.currentPath or not os.path.exists(self.ui.labelPathLineEdit.currentPath): - slicer.util.warningDisplay("Label File not selected") + slicer.util.warningDisplay(_("Label File not selected")) return try: @@ -1407,7 +1428,7 @@ def onImportLabel(self): qt.QApplication.restoreOverrideCursor() except: qt.QApplication.restoreOverrideCursor() - slicer.util.errorDisplay("Failed to import label", detailedText=traceback.format_exc()) + slicer.util.errorDisplay(_("Failed to import label"), detailedText=traceback.format_exc()) def onSaveLabel(self): start = time.time() @@ -1477,7 +1498,7 @@ def onSaveLabel(self): except BaseException as e: msg = f"Message:: {e.msg}" if hasattr(e, "msg") else "" slicer.util.errorDisplay( - f"Failed to save Label to MONAI Label Server.\n{msg}", + _("Failed to save Label to MONAI Label Server.\n{message}").format(message=msg), detailedText=traceback.format_exc(), ) finally: @@ -1488,7 +1509,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): @@ -1533,7 +1554,7 @@ def onClickSegmentation(self): except BaseException as e: msg = f"Message:: {e.msg}" if hasattr(e, "msg") else "" slicer.util.errorDisplay( - f"Failed to run inference in MONAI Label Server.\n{msg}", + _("Failed to run inference in MONAI Label Server.\n{message}").format(message=msg), detailedText=traceback.format_exc(), ) finally: @@ -1550,12 +1571,12 @@ def onUpdateDeepgrow(self): def onClickDeepgrow(self, current_point, skip_infer=False): model = self.ui.deepgrowModelSelector.currentText if not model: - slicer.util.warningDisplay("Please select a deepgrow model") + slicer.util.warningDisplay(_("Please select a deepgrow model")) return - _, segment = self.currentSegment() + segment_id, segment = self.currentSegment() if not segment: - slicer.util.warningDisplay("Please add the required label to run deepgrow") + slicer.util.warningDisplay(_("Please add the required label to run deepgrow")) return foreground_all = self.getControlPointsXYZ(self.dgPositivePointListNode, "foreground") @@ -1572,7 +1593,9 @@ def onClickDeepgrow(self, current_point, skip_infer=False): start = time.time() label = segment.GetName() - operationDescription = f"Run Deepgrow for segment: {label}; model: {model}; 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: @@ -1938,7 +1961,7 @@ def onUpdateScribbles(self): params = self.getParamsFromConfig("infer", scribblesMethod) params.update({"roi": selected_roi}) params.update({"label_info": label_info}) - _, segment = self.currentScribSegment() + segment_id, segment = self.currentScribSegment() selected_label_name = segment.GetName() params.update({"selected_label_name": selected_label_name}) @@ -1953,7 +1976,9 @@ def onUpdateScribbles(self): except BaseException as e: msg = f"Message:: {e.msg}" if hasattr(e, "msg") else "" slicer.util.errorDisplay( - f"Failed to post process label on MONAI Label Server using {scribblesMethod}.\n{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: @@ -2314,7 +2339,7 @@ def train_stop(self): class LoginDialog(qt.QDialog): def __init__(self, username, password, resourcePath): super().__init__() - self.setWindowTitle("User Login") + self.setWindowTitle(_("User Login")) layout = qt.QVBoxLayout() uiWidget = slicer.util.loadUI(resourcePath("UI/LoginDialog.ui")) @@ -2340,3 +2365,9 @@ def runTest(self): def test_MONAILabel1(self): self.delayDisplay("Test passed") + + +INFER = "INFER" +TRAIN = "TRAIN" +ACTIVELEARNING = "ACTIVELEARNING" +SCORING = "SCORING"