Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

change every mention of file_writer_config to config. Also some tweaks to ManimConfig

leotrs6e0ba47a1e8b
diff --git a/manim/__main__.py b/manim/__main__.py
index 6db788c9e..bded3c61d 100644
--- a/manim/__main__.py
+++ b/manim/__main__.py
@@ -8,7 +8,7 @@ import traceback
import importlib.util
import types
-from manim import constants, logger, console, config, file_writer_config
+from manim import constants, logger, console, config
from manim import Scene
from manim.utils.module_ops import (
get_module,
@@ -17,38 +17,35 @@ from manim.utils.module_ops import (
)
from manim.utils.file_ops import open_file as open_media_file
from manim.grpc.impl import frame_server_impl
+from manim.config.utils import init_dirs
from manim.config.main_utils import *
def open_file_if_needed(file_writer):
- if file_writer_config["verbosity"] != "DEBUG":
+ if config["verbosity"] != "DEBUG":
curr_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
- open_file = any(
- [file_writer_config["preview"], file_writer_config["show_in_file_browser"]]
- )
+ open_file = any([config["preview"], config["show_in_file_browser"]])
+
if open_file:
current_os = platform.system()
file_paths = []
- if file_writer_config["save_last_frame"]:
+ if config["save_last_frame"]:
file_paths.append(file_writer.get_image_file_path())
- if (
- file_writer_config["write_to_movie"]
- and not file_writer_config["save_as_gif"]
- ):
+ if config["write_to_movie"] and not config["save_as_gif"]:
file_paths.append(file_writer.get_movie_file_path())
- if file_writer_config["save_as_gif"]:
+ if config["save_as_gif"]:
file_paths.append(file_writer.gif_file_path)
for file_path in file_paths:
- if file_writer_config["show_in_file_browser"]:
+ if config["show_in_file_browser"]:
open_media_file(file_path, True)
- if file_writer_config["preview"]:
+ if config["preview"]:
open_media_file(file_path, False)
- if file_writer_config["verbosity"] != "DEBUG":
+ if config["verbosity"] != "DEBUG":
sys.stdout.close()
sys.stdout = curr_stdout
@@ -74,13 +71,13 @@ def main():
# something_else_here()
else:
- update_config_with_cli(args)
- init_dirs(file_writer_config)
+ config.digest_args(args)
+ init_dirs(config)
if file_writer_config["log_to_file"]:
set_file_logger()
- module = get_module(file_writer_config["input_file"])
+ module = get_module(config["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/camera/camera.py b/manim/camera/camera.py
index ef2aa55ea..c4fa3c00d 100644
--- a/manim/camera/camera.py
+++ b/manim/camera/camera.py
@@ -14,7 +14,7 @@ from scipy.spatial.distance import pdist
import cairo
import numpy as np
-from .. import logger, config, camera_config
+from .. import logger, config
from ..constants import *
from ..mobject.types.image_mobject import AbstractImageMobject
from ..mobject.mobject import Mobject
@@ -1063,9 +1063,7 @@ class Camera(object):
"""
# TODO: This seems...unsystematic
- big_sum = op.add(
- camera_config["default_pixel_height"], camera_config["default_pixel_width"]
- )
+ big_sum = op.add(config["default_pixel_height"], config["default_pixel_width"])
this_sum = op.add(self.pixel_height, self.pixel_width)
factor = fdiv(big_sum, this_sum)
return 1 + (thickness - 1) / factor
diff --git a/manim/config/__init__.py b/manim/config/__init__.py
index 3a9317ffa..491b14a89 100644
--- a/manim/config/__init__.py
+++ b/manim/config/__init__.py
@@ -2,14 +2,13 @@ import logging
from contextlib import contextmanager
from .logger import make_logger
-from .utils import make_config_parser, make_config, make_file_writer_config
+from .utils import make_config_parser, ManimConfig, ManimFrame
__all__ = [
"logger",
"console",
"config",
- "file_writer_config",
- "camera_config",
+ "frame",
"tempconfig",
]
@@ -23,9 +22,8 @@ logger, console = make_logger(parser["logger"], parser["CLI"]["verbosity"])
logging.getLogger("PIL").setLevel(logging.INFO)
logging.getLogger("matplotlib").setLevel(logging.INFO)
-config = make_config(parser)
-camera_config = config
-file_writer_config = make_file_writer_config(parser, config)
+config = ManimConfig(parser)
+frame = ManimFrame(config)
# This has to go here because it needs access to this module's config
diff --git a/manim/config/default.cfg b/manim/config/default.cfg
index cc4d7be3a..e911db5d8 100644
--- a/manim/config/default.cfg
+++ b/manim/config/default.cfg
@@ -73,16 +73,13 @@ upto_animation_number = -1
media_dir = ./media
# --log_dir (by default "/logs", that will be put inside the media dir)
-log_dir = logs
+log_dir = {media_dir}/logs
-# # --video_dir
-# video_dir = %(MEDIA_DIR)s/videos
-
-# # --tex_dir
-# tex_dir = %(MEDIA_DIR)s/Tex
-
-# # --text_dir
-# text_dir = %(MEDIA_DIR)s/texts
+# the following do not have CLI arguments but depend on media_dir
+video_dir = {media_dir}/videos
+tex_dir = {media_dir}/Tex
+text_dir = {media_dir}/texts
+images_dir = {media_dir}/images
# --use_js_renderer
use_js_renderer = False
@@ -193,5 +190,6 @@ log_height = -1
log_timestamps = True
[ffmpeg]
-# Uncomment the following line to manually set the loglevel for ffmpeg. See ffmpeg manpage for accepted values
-# loglevel = error
+# Uncomment the following line to manually set the loglevel for ffmpeg. See
+# ffmpeg manpage for accepted values
+loglevel = ERROR
diff --git a/manim/config/logger.py b/manim/config/logger.py
index 9d207fb40..d93228f4a 100644
--- a/manim/config/logger.py
+++ b/manim/config/logger.py
@@ -6,6 +6,7 @@ Functions to create and set the logger.
"""
+import os
import logging
import json
import copy
diff --git a/manim/config/main_utils.py b/manim/config/main_utils.py
index ac3908c63..c91b9ea03 100644
--- a/manim/config/main_utils.py
+++ b/manim/config/main_utils.py
@@ -13,7 +13,7 @@ import logging
import colour
-from manim import constants, logger, config, file_writer_config
+from manim import constants, logger, config
from .utils import make_config_parser
from .logger import JSONFormatter
from ..utils.tex import TexTemplate, TexTemplateFromFile
diff --git a/manim/config/utils.py b/manim/config/utils.py
index e85284e50..4fb4c6fce 100644
--- a/manim/config/utils.py
+++ b/manim/config/utils.py
@@ -6,7 +6,10 @@ Functions to create and set the config.
"""
+import os
import sys
+import copy
+import logging
import configparser
from pathlib import Path
from collections.abc import Mapping, MutableMapping
@@ -42,138 +45,40 @@ def make_config_parser():
return parser
-def make_config(parser):
- """Parse config files into a single dictionary exposed to the user."""
- # By default, use the CLI section of the digested .cfg files
- default = parser["CLI"]
-
- # Loop over [low_quality] for the keys, but get the values from [CLI]
- config = {opt: default.getint(opt) for opt in parser["low_quality"]}
-
- # Set the rest of the frame properties
- config["default_pixel_height"] = default.getint("pixel_height")
- config["default_pixel_width"] = default.getint("pixel_width")
- config["background_color"] = colour.Color(default["background_color"])
- config["frame_height"] = 8.0
- config["frame_width"] = (
- config["frame_height"] * config["pixel_width"] / config["pixel_height"]
- )
- config["frame_y_radius"] = config["frame_height"] / 2
- config["frame_x_radius"] = config["frame_width"] / 2
- config["top"] = config["frame_y_radius"] * constants.UP
- config["bottom"] = config["frame_y_radius"] * constants.DOWN
- config["left_side"] = config["frame_x_radius"] * constants.LEFT
- config["right_side"] = config["frame_x_radius"] * constants.RIGHT
-
- # Tex template
- tex_fn = None if not default["tex_template"] else default["tex_template"]
- if tex_fn is not None and not os.access(tex_fn, os.R_OK):
- # custom template not available, fallback to default
- logging.getLogger("manim").warning(
- f"Custom TeX template {tex_fn} not found or not readable. "
- "Falling back to the default template."
- )
- tex_fn = None
- config["tex_template_file"] = tex_fn
- config["tex_template"] = (
- TexTemplate() if not tex_fn else TexTemplateFromFile(filename=tex_fn)
- )
-
- # Choose the renderer
- config["use_js_renderer"] = default.getboolean("use_js_renderer")
- config["js_renderer_path"] = default.get("js_renderer_path")
-
- return config
-
-
-def make_file_writer_config(parser, config):
- """Parse config files into a single dictionary used internally."""
- # By default, use the CLI section of the digested .cfg files
- default = parser["CLI"]
-
- # This will be the final file_writer_config dict exposed to the user
- fw_config = {}
-
- # These may be overriden by CLI arguments
- fw_config["input_file"] = ""
- fw_config["scene_names"] = ""
- fw_config["output_file"] = ""
- fw_config["custom_folders"] = False
-
- # Note ConfigParser options are all strings and each needs to be converted
- # to the appropriate type.
- for boolean_opt in [
- "preview",
- "show_in_file_browser",
- "leave_progress_bars",
- "write_to_movie",
- "save_last_frame",
- "save_pngs",
- "save_as_gif",
- "write_all",
- "disable_caching",
- "flush_cache",
- "log_to_file",
- "progress_bar",
- ]:
- fw_config[boolean_opt] = default.getboolean(boolean_opt)
-
- for str_opt in [
- "png_mode",
- "movie_file_extension",
- "background_opacity",
- ]:
- fw_config[str_opt] = default.get(str_opt)
-
- for int_opt in [
- "from_animation_number",
- "upto_animation_number",
- ]:
- fw_config[int_opt] = default.getint(int_opt)
- if fw_config["upto_animation_number"] == -1:
- fw_config["upto_animation_number"] = float("inf")
-
- # for str_opt in ['media_dir', 'video_dir', 'tex_dir', 'text_dir']:
- for str_opt in ["media_dir", "log_dir"]:
- fw_config[str_opt] = Path(default[str_opt]).relative_to(".")
- dir_names = {
- "video_dir": "videos",
- "images_dir": "images",
- "tex_dir": "Tex",
- "text_dir": "texts",
+def determine_quality(args):
+ old_qualities = {
+ "k": "fourk_quality",
+ "e": "high_quality",
+ "m": "medium_quality",
+ "l": "low_quality",
}
- for name in dir_names:
- fw_config[name] = fw_config["media_dir"] / dir_names[name]
-
- if not fw_config["write_to_movie"]:
- fw_config["disable_caching"] = True
- if config["use_js_renderer"]:
- file_writer_config["disable_caching"] = True
+ for quality in constants.QUALITIES:
+ if quality == constants.DEFAULT_QUALITY:
+ # Skip so we prioritize anything that overwrites the default quality.
+ pass
+ elif getattr(args, quality, None) or (
+ hasattr(args, "quality") and args.quality == constants.QUALITIES[quality]
+ ):
+ return quality
- # Read in the streaming section -- all values are strings
- fw_config["streaming"] = {
- opt: parser["streaming"].get(opt) for opt in parser["streaming"]
- }
+ for quality in old_qualities:
+ if getattr(args, quality, None):
+ logging.getLogger('manim').warning(
+ f"Option -{quality} is deprecated please use the --quality/-q flag."
+ )
+ return old_qualities[quality]
- # For internal use (no CLI flag)
- fw_config["skip_animations"] = fw_config["save_last_frame"]
- fw_config["max_files_cached"] = default.getint("max_files_cached")
- if fw_config["max_files_cached"] == -1:
- fw_config["max_files_cached"] = float("inf")
+ return constants.DEFAULT_QUALITY
- # Parse the verbosity flag to read in the log level
- fw_config["verbosity"] = default["verbosity"]
-
- # Parse the ffmpeg log level in the config
- ffmpeg_loglevel = parser["ffmpeg"].get("loglevel", None)
- fw_config["ffmpeg_loglevel"] = (
- constants.FFMPEG_VERBOSITY_MAP[fw_config["verbosity"]]
- if ffmpeg_loglevel is None
- else ffmpeg_loglevel
- )
- return fw_config
+_QUAL = {
+ 'low_quality': {'pixel_height': 480, 'pixel_width': 854, 'frame_rate': 15},
+ 'medium_quality': {'pixel_height': 720, 'pixel_width': 1280, 'frame_rate': 30},
+ 'high_quality': {'pixel_height': 1080, 'pixel_width': 1920, 'frame_rate': 60},
+ 'production_quality': {'pixel_height': 1440, 'pixel_width': 2560, 'frame_rate': 60},
+ '4k_quality': {'pixel_height': 2160, 'pixel_width': 3840, 'frame_rate': 60},
+}
class ManimConfig(MutableMapping):
@@ -193,6 +98,7 @@ class ManimConfig(MutableMapping):
'from_animation_number',
'images_dir',
'input_file',
+ 'js_renderer_path',
'leave_progress_bars',
'log_dir',
'log_to_file',
@@ -215,6 +121,7 @@ class ManimConfig(MutableMapping):
'tex_template_file',
'text_dir',
'upto_animation_number',
+ 'use_js_renderer',
'verbosity',
'video_dir',
'write_all',
@@ -233,18 +140,25 @@ class ManimConfig(MutableMapping):
def __len__(self):
return len(self._d)
+ def __contains__(self, key):
+ try:
+ self.__getitem__(key)
+ return True
+ except AttributeError:
+ return False
+
def __getitem__(self, key):
return getattr(self, key)
def __setitem__(self, key, val):
- getattr(ManimConfigDict, key).fset(self, val) # fset is the property's setter
+ getattr(ManimConfig, key).fset(self, val) # fset is the property's setter
# don't allow to delete anything
def __delitem__(self, key):
- raise AttributeError("'ManimConfigDict' object does not support item deletion")
+ raise AttributeError("'ManimConfig' object does not support item deletion")
def __delattr__(self, key):
- raise AttributeError("'ManimConfigDict' object does not support item deletion")
+ raise AttributeError("'ManimConfig' object does not support item deletion")
# helper type-checking methods
def _set_from_list(self, key, val, values):
@@ -283,6 +197,7 @@ class ManimConfig(MutableMapping):
# builders
def digest_parser(self, parser):
+ # boolean keys
for key in [
'write_to_movie',
'save_last_frame',
@@ -299,9 +214,11 @@ class ManimConfig(MutableMapping):
'flush_cache',
'custom_folders',
'skip_animations',
+ 'use_js_renderer',
]:
setattr(self, key, parser['CLI'].getboolean(key, fallback=False))
+ # int keys
for key in [
'from_animation_number',
'upto_animation_number',
@@ -312,6 +229,7 @@ class ManimConfig(MutableMapping):
]:
setattr(self, key, parser['CLI'].getint(key))
+ # str keys
for key in [
'verbosity',
'media_dir',
@@ -325,16 +243,20 @@ class ManimConfig(MutableMapping):
'png_mode',
'movie_file_extension',
'background_color',
+ 'js_renderer_path',
]:
setattr(self, key, parser['CLI'].get(key, fallback='', raw=True))
- for key in [
- 'background_opacity',
- 'frame_height',
- 'frame_width',
- ]:
+ # float keys
+ for key in ['background_opacity']:
setattr(self, key, parser['CLI'].getfloat(key))
+ # other logic
+ self["frame_height"] = 8.0
+ self["frame_width"] = (
+ self["frame_height"] * self["pixel_width"] / self["pixel_height"]
+ )
+
val = parser['CLI'].get('tex_template_file')
if val:
setattr(self, 'tex_template_file', val)
@@ -364,23 +286,33 @@ class ManimConfig(MutableMapping):
"write_all",
"disable_caching",
"flush_cache",
- "log_to_file",
"transparent",
- "dry_run",
- "media_dir",
"scene_names",
+ "verbosity",
+ "dry_run", # always set this one last
+ ]:
+ if hasattr(args, key):
+ attr = getattr(args, key)
+ # if attr is None, then no argument was passed and we should
+ # not change the current config
+ if attr is not None:
+ self[key] = attr
+
+ for key in [
+ "media_dir", # always set this one first
+ "dry_run",
"video_dir",
"images_dir",
"tex_dir",
"text_dir",
"log_dir",
"custom_folders",
- "verbosity",
+ "log_to_file", # always set this one last
]:
if hasattr(args, key):
attr = getattr(args, key)
- # if attr is None, then no argument was passed and we should not
- # change the current config
+ # if attr is None, then no argument was passed and we should
+ # not change the current config
if attr is not None:
self[key] = attr
@@ -398,6 +330,9 @@ class ManimConfig(MutableMapping):
else:
self.from_animation_number = int(nflag)
+ # Handle the quality flags
+ self.quality = determine_quality(args)
+
# Handle the -r flag.
rflag = args.resolution
if rflag is not None:
@@ -456,11 +391,18 @@ class ManimConfig(MutableMapping):
doc='Whether to leave the progress bar for each animations'
)
- log_to_file = property(
- lambda self: self._d['log_to_file'],
- lambda self, val: self._set_boolean('log_to_file', val),
- doc='Whether to save logs to a file'
- )
+ @property
+ def log_to_file(self):
+ """Whether to save logs to a file"""
+ return self._d['log_to_file']
+
+ @log_to_file.setter
+ def log_to_file(self, val):
+ self._set_boolean('log_to_file', val)
+ if val:
+ if not os.path.exists(self['log_dir']):
+ os.makedirs(self['log_dir'])
+ set_file_logger(self, self['verbosity'])
sound = property(
lambda self: self._d['sound'],
@@ -488,7 +430,7 @@ class ManimConfig(MutableMapping):
save_pngs = property(
lambda self: self._d['save_pngs'],
- lambda self, val: (print(f'setting to {val}'), self._set_boolean('save_pngs', val)),
+ lambda self, val: self._set_boolean('save_pngs', val),
doc='Whether to save all frames in the scene as images files'
)
@@ -498,13 +440,19 @@ class ManimConfig(MutableMapping):
doc='Whether to save the rendered scene in .gif format.'
)
- verbosity = property(
- lambda self: self._d['verbosity'],
- lambda self, val: self._set_from_list(
- 'verbosity', val, ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
- ),
- doc='Verbosity level of the logger.'
- )
+ @property
+ def verbosity(self):
+ return self._d['verbosity']
+
+ @verbosity.setter
+ def verbosity(self, val):
+ """Verbosity level of the logger."""
+ self._set_from_list(
+ 'verbosity',
+ val,
+ ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
+ )
+ logging.getLogger('manim').setLevel(val)
ffmpeg_loglevel = property(
lambda self: self._d['ffmpeg_loglevel'],
@@ -660,7 +608,7 @@ class ManimConfig(MutableMapping):
@property
def quality(self):
- f"""Video quality ({list(_QUAL.keys())})"""
+ """Video quality."""
q = {
'pixel_width': self.pixel_width,
'pixel_height': self.pixel_height,
@@ -675,8 +623,8 @@ class ManimConfig(MutableMapping):
@quality.setter
def quality(self, qual):
if qual not in _QUAL:
- raise KeyError(f'quality must be one of {list(self._qual.keys())}')
- self.frame_size = _QUAL[qual]['width'], _QUAL[qual]['height']
+ raise KeyError(f'quality must be one of {list(_QUAL.keys())}')
+ self.frame_size = _QUAL[qual]['pixel_width'], _QUAL[qual]['pixel_height']
self.frame_rate = _QUAL[qual]['frame_rate']
@property
@@ -699,11 +647,11 @@ class ManimConfig(MutableMapping):
def dry_run(self):
"""Whether dry run is enabled."""
return (
- self.write_to_movie == False
- and self.write_all == False
- and self.save_last_frame == False
- and self.save_pngs == False
- and self.save_as_gif == False
+ self.write_to_movie is False
+ and self.write_all is False
+ and self.save_last_frame is False
+ and self.save_pngs is False
+ and self.save_as_gif is False
)
@dry_run.setter
@@ -724,10 +672,26 @@ class ManimConfig(MutableMapping):
else:
raise ValueError(f'dry_run must be boolean')
+ @property
+ def use_js_renderer(self):
+ self._d['use_js_renderer']
+
+ @use_js_renderer.setter
+ def use_js_renderer(self, val):
+ self._d['use_js_renderer'] = val
+ if val:
+ self["disable_caching"] = True
+
+ js_renderer_path = property(
+ lambda self: self._d['js_renderer_path'],
+ lambda self, val: self._d.__setitem__('js_renderer_path', Path(val)),
+ doc='Path to JS renderer.'
+ )
+
media_dir = property(
lambda self: self._d['media_dir'],
lambda self, val: self._d.__setitem__('media_dir', Path(val)),
- doc='Main output directory, relative to execcution directory.'
+ doc='Main output directory, relative to execution directory.'
)
def _get_dir(self, key):
@@ -822,7 +786,7 @@ class ManimConfig(MutableMapping):
def tex_template_file(self, val):
if val:
if not os.access(val, os.R_OK):
- logging.getLogger("rich").warning(f"Custom TeX template {val} not found or not readable.")
+ logging.getLogger("manim").warning(f"Custom TeX template {val} not found or not readable.")
else:
self._d["tex_template_file"] = Path(val)
self._tex_template = TexTemplateFromFile(filename=val)
@@ -865,8 +829,8 @@ class ManimFrame(Mapping):
}
def __init__(self, c):
- if not isinstance(c, ManimConfigDict):
- raise TypeError("argument must be instance of 'ManimConfigDict'")
+ if not isinstance(c, ManimConfig):
+ raise TypeError("argument must be instance of 'ManimConfig'")
# need to use __dict__ directly because setting attributes is not
# allowed (see __setattr__)
self.__dict__['_c'] = c
diff --git a/manim/constants.py b/manim/constants.py
index 2f13f226e..2d1a9b34c 100644
--- a/manim/constants.py
+++ b/manim/constants.py
@@ -148,5 +148,5 @@ QUALITIES = {
"low_quality": "l",
}
-DEFAULT_QUALITY = "production_quality"
+DEFAULT_QUALITY = "high_quality"
DEFAULT_QUALITY_SHORT = QUALITIES[DEFAULT_QUALITY]
diff --git a/manim/grpc/impl/frame_server_impl.py b/manim/grpc/impl/frame_server_impl.py
index 7f16121fa..d87f2cd95 100644
--- a/manim/grpc/impl/frame_server_impl.py
+++ b/manim/grpc/impl/frame_server_impl.py
@@ -1,5 +1,4 @@
-from ...config import camera_config
-from ...config import file_writer_config
+from ...config import config
from ...scene import scene
from ..gen import frameserver_pb2
from ..gen import frameserver_pb2_grpc
@@ -53,7 +52,7 @@ class FrameServer(frameserver_pb2_grpc.FrameServerServicer):
except grpc._channel._InactiveRpcError:
logger.warning(f"No frontend was detected at localhost:50052.")
try:
- sp.Popen(camera_config["js_renderer_path"])
+ sp.Popen(config["js_renderer_path"])
except PermissionError:
logger.info(JS_RENDERER_INFO)
self.server.stop(None)
@@ -194,7 +193,7 @@ class UpdateFrontendHandler(FileSystemEventHandler):
def on_modified(self, event):
super().on_modified(event)
- module = get_module(file_writer_config["input_file"])
+ module = get_module(config["input_file"])
all_scene_classes = get_scene_classes_from_module(module)
scene_classes_to_render = get_scenes_to_render(all_scene_classes)
scene_class = scene_classes_to_render[0]
@@ -250,7 +249,7 @@ class UpdateFrontendHandler(FileSystemEventHandler):
try:
stub.ManimStatus(request)
except grpc._channel._InactiveRpcError:
- sp.Popen(camera_config["js_renderer_path"])
+ sp.Popen(config["js_renderer_path"])
def get(scene_class):
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 16227bc0d..66fdead7c 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -15,7 +15,7 @@ import sys
from colour import Color
import numpy as np
-from .. import config, file_writer_config
+from .. import config
from ..constants import *
from ..container import Container
from ..utils.color import color_gradient, WHITE, BLACK, YELLOW_C
@@ -199,7 +199,7 @@ class Mobject(Container):
def save_image(self, name=None):
self.get_image().save(
- os.path.join(file_writer_config["video_dir"], (name or str(self)) + ".png")
+ os.path.join(config["video_dir"], (name or str(self)) + ".png")
)
def copy(self):
diff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.py
index da5fd26f5..60a3d1034 100644
--- a/manim/mobject/svg/text_mobject.py
+++ b/manim/mobject/svg/text_mobject.py
@@ -13,7 +13,7 @@ import cairocffi
import pangocairocffi
import pangocffi
-from ... import config, file_writer_config, logger
+from ... import config, logger
from ...constants import *
from ...container import Container
from ...mobject.geometry import Dot, Rectangle
@@ -301,7 +301,7 @@ class CairoText(SVGMobject):
if self.font == "":
if NOT_SETTING_FONT_MSG != "":
print(NOT_SETTING_FONT_MSG)
- dir_name = file_writer_config["text_dir"]
+ dir_name = config["text_dir"]
hash_name = self.text2hash()
file_name = os.path.join(dir_name, hash_name) + ".svg"
if os.path.exists(file_name):
@@ -875,7 +875,7 @@ class PangoText(SVGMobject):
"""
size = self.size * 10
line_spacing = self.line_spacing * 10
- dir_name = file_writer_config["text_dir"]
+ dir_name = config["text_dir"]
if not os.path.exists(dir_name):
os.makedirs(dir_name)
hash_name = self.text2hash()
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index 075db885f..291ff77a8 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -13,7 +13,7 @@ import copy
from tqdm import tqdm as ProgressDisplay
import numpy as np
-from .. import camera_config, file_writer_config, logger
+from .. import config, logger
from ..animation.animation import Animation
from ..animation.transform import MoveToTarget, ApplyMethod
from ..camera.camera import Camera
@@ -47,11 +47,11 @@ def handle_play_like_call(func):
"""
def wrapper(self, *args, **kwargs):
- allow_write = not file_writer_config["skip_animations"]
- if not self.camera.use_js_renderer:
+ allow_write = not config["skip_animations"]
+ if not config.use_js_renderer:
self.file_writer.begin_animation(allow_write)
func(self, *args, **kwargs)
- if not self.camera.use_js_renderer:
+ if not config.use_js_renderer:
self.file_writer.end_animation(allow_write)
self.num_plays += 1
@@ -97,21 +97,18 @@ class Scene(Container):
def __init__(self, **kwargs):
Container.__init__(self, **kwargs)
- self.camera = self.camera_class(**camera_config)
- if not self.camera.use_js_renderer:
- self.file_writer = SceneFileWriter(
- self,
- **file_writer_config,
- )
+ self.camera = self.camera_class()
+ if not config.use_js_renderer:
+ self.file_writer = SceneFileWriter(self)
self.animations_hashes = []
self.mobjects = []
- self.original_skipping_status = file_writer_config["skip_animations"]
+ self.original_skipping_status = config["skip_animations"]
# TODO, remove need for foreground mobjects
self.foreground_mobjects = []
self.num_plays = 0
self.time = 0
- self.original_skipping_status = file_writer_config["skip_animations"]
+ self.original_skipping_status = config["skip_animations"]
if self.random_seed is not None:
random.seed(self.random_seed)
np.random.seed(self.random_seed)
@@ -129,7 +126,7 @@ class Scene(Container):
self.tear_down()
# We have to reset these settings in case of multiple renders.
- file_writer_config["skip_animations"] = False
+ config["skip_animations"] = False
self.file_writer.finish()
self.print_end_message()
@@ -237,7 +234,7 @@ class Scene(Container):
**kwargs
"""
- if file_writer_config["skip_animations"] and not ignore_skipping:
+ if config["skip_animations"] and not ignore_skipping:
return
if mobjects is None:
mobjects = list_update(
@@ -673,7 +670,7 @@ class Scene(Container):
ProgressDisplay
The CommandLine Progress Bar.
"""
- if file_writer_config["skip_animations"] and not override_skip_animations:
+ if config["skip_animations"] and not override_skip_animations:
times = [run_time]
else:
step = 1 / self.camera.frame_rate
@@ -681,9 +678,9 @@ class Scene(Container):
time_progression = ProgressDisplay(
times,
total=n_iterations,
- leave=file_writer_config["leave_progress_bars"],
+ leave=config["leave_progress_bars"],
ascii=True if platform.system() == "Windows" else None,
- disable=not file_writer_config["progress_bar"],
+ disable=not config["progress_bar"],
)
return time_progression
@@ -824,12 +821,12 @@ class Scene(Container):
the number of animations that need to be played, and
raises an EndSceneEarlyException if they don't correspond.
"""
- if file_writer_config["from_animation_number"]:
- if self.num_plays < file_writer_config["from_animation_number"]:
- file_writer_config["skip_animations"] = True
- if file_writer_config["upto_animation_number"]:
- if self.num_plays > file_writer_config["upto_animation_number"]:
- file_writer_config["skip_animations"] = True
+ if config["from_animation_number"]:
+ if self.num_plays < config["from_animation_number"]:
+ config["skip_animations"] = True
+ if config["upto_animation_number"]:
+ if self.num_plays > config["upto_animation_number"]:
+ config["skip_animations"] = True
raise EndSceneEarlyException()
def handle_caching_play(func):
@@ -849,7 +846,7 @@ class Scene(Container):
self.update_skipping_status()
animations = self.compile_play_args_to_animation_list(*args, **kwargs)
self.add_mobjects_from_animations(animations)
- if file_writer_config["skip_animations"]:
+ if config["skip_animations"]:
logger.debug(f"Skipping animation {self.num_plays}")
func(self, *args, **kwargs)
# If the animation is skipped, we mark its hash as None.
@@ -857,7 +854,7 @@ class Scene(Container):
self.animations_hashes.append(None)
self.file_writer.add_partial_movie_file(None)
return
- if not file_writer_config["disable_caching"]:
+ if not config["disable_caching"]:
mobjects_on_scene = self.get_mobjects()
hash_play = get_hash_from_play_call(
self, self.camera, animations, mobjects_on_scene
@@ -867,7 +864,7 @@ class Scene(Container):
f"Animation {self.num_plays} : Using cached data (hash : %(hash_play)s)",
{"hash_play": hash_play},
)
- file_writer_config["skip_animations"] = True
+ config["skip_animations"] = True
else:
hash_play = "uncached_{:05}".format(self.num_plays)
self.animations_hashes.append(hash_play)
@@ -895,7 +892,7 @@ class Scene(Container):
def wrapper(self, duration=DEFAULT_WAIT_TIME, stop_condition=None):
self.revert_to_original_skipping_status()
self.update_skipping_status()
- if file_writer_config["skip_animations"]:
+ if config["skip_animations"]:
logger.debug(f"Skipping wait {self.num_plays}")
func(self, duration, stop_condition)
# If the animation is skipped, we mark its hash as None.
@@ -903,7 +900,7 @@ class Scene(Container):
self.animations_hashes.append(None)
self.file_writer.add_partial_movie_file(None)
return
- if not file_writer_config["disable_caching"]:
+ if not config["disable_caching"]:
hash_wait = get_hash_from_wait_call(
self, self.camera, duration, stop_condition, self.get_mobjects()
)
@@ -911,7 +908,7 @@ class Scene(Container):
logger.info(
f"Wait {self.num_plays} : Using cached data (hash : {hash_wait})"
)
- file_writer_config["skip_animations"] = True
+ config["skip_animations"] = True
else:
hash_wait = "uncached_{:05}".format(self.num_plays)
self.animations_hashes.append(hash_wait)
@@ -982,7 +979,7 @@ class Scene(Container):
animation.finish()
animation.clean_up_from_scene(self)
self.mobjects_from_last_animation = [anim.mobject for anim in animations]
- if file_writer_config["skip_animations"]:
+ if config["skip_animations"]:
# TODO, run this call in for each animation?
self.update_mobjects(self.get_run_time(animations))
else:
@@ -1163,8 +1160,8 @@ class Scene(Container):
Scene
The Scene, with skipping turned on.
"""
- self.original_skipping_status = file_writer_config["skip_animations"]
- file_writer_config["skip_animations"] = True
+ self.original_skipping_status = config["skip_animations"]
+ config["skip_animations"] = True
return self
def revert_to_original_skipping_status(self):
@@ -1179,7 +1176,7 @@ class Scene(Container):
The Scene, with the original skipping status.
"""
if hasattr(self, "original_skipping_status"):
- file_writer_config["skip_animations"] = self.original_skipping_status
+ config["skip_animations"] = self.original_skipping_status
return self
def add_frame(self, frame, num_frames=1):
@@ -1195,7 +1192,7 @@ class Scene(Container):
"""
dt = 1 / self.camera.frame_rate
self.increment_time(num_frames * dt)
- if file_writer_config["skip_animations"]:
+ if config["skip_animations"]:
return
for _ in range(num_frames):
self.file_writer.write_frame(frame)
@@ -1216,7 +1213,7 @@ class Scene(Container):
gain :
"""
- if file_writer_config["skip_animations"]:
+ if config["skip_animations"]:
return
time = self.time + time_offset
self.file_writer.add_sound(sound_file, time, gain, **kwargs)
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.py
index adb1713d1..651bedb4c 100644
--- a/manim/scene/scene_file_writer.py
+++ b/manim/scene/scene_file_writer.py
@@ -13,7 +13,7 @@ from time import sleep
import datetime
from PIL import Image
-from .. import file_writer_config, logger, console
+from .. import config, logger, console
from ..constants import FFMPEG_BIN, GIF_FILE_EXTENSION
from ..utils.config_ops import digest_config
from ..utils.file_ops import guarantee_existence
@@ -60,45 +60,46 @@ class SceneFileWriter(object):
"""
module_directory = self.get_default_module_directory()
scene_name = self.get_default_scene_name()
- if file_writer_config["save_last_frame"] or file_writer_config["save_pngs"]:
- if file_writer_config["media_dir"] != "":
- if not file_writer_config["custom_folders"]:
+ 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(
- file_writer_config["images_dir"],
+ config["images_dir"],
module_directory,
)
)
else:
- image_dir = guarantee_existence(file_writer_config["images_dir"])
+ image_dir = guarantee_existence(config["images_dir"])
self.image_file_path = os.path.join(
image_dir, add_extension_if_not_present(scene_name, ".png")
)
- if file_writer_config["write_to_movie"]:
- if file_writer_config["video_dir"]:
- if not file_writer_config["custom_folders"]:
+ if config["write_to_movie"]:
+ if config["video_dir"]:
+ if not config["custom_folders"]:
movie_dir = guarantee_existence(
os.path.join(
- file_writer_config["video_dir"],
+ config["video_dir"],
module_directory,
self.get_resolution_directory(),
)
)
else:
movie_dir = guarantee_existence(
- os.path.join(file_writer_config["video_dir"])
+ os.path.join(config["video_dir"])
)
+
self.movie_file_path = os.path.join(
movie_dir,
add_extension_if_not_present(
- scene_name, file_writer_config["movie_file_extension"]
+ scene_name, config["movie_file_extension"]
),
)
self.gif_file_path = os.path.join(
movie_dir, add_extension_if_not_present(scene_name, GIF_FILE_EXTENSION)
)
- if not file_writer_config["custom_folders"]:
+ if not config["custom_folders"]:
self.partial_movie_directory = guarantee_existence(
os.path.join(
movie_dir,
@@ -134,7 +135,7 @@ class SceneFileWriter(object):
self.partial_movie_directory,
"{}{}".format(
hash_animation,
- file_writer_config["movie_file_extension"],
+ config["movie_file_extension"],
),
)
self.partial_movie_files.append(new_partial_movie_file)
@@ -149,7 +150,7 @@ class SceneFileWriter(object):
str
The name of the directory.
"""
- filename = os.path.basename(file_writer_config["input_file"])
+ filename = os.path.basename(config["input_file"])
root, _ = os.path.splitext(filename)
return root
@@ -165,7 +166,7 @@ class SceneFileWriter(object):
str
The default scene name.
"""
- fn = file_writer_config["output_file"]
+ fn = config["output_file"]
return fn if fn else self.scene.__class__.__name__
def get_resolution_directory(self):
@@ -313,7 +314,7 @@ class SceneFileWriter(object):
allow_write : bool, optional
Whether or not to write to a video file.
"""
- if file_writer_config["write_to_movie"] and allow_write:
+ if config["write_to_movie"] and allow_write:
self.open_movie_pipe()
def end_animation(self, allow_write=False):
@@ -326,7 +327,7 @@ class SceneFileWriter(object):
allow_write : bool, optional
Whether or not to write to a video file.
"""
- if file_writer_config["write_to_movie"] and allow_write:
+ if config["write_to_movie"] and allow_write:
self.close_movie_pipe()
def write_frame(self, frame):
@@ -339,9 +340,9 @@ class SceneFileWriter(object):
frame : np.array
Pixel array of the frame.
"""
- if file_writer_config["write_to_movie"]:
+ if config["write_to_movie"]:
self.writing_process.stdin.write(frame.tostring())
- if file_writer_config["save_pngs"]:
+ if config["save_pngs"]:
path, extension = os.path.splitext(self.image_file_path)
Image.fromarray(frame).save(f"{path}{self.frame_count}{extension}")
self.frame_count += 1
@@ -384,15 +385,15 @@ class SceneFileWriter(object):
If save_last_frame is True, saves the last
frame in the default image directory.
"""
- if file_writer_config["write_to_movie"]:
+ if config["write_to_movie"]:
if hasattr(self, "writing_process"):
self.writing_process.terminate()
self.combine_movie_files()
- if file_writer_config["flush_cache"]:
+ if config["flush_cache"]:
self.flush_cache_directory()
else:
self.clean_cache()
- if file_writer_config["save_last_frame"]:
+ if config["save_last_frame"]:
self.scene.update_frame(ignore_skipping=True)
self.save_final_image(self.scene.camera.get_image())
@@ -408,7 +409,7 @@ class SceneFileWriter(object):
temp_file_path = (
os.path.splitext(file_path)[0]
+ "_temp"
- + file_writer_config["movie_file_extension"]
+ + config["movie_file_extension"]
)
self.partial_movie_file_path = file_path
self.temp_partial_movie_file_path = temp_file_path
@@ -432,11 +433,11 @@ class SceneFileWriter(object):
"-", # The imput comes from a pipe
"-an", # Tells FFMPEG not to expect any audio
"-loglevel",
- file_writer_config["ffmpeg_loglevel"],
+ config["ffmpeg_loglevel"].lower(),
]
# TODO, the test for a transparent background should not be based on
# the file extension.
- if file_writer_config["movie_file_extension"] == ".mov":
+ if config["movie_file_extension"] == ".mov":
# This is if the background of the exported
# video should be transparent.
command += [
@@ -485,7 +486,7 @@ class SceneFileWriter(object):
"""
path = os.path.join(
self.partial_movie_directory,
- "{}{}".format(hash_invocation, self.movie_file_extension),
+ "{}{}".format(hash_invocation, config['movie_file_extension']),
)
return os.path.exists(path)
@@ -495,20 +496,20 @@ class SceneFileWriter(object):
partial movie files that make up a Scene into a single
video file for that Scene.
"""
- # Manim renders the scene as many smaller movie files
- # which are then concatenated to a larger one. The reason
- # for this is that sometimes video-editing is made easier when
- # one works with the broken up scene, which effectively has
- # cuts at all the places you might want. But for viewing
- # the scene as a whole, one of course wants to see it as a
+ # Manim renders the scene as many smaller movie files which are then
+ # concatenated to a larger one. The reason for this is that sometimes
+ # video-editing is made easier when one works with the broken up scene,
+ # which effectively has cuts at all the places you might want. But for
+ # viewing the scene as a whole, one of course wants to see it as a
# single piece.
partial_movie_files = [el for el in self.partial_movie_files if el is not None]
- # NOTE : Here we should do a check and raise an exeption if partial movie file is empty.
- # We can't, as a lot of stuff (in particular, in tests) use scene initialization, and this error would be raised as it's just
- # an empty scene initialized.
+ # NOTE : Here we should do a check and raise an exeption if partial
+ # movie file is empty. We can't, as a lot of stuff (in particular, in
+ # tests) use scene initialization, and this error would be raised as
+ # it's just an empty scene initialized.
- # Write a file partial_file_list.txt containing all
- # partial movie files. This is used by FFMPEG.
+ # Write a file partial_file_list.txt containing all partial movie
+ # files. This is used by FFMPEG.
file_list = os.path.join(
self.partial_movie_directory, "partial_movie_file_list.txt"
)
@@ -533,24 +534,27 @@ class SceneFileWriter(object):
"-i",
file_list,
"-loglevel",
- file_writer_config["ffmpeg_loglevel"],
+ config["ffmpeg_loglevel"].lower(),
]
- if self.write_to_movie and not self.save_as_gif:
+ if config['write_to_movie'] and not config['save_as_gif']:
commands += ["-c", "copy", movie_file_path]
- if self.save_as_gif:
+ if config['save_as_gif']:
commands += [self.gif_file_path]
if not self.includes_sound:
commands.insert(-1, "-an")
- combine_process = subprocess.Popen(commands)
- combine_process.wait()
+ try:
+ subprocess.check_call(commands)
+ except subprocess.CalledProcessError as exc:
+ logger.error(f'FFMPEG returned with code {exc.returncode}')
+ raise exc
if self.includes_sound:
sound_file_path = movie_file_path.replace(
- file_writer_config["movie_file_extension"], ".wav"
+ config["movie_file_extension"], ".wav"
)
# Makes sure sound file length will match video file
self.add_audio_segment(AudioSegment.silent(0))
@@ -579,7 +583,7 @@ class SceneFileWriter(object):
"-map",
"1:a:0",
"-loglevel",
- file_writer_config["ffmpeg_loglevel"],
+ config["ffmpeg_loglevel"].lower(),
# "-shortest",
temp_file_path,
]
@@ -588,9 +592,9 @@ class SceneFileWriter(object):
os.remove(sound_file_path)
self.print_file_ready_message(
- self.gif_file_path if self.save_as_gif else movie_file_path
+ self.gif_file_path if config['save_as_gif'] else movie_file_path
)
- if file_writer_config["write_to_movie"]:
+ if config["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)
@@ -602,9 +606,9 @@ class SceneFileWriter(object):
for file_name in os.listdir(self.partial_movie_directory)
if file_name != "partial_movie_file_list.txt"
]
- if len(cached_partial_movies) > file_writer_config["max_files_cached"]:
+ if len(cached_partial_movies) > config["max_files_cached"]:
number_files_to_delete = (
- len(cached_partial_movies) - file_writer_config["max_files_cached"]
+ len(cached_partial_movies) - config["max_files_cached"]
)
oldest_files_to_delete = sorted(
[partial_movie_file for partial_movie_file in cached_partial_movies],
@@ -614,7 +618,7 @@ class SceneFileWriter(object):
for file_to_delete in oldest_files_to_delete:
os.remove(file_to_delete)
logger.info(
- f"The partial movie directory is full (> {file_writer_config['max_files_cached']} files). Therefore, manim has removed {number_files_to_delete} file(s) used by it the longest ago."
+ f"The partial movie directory is full (> {config['max_files_cached']} files). Therefore, manim has removed {number_files_to_delete} file(s) used by it the longest ago."
+ "You can change this behaviour by changing max_files_cached in config."
)
diff --git a/manim/utils/module_ops.py b/manim/utils/module_ops.py
index 98bd91079..a5b2f6f46 100644
--- a/manim/utils/module_ops.py
+++ b/manim/utils/module_ops.py
@@ -1,6 +1,4 @@
-from .. import constants
-from ..config import file_writer_config
-from .. import logger, console
+from .. import constants, logger, console, config
import importlib.util
import inspect
import os
@@ -62,10 +60,10 @@ def get_scenes_to_render(scene_classes):
if not scene_classes:
logger.error(constants.NO_SCENE_MESSAGE)
return []
- if file_writer_config["write_all"]:
+ if config["write_all"]:
return scene_classes
result = []
- for scene_name in file_writer_config["scene_names"]:
+ for scene_name in config["scene_names"]:
found = False
for scene_class in scene_classes:
if scene_class.__name__ == scene_name:
diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.py
index 51298b1ac..924e761d6 100644
--- a/manim/utils/tex_file_writing.py
+++ b/manim/utils/tex_file_writing.py
@@ -10,7 +10,7 @@ import os
import hashlib
from pathlib import Path
-from .. import file_writer_config, config, logger
+from .. import config, logger
def tex_hash(expression):
@@ -37,7 +37,7 @@ def generate_tex_file(expression, tex_template, source_type):
elif source_type == "tex":
output = tex_template.get_text_for_tex_mode(expression)
- result = os.path.join(file_writer_config["tex_dir"], tex_hash(output)) + ".tex"
+ result = os.path.join(config["tex_dir"], tex_hash(output)) + ".tex"
if not os.path.exists(result):
logger.info('Writing "%s" to %s' % ("".join(expression), result))
with open(result, "w", encoding="utf-8") as outfile:
@@ -89,7 +89,7 @@ def tex_to_dvi(tex_file, use_ctex=False, tex_compiler=None):
result = tex_file.replace(".tex", tex_compiler["output_format"])
result = Path(result).as_posix()
tex_file = Path(tex_file).as_posix()
- tex_dir = Path(file_writer_config["tex_dir"]).as_posix()
+ tex_dir = Path(config["tex_dir"]).as_posix()
if not os.path.exists(result):
command = tex_compilation_command(tex_compiler, tex_file, tex_dir)
exit_code = os.system(command)
diff --git a/tests/control_data/logs_data/BasicSceneLoggingTest.txt b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
index 2e60f36bd..c4131e12a 100644
--- a/tests/control_data/logs_data/BasicSceneLoggingTest.txt
+++ b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
@@ -1,4 +1,4 @@
-{"levelname": "INFO", "module": "main_utils", "message": "Log file will be saved in <>"}
+{"levelname": "INFO", "module": "logger", "message": "Log file will be saved in <>"}
{"levelname": "DEBUG", "module": "hashing", "message": "Hashing ..."}
{"levelname": "DEBUG", "module": "hashing", "message": "Hashing done in <> s."}
{"levelname": "DEBUG", "module": "hashing", "message": "Hash generated : <>"}
diff --git a/tests/helpers/graphical_units.py b/tests/helpers/graphical_units.py
index ad8914a03..42b5e8e4d 100644
--- a/tests/helpers/graphical_units.py
+++ b/tests/helpers/graphical_units.py
@@ -5,8 +5,7 @@ import os
import tempfile
import numpy as np
-import manim
-from manim import config, file_writer_config, logger
+from manim import config, logger
def set_test_scene(scene_object, module_name):
@@ -28,17 +27,17 @@ def set_test_scene(scene_object, module_name):
set_test_scene(DotTest, "geometry")
"""
- file_writer_config["skip_animations"] = True
- file_writer_config["write_to_movie"] = False
- file_writer_config["disable_caching"] = True
+ config["skip_animations"] = True
+ config["write_to_movie"] = False
+ config["disable_caching"] = True
config["pixel_height"] = 480
config["pixel_width"] = 854
config["frame_rate"] = 15
with tempfile.TemporaryDirectory() as tmpdir:
os.makedirs(os.path.join(tmpdir, "tex"))
- file_writer_config["text_dir"] = os.path.join(tmpdir, "text")
- file_writer_config["tex_dir"] = os.path.join(tmpdir, "tex")
+ config["text_dir"] = os.path.join(tmpdir, "text")
+ config["tex_dir"] = os.path.join(tmpdir, "tex")
scene = scene_object()
data = scene.get_frame()
diff --git a/tests/test_cli_flags.py b/tests/test_cli_flags.py
index 242c72884..c77b94ac1 100644
--- a/tests/test_cli_flags.py
+++ b/tests/test_cli_flags.py
@@ -1,5 +1,6 @@
from manim import constants
-from manim.config.main_utils import _determine_quality, parse_args
+from manim.config.main_utils import parse_args
+from manim.config.utils import determine_quality
def test_quality_flags():
@@ -7,7 +8,7 @@ def test_quality_flags():
parsed = parse_args("manim dummy_filename".split())
assert parsed.quality == constants.DEFAULT_QUALITY_SHORT
- assert _determine_quality(parsed) == constants.DEFAULT_QUALITY
+ assert determine_quality(parsed) == constants.DEFAULT_QUALITY
for quality in constants.QUALITIES.keys():
# Assert that quality is properly set when using -q*
@@ -15,14 +16,14 @@ def test_quality_flags():
parsed = parse_args(arguments)
assert parsed.quality == constants.QUALITIES[quality]
- assert quality == _determine_quality(parsed)
+ assert quality == determine_quality(parsed)
# Assert that quality is properly set when using -q *
arguments = f"manim -q {constants.QUALITIES[quality]} dummy_filename".split()
parsed = parse_args(arguments)
assert parsed.quality == constants.QUALITIES[quality]
- assert quality == _determine_quality(parsed)
+ assert quality == determine_quality(parsed)
# Assert that quality is properly set when using --quality *
arguments = (
@@ -31,17 +32,17 @@ def test_quality_flags():
parsed = parse_args(arguments)
assert parsed.quality == constants.QUALITIES[quality]
- assert quality == _determine_quality(parsed)
+ assert quality == determine_quality(parsed)
# Assert that quality is properly set when using -*_quality
arguments = f"manim --{quality} dummy_filename".split()
parsed = parse_args(arguments)
assert getattr(parsed, quality)
- assert quality == _determine_quality(parsed)
+ assert quality == determine_quality(parsed)
# Assert that *_quality is False when not specifying it
parsed = parse_args("manim dummy_filename".split())
assert not getattr(parsed, quality)
- assert _determine_quality(parsed) == constants.DEFAULT_QUALITY
+ assert determine_quality(parsed) == constants.DEFAULT_QUALITY
diff --git a/tests/test_config.py b/tests/test_config.py
index 36c60243b..bb906578d 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -7,14 +7,11 @@ def test_tempconfig():
"""Test the tempconfig context manager."""
original = config.copy()
- with tempconfig({"frame_width": 100, "frame_height": 42, "foo": -1}):
+ with tempconfig({"frame_width": 100, "frame_height": 42}):
# check that config was modified correctly
assert config["frame_width"] == 100
assert config["frame_height"] == 42
- # 'foo' is not a key in the original dict so it shouldn't be added
- assert "foo" not in config
-
# check that no keys are missing and no new keys were added
assert set(original.keys()) == set(config.keys())
diff --git a/tests/test_container.py b/tests/test_container.py
index 4bf8d2753..5a26b3ba5 100644
--- a/tests/test_container.py
+++ b/tests/test_container.py
@@ -1,5 +1,5 @@
import pytest
-from manim import Container, Mobject, Scene, file_writer_config
+from manim import Container, Mobject, Scene
def test_ABC():
diff --git a/tests/test_copy.py b/tests/test_copy.py
index dde6a0894..2210dda1e 100644
--- a/tests/test_copy.py
+++ b/tests/test_copy.py
@@ -1,5 +1,5 @@
import os
-from manim import Mobject, BraceLabel, file_writer_config
+from manim import Mobject, BraceLabel, config
def test_mobject_copy():
@@ -18,13 +18,13 @@ def test_mobject_copy():
def test_bracelabel_copy(tmp_path):
"""Test that a copy is a deepcopy."""
# For this test to work, we need to tweak some folders temporarily
- original_text_dir = file_writer_config["text_dir"]
- original_tex_dir = file_writer_config["tex_dir"]
+ original_text_dir = config["text_dir"]
+ original_tex_dir = config["tex_dir"]
mediadir = os.path.join(tmp_path, "deepcopy")
- file_writer_config["text_dir"] = os.path.join(mediadir, "Text")
- file_writer_config["tex_dir"] = os.path.join(mediadir, "Tex")
+ config["text_dir"] = os.path.join(mediadir, "Text")
+ config["tex_dir"] = os.path.join(mediadir, "Tex")
for el in ["text_dir", "tex_dir"]:
- os.makedirs(file_writer_config[el])
+ os.makedirs(config[el])
# Before the refactoring of Mobject.copy(), the class BraceLabel was the
# only one to have a non-trivial definition of copy. Here we test that it
@@ -43,5 +43,5 @@ def test_bracelabel_copy(tmp_path):
assert copy.submobjects[0] is not orig.brace
# Restore the original folders
- file_writer_config["text_dir"] = original_text_dir
- file_writer_config["tex_dir"] = original_tex_dir
+ config["text_dir"] = original_text_dir
+ config["tex_dir"] = original_tex_dir
diff --git a/tests/test_logging/test_logging.py b/tests/test_logging/test_logging.py
index f4ae349a3..504a76ecc 100644
--- a/tests/test_logging/test_logging.py
+++ b/tests/test_logging/test_logging.py
@@ -43,7 +43,7 @@ def test_logging_when_scene_is_not_specified(tmp_path, python_version):
"-m",
"manim",
path_basic_scene,
- "-l",
+ "-ql",
"--log_to_file",
"-v",
"DEBUG",
diff --git a/tests/test_scene_rendering/conftest.py b/tests/test_scene_rendering/conftest.py
index 81826ab81..055555063 100644
--- a/tests/test_scene_rendering/conftest.py
+++ b/tests/test_scene_rendering/conftest.py
@@ -2,9 +2,6 @@ import pytest
import os
-from manim import file_writer_config
-
-
@pytest.fixture
def manim_cfg_file():
return os.path.join(os.path.dirname(__file__), "manim.cfg")
diff --git a/tests/test_scene_rendering/test_caching_relalted.py b/tests/test_scene_rendering/test_caching_relalted.py
index 629917332..7827248e0 100644
--- a/tests/test_scene_rendering/test_caching_relalted.py
+++ b/tests/test_scene_rendering/test_caching_relalted.py
@@ -1,7 +1,6 @@
import os
import pytest
import subprocess
-from manim import file_writer_config
from ..utils.commands import capture
from ..utils.video_tester import video_comparison
diff --git a/tests/test_scene_rendering/test_caching_related.py b/tests/test_scene_rendering/test_caching_related.py
index 3f6d4ec97..03395571a 100644
--- a/tests/test_scene_rendering/test_caching_related.py
+++ b/tests/test_scene_rendering/test_caching_related.py
@@ -1,7 +1,6 @@
import os
import pytest
import subprocess
-from manim import file_writer_config
from ..utils.commands import capture
from ..utils.video_tester import *
diff --git a/tests/utils/GraphicalUnitTester.py b/tests/utils/GraphicalUnitTester.py
index 7f856ded1..e9db4f0f7 100644
--- a/tests/utils/GraphicalUnitTester.py
+++ b/tests/utils/GraphicalUnitTester.py
@@ -7,7 +7,7 @@ import pytest
import warnings
from platform import system
-from manim import config, file_writer_config
+from manim import config
class GraphicalUnitTester:
@@ -52,26 +52,24 @@ class GraphicalUnitTester:
tests_directory, "control_data", "graphical_units_data", module_tested
)
- # IMPORTANT NOTE : The graphical units tests don't use for now any custom manim.cfg,
- # since it is impossible to manually select a manim.cfg from a python file. (see issue #293)
- file_writer_config["text_dir"] = os.path.join(
- self.path_tests_medias_cache, "Text"
- )
- file_writer_config["tex_dir"] = os.path.join(
- self.path_tests_medias_cache, "Tex"
- )
+ # IMPORTANT NOTE : The graphical units tests don't use for now any
+ # custom manim.cfg, since it is impossible to manually select a
+ # manim.cfg from a python file. (see issue #293)
+ config["text_dir"] = os.path.join(self.path_tests_medias_cache, "Text")
+ config["tex_dir"] = os.path.join(self.path_tests_medias_cache, "Tex")
- file_writer_config["skip_animations"] = True
- file_writer_config["write_to_movie"] = False
- file_writer_config["disable_caching"] = True
+ config["skip_animations"] = True
+ config["save_last_frame"] = True
+ config["write_to_movie"] = False
+ config["disable_caching"] = True
config["pixel_height"] = 480
config["pixel_width"] = 854
config["frame_rate"] = 15
for dir_temp in [
self.path_tests_medias_cache,
- file_writer_config["text_dir"],
- file_writer_config["tex_dir"],
+ config["text_dir"],
+ config["tex_dir"],
]:
os.makedirs(dir_temp)