Skip to content

napari_cellseg3d.code_models.workers_utils

Several worker-related utilities for inference and training.

Classes:

Name Description
InferenceResult

Class to record results of a segmentation job.

LogSignal

Signal to send messages to be logged from another thread.

ONNXModelWrapper

Class to replace torch model by ONNX Runtime session.

QuantileNormalization

MONAI-style transform to normalize each image in a batch individually by quantile normalization.

QuantileNormalizationd

MONAI-style dict transform to normalize each image in a batch individually by quantile normalization.

RemapTensor

Remap the values of a tensor to a new range.

Threshold

Threshold a tensor to 0 or 1.

TqdmToLogSignal

File-like object to redirect tqdm output to the logger widget in the GUI that self.log emits to.

TrainingReport

Class to record results of a training job.

WeightsDownloader

A utility class the downloads the weights of a model when needed.

InferenceResult dataclass

Class to record results of a segmentation job.

Source code in napari_cellseg3d/code_models/workers_utils.py
293
294
295
296
297
298
299
300
301
302
303
@dataclass
class InferenceResult:
    """Class to record results of a segmentation job."""

    image_id: int = 0
    original: np.array = None
    instance_labels: np.array = None
    crf_results: np.array = None
    stats: "np.array[ImageStats]" = None
    semantic_segmentation: np.array = None
    model_name: str = None

LogSignal

Bases: WorkerBaseSignals

Signal to send messages to be logged from another thread.

Separate from Worker instances as indicated on this post_

.. _on this post: https://stackoverflow.com/questions/2970312/pyqt4-qtcore-pyqtsignal-object-has-no-attribute-connect

Methods:

Name Description
__init__

Creates a LogSignal.

Attributes:

Name Type Description
error_signal

qtpy.QtCore.Signal: signal to be sent when some error should be emitted in main thread

log_signal

qtpy.QtCore.Signal: signal to be sent when some text should be logged

log_w_replace_signal

qtpy.QtCore.Signal: signal to be sent when some text should be logged, replacing the last line

warn_signal

qtpy.QtCore.Signal: signal to be sent when some warning should be emitted in main thread

Source code in napari_cellseg3d/code_models/workers_utils.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
class LogSignal(WorkerBaseSignals):
    """Signal to send messages to be logged from another thread.

    Separate from Worker instances as indicated `on this post`_

    .. _on this post: https://stackoverflow.com/questions/2970312/pyqt4-qtcore-pyqtsignal-object-has-no-attribute-connect
    """  # TODO link ?

    log_signal = Signal(str)
    """qtpy.QtCore.Signal: signal to be sent when some text should be logged"""
    log_w_replace_signal = Signal(str)
    """qtpy.QtCore.Signal: signal to be sent when some text should be logged, replacing the last line"""
    warn_signal = Signal(str)
    """qtpy.QtCore.Signal: signal to be sent when some warning should be emitted in main thread"""
    error_signal = Signal(Exception, str)
    """qtpy.QtCore.Signal: signal to be sent when some error should be emitted in main thread"""

    # Should not be an instance variable but a class variable, not defined in __init__, see
    # https://stackoverflow.com/questions/2970312/pyqt4-qtcore-pyqtsignal-object-has-no-attribute-connect

    def __init__(self, parent=None):
        """Creates a LogSignal."""
        super().__init__(parent=parent)

error_signal class-attribute instance-attribute

error_signal = Signal(Exception, str)

qtpy.QtCore.Signal: signal to be sent when some error should be emitted in main thread

log_signal class-attribute instance-attribute

log_signal = Signal(str)

qtpy.QtCore.Signal: signal to be sent when some text should be logged

log_w_replace_signal class-attribute instance-attribute

log_w_replace_signal = Signal(str)

qtpy.QtCore.Signal: signal to be sent when some text should be logged, replacing the last line

warn_signal class-attribute instance-attribute

warn_signal = Signal(str)

qtpy.QtCore.Signal: signal to be sent when some warning should be emitted in main thread

__init__

__init__(parent=None)

Creates a LogSignal.

Source code in napari_cellseg3d/code_models/workers_utils.py
138
139
140
def __init__(self, parent=None):
    """Creates a LogSignal."""
    super().__init__(parent=parent)

ONNXModelWrapper

Bases: Module

Class to replace torch model by ONNX Runtime session.

Methods:

Name Description
__init__

Creates an ONNXModelWrapper.

eval

Dummy function.

forward

Wraps ONNX output in a torch tensor.

to

Dummy function.

