Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

refactor config system so that all the global variables are defined in manim/config/__init__.py. All other files inside manim/config/ just contain utils that are used by either manim/config/__init__.py or directly by manim/__main__.py

leotrs504ac73859f9
diff --git a/manim/__main__.py b/manim/__main__.py
index 2450229bc..6db788c9e 100644
--- a/manim/__main__.py
+++ b/manim/__main__.py
@@ -8,17 +8,16 @@ import traceback
import importlib.util
import types
-from . import constants, logger, console, file_writer_config
-from .config.config import camera_config, args
-from .config import cfg_subcmds
-from .utils.module_ops import (
+from manim import constants, logger, console, config, file_writer_config
+from manim import Scene
+from manim.utils.module_ops import (
get_module,
get_scene_classes_from_module,
get_scenes_to_render,
)
-from .scene.scene import Scene
-from .utils.file_ops import open_file as open_media_file
-from .grpc.impl import frame_server_impl
+from manim.utils.file_ops import open_file as open_media_file
+from manim.grpc.impl import frame_server_impl
+from manim.config.main_utils import *
def open_file_if_needed(file_writer):
@@ -55,26 +54,38 @@ def open_file_if_needed(file_writer):
def main():
- if hasattr(args, "subcommands"):
- if "cfg" in args.subcommands:
- if args.cfg_subcommand is not None:
- subcommand = args.cfg_subcommand
- if subcommand == "write":
+ args = parse_args(sys.argv)
+
+ if hasattr(args, "cmd"):
+ if args.cmd == "cfg":
+ if args.subcmd:
+ from manim.config import cfg_subcmds
+
+ if args.subcmd == "write":
cfg_subcmds.write(args.level, args.open)
- elif subcommand == "show":
+ elif args.subcmd == "show":
cfg_subcmds.show()
- elif subcommand == "export":
+ elif args.subcmd == "export":
cfg_subcmds.export(args.dir)
else:
- logger.error("No argument provided; Exiting...")
+ logger.error("No subcommand provided; Exiting...")
+
+ # elif args.cmd == "some_other_cmd":
+ # something_else_here()
else:
+ update_config_with_cli(args)
+ init_dirs(file_writer_config)
+
+ if file_writer_config["log_to_file"]:
+ set_file_logger()
+
module = get_module(file_writer_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:
try:
- if camera_config["use_js_renderer"]:
+ if config["use_js_renderer"]:
frame_server_impl.get(SceneClass).start()
else:
scene = SceneClass()
diff --git a/manim/config/__init__.py b/manim/config/__init__.py
index 05aa100e2..5895076cc 100644
--- a/manim/config/__init__.py
+++ b/manim/config/__init__.py
@@ -1,16 +1,73 @@
-# Note that the global config dict is called 'config', just like the module
-# itself. That's why we import the module first with a different name
-# (_config), and then the dict.
-from . import config as _config
-from .config import config, tempconfig, file_writer_config, camera_config
-from .logger import logger, console
+import logging
+from contextlib import contextmanager
+
+from .utils import make_config_parser, make_logger, make_config, make_file_writer_config
__all__ = [
- "_config",
+ "logger",
+ "console",
"config",
- "tempconfig",
"file_writer_config",
"camera_config",
- "logger",
- "console",
+ "tempconfig",
]
+
+parser = make_config_parser()
+
+# The logger can be accessed from anywhere as manim.logger, or as
+# logging.getLogger("manim"). The console must be accessed as manim.console.
+# Throughout the codebase, use manim.console.print() instead of print().
+logger, console = make_logger(parser["logger"], parser["CLI"]["verbosity"])
+# TODO: temporary to have a clean terminal output when working with PIL or matplotlib
+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)
+
+
+# This has to go here because it needs access to this module's config
+@contextmanager
+def tempconfig(temp):
+ """Context manager that temporarily modifies the global config dict.
+
+ The code block inside the ``with`` statement will use the modified config.
+ After the code block, the config will be restored to its original value.
+
+ Parameters
+ ----------
+
+ temp : :class:`dict`
+ A dictionary whose keys will be used to temporarily update the global
+ config.
+
+ Examples
+ --------
+ Use ``with tempconfig({...})`` to temporarily change the default values of
+ certain objects.
+
+ .. code_block:: python
+
+ c = Camera()
+ c.frame_width == config['frame_width'] # -> True
+ with tempconfig({'frame_width': 100}):
+ c = Camera()
+ c.frame_width == config['frame_width'] # -> False
+ c.frame_width == 100 # -> True
+
+ """
+ global config
+ original = config.copy()
+
+ temp = {k: v for k, v in temp.items() if k in original}
+
+ # In order to change the config that every module has acces to, use
+ # update(), DO NOT use assignment. Assigning config = some_dict will just
+ # make the local variable named config point to a new dictionary, it will
+ # NOT change the dictionary that every module has a reference to.
+ config.update(temp)
+ try:
+ yield
+ finally:
+ config.update(original) # update, not assignment!
diff --git a/manim/config/cfg_subcmds.py b/manim/config/cfg_subcmds.py
index f5e457f14..9595e6b20 100644
--- a/manim/config/cfg_subcmds.py
+++ b/manim/config/cfg_subcmds.py
@@ -6,24 +6,22 @@ General Config File Managing Utilities.
The functions below can be called via the `manim cfg` subcommand.
"""
+
import os
-import configparser
from ast import literal_eval
-from .config_utils import _run_config, _paths_config_file, finalized_configs_dict
-from ..utils.file_ops import guarantee_existence, open_file
-
-from rich.console import Console
-from rich.style import Style
-from rich.errors import StyleSyntaxError
+from manim import logger, console, config
+from manim.config.utils import config_file_paths, make_config_parser
+from manim.utils.file_ops import guarantee_existence, open_file
__all__ = ["write", "show", "export"]
-RICH_COLOUR_INSTRUCTIONS = """[red]The default colour is used by the input statement.
+RICH_COLOUR_INSTRUCTIONS = """
+[red]The default colour is used by the input statement.
If left empty, the default colour will be used.[/red]
-[magenta] For a full list of styles, visit[/magenta] [green]https://rich.readthedocs.io/en/latest/style.html[/green]"""
+[magenta] For a full list of styles, visit[/magenta] [green]https://rich.readthedocs.io/en/latest/style.html[/green]
+"""
RICH_NON_STYLE_ENTRIES = ["log.width", "log.height", "log.timestamps"]
-console = Console()
def value_from_string(value):
@@ -114,8 +112,7 @@ def replace_keys(default):
def write(level=None, openfile=False):
- config = _run_config()[1]
- config_paths = _paths_config_file() + [os.path.abspath("manim.cfg")]
+ config_paths = config_file_paths()
console.print(
"[yellow bold]Manim Configuration File Writer[/yellow bold]", justify="center"
)
@@ -127,11 +124,12 @@ you will have to create a manim.cfg in the local directory, where you want those
CWD_CONFIG_MSG = f"""A configuration file at [yellow]{config_paths[2]}[/yellow] has been created.
To save your config please save that file and place it in your current working directory, from where you run the manim command."""
+ parser = make_config_parser()
if not openfile:
action = "save this as"
- for category in config:
+ for category in parser:
console.print(f"{category}", style="bold green underline")
- default = config[category]
+ default = parser[category]
if category == "logger":
console.print(RICH_COLOUR_INSTRUCTIONS)
default = replace_keys(default)
@@ -178,7 +176,7 @@ modify write_cfg_subcmd_input to account for it."""
default = replace_keys(default) if category == "logger" else default
- config[category] = dict(default)
+ parser[category] = dict(default)
else:
action = "open"
@@ -194,40 +192,37 @@ modify write_cfg_subcmd_input to account for it."""
action_to_userpath = ""
if action_to_userpath.lower() == "y" or level == "user":
- cfg_file_path = os.path.join(
- guarantee_existence(os.path.dirname(config_paths[1])), "manim.cfg"
- )
+ cfg_file_path = config_paths[1]
+ guarantee_existence(config_paths[1].parents[0])
console.print(USER_CONFIG_MSG)
else:
- cfg_file_path = os.path.join(
- guarantee_existence(os.path.dirname(config_paths[2])), "manim.cfg"
- )
+ cfg_file_path = config_paths[2]
+ guarantee_existence(config_paths[2].parents[0])
console.print(CWD_CONFIG_MSG)
with open(cfg_file_path, "w") as fp:
- config.write(fp)
+ parser.write(fp)
if openfile:
open_file(cfg_file_path)
def show():
- current_config = finalized_configs_dict()
+ parser = make_config_parser()
rich_non_style_entries = [a.replace(".", "_") for a in RICH_NON_STYLE_ENTRIES]
- for category in current_config:
+ for category in parser:
console.print(f"{category}", style="bold green underline")
- for entry in current_config[category]:
+ for entry in parser[category]:
if category == "logger" and entry not in rich_non_style_entries:
console.print(f"{entry} :", end="")
console.print(
- f" {current_config[category][entry]}",
- style=current_config[category][entry],
+ f" {parser[category][entry]}",
+ style=parser[category][entry],
)
else:
- console.print(f"{entry} : {current_config[category][entry]}")
+ console.print(f"{entry} : {parser[category][entry]}")
console.print("\n")
def export(path):
- config = _run_config()[1]
if os.path.abspath(path) == os.path.abspath(os.getcwd()):
console.print(
"""You are reading the config from the same directory you are exporting to.
diff --git a/manim/config/config.py b/manim/config/config.py
deleted file mode 100644
index 3e7481c0d..000000000
--- a/manim/config/config.py
+++ /dev/null
@@ -1,190 +0,0 @@
-"""
-config.py
----------
-Process the manim.cfg file and the command line arguments into a single
-config object.
-"""
-
-
-__all__ = ["file_writer_config", "config", "camera_config", "tempconfig"]
-
-
-import os
-import sys
-from contextlib import contextmanager
-
-import colour
-
-from .. import constants
-from .config_utils import (
- _determine_quality,
- _run_config,
- _init_dirs,
- _from_command_line,
-)
-
-from .logger import set_rich_logger, set_file_logger, logger
-from ..utils.tex import TexTemplate, TexTemplateFromFile
-
-__all__ = ["file_writer_config", "config", "camera_config", "tempconfig"]
-
-
-config = None
-
-
-@contextmanager
-def tempconfig(temp):
- """Context manager that temporarily modifies the global config dict.
-
- The code block inside the ``with`` statement will use the modified config.
- After the code block, the config will be restored to its original value.
-
- Parameters
- ----------
-
- temp : :class:`dict`
- A dictionary whose keys will be used to temporarily update the global
- config.
-
- Examples
- --------
- Use ``with tempconfig({...})`` to temporarily change the default values of
- certain objects.
-
- .. code_block:: python
-
- c = Camera()
- c.frame_width == config['frame_width'] # -> True
- with tempconfig({'frame_width': 100}):
- c = Camera()
- c.frame_width == config['frame_width'] # -> False
- c.frame_width == 100 # -> True
-
- """
- global config
- original = config.copy()
-
- temp = {k: v for k, v in temp.items() if k in original}
-
- # In order to change the config that every module has acces to, use
- # update(), DO NOT use assignment. Assigning config = some_dict will just
- # make the local variable named config point to a new dictionary, it will
- # NOT change the dictionary that every module has a reference to.
- config.update(temp)
- try:
- yield
- finally:
- config.update(original) # update, not assignment!
-
-
-def _parse_config(config_parser, args):
- """Parse config files and CLI arguments into a single dictionary."""
- # By default, use the CLI section of the digested .cfg files
- default = config_parser["CLI"]
-
- # Handle the *_quality flags. These determine the section to read
- # and are stored in 'camera_config'. Note the highest resolution
- # passed as argument will be used.
- quality = _determine_quality(args)
- section = config_parser[quality if quality != constants.DEFAULT_QUALITY else "CLI"]
-
- # Loop over low quality for the keys, could be any quality really
- config = {opt: section.getint(opt) for opt in config_parser["low_quality"]}
-
- config["default_pixel_height"] = default.getint("pixel_height")
- config["default_pixel_width"] = default.getint("pixel_width")
- # The -r, --resolution flag overrides the *_quality flags
- if args.resolution is not None:
- if "," in args.resolution:
- height_str, width_str = args.resolution.split(",")
- height, width = int(height_str), int(width_str)
- else:
- height = int(args.resolution)
- width = int(16 * height / 9)
- config.update({"pixel_height": height, "pixel_width": width})
-
- # Handle the -c (--background_color) flag
- if args.background_color is not None:
- try:
- background_color = colour.Color(args.background_color)
- except AttributeError as err:
- logger.warning("Please use a valid color.")
- logger.error(err)
- sys.exit(2)
- else:
- background_color = colour.Color(default["background_color"])
- config["background_color"] = background_color
-
- config["use_js_renderer"] = args.use_js_renderer or default.getboolean(
- "use_js_renderer"
- )
-
- config["js_renderer_path"] = args.js_renderer_path or default.get(
- "js_renderer_path"
- )
-
- # Set the rest of the frame properties
- 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
-
- # Handle the --tex_template flag, if the flag is absent read it from the config.
- if args.tex_template:
- tex_fn = os.path.expanduser(args.tex_template)
- else:
- tex_fn = default["tex_template"] if default["tex_template"] != "" else None
-
- if tex_fn is not None and not os.access(tex_fn, os.R_OK):
- # custom template not available, fallback to default
- logger.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"] = (
- TexTemplateFromFile(filename=tex_fn) if tex_fn is not None else TexTemplate()
- )
-
- return config
-
-
-args, config_parser, file_writer_config, successfully_read_files = _run_config()
-logger.setLevel(file_writer_config["verbosity"])
-set_rich_logger(config_parser["logger"], file_writer_config["verbosity"])
-
-if _from_command_line():
- logger.debug(
- f"Read configuration files: {[os.path.abspath(cfgfile) for cfgfile in successfully_read_files]}"
- )
- if not (hasattr(args, "subcommands")):
- _init_dirs(file_writer_config)
-config = _parse_config(config_parser, args)
-if config["use_js_renderer"]:
- file_writer_config["disable_caching"] = True
-camera_config = config
-
-if file_writer_config["log_to_file"]:
- # Note about log_file_name : The log file name will be the <name_of_animation_file>_<name_of_scene>.log
- # get from the args (contained in file_writer_config). So it can differ from the real name of the scene.
- # <name_of_scene> would only appear if scene name was provided on manim call
- scene_name_suffix = "".join(file_writer_config["scene_names"])
- scene_file_name = os.path.basename(args.file).split(".")[0]
- log_file_name = (
- f"{scene_file_name}_{scene_name_suffix}.log"
- if scene_name_suffix
- else f"{scene_file_name}.log"
- )
- log_file_path = os.path.join(
- file_writer_config["log_dir"],
- log_file_name,
- )
- set_file_logger(log_file_path)
- logger.info("Log file will be saved in %(logpath)s", {"logpath": log_file_path})
diff --git a/manim/config/logger.py b/manim/config/logger.py
deleted file mode 100644
index 4ca7ee2eb..000000000
--- a/manim/config/logger.py
+++ /dev/null
@@ -1,120 +0,0 @@
-"""
-logger.py
----------
-This is the logging library for manim.
-This library uses rich for coloured log outputs.
-
-"""
-
-
-__all__ = ["logger", "console"]
-
-
-import configparser
-import logging
-
-from rich.console import Console
-from rich.logging import RichHandler
-from rich.theme import Theme
-from rich import print as printf
-from rich import errors, color
-import json
-import copy
-
-
-class JSONFormatter(logging.Formatter):
- """Subclass of `:class:`logging.Formatter`, to build our own format of the logs (JSON)."""
-
- def format(self, record):
- record_c = copy.deepcopy(record)
- if record_c.args:
- for arg in record_c.args:
- record_c.args[arg] = "<>"
- return json.dumps(
- {
- "levelname": record_c.levelname,
- "module": record_c.module,
- "message": super().format(record_c),
- }
- )
-
-
-def _parse_theme(config_logger):
- theme = dict(
- zip(
- [key.replace("_", ".") for key in config_logger.keys()],
- list(config_logger.values()),
- )
- )
-
- theme["log.width"] = None if theme["log.width"] == "-1" else int(theme["log.width"])
-
- theme["log.height"] = (
- None if theme["log.height"] == "-1" else int(theme["log.height"])
- )
- theme["log.timestamps"] = False
- try:
- customTheme = Theme(
- {
- k: v
- for k, v in theme.items()
- if k not in ["log.width", "log.height", "log.timestamps"]
- }
- )
- except (color.ColorParseError, errors.StyleSyntaxError):
- customTheme = None
- printf(
- "[logging.level.error]It seems your colour configuration couldn't be parsed. Loading the default color configuration...[/logging.level.error]"
- )
- return customTheme
-
-
-def set_rich_logger(config_logger, verbosity):
- """Will set the RichHandler of the logger.
-
- Parameter
- ----------
- config_logger :class:
- Config object of the logger.
- """
- theme = _parse_theme(config_logger)
- global console
- console = Console(theme=theme)
- # These keywords Are Highlighted specially.
- RichHandler.KEYWORDS = [
- "Played",
- "animations",
- "scene",
- "Reading",
- "Writing",
- "script",
- "arguments",
- "Invalid",
- "Aborting",
- "module",
- "File",
- "Rendering",
- "Rendered",
- ]
- rich_handler = RichHandler(
- console=console, show_time=config_logger.getboolean("log_timestamps")
- )
- global logger
- rich_handler.setLevel(verbosity)
- logger.addHandler(rich_handler)
-
-
-def set_file_logger(log_file_path):
- file_handler = logging.FileHandler(log_file_path, mode="w")
- file_handler.setFormatter(JSONFormatter())
- global logger
- logger.addHandler(file_handler)
-
-
-logger = logging.getLogger("manim")
-# The console is set to None as it will be changed by set_rich_logger.
-console = None
-
-# TODO : This is only temporary to keep the terminal output clean when working with ImageMobject and matplotlib plots
-logging.getLogger("PIL").setLevel(logging.INFO)
-logging.getLogger("matplotlib").setLevel(logging.INFO)
diff --git a/manim/config/config_utils.py b/manim/config/main_utils.py
similarity index 61%
rename from manim/config/config_utils.py
rename to manim/config/main_utils.py
index d97b8215a..1c937b18d 100644
--- a/manim/config/config_utils.py
+++ b/manim/config/main_utils.py
@@ -1,218 +1,190 @@
"""
-config_utils.py
----------------
+main_utils.py
+-------------
-Utility functions for parsing manim config files.
+Functions called from __main__.py to interact with the config.
"""
+import os
+import sys
+import argparse
+import logging
-__all__ = [
- "_run_config",
- "_paths_config_file",
- "_from_command_line",
- "finalized_configs_dict",
-]
+import colour
+from manim import constants, logger, config, file_writer_config
+from .utils import make_config_parser, JSONFormatter
+from ..utils.tex import TexTemplate, TexTemplateFromFile
-import argparse
-import configparser
-import logging
-import os
-import sys
-from .. import constants
+def init_dirs(config):
+ for folder in [
+ config["media_dir"],
+ config["video_dir"],
+ config["tex_dir"],
+ config["text_dir"],
+ config["log_dir"],
+ ]:
+ if not os.path.exists(folder):
+ if folder == config["log_dir"] and (not config["log_to_file"]):
+ pass
+ else:
+ os.makedirs(folder)
-def _parse_file_writer_config(config_parser, args):
- """Parse config files and CLI arguments into a single dictionary."""
- # By default, use the CLI section of the digested .cfg files
- default = config_parser["CLI"]
+def _find_subcommand(args):
+ """Return the subcommand that has been passed, if any.
- # This will be the final file_writer_config dict exposed to the user
- fw_config = {}
+ Parameters
+ ----------
+ args : list
+ The argument list.
- # Handle input files and scenes. Note these cannot be set from
- # the .cfg files, only from CLI arguments.
- # If a subcommand is given, manim will not render a video and
- # thus these specific input/output files are not needed.
- if not (hasattr(args, "subcommands")):
- fw_config["input_file"] = args.file
- fw_config["scene_names"] = (
- args.scene_names if args.scene_names is not None else []
- )
- fw_config["output_file"] = args.output_file
+ Returns
+ -------
+ Optional[:class:`str`]
+ If a subcommand is found, returns the string of its name. Returns None
+ otherwise.
- # Handle all options that are directly overridden by CLI
- # arguments. Note ConfigParser options are all strings and each
- # needs to be converted to the appropriate type. Thus, we do this
- # in batches, depending on their type: booleans and strings
- 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",
+ Notes
+ -----
+ This assumes that "manim" is the first word in the argument list, and that
+ the subcommand will be the second word, if it exists.
+
+ """
+ subcmd = args[1]
+ if subcmd in [
+ "cfg"
+ # , 'init',
]:
+ return subcmd
+ else:
+ return None
- attr = getattr(args, boolean_opt)
- fw_config[boolean_opt] = (
- default.getboolean(boolean_opt) if attr is None else attr
- )
- # for str_opt in ['media_dir', 'video_dir', 'tex_dir', 'text_dir']:
- for str_opt in ["media_dir"]:
- attr = getattr(args, str_opt)
- fw_config[str_opt] = os.path.relpath(default[str_opt]) if attr is None else attr
- attr = getattr(args, "log_dir")
- fw_config["log_dir"] = (
- os.path.join(fw_config["media_dir"], default["log_dir"])
- if attr is None
- else attr
+
+def _init_cfg_subcmd(subparsers):
+ """Initialises the subparser for the `cfg` subcommand.
+
+ Parameters
+ ----------
+ subparsers : :class:`argparse._SubParsersAction`
+ The subparser object for which to add the sub-subparser for the cfg subcommand.
+
+ Returns
+ -------
+ :class:`argparse.ArgumentParser`
+ The parser that parser anything cfg subcommand related.
+ """
+ cfg_related = subparsers.add_parser("cfg")
+ cfg_subparsers = cfg_related.add_subparsers(dest="cfg_subcommand")
+
+ cfg_write_parser = cfg_subparsers.add_parser("write")
+ cfg_write_parser.add_argument(
+ "--level",
+ choices=["user", "cwd"],
+ default=None,
+ help="Specify if this config is for user or just the working directory.",
)
- dir_names = {
- "video_dir": "videos",
- "images_dir": "images",
- "tex_dir": "Tex",
- "text_dir": "texts",
- }
- for name in dir_names:
- fw_config[name] = os.path.join(fw_config["media_dir"], dir_names[name])
+ cfg_write_parser.add_argument(
+ "--open", action="store_const", const=True, default=False
+ )
+ cfg_subparsers.add_parser("show")
- # the --custom_folders flag overrides the default folder structure with the
- # custom folders defined in the [custom_folders] section of the config file
- fw_config["custom_folders"] = args.custom_folders
- if fw_config["custom_folders"]:
- fw_config["media_dir"] = config_parser["custom_folders"].get("media_dir")
- for opt in ["video_dir", "images_dir", "tex_dir", "text_dir"]:
- fw_config[opt] = config_parser["custom_folders"].get(opt)
+ cfg_export_parser = cfg_subparsers.add_parser("export")
+ cfg_export_parser.add_argument("--dir", default=os.getcwd())
- # Handle the -s (--save_last_frame) flag: invalidate the -w flag
- # At this point the save_last_frame option has already been set by
- # both CLI and the cfg file, so read the config dict directly
- if fw_config["save_last_frame"]:
- fw_config["write_to_movie"] = False
+ return cfg_related
- # Handle the -t (--transparent) flag. This flag determines which
- # section to use from the .cfg file.
- section = config_parser["transparent"] if args.transparent else default
- for opt in ["png_mode", "movie_file_extension", "background_opacity"]:
- fw_config[opt] = section[opt]
- # Handle the -n flag. Read first from the cfg and then override with CLI.
- # These two are integers -- use getint()
- for opt in ["from_animation_number", "upto_animation_number"]:
- fw_config[opt] = default.getint(opt)
- if fw_config["upto_animation_number"] == -1:
- fw_config["upto_animation_number"] = float("inf")
- nflag = args.from_animation_number
- if nflag is not None:
- if "," in nflag:
- start, end = nflag.split(",")
- fw_config["from_animation_number"] = int(start)
- fw_config["upto_animation_number"] = int(end)
- else:
- fw_config["from_animation_number"] = int(nflag)
+def _str2bool(s):
+ if s == "True":
+ return True
+ elif s == "False":
+ return False
+ else:
+ raise argparse.ArgumentTypeError("True or False expected")
- # Handle the --dry_run flag. This flag determines which section
- # to use from the .cfg file. All options involved are boolean.
- # Note this overrides the flags -w, -s, -a, -g, and -i.
- if args.dry_run:
- for opt in [
- "write_to_movie",
- "save_last_frame",
- "save_pngs",
- "save_as_gif",
- "write_all",
- ]:
- fw_config[opt] = config_parser["dry_run"].getboolean(opt)
- if not fw_config["write_to_movie"]:
- fw_config["disable_caching"] = True
- # Read in the streaming section -- all values are strings
- fw_config["streaming"] = {
- opt: config_parser["streaming"][opt]
- for opt in [
- "live_stream_name",
- "twitch_stream_key",
- "streaming_protocol",
- "streaming_ip",
- "streaming_protocol",
- "streaming_client",
- "streaming_port",
- "streaming_port",
- "streaming_console_banner",
- ]
- }
- # 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")
- # Parse the verbosity flag to read in the log level
- verbosity = getattr(args, "verbosity")
- verbosity = default["verbosity"] if verbosity is None else verbosity
- fw_config["verbosity"] = verbosity
+def parse_args(args):
+ if args[0] == "python" and args[1] == "-m":
+ args = args[2:]
- # Parse the ffmpeg log level in the config
- ffmpeg_loglevel = config_parser["ffmpeg"].get("loglevel", None)
- fw_config["ffmpeg_loglevel"] = (
- constants.FFMPEG_VERBOSITY_MAP[verbosity]
- if ffmpeg_loglevel is None
- else ffmpeg_loglevel
+ subcmd = _find_subcommand(args)
+ if subcmd == "cfg":
+ return _parse_args_cfg_subcmd(args)
+ # elif subcmd == some_other_future_subcmd:
+ # return _parse_args_some_other_subcmd(args)
+ elif subcmd is None:
+ return _parse_args_no_subcmd(args)
+
+
+def _parse_args_cfg_subcmd(args):
+ """Parse arguments of the form 'manim cfg <subcmd> <args>'."""
+ parser = argparse.ArgumentParser(
+ description="Animation engine for explanatory math videos",
+ prog="manim cfg",
+ epilog="Made with <3 by the manim community devs",
)
+ subparsers = parser.add_subparsers(help="subcommand", dest="subcmd")
- # Parse the progress_bar flag
- progress_bar = getattr(args, "progress_bar")
- if progress_bar is None:
- progress_bar = default.getboolean("progress_bar")
- fw_config["progress_bar"] = progress_bar
- return fw_config
+ cfg_subparsers = {
+ subcmd: subparsers.add_parser(subcmd) for subcmd in ["write", "show", "export"]
+ }
+
+ # Arguments for the write subcmd
+ cfg_subparsers["write"].add_argument(
+ "--level",
+ choices=["user", "cwd"],
+ default="cwd",
+ help="Specify if this config is for user or the working directory.",
+ )
+ cfg_subparsers["write"].add_argument(
+ "--open", action="store_const", const=True, default=False
+ )
+ # Arguments for the export subcmd
+ cfg_subparsers["export"].add_argument("--dir", default=os.getcwd())
-def _parse_cli(arg_list, input=True):
+ # Arguments for the show subcmd: currently no arguments
+
+ # Recall the argument list looks like 'manim cfg <subcmd> <args>' so we
+ # only need to parse the remaining args
+ parsed = parser.parse_args(args[2:])
+ parsed.cmd = "cfg"
+ parsed.cfg_subcommand = parsed.subcmd
+
+ return parsed
+
+
+def _parse_args_no_subcmd(args):
parser = argparse.ArgumentParser(
description="Animation engine for explanatory math videos",
+ prog="manim",
+ usage=(
+ "%(prog)s file [flags] [scene [scene ...]]\n"
+ " %(prog)s {cfg,init} [opts]"
+ ),
epilog="Made with <3 by the manim community devs",
)
- if input:
- # If the only command is `manim`, we want both subcommands like `cfg`
- # and mandatory positional arguments like `file` to show up in the help section.
- only_manim = len(sys.argv) == 1
-
- if only_manim or _subcommand_name():
- subparsers = parser.add_subparsers(dest="subcommands")
-
- # More subcommands can be added here, with elif statements.
- # If a help command is passed, we still want subcommands to show
- # up, so we check for help commands as well before adding the
- # subcommand's subparser.
- if only_manim or _subcommand_name() in ["cfg", "--help", "-h"]:
- cfg_related = _init_cfg_subcmd(subparsers)
-
- if only_manim or not _subcommand_name(ignore=["--help", "-h"]):
- parser.add_argument(
- "file",
- help="path to file holding the python code for the scene",
- )
- parser.add_argument(
- "scene_names",
- nargs="*",
- help="Name of the Scene class you want to see",
- default=[""],
- )
- parser.add_argument(
- "-o",
- "--output_file",
- help="Specify the name of the output file, if "
- "it should be different from the scene class name",
- default="",
- )
+
+ parser.add_argument(
+ "file",
+ help="Path to file holding the python code for the scene",
+ )
+ parser.add_argument(
+ "scene_names",
+ nargs="*",
+ help="Name of the Scene class you want to see",
+ default=[""],
+ )
+ parser.add_argument(
+ "-o",
+ "--output_file",
+ help="Specify the name of the output file, if "
+ "it should be different from the scene class name",
+ default="",
+ )
# The following use (action='store_const', const=True) instead of
# the built-in (action='store_true'). This is because the latter
@@ -233,6 +205,12 @@ def _parse_cli(arg_list, input=True):
const=True,
help="Show the output file in the File Browser",
)
+ parser.add_argument(
+ "--sound",
+ action="store_const",
+ const=True,
+ help="Play a success/failure sound",
+ )
parser.add_argument(
"--leave_progress_bars",
action="store_const",
@@ -399,7 +377,7 @@ def _parse_cli(arg_list, input=True):
"-r",
"--resolution",
help='Resolution, passed as "height,width". '
- "Overrides any quality flags, if present",
+ "Overrides the -l, -m, -e, and -k flags, if present",
)
# This sets FROM_ANIMATION_NUMBER and UPTO_ANIMATION_NUMBER
@@ -443,208 +421,243 @@ def _parse_cli(arg_list, input=True):
"-v",
"--verbosity",
type=str,
- help="Verbosity level. Also changes the ffmpeg log level unless the latter is specified in the config",
+ help=(
+ "Verbosity level. Also changes the ffmpeg log level unless "
+ "the latter is specified in the config"
+ ),
choices=constants.VERBOSITY_CHOICES,
)
# Specify if the progress bar should be displayed
- def _str2bool(s):
- if s == "True":
- return True
- elif s == "False":
- return False
- else:
- raise argparse.ArgumentTypeError("True or False expected")
-
parser.add_argument(
"--progress_bar",
type=_str2bool,
help="Display the progress bar",
metavar="True/False",
)
- parsed = parser.parse_args(arg_list)
- if hasattr(parsed, "subcommands"):
- if _subcommand_name() == "cfg":
- setattr(
- parsed,
- "cfg_subcommand",
- cfg_related.parse_args(sys.argv[2:]).cfg_subcommand,
- )
-
- return parsed
+ return parser.parse_args(args[1:])
-def _init_dirs(config):
- # Make sure all folders exist
- for folder in [
- config["media_dir"],
- config["video_dir"],
- config["tex_dir"],
- config["text_dir"],
- config["log_dir"],
- ]:
- if not os.path.exists(folder):
- # If log_to_file is False, ignore log_dir
- if folder is config["log_dir"] and (not config["log_to_file"]):
- pass
- else:
- os.makedirs(folder)
+def update_config_with_cli(args):
+ """Update the config dictionaries after parsing CLI flags."""
+ parser = make_config_parser()
+ default = parser["CLI"]
-def _from_command_line():
- """Determine if manim was called from the command line."""
- # Manim can be called from the command line in three different
- # ways. The first two involve using the manim or manimcm commands.
- # Note that some Windows CLIs replace those commands with the path
- # to their executables, so we must check for this as well
- prog = os.path.split(sys.argv[0])[-1]
- from_cli_command = prog in ["manim", "manim.exe", "manimcm", "manimcm.exe"]
+ ## Update config
+ global config
- # The third way involves using `python -m manim ...`. In this
- # case, the CLI arguments passed to manim do not include 'manim',
- # 'manimcm', or even 'python'. However, the -m flag will always
- # be the first argument.
- from_python_m = sys.argv[0] == "-m"
+ # Handle the *_quality flags. These determine the section to read
+ # and are stored in 'camera_config'. Note the highest resolution
+ # passed as argument will be used.
+ quality = _determine_quality(args)
+ section = parser[quality if quality != constants.DEFAULT_QUALITY else "CLI"]
- return from_cli_command or from_python_m
+ # Loop over low quality for the keys, could be any quality really
+ config.update({opt: section.getint(opt) for opt in parser["low_quality"]})
+ # The -r, --resolution flag overrides the *_quality flags
+ if args.resolution is not None:
+ if "," in args.resolution:
+ height_str, width_str = args.resolution.split(",")
+ height, width = int(height_str), int(width_str)
+ else:
+ height = int(args.resolution)
+ width = int(16 * height / 9)
+ config.update({"pixel_height": height, "pixel_width": width})
+
+ # Handle the -c (--background_color) flag
+ if args.background_color is not None:
+ try:
+ background_color = colour.Color(args.background_color)
+ except AttributeError as err:
+ logger.warning("Please use a valid color.")
+ logger.error(err)
+ sys.exit(2)
+ else:
+ background_color = colour.Color(default["background_color"])
+ config["background_color"] = background_color
-def _from_dunder_main():
- dunder_main_path = os.path.join(
- os.path.dirname(os.path.dirname(__file__)), "__main__.py"
+ config["use_js_renderer"] = args.use_js_renderer or default.getboolean(
+ "use_js_renderer"
+ )
+ config["js_renderer_path"] = args.js_renderer_path or default.get(
+ "js_renderer_path"
)
- return sys.argv[0] == dunder_main_path
-
-def _paths_config_file():
- library_wide = os.path.abspath(
- os.path.join(os.path.dirname(__file__), "default.cfg")
+ # Set the rest of the frame properties
+ config["frame_height"] = 8.0
+ config["frame_width"] = (
+ config["frame_height"] * config["pixel_width"] / config["pixel_height"]
)
- if sys.platform.startswith("win32"):
- user_wide = os.path.expanduser(
- os.path.join("~", "AppData", "Roaming", "Manim", "manim.cfg")
- )
- else:
- user_wide = os.path.expanduser(
- os.path.join("~", ".config", "manim", "manim.cfg")
- )
- return [library_wide, user_wide]
-
-
-def _run_config():
- # Config files to be parsed, in ascending priority
- config_files = _paths_config_file()
- if _from_command_line() or _from_dunder_main():
- args = _parse_cli(sys.argv[1:])
- if not hasattr(args, "subcommands"):
- if args.config_file is not None:
- if os.path.exists(args.config_file):
- config_files.append(args.config_file)
- else:
- raise FileNotFoundError(
- f"Config file {args.config_file} doesn't exist"
- )
- else:
- script_directory_file_config = os.path.join(
- os.path.dirname(args.file), "manim.cfg"
- )
- if os.path.exists(script_directory_file_config):
- config_files.append(script_directory_file_config)
- else:
- working_directory_file_config = os.path.join(os.getcwd(), "manim.cfg")
- if os.path.exists(working_directory_file_config):
- config_files.append(working_directory_file_config)
+ 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
+ # Handle the --tex_template flag, if the flag is absent read it from the config.
+ if args.tex_template:
+ tex_fn = os.path.expanduser(args.tex_template)
else:
- # In this case, we still need an empty args object.
- args = _parse_cli([], input=False)
- # Need to populate the options left out
- args.file, args.scene_names, args.output_file = "", "", ""
-
- config_parser = configparser.ConfigParser()
- successfully_read_files = config_parser.read(config_files)
-
- # this is for internal use when writing output files
- file_writer_config = _parse_file_writer_config(config_parser, args)
- return args, config_parser, file_writer_config, successfully_read_files
+ tex_fn = default["tex_template"] if default["tex_template"] != "" else None
+ if tex_fn is not None and not os.access(tex_fn, os.R_OK):
+ # custom template not available, fallback to default
+ logger.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"] = (
+ TexTemplateFromFile(filename=tex_fn) if tex_fn is not None else TexTemplate()
+ )
-def finalized_configs_dict():
- config = _run_config()[1]
- return {section: dict(config[section]) for section in config.sections()}
+ ## Update file_writer_config
+ fw_config = {}
+ if config["use_js_renderer"]:
+ fw_config["disable_caching"] = True
-def _subcommand_name(ignore=()):
- """Goes through sys.argv to check if any subcommand has been passed,
- and returns the first such subcommand's name, if found.
+ if not hasattr(args, "subcommands"):
+ fw_config["input_file"] = args.file if args.file else ""
+ fw_config["scene_names"] = (
+ args.scene_names if args.scene_names is not None else []
+ )
+ fw_config["output_file"] = args.output_file if args.output_file else ""
- Parameters
- ----------
- ignore : Iterable[:class:`str`], optional
- List of NON_ANIM_UTILS to ignore when searching for subcommands, by default []
+ # 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",
+ ]:
+ attr = getattr(args, boolean_opt)
+ fw_config[boolean_opt] = (
+ default.getboolean(boolean_opt) if attr is None else attr
+ )
+ # for str_opt in ['media_dir', 'video_dir', 'tex_dir', 'text_dir']:
+ for str_opt in ["media_dir"]:
+ attr = getattr(args, str_opt)
+ fw_config[str_opt] = os.path.relpath(default[str_opt]) if attr is None else attr
+ attr = getattr(args, "log_dir")
+ fw_config["log_dir"] = (
+ os.path.join(fw_config["media_dir"], default["log_dir"])
+ if attr is None
+ else attr
+ )
+ dir_names = {
+ "video_dir": "videos",
+ "images_dir": "images",
+ "tex_dir": "Tex",
+ "text_dir": "texts",
+ }
+ for name in dir_names:
+ fw_config[name] = os.path.join(fw_config["media_dir"], dir_names[name])
- Returns
- -------
- Optional[:class:`str`]
- If a subcommand is found, returns the string of its name. Returns None if no
- subcommand is found.
- """
- NON_ANIM_UTILS = ["cfg", "--help", "-h"]
- NON_ANIM_UTILS = [util for util in NON_ANIM_UTILS if util not in ignore]
-
- # If a subcommand is found, break out of the inner loop, and hit the break of the outer loop
- # on the way out, effectively breaking out of both loops. The value of arg will be the
- # subcommand to be taken.
- # If no subcommand is found, none of the breaks are hit, and the else clause of the outer loop
- # is run, setting arg to None.
-
- for item in NON_ANIM_UTILS:
- for arg in sys.argv:
- if arg == item:
- break
- else:
- continue
- break
- else:
- arg = None
+ # the --custom_folders flag overrides the default folder structure with the
+ # custom folders defined in the [custom_folders] section of the config file
+ fw_config["custom_folders"] = args.custom_folders
+ if fw_config["custom_folders"]:
+ fw_config["media_dir"] = parser["custom_folders"].get("media_dir")
+ for opt in ["video_dir", "images_dir", "tex_dir", "text_dir"]:
+ fw_config[opt] = parser["custom_folders"].get(opt)
- return arg
+ # Handle the -s (--save_last_frame) flag: invalidate the -w flag
+ # At this point the save_last_frame option has already been set by
+ # both CLI and the cfg file, so read the config dict directly
+ if fw_config["save_last_frame"]:
+ fw_config["write_to_movie"] = False
+ # Handle the -t (--transparent) flag. This flag determines which
+ # section to use from the .cfg file.
+ section = parser["transparent"] if args.transparent else default
+ for opt in ["png_mode", "movie_file_extension", "background_opacity"]:
+ fw_config[opt] = section[opt]
-def _init_cfg_subcmd(subparsers):
- """Initialises the subparser for the `cfg` subcommand.
+ # Handle the -n flag. Read first from the cfg and then override with CLI.
+ # These two are integers -- use getint()
+ for opt in ["from_animation_number", "upto_animation_number"]:
+ fw_config[opt] = default.getint(opt)
+ if fw_config["upto_animation_number"] == -1:
+ fw_config["upto_animation_number"] = float("inf")
+ nflag = args.from_animation_number
+ if nflag is not None:
+ if "," in nflag:
+ start, end = nflag.split(",")
+ fw_config["from_animation_number"] = int(start)
+ fw_config["upto_animation_number"] = int(end)
+ else:
+ fw_config["from_animation_number"] = int(nflag)
- Parameters
- ----------
- subparsers : :class:`argparse._SubParsersAction`
- The subparser object for which to add the sub-subparser for the cfg subcommand.
+ # Handle the --dry_run flag. This flag determines which section
+ # to use from the .cfg file. All options involved are boolean.
+ # Note this overrides the flags -w, -s, -a, -g, and -i.
+ if args.dry_run:
+ for opt in [
+ "write_to_movie",
+ "save_last_frame",
+ "save_pngs",
+ "save_as_gif",
+ "write_all",
+ ]:
+ fw_config[opt] = parser["dry_run"].getboolean(opt)
+ if not fw_config["write_to_movie"]:
+ fw_config["disable_caching"] = True
+ # Read in the streaming section -- all values are strings
+ fw_config["streaming"] = {
+ opt: parser["streaming"][opt]
+ for opt in [
+ "live_stream_name",
+ "twitch_stream_key",
+ "streaming_protocol",
+ "streaming_ip",
+ "streaming_protocol",
+ "streaming_client",
+ "streaming_port",
+ "streaming_port",
+ "streaming_console_banner",
+ ]
+ }
- Returns
- -------
- :class:`argparse.ArgumentParser`
- The parser that parser anything cfg subcommand related.
- """
- cfg_related = subparsers.add_parser(
- "cfg",
- )
- cfg_subparsers = cfg_related.add_subparsers(dest="cfg_subcommand")
+ # 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")
+ # Parse the verbosity flag to read in the log level
+ verbosity = getattr(args, "verbosity")
+ verbosity = default["verbosity"] if verbosity is None else verbosity
+ fw_config["verbosity"] = verbosity
+ logger.setLevel(verbosity)
- cfg_write_parser = cfg_subparsers.add_parser("write")
- cfg_write_parser.add_argument(
- "--level",
- choices=["user", "cwd"],
- default=None,
- help="Specify if this config is for user or just the working directory.",
- )
- cfg_write_parser.add_argument(
- "--open", action="store_const", const=True, default=False
+ # Parse the ffmpeg log level in the config
+ ffmpeg_loglevel = parser["ffmpeg"].get("loglevel", None)
+ fw_config["ffmpeg_loglevel"] = (
+ constants.FFMPEG_VERBOSITY_MAP[verbosity]
+ if ffmpeg_loglevel is None
+ else ffmpeg_loglevel
)
- cfg_subparsers.add_parser("show")
- cfg_export_parser = cfg_subparsers.add_parser("export")
- cfg_export_parser.add_argument("--dir", default=os.getcwd())
+ # Parse the progress_bar flag
+ progress_bar = getattr(args, "progress_bar")
+ if progress_bar is None:
+ progress_bar = default.getboolean("progress_bar")
+ fw_config["progress_bar"] = progress_bar
- return cfg_related
+ global file_writer_config
+ file_writer_config.update(fw_config)
def _determine_quality(args):
@@ -655,20 +668,42 @@ def _determine_quality(args):
"l": "low_quality",
}
- for quality in constants.QUALITIES.keys():
+ 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) or (
+ elif getattr(args, quality, None) or (
hasattr(args, "quality") and args.quality == constants.QUALITIES[quality]
):
return quality
- for quality in old_qualities.keys():
- if getattr(args, quality):
- logging.getLogger("manim").warning(
+ for quality in old_qualities:
+ if getattr(args, quality, None):
+ logger.warning(
f"Option -{quality} is deprecated please use the --quality/-q flag."
)
return old_qualities[quality]
return constants.DEFAULT_QUALITY
+
+
+def set_file_logger():
+ # Note: The log file name will be
+ # <name_of_animation_file>_<name_of_scene>.log, gotten from
+ # file_writer_config. So it can differ from the real name of the scene.
+ # <name_of_scene> would only appear if scene name was provided when manim
+ # was called.
+ scene_name_suffix = "".join(file_writer_config["scene_names"])
+ scene_file_name = os.path.basename(file_writer_config["input_file"]).split(".")[0]
+ log_file_name = (
+ f"{scene_file_name}_{scene_name_suffix}.log"
+ if scene_name_suffix
+ else f"{scene_file_name}.log"
+ )
+ log_file_path = os.path.join(file_writer_config["log_dir"], log_file_name)
+
+ file_handler = logging.FileHandler(log_file_path, mode="w")
+ file_handler.setFormatter(JSONFormatter())
+
+ logger.addHandler(file_handler)
+ logger.info("Log file will be saved in %(logpath)s", {"logpath": log_file_path})
diff --git a/manim/config/utils.py b/manim/config/utils.py
new file mode 100644
index 000000000..e3354329b
--- /dev/null
+++ b/manim/config/utils.py
@@ -0,0 +1,270 @@
+"""
+utils.py
+--------
+
+Functions to create the logger and config.
+
+"""
+
+import os
+import sys
+import logging
+from pathlib import Path
+import configparser
+import json
+import copy
+
+import colour
+from rich.console import Console
+from rich.logging import RichHandler
+from rich.theme import Theme
+from rich import print as printf
+from rich import errors, color
+
+from .. import constants
+from ..utils.tex import TexTemplate, TexTemplateFromFile
+
+HIGHLIGHTED_KEYWORDS = [ # these keywords are highlighted specially
+ "Played",
+ "animations",
+ "scene",
+ "Reading",
+ "Writing",
+ "script",
+ "arguments",
+ "Invalid",
+ "Aborting",
+ "module",
+ "File",
+ "Rendering",
+ "Rendered",
+]
+
+WRONG_COLOR_CONFIG_MSG = """
+[logging.level.error]Your colour configuration couldn't be parsed.
+Loading the default color configuration.[/logging.level.error]
+"""
+
+
+def config_file_paths():
+ library_wide = Path.resolve(Path(__file__).parent / "default.cfg")
+ if sys.platform.startswith("win32"):
+ user_wide = Path.home() / "AppData" / "Roaming" / "Manim" / "manim.cfg"
+ else:
+ user_wide = Path.home() / ".config" / "manim" / "manim.cfg"
+ folder_wide = Path("manim.cfg")
+ return [library_wide, user_wide, folder_wide]
+
+
+def make_config_parser():
+ """Make a ConfigParser object and load the .cfg files."""
+ library_wide, user_wide, folder_wide = config_file_paths()
+ # From the documentation: "An application which requires initial values to
+ # be loaded from a file should load the required file or files using
+ # read_file() before calling read() for any optional files."
+ # https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.read
+ parser = configparser.ConfigParser()
+ with open(library_wide) as file:
+ parser.read_file(file)
+ parser.read([user_wide, folder_wide])
+ return parser
+
+
+def make_logger(parser, verbosity):
+ """Make the manim logger and the console."""
+ # Throughout the codebase, use Console.print() instead of print()
+ theme = parse_theme(parser)
+ console = Console(theme=theme)
+
+ # set the rich handler
+ RichHandler.KEYWORDS = HIGHLIGHTED_KEYWORDS
+ rich_handler = RichHandler(
+ console=console, show_time=parser.getboolean("log_timestamps")
+ )
+ rich_handler.setLevel(verbosity)
+
+ # finally, the logger
+ logger = logging.getLogger("manim")
+ logger.addHandler(rich_handler)
+
+ return logger, console
+
+
+def parse_theme(config_logger):
+ theme = dict(
+ zip(
+ [key.replace("_", ".") for key in config_logger.keys()],
+ list(config_logger.values()),
+ )
+ )
+
+ theme["log.width"] = None if theme["log.width"] == "-1" else int(theme["log.width"])
+
+ theme["log.height"] = (
+ None if theme["log.height"] == "-1" else int(theme["log.height"])
+ )
+ theme["log.timestamps"] = False
+ try:
+ customTheme = Theme(
+ {
+ k: v
+ for k, v in theme.items()
+ if k not in ["log.width", "log.height", "log.timestamps"]
+ }
+ )
+ except (color.ColorParseError, errors.StyleSyntaxError):
+ printf(WRONG_COLOR_CONFIG_MSG)
+ customTheme = None
+
+ return customTheme
+
+
+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",
+ }
+ 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
+
+ # Read in the streaming section -- all values are strings
+ fw_config["streaming"] = {
+ opt: parser["streaming"].get(opt) for opt in parser["streaming"]
+ }
+
+ # 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")
+
+ # 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
+
+
+class JSONFormatter(logging.Formatter):
+ """Subclass of `:class:`logging.Formatter`, to build our own format of the logs (JSON)."""
+
+ def format(self, record):
+ record_c = copy.deepcopy(record)
+ if record_c.args:
+ for arg in record_c.args:
+ record_c.args[arg] = "<>"
+ return json.dumps(
+ {
+ "levelname": record_c.levelname,
+ "module": record_c.module,
+ "message": super().format(record_c),
+ }
+ )
diff --git a/manim/grpc/impl/frame_server_impl.py b/manim/grpc/impl/frame_server_impl.py
index e288142cc..7f16121fa 100644
--- a/manim/grpc/impl/frame_server_impl.py
+++ b/manim/grpc/impl/frame_server_impl.py
@@ -19,7 +19,7 @@ from ...utils.module_ops import (
get_scene_classes_from_module,
get_scenes_to_render,
)
-from ...config.logger import logger
+from ... import logger
from ...constants import JS_RENDERER_INFO
diff --git a/manim/scene/js_scene.py b/manim/scene/js_scene.py
index 80aa682d7..dafa33155 100644
--- a/manim/scene/js_scene.py
+++ b/manim/scene/js_scene.py
@@ -14,7 +14,7 @@ import inspect
import random
import string
import types
-from ..config.logger import logger
+from .. import logger
def get_random_name(name_map):
diff --git a/manim/utils/module_ops.py b/manim/utils/module_ops.py
index d08357280..98bd91079 100644
--- a/manim/utils/module_ops.py
+++ b/manim/utils/module_ops.py
@@ -1,6 +1,6 @@
from .. import constants
from ..config import file_writer_config
-from ..config.logger import logger, console
+from .. import logger, console
import importlib.util
import inspect
import os
diff --git a/tests/control_data/logs_data/BasicSceneLoggingTest.txt b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
index e7595ef9b..96e88341c 100644
--- a/tests/control_data/logs_data/BasicSceneLoggingTest.txt
+++ b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
@@ -1,4 +1,4 @@
-{"levelname": "INFO", "module": "config", "message": "Log file will be saved in <>"}
+{"levelname": "INFO", "module": "main_utils", "message": "Log file will be saved in <>"}
{"levelname": "DEBUG", "module": "hashing", "message": "Hashing ..."}
{"levelname": "DEBUG", "module": "hashing", "message": "Hashing done in <> s."}
{"levelname": "INFO", "module": "scene_file_writer", "message": "Animation 0 : Partial movie file written in <>"}
diff --git a/tests/test_cli_flags.py b/tests/test_cli_flags.py
index 1ed0b17f9..999bb36fa 100644
--- a/tests/test_cli_flags.py
+++ b/tests/test_cli_flags.py
@@ -1,45 +1,45 @@
from manim import constants
-from manim.config.config_utils import _determine_quality, _parse_cli
+from manim.config.main_utils import _determine_quality, parse_args
def test_quality_flags():
# Assert that quality is the default when not specifying it
- parsed = _parse_cli([], False)
+ parsed = parse_args('manim dummy_filename'.split())
assert parsed.quality == constants.DEFAULT_QUALITY_SHORT
assert _determine_quality(parsed) == constants.DEFAULT_QUALITY
for quality in constants.QUALITIES.keys():
# Assert that quality is properly set when using -q*
- arguments = f"-q{constants.QUALITIES[quality]}".split()
- parsed = _parse_cli(arguments, False)
+ 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 that quality is properly set when using -q *
- arguments = f"-q {constants.QUALITIES[quality]}".split()
- parsed = _parse_cli(arguments, False)
+ 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 that quality is properly set when using --quality *
- arguments = f"--quality {constants.QUALITIES[quality]}".split()
- parsed = _parse_cli(arguments, False)
+ arguments = f"manim --quality {constants.QUALITIES[quality]} dummy_filename".split()
+ parsed = parse_args(arguments)
assert parsed.quality == constants.QUALITIES[quality]
assert quality == _determine_quality(parsed)
# Assert that quality is properly set when using -*_quality
- arguments = f"--{quality}".split()
- parsed = _parse_cli(arguments, False)
+ arguments = f"manim --{quality} dummy_filename".split()
+ parsed = parse_args(arguments)
assert getattr(parsed, quality)
assert quality == _determine_quality(parsed)
# Assert that *_quality is False when not specifying it
- parsed = _parse_cli([], False)
+ parsed = parse_args('manim dummy_filename'.split())
assert not getattr(parsed, quality)
assert _determine_quality(parsed) == constants.DEFAULT_QUALITY
diff --git a/tests/test_container.py b/tests/test_container.py
index 5a26b3ba5..4bf8d2753 100644
--- a/tests/test_container.py
+++ b/tests/test_container.py
@@ -1,5 +1,5 @@
import pytest
-from manim import Container, Mobject, Scene
+from manim import Container, Mobject, Scene, file_writer_config
def test_ABC():
diff --git a/tests/test_logging/test_logging.py b/tests/test_logging/test_logging.py
index 4ac424265..f4ae349a3 100644
--- a/tests/test_logging/test_logging.py
+++ b/tests/test_logging/test_logging.py
@@ -1,7 +1,4 @@
-import subprocess
import os
-import sys
-import pytest
import re
from ..utils.commands import capture