Skip to content

napari_cellseg3d.code_plugins.plugin_review_dock

Widget opened when a new Review session is started.

Classes:

Name Description
Datamanager

A widget with a single checkbox that allows to store the status of a slice in csv file (checked/not checked).

Attributes:

Name Type Description
logger

plugin_dock.py

logger module-attribute

logger = utils.LOGGER

plugin_dock.py

Definition of Datamanager widget, for saving labels status in csv file

Datamanager

Bases: QWidget

A widget with a single checkbox that allows to store the status of a slice in csv file (checked/not checked).

Methods:

Name Description
__init__

Creates the datamanager widget in the specified viewer window.

create_csv

Create a new dataframe and save the csv.

load_csv

Loads newest csv or create new csv.

pause_timer

Pause the timer for the review time.

prepare

Initialize the Datamanager, which loads the csv file and updates it with the index of the current slice.

update_dm

Updates the Datamanager with the index of the current slice.

Attributes:

Name Type Description
as_folder

Whether to load as folder or single file

viewer

napari.viewer.Viewer: viewer in which the widget is displayed

Source code in napari_cellseg3d/code_plugins/plugin_review_dock.py
 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
class Datamanager(QWidget):
    """A widget with a single checkbox that allows to store the status of a slice in csv file (checked/not checked)."""

    def __init__(self, parent: "napari.viewer.Viewer", image_shape=None):
        """Creates the datamanager widget in the specified viewer window.

        Args:
            parent (napari.viewer.Viewer): napari Viewer for the widget to be displayed in
            image_shape (tuple, optional): shape of the reviewed volume. Defaults to the shape
                of the viewer's first layer, which is only right when the viewer holds nothing
                but the review.
        """
        super().__init__()

        layout = QVBoxLayout()
        self.viewer = parent
        """napari.viewer.Viewer: viewer in which the widget is displayed"""

        # add some buttons
        self.button = ui.Button("1", self._button_func, parent=self, fixed=True)
        self.time_label = ui.make_label("", self)
        self.time_label.setVisible(False)

        self.pause_box = ui.CheckBox(
            "Pause timer", self.pause_timer, parent=self, fixed=True
        )

        io_panel = ui.ContainerWidget()
        io_layout = io_panel.layout
        io_layout.addWidget(self.button, alignment=ui.ABS_AL)
        io_layout.addWidget(
            ui.combine_blocks(
                left_or_above=self.pause_box,
                right_or_below=self.time_label,
                horizontal=True,
            ),
            alignment=ui.ABS_AL,
        )

        io_panel.setLayout(io_layout)
        io_panel.setMaximumWidth(GUI_MAXIMUM_WIDTH)
        layout.addWidget(io_panel, alignment=ui.ABS_AL)

        self.setLayout(layout)
        # self.setMaximumHeight(GUI_MAXIMUM_HEIGHT)
        # self.setMaximumWidth(GUI_MAXIMUM_WIDTH)

        self.df = None
        self.csv_path = None
        self.slice_num = 0
        self.filetype = ""
        self.filename = None
        self.image_dims = (
            tuple(image_shape)
            if image_shape is not None
            else self.viewer.layers[0].data.shape
        )
        self.as_folder = False
        """Whether to load as folder or single file"""

        self.start_time = datetime.now()
        self.time_elapsed = timedelta()
        self.pause_start = None
        self.is_paused = False
        # self.pause_time = None

    def pause_timer(self):
        """Pause the timer for the review time."""
        if self.pause_box.isChecked():
            self.time_label.setVisible(True)

            self.pause_start = datetime.now()
            self.time_elapsed += self.pause_start - self.start_time
            self.pause_box.setText("Resume timer")
            self.time_label.setText(
                f"({utils.time_difference(timedelta(), self.time_elapsed)})"
            )
            self.is_paused = True
        else:
            self.time_label.setVisible(False)
            self.pause_box.setText("Pause timer")

            # self.pause_time = datetime.now() - self.pause_start
            self.start_time = datetime.now()
            self.is_paused = False
        self._update_time_csv()

    def _update_time_csv(self):
        if not self.is_paused:
            self.time_elapsed += datetime.now() - self.start_time
            self.start_time = datetime.now()
        str_time = utils.time_difference(timedelta(), self.time_elapsed)
        logger.info(f"Time elapsed : {str_time}")
        self.df.at[0, "time"] = str_time
        self.df.to_csv(self.csv_path)

    def prepare(self, label_dir, filetype, model_type, checkbox, slice_num=None):
        """Initialize the Datamanager, which loads the csv file and updates it with the index of the current slice.

        Args:
            label_dir (str): label path
            filetype (str) : file extension
            model_type (str): model type
            checkbox (bool): create new dataset or not
            slice_num (int, optional): current slice of the reviewed volume. Defaults to
                the viewer's first axis, which is only correct if only review layers are present.
        """
        # label_dir = os.path.dirname(label_dir)
        logger.debug("csv path try :")
        logger.debug(label_dir)
        self.filetype = filetype

        if not self.as_folder:
            p = Path(label_dir)
            self.filename = p.name
            label_dir = p.parents[0]
            logger.info(f"Loading single image : {self.filename}")
            logger.debug(label_dir)

        self.df, self.csv_path = self.load_csv(label_dir, model_type, checkbox)

        logger.debug(f"csv path : {self.csv_path}")
        logger.debug(f"Create new dataset : {checkbox}")
        if slice_num is None:
            slice_num = self.viewer.dims.current_step[0]
        self.update_dm(slice_num)

    def load_csv(self, label_dir, model_type, checkbox):
        """Loads newest csv or create new csv.

        Args:
            label_dir (str): label path
            model_type (str): model type
            checkbox ( bool ): create new dataset or not

        Returns:
            (pandas.DataFrame, str) dataframe、csv path
        """
        # if not self.as_folder :
        #     label_dir = os.path.dirname(label_dir)
        logger.debug("label dir")
        logger.debug(label_dir)
        csvs = sorted(list(Path(str(label_dir)).glob(f"{model_type}*.csv")))
        if len(csvs) == 0:
            df, csv_path = self.create_csv(
                label_dir, model_type
            )  # df,  train_data_dir, ...
        else:
            csv_path = str(csvs[-1])
            df = pd.read_csv(csv_path, index_col=0)
            if checkbox is True:
                csv_path = (
                    csv_path.split("_train")[0]
                    + "_train"
                    + str(int(Path(csv_path.split("_train")[1]).parent) + 1)
                    + ".csv"
                )  # adds 1 to current csv name number
                df.to_csv(csv_path)
            else:
                pass

        recorded_time = df.at[0, "time"]
        # logger.debug("csv load time")
        # logger.debug(recorded_time)
        t = datetime.strptime(recorded_time, TIMER_FORMAT)
        self.time_elapsed = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
        # logger.debug(self.time_elapsed)
        return df, csv_path

    def create_csv(self, label_dir, model_type):
        """Create a new dataframe and save the csv.

        Args:
          label_dir (str): label path
          model_type (str): model type
        Returns:
         (pandas.DataFrame, str): dataframe, csv path.
        """
        if self.as_folder:
            labels = sorted(
                list(
                    path.name
                    for path in Path(str(label_dir)).glob("./*" + self.filetype)
                )
            )
        else:
            # logger.debug(self.image_dims[0])
            filename = self.filename if self.filename is not None else "image"
            labels = [str(filename) for i in range(self.image_dims[0])]

        df = pd.DataFrame(
            {
                "filename": labels,
                "train": ["Not checked"] * len(labels),
                "time": [""] * len(labels),
            }
        )
        df.at[0, "time"] = "00:00:00"

        csv_path = Path(label_dir) / Path(f"{model_type}_train0.csv")
        if not csv_path.parent.exists():
            csv_path.parent.mkdir(parents=True)
        logger.debug(f"CSV path : {csv_path}")
        df.to_csv(str(csv_path))

        return df, csv_path

    def _update_button(self):
        if len(self.df) > 1:
            self.button.setText(
                self.df.at[self.df.index[self.slice_num], "train"]
            )  # puts  button values at value of 1st csv item

    def update_dm(self, slice_num):
        """Updates the Datamanager with the index of the current slice.

        Also updates the text with the status contained in the csv (e.g. checked/not checked).

        Args:
            slice_num (int): index of the current slice
        """
        self.slice_num = slice_num
        self._update_time_csv()

        logger.info(f"New slice review started at {utils.get_time()}")
        # logger.debug(self.df)

        try:
            self._update_button()
        except IndexError:
            self.slice_num -= 1
            self._update_button()

    def _button_func(self):  # updates csv every time you press button...
        if self.viewer.dims.ndisplay != 2:
            # TODO test if undefined behaviour or if okay
            logger.warning("Please switch back to 2D mode !")
            return

        self._update_time_csv()

        if self.button.text() == "Not checked":
            self.button.setText("Checked")
            self.df.at[self.df.index[self.slice_num], "train"] = "Checked"
            self.df.to_csv(self.csv_path)
        else:
            self.button.setText("Not checked")
            self.df.at[self.df.index[self.slice_num], "train"] = "Not checked"
            self.df.to_csv(self.csv_path)

