Skip to content

importvideos

sleap.gui.dialogs.importvideos

Interface to handle the UI for importing videos.

Usage: ::

import_list = ImportVideos().ask()

This will show the user a file-selection dialog, and then a second dialog to select the import parameters for each file.

It returns a list with data about each file selected by the user. In particular, we'll have the name of the file and all of the parameters relevant for that specific type of file. It also includes a reference to the relevant method of :class:Video.

For each item in import_list, we can load the video by calling this method while passing the user-selected params as the named parameters: ::

vid = item"video_class"

Classes:

Name Description
ImportItemWidget

Widget for selecting parameters with preview when importing video.

ImportParamDialog

Dialog for selecting parameters with preview when importing video.

ImportParamWidget

Widget for allowing user to select video parameters.

ImportVideos

Class to handle video importing UI.

MessageWidget

Widget to show message.

VideoPreviewWidget

Widget to show video preview. Based on :class:Video class.

ImportItemWidget

Bases: QFrame

Widget for selecting parameters with preview when importing video.

Parameters:

Name Type Description Default
file_path str

Full path to selected video file.

required
import_type dict

Data about user-selectable import parameters.

required

Methods:

Name Description
boundingRect

Method required by Qt.

get_data

Get all data (fixed and user-selected) for imported video.

is_enabled

Am I enabled?

paint

Method required by Qt.

update_video

Update preview video using current param values.

Source code in sleap/gui/dialogs/importvideos.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
class ImportItemWidget(QFrame):
    """Widget for selecting parameters with preview when importing video.

    Args:
        file_path (str): Full path to selected video file.
        import_type (dict): Data about user-selectable import parameters.
    """

    def __init__(
        self,
        file_path: str,
        import_type: Dict[str, Any],
        message: str = "",
        *args,
        **kwargs,
    ):
        super(ImportItemWidget, self).__init__(*args, **kwargs)

        self.file_path = file_path
        self.import_type = import_type
        self.video = None

        import_item_layout = QVBoxLayout()

        self.enabled_checkbox_widget = QCheckBox(self.file_path)
        self.enabled_checkbox_widget.setChecked(True)
        import_item_layout.addWidget(self.enabled_checkbox_widget)

        # import_item_layout.addWidget(QLabel(self.file_path))
        inner_layout = QHBoxLayout()
        self.options_widget = ImportParamWidget(
            parent=self, file_path=self.file_path, import_type=self.import_type
        )

        self.message_widget = MessageWidget(parent=self, message=message)

        self.preview_widget = VideoPreviewWidget(parent=self)
        self.preview_widget.setFixedSize(200, 200)

        self.enabled_checkbox_widget.stateChanged.connect(
            lambda state: self.options_widget.setEnabled(state == Qt.Checked)
        )

        inner_layout.addWidget(self.options_widget)
        inner_layout.addWidget(self.message_widget)
        inner_layout.addWidget(self.preview_widget)
        import_item_layout.addLayout(inner_layout)
        self.setLayout(import_item_layout)

        self.setFrameStyle(QFrame.Panel)

        self.options_widget.changed.connect(self.update_video)
        self.update_video(initial=True)

    def is_enabled(self):
        """Am I enabled?

        Our UI provides a way to enable/disable this item (file).
        We only want to import enabled items.

        Returns:
            Boolean: Am I enabled?
        """
        return self.enabled_checkbox_widget.isChecked()

    def get_data(self) -> dict:
        """Get all data (fixed and user-selected) for imported video.

        Returns:
            Dict with data for this video.
        """

        video_data = {
            "params": self.options_widget.get_values(),
            "video_type": self.import_type["video_type"],
            "video_class": self.import_type["video_class"],
        }
        return video_data

    def update_video(self, initial: bool = False):
        """Update preview video using current param values.

        Args:
            initial: if True, then get video settings that are used by
                the `Video` object when they aren't specified as params
        Returns:
            None.
        """

        video_params = self.options_widget.get_values(only_required=initial)

        try:
            if self.import_type["video_class"] is not None:
                self.video = self.import_type["video_class"](**video_params)
            else:
                self.video = None

            self.preview_widget.load_video(self.video)
        except Exception as e:
            print(f"Unable to load video with these parameters. Error: {e}")
            # if we got an error showing video with those settings, clear the video
            # preview
            self.video = None
            self.preview_widget.clear_video()

        if initial and self.video is not None:
            self.options_widget.set_values_from_video(self.video)

    def boundingRect(self) -> QRectF:
        """Method required by Qt."""
        return QRectF()

    def paint(self, painter, option, widget=None):
        """Method required by Qt."""
        pass

