Example #1
0
def test_non_native_dialog():
    d = dict()
    FileDialog._non_native_if_set(d)
    assert "options" not in d

    os.environ["USE_NON_NATIVE_FILE"] = "1"

    FileDialog._non_native_if_set(d)
    assert d["options"] == QtWidgets.QFileDialog.DontUseNativeDialog
Example #2
0
    def _add_model_action(self):
        """Method called when user clicks 'add models' button."""
        dir = FileDialog.openDir(None, dir=None, caption="")

        if dir:
            self._cfg_getter.dir_paths.append(dir)
            self._update_cfgs()
Example #3
0
File: app.py Project: jens-k/sleap
    def visualizeOutputs(self):
        """Gui for adding overlay with live visualization of predictions."""
        filters = ["Model (*.json)"]

        # Default to opening from models directory from project
        models_dir = None
        if self.state["filename"] is not None:
            models_dir = os.path.join(os.path.dirname(self.state["filename"]),
                                      "models/")

        # Show dialog
        filename, selected_filter = FileDialog.open(
            self,
            dir=models_dir,
            caption="Import model outputs...",
            filter=";;".join(filters),
        )

        if len(filename) == 0:
            return

        # Model as overlay datasource
        # This will show live inference results

        from sleap.gui.overlays.base import DataOverlay

        overlay = DataOverlay.from_model(filename,
                                         self.state["video"],
                                         player=self.player)

        self.overlays["inference"] = overlay

        self.plotFrame()
Example #4
0
 def select_file(*args, x=field):
     filename = FileDialog.openDir(None,
                                   directory=None,
                                   caption="Open File")
     if len(filename):
         x.setText(filename)
     self.valueChanged.emit()
Example #5
0
    def save(
        self, output_dir: Optional[str] = None, labels_filename: Optional[str] = None
    ):
        """Save scripts and configs to run pipeline."""
        if output_dir is None:
            models_dir = os.path.join(os.path.dirname(self.labels_filename), "/models")
            output_dir = FileDialog.openDir(
                None, directory=models_dir, caption="Select directory to save scripts"
            )

            if not output_dir:
                return

        pipeline_form_data = self.pipeline_form_widget.get_form_data()
        items_for_inference = self.get_items_for_inference(pipeline_form_data)
        config_info_list = self.get_every_head_config_data(pipeline_form_data)

        if labels_filename is None:
            labels_filename = self.labels_filename

        runners.write_pipeline_files(
            output_dir=output_dir,
            labels_filename=labels_filename,
            config_info_list=config_info_list,
            inference_params=pipeline_form_data,
            items_for_inference=items_for_inference,
        )
Example #6
0
def test_non_native_dialog():
    save_env_non_native = os.environ.get("USE_NON_NATIVE_FILE", None)

    os.environ["USE_NON_NATIVE_FILE"] = ""

    d = dict()
    FileDialog._non_native_if_set(d)
    assert "options" not in d

    os.environ["USE_NON_NATIVE_FILE"] = "1"

    FileDialog._non_native_if_set(d)
    assert d["options"] == QtWidgets.QFileDialog.DontUseNativeDialog

    if save_env_non_native is not None:
        os.environ["USE_NON_NATIVE_FILE"] = save_env_non_native
Example #7
0
 def select_file(*args, x=field):
     filter = item.get("filter", "Any File (*.*)")
     filename, _ = FileDialog.open(
         None, directory=None, caption="Open File", filter=filter
     )
     if len(filename):
         x.setText(filename)
     self.valueChanged.emit()
Example #8
0
 def doFileSelection(self):
     """Shows file browser to add training profile for given model type."""
     filename, _ = FileDialog.open(
         None,
         dir=None,
         caption="Select training configuration file...",
         filter="JSON (*.json)",
     )
     return self._cfg_getter.try_loading_path(filename) if filename else None
Example #9
0
def test_non_native_dialog():
    save_env_non_native = os.environ.get("USE_NON_NATIVE_FILE", None)

    os.environ["USE_NON_NATIVE_FILE"] = ""

    d = dict()
    FileDialog._non_native_if_set(d)
    is_linux = sys.platform.startswith("linux")
    if is_linux:
        assert d["options"] == QtWidgets.QFileDialog.DontUseNativeDialog
    else:
        assert "options" not in d

    os.environ["USE_NON_NATIVE_FILE"] = "1"
    d = dict()
    FileDialog._non_native_if_set(d)
    assert d["options"] == QtWidgets.QFileDialog.DontUseNativeDialog

    if save_env_non_native is not None:
        os.environ["USE_NON_NATIVE_FILE"] = save_env_non_native