as_folder instance-attribute

as_folder = False

Whether to load as folder or single file

viewer instance-attribute

viewer = parent

napari.viewer.Viewer: viewer in which the widget is displayed

__init__

__init__(parent: Viewer, image_shape=None)

Creates the datamanager widget in the specified viewer window.

Parameters:

Name Type Description Default
parent Viewer

napari Viewer for the widget to be displayed in

required
image_shape tuple

shape of the reviewed volume. Defaults to the shape of the viewer's first layer, which is only right when the viewer holds nothing but the review.

None
Source code in napari_cellseg3d/code_plugins/plugin_review_dock.py
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
def __init__(self, parent: "napari.viewer.Viewer", image_shape=None):
    """Creates the datamanager widget in the specified viewer window.

    Args:
        parent (napari.viewer.Viewer): napari Viewer for the widget to be displayed in
        image_shape (tuple, optional): shape of the reviewed volume. Defaults to the shape
            of the viewer's first layer, which is only right when the viewer holds nothing
            but the review.
    """
    super().__init__()

    layout = QVBoxLayout()
    self.viewer = parent
    """napari.viewer.Viewer: viewer in which the widget is displayed"""

    # add some buttons
    self.button = ui.Button("1", self._button_func, parent=self, fixed=True)
    self.time_label = ui.make_label("", self)
    self.time_label.setVisible(False)

    self.pause_box = ui.CheckBox(
        "Pause timer", self.pause_timer, parent=self, fixed=True
    )

    io_panel = ui.ContainerWidget()
    io_layout = io_panel.layout
    io_layout.addWidget(self.button, alignment=ui.ABS_AL)
    io_layout.addWidget(
        ui.combine_blocks(
            left_or_above=self.pause_box,
            right_or_below=self.time_label,
            horizontal=True,
        ),
        alignment=ui.ABS_AL,
    )

    io_panel.setLayout(io_layout)
    io_panel.setMaximumWidth(GUI_MAXIMUM_WIDTH)
    layout.addWidget(io_panel, alignment=ui.ABS_AL)

    self.setLayout(layout)
    # self.setMaximumHeight(GUI_MAXIMUM_HEIGHT)
    # self.setMaximumWidth(GUI_MAXIMUM_WIDTH)

    self.df = None
    self.csv_path = None
    self.slice_num = 0
    self.filetype = ""
    self.filename = None
    self.image_dims = (
        tuple(image_shape)
        if image_shape is not None
        else self.viewer.layers[0].data.shape
    )
    self.as_folder = False
    """Whether to load as folder or single file"""

    self.start_time = datetime.now()
    self.time_elapsed = timedelta()
    self.pause_start = None
    self.is_paused = False