boundingRect()

Method required by Qt.

Source code in sleap/gui/dialogs/importvideos.py
417
418
419
def boundingRect(self) -> QRectF:
    """Method required by Qt."""
    return QRectF()

get_data()

Get all data (fixed and user-selected) for imported video.

Returns:

Type Description
dict

Dict with data for this video.

Source code in sleap/gui/dialogs/importvideos.py
374
375
376
377
378
379
380
381
382
383
384
385
386
def get_data(self) -> dict:
    """Get all data (fixed and user-selected) for imported video.

    Returns:
        Dict with data for this video.
    """

    video_data = {
        "params": self.options_widget.get_values(),
        "video_type": self.import_type["video_type"],
        "video_class": self.import_type["video_class"],
    }
    return video_data

is_enabled()

Am I enabled?

Our UI provides a way to enable/disable this item (file). We only want to import enabled items.

Returns:

Name Type Description
Boolean

Am I enabled?

Source code in sleap/gui/dialogs/importvideos.py
363
364
365
366
367
368
369
370
371
372
def is_enabled(self):
    """Am I enabled?

    Our UI provides a way to enable/disable this item (file).
    We only want to import enabled items.

    Returns:
        Boolean: Am I enabled?
    """
    return self.enabled_checkbox_widget.isChecked()

paint(painter, option, widget=None)

Method required by Qt.

Source code in sleap/gui/dialogs/importvideos.py
421
422
423
def paint(self, painter, option, widget=None):
    """Method required by Qt."""
    pass

update_video(initial=False)

Update preview video using current param values.

Parameters:

Name Type Description Default
initial bool

if True, then get video settings that are used by the Video object when they aren't specified as params

False
Source code in sleap/gui/dialogs/importvideos.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
def update_video(self, initial: bool = False):
    """Update preview video using current param values.

    Args:
        initial: if True, then get video settings that are used by
            the `Video` object when they aren't specified as params
    Returns:
        None.
    """

    video_params = self.options_widget.get_values(only_required=initial)

    try:
        if self.import_type["video_class"] is not None:
            self.video = self.import_type["video_class"](**video_params)
        else:
            self.video = None

        self.preview_widget.load_video(self.video)
    except Exception as e:
        print(f"Unable to load video with these parameters. Error: {e}")
        # if we got an error showing video with those settings, clear the video
        # preview
        self.video = None
        self.preview_widget.clear_video()

    if initial and self.video is not None:
        self.options_widget.set_values_from_video(self.video)

ImportParamDialog

Bases: QDialog

Dialog for selecting parameters with preview when importing video.

Parameters:

Name Type Description Default
filenames list

List of files we want to import.

required

Methods:

Name Description
get_data

Method to get results from import.