Source code in napari_cellseg3d/code_models/workers_utils.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
class ONNXModelWrapper(torch.nn.Module):
    """Class to replace torch model by ONNX Runtime session."""

    def __init__(self, file_location):
        """Creates an ONNXModelWrapper."""
        super().__init__()
        try:
            import onnxruntime as ort
        except ImportError as e:
            logger.error("ONNX is not installed but ONNX model was loaded")
            logger.error(e)
            msg = "PLEASE INSTALL ONNX CPU OR GPU USING: pip install napari-cellseg3d[onnx-cpu] OR pip install napari-cellseg3d[onnx-gpu]"
            logger.error(msg)
            raise ImportError(msg) from e

        self.ort_session = ort.InferenceSession(
            file_location,
            providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
        )

    def forward(self, modeL_input):
        """Wraps ONNX output in a torch tensor."""
        outputs = self.ort_session.run(None, {"input": modeL_input.cpu().numpy()})
        return torch.tensor(outputs[0])

    def eval(self):
        """Dummy function.

        Replaces model.eval().
        """
        pass

    def to(self, device):
        """Dummy function.

        Replaces model.to(device).
        """
        pass

__init__

__init__(file_location)

Creates an ONNXModelWrapper.

Source code in napari_cellseg3d/code_models/workers_utils.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def __init__(self, file_location):
    """Creates an ONNXModelWrapper."""
    super().__init__()
    try:
        import onnxruntime as ort
    except ImportError as e:
        logger.error("ONNX is not installed but ONNX model was loaded")
        logger.error(e)
        msg = "PLEASE INSTALL ONNX CPU OR GPU USING: pip install napari-cellseg3d[onnx-cpu] OR pip install napari-cellseg3d[onnx-gpu]"
        logger.error(msg)
        raise ImportError(msg) from e

    self.ort_session = ort.InferenceSession(
        file_location,
        providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
    )

eval

eval()

Dummy function.

Replaces model.eval().

Source code in napari_cellseg3d/code_models/workers_utils.py
188
189
190
191
192
193
def eval(self):
    """Dummy function.

    Replaces model.eval().
    """
    pass

forward

forward(modeL_input)

Wraps ONNX output in a torch tensor.

Source code in napari_cellseg3d/code_models/workers_utils.py
183
184
185
186
def forward(self, modeL_input):
    """Wraps ONNX output in a torch tensor."""
    outputs = self.ort_session.run(None, {"input": modeL_input.cpu().numpy()})
    return torch.tensor(outputs[0])

to

to(device)

Dummy function.

Replaces model.to(device).

Source code in napari_cellseg3d/code_models/workers_utils.py
195
196
197
198
199
200
def to(self, device):
    """Dummy function.

    Replaces model.to(device).
    """
    pass

QuantileNormalization

Bases: Transform

MONAI-style transform to normalize each image in a batch individually by quantile normalization.

Methods:

Name Description
__call__

Normalize each image in a batch individually by quantile normalization.

Source code in napari_cellseg3d/code_models/workers_utils.py
229
230
231
232
233
234
class QuantileNormalization(Transform):
    """MONAI-style transform to normalize each image in a batch individually by quantile normalization."""

    def __call__(self, img):
        """Normalize each image in a batch individually by quantile normalization."""
        return utils.quantile_normalization(img)

__call__

__call__(img)

Normalize each image in a batch individually by quantile normalization.

Source code in napari_cellseg3d/code_models/workers_utils.py
232
233
234
def __call__(self, img):
    """Normalize each image in a batch individually by quantile normalization."""
    return utils.quantile_normalization(img)

QuantileNormalizationd

Bases: MapTransform

MONAI-style dict transform to normalize each image in a batch individually by quantile normalization.

Methods:

Name Description
__call__

Normalize each image in a batch individually by quantile normalization.

__init__

Creates a QuantileNormalizationd transform.

normalizer

Normalize each image in a batch individually by quantile normalization.

Source code in napari_cellseg3d/code_models/workers_utils.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
class QuantileNormalizationd(MapTransform):
    """MONAI-style dict transform to normalize each image in a batch individually by quantile normalization."""

    def __init__(self, keys, allow_missing_keys: bool = False):
        """Creates a QuantileNormalizationd transform."""
        super().__init__(keys, allow_missing_keys)

    def __call__(self, data):
        """Normalize each image in a batch individually by quantile normalization."""
        d = dict(data)
        for key in self.keys:
            d[key] = self.normalizer(d[key])
        return d

    def normalizer(self, image: torch.Tensor):
        """Normalize each image in a batch individually by quantile normalization."""
        if image.ndim == 4:
            for i in range(image.shape[0]):
                image[i] = utils.quantile_normalization(image[i])
        else:
            raise NotImplementedError(
                "QuantileNormalizationd only supports 2D and 3D tensors with NCHWD format"
            )
        return image

