A community-maintained Python framework for creating mathematical animations.
use ManimConfig.get_dir() where possible
leotrs133e33c1f472
diff --git a/manim/__main__.py b/manim/__main__.pyindex 0f13228f6..6e4dae6e5 100644--- a/manim/__main__.py+++ b/manim/__main__.py@@ -24,13 +24,12 @@ def open_file_if_needed(file_writer):open_file = any([config["preview"], config["show_in_file_browser"]])if open_file:- current_os = platform.system()file_paths = []if config["save_last_frame"]:- file_paths.append(file_writer.get_image_file_path())+ file_paths.append(file_writer.image_file_path)if config["write_to_movie"] and not config["save_as_gif"]:- file_paths.append(file_writer.get_movie_file_path())+ file_paths.append(file_writer.movie_file_path)if config["save_as_gif"]:file_paths.append(file_writer.gif_file_path)@@ -69,7 +68,7 @@ def main():config.digest_args(args)init_dirs(config)- module = get_module(config["input_file"])+ module = get_module(config.get_dir("input_file"))all_scene_classes = get_scene_classes_from_module(module)scene_classes_to_render = get_scenes_to_render(all_scene_classes)for SceneClass in scene_classes_to_render:diff --git a/manim/config/default.cfg b/manim/config/default.cfgindex 64ee4b21a..2fff637ae 100644--- a/manim/config/default.cfg+++ b/manim/config/default.cfg@@ -68,18 +68,17 @@ upto_animation_number = -1# Set them at the CLI with the corresponding flag, or set their default# values here.-# --media_dir. Note that video files will be put in a folder below media_dir,-# as well as Tex and texts.+# --media_dirmedia_dir = ./media-# --log_dir (by default "/logs", that will be put inside the media dir)+# --log_dirlog_dir = {media_dir}/logs# the following do not have CLI arguments but depend on media_dir-video_dir = {media_dir}/videos+video_dir = {media_dir}/videos/{module_name}/{quality}+images_dir = {media_dir}/images/{module_name}tex_dir = {media_dir}/Textext_dir = {media_dir}/texts-images_dir = {media_dir}/images# --use_js_rendereruse_js_renderer = Falsediff --git a/manim/config/logger.py b/manim/config/logger.pyindex 2ca472def..2b3c788e2 100644--- a/manim/config/logger.py+++ b/manim/config/logger.py@@ -101,7 +101,9 @@ def set_file_logger(config, verbosity):if scene_name_suffixelse f"{scene_file_name}.log")- log_file_path = os.path.join(config["log_dir"], log_file_name)+ log_file_path = config.get_dir("log_dir") / log_file_name+ log_file_path.parent.mkdir(parents=True, exist_ok=True)+file_handler = logging.FileHandler(log_file_path, mode="w")file_handler.setFormatter(JSONFormatter())diff --git a/manim/config/utils.py b/manim/config/utils.pyindex 4f03815de..94ad3b3a9 100644--- a/manim/config/utils.py+++ b/manim/config/utils.py@@ -753,7 +753,7 @@ class ManimConfig(MutableMapping):doc="Main output directory, relative to execution directory.",)- def _get_dir(self, key):+ def get_dir(self, key, **kwargs):dirs = ["media_dir","video_dir",@@ -764,9 +764,23 @@ class ManimConfig(MutableMapping):"input_file","output_file",]- dirs.remove(key)- dirs = {k: self._d[k] for k in dirs}- path = self._d[key].format(**dirs)+ if key not in dirs:+ raise KeyError('must pass one of '+ '{media,video,images,text,tex,log}_dir '+ 'or {input,output}_file')++ dirs.remove(key) # a path cannot contain itself+ dir_args = {k: self._d[k] for k in dirs}++ qual = constants.QUALITIES[self.quality]+ qual_arg = f'{qual["pixel_height"]}p{qual["frame_rate"]}'++ try:+ path = self._d[key].format(quality=qual_arg, **dir_args, **kwargs)+ except KeyError as exc:+ raise KeyError(f'{key} requires the following keyword arguments: '+ + " ".join(exc.args)) from exc+return Path(path) if path else Nonedef _set_dir(self, key, val):@@ -776,31 +790,31 @@ class ManimConfig(MutableMapping):self._d.__setitem__(key, val)log_dir = property(- lambda self: self._get_dir("log_dir"),+ lambda self: self._d["log_dir"],lambda self, val: self._set_dir("log_dir", val),doc="Directory to place logs",)video_dir = property(- lambda self: self._get_dir("video_dir"),+ lambda self: self._d["video_dir"],lambda self, val: self._set_dir("video_dir", val),doc="Directory to place videos",)images_dir = property(- lambda self: self._get_dir("images_dir"),+ lambda self: self._d["images_dir"],lambda self, val: self._set_dir("images_dir", val),doc="Directory to place images",)text_dir = property(- lambda self: self._get_dir("text_dir"),+ lambda self: self._d["text_dir"],lambda self, val: self._set_dir("text_dir", val),doc="Directory to place text",)tex_dir = property(- lambda self: self._get_dir("tex_dir"),+ lambda self: self._d["tex_dir"],lambda self, val: self._set_dir("tex_dir", val),doc="Directory to place tex",)@@ -812,13 +826,13 @@ class ManimConfig(MutableMapping):)input_file = property(- lambda self: self._get_dir("input_file"),+ lambda self: self._d["input_file"],lambda self, val: self._set_dir("input_file", val),doc="Input file name.",)output_file = property(- lambda self: self._get_dir("output_file"),+ lambda self: self._d["output_file"],lambda self, val: self._set_dir("output_file", val),doc="Output file name.",)diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.pyindex 5a3458218..4bd94de85 100644--- a/manim/mobject/mobject.py+++ b/manim/mobject/mobject.py@@ -199,7 +199,7 @@ class Mobject(Container):def save_image(self, name=None):self.get_image().save(- Path(config["video_dir"]).joinpath((name or str(self)) + ".png")+ Path(config.get_dir("video_dir")).joinpath((name or str(self)) + ".png"))def copy(self):diff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.pyindex 204834ed1..0dd0981a8 100644--- a/manim/mobject/svg/text_mobject.py+++ b/manim/mobject/svg/text_mobject.py@@ -310,7 +310,7 @@ class CairoText(SVGMobject):if NOT_SETTING_FONT_MSG:logger.warning(NOT_SETTING_FONT_MSG)- dir_name = config["text_dir"]+ dir_name = config.get_dir("text_dir")if not os.path.exists(dir_name):os.makedirs(dir_name)@@ -884,7 +884,7 @@ class Text(SVGMobject):"""size = self.size * 10line_spacing = self.line_spacing * 10- dir_name = config["text_dir"]+ dir_name = config.get_dir("text_dir")if not os.path.exists(dir_name):os.makedirs(dir_name)hash_name = self.text2hash()diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.pyindex a72c15265..16d4a2813 100644--- a/manim/scene/scene_file_writer.py+++ b/manim/scene/scene_file_writer.py@@ -67,42 +67,28 @@ class SceneFileWriter(object):returnif config["input_file"]:- module_directory = config["input_file"].stem+ module_name = config.get_dir("input_file").stemelse:- module_directory = ""+ module_name = ""if config["output_file"]:- default_name = config["output_file"]+ default_name = config.get_dir("output_file")else:default_name = Path(scene_name)if config["save_last_frame"] or config["save_pngs"]:- if config["media_dir"] != "":- if not config["custom_folders"]:- image_dir = guarantee_existence(- os.path.join(- config["images_dir"],- module_directory,- )- )- else:- image_dir = guarantee_existence(config["images_dir"])+ if config["media_dir"]:+ image_dir = guarantee_existence(+ config.get_dir("images_dir", module_name=module_name)+ )self.image_file_path = os.path.join(image_dir, add_extension_if_not_present(default_name, ".png"))if config["write_to_movie"]:- if config["video_dir"]:- if not config["custom_folders"]:- movie_dir = guarantee_existence(- os.path.join(- config["video_dir"],- module_directory,- self.get_resolution_directory(),- )- )- else:- movie_dir = guarantee_existence(os.path.join(config["video_dir"]))+ movie_dir = guarantee_existence(+ config.get_dir("video_dir", module_name=module_name)+ )self.movie_file_path = os.path.join(movie_dir,@@ -115,6 +101,7 @@ class SceneFileWriter(object):movie_dir,add_extension_if_not_present(default_name, GIF_FILE_EXTENSION),)+if not config["custom_folders"]:self.partial_movie_directory = guarantee_existence(os.path.join(@@ -126,7 +113,7 @@ class SceneFileWriter(object):else:self.partial_movie_directory = guarantee_existence(os.path.join(- config["media_dir"],+ config.get_dir("media_dir"),"temp_files","partial_movie_files",default_name,diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.pyindex 71b080c95..de98d70e3 100644--- a/manim/utils/tex_file_writing.py+++ b/manim/utils/tex_file_writing.py@@ -72,7 +72,7 @@ def generate_tex_file(expression, environment=None, tex_template=None):else:output = tex_template.get_texcode_for_expression(expression)- tex_dir = config["tex_dir"]+ tex_dir = config.get_dir("tex_dir")if not os.path.exists(tex_dir):os.makedirs(tex_dir)@@ -156,7 +156,7 @@ def compile_tex(tex_file, tex_compiler, output_format):result = tex_file.replace(".tex", output_format)result = Path(result).as_posix()tex_file = Path(tex_file).as_posix()- tex_dir = Path(config["tex_dir"]).as_posix()+ tex_dir = Path(config.get_dir("tex_dir")).as_posix()if not os.path.exists(result):command = tex_compilation_command(tex_compiler, output_format, tex_file, tex_dirdiff --git a/tests/test_config.py b/tests/test_config.pyindex adeda7f24..f18880d09 100644--- a/tests/test_config.py+++ b/tests/test_config.py@@ -65,9 +65,6 @@ def test_background_color():def test_digest_file(tmp_path):"""Test that a config file can be digested programatically."""- assert config["media_dir"] == Path("media")- assert config["video_dir"] == Path("media/videos")-with tempconfig({}):tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)tmp_cfg.write(@@ -80,11 +77,8 @@ def test_digest_file(tmp_path):tmp_cfg.close()config.digest_file(tmp_cfg.name)- assert config["media_dir"] == Path("this_is_my_favorite_path")- assert config["video_dir"] == Path("this_is_my_favorite_path/videos")-- assert config["media_dir"] == Path("media")- assert config["video_dir"] == Path("media/videos")+ assert config.get_dir("media_dir") == Path("this_is_my_favorite_path")+ assert config.get_dir("video_dir") == Path("this_is_my_favorite_path/videos")def test_temporary_dry_run():diff --git a/tests/test_scene_rendering/test_cli_flags.py b/tests/test_scene_rendering/test_cli_flags.pyindex 934445f13..a989596fd 100644--- a/tests/test_scene_rendering/test_cli_flags.py+++ b/tests/test_scene_rendering/test_cli_flags.py@@ -80,10 +80,8 @@ def test_s_flag_no_animations(tmp_path, manim_cfg_file, simple_scenes_path):out, err, exit_code = capture(command)assert exit_code == 0, err- print(list((tmp_path / "images" / "simple_scenes").iterdir()))-- is_empty = not any((tmp_path / "videos").iterdir())- assert is_empty, "running manim with -s flag rendered a video"+ exists = (tmp_path / "videos").exists()+ assert not exists, "running manim with -s flag rendered a video"is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir())assert not is_empty, "running manim with -s flag did not render an image"@@ -105,8 +103,8 @@ def test_s_flag(tmp_path, manim_cfg_file, simple_scenes_path):out, err, exit_code = capture(command)assert exit_code == 0, err- is_empty = not any((tmp_path / "videos").iterdir())- assert is_empty, "running manim with -s flag rendered a video"+ exists = (tmp_path / "videos").exists()+ assert not exists, "running manim with -s flag rendered a video"is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir())assert not is_empty, "running manim with -s flag did not render an image"