Source code in sleap/gui/dialogs/importvideos.py
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
class ImportParamDialog(QDialog):
    """Dialog for selecting parameters with preview when importing video.

    Args:
        filenames (list): List of files we want to import.
    """

    def __init__(
        self, filenames: List[str], messages: Dict[str, str] = None, *args, **kwargs
    ):
        super(ImportParamDialog, self).__init__(*args, **kwargs)

        messages = dict() if messages is None else messages
        self.import_widgets = []

        self.setWindowTitle("Video Import Options")

        self.import_types = [
            {
                "video_type": "hdf5",
                "match": ",".join(HDF5Video.EXTS),
                "video_class": Video.from_filename,
                "params": [
                    {
                        "name": "dataset",
                        "type": "function_menu",
                        "options": "_get_h5_dataset_options",
                        "required": True,
                    },
                    {
                        "name": "input_format",
                        "type": "radio",
                        "options": "channels_first,channels_last",
                        "required": True,  # we can't currently auto-detect
                    },
                ],
            },
            {
                "video_type": "mp4",
                "match": ",".join(MediaVideo.EXTS),
                "video_class": Video.from_filename,
                "params": [{"name": "grayscale", "type": "check"}],
            },
            {
                "video_type": "image",
                "match": ",".join(ImageVideo.EXTS),
                "video_class": Video.from_filename,
                "params": [],
            },
            {
                "video_type": "tiff",
                "match": ",".join(TiffVideo.EXTS),
                "video_class": Video.from_filename,
                "params": [{"name": "grayscale", "type": "check"}],
            },
        ]

        outer_layout = QVBoxLayout()

        scroll_widget = QScrollArea()
        scroll_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        scroll_items_widget = QWidget()
        scroll_layout = QVBoxLayout()
        for file_name in filenames:
            if file_name:
                this_type = None
                for import_type in self.import_types:
                    if import_type.get("match", None) is not None:
                        if file_name.lower().endswith(
                            tuple(import_type["match"].split(","))
                        ):
                            this_type = import_type
                            break
                if this_type is not None:
                    message = messages[file_name] if file_name in messages else ""
                    import_item_widget = ImportItemWidget(
                        file_name, this_type, message=message
                    )
                    self.import_widgets.append(import_item_widget)
                    scroll_layout.addWidget(import_item_widget)
                else:
                    raise Exception("No match found for file type.")
        scroll_items_widget.setLayout(scroll_layout)
        scroll_widget.setWidget(scroll_items_widget)
        outer_layout.addWidget(scroll_widget)

        button_layout = QHBoxLayout()

        if any(
            [
                widget.import_type["video_type"] == "mp4"
                for widget in self.import_widgets
            ]
        ):
            all_grayscale_button = QPushButton("All grayscale")
            all_rgb_button = QPushButton("All RGB")
            button_layout.addWidget(all_grayscale_button)
            button_layout.addWidget(all_rgb_button)
            all_grayscale_button.clicked.connect(self.set_all_grayscale)
            all_rgb_button.clicked.connect(self.set_all_rgb)
        if any(
            [
                widget.import_type["video_type"] == "hdf5"
                for widget in self.import_widgets
            ]
        ):
            all_channels_last_button = QPushButton("All channels last")
            all_channels_first_button = QPushButton("All channels first")
            button_layout.addWidget(all_channels_last_button)
            button_layout.addWidget(all_channels_first_button)
            all_channels_last_button.clicked.connect(self.set_all_channels_last)
            all_channels_first_button.clicked.connect(self.set_all_channels_first)
        if any(
            [
                widget.import_type["video_type"] == "single_image"
                for widget in self.import_widgets
            ]
        ):
            all_grayscale_button = QPushButton("All grayscale")
            all_rgb_button = QPushButton("All RGB")
            button_layout.addWidget(all_grayscale_button)
            button_layout.addWidget(all_rgb_button)
            all_grayscale_button.clicked.connect(self.set_all_grayscale)
            all_rgb_button.clicked.connect(self.set_all_rgb)

        cancel_button = QPushButton("Cancel")
        import_button = QPushButton("Import")
        import_button.setDefault(True)

        button_layout.addStretch()
        button_layout.addWidget(cancel_button)
        button_layout.addWidget(import_button)

        outer_layout.addLayout(button_layout)
        self.adjustSize()

        self.setLayout(outer_layout)

        import_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)

    def get_data(self, import_result=None):
        """Method to get results from import.

        Args:
            import_result (optional): If specified, we'll insert data into this.

        Returns:
            List of dicts with data for each (enabled) imported file.
        """
        # we don't want to set default to [] because that persists
        if import_result is None:
            import_result = []
        for import_item in self.import_widgets:
            if import_item.is_enabled():
                import_result.append(import_item.get_data())
        return import_result

    def set_all_grayscale(self):
        for import_item in self.import_widgets:
            widget_elements = import_item.options_widget.widget_elements
            if "grayscale" in widget_elements:
                widget_elements["grayscale"].setChecked(True)

    def set_all_rgb(self):
        for import_item in self.import_widgets:
            widget_elements = import_item.options_widget.widget_elements
            if "grayscale" in widget_elements:
                widget_elements["grayscale"].setChecked(False)

    def set_all_channels_last(self):
        for import_item in self.import_widgets:
            widget_elements = import_item.options_widget.widget_elements

            if "input_format" in widget_elements:
                for btn in widget_elements["input_format"].buttons():
                    if btn.text() == "channels_last":
                        btn.click()
                        break

    def set_all_channels_first(self):
        for import_item in self.import_widgets:
            widget_elements = import_item.options_widget.widget_elements

            if "input_format" in widget_elements:
                for btn in widget_elements["input_format"].buttons():
                    if btn.text() == "channels_first":
                        btn.click()
                        break