__call__

__call__(data)

Normalize each image in a batch individually by quantile normalization.

Source code in napari_cellseg3d/code_models/workers_utils.py
210
211
212
213
214
215
def __call__(self, data):
    """Normalize each image in a batch individually by quantile normalization."""
    d = dict(data)
    for key in self.keys:
        d[key] = self.normalizer(d[key])
    return d

__init__

__init__(keys, allow_missing_keys: bool = False)

Creates a QuantileNormalizationd transform.

Source code in napari_cellseg3d/code_models/workers_utils.py
206
207
208
def __init__(self, keys, allow_missing_keys: bool = False):
    """Creates a QuantileNormalizationd transform."""
    super().__init__(keys, allow_missing_keys)

normalizer

normalizer(image: Tensor)

Normalize each image in a batch individually by quantile normalization.

Source code in napari_cellseg3d/code_models/workers_utils.py
217
218
219
220
221
222
223
224
225
226
def normalizer(self, image: torch.Tensor):
    """Normalize each image in a batch individually by quantile normalization."""
    if image.ndim == 4:
        for i in range(image.shape[0]):
            image[i] = utils.quantile_normalization(image[i])
    else:
        raise NotImplementedError(
            "QuantileNormalizationd only supports 2D and 3D tensors with NCHWD format"
        )
    return image

RemapTensor

Bases: Transform

Remap the values of a tensor to a new range.

Methods:

Name Description
__call__

Remap the values of a tensor to a new range.

__init__

Creates a RemapTensor transform.

Source code in napari_cellseg3d/code_models/workers_utils.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
class RemapTensor(Transform):
    """Remap the values of a tensor to a new range."""

    def __init__(self, new_max, new_min):
        """Creates a RemapTensor transform.

        Args:
            new_max (float): new maximum value
            new_min (float): new minimum value
        """
        super().__init__()
        self.max = new_max
        self.min = new_min

    def __call__(self, img):
        """Remap the values of a tensor to a new range."""
        return utils.remap_image(img, new_max=self.max, new_min=self.min)

__call__

__call__(img)

Remap the values of a tensor to a new range.

Source code in napari_cellseg3d/code_models/workers_utils.py
251
252
253
def __call__(self, img):
    """Remap the values of a tensor to a new range."""
    return utils.remap_image(img, new_max=self.max, new_min=self.min)

__init__

__init__(new_max, new_min)

Creates a RemapTensor transform.

Parameters:

Name Type Description Default
new_max float

new maximum value

required
new_min float

new minimum value

required
Source code in napari_cellseg3d/code_models/workers_utils.py
240
241
242
243
244
245
246
247
248
249
def __init__(self, new_max, new_min):
    """Creates a RemapTensor transform.

    Args:
        new_max (float): new maximum value
        new_min (float): new minimum value
    """
    super().__init__()
    self.max = new_max
    self.min = new_min

Threshold

Bases: Transform

Threshold a tensor to 0 or 1.

Methods:

Name Description
__call__

Threshold a tensor to 0 or 1.

__init__

Creates a Threshold transform.

Source code in napari_cellseg3d/code_models/workers_utils.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
class Threshold(Transform):
    """Threshold a tensor to 0 or 1."""

    def __init__(self, threshold=0.5):
        """Creates a Threshold transform.

        Args:
            threshold (float): threshold value
        """
        super().__init__()
        self.threshold = threshold

    def __call__(self, img):
        """Threshold a tensor to 0 or 1."""
        res = torch.where(img > self.threshold, 1, 0)
        return torch.Tensor(res).float()

__call__

__call__(img)

Threshold a tensor to 0 or 1.

Source code in napari_cellseg3d/code_models/workers_utils.py
287
288
289
290
def __call__(self, img):
    """Threshold a tensor to 0 or 1."""
    res = torch.where(img > self.threshold, 1, 0)
    return torch.Tensor(res).float()

__init__

__init__(threshold=0.5)

Creates a Threshold transform.

Parameters:

Name Type Description Default
threshold float

threshold value

0.5
Source code in napari_cellseg3d/code_models/workers_utils.py
278
279
280
281
282
283
284
285
def __init__(self, threshold=0.5):
    """Creates a Threshold transform.

    Args:
        threshold (float): threshold value
    """
    super().__init__()
    self.threshold = threshold

TqdmToLogSignal

File-like object to redirect tqdm output to the logger widget in the GUI that self.log emits to.

Methods:

Name Description
__init__

Creates a TqdmToLogSignal.

flush

Flushes the output. Unused.

write

