Skip to content

armgit / manim

Public Imported from GitHub
0

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__.py
index 1185c9c3b..4540a5825 100644
--- a/manim/__init__.py
+++ b/manim/__init__.py
@@ -2,8 +2,7 @@
from . import config
from . 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.py
index a0985388f..5a76684b9 100644
--- a/manim/camera/camera.py
+++ b/manim/camera/camera.py
@@ -10,6 +10,7 @@ import cairo
import numpy as np
from ..constants import *
+from ..logger import logger
from ..mobject.types.image_mobject import AbstractImageMobject
from ..mobject.mobject import Mobject
from ..mobject.types.point_cloud_mobject import PMobject
@@ -24,7 +25,6 @@ from ..utils.simple_functions import fdiv
from ..utils.space_ops import angle_of_vector
from ..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.py
index 1fb2e11ce..972d70f66 100644
--- a/manim/config.py
+++ b/manim/config.py
@@ -5,7 +5,9 @@ import sys
import types
from . 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 the
diff --git a/manim/constants.py b/manim/constants.py
index 9ae2163af..0a4f19d20 100644
--- a/manim/constants.py
+++ b/manim/constants.py
@@ -1,5 +1,6 @@
import numpy as np
import os
+from .logger import logger
MEDIA_DIR = ""
VIDEO_DIR = ""
@@ -7,7 +8,6 @@ VIDEO_OUTPUT_DIR = ""
TEX_DIR = ""
TEXT_DIR = ""
-
def initialize_directories(config):
global MEDIA_DIR
global 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.py
index 27f9e1fbd..b6feec706 100644
--- a/manim/extract_scene.py
+++ b/manim/extract_scene.py
@@ -11,6 +11,7 @@ from .scene.scene import Scene
from .utils.sounds import play_error_sound
from .utils.sounds import play_finish_sound
from . import constants
+from .logger import logger
def 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 = True
break
if 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 module
except 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.py
new file mode 100644
index 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 file
diff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.py
index 9736c2d00..1e56ae49d 100644
--- a/manim/mobject/svg/text_mobject.py
+++ b/manim/mobject/svg/text_mobject.py
@@ -5,6 +5,7 @@ import hashlib
import cairo
from ...constants import *
from ...container.container import Container
+from ...logger import logger
from ...mobject.geometry import Dot, Rectangle
from ...mobject.svg.svg_mobject import SVGMobject
from ...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_DIR
hash_name = self.text2hash()
diff --git a/manim/mobject/vector_field.py b/manim/mobject/vector_field.py
index 50a5bd82e..774b753ee 100644
--- a/manim/mobject/vector_field.py
+++ b/manim/mobject/vector_field.py
@@ -5,7 +5,7 @@ from PIL import Image
import random
from ..constants import *
-
+from ..logger import logger
from ..animation.composition import AnimationGroup
from ..animation.indication import ShowPassingFlash
from ..mobject.geometry import Vector
@@ -85,7 +85,7 @@ def get_color_field_image_file(scalar_func,
file_name = "%d.png" % func_hash
full_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.py
index 1dac19dfd..ce24579c4 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -11,6 +11,7 @@ from ..animation.transform import MoveToTarget, ApplyMethod
from ..camera.camera import Camera
from ..constants import *
from ..container.container import Container
+from ..logger import logger
from ..mobject.mobject import Mobject
from ..scene.scene_file_writer import SceneFileWriter
from ..utils.iterables import list_update
@@ -110,7 +111,7 @@ class Scene(Container):
Used internally to print the number of
animations 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.py
index 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_PORT
from ..constants import STREAMING_PROTOCOL
from ..constants import VIDEO_DIR
from ..constants import VIDEO_OUTPUT_DIR
+from ..logger import logger
from ..utils.config_ops import digest_config
from ..utils.file_ops import guarantee_existence
from ..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.py
index 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_progress
import cv2
from ..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.py
index 4e166b74a..d781f1797 100644
--- a/manim/utils/tex_file_writing.py
+++ b/manim/utils/tex_file_writing.py
@@ -6,6 +6,7 @@ from pathlib import Path
from ..constants import TEX_TEXT_TO_REPLACE
from ..constants import TEX_USE_CTEX
from ..constants import TEX_DIR
+from ..logger import logger
def 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.txt
index 9b54f76ae..7dec25c9b 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -9,4 +9,5 @@ opencv-python
pycairo
pydub
pygments
-pyreadline; sys_platform == 'win32'
+pyreadline; sys_platform == 'win32',
+rich
diff --git a/setup.py b/setup.py
index 688d12981..51b827981 100755
--- a/setup.py
+++ b/setup.py
@@ -26,5 +26,6 @@ setup(
"pydub",
"pygments",
"pyreadline; sys_platform == 'win32'",
+ "rich"
],
)