get_data(import_result=None)

Method to get results from import.

Parameters:

Name Type Description Default
import_result optional

If specified, we'll insert data into this.

None

Returns:

Type Description

List of dicts with data for each (enabled) imported file.

Source code in sleap/gui/dialogs/importvideos.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def get_data(self, import_result=None):
    """Method to get results from import.

    Args:
        import_result (optional): If specified, we'll insert data into this.

    Returns:
        List of dicts with data for each (enabled) imported file.
    """
    # we don't want to set default to [] because that persists
    if import_result is None:
        import_result = []
    for import_item in self.import_widgets:
        if import_item.is_enabled():
            import_result.append(import_item.get_data())
    return import_result

ImportParamWidget

Bases: QWidget

Widget for allowing user to select video parameters.

Parameters:

Name Type Description Default
file_path str

file path/name

required
import_type Dict[str, Any]

data about the parameters for this type of video

required
Note

Object is a widget with the UI for params specific to this video type.

Methods:

Name Description
get_values

Method to get current user-selected values for import parameters.

make_layout

Builds the layout of widgets for user-selected import parameters.

set_values_from_video

Set the form fields using attributes on video.

Source code in sleap/gui/dialogs/importvideos.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
class ImportParamWidget(QWidget):
    """Widget for allowing user to select video parameters.

    Args:
        file_path: file path/name
        import_type: data about the parameters for this type of video

    Note:
        Object is a widget with the UI for params specific to this video type.
    """

    changed = Signal()

    def __init__(self, file_path: str, import_type: Dict[str, Any], *args, **kwargs):
        super(ImportParamWidget, self).__init__(*args, **kwargs)

        self.file_path = file_path
        self.import_type = import_type
        self.widget_elements = {}
        self.video_params = {}

        option_layout = self.make_layout()
        # self.changed.connect( lambda: print(self.get_values()) )

        self.setLayout(option_layout)

    def make_layout(self) -> QLayout:
        """Builds the layout of widgets for user-selected import parameters."""

        param_list = self.import_type["params"]
        widget_layout = QVBoxLayout()
        widget_elements = dict()
        for param_item in param_list:
            name = param_item["name"]
            type = param_item["type"]
            options = param_item.get("options", None)
            if type == "radio":
                radio_group = QButtonGroup(parent=self)
                option_list = options.split(",")
                selected_option = option_list[0]
                for option in option_list:
                    btn_widget = QRadioButton(option)
                    if option == selected_option:
                        btn_widget.setChecked(True)
                    widget_layout.addWidget(btn_widget)
                    radio_group.addButton(btn_widget)
                radio_group.buttonToggled.connect(lambda: self.changed.emit())
                widget_elements[name] = radio_group
            elif type == "check":
                check_widget = QCheckBox(name)
                check_widget.stateChanged.connect(lambda: self.changed.emit())
                widget_layout.addWidget(check_widget)
                widget_elements[name] = check_widget
            elif type == "function_menu":
                list_widget = QComboBox()
                # options has name of method which returns list of options
                option_list = getattr(self, options)()
                for option in option_list:
                    list_widget.addItem(option)
                list_widget.currentIndexChanged.connect(lambda: self.changed.emit())
                widget_layout.addWidget(list_widget)
                widget_elements[name] = list_widget
            self.widget_elements = widget_elements
        return widget_layout

    def get_values(self, only_required=False):
        """Method to get current user-selected values for import parameters.

        Args:
            only_required: Only return the parameters that are required
                for instantiating `Video` object

        Returns:
            Dict of param keys/values.

        Note:
            It's easiest if the return dict matches the arguments we need
            for the Video object, so we'll add the file name to the dict
            even though it's not a user-selectable param.
        """
        param_list = self.import_type["params"]
        param_values = {"filename": self.file_path}
        for param_item in param_list:
            name = param_item["name"]
            type = param_item["type"]
            is_required = param_item.get("required", False)

            if not only_required or is_required:
                value = None
                if type == "radio":
                    value = self.widget_elements[name].checkedButton().text()
                elif type == "check":
                    value = self.widget_elements[name].isChecked()
                elif type == "function_menu":
                    value = self.widget_elements[name].currentText()
                param_values[name] = value
        return param_values

    def set_values_from_video(self, video):
        """Set the form fields using attributes on video."""
        param_list = self.import_type["params"]
        for param in param_list:
            name = param["name"]
            param["type"]

            if hasattr(video, name):
                val = getattr(video, name)

                widget = self.widget_elements[name]
                if hasattr(widget, "isChecked"):
                    widget.setChecked(val)
                elif hasattr(widget, "value"):
                    widget.setValue(val)
                elif hasattr(widget, "currentText"):
                    widget.setCurrentText(str(val))
                elif hasattr(widget, "text"):
                    widget.setText(str(val))

    def _get_h5_dataset_options(self) -> list:
        """Method to get a list of all datasets in hdf5 file.

        Args:
            None.

        Returns:
            List of datasets in the hdf5 file for our import item.

        Note:
            This is used to populate the "function_menu"-type param.
        """
        try:
            with h5py.File(self.file_path, "r") as f:
                options = self._find_h5_datasets("", f)
        except Exception:
            options = []
        return options

    def _find_h5_datasets(self, data_path, data_object) -> list:
        """Recursively find datasets in hdf5 file."""
        options = []
        for key in data_object.keys():
            if isinstance(data_object[key], h5py._hl.dataset.Dataset):
                if len(data_object[key].shape) == 4:
                    options.append(data_path + "/" + key)
            elif isinstance(data_object[key], h5py._hl.group.Group):
                options.extend(
                    self._find_h5_datasets(data_path + "/" + key, data_object[key])
                )
        return options