Writes the output to the log_func.

Source code in napari_cellseg3d/code_models/workers_utils.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
class TqdmToLogSignal:
    """File-like object to redirect tqdm output to the logger widget in the GUI that self.log emits to."""

    def __init__(self, log_func):
        """Creates a TqdmToLogSignal.

        Args:
        log_func (callable): function to call to log the output.
        """
        self.log_func = log_func

    def write(self, x):
        """Writes the output to the log_func."""
        self.log_func(x.strip())

    def flush(self):
        """Flushes the output. Unused."""
        pass

__init__

__init__(log_func)

Creates a TqdmToLogSignal.

Args: log_func (callable): function to call to log the output.

Source code in napari_cellseg3d/code_models/workers_utils.py
146
147
148
149
150
151
152
def __init__(self, log_func):
    """Creates a TqdmToLogSignal.

    Args:
    log_func (callable): function to call to log the output.
    """
    self.log_func = log_func

flush

flush()

Flushes the output. Unused.

Source code in napari_cellseg3d/code_models/workers_utils.py
158
159
160
def flush(self):
    """Flushes the output. Unused."""
    pass

write

write(x)

Writes the output to the log_func.

Source code in napari_cellseg3d/code_models/workers_utils.py
154
155
156
def write(self, x):
    """Writes the output to the log_func."""
    self.log_func(x.strip())

TrainingReport dataclass

Class to record results of a training job.

Source code in napari_cellseg3d/code_models/workers_utils.py
306
307
308
309
310
311
312
313
314
315
316
@dataclass
class TrainingReport:
    """Class to record results of a training job."""

    show_plot: bool = True
    epoch: int = 0
    loss_1_values: t.Dict = None  # example : {"Loss" : [0.1, 0.2, 0.3]}
    loss_2_values: t.List = None
    weights: np.array = None
    images_dict: t.Dict = None  # output, discrete output, target, target labels
    supervised: bool = True

WeightsDownloader

A utility class the downloads the weights of a model when needed.

Methods:

Name Description
__init__

Creates a WeightsDownloader, optionally with a log widget to display the progress.

download_weights

Downloads a specific pretrained model.

Source code in napari_cellseg3d/code_models/workers_utils.py
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class WeightsDownloader:
    """A utility class the downloads the weights of a model when needed."""

    def __init__(self, log_widget: t.Optional[ui.Log] = None):
        """Creates a WeightsDownloader, optionally with a log widget to display the progress.

        Args:
            log_widget (log_utility.Log): a Log to display the progress bar in. If None, uses logger.info()
        """
        self.log_widget = log_widget

    def download_weights(self, model_name: str, model_weights_filename: str) -> Path:
        """Downloads a specific pretrained model.

        This code is adapted from DeepLabCut with permission from MWMathis.

        Args:
            model_name (str): name of the model to download
            model_weights_filename (str): name of the .pth file expected for the model

        Returns:
            Path: path to the weights file, in utils.get_pretrained_weights_dir()
        """
        import json
        import tarfile
        import urllib.request

        def show_progress(_, block_size, __):  # count, block_size, total_size
            pbar.update(block_size)

        logger.info("*" * 20)
        pretrained_folder_path = utils.get_pretrained_weights_dir()
        pretrained_folder_path.mkdir(parents=True, exist_ok=True)
        json_path = utils.PACKAGE_PRETRAINED_DIR / Path("pretrained_model_urls.json")

        check_path = pretrained_folder_path / Path(model_weights_filename)

        if Path(check_path).is_file():
            message = f"Weight file {model_weights_filename} already exists, skipping download"
            if self.log_widget is not None:
                self.log_widget.print_and_log(message, printing=False)
            logger.info(message)
            return check_path

        with Path.open(json_path) as f:
            neturls = json.load(f)
        if model_name in neturls:
            url = neturls[model_name]
            response = urllib.request.urlopen(url)

            start_message = f"Downloading the model from HuggingFace {url}...."
            total_size = int(response.getheader("Content-Length"))
            if self.log_widget is None:
                logger.info(start_message)
                pbar = tqdm(unit="B", total=total_size, position=0)
            else:
                self.log_widget.print_and_log(start_message)
                pbar = tqdm(
                    unit="B",
                    total=total_size,
                    position=0,
                    file=self.log_widget,
                )

            filename, _ = urllib.request.urlretrieve(url, reporthook=show_progress)
            with tarfile.open(filename, mode="r:gz") as tar:

                def is_within_directory(directory, target):
                    abs_directory = Path(directory).resolve()
                    abs_target = Path(target).resolve()
                    # prefix = os.path.commonprefix([abs_directory, abs_target])
                    logger.debug(abs_directory)
                    logger.debug(abs_target)
                    logger.debug(abs_directory.parents)

                    return abs_directory in abs_target.parents

                def safe_extract(tar, path=".", members=None, *, numeric_owner=False):
                    for member in tar.getmembers():
                        member_path = str(Path(path) / member.name)
                        if not is_within_directory(path, member_path):
                            raise Exception("Attempted Path Traversal in Tar File")

                    tar.extractall(path, members, numeric_owner=numeric_owner)

                safe_extract(tar, pretrained_folder_path)
                # tar.extractall(pretrained_folder_path)
        else:
            raise ValueError(
                f"Unknown model: {model_name}. Should be one of {', '.join(neturls)}"
            )
        return check_path