Example #10
0
    def visualizeOutputs(self):
        """Gui for adding overlay with live visualization of predictions."""
        filters = ["Model (*.json)"]

        # Default to opening from models directory from project
        models_dir = None
        if self.state["filename"] is not None:
            models_dir = os.path.join(os.path.dirname(self.state["filename"]),
                                      "models/")

        # Show dialog
        filename, selected_filter = FileDialog.open(
            self,
            dir=models_dir,
            caption="Import model outputs...",
            filter=";;".join(filters),
        )

        if len(filename) == 0:
            return

        # Model as overlay datasource
        # This will show live inference results

        from sleap.gui.overlays.base import DataOverlay

        predictor = DataOverlay.make_predictor(filename)
        show_pafs = False

        # If multi-head model with both confmaps and pafs,
        # ask user which to show.
        if (predictor.confidence_maps_key_name
                and predictor.part_affinity_fields_key_name):
            results = FormBuilderModalDialog(
                form_name="head_type_form").get_results()
            show_pafs = "Part Affinity" in results["head_type"]

        overlay = DataOverlay.from_predictor(
            predictor=predictor,
            video=self.state["video"],
            player=self.player,
            show_pafs=show_pafs,
        )

        self.overlays["inference"] = overlay

        self.plotFrame()
Example #11
0
    def locateFile(self, idx: int):
        """Shows dialog for user to locate a specific missing file."""
        old_filename = self.filenames[idx]
        _, old_ext = os.path.splitext(old_filename)

        caption = f"Please locate {old_filename}..."
        filters = [f"Missing file type (*{old_ext})", "Any File (*.*)"]
        new_filename, _ = FileDialog.open(None,
                                          dir=None,
                                          caption=caption,
                                          filter=";;".join(filters))

        if new_filename:
            # Try using this change to find other missing files
            self.setFilename(idx, new_filename)

            # Redraw the table
            self.file_table.reset()
Example #12
0
    def ask(self):
        """Runs the import UI.

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

        Args:
            None.
        Returns:
            List with dict of the parameters for each file to import.
        """
        filenames, filter = FileDialog.openMultiple(
            None,
            "Select videos to import...",  # dialogue title
            ".",  # initial path
            "Any Video (*.h5 *.hd5v *.mp4 *.avi *.json);;HDF5 (*.h5 *.hd5v);;ImgStore (*.json);;Media Video (*.mp4 *.avi);;Any File (*.*)",
        )
        if len(filenames) > 0:
            importer = ImportParamDialog(filenames)
            importer.accepted.connect(lambda: importer.get_data(self.result))
            importer.exec_()
        return self.result
Example #13
0
    def export_package(self, output_path: Optional[str] = None, gui: bool = True):
        """Export training job package."""
        # TODO: Warn if self.mode != "training"?
        if output_path is None:
            # Prompt for output path.
            output_path, _ = FileDialog.save(
                caption="Export Training Job Package...",
                dir=f"{self.labels_filename}.training_job.zip",
                filter="Training Job Package (*.zip)",
            )
            if len(output_path) == 0:
                return

        # Create temp dir before packaging.
        tmp_dir = tempfile.TemporaryDirectory()

        # Remove the temp dir when program exits in case something goes wrong.
        # atexit.register(shutil.rmtree, tmp_dir.name, ignore_errors=True)

        # Check if we need to include suggestions.
        include_suggestions = False
        items_for_inference = self.get_items_for_inference(
            self.pipeline_form_widget.get_form_data()
        )
        for item in items_for_inference.items:
            if (
                isinstance(item, runners.DatasetItemForInference)
                and item.frame_filter == "suggested"
            ):
                include_suggestions = True

        # Save dataset with images.
        labels_pkg_filename = str(
            Path(self.labels_filename).with_suffix(".pkg.slp").name
        )
        if gui:
            ret = sleap.gui.commands.export_dataset_gui(
                self.labels,
                tmp_dir.name + "/" + labels_pkg_filename,
                all_labeled=False,
                suggested=include_suggestions,
            )
            if ret == "canceled":
                # Quit if user canceled during export.
                tmp_dir.cleanup()
                return
        else:
            self.labels.save(
                tmp_dir.name + "/" + labels_pkg_filename,
                with_images=True,
                embed_all_labeled=False,
                embed_suggested=include_suggestions,
            )

        # Save config and scripts.
        self.save(tmp_dir.name, labels_filename=labels_pkg_filename)

        # Package everything.
        shutil.make_archive(
            base_name=str(Path(output_path).with_suffix("")),
            format="zip",
            root_dir=tmp_dir.name,
        )

        msg = f"Saved training job package to: {output_path}"
        print(msg)

        # Close training editor.
        self.accept()

        if gui:
            msgBox = QtWidgets.QMessageBox(text="Created training job package.")
            msgBox.setDetailedText("Path:\n" + output_path)
            msgBox.setWindowTitle("Training Job Package")
            okButton = msgBox.addButton(QtWidgets.QMessageBox.Ok)
            openFolderButton = msgBox.addButton(
                "Open containing folder", QtWidgets.QMessageBox.ActionRole
            )
            colabButton = msgBox.addButton(
                "Go to Colab", QtWidgets.QMessageBox.ActionRole
            )
            msgBox.exec_()

            if msgBox.clickedButton() == openFolderButton:
                sleap.gui.commands.open_file(str(Path(output_path).resolve().parent))
            elif msgBox.clickedButton() == colabButton:
                # TODO: Update this to more workflow-tailored notebook.
                sleap.gui.commands.copy_to_clipboard(output_path)
                sleap.gui.commands.open_website(
                    "https://colab.research.google.com/github/murthylab/sleap-notebooks/blob/master/Training_and_inference_using_Google_Drive.ipynb"
                )

        tmp_dir.cleanup()