get_values(only_required=False)

Method to get current user-selected values for import parameters.

Parameters:

Name Type Description Default
only_required

Only return the parameters that are required for instantiating Video object

False

Returns:

Type Description

Dict of param keys/values.

Note

It's easiest if the return dict matches the arguments we need for the Video object, so we'll add the file name to the dict even though it's not a user-selectable param.

Source code in sleap/gui/dialogs/importvideos.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
def get_values(self, only_required=False):
    """Method to get current user-selected values for import parameters.

    Args:
        only_required: Only return the parameters that are required
            for instantiating `Video` object

    Returns:
        Dict of param keys/values.

    Note:
        It's easiest if the return dict matches the arguments we need
        for the Video object, so we'll add the file name to the dict
        even though it's not a user-selectable param.
    """
    param_list = self.import_type["params"]
    param_values = {"filename": self.file_path}
    for param_item in param_list:
        name = param_item["name"]
        type = param_item["type"]
        is_required = param_item.get("required", False)

        if not only_required or is_required:
            value = None
            if type == "radio":
                value = self.widget_elements[name].checkedButton().text()
            elif type == "check":
                value = self.widget_elements[name].isChecked()
            elif type == "function_menu":
                value = self.widget_elements[name].currentText()
            param_values[name] = value
    return param_values

