A community-maintained Python framework for creating mathematical animations.
Add logger and replace print calls with appropriate logging functions
kilacoda00a786edaa0a
diff --git a/manim/__init__.py b/manim/__init__.pyindex 1185c9c3b..4540a5825 100644--- a/manim/__init__.py+++ b/manim/__init__.py@@ -2,8 +2,7 @@from . import configfrom . import constants--def main():+def main():args = config.parse_cli()cfg = config.get_configuration(args)constants.initialize_directories(cfg)diff --git a/manim/camera/camera.py b/manim/camera/camera.pyindex a0985388f..5a76684b9 100644--- a/manim/camera/camera.py+++ b/manim/camera/camera.py@@ -10,6 +10,7 @@ import cairoimport numpy as npfrom ..constants import *+from ..logger import loggerfrom ..mobject.types.image_mobject import AbstractImageMobjectfrom ..mobject.mobject import Mobjectfrom ..mobject.types.point_cloud_mobject import PMobject@@ -24,7 +25,6 @@ from ..utils.simple_functions import fdivfrom ..utils.space_ops import angle_of_vectorfrom ..utils.space_ops import get_norm-class Camera(object):"""Base Camera class.@@ -348,14 +348,14 @@ class Camera(object):The pixel array which can then be passed to set_background."""- print("Starting set_background; for reference, the current time is ", time.strftime("%H:%M:%S"))+ logger.info("Starting set_background; for reference, the current time is ", time.strftime("%H:%M:%S"))coords = self.get_coords_of_all_pixels()new_background = np.apply_along_axis(coords_to_colors_func,2,coords)- print("Ending set_background; for reference, the current time is ", time.strftime("%H:%M:%S"))+ logger.info("Ending set_background; for reference, the current time is ", time.strftime("%H:%M:%S"))return self.convert_pixel_array(new_background, convert_from_floats=True)diff --git a/manim/config.py b/manim/config.pyindex 1fb2e11ce..972d70f66 100644--- a/manim/config.py+++ b/manim/config.py@@ -5,7 +5,9 @@ import sysimport typesfrom . import constants+from .logger import logger+def parse_cli():try:@@ -133,7 +135,7 @@ def parse_cli():)return parser.parse_args()except argparse.ArgumentError as err:- print(str(err))+ logger.error(str(err))sys.exit(2)@@ -229,8 +231,8 @@ def get_camera_configuration(args):try:camera_config["background_color"] = colour.Color(args.color)except AttributeError as err:- print("Please use a valid color")- print(err)+ logger.warning("Please use a valid color")+ logger.error(err)sys.exit(2)# If rendering a transparent image/move, make sure thediff --git a/manim/constants.py b/manim/constants.pyindex 9ae2163af..0a4f19d20 100644--- a/manim/constants.py+++ b/manim/constants.py@@ -1,5 +1,6 @@import numpy as npimport os+from .logger import loggerMEDIA_DIR = ""VIDEO_DIR = ""@@ -7,7 +8,6 @@ VIDEO_OUTPUT_DIR = ""TEX_DIR = ""TEXT_DIR = ""-def initialize_directories(config):global MEDIA_DIRglobal VIDEO_DIR@@ -27,13 +27,13 @@ def initialize_directories(config):)if not os.path.isdir(MEDIA_DIR):MEDIA_DIR = "./media"- print(+ logger.info(f"Media will be written to {MEDIA_DIR + os.sep}. You can change ""this behavior with the --media_dir flag.")else:if config["media_dir"]:- print(+ logger.warning("Ignoring --media_dir, since both --tex_dir and a video ""directory were both passed")@@ -53,7 +53,6 @@ def initialize_directories(config):os.makedirs(folder)NOT_SETTING_FONT_MSG='''-Warning:You haven't set font.If you are not using English, this may cause text rendering problem.You set font like:diff --git a/manim/extract_scene.py b/manim/extract_scene.pyindex 27f9e1fbd..b6feec706 100644--- a/manim/extract_scene.py+++ b/manim/extract_scene.py@@ -11,6 +11,7 @@ from .scene.scene import Scenefrom .utils.sounds import play_error_soundfrom .utils.sounds import play_finish_soundfrom . import constants+from .logger import loggerdef open_file_if_needed(file_writer, **config):@@ -83,7 +84,7 @@ def prompt_user_for_choice(scene_classes):for num_str in user_input.split(",")]except KeyError:- print(constants.INVALID_NUMBER_MESSAGE)+ logger.error(constants.INVALID_NUMBER_MESSAGE)sys.exit(2)user_input = input(constants.CHOOSE_NUMBER_MESSAGE)return [@@ -96,7 +97,7 @@ def prompt_user_for_choice(scene_classes):def get_scenes_to_render(scene_classes, config):if len(scene_classes) == 0:- print(constants.NO_SCENE_MESSAGE)+ logger.error(constants.NO_SCENE_MESSAGE)return []if config["write_all"]:return scene_classes@@ -109,7 +110,7 @@ def get_scenes_to_render(scene_classes, config):found = Truebreakif not found and (scene_name != ""):- print(+ logger.error(constants.SCENE_NOT_FOUND_MESSAGE.format(scene_name),@@ -141,7 +142,7 @@ def get_module(file_name):exec(code, module.__dict__)return moduleexcept Exception as e:- print(f"Failed to render scene: {str(e)}")+ logger.error(f"Failed to render scene: {str(e)}")sys.exit(2)else:module_name = file_name.replace(os.sep, ".").replace(".py", "")diff --git a/manim/logger.py b/manim/logger.pynew file mode 100644index 000000000..4e4e05b4e--- /dev/null+++ b/manim/logger.py@@ -0,0 +1,12 @@+import logging+from rich.logging import RichHandler++## Setting config for logger.+logging.basicConfig(+ level="NOTSET",+ format="%(message)s",+ datefmt="[%X]",+ handlers=[RichHandler()]+)++logger = logging.getLogger("rich")\ No newline at end of filediff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.pyindex 9736c2d00..1e56ae49d 100644--- a/manim/mobject/svg/text_mobject.py+++ b/manim/mobject/svg/text_mobject.py@@ -5,6 +5,7 @@ import hashlibimport cairofrom ...constants import *from ...container.container import Container+from ...logger import loggerfrom ...mobject.geometry import Dot, Rectanglefrom ...mobject.svg.svg_mobject import SVGMobjectfrom ...mobject.types.vectorized_mobject import VGroup@@ -287,7 +288,7 @@ class Text(SVGMobject):if self.font == '':if NOT_SETTING_FONT_MSG != '':- print(NOT_SETTING_FONT_MSG)+ logger.warning(NOT_SETTING_FONT_MSG)dir_name = TEXT_DIRhash_name = self.text2hash()diff --git a/manim/mobject/vector_field.py b/manim/mobject/vector_field.pyindex 50a5bd82e..774b753ee 100644--- a/manim/mobject/vector_field.py+++ b/manim/mobject/vector_field.py@@ -5,7 +5,7 @@ from PIL import Imageimport randomfrom ..constants import *-+from ..logger import loggerfrom ..animation.composition import AnimationGroupfrom ..animation.indication import ShowPassingFlashfrom ..mobject.geometry import Vector@@ -85,7 +85,7 @@ def get_color_field_image_file(scalar_func,file_name = "%d.png" % func_hashfull_path = os.path.join(RASTER_IMAGE_DIR, file_name)if not os.path.exists(full_path):- print("Rendering color field image " + str(func_hash))+ logger.info("Rendering color field image " + str(func_hash))rgb_gradient_func = get_rgb_gradient_function(min_value=min_value,max_value=max_value,diff --git a/manim/scene/scene.py b/manim/scene/scene.pyindex 1dac19dfd..ce24579c4 100644--- a/manim/scene/scene.py+++ b/manim/scene/scene.py@@ -11,6 +11,7 @@ from ..animation.transform import MoveToTarget, ApplyMethodfrom ..camera.camera import Camerafrom ..constants import *from ..container.container import Container+from ..logger import loggerfrom ..mobject.mobject import Mobjectfrom ..scene.scene_file_writer import SceneFileWriterfrom ..utils.iterables import list_update@@ -110,7 +111,7 @@ class Scene(Container):Used internally to print the number ofanimations played after the scene ends."""- print("Played {} animations".format(self.num_plays))+ logger.info("Played {} animations".format(self.num_plays))def set_variables_as_attrs(self, *objects, **newly_named_objects):"""diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.pyindex d68dc33cb..9cbc61cb5 100644--- a/manim/scene/scene_file_writer.py+++ b/manim/scene/scene_file_writer.py@@ -14,6 +14,7 @@ from ..constants import STREAMING_PORTfrom ..constants import STREAMING_PROTOCOLfrom ..constants import VIDEO_DIRfrom ..constants import VIDEO_OUTPUT_DIR+from ..logger import loggerfrom ..utils.config_ops import digest_configfrom ..utils.file_ops import guarantee_existencefrom ..utils.file_ops import add_extension_if_not_present@@ -473,7 +474,7 @@ class SceneFileWriter(object):**kwargs)if len(partial_movie_files) == 0:- print("No animations in this scene")+ logger.error("No animations in this scene")return# Write a file partial_file_list.txt containing all@@ -542,4 +543,4 @@ class SceneFileWriter(object):"""Prints the "File Ready" message to STDOUT."""- print("\nFile ready at {}\n".format(file_path))+ logger.info("\nFile ready at {}\n".format(file_path))diff --git a/manim/scene/scene_from_video.py b/manim/scene/scene_from_video.pyindex ba3e6562e..170c6f016 100644--- a/manim/scene/scene_from_video.py+++ b/manim/scene/scene_from_video.py@@ -2,6 +2,7 @@ from tqdm import tqdm as show_progressimport cv2from ..scene.scene import Scene+from ..logger import logger# TODO, is this depricated?@@ -24,7 +25,7 @@ class SceneFromVideo(Scene):start_frame, end_frame = [fps * t for t in time_range]frame_count = end_frame - start_frame- print("Reading in " + file_name + "...")+ logger.info("Reading in " + file_name + "...")for count in show_progress(list(range(start_frame, end_frame + 1))):returned, frame = cap.read()if not returned:diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.pyindex 4e166b74a..d781f1797 100644--- a/manim/utils/tex_file_writing.py+++ b/manim/utils/tex_file_writing.py@@ -6,6 +6,7 @@ from pathlib import Pathfrom ..constants import TEX_TEXT_TO_REPLACEfrom ..constants import TEX_USE_CTEXfrom ..constants import TEX_DIR+from ..logger import loggerdef tex_hash(expression, template_tex_file_body):@@ -28,7 +29,7 @@ def generate_tex_file(expression, template_tex_file_body):tex_hash(expression, template_tex_file_body)) + ".tex"if not os.path.exists(result):- print("Writing \"%s\" to %s" % (+ logger.info("Writing \"%s\" to %s" % ("".join(expression), result))new_body = template_tex_file_body.replace(diff --git a/requirements.txt b/requirements.txtindex 9b54f76ae..7dec25c9b 100644--- a/requirements.txt+++ b/requirements.txt@@ -9,4 +9,5 @@ opencv-pythonpycairopydubpygments-pyreadline; sys_platform == 'win32'+pyreadline; sys_platform == 'win32',+richdiff --git a/setup.py b/setup.pyindex 688d12981..51b827981 100755--- a/setup.py+++ b/setup.py@@ -26,5 +26,6 @@ setup("pydub","pygments","pyreadline; sys_platform == 'win32'",+ "rich"],)