Skip to content

Commit ed3d441

Browse files
authored
Merge pull request #1637 from 3b1b/add_warnings
Add warnings and use rich to display log
2 parents e9aba0b + 4466cfe commit ed3d441

File tree

10 files changed

+70
-35
lines changed

10 files changed

+70
-35
lines changed

manimlib/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import pkg_resources
2+
3+
__version__ = pkg_resources.get_distribution("manimgl").version
4+
15
from manimlib.constants import *
26

37
from manimlib.animation.animation import *

manimlib/__main__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,15 @@
22
import manimlib.config
33
import manimlib.extract_scene
44
import manimlib.utils.init_config
5+
from manimlib import __version__
56

67

78
def main():
89
args = manimlib.config.parse_cli()
10+
11+
print(f"ManimGL \033[32mv{__version__}\033[0m")
12+
if args.version and args.file == None:
13+
return
914

1015
if args.config:
1116
manimlib.utils.init_config.init_customization()

manimlib/config.py

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
from manimlib.utils.config_ops import merge_dicts_recursively
1111
from manimlib.utils.init_config import init_customization
12+
from manimlib.logger import log
1213

1314

1415
def parse_cli():
@@ -136,10 +137,15 @@ def parse_cli():
136137
"--config_file",
137138
help="Path to the custom configuration file",
138139
)
140+
parser.add_argument(
141+
"-v", "--version",
142+
action="store_true",
143+
help="Display the version of manimgl"
144+
)
139145
args = parser.parse_args()
140146
return args
141147
except argparse.ArgumentError as err:
142-
print(str(err))
148+
log.error(str(err))
143149
sys.exit(2)
144150

145151

@@ -185,36 +191,45 @@ def get_custom_config():
185191
return config
186192

187193