make_layout()

Builds the layout of widgets for user-selected import parameters.

Source code in sleap/gui/dialogs/importvideos.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
def make_layout(self) -> QLayout:
    """Builds the layout of widgets for user-selected import parameters."""

    param_list = self.import_type["params"]
    widget_layout = QVBoxLayout()
    widget_elements = dict()
    for param_item in param_list:
        name = param_item["name"]
        type = param_item["type"]
        options = param_item.get("options", None)
        if type == "radio":
            radio_group = QButtonGroup(parent=self)
            option_list = options.split(",")
            selected_option = option_list[0]
            for option in option_list:
                btn_widget = QRadioButton(option)
                if option == selected_option:
                    btn_widget.setChecked(True)
                widget_layout.addWidget(btn_widget)
                radio_group.addButton(btn_widget)
            radio_group.buttonToggled.connect(lambda: self.changed.emit())
            widget_elements[name] = radio_group
        elif type == "check":
            check_widget = QCheckBox(name)
            check_widget.stateChanged.connect(lambda: self.changed.emit())
            widget_layout.addWidget(check_widget)
            widget_elements[name] = check_widget
        elif type == "function_menu":
            list_widget = QComboBox()
            # options has name of method which returns list of options
            option_list = getattr(self, options)()
            for option in option_list:
                list_widget.addItem(option)
            list_widget.currentIndexChanged.connect(lambda: self.changed.emit())
            widget_layout.addWidget(list_widget)
            widget_elements[name] = list_widget
        self.widget_elements = widget_elements
    return widget_layout

set_values_from_video(video)

Set the form fields using attributes on video.

Source code in sleap/gui/dialogs/importvideos.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def set_values_from_video(self, video):
    """Set the form fields using attributes on video."""
    param_list = self.import_type["params"]
    for param in param_list:
        name = param["name"]
        param["type"]

        if hasattr(video, name):
            val = getattr(video, name)

            widget = self.widget_elements[name]
            if hasattr(widget, "isChecked"):
                widget.setChecked(val)
            elif hasattr(widget, "value"):
                widget.setValue(val)
            elif hasattr(widget, "currentText"):
                widget.setCurrentText(str(val))
            elif hasattr(widget, "text"):
                widget.setText(str(val))

ImportVideos

Class to handle video importing UI.

Methods:

Name Description
ask

Runs the import UI.

Source code in sleap/gui/dialogs/importvideos.py
 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
