From 29331245bbfbd8e1344956b71f3be1134955ea86 Mon Sep 17 00:00:00 2001 From: Talmo Pereira Date: Sun, 14 Apr 2024 00:04:25 -0700 Subject: [PATCH] Replace filename --- sleap_io/model/video.py | 19 +++++++++++++++++++ tests/model/test_video.py | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/sleap_io/model/video.py b/sleap_io/model/video.py index b091389c..87bdfe30 100644 --- a/sleap_io/model/video.py +++ b/sleap_io/model/video.py @@ -192,3 +192,22 @@ def close(self): if self.backend is not None: del self.backend self.backend = None + + def replace_filename(self, new_filename: str | Path, open: bool = True): + """Update the filename of the video, optionally opening the backend. + + Args: + new_filename: New filename to set for the video. + open: If `True` (the default), open the backend with the new filename. If + the new filename does not exist, no error is raised. + """ + if isinstance(new_filename, Path): + new_filename = str(new_filename) + + self.filename = new_filename + + if open: + if self.exists(): + self.open() + else: + self.close() diff --git a/tests/model/test_video.py b/tests/model/test_video.py index 82b818d1..062353a0 100644 --- a/tests/model/test_video.py +++ b/tests/model/test_video.py @@ -74,3 +74,22 @@ def test_video_open_close(centered_pair_low_quality_path): assert video.shape == (1100, 384, 384, 3) video.open(grayscale=True) assert video.shape == (1100, 384, 384, 1) + + +def test_video_replace_filename(centered_pair_low_quality_path): + video = Video.from_filename("test.mp4") + assert video.exists() is False + + video.replace_filename(centered_pair_low_quality_path) + assert video.exists() is True + assert video.is_open is True + assert type(video.backend) == MediaVideo + + video.replace_filename("test.mp4") + assert video.exists() is False + assert video.is_open is False + + video.replace_filename(centered_pair_low_quality_path, open=False) + assert video.exists() is True + assert video.is_open is False + assert video.backend is None