create_csv

create_csv(label_dir, model_type)

Create a new dataframe and save the csv.

Parameters:

Name Type Description Default
label_dir str

label path

required
model_type str

model type

required

Returns: (pandas.DataFrame, str): dataframe, csv path.

Source code in napari_cellseg3d/code_plugins/plugin_review_dock.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def create_csv(self, label_dir, model_type):
    """Create a new dataframe and save the csv.

    Args:
      label_dir (str): label path
      model_type (str): model type
    Returns:
     (pandas.DataFrame, str): dataframe, csv path.
    """
    if self.as_folder:
        labels = sorted(
            list(
                path.name
                for path in Path(str(label_dir)).glob("./*" + self.filetype)
            )
        )
    else:
        # logger.debug(self.image_dims[0])
        filename = self.filename if self.filename is not None else "image"
        labels = [str(filename) for i in range(self.image_dims[0])]

    df = pd.DataFrame(
        {
            "filename": labels,
            "train": ["Not checked"] * len(labels),
            "time": [""] * len(labels),
        }
    )
    df.at[0, "time"] = "00:00:00"

    csv_path = Path(label_dir) / Path(f"{model_type}_train0.csv")
    if not csv_path.parent.exists():
        csv_path.parent.mkdir(parents=True)
    logger.debug(f"CSV path : {csv_path}")
    df.to_csv(str(csv_path))

    return df, csv_path

load_csv

load_csv(label_dir, model_type, checkbox)

Loads newest csv or create new csv.

Parameters:

Name Type Description Default
label_dir str

label path

required
model_type str

model type

required
checkbox bool

create new dataset or not

required

Returns:

Type Description

(pandas.DataFrame, str) dataframe、csv path