class ImportVideos:
    """Class to handle video importing UI."""

    def __init__(self):
        self.result = []

    def ask(
        self,
        filenames: Optional[List[str]] = None,
        messages: Optional[Dict[str, str]] = None,
    ):
        """Runs the import UI.

        1. Show file selection dialog.
        2. Show import parameter dialog with widget for each file.

        Args:
            filenames: List of the filenames. If not provided, a file browser GUI will
                appear.

        Returns:
            List with dict of the parameters for each file to import.
        """
        messages = dict() if messages is None else messages

        if filenames is None:
            any_video_exts = " ".join(["*." + ext for ext in available_video_exts()])
            media_video_exts = " ".join(["*." + ext for ext in MediaVideo.EXTS])
            hdf5_video_exts = " ".join(["*." + ext for ext in HDF5Video.EXTS])
            image_video_exts = " ".join(["*." + ext for ext in ImageVideo.EXTS])
            tiff_video_exts = " ".join(["*." + ext for ext in TiffVideo.EXTS])

            filenames, filter = FileDialog.openMultiple(
                None,
                "Select videos to import...",  # dialogue title
                ".",  # initial path
                f"Any Video ({any_video_exts});;"
                f"Media ({media_video_exts});;"
                f"HDF5 ({hdf5_video_exts});;"
                f"Image ({image_video_exts});;"
                f"TIFF ({tiff_video_exts});;"
                "Any File (*.*)",
            )

        if len(filenames) > 0:
            importer = ImportParamDialog(filenames, messages)
            importer.accepted.connect(lambda: importer.get_data(self.result))
            importer.exec_()

        return self.result

    @classmethod
    def create_videos(cls, import_param_list: List[Dict[str, Any]]) -> List[Video]:
        return [cls.create_video(import_item) for import_item in import_param_list]

    @staticmethod
    def create_video(import_item: Dict[str, Any]) -> Video:
        return Video.from_filename(**import_item["params"])

    def ask_and_return_videos(self) -> List[Video]:
        return ImportVideos.create_videos(ImportVideos().ask())

ask(filenames=None, messages=None)

Runs the import UI.

  1. Show file selection dialog.
  2. Show import parameter dialog with widget for each file.

Parameters:

Name Type Description Default
filenames Optional[List[str]]

List of the filenames. If not provided, a file browser GUI will appear.

None

Returns:

Type Description

List with dict of the parameters for each file to import.

Source code in sleap/gui/dialogs/importvideos.py
 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
def ask(
    self,
    filenames: Optional[List[str]] = None,
    messages: Optional[Dict[str, str]] = None,
):
    """Runs the import UI.

    1. Show file selection dialog.
    2. Show import parameter dialog with widget for each file.

    Args:
        filenames: List of the filenames. If not provided, a file browser GUI will
            appear.

    Returns:
        List with dict of the parameters for each file to import.
    """
    messages = dict() if messages is None else messages

    if filenames is None:
        any_video_exts = " ".join(["*." + ext for ext in available_video_exts()])
        media_video_exts = " ".join(["*." + ext for ext in MediaVideo.EXTS])
        hdf5_video_exts = " ".join(["*." + ext for ext in HDF5Video.EXTS])
        image_video_exts = " ".join(["*." + ext for ext in ImageVideo.EXTS])
        tiff_video_exts = " ".join(["*." + ext for ext in TiffVideo.EXTS])

        filenames, filter = FileDialog.openMultiple(
            None,
            "Select videos to import...",  # dialogue title
            ".",  # initial path
            f"Any Video ({any_video_exts});;"
            f"Media ({media_video_exts});;"
            f"HDF5 ({hdf5_video_exts});;"
            f"Image ({image_video_exts});;"
            f"TIFF ({tiff_video_exts});;"
            "Any File (*.*)",
        )

    if len(filenames) > 0:
        importer = ImportParamDialog(filenames, messages)
        importer.accepted.connect(lambda: importer.get_data(self.result))
        importer.exec_()

    return self.result

MessageWidget

Bases: QWidget

Widget to show message.

Source code in sleap/gui/dialogs/importvideos.py
577
578
579
580
581
582
583
584
585
586
class MessageWidget(QWidget):
    """Widget to show message."""

    def __init__(self, message: str = str(), *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.message = QLabel(message)
        self.message.setStyleSheet("color: red")
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.message)
        self.setLayout(self.layout)

VideoPreviewWidget

Bases: QWidget

Widget to show video preview. Based on :class:Video class.

Attributes:

Name Type Description
video

the video to show

max_preview_size

Maximum size of the preview images.

Note

This widget is used by ImportItemWidget.

Methods:

Name Description
clear_video

Clear the video preview.

load_video

Load the video preview and display label text.

plot

Show the video preview.

