A community-maintained Python framework for creating mathematical animations.
Refactored logs and added log-to-json feature (removed the old log-to-file feature), added logging test utils. (#403)
Hugues Devimeux50c504f094c2
diff --git a/docs/source/changelog.rst b/docs/source/changelog.rstindex 1c5de6219..dc06363cb 100644--- a/docs/source/changelog.rst+++ b/docs/source/changelog.rst@@ -89,6 +89,8 @@ Of interest to developers#. Added autogenerated documentation with sphinx and autodoc/autosummary [WIP]#. Made manim internally use relative imports#. Since the introduction of the :code:`TexTemplate` class, the files :code:`tex_template.tex` and :code:`ctex_template.tex` have been removed+#. Added logging tests tools.+#. Added ability to save logs in json#. Move to Poetry.Other Changesdiff --git a/manim/__main__.py b/manim/__main__.pyindex 4952d415e..88017b1c4 100644--- a/manim/__main__.py+++ b/manim/__main__.py@@ -14,6 +14,7 @@ from .config import cfg_subcmdsfrom .scene.scene import Scenefrom .utils.sounds import play_error_sound, play_finish_soundfrom .utils.file_ops import open_file as open_media_file+from . import constantsdef open_file_if_needed(file_writer):diff --git a/manim/config/config.py b/manim/config/config.pyindex c1f0936e5..a44222386 100644--- a/manim/config/config.py+++ b/manim/config/config.py@@ -18,9 +18,11 @@ import colourfrom .. import constantsfrom .config_utils import _run_config, _init_dirs, _from_command_line-from .logger import logger+from .logger import set_rich_logger, set_file_logger, loggerfrom ..utils.tex import TexTemplate, TexTemplateFromFile+__all__ = ["file_writer_config", "config", "camera_config", "tempconfig"]+config = None@@ -150,3 +152,14 @@ if _from_command_line():_init_dirs(file_writer_config)config = _parse_config(config_parser, args)camera_config = config++# Set the different loggers+set_rich_logger(config_parser["logger"], file_writer_config["verbosity"])+if file_writer_config["log_to_file"]:+ # IMPORTANT note about file name : The log file name will be the scene_name get from the args (contained in file_writer_config). So it can differ from the real name of the scene.+ log_file_path = os.path.join(+ file_writer_config["log_dir"],+ "".join(file_writer_config["scene_names"]) + ".log",+ )+ set_file_logger(log_file_path)+ logger.info("Log file wil be saved in %(logpath)s", {"logpath": log_file_path})diff --git a/manim/config/config_utils.py b/manim/config/config_utils.pyindex 0254bcf84..5dab16a37 100644--- a/manim/config/config_utils.py+++ b/manim/config/config_utils.py@@ -69,9 +69,15 @@ def _parse_file_writer_config(config_parser, args):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", "log_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",diff --git a/manim/config/default.cfg b/manim/config/default.cfgindex 0b4fb6096..d864da45c 100644--- a/manim/config/default.cfg+++ b/manim/config/default.cfg@@ -75,8 +75,8 @@ upto_animation_number = -1# as well as Tex and texts.media_dir = ./media-# --log_dir-log_dir = %(media_dir)s/logs+# --log_dir (by default "/logs", that will be put inside the media dir)+log_dir = logs# If the -t (--transparent) flag is used, these will be replaced with the# values specified in the [TRANSPARENT] section later in this file.diff --git a/manim/config/logger.py b/manim/config/logger.pyindex 46f8af97e..4ca7ee2eb 100644--- a/manim/config/logger.py+++ b/manim/config/logger.py@@ -18,16 +18,33 @@ from rich.logging import RichHandlerfrom rich.theme import Themefrom rich import print as printffrom rich import errors, color+import json+import copy-from .config_utils import _run_config+class JSONFormatter(logging.Formatter):+ """Subclass of `:class:`logging.Formatter`, to build our own format of the logs (JSON)."""-def parse_theme(fp):- config_parser.read(fp)- theme = dict(config_parser["logger"])- # replaces `_` by `.` as rich understands it+ 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 theme.keys()], list(theme.values()))+ 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"])@@ -35,7 +52,7 @@ def parse_theme(fp):theme["log.height"] = (None if theme["log.height"] == "-1" else int(theme["log.height"]))- theme["log.timestamps"] = config_parser["logger"].getboolean("log.timestamps")+ theme["log.timestamps"] = Falsetry:customTheme = Theme({@@ -49,51 +66,54 @@ def parse_theme(fp):printf("[logging.level.error]It seems your colour configuration couldn't be parsed. Loading the default color configuration...[/logging.level.error]")- return customTheme, theme---config_items = _run_config()-config_parser, successfully_read_files = config_items[1], config_items[-1]-try:- customTheme, themedict = parse_theme(successfully_read_files)- console = Console(- theme=customTheme,- record=True,- height=themedict["log.height"],- width=themedict["log.width"],- )-except KeyError:- console = Console(record=True)- printf(- "[logging.level.warning]No cfg file found, creating one in "- + successfully_read_files[0]- + " [/logging.level.warning]"+ 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)+-# These keywords Are Highlighted specially.-RichHandler.KEYWORDS = [- "Played",- "animations",- "scene",- "Reading",- "Writing",- "script",- "arguments",- "Invalid",- "Aborting",- "module",- "File",- "Rendering",- "Rendered",-]-logging.basicConfig(- level="NOTSET",- format="%(message)s",- datefmt="[%X]",- handlers=[RichHandler(console=console, show_time=themedict["log.timestamps"])],-)--logger = logging.getLogger("rich")+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 plotslogging.getLogger("PIL").setLevel(logging.INFO)diff --git a/manim/scene/scene.py b/manim/scene/scene.pyindex 951dc8d81..94e14402e 100644--- a/manim/scene/scene.py+++ b/manim/scene/scene.py@@ -816,7 +816,8 @@ class Scene(Container):self.play_hashes_list.append(hash_play)if self.file_writer.is_already_cached(hash_play):logger.info(- f"Animation {self.num_plays} : Using cached data (hash : {hash_play})"+ f"Animation {self.num_plays} : Using cached data (hash : %(hash_play)s)",+ {"hash_play": hash_play},)file_writer_config["skip_animations"] = Trueelse:diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.pyindex 4a4a5d2c8..1ad2b1875 100644--- a/manim/scene/scene_file_writer.py+++ b/manim/scene/scene_file_writer.py@@ -454,7 +454,8 @@ class SceneFileWriter(object):self.partial_movie_file_path,)logger.info(- f"Animation {self.scene.num_plays} : Partial movie file written in {self.partial_movie_file_path}"+ f"Animation {self.scene.num_plays} : Partial movie file written in %(path)s",+ {"path": {self.partial_movie_file_path}},)def is_already_cached(self, hash_invocation):@@ -616,21 +617,12 @@ class SceneFileWriter(object):for f in cached_partial_movies:os.remove(f)logger.info(- f"Cache flushed. {len(cached_partial_movies)} file(s) deleted in {self.partial_movie_directory}."+ f"Cache flushed. {len(cached_partial_movies)} file(s) deleted in %(par_dir)s.",+ {"par_dir": self.partial_movie_directory},)def print_file_ready_message(self, file_path):"""Prints the "File Ready" message to STDOUT."""- logger.info("\nFile ready at {}\n".format(file_path))-- if file_writer_config["log_to_file"]:- self.write_log()-- def write_log(self):- log_file_path = os.path.join(- file_writer_config["log_dir"], f"{self.get_default_scene_name()}.log"- )- console.save_text(log_file_path)- logger.info("Log written to {}\n".format(log_file_path))+ logger.info("\nFile ready at %(file_path)s\n", {"file_path": file_path})diff --git a/manim/utils/hashing.py b/manim/utils/hashing.pyindex e17e979d9..b753cb160 100644--- a/manim/utils/hashing.py+++ b/manim/utils/hashing.py@@ -244,7 +244,7 @@ def get_hash_from_play_call(for json_val in [camera_json, animations_list_json, current_mobjects_list_json]]t_end = perf_counter()- logger.debug("Hashing done in {:.5f} s.".format(t_end - t_start))+ logger.debug("Hashing done in %(time)s s.", {"time": str(t_end - t_start)[:8]})# This will reset ALREADY_PROCESSED_ID as all the hashing processus is finished.ALREADY_PROCESSED_ID = {}return "{}_{}_{}".format(hash_camera, hash_animations, hash_current_mobjects)@@ -291,7 +291,7 @@ def get_hash_from_wait_call(# This will reset ALREADY_PROCESSED_ID as all the hashing processus is finished.ALREADY_PROCESSED_ID = {}t_end = perf_counter()- logger.debug("Hashing done in {:.5f} s.".format(t_end - t_start))+ logger.debug("Hashing done in %(time)s s.", {"time": str(t_end - t_start)[:8]})return "{}_{}{}_{}".format(hash_camera,str(wait_time).replace(".", "-"),@@ -300,7 +300,7 @@ def get_hash_from_wait_call()ALREADY_PROCESSED_ID = {}t_end = perf_counter()- logger.debug("Hashing done in {:.5f} s.".format(t_end - t_start))+ logger.debug("Hashing done in %(time)s s.", {"time": str(t_end - t_start)[:8]})return "{}_{}_{}".format(hash_camera, str(wait_time).replace(".", "-"), hash_current_mobjects)diff --git a/tests/control_data/logs_data/BasicSceneLoggingTest.txt b/tests/control_data/logs_data/BasicSceneLoggingTest.txtnew file mode 100644index 000000000..8b947a2c4--- /dev/null+++ b/tests/control_data/logs_data/BasicSceneLoggingTest.txt@@ -0,0 +1,6 @@+{"levelname": "INFO", "module": "config", "message": "Log file wil 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 <>"}+{"levelname": "INFO", "module": "scene_file_writer", "message": "\nFile ready at <>\n"}+{"levelname": "INFO", "module": "scene", "message": "Rendered SquareToCircle\nPlayed 1 animations"}diff --git a/tests/test_logging/__init__.py b/tests/test_logging/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/test_logging/basic_scenes.py b/tests/test_logging/basic_scenes.pyindex 09172c3f7..3f190f36e 100644--- a/tests/test_logging/basic_scenes.py+++ b/tests/test_logging/basic_scenes.py@@ -5,15 +5,7 @@ from manim import *class SquareToCircle(Scene):def construct(self):- circle = Circle()- square = Square()- square.flip(RIGHT)- square.rotate(-3 * TAU / 8)- circle.set_fill(PINK, opacity=0.5)-- self.play(ShowCreation(square))- self.play(Transform(square, circle))- self.play(FadeOut(square))+ self.play(Transform(Square(), Circle()))class WriteStuff(Scene):diff --git a/tests/test_logging/expected.txt b/tests/test_logging/expected.txtdeleted file mode 100644index 1f56f982e..000000000--- a/tests/test_logging/expected.txt+++ /dev/null@@ -1,13 +0,0 @@-DEBUG Read configuration files: config.py:-DEBUG Hashing ... hashing.py:-DEBUG Hashing done in . s. hashing.py:-INFO Animation : Partial movie file written in scene_file_writer.py:-DEBUG Hashing ... hashing.py:-DEBUG Hashing done in . s. hashing.py:-INFO Animation : Partial movie file written in scene_file_writer.py:-DEBUG Hashing ... hashing.py:-DEBUG Hashing done in . s. hashing.py:-INFO Animation : Partial movie file written in scene_file_writer.py:-INFO scene_file_writer.py:- File ready at-diff --git a/tests/test_logging/test_logging.py b/tests/test_logging/test_logging.pyindex 7f188d018..a180c7315 100644--- a/tests/test_logging/test_logging.py+++ b/tests/test_logging/test_logging.py@@ -4,65 +4,27 @@ import sysimport pytestimport re--def capture(command, instream=None, use_shell=False):- proc = subprocess.Popen(- command,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- stdin=instream,- shell=use_shell,- )- out, err = proc.communicate()- return out, err, proc.returncode+from ..utils.commands import capture+from ..utils.logging_tester import *+@logs_comparison(+ "BasicSceneLoggingTest.txt", os.path.join("logs", "SquareToCircle.log")+)def test_logging_to_file(tmp_path, python_version):- """Test logging Terminal output to a log file.- As some data will differ with each log (the timestamps, file paths, line nums etc)- a regex substitution has been employed to replace the strings that may change with- whitespace.- """path_basic_scene = os.path.join("tests", "test_logging", "basic_scenes.py")- path_output = os.path.join(tmp_path, "media_temp")- os.makedirs(tmp_path, exist_ok=True)- command = " ".join(- [- python_version,- "-m",- "manim",- path_basic_scene,- "SquareToCircle",- "-l",- "--log_to_file",- "--log_dir",- os.path.join(path_output, "logs"),- "--media_dir",- path_output,- "-v",- "DEBUG",- "--config_file",- os.path.join("tests", "test_logging", "testloggingconfig.cfg"),- ]- )- out, err, exitcode = capture(command, use_shell=True)- log_file_path = os.path.join(path_output, "logs", "SquareToCircle.log")- assert exitcode == 0, err.decode()- assert os.path.exists(log_file_path), err.decode()- if sys.platform.startswith("win32") or sys.platform.startswith("cygwin"):- enc = "Windows-1252"- else:- enc = "utf-8"- with open(log_file_path, encoding=enc) as logfile:- logs = logfile.read()- # The following regex pattern selects file paths and all numbers.- pattern = r"(\['[A-Z]?:?[\/\\].*cfg'])|([A-Z]?:?[\/\\].*mp4)|(\d+)"-- logs = re.sub(pattern, lambda m: " " * len((m.group(0))), logs)- with open(- os.path.join(os.path.dirname(__file__), "expected.txt"), "r"- ) as expectedfile:- expected = re.sub(- pattern, lambda m: " " * len((m.group(0))), expectedfile.read()- )- assert logs == expected, logs+ command = [+ python_version,+ "-m",+ "manim",+ path_basic_scene,+ "SquareToCircle",+ "-l",+ "--log_to_file",+ "-v",+ "DEBUG",+ "--media_dir",+ str(tmp_path),+ ]+ _, err, exitcode = capture(command)+ assert exitcode == 0, errdiff --git a/tests/test_logging/testloggingconfig.cfg b/tests/test_logging/testloggingconfig.cfgdeleted file mode 100644index 069801255..000000000--- a/tests/test_logging/testloggingconfig.cfg+++ /dev/null@@ -1,11 +0,0 @@-[CLI]-movie_file_extension = .mp4-write_to_movie = True-# write_all = False-save_last_frame = False-# save_pngs = False-verbosity = DEBUG--[logger]-log_width = 512-log_timestamps = Falsediff --git a/tests/utils/logging_tester.py b/tests/utils/logging_tester.pynew file mode 100644index 000000000..e2dc642a4--- /dev/null+++ b/tests/utils/logging_tester.py@@ -0,0 +1,88 @@+from functools import wraps+import os+import json+import itertools+++def _check_logs(reference_logfile, generated_logfile):+ with open(reference_logfile, "r") as reference_logs, open(+ generated_logfile, "r"+ ) as generated_logs:+ reference_logs = reference_logs.readlines()+ generated_logs = generated_logs.readlines()+ diff = abs(len(reference_logs) - len(generated_logs))+ if len(reference_logs) != len(generated_logs):+ msg_assert = ""+ if len(reference_logs) > len(generated_logs):+ msg_assert += f"Logs generated are SHORTER than the expected logs. There are {diff} extra logs.\n"+ msg_assert += "Last log of the generated log is : \n"+ msg_assert += generated_logs[-1]+ else:+ msg_assert += f"Logs generated are LONGER than the expected logs.\n There are {diff} extra logs :\n"+ for log in generated_logs[len(reference_logs) :]:+ msg_assert += log+ assert 0, msg_assert++ for index, ref, gen in zip(itertools.count(), reference_logs, generated_logs):+ # As they are string, we only need to check if they are equal. If they are not, we then compute a more precise difference, to debug.+ if ref == gen:+ continue+ ref_log = json.loads(ref)+ gen_log = json.loads(gen)+ diff_keys = [+ d1[0] for d1, d2 in zip(ref_log.items(), gen_log.items()) if d1[1] != d2[1]+ ]+ # \n and \t don't not work in f-strings.+ newline = "\n"+ tab = "\t"+ assert (+ len(diff_keys) == 0+ ), f"Logs don't match at {index} log. : \n{newline.join([f'In {key} field, got -> {newline}{tab}{repr(gen_log[key])}. {newline}Expected : -> {newline}{tab}{repr(ref_log[key])}.' for key in diff_keys])}"+++def logs_comparison(control_data_file, log_path_from_media_dir):+ """Decorator used for any test that needs to check logs.++ Parameters+ ----------+ control_data_file : :class:`str`+ Name of the control data file, i.e. .log that will be compared to the outputed logs.+ .. warning:: You don't have to pass the path here.+ .. example:: "SquareToCircleWithLFlag.log"++ log_path_from_media_dir : :class:`str`+ The path of the .log generated, from the media dir. Example: /logs/Square.log.++ Returns+ -------+ Callable[[Any], Any]+ The test wrapped with which we are going to make the comparison.+ """++ def decorator(f):+ @wraps(f)+ def wrapper(*args, **kwargs):+ # NOTE : Every args goes seemingly in kwargs instead of args; this is perhaps Pytest.+ result = f(*args, **kwargs)+ tmp_path = kwargs["tmp_path"]+ tests_directory = os.path.dirname(+ os.path.dirname(os.path.abspath(__file__))+ )+ controle_data_path = os.path.join(+ tests_directory, "control_data", "logs_data", control_data_file+ )+ path_log_generated = tmp_path / log_path_from_media_dir+ # The following will say precisely which subdir does not exist.+ if not os.path.exists(path_log_generated):+ for parent in reversed(path_log_generated.parents):+ if not parent.exists():+ assert (+ False+ ), f"'{parent.name}' does not exist in '{parent.parent}' (which exists). "+ break+ _check_logs(controle_data_path, str(path_log_generated))+ return result++ return wrapper++ return decorator