194+
def check_temporary_storage(config):
195+
if config["directories"]["temporary_storage"] == "" and sys.platform == "win32":
196+
log.warning("You may be using Windows platform and have not specified the `temporary\
197+
_storage` path, which may cause OSError. So it is recommended that you specify the `temporary\
198+
_storage` in the config file (.yml)")
199+
200+
188201
def get_configuration(args):
189202
global __config_file__
190203

191204
# ensure __config_file__ always exists
192205
if args.config_file is not None:
193206
if not os.path.exists(args.config_file):
194-
print(f"Can't find {args.config_file}.")
207+
log.error(f"Can't find {args.config_file}.")
195208
if sys.platform == 'win32':
196-
print(f"Copying default configuration file to {args.config_file}...")
209+
log.info(f"Copying default configuration file to {args.config_file}...")
197210
os.system(f"copy default_config.yml {args.config_file}")
198211
elif sys.platform in ["linux2", "darwin"]:
199-
print(f"Copying default configuration file to {args.config_file}...")
212+
log.info(f"Copying default configuration file to {args.config_file}...")
200213
os.system(f"cp default_config.yml {args.config_file}")
201214
else:
202-
print("Please create the configuration file manually.")
203-
print("Read configuration from default_config.yml.")
215+
log.info("Please create the configuration file manually.")
216+
log.info("Read configuration from default_config.yml.")
204217
else:
205218
__config_file__ = args.config_file
206219

207220
global_defaults_file = os.path.join(get_manim_dir(), "manimlib", "default_config.yml")
208221

209222
if not (os.path.exists(global_defaults_file) or os.path.exists(__config_file__)):
210-
print("There is no configuration file detected. Initial configuration:\n")
223+
log.info("There is no configuration file detected. Initial configuration:\n")
211224
init_customization()
212225

213226
elif not os.path.exists(__config_file__):
214-
print(f"Warning: Using the default configuration file, which you can modify in {global_defaults_file}")
215-
print(f"If you want to create a local configuration file, you can create a file named {__config_file__}, or run manimgl --config")
227+
log.info(f"Using the default configuration file, which you can modify in `{global_defaults_file}`")
228+
log.info(f"If you want to create a local configuration file, you can create a file named \
229+
`{__config_file__}`, or run `manimgl --config`")
216230

217231
custom_config = get_custom_config()
232+
check_temporary_storage(custom_config)
218233

219234
write_file = any([args.write_file, args.open, args.finder])
220235
if args.transparent:
@@ -319,9 +334,9 @@ def get_camera_configuration(args, custom_config):
319334
try:
320335
bg_color = args.color or custom_config["style"]["background_color"]
321336
camera_config["background_color"] = colour.Color(bg_color)
322-
except AttributeError as err:
323-
print("Please use a valid color")
324-
print(err)
337+
except ValueError as err:
338+
log.error("Please use a valid color")
339+
log.error(err)
325340
sys.exit(2)
326341

327342
# If rendering a transparent image/move, make sure the

manimlib/extract_scene.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import inspect
22
import sys
3-
import logging
43

54
from manimlib.scene.scene import Scene
65
from manimlib.config import get_custom_config
6+
from manimlib.logger import log
77

88

99
class BlankScene(Scene):
@@ -41,8 +41,11 @@ def prompt_user_for_choice(scene_classes):
4141
name_to_class[split_str] if not split_str.isnumeric() else scene_classes[int(split_str)-1]
4242
for split_str in user_input.replace(" ", "").split(",")
4343
]
44+
except IndexError:
45+
log.error("Invalid scene number")
46+
sys.exit(2)
4447
except KeyError:
45-
logging.log(logging.ERROR, "Invalid scene")
48+
log.error("Invalid scene name")
4649
sys.exit(2)
4750
except EOFError:
4851
sys.exit(1)
@@ -78,10 +81,7 @@ def get_scenes_to_render(scene_classes, scene_config, config):
7881
found = True
7982
break
8083
if not found and (scene_name != ""):
81-
logging.log(
82-
logging.ERROR,
83-
f"No scene named {scene_name} found",
84-
)
84+
log.error(f"No scene named {scene_name} found")
8585
if result:
8686
return result
8787
if len(scene_classes) == 1:

manimlib/logger.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import logging
2+
from rich.logging import RichHandler
3+
4+
FORMAT = "%(message)s"
5+
logging.basicConfig(
6+
level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
7+
)
8+
9+
log = logging.getLogger("rich")

manimlib/scene/scene.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import random
33
import platform
44
import itertools as it
5-
import logging
65
from functools import wraps
76

87
from tqdm import tqdm as ProgressDisplay
@@ -21,6 +20,7 @@
2120
from manimlib.utils.family_ops import restructure_list_to_exclude_certain_family_members
2221
from manimlib.event_handler.event_type import EventType
2322
from manimlib.event_handler import EVENT_DISPATCHER
23+
from manimlib.logger import log
2424

2525

2626
class Scene(object):
@@ -101,6 +101,8 @@ def interact(self):
101101
# If there is a window, enter a loop
102102
# which updates the frame while under
103103
# the hood calling the pyglet event loop
104+
log.info("Tips: You are now in the interactive mode. Now you can use the keyboard\
105+
and the mouse to interact with the scene. Just press `q` if you want to quit.")
104106
self.quit_interaction = False
105107
self.lock_static_mobject_data()
106108
while not (self.window.is_closing or self.quit_interaction):
@@ -132,6 +134,8 @@ def embed(self):
132134
local_ns["touch"] = self.interact
133135
for term in ("play", "wait", "add", "remove", "clear", "save_state", "restore"):
134136
local_ns[term] = getattr(self, term)
137+
log.info("Tips: Now the embed iPython terminal is open. But you can't interact with \
138+
the window directly. To do so, you need to type `touch()` or `self.interact()`")
135139
shell(local_ns=local_ns, stack_depth=2)
136140
# End scene when exiting an embed.
137141
raise EndSceneEarlyException()
@@ -459,8 +463,7 @@ def finish_animations(self, animations):
459463
@handle_play_like_call
460464
def play(self, *args, **kwargs):
461465
if len(args) == 0:
462-
logging.log(
463-
logging.WARNING,
466+
log.warning(
464467
"Called Scene.play with no animations"
465468
)
466469
return
@@ -602,7 +605,7 @@ def on_key_press(self, symbol, modifiers):
602605
try:
603606
char = chr(symbol)
604607
except OverflowError:
605-
print(" Warning: The value of the pressed key is too large.")
608+
log.warning("The value of the pressed key is too large.")
606609
return
607610

608611
event_data = {"symbol": symbol, "modifiers": modifiers}

manimlib/scene/scene_file_writer.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from manimlib.utils.file_ops import add_extension_if_not_present
1313
from manimlib.utils.file_ops import get_sorted_integer_files
1414
from manimlib.utils.sounds import get_full_sound_file_path
15+
from manimlib.logger import log
1516

1617

1718
class SceneFileWriter(object):
@@ -231,7 +232,7 @@ def combine_movie_files(self):
231232
**kwargs
232233
)
233234
if len(partial_movie_files) == 0:
234-
print("No animations in this scene")
235+
log.warning("No animations in this scene")
235236
return
236237

237238
# Write a file partial_file_list.txt containing all
@@ -300,7 +301,7 @@ def save_final_image(self, image):
300301
self.print_file_ready_message(file_path)
301302

302303
def print_file_ready_message(self, file_path):
303-
print(f"\nFile ready at {file_path}\n")
304+
log.info(f"\nFile ready at {file_path}\n")
304305

305306
def should_open_file(self):
306307
return any([

manimlib/utils/bezier.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from manimlib.utils.space_ops import find_intersection
66
from manimlib.utils.space_ops import cross2d
77
from manimlib.utils.space_ops import midpoint
8+
from manimlib.logger import log
89

910
CLOSED_THRESHOLD = 0.001
1011

@@ -68,9 +69,9 @@ def interpolate(start, end, alpha):
6869
try:
6970
return (1 - alpha) * start + alpha * end
7071
except TypeError:
71-
print(type(start), start.dtype)
72-
print(type(end), start.dtype)
73-
print(alpha)
72+
log.debug(type(start), start.dtype)
73+
log.debug(type(end), start.dtype)
74+
log.debug(alpha)
7475
import sys
7576
sys.exit(2)
7677

manimlib/utils/debug.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
from manimlib.constants import BLACK
44
from manimlib.mobject.numbers import Integer
55
from manimlib.mobject.types.vectorized_mobject import VGroup
6+
from manimlib.logger import log
67

78

89
def print_family(mobject, n_tabs=0):
910
"""For debugging purposes"""
10-
print("\t" * n_tabs, mobject, id(mobject))
11+
log.debug("\t" * n_tabs + str(mobject) + " " + str(id(mobject)))
1112
for submob in mobject.submobjects:
1213
print_family(submob, n_tabs + 1)
1314

manimlib/utils/tex_file_writing.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import logging
21
import sys
32
import os
43
import hashlib
@@ -7,6 +6,7 @@
76
from manimlib.utils.directories import get_tex_dir
87
from manimlib.config import get_manim_dir
98
from manimlib.config import get_custom_config
9+
from manimlib.logger import log
1010

1111

1212
SAVED_TEX_CONFIG = {}
@@ -87,15 +87,11 @@ def tex_to_dvi(tex_file):
8787
exit_code = os.system(" ".join(commands))
8888
if exit_code != 0:
8989
log_file = tex_file.replace(".tex", ".log")
90-
logging.log(
91-
logging.ERROR,
92-
"\n\n LaTeX Error! Not a worry, it happens to the best of us.\n"
93-
)
90+
log.error("LaTeX Error! Not a worry, it happens to the best of us.")
9491
with open(log_file, "r") as file:
9592
for line in file.readlines():
9693
if line.startswith("!"):
97-
print(line[1:])
98-
logging.log(logging.INFO, line)
94+
log.debug(f"The error could be: `{line[2:-1]}`")
9995
sys.exit(2)
10096
return result
10197

0 commit comments

Comments
 (0)