### Basic Segmentation Example Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Loads a volume, selects a device, and starts the segmentation process. It then waits for the segmentation to complete. ```python from DentalSegmentatorLib import SegmentationWidget import slicer widget = SegmentationWidget() # Load volume (example using Slicer sample data) import SampleData volume_node = SampleData.SampleDataLogic().downloadDentalSurgery() # Select volume widget.inputSelector.setCurrentNode(volume_node) # Select device widget.deviceComboBox.setCurrentText("cuda") # or "cpu", "mps" # Start segmentation (as if user clicked Apply) widget.onApplyClicked() # Wait for completion (in real application, connect to signal) widget.logic.waitForSegmentationFinished() slicer.app.processEvents() print("Segmentation complete") ``` -------------------------------- ### Complete UI Setup Example Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-utilities.md This example demonstrates how to set up the 3D view and create interactive UI elements like buttons and collapsible sections using the library's utility functions. It shows the integration of view configuration, button creation with callbacks and icons, and adding widgets to a collapsible layout. ```python from DentalSegmentatorLib import ( createButton, addInCollapsibleLayout, set3DViewBackgroundColors, setConventionalWideScreenView, setBoxAndTextVisibilityOnThreeDViews, icon ) import qt # Setup view setConventionalWideScreenView() set3DViewBackgroundColors([1, 1, 1], [1, 1, 1]) setBoxAndTextVisibilityOnThreeDViews(False) # Create buttons main_layout = qt.QVBoxLayout() apply_btn = createButton( "Apply Segmentation", callback=lambda: print("Starting..."), icon=icon("start_icon.png"), toolTip="Run segmentation" ) main_layout.addWidget(apply_btn) # Create collapsible section export_widget = qt.QWidget() export_layout = qt.QVBoxLayout(export_widget) export_layout.addWidget(qt.QLabel("Export options")) addInCollapsibleLayout( export_widget, main_layout, "Export Results", isCollapsed=False ) main_layout.addStretch() ``` -------------------------------- ### onApplyClicked() Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md Initiates the segmentation process, handling necessary installations, downloads, and starting the segmentation. ```APIDOC #### `onApplyClicked()` Main entry point for segmentation. Handles dependency installation, weight download, and segmentation startup. ```python def onApplyClicked(self, * _) ``` **Returns**: None **Throws**: - Shows error dialog if NNUNet module not installed - Shows error dialog if weight download fails **Flow**: 1. Verifies NNUNet module is installed 2. Installs nn-Net if needed 3. Downloads model weights if missing 4. Starts segmentation process **Example**: ```python # Typically called by button click connection # Can be invoked programmatically: widget.onApplyClicked() ``` ``` -------------------------------- ### Manual Weight Installation Script Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/errors.md Provides instructions for manually downloading and installing model weights. This is a fallback when automatic download fails. ```bash # Download weights ZIP from: # https://github.com/gaudot/SlicerDentalSegmentator/releases # Extract to DentalSegmentator module folder: # Module path shown in error dialog or found in Extension Manager # Create download_info.json: cat > Resources/ML/download_info.json << 'EOF' { "download_url": "https://github.com/gaudot/SlicerDentalSegmentator/releases/download/v1.0.0-alpha/Dataset111_453CT_v100.zip" } EOF # Restart Slicer ``` -------------------------------- ### Manual Installation of Model Weights Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md This snippet demonstrates how to manually install model weights by creating a download_info.json file after downloading and extracting the ZIP archive to the specified resource directory. ```bash # Download from GitHub release page # Extract to: DentalSegmentator/Resources/ML/ # Create download_info.json cat > Resources/ML/download_info.json << EOF { "download_url": "https://github.com/gaudot/SlicerDentalSegmentator/releases/download/vX.Y.Z/Dataset111_weights.zip" } EOF ``` -------------------------------- ### Setup DentalSegmentatorWidget UI Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-module.md Demonstrates the manual call to the setup() method for the DentalSegmentatorWidget. This method initializes the UI components and is usually called automatically by the Slicer framework. ```python widget.setup() # Now widget.logic is available and UI is initialized ``` -------------------------------- ### Progress Handler Example Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/types.md An example of a function that can be used as a progress callback, printing the received message. ```python def progress_handler(msg: str) -> None: print(f"Progress: {msg}") checker.downloadWeights(progress_handler) ``` -------------------------------- ### Download and Install Model Weights Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Downloads and installs model weights from a GitHub release, providing progress updates via a callback function. This process involves checking internet connectivity, removing old weights, creating directories, streaming the ZIP file, extracting its contents, and updating the download metadata. ```python def downloadWeights(self, progressCallback: Callable[[str], None]) -> bool ``` ```python def progress_handler(msg): print(f"Download: {msg}") success = checker.downloadWeights(progress_handler) if success: print("Weights installed") else: print("Download failed - check internet connection") ``` -------------------------------- ### Get Destination Weights Folder Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Returns the path to the directory where model weights are stored. This is a required setup step for weight management. ```python def getDestWeightFolder(self) -> Path ``` ```python weights_dir = checker.getDestWeightFolder() print(f"Weights stored in: {weights_dir}") ``` -------------------------------- ### Slicer Module Loading and UI Setup Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/architecture.md Details the process of loading a Slicer module and setting up its user interface, including the creation of various interactive components. ```text User opens DentalSegmentator module ↓ Slicer calls DentalSegmentatorWidget.setup() ↓ ├─ Calls parent setup() ├─ Creates SegmentationWidget(logic=None) │ ├─ Checks if NNUNetLib installed │ ├─ Initializes logic from SlicerNNUNetLib │ ├─ Creates all UI components │ │ ├─ Volume selector │ │ ├─ Device selector │ │ ├─ Segmentation selector │ │ ├─ Segment editor │ │ ├─ Export options │ │ └─ Progress display │ └─ Connects signals └─ Adds widget to layout UI now ready for user interaction ``` -------------------------------- ### ExportFormat Usage Example Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md Demonstrates how to combine multiple export formats using bitwise OR and how to check for the presence of a specific format using bitwise AND. ```python from DentalSegmentatorLib import ExportFormat # Create a flag combining multiple formats formats = ExportFormat.STL | ExportFormat.NIFTI # Check if a format is selected if formats & ExportFormat.OBJ: print("OBJ format selected") ``` -------------------------------- ### Download Info JSON Structure Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/types.md Example structure for the download_info.json file, containing the URL for downloading model weights. ```json { "download_url": "https://github.com/gaudot/SlicerDentalSegmentator/releases/download/vX.Y.Z/DatasetXXX_weights.zip" } ``` -------------------------------- ### getDatasetPath() Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Retrieves the installation path for the `dataset.json` file. Returns `None` if the file is not found. ```APIDOC ## getDatasetPath() ### Description Returns the path to the installed `dataset.json` file. ### Returns `Path` to dataset.json, or `None` if not found. ### Example ```python dataset_path = checker.getDatasetPath() if dataset_path: print(f"Weights installed at: {dataset_path.parent}") ``` ``` -------------------------------- ### Get Dataset Path Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Retrieves the path to the installed dataset.json file. Returns None if the file is not found. ```python def getDatasetPath(self) -> Optional[Path] ``` ```python dataset_path = checker.getDatasetPath() if dataset_path: print(f"Weights installed at: {dataset_path.parent}") ``` -------------------------------- ### downloadWeights(progressCallback) Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Downloads and installs model weights from a GitHub release, providing progress updates. ```APIDOC ## downloadWeights(progressCallback) ### Description Downloads and installs model weights from a GitHub release. ### Parameters #### Parameters - `progressCallback` (`Callable[[str], None]`) - Called with status messages. ### Returns `True` if download successful, `False` if failed or no internet. ### Flow 1. Calls progress callback: "Downloading model weights..." 2. Checks internet connectivity 3. Removes old weight folder (if exists) 4. Creates destination folder 5. Queries GitHub for latest release URL 6. Streams ZIP file in 1MB chunks 7. Extracts ZIP to weights folder 8. Writes download URL to `download_info.json` ### Throws - Shows error dialog if no internet connection. - Shows error dialog with traceback on download/extraction failure. ### Side effects - Deletes existing weights folder. - Creates new folder hierarchy. - Writes `download_info.json`. ### Example ```python def progress_handler(msg): print(f"Download: {msg}") success = checker.downloadWeights(progress_handler) if success: print("Weights installed") else: print("Download failed - check internet connection") ``` ``` -------------------------------- ### ExportFormat Enum Usage Examples Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/types.md Demonstrates how to create single format flags, combine multiple formats using bitwise OR, and check for the presence of a specific format. ```python # Create single format format1 = ExportFormat.STL # Combine multiple formats using bitwise OR formats = ExportFormat.STL | ExportFormat.NIFTI # Check if format is selected if formats & ExportFormat.OBJ: export_to_obj() # Get selected formats from widget selected = widget.getSelectedExportFormats() # Returns ExportFormat flag with checked boxes combined ``` -------------------------------- ### Mock Segmentation Logic for UI Testing Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md This example shows how to create a mock logic object for testing the UI behavior of the SegmentationWidget without executing actual inference. It asserts that the startSegmentation method was called. ```python from unittest.mock import MagicMock from DentalSegmentatorLib import SegmentationWidget, Signal # Create mock logic mock_logic = MagicMock() mock_logic.inferenceFinished = Signal() mock_logic.errorOccurred = Signal("str") mock_logic.progressInfo = Signal("str") mock_logic.startSegmentation = MagicMock() mock_logic.stopSegmentation = MagicMock() mock_logic.loadSegmentation = MagicMock() # Create widget with mock widget = SegmentationWidget(logic=mock_logic) # Test UI behavior without running actual inference widget.onApplyClicked() # Won't run real segmentation mock_logic.startSegmentation.assert_called_once() ``` -------------------------------- ### Check NNUNet Module Installation Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/errors.md Verifies if the NNUNet module is installed before proceeding. This check is crucial to ensure all dependencies are met. ```python from DentalSegmentatorLib import SegmentationWidget if SegmentationWidget.isNNUNetModuleInstalled(): # Safe to create widget pass ``` -------------------------------- ### Run DentalSegmentator Tests Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-module.md Provides an example of how to manually execute the DentalSegmentator tests. This is typically handled by the Slicer test interface or a command-line script. ```python test = DentalSegmentatorTest() try: test.runTest() print("All tests passed!") except AssertionError as e: print(f"Tests failed: {e}") ``` -------------------------------- ### Configure Device Selection Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Get or set the processing device (e.g., 'cuda', 'cpu', 'mps'). The default is the first available option, typically 'cuda'. ```python widget = SegmentationWidget() device = widget.deviceComboBox.currentText # e.g., "cuda" widget.deviceComboBox.setCurrentText("cpu") # Switch to CPU ``` -------------------------------- ### Check Dependencies Satisfied Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md A static method to verify if essential Python packages, PyTorch and nnU-Net v2, are installed and importable. Use this to ensure the environment is ready for segmentation tasks. ```python if PythonDependencyChecker.areDependenciesSatisfied(): print("All dependencies installed") # Ready to run segmentation else: print("Missing PyTorch or nnU-Net v2") ``` -------------------------------- ### areDependenciesSatisfied Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Static method checking if required Python packages (PyTorch, nnU-Net v2) are installed. ```APIDOC ## areDependenciesSatisfied() ### Description Static method checking if required Python packages are installed. ### Method GET (simulated) ### Parameters None ### Response #### Success Response - **bool**: `True` if both PyTorch and nn-Net v2 can be imported, `False` otherwise ### Example ```python if PythonDependencyChecker.areDependenciesSatisfied(): print("All dependencies installed") # Ready to run segmentation else: print("Missing PyTorch or nnU-Net v2") ``` ``` -------------------------------- ### Segmentation Workflow Triggered by User Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/architecture.md Describes the end-to-end segmentation process initiated by the user clicking 'Apply', including checks, potential installations, weight downloads, and asynchronous inference. ```text User clicks Apply ↓ onApplyClicked() ├─ Check: NNUNet installed? ├─ Check: Volume selected? ├─ Install: nnU-Net v2 if needed │ └─ CallsSlicerNNUNetLib.InstallLogic ├─ Download: Weights if needed │ └─ Calls PythonDependencyChecker.downloadWeightsIfNeeded() │ ├─ Check: Weights exist? │ ├─ Check: Weights outdated? │ ├─ GitHub: Query latest release │ └─ Download: Stream ZIP from GitHub └─ Run: Segmentation ↓ _runSegmentation() ├─ Create Parameter (folds, device, model path) ├─ Check: Device available? │ └─ If not: Prompt user, default to CPU ├─ Set: Widget invisible, stop button visible └─ Call: logic.startSegmentation(volumeNode) ↓ SlicerNNUNetLib processes asynchronously ├─ Preprocess volume ├─ Load model from weights ├─ Run inference └─ Save results to disk ↓ Emit signal: inferenceFinished() ↓ onInferenceFinished() ├─ Load segmentation from disk ├─ Update segment names, colors, opacity ├─ Post-process: Remove small islands ├─ Store: Map volume → segmentation ├─ Set: Widget visible, stop button invisible └─ Display success message User can now: ├─ Edit results with segment editor ├─ Export in STL/OBJ/NIFTI/glTF └─ Process new volume ``` -------------------------------- ### Check Python Dependencies Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Verifies if PyTorch and nnU-Net v2 are installed. Use this to ensure the environment is correctly set up before running segmentation tasks. ```python from DentalSegmentatorLib import PythonDependencyChecker # Check if PyTorch and nnU-Net v2 installed if PythonDependencyChecker.areDependenciesSatisfied(): print("All dependencies installed") print("PyTorch and nnU-Net v2 are available") else: print("Missing dependencies") print("Need to install PyTorch or nnU-Net v2") ``` -------------------------------- ### Check NNUNet Module Installation Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md A static method to check if the SlicerNNUNetLib is available. Returns True if the module can be imported, False otherwise. ```python @staticmethod def isNNUNetModuleInstalled() -> bool ``` ```python if SegmentationWidget.isNNUNetModuleInstalled(): widget = SegmentationWidget() else: print("NNUNet extension not installed") ``` -------------------------------- ### Get Weight Download Info Path Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Retrieves the path to the download metadata file, typically named download_info.json. This file records information about previously downloaded weights. ```python def getWeightDownloadInfoPath(self) -> Path ``` ```json { "download_url": "https://github.com/.../releases/download/.../Dataset111_xyz.zip" } ``` ```python info_path = checker.getWeightDownloadInfoPath() if info_path.exists(): print("Download history recorded") ``` -------------------------------- ### Configure Output Segmentation Selection Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Get the selected output segmentation node. If none is selected, a new segmentation node will be created when the Apply button is clicked. ```python widget = SegmentationWidget() seg_node = widget.segmentationNodeSelector.currentNode() # Returns None if "Create new Segmentation on Apply" selected ``` -------------------------------- ### Configure Input Volume Selection Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Get or set the currently selected input volume node for segmentation. The Apply button is disabled if no volume is selected. ```python widget = SegmentationWidget() volume_node = widget.inputSelector.currentNode() # Get selected widget.inputSelector.setCurrentNode(new_volume) # Set selected ``` -------------------------------- ### Check Model Weight Status Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Verify if model weights are installed and up-to-date. This helps determine if a download is necessary before proceeding with segmentation tasks. ```python from DentalSegmentatorLib import PythonDependencyChecker from pathlib import Path checker = PythonDependencyChecker() # Check if weights installed if checker.areWeightsMissing(): print("Weights not installed") else: print("Weights installed") dataset_path = checker.getDatasetPath() print(f"Location: {dataset_path.parent}") # Check if weights outdated if checker.areWeightsOutdated(): print("Newer weights available on GitHub") else: print("Weights are up to date") ``` -------------------------------- ### Implement Custom Error Handler Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md This example demonstrates how to create a custom error handler that logs error messages and detailed text to a specified file. It's used to customize error reporting for operations like dependency checking. ```python from DentalSegmentatorLib import PythonDependencyChecker class CustomErrorHandler: def __init__(self, log_file): self.log_file = log_file def __call__(self, msg, detailedText=None): with open(self.log_file, 'a') as f: f.write(f"ERROR: {msg}\n") if detailedText: f.write(f"DETAILS: {detailedText}\n") # Use custom error handler error_handler = CustomErrorHandler("/var/log/dental_segmentator.log") checker = PythonDependencyChecker(errorDisplayF=error_handler) ``` -------------------------------- ### Create and Set Segmentation Logic Parameters Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Instantiate the Parameter object for SlicerNNUNetLib, specifying the inference fold, model path, and compute device. This configuration is then applied to the segmentation logic before starting the process. ```python from SlicerNNUNetLib import Parameter # Create parameter configuration parameter = Parameter( folds="0", # nn-Net fold (0 = all folds) modelPath=widget.nnUnetFolder(), # Path to weights device=widget.deviceComboBox.currentText # cuda/cpu/mps ) # Check device availability if parameter.isSelectedDeviceAvailable(): # Proceed with inference widget.logic.setParameter(parameter) widget.logic.startSegmentation(volume_node) ``` -------------------------------- ### Trigger Segmentation Process Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md Programmatically initiates the segmentation process. This method handles necessary checks, installations, and downloads before starting the segmentation. ```python # Typically called by button click connection # Can be invoked programmatically: widget.onApplyClicked() ``` -------------------------------- ### Basic Usage of SegmentationWidget Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/INDEX.md Demonstrates how to create, show, and use the SegmentationWidget for loading volumes, running segmentation, and exporting results. Segmentation runs asynchronously. ```python import slicer from DentalSegmentatorLib import SegmentationWidget # Create and show widget widget = SegmentationWidget() widget.show() # Load volume, select device, click Apply # Segmentation runs asynchronously # Export results when complete ``` -------------------------------- ### Initialize and Download Weights Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Demonstrates how to create a PythonDependencyChecker instance, define a progress callback, and initialize model weights. It first checks Python dependencies and then downloads weights if necessary, printing status messages. ```python from DentalSegmentatorLib import PythonDependencyChecker # Create checker checker = PythonDependencyChecker() # Define progress callback def show_progress(msg): print(f"Progress: {msg}") # Check and install if needed def initialize_weights(): # First ensure Python dependencies if not PythonDependencyChecker.areDependenciesSatisfied(): print("ERROR: PyTorch or nnU-Net v2 not installed") return False # Then check and download weights if not checker.downloadWeightsIfNeeded(show_progress): print("ERROR: Could not prepare weights") return False print("Ready for segmentation") return True # Use in application if initialize_weights(): # Can now run segmentation pass ``` -------------------------------- ### Slicer Module Initialization Flow Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/architecture.md Illustrates the sequence of events during Slicer module startup, from CMake discovery to module registration and appearance in the user interface. ```text Slicer Startup ↓ CMakeLists.txt discovers DentalSegmentator.py ↓ Instantiate DentalSegmentator class ├─ Sets title, category, help text └─ Registers module ↓ Module appears in Segmentation category ``` -------------------------------- ### Segmentation with Device Selection Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Demonstrates how to select a computation device (e.g., CPU) and create a parameter object with the selected device. It includes a check to ensure the selected device is available. ```python from DentalSegmentatorLib import SegmentationWidget from SlicerNNUNetLib import Parameter widget = SegmentationWidget() # Select device before running widget.deviceComboBox.setCurrentText("cpu") # Create parameter with selected device parameter = Parameter( folds="0", modelPath=widget.nnUnetFolder(), device=widget.deviceComboBox.currentText ) # Check if device available if not parameter.isSelectedDeviceAvailable(): print("Selected device not available, will use CPU") widget.deviceComboBox.setCurrentText("cpu") # Set parameter and start widget.logic.setParameter(parameter) widget.logic.startSegmentation(widget.getCurrentVolumeNode()) ``` -------------------------------- ### DentalSegmentatorWidget.setup() Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-module.md Initializes the UI components of the DentalSegmentatorWidget. This method is called automatically by the Slicer framework when the module is first opened. ```APIDOC ## DentalSegmentatorWidget.setup() ### Description Initializes the user interface components of the DentalSegmentatorWidget. This method is automatically invoked by the Slicer framework when the module is loaded. ### Method Signature ```python def setup(self) -> None ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - None ### Side Effects - Calls the `setup()` method of the parent `ScriptedLoadableModuleWidget`. - Creates an instance of `SegmentationWidget`. - Stores a reference to the segmentation logic. - Adds the widget to the main layout and includes a stretchable space. ``` -------------------------------- ### hasInternetConnection Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Checks if the system has internet connectivity by attempting an HTTP GET request to google.com. ```APIDOC ## hasInternetConnection(timeOut_sec=2) ### Description Checks if the system has internet connectivity. ### Method GET (simulated) ### Parameters #### Query Parameters - **timeOut_sec** (int) - Optional - Timeout in seconds for connection test. Defaults to 2. ### Response #### Success Response - **bool**: `True` if internet accessible, `False` otherwise ### Example ```python from DentalSegmentatorLib import hasInternetConnection if hasInternetConnection(): print("Internet available, can download weights") else: print("Offline mode - use cached weights") ``` ``` -------------------------------- ### areWeightsOutdated Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Checks if the currently installed model weights are outdated by comparing with the latest GitHub release. ```APIDOC ## areWeightsOutdated() ### Description Checks if installed weights are outdated. ### Method GET (simulated) ### Parameters None ### Response #### Success Response - **bool**: `True` if weights need update, `False` otherwise ### Example ```python if checker.areWeightsOutdated(): print("Newer weights available on GitHub") ``` ``` -------------------------------- ### Weight Management Flow on First and Subsequent Runs Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/architecture.md Explains how the module checks for, downloads, and manages model weights, including handling internet connectivity and version checking. ```text First Run: ├─ onApplyClicked() → Check weights ├─ areWeightsMissing() checks for dataset.json │ └─ Not found ├─ downloadWeightsIfNeeded() │ ├─ hasInternetConnection()? → requests.get("google.com") │ ├─ Yes: Download weights │ │ ├─ Query GitHub API for latest release │ │ ├─ Stream ZIP in 1MB chunks │ │ ├─ Extract to Resources/ML/ │ │ └─ Write download_info.json │ └─ No: Show error, return False └─ Proceed or error Subsequent Runs (weights installed): ├─ Check: areWeightsMissing()? → No, dataset.json found ├─ Check: areWeightsOutdated()? │ ├─ hasInternetConnection()? → No: Assume up-to-date │ ├─ Yes: Query GitHub for latest URL │ │ └─ Compare with stored download_info.json │ │ ├─ Same URL: Up-to-date │ │ └─ Different URL: Prompt user to update │ └─ User choice: Download or skip └─ Proceed with inference ``` -------------------------------- ### Get Absolute Icon Path Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-utilities.md Returns the absolute path to an icon file. Icons are stored in the DentalSegmentator/Resources/Icons/ directory. ```python from DentalSegmentatorLib import iconPath path = iconPath("DentalSegmentator.png") print(f"Icon at: {path}") # Output: /path/to/DentalSegmentator/Resources/Icons/DentalSegmentator.png ``` -------------------------------- ### Run Segmentation Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/INDEX.md Configure the SegmentationWidget by setting the input volume and desired device (e.g., 'cuda'), then trigger the segmentation process by clicking the apply button. ```python widget.inputSelector.setCurrentNode(volume) widget.deviceComboBox.setCurrentText("cuda") widget.onApplyClicked() ``` -------------------------------- ### Access Dental Segmentator Module Programmatically Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Get a reference to the Dental Segmentator module and access its widget, representation, and logic. ```python import slicer # Get reference to the module module = slicer.modules.dentalsegmentator # Access the widget widget = module.widgetRepresentation() # Access the logic logic = widget.logic ``` -------------------------------- ### Manually Download Model Weights Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Initiate a manual download of model weights. A progress callback function can be provided to monitor the download status. ```python from DentalSegmentatorLib import PythonDependencyChecker checker = PythonDependencyChecker() def progress_callback(msg): print(f"Download progress: {msg}") # Download weights success = checker.downloadWeights(progress_callback) if success: print("Weights downloaded successfully") dataset_path = checker.getDatasetPath() print(f"Installed at: {dataset_path.parent}") else: print("Weight download failed") ``` -------------------------------- ### Get Current Volume Node Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md Retrieves the currently selected input volume node from the widget. Returns None if no volume is selected. ```python volume_node = widget.getCurrentVolumeNode() if volume_node: print(f"Processing volume: {volume_node.GetName()}") ``` -------------------------------- ### Initialize PythonDependencyChecker with Default Repository Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Initializes the checker using the default GitHub repository for downloading weights. ```python checker = PythonDependencyChecker() # Uses official: gaudot/SlicerDentalSegmentator ``` -------------------------------- ### Create Configured QPushButton Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-utilities.md Use `createButton` to generate a configured QPushButton. It supports callbacks, checkable states, icons, tooltips, and parent widgets. ```python from DentalSegmentatorLib import createButton, icon def on_click(checked): print(f"Button clicked, checked: {checked}") # Simple button button = createButton("Apply", callback=on_click) # Button with icon apply_btn = createButton( "Apply", callback=on_click, icon=icon("start_icon.png"), toolTip="Click to run segmentation" ) # Checkable button toggle_btn = createButton( "Show Details", isCheckable=True, callback=lambda checked: print(f"Toggled: {checked}") ) # Button in layout layout.addWidget(apply_btn) ``` -------------------------------- ### Instantiate DentalSegmentatorWidget Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-module.md Shows how to create an instance of the DentalSegmentatorWidget. This is typically done by the Slicer framework, but can be done manually for testing purposes. ```python from DentalSegmentator import DentalSegmentatorWidget widget = DentalSegmentatorWidget() ``` -------------------------------- ### Initialize PythonDependencyChecker with Custom Repository Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Initializes the checker to download weights from a specified custom GitHub repository. ```python checker = PythonDependencyChecker( repoPath="my-org/my-dental-segmentator" ) # Downloads from my-org/my-dental-segmentator releases ``` -------------------------------- ### Python Exception Handling for ImportError Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/errors.md Handles cases where the NNUNet module is not installed. This allows the UI to be created without logic and an error to be displayed. ```python try: widget = SegmentationWidget() except ImportError: print("NNUNet module not installed") # Create UI without logic, show error ``` -------------------------------- ### Check and Download Weights if Needed Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Automatically download weights if they are missing, or prompt for download if they are outdated. This ensures weights are ready for segmentation with minimal user intervention. ```python from DentalSegmentatorLib import PythonDependencyChecker checker = PythonDependencyChecker() def progress_callback(msg): print(f"Status: {msg}") # Auto-download if missing, prompt if outdated success = checker.downloadWeightsIfNeeded(progress_callback) if success: print("Weights ready for segmentation") else: print("Could not prepare weights") ``` -------------------------------- ### Get Selected Export Formats Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md Retrieves the currently selected export formats. This is useful for determining which file types the user wishes to export. ```python def getSelectedExportFormats(self) -> ExportFormat ``` ```python formats = widget.getSelectedExportFormats() if formats & ExportFormat.STL: print("STL export is enabled") if formats & ExportFormat.NIFTI: print("NIFTI export is enabled") ``` -------------------------------- ### Get Current Segmentation Node Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md Retrieves the currently selected segmentation node. Returns None if no segmentation is selected. Useful for inspecting existing segmentations. ```python seg_node = widget.getCurrentSegmentationNode() if seg_node: segmentation = seg_node.GetSegmentation() num_segments = segmentation.GetNumberOfSegments() print(f"Segmentation has {num_segments} segments") ``` -------------------------------- ### Signal Constructor Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-utilities.md Initializes a new Signal instance. Type information can be provided for documentation purposes but is not enforced at runtime. ```APIDOC ## Signal Constructor ### Description Initializes a new Signal instance. Type information can be provided for documentation purposes but is not enforced at runtime. ### Signature ```python def __init__(self, *typeInfo) ``` ### Parameters #### Arguments - `*typeInfo` (tuple) - Optional type information for documentation. ### Returns - `Signal` instance ### Example ```python from DentalSegmentatorLib import Signal # Create signal with type info progress_signal = Signal("str") # Expects string parameter # Create untyped signal finished_signal = Signal() ``` ``` -------------------------------- ### Signal Constructor Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-utilities.md Initializes a Signal instance. Type information can be provided for documentation purposes but is not enforced at runtime. ```python from DentalSegmentatorLib import Signal # Create signal with type info progress_signal = Signal("str") # Expects string parameter # Create untyped signal finished_signal = Signal() ``` -------------------------------- ### Initialize PythonDependencyChecker with Custom Weight Folder Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Initializes the checker to store model weights in a specified custom directory. ```python from pathlib import Path from DentalSegmentatorLib import PythonDependencyChecker # Custom location checker = PythonDependencyChecker( destWeightFolder=Path("/custom/weights") ) # Weights will be at: /custom/weights/ ``` -------------------------------- ### Configure Custom Weight Repository Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Download model weights from a specified custom GitHub repository. This allows for using private or alternative sources for model weights. ```python from DentalSegmentatorLib import PythonDependencyChecker # Use weights from custom GitHub repository checker = PythonDependencyChecker( repoPath="my-org/my-dental-weights" ) def progress_callback(msg): print(f"Status: {msg}") # Will download from my-org/my-dental-weights releases success = checker.downloadWeights(progress_callback) ``` -------------------------------- ### Get nn-Unet Model Weights Folder Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md A class method that returns the path to the nn-Unet model weights folder. This is typically located within the Resources/ML directory. ```python @classmethod def nnUnetFolder(cls) -> Path ``` ```python weights_dir = SegmentationWidget.nnUnetFolder() print(f"Model weights location: {weights_dir}") ``` -------------------------------- ### Download Weights If Needed Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Initiates the download of model weights if they are missing or prompts the user to update if newer versions are available on GitHub. Requires a callback function to report progress. Returns true if weights are satisfied. ```python def on_progress(msg): print(f"Status: {msg}") success = checker.downloadWeightsIfNeeded(on_progress) if success: print("Weights ready") else: print("Weights unavailable") ``` -------------------------------- ### Get Last Downloaded Weights URL Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Retrieves the URL of the last downloaded weights from the download metadata file. Returns None if the URL is not found in the file. ```python def getLastDownloadedWeights(self) -> Optional[str] ``` ```python last_url = checker.getLastDownloadedWeights() if last_url: print(f"Last download from: {last_url}") ``` -------------------------------- ### Get QIcon Object for Qt Widgets Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-utilities.md Returns a QIcon object that can be used in Qt buttons and widgets. This is useful for displaying icons in the application's user interface. ```python from DentalSegmentatorLib import icon, createButton # Use icon in button start_icon = icon("start_icon.png") button = createButton("Start", icon=start_icon) # Use in multiple places info_icon = icon("info.png") info_button = createButton("", icon=info_icon, toolTip="Show info") ``` -------------------------------- ### Initialize PythonDependencyChecker with Default Weight Folder Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Initializes the checker using the default directory for storing model weights. ```python from pathlib import Path from DentalSegmentatorLib import PythonDependencyChecker # Default location checker = PythonDependencyChecker() # Uses: {Slicer}/Extensions/DentalSegmentator/Resources/ML/ ``` -------------------------------- ### Download Segmentation Weights Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/INDEX.md Instantiate the PythonDependencyChecker and use it to download necessary weights if they are not already present. A print function can be passed to show download progress. ```python checker = PythonDependencyChecker() success = checker.downloadWeightsIfNeeded(print) ``` -------------------------------- ### Initialize PythonDependencyChecker Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Instantiates the PythonDependencyChecker. Allows for default configuration or custom paths for the repository and destination weight folder, and custom functions for internet connection checks and error display. ```python from pathlib import Path from DentalSegmentatorLib import PythonDependencyChecker # Default initialization checker = PythonDependencyChecker() # Custom initialization checker = PythonDependencyChecker( repoPath="my-org/my-fork", destWeightFolder=Path("/custom/weights/path") ) ``` -------------------------------- ### Check if Weights Are Outdated Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Verifies if the currently installed model weights are outdated compared to the latest release on GitHub. Returns false if there's no internet connection or if an error occurs during the check. ```python if checker.areWeightsOutdated(): print("Newer weights available on GitHub") ``` -------------------------------- ### Pre-Execution Error Checks Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/errors.md This function performs several checks before initiating segmentation to prevent common errors. It verifies the NNUNet installation, volume selection, dependency availability, and device readiness. ```python def onApplyClicked(self): # Check 1: NNUNet installed if not self.isNNUNetModuleInstalled(): slicer.util.errorDisplay("NNUNet not installed") return # Check 2: Volume selected if self.getCurrentVolumeNode() is None: slicer.util.errorDisplay("No volume selected") return # Check 3: Dependencies downloadable if not self._installNNUNetIfNeeded(): return # Check 4: Weights available if not self._dependencyChecker.downloadWeightsIfNeeded(...): return # Check 5: Device available if not parameter.isSelectedDeviceAvailable(): if not user_accepts_cpu(): return # All checks passed - safe to proceed self._runSegmentation() ``` -------------------------------- ### Load and Verify Test Segmentation Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md This snippet demonstrates how to load a test CT volume and its corresponding segmentation using utility functions. It then verifies the number of segments in the loaded segmentation. ```python from DentalSegmentator.Testing.Utils import ( DentalSegmentatorTestCase, load_test_CT_volume, get_test_multi_label_path ) import slicer class MyTest(DentalSegmentatorTestCase): def test_segmentation(self): # Load test volume volume = load_test_CT_volume() self.assertIsNotNone(volume) # Load test segmentation seg_path = get_test_multi_label_path() seg = slicer.util.loadSegmentation(seg_path) self.assertIsNotNone(seg) # Verify segments segmentation = seg.GetSegmentation() self.assertEqual(segmentation.GetNumberOfSegments(), 5) ``` -------------------------------- ### nnUnetFolder() Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md Static method returning the path to the nn-U-Net model weights folder, which is located within the Resources/ML directory. ```APIDOC ## nnUnetFolder() ### Description Static method returning the path to the nn-U-Net model weights folder. This path points to the `Resources/ML` directory. ### Method `@classmethod def nnUnetFolder(cls) -> Path` ### Parameters None ### Request Example ```python weights_dir = SegmentationWidget.nnUnetFolder() print(f"Model weights location: {weights_dir}") ``` ### Response #### Success Response - **Path** (`Path`) - Path object pointing to the `Resources/ML` directory ``` -------------------------------- ### Access and Modify Individual Segments Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Get a specific segment by its ID, modify its name and color, and check for its binary labelmap representation. This allows for fine-grained control over individual segmentation components. ```python from DentalSegmentatorLib import SegmentationWidget import slicer widget = SegmentationWidget() seg_node = widget.getCurrentSegmentationNode() segmentation = seg_node.GetSegmentation() # Get specific segment maxilla = segmentation.GetSegment("Segment_1") if maxilla: print(f"Segment name: {maxilla.GetName()}") # Modify properties maxilla.SetName("Maxilla Modified") maxilla.SetColor(1.0, 1.0, 0.0) # Yellow # Get segment data segment_data = maxilla.GetRepresentation("Binary labelmap") if segment_data: print("Has binary labelmap representation") ``` -------------------------------- ### Initialize PythonDependencyChecker with Default Internet Connection Check Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Initializes the checker using the default function to test internet connectivity. ```python # Default: uses requests.get("https://www.google.com") checker = PythonDependencyChecker() ``` -------------------------------- ### Retrieve Selected Volume and Segmentation Nodes Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Get the currently selected input volume node and segmentation node from the widget. Provides feedback on whether a volume is selected and if a new segmentation will be created. ```python from DentalSegmentatorLib import SegmentationWidget widget = SegmentationWidget() # Get current selections volume_node = widget.getCurrentVolumeNode() segmentation_node = widget.getCurrentSegmentationNode() if volume_node: print(f"Processing volume: {volume_node.GetName()}") else: print("No volume selected") if segmentation_node: print(f"Using segmentation: {segmentation_node.GetName()}") else: print("Will create new segmentation") ``` -------------------------------- ### SegmentationWidget Constructor Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md Initializes the SegmentationWidget, setting up UI components and connecting signals. ```APIDOC ## SegmentationWidget Class Main widget providing the user interface for dental volume segmentation. ### Constructor ```python def __init__(self, logic=None, parent=None) ``` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `logic` | `SegmentationLogic` | No | `None` | Segmentation logic instance. If `None`, creates default logic from SlicerNNUNetLib | | `parent` | `qt.QWidget` | No | `None` | Parent Qt widget | **Returns**: `SegmentationWidget` instance **Throws**: None directly; may raise `ImportError` if SlicerNNUNetLib is not installed The constructor initializes all UI components including volume selectors, device selector, segment editor, and export options. It automatically connects the segmentation logic signals for progress updates and completion handling. ```python # Example: Create widget with default logic widget = SegmentationWidget() # Example: Create widget with custom logic from SlicerNNUNetLib import SegmentationLogic custom_logic = SegmentationLogic() widget = SegmentationWidget(logic=custom_logic) ``` ``` -------------------------------- ### Import Segmentation Widget Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/INDEX.md Import the main SegmentationWidget class from the library. This is the primary entry point for segmentation tasks. ```python from DentalSegmentatorLib import SegmentationWidget widget = SegmentationWidget() ``` -------------------------------- ### Get Latest Release Download URL from GitHub Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-dependency-checker.md Queries the GitHub API to find the download URL for the latest release of the model weights. This method uses the PyGithub library and may throw a GithubException if the API request fails. ```python def getLatestReleaseUrl(self) -> str ``` ```python try: latest_url = checker.getLatestReleaseUrl() print(f"Latest weights at: {latest_url}") except Exception as e: print(f"Cannot reach GitHub: {e}") ``` -------------------------------- ### Initialize PythonDependencyChecker with Custom Internet Connection Check Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/configuration.md Initializes the checker with a custom function to determine internet connectivity. ```python # Custom: use alternative test def custom_check(): # Your custom connectivity test return network_available checker = PythonDependencyChecker( hasInternetConnectionF=custom_check ) ``` -------------------------------- ### SegmentationWidget Constructor with Default Logic Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/api-reference-segmentation-widget.md Initializes the SegmentationWidget using its default segmentation logic. This is the simplest way to create an instance. ```python # Example: Create widget with default logic widget = SegmentationWidget() ``` -------------------------------- ### Create Segmentation Widget with Default Logic Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Instantiate the SegmentationWidget with its default logic initialization. Ensure the Slicer application event loop is processed before creating the widget. ```python from DentalSegmentatorLib import SegmentationWidget import slicer # Ensure scene is set up slicer.app.processEvents() # Create widget with automatic logic initialization widget = SegmentationWidget() widget.show() ``` -------------------------------- ### Configure Custom Weight Download Location Source: https://github.com/gaudot/slicerdentalsegmentator/blob/main/_autodocs/usage-examples.md Specify a custom directory for storing downloaded model weights. This is useful for managing storage space or organizing models on different drives. ```python from DentalSegmentatorLib import PythonDependencyChecker from pathlib import Path # Store weights in custom location custom_path = Path("/mnt/large_drive/ml_models") checker = PythonDependencyChecker( destWeightFolder=custom_path ) print(f"Using weights from: {checker.getDestWeightFolder()}") # All download/check operations use custom location ```