__init__

__init__(log_widget: Optional[Log] = None)

Creates a WeightsDownloader, optionally with a log widget to display the progress.

Parameters:

Name Type Description Default
log_widget Log

a Log to display the progress bar in. If None, uses logger.info()

None
Source code in napari_cellseg3d/code_models/workers_utils.py
27
28
29
30
31
32
33
def __init__(self, log_widget: t.Optional[ui.Log] = None):
    """Creates a WeightsDownloader, optionally with a log widget to display the progress.

    Args:
        log_widget (log_utility.Log): a Log to display the progress bar in. If None, uses logger.info()
    """
    self.log_widget = log_widget

download_weights

download_weights(model_name: str, model_weights_filename: str) -> Path

Downloads a specific pretrained model.

This code is adapted from DeepLabCut with permission from MWMathis.

Parameters:

Name Type Description Default
model_name str

name of the model to download

required
model_weights_filename str

name of the .pth file expected for the model

required

Returns:

Name Type Description
Path Path

path to the weights file, in utils.get_pretrained_weights_dir()

Source code in napari_cellseg3d/code_models/workers_utils.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def download_weights(self, model_name: str, model_weights_filename: str) -> Path:
    """Downloads a specific pretrained model.

    This code is adapted from DeepLabCut with permission from MWMathis.

    Args:
        model_name (str): name of the model to download
        model_weights_filename (str): name of the .pth file expected for the model

    Returns:
        Path: path to the weights file, in utils.get_pretrained_weights_dir()
    """
    import json
    import tarfile
    import urllib.request

    def show_progress(_, block_size, __):  # count, block_size, total_size
        pbar.update(block_size)

    logger.info("*" * 20)
    pretrained_folder_path = utils.get_pretrained_weights_dir()
    pretrained_folder_path.mkdir(parents=True, exist_ok=True)
    json_path = utils.PACKAGE_PRETRAINED_DIR / Path("pretrained_model_urls.json")

    check_path = pretrained_folder_path / Path(model_weights_filename)

    if Path(check_path).is_file():
        message = f"Weight file {model_weights_filename} already exists, skipping download"
        if self.log_widget is not None:
            self.log_widget.print_and_log(message, printing=False)
        logger.info(message)
        return check_path

    with Path.open(json_path) as f:
        neturls = json.load(f)
    if model_name in neturls:
        url = neturls[model_name]
        response = urllib.request.urlopen(url)

        start_message = f"Downloading the model from HuggingFace {url}...."
        total_size = int(response.getheader("Content-Length"))
        if self.log_widget is None:
            logger.info(start_message)
            pbar = tqdm(unit="B", total=total_size, position=0)
        else:
            self.log_widget.print_and_log(start_message)
            pbar = tqdm(
                unit="B",
                total=total_size,
                position=0,
                file=self.log_widget,
            )

        filename, _ = urllib.request.urlretrieve(url, reporthook=show_progress)
        with tarfile.open(filename, mode="r:gz") as tar:

            def is_within_directory(directory, target):
                abs_directory = Path(directory).resolve()
                abs_target = Path(target).resolve()
                # prefix = os.path.commonprefix([abs_directory, abs_target])
                logger.debug(abs_directory)
                logger.debug(abs_target)
                logger.debug(abs_directory.parents)

                return abs_directory in abs_target.parents

            def safe_extract(tar, path=".", members=None, *, numeric_owner=False):
                for member in tar.getmembers():
                    member_path = str(Path(path) / member.name)
                    if not is_within_directory(path, member_path):
                        raise Exception("Attempted Path Traversal in Tar File")

                tar.extractall(path, members, numeric_owner=numeric_owner)

            safe_extract(tar, pretrained_folder_path)
            # tar.extractall(pretrained_folder_path)
    else:
        raise ValueError(
            f"Unknown model: {model_name}. Should be one of {', '.join(neturls)}"
        )
    return check_path