Source code in sleap/gui/dialogs/importvideos.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
class VideoPreviewWidget(QWidget):
    """Widget to show video preview. Based on :class:`Video` class.

    Attributes:
        video: the video to show
        max_preview_size: Maximum size of the preview images.

    Note:
        This widget is used by ImportItemWidget.
    """

    def __init__(
        self, video: Video = None, max_preview_size: int = 256, *args, **kwargs
    ):
        super(VideoPreviewWidget, self).__init__(*args, **kwargs)
        self.max_preview_size = max_preview_size
        # widgets to include
        self.view = GraphicsView()
        self.video_label = QLabel()
        # layout for widgets
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.view)
        self.layout.addWidget(self.video_label)
        self.setLayout(self.layout)
        self.view.show()

        if video is not None:
            self.load_video(video)

    def clear_video(self):
        """Clear the video preview."""
        self.view.clear()

    def load_video(self, video: Video, initial_frame=0, plot=True):
        """Load the video preview and display label text."""
        self.video = video
        self.frame_idx = initial_frame
        n_frames, height, width, channels = self.video.shape
        label = "(%d, %d), %d f, %d c" % (
            width,
            height,
            n_frames,
            channels,
        )
        self.video_label.setText(label)
        if plot:
            self.plot(initial_frame)

    def plot(self, idx=0):
        """Show the video preview."""
        if self.video is None:
            return

        # Get image data
        frame = self.video[idx]

        # Re-size the preview image
        height, width = frame.shape[:2]
        img_length = max(height, width)
        if img_length > self.max_preview_size:
            ratio = self.max_preview_size / img_length
            frame = cv2.resize(frame, None, fx=ratio, fy=ratio)

        # Clear existing objects
        self.view.clear()

        # Ensure frame has 3 dimensions for ndarray_to_qimage
        if frame.ndim == 2:
            frame = np.expand_dims(frame, axis=-1)

        # TODO: Look into this -- BGR to RGB should be handled by the video backend
        # Convert BGR to RGB if image has 3 channels
        # if frame.shape[-1] == 3:
        #     frame = frame[..., ::-1]
        image = ndarray_to_qimage(frame)

        # Display image
        self.view.setImage(image)

clear_video()

Clear the video preview.

Source code in sleap/gui/dialogs/importvideos.py
618
619
620
def clear_video(self):
    """Clear the video preview."""
    self.view.clear()

load_video(video, initial_frame=0, plot=True)

Load the video preview and display label text.

Source code in sleap/gui/dialogs/importvideos.py
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def load_video(self, video: Video, initial_frame=0, plot=True):
    """Load the video preview and display label text."""
    self.video = video
    self.frame_idx = initial_frame
    n_frames, height, width, channels = self.video.shape
    label = "(%d, %d), %d f, %d c" % (
        width,
        height,
        n_frames,
        channels,
    )
    self.video_label.setText(label)
    if plot:
        self.plot(initial_frame)

plot(idx=0)

Show the video preview.

Source code in sleap/gui/dialogs/importvideos.py
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
def plot(self, idx=0):
    """Show the video preview."""
    if self.video is None:
        return

    # Get image data
    frame = self.video[idx]

    # Re-size the preview image
    height, width = frame.shape[:2]
    img_length = max(height, width)
    if img_length > self.max_preview_size:
        ratio = self.max_preview_size / img_length
        frame = cv2.resize(frame, None, fx=ratio, fy=ratio)

    # Clear existing objects
    self.view.clear()

    # Ensure frame has 3 dimensions for ndarray_to_qimage
    if frame.ndim == 2:
        frame = np.expand_dims(frame, axis=-1)

    # TODO: Look into this -- BGR to RGB should be handled by the video backend
    # Convert BGR to RGB if image has 3 channels
    # if frame.shape[-1] == 3:
    #     frame = frame[..., ::-1]
    image = ndarray_to_qimage(frame)

    # Display image
    self.view.setImage(image)