A community-maintained Python framework for creating mathematical animations.
Fixed a few CLI and rendering bugs (#1595)
Ryan McCauleye4d00b5eb2b7
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.pyindex e50706215..04d59924b 100644--- a/manim/scene/scene_file_writer.py+++ b/manim/scene/scene_file_writer.py@@ -2,7 +2,6 @@__all__ = ["SceneFileWriter"]-import datetimeimport osimport shutil@@ -22,7 +21,10 @@ from ..utils.file_ops import (add_extension_if_not_present,add_version_before_extension,guarantee_existence,+ is_gif_format,+ is_png_format,modify_atime,+ write_to_movie,)from ..utils.sounds import get_full_sound_file_path@@ -86,7 +88,7 @@ class SceneFileWriter(object):image_dir, add_extension_if_not_present(default_name, ".png"))- if config["write_to_movie"]:+ if write_to_movie():movie_dir = guarantee_existence(config.get_dir("video_dir", module_name=module_name))@@ -97,7 +99,7 @@ class SceneFileWriter(object):default_name, config["movie_file_extension"]),)- if config["format"] == "gif":+ if is_gif_format():self.gif_file_path = os.path.join(movie_dir,add_extension_if_not_present(default_name, GIF_FILE_EXTENSION),@@ -119,7 +121,7 @@ class SceneFileWriter(object):hash_animation : strHash of the animation."""- if not hasattr(self, "partial_movie_directory"):+ if not hasattr(self, "partial_movie_directory") or not write_to_movie():return# None has to be added to partial_movie_files to keep the right index with scene.num_plays.@@ -252,7 +254,7 @@ class SceneFileWriter(object):allow_write : bool, optionalWhether or not to write to a video file."""- if config["write_to_movie"] and allow_write:+ if write_to_movie() and allow_write:self.open_movie_pipe(file_path=file_path)def end_animation(self, allow_write=False):@@ -265,7 +267,7 @@ class SceneFileWriter(object):allow_write : bool, optionalWhether or not to write to a video file."""- if config["write_to_movie"] and allow_write:+ if write_to_movie() and allow_write:self.close_movie_pipe()def write_frame(self, frame_or_renderer):@@ -285,11 +287,13 @@ class SceneFileWriter(object):)else:frame = frame_or_renderer- if config["write_to_movie"]:+ if write_to_movie():self.writing_process.stdin.write(frame.tobytes())- if config["format"] == "png":- path, extension = os.path.splitext(self.image_file_path)- Image.fromarray(frame).save(f"{path}{self.frame_count}{extension}")+ if is_png_format():+ target_dir, extension = os.path.splitext(self.image_file_path)+ Image.fromarray(frame).save(+ f"{target_dir}{self.frame_count}{extension}"+ )self.frame_count += 1def save_final_image(self, image):@@ -329,13 +333,14 @@ class SceneFileWriter(object):def finish(self, partial_movie_files=None):"""- Finishes writing to the FFMPEG buffer.+ Finishes writing to the FFMPEG buffer or writing images+ to output directory.Combines the partial movie files into thewhole scene.If save_last_frame is True, saves the lastframe in the default image directory."""- if config["write_to_movie"]:+ if write_to_movie():if hasattr(self, "writing_process"):self.writing_process.terminate()self.combine_movie_files(partial_movie_files=partial_movie_files)@@ -343,6 +348,9 @@ class SceneFileWriter(object):self.flush_cache_directory()else:self.clean_cache()+ elif is_png_format():+ target_dir, _ = os.path.splitext(self.image_file_path)+ logger.info("\n%i images ready at %s\n", self.frame_count, target_dir)def open_movie_pipe(self, file_path=None):"""@@ -416,7 +424,7 @@ class SceneFileWriter(object)::class:`bool`Whether the file exists."""- if not hasattr(self, "partial_movie_directory"):+ if not hasattr(self, "partial_movie_directory") or not write_to_movie():return Falsepath = os.path.join(self.partial_movie_directory,@@ -474,10 +482,10 @@ class SceneFileWriter(object):"-nostdin",]- if config["write_to_movie"] and not config["format"] == "gif":+ if write_to_movie() and not is_gif_format():commands += ["-c", "copy", movie_file_path]- if config["format"] == "gif":+ if is_gif_format():if not config["output_file"]:self.gif_file_path = str(add_version_before_extension(self.gif_file_path)@@ -535,9 +543,9 @@ class SceneFileWriter(object):os.remove(sound_file_path)self.print_file_ready_message(- self.gif_file_path if config["save_as_gif"] else movie_file_path+ self.gif_file_path if is_gif_format() else movie_file_path)- if config["write_to_movie"]:+ if write_to_movie():for file_path in partial_movie_files:# We have to modify the accessed time so if we have to clean the cache we remove the one used the longest.modify_atime(file_path)diff --git a/manim/utils/file_ops.py b/manim/utils/file_ops.pyindex b980fd607..bf16b4023 100644--- a/manim/utils/file_ops.py+++ b/manim/utils/file_ops.py@@ -6,9 +6,12 @@ __all__ = ["seek_full_path_from_defaults","modify_atime","open_file",+ "is_mp4_format",+ "is_gif_format",+ "is_png_format",+ "write_to_movie",]-import osimport platformimport subprocess as sp@@ -21,6 +24,61 @@ from manim import __version__, config, loggerfrom .. import console+def is_mp4_format() -> bool:+ """+ Determines if output format is .mp4++ Returns+ -------+ class:`bool`+ ``True`` if format is set as mp4++ """+ return config["format"] == "mp4"+++def is_gif_format() -> bool:+ """+ Determines if output format is .gif++ Returns+ -------+ class:`bool`+ ``True`` if format is set as gif++ """+ return config["format"] == "gif"+++def is_png_format() -> bool:+ """+ Determines if output format is .png++ Returns+ -------+ class:`bool`+ ``True`` if format is set as png++ """+ return config["format"] == "png"+++def write_to_movie() -> bool:+ """+ Determines from config if the output is a video format such as mp4 or gif, if the --format is set as 'png'+ then it will take precedence event if the write_to_movie flag is set++ Returns+ -------+ class:`bool`+ ``True`` if the output should be written in a movie format++ """+ if is_png_format():+ return False+ return config["write_to_movie"] or is_mp4_format() or is_gif_format()++def add_extension_if_not_present(file_name, extension):if file_name.suffix != extension:return file_name.with_suffix(extension)@@ -87,9 +145,9 @@ def open_media_file(file_writer):if config["save_last_frame"]:file_paths.append(file_writer.image_file_path)- if config["write_to_movie"] and not config["format"] == "gif":+ if write_to_movie() and not is_gif_format():file_paths.append(file_writer.movie_file_path)- if config["format"] == "gif":+ if write_to_movie() and is_gif_format():file_paths.append(file_writer.gif_file_path)for file_path in file_paths:diff --git a/tests/test_scene_rendering/test_cli_flags.py b/tests/test_scene_rendering/test_cli_flags.pyindex b5cdac8c8..3f7c78718 100644--- a/tests/test_scene_rendering/test_cli_flags.py+++ b/tests/test_scene_rendering/test_cli_flags.py@@ -224,3 +224,142 @@ def test_dash_as_filename(tmp_path):tmp_path / "images" / "-" / "Test.png").exists()assert exists, result.output+++def test_gif_format_output(tmp_path, manim_cfg_file, simple_scenes_path):+ """Test only gif created with manim version in file name when --format gif is set"""+ scene_name = "SquareToCircle"+ command = [+ sys.executable,+ "-m",+ "manim",+ "-ql",+ "--media_dir",+ str(tmp_path),+ "--format",+ "gif",+ simple_scenes_path,+ scene_name,+ ]+ out, err, exit_code = capture(command)+ assert exit_code == 0, err++ unexpected_mp4_path = (+ tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4"+ )+ assert not unexpected_mp4_path.exists(), "unexpected mp4 file found at " + str(+ unexpected_mp4_path+ )++ expected_gif_path = (+ tmp_path+ / "videos"+ / "simple_scenes"+ / "480p15"+ / add_version_before_extension("SquareToCircle.gif")+ )+ assert expected_gif_path.exists(), "gif file not found at " + str(expected_gif_path)+++def test_mp4_format_output(tmp_path, manim_cfg_file, simple_scenes_path):+ """Test only mp4 created without manim version in file name when --format mp4 is set"""+ scene_name = "SquareToCircle"+ command = [+ sys.executable,+ "-m",+ "manim",+ "-ql",+ "--media_dir",+ str(tmp_path),+ "--format",+ "mp4",+ simple_scenes_path,+ scene_name,+ ]+ out, err, exit_code = capture(command)+ assert exit_code == 0, err++ unexpected_gif_path = (+ tmp_path+ / "videos"+ / "simple_scenes"+ / "480p15"+ / add_version_before_extension("SquareToCircle.gif")+ )+ assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str(+ unexpected_gif_path+ )++ expected_mp4_path = (+ tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4"+ )+ assert expected_mp4_path.exists(), "expected mp4 file not found at " + str(+ expected_mp4_path+ )+++def test_videos_not_created_when_png_format_set(+ tmp_path, manim_cfg_file, simple_scenes_path+):+ """Test mp4 and gifs are not created when --format png is set"""+ scene_name = "SquareToCircle"+ command = [+ sys.executable,+ "-m",+ "manim",+ "-ql",+ "--media_dir",+ str(tmp_path),+ "--format",+ "png",+ simple_scenes_path,+ scene_name,+ ]+ out, err, exit_code = capture(command)+ assert exit_code == 0, err++ unexpected_gif_path = (+ tmp_path+ / "videos"+ / "simple_scenes"+ / "480p15"+ / add_version_before_extension("SquareToCircle.gif")+ )+ assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str(+ unexpected_gif_path+ )++ unexpected_mp4_path = (+ tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4"+ )+ assert not unexpected_mp4_path.exists(), "expected mp4 file not found at " + str(+ unexpected_mp4_path+ )+++def test_images_are_created_when_png_format_set(+ tmp_path, manim_cfg_file, simple_scenes_path+):+ """Test images are created in media directory when --format png is set"""+ scene_name = "SquareToCircle"+ command = [+ sys.executable,+ "-m",+ "manim",+ "-ql",+ "--media_dir",+ str(tmp_path),+ "--format",+ "png",+ simple_scenes_path,+ scene_name,+ ]+ out, err, exit_code = capture(command)+ assert exit_code == 0, err++ expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0.png"+ assert expected_png_path.exists(), "png file not found at " + str(expected_png_path)