Skip to content

Commit bc3d55f

Browse files
authored
feat(cli): add basic logging facilities (#50)
* feat(cli): add basic logging facilities This PR adds basic logging support, to be extended in the future. * fix: typo in decorator name
1 parent 5b9cb15 commit bc3d55f

File tree

4 files changed

+55
-9
lines changed

4 files changed

+55
-9
lines changed

manim_slides/commons.py

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
from typing import Callable
22

33
import click
4+
from click import Context, Parameter
45

56
from .defaults import CONFIG_PATH
7+
from .manim import logger
68

79

8-
def config_path_option(function) -> Callable:
10+
def config_path_option(function: Callable) -> Callable:
911
"""Wraps a function to add configuration path option."""
1012
return click.option(
1113
"-c",
@@ -18,7 +20,7 @@ def config_path_option(function) -> Callable:
1820
)(function)
1921

2022

21-
def config_options(function) -> Callable:
23+
def config_options(function: Callable) -> Callable:
2224
"""Wraps a function to add configuration options."""
2325
function = config_path_option(function)
2426
function = click.option(
@@ -31,3 +33,27 @@ def config_options(function) -> Callable:
3133
help="Merge any existing configuration file with the new configuration.",
3234
)(function)
3335
return function
36+
37+
38+
def verbosity_option(function: Callable) -> Callable:
39+
"""Wraps a function to add verbosity option."""
40+
41+
def callback(ctx: Context, param: Parameter, value: bool) -> None:
42+
43+
if not value or ctx.resilient_parsing:
44+
return
45+
46+
logger.setLevel(value)
47+
48+
return click.option(
49+
"-v",
50+
"--verbosity",
51+
type=click.Choice(
52+
["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
53+
case_sensitive=False,
54+
),
55+
help="Verbosity of CLI output",
56+
default=None,
57+
expose_value=False,
58+
callback=callback,
59+
)(function)

manim_slides/config.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from pydantic import BaseModel, root_validator, validator
66

77
from .defaults import LEFT_ARROW_KEY_CODE, RIGHT_ARROW_KEY_CODE
8+
from .manim import logger
89

910

1011
class Key(BaseModel):
@@ -20,7 +21,12 @@ def id_is_posint(cls, v: int):
2021
return v
2122

2223
def match(self, key_id: int):
23-
return key_id in self.ids
24+
m = key_id in self.ids
25+
26+
if m:
27+
logger.debug(f"Pressed key: {self.name}")
28+
29+
return m
2430

2531

2632
class Config(BaseModel):

manim_slides/present.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@
1111
from pydantic import ValidationError
1212
from tqdm import tqdm
1313

14-
from .commons import config_path_option
14+
from .commons import config_path_option, verbosity_option
1515
from .config import Config, PresentationConfig, SlideConfig, SlideType
1616
from .defaults import FOLDER_PATH, FONT_ARGS
17+
from .manim import logger
1718

1819
INTERPOLATION_FLAGS = {
1920
"nearest": cv2.INTER_NEAREST,
@@ -450,6 +451,9 @@ def quit(self) -> None:
450451
cv2.destroyAllWindows()
451452

452453
if self.record_to is not None and len(self.recordings) > 0:
454+
logger.debug(
455+
f"A total of {len(self.recordings)} frames will be saved to {self.record_to}"
456+
)
453457
file, frame_number, fps = self.recordings[0]
454458

455459
cap = cv2.VideoCapture(file)
@@ -489,6 +493,7 @@ def quit(self) -> None:
489493
show_default=True,
490494
)
491495
@click.help_option("-h", "--help")
496+
@verbosity_option
492497
def list_scenes(folder) -> None:
493498
"""List available scenes."""
494499

@@ -502,13 +507,18 @@ def _list_scenes(folder) -> List[str]:
502507

503508
for file in os.listdir(folder):
504509
if file.endswith(".json"):
510+
filepath = os.path.join(folder, file)
505511
try:
506-
filepath = os.path.join(folder, file)
507512
_ = PresentationConfig.parse_file(filepath)
508513
scenes.append(os.path.basename(file)[:-5])
509-
except Exception: # Could not parse this file as a proper presentation config
514+
except Exception as e: # Could not parse this file as a proper presentation config
515+
logger.warn(
516+
f"Something went wrong with parsing presentation config `{filepath}`: {e}"
517+
)
510518
pass
511519

520+
logger.info(f"Found {len(scenes)} valid scene configuration files in `{folder}`.")
521+
512522
return scenes
513523

514524

@@ -552,6 +562,7 @@ def _list_scenes(folder) -> List[str]:
552562
help="If set, the presentation will be recorded into a AVI video file with given name.",
553563
)
554564
@click.help_option("-h", "--help")
565+
@verbosity_option
555566
def present(
556567
scenes,
557568
config_path,
@@ -616,8 +627,8 @@ def value_proc(value: str) -> List[str]:
616627
f"File {config_file} does not exist, check the scene name and make sure to use Slide as your scene base class"
617628
)
618629
try:
619-
config = PresentationConfig.parse_file(config_file)
620-
presentations.append(Presentation(config))
630+
pres_config = PresentationConfig.parse_file(config_file)
631+
presentations.append(Presentation(pres_config))
621632
except ValidationError as e:
622633
raise click.UsageError(str(e))
623634

@@ -627,6 +638,7 @@ def value_proc(value: str) -> List[str]:
627638
except ValidationError as e:
628639
raise click.UsageError(str(e))
629640
else:
641+
logger.info("No configuration file found, using default configuration.")
630642
config = Config()
631643

632644
if record_to is not None:

manim_slides/wizard.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import cv2
66
import numpy as np
77

8-
from .commons import config_options
8+
from .commons import config_options, verbosity_option
99
from .config import Config
1010
from .defaults import CONFIG_PATH, FONT_ARGS
1111

@@ -39,6 +39,7 @@ def prompt(question: str) -> int:
3939
@click.command()
4040
@config_options
4141
@click.help_option("-h", "--help")
42+
@verbosity_option
4243
def wizard(config_path, force, merge):
4344
"""Launch configuration wizard."""
4445
return _init(config_path, force, merge, skip_interactive=False)
@@ -47,6 +48,7 @@ def wizard(config_path, force, merge):
4748
@click.command()
4849
@config_options
4950
@click.help_option("-h", "--help")
51+
@verbosity_option
5052
def init(config_path, force, merge, skip_interactive=False):
5153
"""Initialize a new default configuration file."""
5254
return _init(config_path, force, merge, skip_interactive=True)

0 commit comments

Comments
 (0)