Source code in napari_cellseg3d/code_plugins/plugin_review_dock.py
158
159
160
161
162
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
def load_csv(self, label_dir, model_type, checkbox):
    """Loads newest csv or create new csv.

    Args:
        label_dir (str): label path
        model_type (str): model type
        checkbox ( bool ): create new dataset or not

    Returns:
        (pandas.DataFrame, str) dataframe、csv path
    """
    # if not self.as_folder :
    #     label_dir = os.path.dirname(label_dir)
    logger.debug("label dir")
    logger.debug(label_dir)
    csvs = sorted(list(Path(str(label_dir)).glob(f"{model_type}*.csv")))
    if len(csvs) == 0:
        df, csv_path = self.create_csv(
            label_dir, model_type
        )  # df,  train_data_dir, ...
    else:
        csv_path = str(csvs[-1])
        df = pd.read_csv(csv_path, index_col=0)
        if checkbox is True:
            csv_path = (
                csv_path.split("_train")[0]
                + "_train"
                + str(int(Path(csv_path.split("_train")[1]).parent) + 1)
                + ".csv"
            )  # adds 1 to current csv name number
            df.to_csv(csv_path)
        else:
            pass

    recorded_time = df.at[0, "time"]
    # logger.debug("csv load time")
    # logger.debug(recorded_time)
    t = datetime.strptime(recorded_time, TIMER_FORMAT)
    self.time_elapsed = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
    # logger.debug(self.time_elapsed)
    return df, csv_path

pause_timer

pause_timer()

Pause the timer for the review time.

Source code in napari_cellseg3d/code_plugins/plugin_review_dock.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def pause_timer(self):
    """Pause the timer for the review time."""
    if self.pause_box.isChecked():
        self.time_label.setVisible(True)

        self.pause_start = datetime.now()
        self.time_elapsed += self.pause_start - self.start_time
        self.pause_box.setText("Resume timer")
        self.time_label.setText(
            f"({utils.time_difference(timedelta(), self.time_elapsed)})"
        )
        self.is_paused = True
    else:
        self.time_label.setVisible(False)
        self.pause_box.setText("Pause timer")

        # self.pause_time = datetime.now() - self.pause_start
        self.start_time = datetime.now()
        self.is_paused = False
    self._update_time_csv()

prepare

prepare(label_dir, filetype, model_type, checkbox, slice_num=None)

Initialize the Datamanager, which loads the csv file and updates it with the index of the current slice.

Parameters:

Name Type Description Default
label_dir str

label path

required
filetype (str)

file extension

required
model_type str

model type

required
checkbox bool

create new dataset or not

required
slice_num int

current slice of the reviewed volume. Defaults to the viewer's first axis, which is only correct if only review layers are present.

None
Source code in napari_cellseg3d/code_plugins/plugin_review_dock.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def prepare(self, label_dir, filetype, model_type, checkbox, slice_num=None):
    """Initialize the Datamanager, which loads the csv file and updates it with the index of the current slice.

    Args:
        label_dir (str): label path
        filetype (str) : file extension
        model_type (str): model type
        checkbox (bool): create new dataset or not
        slice_num (int, optional): current slice of the reviewed volume. Defaults to
            the viewer's first axis, which is only correct if only review layers are present.
    """
    # label_dir = os.path.dirname(label_dir)
    logger.debug("csv path try :")
    logger.debug(label_dir)
    self.filetype = filetype

    if not self.as_folder:
        p = Path(label_dir)
        self.filename = p.name
        label_dir = p.parents[0]
        logger.info(f"Loading single image : {self.filename}")
        logger.debug(label_dir)

    self.df, self.csv_path = self.load_csv(label_dir, model_type, checkbox)

    logger.debug(f"csv path : {self.csv_path}")
    logger.debug(f"Create new dataset : {checkbox}")
    if slice_num is None:
        slice_num = self.viewer.dims.current_step[0]
    self.update_dm(slice_num)

update_dm

update_dm(slice_num)

Updates the Datamanager with the index of the current slice.

Also updates the text with the status contained in the csv (e.g. checked/not checked).

Parameters:

Name Type Description Default
slice_num int

index of the current slice

required
Source code in napari_cellseg3d/code_plugins/plugin_review_dock.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def update_dm(self, slice_num):
    """Updates the Datamanager with the index of the current slice.

    Also updates the text with the status contained in the csv (e.g. checked/not checked).

    Args:
        slice_num (int): index of the current slice
    """
    self.slice_num = slice_num
    self._update_time_csv()

    logger.info(f"New slice review started at {utils.get_time()}")
    # logger.debug(self.df)

    try:
        self._update_button()
    except IndexError:
        self.slice_num -= 1
        self._update_button()