### Start MONAI Label Server with OHIF Viewer (with Auth) Source: https://monai.readthedocs.io/projects/label/en/latest/installation Starts the MONAI Label server for OHIF Viewer with authentication credentials for DICOM-web. The username and password are provided via environment variables. ```bash export MONAI_LABEL_DICOMWEB_USERNAME=xyz export MONAI_LABEL_DICOMWEB_PASSWORD=abc monailabel start_server --app apps/radiology --studies http://127.0.0.1:8042/dicom-web --conf models deepedit ``` -------------------------------- ### Start MONAI Label Server with Local Dataset Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart This command starts the MONAI Label server using the DeepEdit application and specifies a local directory for studies. It's used for initial setup and testing with local data. ```bash mkdir my_dataset monailabel start_server --app radiology --studies my_dataset --conf models deepedit ``` -------------------------------- ### Start MONAI Label Server with OHIF Viewer (Basic) Source: https://monai.readthedocs.io/projects/label/en/latest/installation Starts the MONAI Label server configured for the OHIF Viewer, using the radiology application and specifying the DICOM-web studies endpoint. The 'deepedit' models are also configured. ```bash monailabel start_server --app apps/radiology --studies http://127.0.0.1:8042/dicom-web --conf models deepedit ``` -------------------------------- ### Install and Configure MONAI Label with Bundle App Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart Installs the MONAI Label package, downloads the Bundle sample app, and fetches sample datasets. This is a prerequisite for using bundle-based workflows. ```bash # install MONAI Label pip install monailabel # download Bundle sample app to local directory monailabel apps --name monaibundle --download --output . # download a local study images, sample dataset such as spleen: monailabel datasets --download --name Task09_Spleen --output . ``` -------------------------------- ### Start MONAI Label Server with Bundle App and SwinUNETR Model Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart Starts the MONAI Label server using the downloaded Bundle app and configures it to use the SwinUNETR model for segmentation tasks. This command is used in conjunction with the prerequisite setup for bundle apps. ```bash monailabel start_server --app monaibundle --studies Task09_Spleen/imagesTr --conf models swin_unetr_btcv_segmentation ``` -------------------------------- ### Start MONAI Label Server with Deepedit Model Source: https://monai.readthedocs.io/projects/label/en/latest/installation Starts the MONAI Label server using the radiology app, specifying the image training studies directory and configuring it to run the deepedit model. ```bash # Run Deepedit Model. # Options can be (deepedit|deepgrow|segmentation|segmentation_spleen|all) in case of radiology app. # You can also pass comma separated models like --conf models deepedit,segmentation monailabel start_server --app apps/radiology --studies datasets/Task09_Spleen/imagesTr --conf models deepedit ``` -------------------------------- ### Install MONAI Label and Deploy Radiology App Server Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart Installs the MONAI Label library, downloads the Radiology sample application, and deploys it along with a sample dataset (MSD heart MRI) to the MONAI Label server. This prepares the environment for annotation using the deepedit model. ```bash # install MONAI Label pip install monailabel # download Radiology sample app to local directory monailabel apps --name radiology --download --output . # download Task 2 MSD dataset monailabel datasets --download --name Task09_Spleen --output . # start the Radiology app in MONAI label server # and start annotating the downloaded images using deepedit model monailabel start_server --app radiology --studies Task09_Spleen/imagesTr --conf models deepedit ``` -------------------------------- ### Download MONAI Label Sample Apps and Datasets Source: https://monai.readthedocs.io/projects/label/en/latest/installation Uses the MONAI Label CLI to list and download sample applications (e.g., radiology) and datasets (e.g., Task09_Spleen) for testing and development. ```bash # Download Sample Apps monailabel apps # List sample apps monailabel apps --download --name radiology --output apps # Download MSD Datasets monailabel datasets # List sample datasets monailabel datasets --download --name Task09_Spleen --output datasets ``` -------------------------------- ### Run Uvicorn Server for MONAI Label (Windows) Source: https://monai.readthedocs.io/projects/label/en/latest/installation This command starts the Uvicorn server for MONAI Label on Windows. It specifies the host, port, and a logging configuration file. Ensure you have the 'env.bat' script called beforehand to set up the environment. ```batch call env.bat uvicorn monailabel.app:app ^ --host 0.0.0.0 ^ --port 8000 ^ --log-config apps\radiology\logs\logging.json ^ --no-access-log ``` -------------------------------- ### Start MONAI Label Server in SSL Mode Source: https://monai.readthedocs.io/projects/label/en/latest/installation Starts the MONAI Label server with SSL enabled, using the previously generated self-signed key and certificate files. This allows for secure HTTPS connections. ```bash # Start server in ssl mode monailabel start_server --app apps/radiology --studies datasets/Task09_Spleen/imagesTr --conf models deepedit --ssl_keyfile uvicorn-selfsigned.key --ssl_certfile uvicorn-selfsigned.crt ``` -------------------------------- ### Start MONAI Label Server with OHIF Viewer (Disable NIFTI Conversion) Source: https://monai.readthedocs.io/projects/label/en/latest/installation Starts the MONAI Label server for OHIF Viewer, disabling DICOM to NIFTI conversion for improved performance. This is recommended when using OHIF exclusively. ```bash export MONAI_LABEL_DICOMWEB_CONVERT_TO_NIFTI=false monailabel start_server --app apps/radiology --studies http://127.0.0.1:8042/dicom-web --conf models deepedit ``` -------------------------------- ### Install Orthanc DICOM Server and DICOMweb Plugin on Ubuntu Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart Installs the Orthanc DICOM server and its DICOMweb plugin using apt-get. It also includes steps to stop, reconfigure, and restart the Orthanc service to ensure the plugins are loaded correctly. ```bash # Install orthanc and dicomweb plugin sudo apt-get install orthanc orthanc-dicomweb -y # stop the existing Orthanc instance if there is one sudo service orthanc stop # setup and upgrade Orthanc libraries sudo wget https://lsb.orthanc-server.com/orthanc/1.9.7/Orthanc --output-document /usr/sbin/Orthanc sudo rm -f /usr/share/orthanc/plugins/*.so sudo wget https://lsb.orthanc-server.com/orthanc/1.9.7/libServeFolders.so --output-document /usr/share/orthanc/plugins/libServeFolders.so sudo wget https://lsb.orthanc-server.com/orthanc/1.9.7/libModalityWorklists.so --output-document /usr/share/orthanc/plugins/libModalityWorklists.so sudo wget https://lsb.orthanc-server.com/plugin-dicom-web/1.6/libOrthancDicomWeb.so --output-document /usr/share/orthanc/plugins/libOrthancDicomWeb.so # start sudo service orthanc restart ``` -------------------------------- ### Install MONAI Label from GitHub Source: https://monai.readthedocs.io/projects/label/en/latest/installation Installs the latest development version of MONAI Label directly from the GitHub main branch. This is useful for accessing the newest features. ```bash pip install git+https://github.com/Project-MONAI/MONAILabel#egg=monailabel ``` -------------------------------- ### Start MONAI Label Server for Pathology with QuPath Source: https://monai.readthedocs.io/projects/label/en/latest/installation Starts the MONAI Label server specifically for pathology use cases, utilizing the 'pathology' app and pointing to 'wsi_images' as the study directory. This is intended for use with QuPath. ```bash # start server using pathology over downloaded whole slide images monailabel start_server --app apps/pathology --studies wsi_images ``` -------------------------------- ### Install MONAI Label from PyPI Source: https://monai.readthedocs.io/projects/label/en/latest/installation Installs the latest milestone release of MONAI Label from the Python Package Index (PyPI). ```bash pip install monailabel ``` -------------------------------- ### Install Python Development Headers on Ubuntu Source: https://monai.readthedocs.io/projects/label/en/latest/installation Installs the python3-dev package on Ubuntu systems, which is required for building Python extensions and is not bundled with Python itself. ```bash sudo apt install python3-dev ``` -------------------------------- ### MONAI Label CLI Help Source: https://monai.readthedocs.io/projects/label/en/latest/installation Displays the help message for the MONAI Label command-line interface, outlining available commands and options. ```bash monailabel --help ``` -------------------------------- ### Download and Start MONAI Label Sample App Source: https://monai.readthedocs.io/projects/label/en/latest/appdeployment Commands to download a sample MONAI Label application (e.g., 'radiology') and start the MONAI Label server locally with the specified application and study path. The `--conf` argument specifies the models to load. ```bash # download a sample app monailabel apps --name radiology --download --output . # start the sample app locally monailabel start_server --app radiology --studies --conf models (deepedit|deepgrow|segmentation|segmentation_speen|all) ``` -------------------------------- ### Dry Run MONAI Label Server Configuration Source: https://monai.readthedocs.io/projects/label/en/latest/installation Performs a dry run of the MONAI Label server start command, which pre-initializes the environment and dumps configuration variables to a .env file for manual Uvicorn deployment. ```bash # dryrun the MONAI Label CLI for pre-init and dump the env variables to .env or env.bat monailabel start_server --app apps/radiology --studies datasets/Task09_Spleen/imagesTr --host 0.0.0.0 --port 8000 --dryrun ``` -------------------------------- ### Start MONAI Label Server with DICOMweb Studies Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart This command initiates the MONAI Label server, utilizing the DeepEdit application and connecting to a remote DICOMweb service for studies. It's essential for annotating data stored in a DICOM server. ```bash # install MONAI Label (if you have not already) pip install monailabel # download DeepEdit sample app to local directory monailabel apps --name radiology --download --output . # For MONAI Label version <=0.2.0, pass credentials and start the DeepEdit app in MONAI label server # and start annotating images in our DICOM server monailabel start_server --app radiology --studies http://localhost:8042/dicom-web --conf models deepedit ``` -------------------------------- ### Install MONAI Label for Renal Substructure Segmentation Use Case Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart Installs the MONAI Label package, which is the first step for setting up the environment for the renal substructure segmentation use case. This command ensures the necessary libraries are available. ```bash # Step 1: install MONAI Label pip install monailabel ``` -------------------------------- ### Setup Custom Dataset Annotation with Radiology App Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart This snippet demonstrates how to set up MONAI Label for annotating a custom dataset using the Radiology app. It involves installing MONAI Label, downloading the Radiology app, and specifying a local directory for image and label storage. ```bash # install MONAI Label pip install monailabel # download DeepEdit sample app to local directory monailabel apps --name radiology --download --output . ``` -------------------------------- ### Download Bundle Sample App for Renal Substructure Segmentation Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart Downloads the sample Bundle application to the local directory. This is part of the setup for the renal substructure segmentation use case, allowing the use of pre-defined bundle structures. ```bash # Step 2: download Bundle sample app to local directory monailabel apps --name monaibundle --download --output . ``` -------------------------------- ### Deploy MONAI Label Server with Uvicorn (Linux/Ubuntu) Source: https://monai.readthedocs.io/projects/label/en/latest/installation Manually deploys the MONAI Label server using Uvicorn on Linux/Ubuntu after sourcing environment variables from a .env file. This provides more control over the server configuration. ```bash # Linux/Ubuntu source .env uvicorn monailabel.app:app \ --host 0.0.0.0 \ --port 8000 \ --log-config apps/radiology/logs/logging.json \ --no-access-log ``` -------------------------------- ### Install Python Libraries and Check CUDA Source: https://monai.readthedocs.io/projects/label/en/latest/installation Installs the latest stable version of PyTorch with CUDA support and verifies if CUDA is available. This is a prerequisite for installing MONAI Label. ```python python -m pip install --upgrade pip setuptools wheel # Install latest stable version for pytorch pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113 # Check if cuda enabled python -c "import torch; print(torch.cuda.is_available())" ``` -------------------------------- ### Convert NIFTI to DICOM using plastimatch Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart This script demonstrates converting a NIFTI image file to DICOM format using the `plastimatch` tool. It first installs MONAI Label and plastimatch, downloads a sample dataset, and then performs the conversion. ```bash # install MONAI Label (if you have not already) pip install monailabel # Install `plastimatch` NIFTI to DICOM converter sudo apt-get install plastimatch -y # download Task 2 MSD dataset monailabel datasets --download --name Task09_Spleen --output . # convert one of the NIFTI images to DICOM plastimatch convert --patient-id patient1 --input Task09_Spleen/imagesTs/spleen_1.nii.gz --output-dicom dicom_output ``` -------------------------------- ### Train Start Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/client/client Initiates a training task on the server for a specified model with given parameters. ```APIDOC ## POST /train/start/{model} ### Description Starts a training task for a specified model. ### Method POST ### Endpoint /train/start/{model} ### Parameters #### Path Parameters - **model** (string) - Required - The name of the model to train. #### Request Body - **params** (object) - Required - Additional JSON parameters for the training request. ### Request Example ```json { "params": { "epochs": 100, "learning_rate": 0.001 } } ``` ### Response #### Success Response (200) - **response** (object) - JSON response indicating the status of the training task initiation. #### Response Example ```json { "message": "Training task started successfully.", "task_id": "abc123xyz789" } ``` ``` -------------------------------- ### MONAILabel Main Application Methods Source: https://monai.readthedocs.io/projects/label/en/latest/genindex Details methods related to the main application control flow, such as starting servers and managing arguments. ```APIDOC ## MONAILabel Main Application Methods ### Description Methods associated with the main entry point of the MONAILabel application, handling command-line arguments and server actions. ### Methods #### `action_apps()` - **Description**: Action to list available applications. - **Method**: GET - **Endpoint**: `/apps` #### `action_datasets()` - **Description**: Action to list available datasets. - **Method**: GET - **Endpoint**: `/datasets` #### `action_plugins()` - **Description**: Action to list available plugins. - **Method**: GET - **Endpoint**: `/plugins` #### `action_start_server()` - **Description**: Action to start the MONAILabel server. - **Method**: POST - **Endpoint**: `/start` - **Request Body**: - `config_file` (string) - Optional - Path to the configuration file. #### `args_apps()` - **Description**: Parses arguments related to applications. - **Method**: CLI Argument Parser - **Endpoint**: N/A #### `args_datasets()` - **Description**: Parses arguments related to datasets. - **Method**: CLI Argument Parser - **Endpoint**: N/A #### `args_parser()` - **Description**: Main argument parser for the application. - **Method**: CLI Argument Parser - **Endpoint**: N/A #### `args_plugins()` - **Description**: Parses arguments related to plugins. - **Method**: CLI Argument Parser - **Endpoint**: N/A #### `args_start_server()` - **Description**: Parses arguments for starting the server. - **Method**: CLI Argument Parser - **Endpoint**: N/A ``` -------------------------------- ### Start MONAILabel Server with Pathology App and DSA Connection Source: https://monai.readthedocs.io/projects/label/en/latest/installation This command starts the MONAILabel server, utilizing the pathology application and connecting to a Digital Slide Archive (DSA) server. Ensure DSA is running and accessible at the specified URI. ```bash # start server using pathology connecting to DSA server monailabel start_server --app apps/pathology --studies http://0.0.0.0:8080/api/v1 ``` -------------------------------- ### Initialize MONAILabelClient Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/client/client Initializes the MONAILabelClient with a server URL, an optional temporary directory, and an optional client ID. The server URL is cleaned of trailing slashes. If no temporary directory is provided, it defaults to the system's temporary directory or '/tmp'. ```python client = MONAILabelClient(server_url="http://127.0.0.1:8000", tmpdir="/path/to/tmp") ``` -------------------------------- ### MONAILabelClient Initialization Source: https://monai.readthedocs.io/projects/label/en/latest/apis Initializes the MONAILabelClient to connect to a MONAILabel server. It allows specifying the server URL, a temporary directory for files, and an optional client ID. ```APIDOC ## MONAILabelClient Initialization ### Description Initializes the MONAILabelClient to connect to a MONAILabel server. It allows specifying the server URL, a temporary directory for files, and an optional client ID. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **server_url** (string) - Required - Server URL for MONAILabel (e.g. http://127.0.0.1:8000) * **tmpdir** (string) - Optional - Temp directory to save temporary files. If None then it uses tempfile.tempdir * **client_id** (string) - Optional - Client ID that will be added for all basic requests ### Request Example ```python from monailabel.client.client import MONAILabelClient client = MONAILabelClient(server_url='http://127.0.0.1:8000', client_id='my-client') ``` ### Response None (initialization does not return a value) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### BasicTrainTask Methods Source: https://monai.readthedocs.io/projects/label/en/latest/apidocs/monailabel.tasks.train.basic_train Provides documentation for various methods available within the BasicTrainTask class, including cleanup, configuration, event handling, and more. ```APIDOC ## BasicTrainTask Methods ### Description This section details the various methods available in the BasicTrainTask class for managing training processes, configurations, and data. ### Methods Overview #### cleanup(_request_) - **Description**: Cleans up resources associated with a request. - **Method**: `cleanup` #### config() - **Description**: Returns the configuration of the task. - **Method**: `config` #### event_names(_context_) - **Description**: Retrieves the names of events associated with a given context. - **Method**: `event_names` #### finalize(_context_) - **Description**: Finalizes the training process for a given context. - **Method**: `finalize` #### get_cache_dir(_request_) - **Description**: Gets the cache directory for a given request. - **Method**: `get_cache_dir` #### info() - **Description**: Provides information about the training task. - **Method**: `info` #### load_path(_output_dir_, _pretrained_=True) - **Description**: Loads a model from a specified path. - **Parameters**: - **output_dir** (string) - The directory to load the model from. - **pretrained** (boolean) - Whether to load a pre-trained model (default: True). - **Method**: `load_path` #### loss_function(_context_) - **Description**: Defines the loss function used during training. This is an abstract method. - **Method**: `_abstract _loss_function` #### lr_scheduler_handler(_context_) - **Description**: Handles the learning rate scheduler during training. - **Method**: `lr_scheduler_handler` #### network(_context_) - **Description**: Defines the network architecture to be used for training. This is an abstract method. - **Method**: `_abstract _network` #### optimizer(_context_) - **Description**: Defines the optimizer used for training. This is an abstract method. - **Method**: `_abstract _optimizer` #### partition_datalist(_context_, _shuffle_=False) - **Description**: Partitions the datalist for training and validation. - **Parameters**: - **context** (object) - The training context. - **shuffle** (boolean) - Whether to shuffle the datalist (default: False). - **Method**: `partition_datalist` ### Request Example ```json // Example for load_path method: { "output_dir": "/path/to/model/checkpoints", "pretrained": true } ``` ### Response #### Success Response (200) - **Varies** - The response depends on the specific method called. Some methods return configuration details, paths, or event names, while others are abstract and intended for implementation in subclasses. ``` -------------------------------- ### Generate Self-Signed SSL Certificates Source: https://monai.readthedocs.io/projects/label/en/latest/installation Creates self-signed SSL certificates (key and certificate files) using OpenSSL, which can then be used to run the MONAI Label server in HTTPS mode. ```bash # Create self-signed ssl cert openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout uvicorn-selfsigned.key -out uvicorn-selfsigned.crt ``` -------------------------------- ### Run Uvicorn Server with Configuration Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/main Starts the Uvicorn web server with specified host, port, application, and logging configurations. It accepts various arguments to customize the server's behavior, including SSL settings and concurrency limits. The log configuration is initialized based on provided arguments. ```python log_config = init_log_config(args.log_config, args.app, "app.log", args.verbose) if args.dryrun: return uvicorn.run( args.uvicorn_app, host=args.host, port=args.port, root_path=args.root_path, log_level=args.log_level, log_config=log_config, use_colors=True, access_log=args.access_log, ssl_keyfile=args.ssl_keyfile, ssl_certfile=args.ssl_certfile, ssl_keyfile_password=args.ssl_keyfile_password, ssl_ca_certs=args.ssl_ca_certs, workers=args.workers, limit_concurrency=args.limit_concurrency, ) ``` -------------------------------- ### Run MONAI Label Docker Container Source: https://monai.readthedocs.io/projects/label/en/latest/installation Launches the latest MONAI Label version from DockerHub with GPU and host networking enabled. This provides a self-contained environment for running MONAI Label. ```bash docker run -it --rm --gpus all --ipc=host --net=host -v ~:/workspace/ projectmonai/monailabel:latest bash ``` -------------------------------- ### Check DICOMweb Endpoint Status with cURL Source: https://monai.readthedocs.io/projects/label/en/latest/quickstart This command uses cURL to send a GET request to the default DICOMweb endpoint of an Orthanc server. It helps verify if the DICOMweb service is active and accessible. ```bash curl -X GET -v http://127.0.0.1:8042/dicomweb ``` -------------------------------- ### Configure File Watcher Patterns and Event Handlers (Python) Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/datastore/local This snippet configures patterns for file inclusion and sets up event handlers for file system events (creation, deletion, modification). It initializes a file observer, either PollingObserver or Observer, based on whether the datastore is on a mount point. Error handling is included for observer startup failures. ```python include_patterns.extend(f"{label_dir}{os.path.sep}{ext}" for ext in [*extensions]) # Config include_patterns.append(self._datastore_config_path) self._handler = PatternMatchingEventHandler(patterns=include_patterns) self._handler.on_created = self._on_any_event self._handler.on_deleted = self._on_any_event self._handler.on_modified = self._on_modify_event try: self._ignore_event_count = 0 self._ignore_event_config = False self._observer = PollingObserver() if self._is_on_mount(self._datastore.image_path()) else Observer() self._observer.schedule(self._handler, recursive=True, path=self._datastore_path) self._observer.start() except OSError as e: logger.error( "Failed to start File watcher. " "Local datastore will not update if images and labels are moved from datastore location." ) logger.error(str(e)) ``` -------------------------------- ### BasicTrainTask Initialization Source: https://monai.readthedocs.io/projects/label/en/latest/apidocs/monailabel.tasks.train.basic_train Initializes the BasicTrainTask with various parameters to configure model training, checkpointing, and experiment tracking. ```APIDOC ## BasicTrainTask Initialization ### Description Initializes the BasicTrainTask, setting up parameters for model directory, training configuration, automatic mixed precision (AMP), checkpoint loading/saving, and experiment tracking. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model_dir** (string) - Required - Base Model Dir to save the model checkpoints, events etc… - **description** (string) - Optional - Description for this task - **config** (dict) - Optional - K,V pairs to be part of user config - **amp** (boolean) - Optional - Enable AMP for training (default: True) - **load_path** (string) - Optional - Initialize model from existing checkpoint (pre-trained) - **load_dict** (dict) - Optional - Provide dictionary to load from checkpoint. If None, then net will be loaded - **publish_path** (string) - Optional - Publish path for best trained model (based on best key metric) - **stats_path** (string) - Optional - Path to save the train stats - **train_save_interval** (int) - Optional - checkpoint save interval for training (default: 20) - **val_interval** (int) - Optional - validation interval (run every x epochs) (default: 1) - **n_saved** (int) - Optional - max checkpoints to save (default: 5) - **final_filename** (string) - Optional - name of final checkpoint that will be saved (default: 'checkpoint_final.pt') - **key_metric_filename** (string) - Optional - best key metric model file name (default: 'model.pt') - **model_dict_key** (string) - Optional - key to save network weights into checkpoint (default: 'model') - **find_unused_parameters** (boolean) - Optional - Applicable for DDP/Multi GPU training (default: False) - **load_strict** (boolean) - Optional - Load pre-trained model in strict mode (default: False) - **labels** (list) - Optional - Labels to be used as part of training context (some transform might need) - **disable_meta_tracking** (boolean) - Optional - Disable tracking for faster training rate (unless you are using MetaTensor/batched transforms) (default: False) - **tracking** (string) - Optional - Tracking Manager for Experiment Management (only ‘mlflow’ is supported) (default: 'mlflow') - **tracking_uri** (string) - Optional - Tracking URI for Experiment Management - **tracking_experiment_name** (string) - Optional - Name for tracking experiment ### Request Example ```json { "model_dir": "/path/to/models", "description": "My custom training task", "amp": true, "load_path": "/path/to/pretrained/model.pt", "tracking_uri": "http://localhost:5000" } ``` ### Response #### Success Response (200) - **None** - This is an initializer, it does not return a value directly. #### Response Example None ``` -------------------------------- ### Load Labelmap from TXT File Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/datastore/cvat Loads a label map from a text file where each line defines a label and its RGB color. It parses lines, splitting by ':' to get the name and RGB values. Supports comments starting with '#'. Returns a dictionary mapping label names to RGB tuples. ```python def _load_labelmap_txt(self, file): labelmap = {} if os.path.exists(file): with open(file) as f: for line in f.readlines(): if line and not line.startswith("#"): fields = line.split(":") name = fields[0] rgb = tuple(int(c) for c in fields[1].split(",")) labelmap[name] = rgb return labelmap ``` -------------------------------- ### Start Training Task on MONAILabel Server Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/client/client Initiates a model training task on the MONAILabel server. This method requires the model name and a dictionary of training parameters. It prepares the parameters by updating the client ID before sending the request. Dependencies include _update_client_id. ```python def train_start(self, model, params): """ Run Train Task :param model: Name of Model :param params: Additional configs/json params as part of Train request :return: json response """ params = self._update_client_id(params) ``` -------------------------------- ### Main Worker Entry Point for Training (Python) Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/tasks/train/basic_train This is the main entry point for a worker process in a distributed training setup. It initializes logging for the worker and then calls the task's train method to start the training process, passing necessary arguments like rank, world size, and data. ```python def main_worker(rank, world_size, request, datalist, task: BasicTrainTask): logging.basicConfig( level=logging.INFO, format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", force=True, ) logger.info(f"Main Worker: {rank}") task.train(rank, world_size, request, datalist) ``` -------------------------------- ### Check if Python Package is Installed Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/config A utility function to check if a given Python package is installed in the current environment. It iterates through installed distributions and compares their names. This is used to conditionally set model URLs based on package availability. ```python import os from distutils.util import strtobool from importlib.metadata import distributions from typing import Any, Dict, List, Optional from pydantic import AnyHttpUrl from pydantic_settings import BaseSettings, SettingsConfigDict [docs]def is_package_installed(name): return name in (x.metadata.get("Name") for x in distributions() if x.metadata is not None) [docs]class Settings(BaseSettings): MONAI_LABEL_API_STR: str = "" MONAI_LABEL_PROJECT_NAME: str = "MONAILabel" MONAI_LABEL_APP_DIR: str = "" MONAI_LABEL_STUDIES: str = "" MONAI_LABEL_APP_CONF: Dict[str, Any] = {} MONAI_LABEL_AUTH_ENABLE: bool = False MONAI_LABEL_AUTH_REALM_URI: str = "http://localhost:8080/realms/monailabel" MONAI_LABEL_AUTH_TIMEOUT: int = 10 MONAI_LABEL_AUTH_TOKEN_USERNAME: str = "preferred_username" MONAI_LABEL_AUTH_TOKEN_EMAIL: str = "email" MONAI_LABEL_AUTH_TOKEN_NAME: str = "name" MONAI_LABEL_AUTH_TOKEN_ROLES: str = "realm_access#roles" MONAI_LABEL_AUTH_CLIENT_ID: str = "monailabel-app" MONAI_LABEL_AUTH_ROLE_ADMIN: str = "monailabel-admin" MONAI_LABEL_AUTH_ROLE_REVIEWER: str = "monailabel-reviewer" MONAI_LABEL_AUTH_ROLE_ANNOTATOR: str = "monailabel-annotator" MONAI_LABEL_AUTH_ROLE_USER: str = "monailabel-user" MONAI_LABEL_TASKS_TRAIN: bool = True MONAI_LABEL_TASKS_STRATEGY: bool = True MONAI_LABEL_TASKS_SCORING: bool = True MONAI_LABEL_TASKS_BATCH_INFER: bool = True MONAI_LABEL_DATASTORE: str = "" MONAI_LABEL_DATASTORE_URL: str = "" MONAI_LABEL_DATASTORE_USERNAME: str = "" MONAI_LABEL_DATASTORE_PASSWORD: str = "" MONAI_LABEL_DATASTORE_API_KEY: str = "" MONAI_LABEL_DATASTORE_CACHE_PATH: str = "" MONAI_LABEL_DATASTORE_PROJECT: str = "" MONAI_LABEL_DATASTORE_ASSET_PATH: str = "" MONAI_LABEL_DATASTORE_DSA_ANNOTATION_GROUPS: str = "" MONAI_LABEL_DICOMWEB_USERNAME: str = "" # will be deprecated; use MONAI_LABEL_DATASTORE_USERNAME MONAI_LABEL_DICOMWEB_PASSWORD: str = "" # will be deprecated; use MONAI_LABEL_DATASTORE_PASSWORD MONAI_LABEL_DICOMWEB_CACHE_PATH: str = "" # will be deprecated; use MONAI_LABEL_DATASTORE_CACHE_PATH MONAI_LABEL_QIDO_PREFIX: Optional[str] = None MONAI_LABEL_WADO_PREFIX: Optional[str] = None MONAI_LABEL_STOW_PREFIX: Optional[str] = None MONAI_LABEL_DICOMWEB_FETCH_BY_FRAME: bool = False MONAI_LABEL_DICOMWEB_CONVERT_TO_NIFTI: bool = True MONAI_LABEL_DICOMWEB_SEARCH_FILTER: Dict[str, Any] = {"Modality": "CT"} MONAI_LABEL_DICOMWEB_CACHE_EXPIRY: int = 7200 MONAI_LABEL_DICOMWEB_PROXY_TIMEOUT: float = 30.0 MONAI_LABEL_DICOMWEB_READ_TIMEOUT: float = 5.0 MONAI_LABEL_DATASTORE_AUTO_RELOAD: bool = True MONAI_LABEL_DATASTORE_READ_ONLY: bool = False MONAI_LABEL_DATASTORE_FILE_EXT: List[str] = [ "*.nii.gz", "*.nii", "*.nrrd", "*.jpg", "*.png", "*.tif", "*.svs", "*.xml", ] MONAI_LABEL_SERVER_PORT: int = 8000 MONAI_LABEL_CORS_ORIGINS: List[AnyHttpUrl] = [] MONAI_LABEL_AUTO_UPDATE_SCORING: bool = True MONAI_LABEL_SESSIONS: bool = True MONAI_LABEL_SESSION_PATH: str = "" MONAI_LABEL_SESSION_EXPIRY: int = 3600 MONAI_LABEL_INFER_CONCURRENCY: int = -1 MONAI_LABEL_INFER_TIMEOUT: int = 600 MONAI_LABEL_TRACKING_ENABLED: bool = True MONAI_LABEL_TRACKING_URI: str = "" MONAI_ZOO_SOURCE: str = os.environ.get("BUNDLE_DOWNLOAD_SRC", "monaihosting") MONAI_ZOO_REPO: str = "Project-MONAI/model-zoo/hosting_storage_v1" MONAI_ZOO_AUTH_TOKEN: str = "" # Refer: https://github.com/facebookresearch/sam2?tab=readme-ov-file#model-description # Refer: https://huggingface.co/facebook/sam2-hiera-large MONAI_SAM_MODEL_PT: str = ( "https://huggingface.co/facebook/sam2.1-hiera-large/resolve/main/sam2.1_hiera_large.pt" if is_package_installed("SAM-2") else "https://huggingface.co/facebook/sam2-hiera-large/resolve/main/sam2_hiera_large.pt" ) MONAI_SAM_MODEL_CFG: str = ( "https://huggingface.co/facebook/sam2.1-hiera-large/resolve/main/sam2.1_hiera_l.yaml" if is_package_installed("SAM-2") else "https://huggingface.co/facebook/sam2-hiera-large/resolve/main/sam2_hiera_l.yaml" ) MONAI_LABEL_USE_ITK_FOR_DICOM_SEG: bool = bool( strtobool(os.environ.get("MONAI_LABEL_USE_ITK_FOR_DICOM_SEG", "True")) ) model_config = SettingsConfigDict( env_file=".env", case_sensitive=True, extra="ignore", ) settings = Settings() RBAC_ADMIN = f"|RBAC: {settings.MONAI_LABEL_AUTH_ROLE_ADMIN}| - " if settings.MONAI_LABEL_AUTH_ENABLE else "" RBAC_REVIEWER = f"|RBAC: {settings.MONAI_LABEL_AUTH_ROLE_REVIEWER}| - " if settings.MONAI_LABEL_AUTH_ENABLE else "" RBAC_ANNOTATOR = f"|RBAC: {settings.MONAI_LABEL_AUTH_ROLE_ANNOTATOR}| - " if settings.MONAI_LABEL_AUTH_ENABLE else "" ``` -------------------------------- ### monailabel.utils.others.class_utils.init_class Source: https://monai.readthedocs.io/projects/label/en/latest/apidocs/monailabel.utils.others.class_utils Initializes a class given its path and arguments. ```APIDOC ## init_class ### Description Initializes a class given its path and arguments. ### Method (Not specified, likely a utility function) ### Endpoint (Not applicable, this is a function) ### Parameters - **_class_path_** (any) - Description not provided. - **_class_args_** (any) - Description not provided. ### Request Example (Not applicable) ### Response (Return type not specified) ### Response Example (Not applicable) ``` -------------------------------- ### Get Basename Without Extension Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/utils/others/generic Combines `get_basename` and `file_ext` to return the basename of a path with its extension removed. It first gets the basename and then strips the identified file extension. ```python def get_basename_no_ext(path): p = get_basename(path) e = file_ext(p) return p.rstrip(e) ``` -------------------------------- ### Initialize CVATDatastore with Configuration Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/datastore/cvat Initializes the CVATDatastore, setting up connections to a CVAT instance and configuring project details, authentication, and label schemas. It supports custom labels and normalization options. ```python from monailabel.datastore.local import LocalDatastore from monailabel.interfaces.datastore import DefaultLabelTag from monailabel.utils.others.generic import get_mime_type import json import logging import os import shutil import tempfile import time import urllib.parse import numpy as np import requests from PIL import Image from requests.auth import HTTPBasicAuth logger = logging.getLogger(__name__) class CVATDatastore(LocalDatastore): def __init__( self, datastore_path, api_url, username=None, password=None, project="MONAILabel", task_prefix="ActiveLearning_Iteration", image_quality=70, labels=None, normalize_label=True, segment_size=1, **kwargs, ): default_labels = [ {"name": "Tool", "attributes": [], "color": "#66ff66"}, {"name": "InBody", "attributes": [], "color": "#ff0000"}, {"name": "OutBody", "attributes": [], "color": "#0000ff"}, ] labels = labels if labels else default_labels labels = json.loads(labels) if isinstance(labels, str) else labels self.api_url = api_url.rstrip("/").strip() self.auth = HTTPBasicAuth(username, password) if username else None self.project = project self.task_prefix = task_prefix self.image_quality = image_quality self.labels = labels self.label_map = {l["name"]: idx for idx, l in enumerate(labels, start=1)} self.normalize_label = normalize_label self.segment_size = segment_size logger.info(f"CVAT:: API URL: {api_url}") logger.info(f"CVAT:: UserName: {username}") logger.info(f"CVAT:: Password: {'*' * len(password) if password else ''}") logger.info(f"CVAT:: Project: {project}") logger.info(f"CVAT:: Task Prefix: {task_prefix}") logger.info(f"CVAT:: Image Quality: {image_quality}") logger.info(f"CVAT:: Labels: {labels}") logger.info(f"CVAT:: Normalize Label: {normalize_label}") logger.info(f"CVAT:: Segment Size: {normalize_label}") super().__init__(datastore_path=datastore_path, **kwargs) self.done_prefix = "DONE" ``` -------------------------------- ### Get Label Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/datastore/dsa Retrieves label data associated with a given image ID. It makes a GET request to the annotation endpoint for the specified item. ```python def get_label(self, label_id: str, label_tag: str, params=None) -> Any: return self.gc.get(f"annotation/item/{label_id}") ``` -------------------------------- ### MONAILabel Client Initialization Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/client/client Initializes the MONAILabel client with the server URL, an optional temporary directory, and an optional client ID. ```APIDOC ## MONAILabelClient Constructor ### Description Initializes the MONAILabel client with the server URL, an optional temporary directory, and an optional client ID. ### Method __init__ ### Parameters - **server_url** (str) - Required - Server URL for MONAILabel (e.g. http://127.0.0.1:8000) - **tmpdir** (str) - Optional - Temp directory to save temporary files. If None then it uses tempfile.tempdir. - **client_id** (str) - Optional - Client ID that will be added for all basic requests ``` -------------------------------- ### Initialize Summary Writer and Event Handler Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/deepedit/handlers Initializes a SummaryWriter for logging and attaches an event handler to the engine for epoch completion. It configures logging directories, intervals, and transformations, and integrates with distributed training by prefixing tags with the process rank. ```python def __init__( self, summary_writer: Optional[SummaryWriter] = None, log_dir: str = "./runs", tag_prefix="", interval: int = 1, batch_transform: Callable = lambda x: x, output_transform: Callable = lambda x: x, batch_limit=1, device=None, ) -> None: self.writer = SummaryWriter(log_dir=log_dir) if summary_writer is None else summary_writer self.tag_prefix = tag_prefix self.interval = interval self.batch_transform = batch_transform self.output_transform = output_transform self.batch_limit = batch_limit self.device = device self.logger = logging.getLogger(__name__) if dist.is_initialized(): self.tag_prefix = f"{self.tag_prefix}r{dist.get_rank()}-" self.metric_data: Dict[Any, Any] = dict() def attach(self, engine: Engine) -> None: engine.add_event_handler(Events.EPOCH_COMPLETED(every=self.interval), self, "epoch") ``` -------------------------------- ### Get MONAILabel Session Details Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/client/client Retrieves details for a specific MONAILabel session using its session ID. It makes a GET request to the server and returns a JSON response with session information. Errors during the request are caught and re-raised as MONAILabelClientException. ```python def get_session(self, session_id): """ Get Session :param session_id: Session Id :return: json response which contains more details about the session """ selector = f"/session/{MONAILabelUtils.urllib_quote_plus(session_id)}" status, response, _, _ = MONAILabelUtils.http_method("GET", self._server_url, selector, headers=self._headers) if status != 200: raise MONAILabelClientException( MONAILabelError.SERVER_ERROR, f"Status: {status}; Response: {bytes_to_str(response)}", status, response ) response = bytes_to_str(response) logging.debug(f"Response: {response}") return json.loads(response) ``` -------------------------------- ### Start MONAI Label Server Action (Python) Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/main Handles the 'start_server' action for MONAI Label. This action initiates the MONAI Label server, involving validation of arguments and initialization of server settings. ```python [docs] def action_start_server(self, args): self.start_server_validate_args(args) self.start_server_init_settings(args) ``` -------------------------------- ### Get Datastore Status Source: https://monai.readthedocs.io/projects/label/en/latest/apidocs/monailabel.interfaces.datastore Retrieves the current statistics and status of the datastore. ```APIDOC ## GET /datastore/status ### Description Returns current statistics of the datastore. ### Method GET ### Endpoint /datastore/status ### Response #### Success Response (200) - **status** (Dict[str, Any]) - A dictionary containing various statistics and status information about the datastore. #### Response Example ```json { "status": { "total_images": 100, "total_labels": 500, "storage_used": "10GB" } } ``` ``` -------------------------------- ### Initialize Class from Path and Args in Python Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/utils/others/class_utils This function initializes a class given its path and arguments. It imports the module, reloads it, and then instantiates the class using the provided arguments. It raises an exception if the class path is not in the correct format. This is useful for dynamic class instantiation. ```python def init_class(class_path, class_args): if "." not in class_path: raise MONAILabelException( MONAILabelError.CLASS_INIT_ERROR, "Class path need to be in the form [module/file].[class_name]." ) module_name, class_name = class_path.rsplit(".", 1) m = importlib.import_module(module_name) importlib.reload(m) c = getattr(m, class_name) return c(**class_args) if class_args else c() ``` -------------------------------- ### Initialize Datastore from File - Python Source: https://monai.readthedocs.io/projects/label/en/latest/_modules/monailabel/datastore/local Initializes or updates the datastore from its configuration file. It acquires a file lock, checks if the configuration file exists, and compares its modification timestamp with a stored timestamp to determine if an update is needed. This function is crucial for ensuring the datastore reflects the latest state. ```python import os import logging from filelock import FileLock logger = logging.getLogger(__name__) def _init_from_datastore_file(self, throw_exception=False): try: with FileLock(self._lock_file): logger.debug("Acquired the lock!") if os.path.exists(self._datastore_config_path): ts = os.stat(self._datastore_config_path).st_mtime if self._config_ts != ts: # Further logic to load and update datastore would follow here ```