A community-maintained Python framework for creating mathematical animations.
Some slight formatting changes
Syrus Darkdd890aa4fcab
diff --git a/manim/cfgwriter/__main__.py b/manim/cfgwriter/__main__.pyindex 6eeb24d20..8df700366 100644--- a/manim/cfgwriter/__main__.py+++ b/manim/cfgwriter/__main__.py@@ -6,7 +6,7 @@ from rich.color import Colordef check_valid_colour(color):- '''Checks whether the entered color is a valid color according to rich+ """Checks whether the entered color is a valid color according to richParameters----------color : :class:`str`@@ -15,45 +15,60 @@ def check_valid_colour(color):-------BooleanReturns whether it is valid color or not.- '''+ """try:Color.parse(color) is Nonereturn Trueexcept:return False++def main():console = Console()config = configparser.ConfigParser()- config.read('manim.cfg')- default={"logging.keyword":"bold yellow",- "logging.level.notset":"dim",- "logging.level.debug":"green",- "logging.level.info":"blue",- "logging.level.warning":"red",+ config.read("manim.cfg")+ default = {+ "logging.keyword": "bold yellow",+ "logging.level.notset": "dim",+ "logging.level.debug": "green",+ "logging.level.info": "blue",+ "logging.level.warning": "red","logging.level.error": "red bold","logging.level.critical": "red bold reverse",- "log.level":"",+ "log.level": "","log.time": "cyan dim","log.message": "","log.path": "dim",- }- console.print("[yellow bold]Manim Logger Configuration Editor[/yellow bold]",justify="center")- console.print("[red]The default colour is shown as input Statement.\nIf left empty default value will be assigned.[/red]")- console.print("[magenta]Please follow the link for available styles.[/magenta][link=https://rich.readthedocs.io/en/latest/style.html]docs[/link]")+ }+ console.print(+ "[yellow bold]Manim Logger Configuration Editor[/yellow bold]", justify="center"+ )+ console.print(+ "[red]The default colour is shown as input Statement.\nIf left empty default value will be assigned.[/red]"+ )+ console.print(+ "[magenta]Please follow the link for available styles.[/magenta][link=https://rich.readthedocs.io/en/latest/style.html]docs[/link]"+ )for key in default:- console.print('Enter the Style for %s'%key+':',style=key,end='')- temp=input()+ console.print("Enter the Style for %s" % key + ":", style=key, end="")+ temp = input()if temp:- while check_valid_colour(temp)==False:- console.print("[red bold]Your Style is not valid. Try again.[/red bold]")- console.print('Enter the Style for %s'%key+':',style=key,end='')- temp=input()+ while check_valid_colour(temp) == False:+ console.print(+ "[red bold]Your Style is not valid. Try again.[/red bold]"+ )+ console.print("Enter the Style for %s" % key + ":", style=key, end="")+ temp = input()else:- default[key]=temp- config['log.color']=default+ default[key] = temp+ config["log.color"] = defaultfor n in track(range(100), description="Converting to Manim.cfg"):- with open("manim.cfg","w") as fp:+ with open("manim.cfg", "w") as fp:config.write(fp)- console.print("A file called [yellow]manim.cfg[/yellow] is created. To save your theme please save that file and each time \nplace it in you current working directory(The directory where you execute manim command) for the your theme to be displayed.")-if __name__=="__main__":- main()\ No newline at end of file+ console.print(+ "A file called [yellow]manim.cfg[/yellow] is created. To save your theme please save that file and each time \nplace it in you current working directory(The directory where you execute manim command) for the your theme to be displayed."+ )+++if __name__ == "__main__":+ main()diff --git a/manim/config.py b/manim/config.pyindex dfbb97c86..867c5dea7 100644--- a/manim/config.py+++ b/manim/config.py@@ -1,28 +1,38 @@-from .logger import logger-from .config_utils import config_parser,successfully_read_files,file_writer_config,args,_init_dirs-import sysimport os-from . import constants-from .utils.tex import TexTemplateFromFile, TexTemplate+import sys+import colour+from . import constants+from .config_utils import (+ _init_dirs,+ args,+ config_parser,+ file_writer_config,+ successfully_read_files,+)+from .logger import logger+from .utils.tex import TexTemplate, TexTemplateFromFile+__all__ = ["config", "camera_config"]-logger.info(f'Read configuration files: {successfully_read_files}')+logger.info(f"Read configuration files: {successfully_read_files}")++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']+ 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.- for flag in ['fourk_quality', 'high_quality', 'medium_quality', 'low_quality']:+ for flag in ["fourk_quality", "high_quality", "medium_quality", "low_quality"]:if getattr(args, flag):section = config_parser[flag]breakelse:- section = config_parser['CLI']+ section = config_parser["CLI"]config = {opt: section.getint(opt) for opt in config_parser[flag]}# The -r, --resolution flag overrides the *_quality flags@@ -32,37 +42,36 @@ def _parse_config(config_parser, args):height, width = int(height_str), int(width_str)else:height, width = int(args.resolution), int(16 * height / 9)- config['camera_config'].update({'pixel_height': height,- 'pixel_width': width})+ config["camera_config"].update({"pixel_height": height, "pixel_width": width})# Handle the -c (--color) flagif args.color is not None:try:background_color = colour.Color(args.color)except AttributeError as err:- logger.warning('Please use a valid color.')+ 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+ background_color = colour.Color(default["background_color"])+ config["background_color"] = background_color# 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+ 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. Note we accept None if the flag is absent- filename = (os.path.expanduser(args.tex_template)- if args.tex_template is not None- else None)+ filename = (+ os.path.expanduser(args.tex_template) if args.tex_template is not None else None+ )if filename is not None and not os.access(filename, os.R_OK):# custom template not available, fallback to default@@ -71,15 +80,18 @@ def _parse_config(config_parser, args):"Falling back to the default template.")filename = None- config['tex_template_file'] = filename- config['tex_template'] = (TexTemplateFromFile(filename=filename)- if filename is not None- else TexTemplate())+ config["tex_template_file"] = filename+ config["tex_template"] = (+ TexTemplateFromFile(filename=filename)+ if filename is not None+ else TexTemplate()+ )return config+# this is for the userconfig = _parse_config(config_parser, args)camera_config = config-_init_dirs(file_writer_config)\ No newline at end of file+_init_dirs(file_writer_config)diff --git a/manim/config_utils.py b/manim/config_utils.pyindex 4f4c85840..c32702eac 100644--- a/manim/config_utils.py+++ b/manim/config_utils.py@@ -7,126 +7,144 @@ config object."""-import os-import sysimport argparseimport configparser+import os+import sys+import colour-from .utils.tex import TexTemplateFromFile, TexTemplate+from . import constants+from .utils.tex import TexTemplate, TexTemplateFromFile__all__ = ["file_writer_config"]---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']+ default = config_parser["CLI"]# This will be the final config dict exposed to the userconfig = {}# Handle input files and scenes. Note these cannot be set from# the .cfg files, only from CLI arguments- config['input_file'] = args.file- config['scene_names'] = (args.scene_names- if args.scene_names is not None else [])- config['output_file'] = args.output_file+ config["input_file"] = args.file+ config["scene_names"] = args.scene_names if args.scene_names is not None else []+ config["output_file"] = args.output_file# 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_file_in_finder', 'quiet', 'sound',- 'leave_progress_bars', 'write_to_movie', 'save_last_frame',- 'save_pngs', 'save_as_gif', 'write_all']:+ for boolean_opt in [+ "preview",+ "show_file_in_finder",+ "quiet",+ "sound",+ "leave_progress_bars",+ "write_to_movie",+ "save_last_frame",+ "save_pngs",+ "save_as_gif",+ "write_all",+ ]:attr = getattr(args, boolean_opt)- config[boolean_opt] = (default.getboolean(boolean_opt)- if attr is None else attr)+ 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']:+ for str_opt in ["media_dir"]:attr = getattr(args, str_opt)- config[str_opt] = (default[str_opt] if attr is None else attr)- dir_names = {'video_dir': 'videos',- 'tex_dir': 'Tex',- 'text_dir': 'texts'}+ config[str_opt] = default[str_opt] if attr is None else attr+ dir_names = {"video_dir": "videos", "tex_dir": "Tex", "text_dir": "texts"}for name in dir_names:- config[name] = os.path.join(config['media_dir'], dir_names[name])+ config[name] = os.path.join(config["media_dir"], dir_names[name])# 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 config['save_last_frame']:- config['write_to_movie'] = False+ if config["save_last_frame"]:+ config["write_to_movie"] = False# 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']:+ section = config_parser["transparent"] if args.transparent else default+ for opt in ["png_mode", "movie_file_extension", "background_opacity"]: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']:+ for opt in ["from_animation_number", "upto_animation_number"]:config[opt] = default.getint(opt)- if config['upto_animation_number'] == -1:- config['upto_animation_number'] = float('inf')+ if config["upto_animation_number"] == -1:+ config["upto_animation_number"] = float("inf")nflag = args.from_animation_numberif nflag is not None:- if ',' in nflag:- start, end = nflag.split(',')- config['from_animation_number'] = int(start)- config['upto_animation_number'] = int(end)+ if "," in nflag:+ start, end = nflag.split(",")+ config["from_animation_number"] = int(start)+ config["upto_animation_number"] = int(end)else:- config['from_animation_number'] = int(nflag)+ config["from_animation_number"] = int(nflag)# 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']:- config[opt] = config_parser['dry_run'].getboolean(opt)+ for opt in [+ "write_to_movie",+ "save_last_frame",+ "save_pngs",+ "save_as_gif",+ "write_all",+ ]:+ config[opt] = config_parser["dry_run"].getboolean(opt)# Read in the streaming section -- all values are strings- 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']}+ 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)- config['skip_animations'] = any([config['save_last_frame'],- config['from_animation_number']])+ config["skip_animations"] = any(+ [config["save_last_frame"], config["from_animation_number"]]+ )return configdef _parse_cli(arg_list, input=True):parser = argparse.ArgumentParser(- description='Animation engine for explanatory math videos',- epilog='Made with ❤ by the manim community devs'+ description="Animation engine for explanatory math videos",+ epilog="Made with ❤ by the manim community devs",)if input:parser.add_argument(- "file",- help="path to file holding the python code for the scene",+ "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=[''],+ default=[""],)parser.add_argument(- "-o", "--output_file",+ "-o",+ "--output_file",help="Specify the name of the output file, if"- "it should be different from the scene class name",- default='',+ "it should be different from the scene class name",+ default="",)# The following use (action='store_const', const=True) instead of@@ -135,22 +153,21 @@ def _parse_cli(arg_list, input=True):# default value. Since we want to set the default value in# manim.cfg rather than here, we use the former.parser.add_argument(- "-p", "--preview",+ "-p",+ "--preview",action="store_const",const=True,help="Automatically open the saved file once its done",)parser.add_argument(- "-f", "--show_file_in_finder",+ "-f",+ "--show_file_in_finder",action="store_const",const=True,help="Show the output file in finder",)parser.add_argument(- "-q", "--quiet",- action="store_const",- const=True,- help="Quiet mode",+ "-q", "--quiet", action="store_const", const=True, help="Quiet mode",)parser.add_argument("--sound",@@ -165,31 +182,36 @@ def _parse_cli(arg_list, input=True):help="Leave progress bars displayed in terminal",)parser.add_argument(- "-a", "--write_all",+ "-a",+ "--write_all",action="store_const",const=True,help="Write all the scenes from a file",)parser.add_argument(- "-w", "--write_to_movie",+ "-w",+ "--write_to_movie",action="store_const",const=True,help="Render the scene as a movie file",)parser.add_argument(- "-s", "--save_last_frame",+ "-s",+ "--save_last_frame",action="store_const",const=True,help="Save the last frame (and do not save movie)",)parser.add_argument(- "-g", "--save_pngs",+ "-g",+ "--save_pngs",action="store_const",const=True,help="Save each frame as a png",)parser.add_argument(- "-i", "--save_as_gif",+ "-i",+ "--save_as_gif",action="store_const",const=True,help="Save the video as gif",@@ -197,16 +219,13 @@ def _parse_cli(arg_list, input=True):# The default value of the following is set in manim.cfgparser.add_argument(- "-c", "--color",- help="Background color",+ "-c", "--color", help="Background color",)parser.add_argument(- "--background_opacity",- help="Background opacity",+ "--background_opacity", help="Background opacity",)parser.add_argument(- "--media_dir",- help="directory to write media",+ "--media_dir", help="directory to write media",)# video_group = parser.add_mutually_exclusive_group()# video_group.add_argument(@@ -222,8 +241,7 @@ def _parse_cli(arg_list, input=True):# help="directory to write text",# )parser.add_argument(- "--tex_template",- help="Specify a custom TeX template file",+ "--tex_template", help="Specify a custom TeX template file",)# All of the following use (action="store_true"). This means that@@ -242,7 +260,8 @@ def _parse_cli(arg_list, input=True):# The following overrides PNG_MODE, MOVIE_FILE_EXTENSION, and# BACKGROUND_OPACITYparser.add_argument(- "-t", "--transparent",+ "-t",+ "--transparent",action="store_true",help="Render to a movie file with an alpha channel",)@@ -250,45 +269,48 @@ def _parse_cli(arg_list, input=True):# The following are mutually exclusive and each overrides# FRAME_RATE, PIXEL_HEIGHT, and PIXEL_WIDTH,parser.add_argument(- "-l", "--low_quality",+ "-l",+ "--low_quality",action="store_true",help="Render at low quality (for fastest rendering)",)parser.add_argument(- "-m", "--medium_quality",+ "-m",+ "--medium_quality",action="store_true",help="Render at medium quality (for much faster rendering)",)parser.add_argument(- "-e", "--high_quality",+ "-e",+ "--high_quality",action="store_true",help="Render at high quality (for slightly faster rendering)",)parser.add_argument(- "-k", "--fourk_quality",+ "-k",+ "--fourk_quality",action="store_true",help="Render at 4K quality (slower rendering)",)# This overrides any of the aboveparser.add_argument(- "-r", "--resolution",- help="Resolution, passed as \"height,width\"",+ "-r", "--resolution", help='Resolution, passed as "height,width"',)# This sets FROM_ANIMATION_NUMBER and UPTO_ANIMATION_NUMBERparser.add_argument(- "-n", "--from_animation_number",+ "-n",+ "--from_animation_number",help="Start rendering not from the first animation, but"- "from another, specified by its index. If you pass"- "in two comma separated values, e.g. \"3,6\", it will end"- "the rendering at the second value",+ "from another, specified by its index. If you pass"+ 'in two comma separated values, e.g. "3,6", it will end'+ "the rendering at the second value",)# Specify the manim.cfg fileparser.add_argument(- "--config_file",- help="Specify the configuration file",+ "--config_file", help="Specify the configuration file",)return parser.parse_args(arg_list)@@ -296,8 +318,12 @@ def _parse_cli(arg_list, input=True):def _init_dirs(config):# Make sure all folders exist- for folder in [config["media_dir"], config["video_dir"],- config["tex_dir"], config["text_dir"]]:+ for folder in [+ config["media_dir"],+ config["video_dir"],+ config["tex_dir"],+ config["text_dir"],+ ]:if not os.path.exists(folder):os.makedirs(folder)@@ -307,22 +333,22 @@ def _from_command_line():# Manim can be called from the command line in three different# ways. The first two involve using the manim or manimcm commandsprog = os.path.split(sys.argv[0])[-1]- from_cli_command = prog in ['manim', 'manimcm']+ from_cli_command = prog in ["manim", "manimcm"]# 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'+ from_python_m = sys.argv[0] == "-m"return from_cli_command or from_python_m# Config files to be parsed, in ascending priority-library_wide = os.path.join(os.path.dirname(__file__), 'default.cfg')+library_wide = os.path.join(os.path.dirname(__file__), "default.cfg")config_files = [library_wide,- os.path.expanduser('~/.manim.cfg'),+ os.path.expanduser("~/.manim.cfg"),]if _from_command_line():@@ -333,7 +359,9 @@ if _from_command_line():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')+ 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)@@ -341,7 +369,7 @@ 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 = '', '', ''+ args.file, args.scene_names, args.output_file = "", "", ""config_parser = configparser.ConfigParser()successfully_read_files = config_parser.read(config_files)diff --git a/manim/logger.py b/manim/logger.pyindex 9919f3ca2..0a15daeb9 100644--- a/manim/logger.py+++ b/manim/logger.py@@ -4,7 +4,9 @@ import loggingfrom rich.console import Consolefrom rich.logging import RichHandlerfrom rich.theme import Theme-from .config_utils import config_parser,successfully_read_files++from .config_utils import config_parser, successfully_read_files+def parseTheme(fp):config_parser.read(fp)@@ -12,13 +14,14 @@ def parseTheme(fp):customTheme = Theme(theme)return customTheme+try:customTheme = parseTheme(successfully_read_files)console = Console(theme=customTheme)except KeyError:console = Console()-#These keywords Are Highlighted specially.+# These keywords Are Highlighted specially.RichHandler.KEYWORDS = ["Played","animations",