Skip to content

Commit e066970

Browse files
authored
Merge pull request #3 from jeertmans/reserve-video-and-more
feat(cli): reverse videos on the fly!
2 parents e82ab99 + 51ca828 commit e066970

File tree

7 files changed

+160
-24
lines changed

7 files changed

+160
-24
lines changed

README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
![PyPI - Downloads](https://img.shields.io/pypi/dm/manim-slides)
44
# Manim Slides
55

6-
Tool for live presentations using either [manim](http://3b1b.github.io/manim/) or [manim-community](https://www.manim.community/).
6+
Tool for live presentations using either [manim-community](https://www.manim.community/). Currently, support for 3b1b's manim is not planned.
77

88
> **_NOTE:_** This project is a fork of [`manim-presentation`](https://github.com/galatolofederico/manim-presentation). Since the project seemed to be inactive, I decided to create my own fork to deploy new features more rapidly.
99
@@ -65,6 +65,7 @@ Default keybindings to control the presentation:
6565
| Right Arrow | Continue/Next Slide |
6666
| Left Arrow | Previous Slide |
6767
| R | Re-Animate Current Slide |
68+
| V | Reverse Current Slide |
6869
| Spacebar | Play/Pause |
6970
| Q | Quit |
7071

@@ -122,11 +123,10 @@ Here are a few things that I implemented (or that I'm planning to implement) on
122123
- [x] Only one cli (to rule them all)
123124
- [x] User can easily generate dummy config file
124125
- [x] Config file path can be manually set
125-
- [ ] Play animation in reverse [#9](https://github.com/galatolofederico/manim-presentation/issues/9)
126+
- [x] Play animation in reverse [#9](https://github.com/galatolofederico/manim-presentation/issues/9)
126127
- [x] Handle 3D scenes out of the box
127-
- [ ] Can work with both community and 3b1b versions (not tested)
128128
- [ ] Generate docs online
129-
- [ ] Fix the quality problem on Windows platforms with `fullscreen` flag
129+
- [x] Fix the quality problem on Windows platforms with `fullscreen` flag
130130

131131
## Contributions and license
132132

manim_slides/__version__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "3.0.1"
1+
__version__ = "3.1.0"

manim_slides/config.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ class Config(BaseModel):
2323
QUIT: Key = Key(ids=[ord("q")], name="QUIT")
2424
CONTINUE: Key = Key(ids=[RIGHT_ARROW_KEY_CODE], name="CONTINUE / NEXT")
2525
BACK: Key = Key(ids=[LEFT_ARROW_KEY_CODE], name="BACK")
26+
REVERSE: Key = Key(ids=[ord("v")], name="REVERSE")
2627
REWIND: Key = Key(ids=[ord("r")], name="REWIND")
2728
PLAY_PAUSE: Key = Key(ids=[32], name="PLAY / PAUSE")
2829

@@ -33,7 +34,7 @@ def ids_are_unique_across_keys(cls, values):
3334
for key in values.values():
3435
if len(ids.intersection(key.ids)) != 0:
3536
raise ValueError(
36-
f"Two or more keys share a common key code: please make sure each key has distinc key codes"
37+
"Two or more keys share a common key code: please make sure each key has distinc key codes"
3738
)
3839
ids.update(key.ids)
3940

manim_slides/main.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from click_default_group import DefaultGroup
33

44
from . import __version__
5-
from .present import present
5+
from .present import list_scenes, present
66
from .wizard import init, wizard
77

88

@@ -13,6 +13,7 @@ def cli():
1313
pass
1414

1515

16+
cli.add_command(list_scenes)
1617
cli.add_command(present)
1718
cli.add_command(wizard)
1819
cli.add_command(init)

manim_slides/present.py

Lines changed: 86 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from .commons import config_path_option
1717
from .config import Config
1818
from .defaults import CONFIG_PATH, FOLDER_PATH
19+
from .slide import reverse_video_path
1920

2021

2122
@unique
@@ -41,7 +42,9 @@ class Presentation:
4142
def __init__(self, config, last_frame_next: bool = False):
4243
self.last_frame_next = last_frame_next
4344
self.slides = config["slides"]
44-
self.files = config["files"]
45+
self.files = [path for path in config["files"]]
46+
self.reverse = False
47+
self.reversed_slide = -1
4548

4649
self.lastframe = []
4750

@@ -79,19 +82,34 @@ def prev(self):
7982
self.current_slide_i = max(0, self.current_slide_i - 1)
8083
self.rewind_slide()
8184

82-
def rewind_slide(self):
85+
def reverse_slide(self):
86+
self.rewind_slide(reverse=True)
87+
88+
def rewind_slide(self, reverse: bool = False):
89+
self.reverse = reverse
8390
self.current_animation = self.current_slide["start_animation"]
8491
self.current_cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
8592

86-
def load_this_cap(self, cap_number):
87-
if self.caps[cap_number] == None:
93+
def load_this_cap(self, cap_number: int):
94+
if (
95+
self.caps[cap_number] is None
96+
or (self.reverse and self.reversed_slide != cap_number)
97+
or (not self.reverse and self.reversed_slide == cap_number)
98+
):
8899
# unload other caps
89100
for i in range(len(self.caps)):
90-
if self.caps[i] != None:
101+
if not self.caps[i] is None:
91102
self.caps[i].release()
92103
self.caps[i] = None
93104
# load this cap
94-
self.caps[cap_number] = cv2.VideoCapture(self.files[cap_number])
105+
file = self.files[cap_number]
106+
if self.reverse:
107+
self.reversed_slide = cap_number
108+
file = "{}_reversed{}".format(*os.path.splitext(file))
109+
else:
110+
self.reversed_slide = -1
111+
112+
self.caps[cap_number] = cv2.VideoCapture(file)
95113

96114
@property
97115
def current_slide(self):
@@ -170,7 +188,9 @@ def __init__(self, presentations, config, start_paused=False, fullscreen=False):
170188

171189
if platform.system() == "Windows":
172190
user32 = ctypes.windll.user32
173-
self.screen_width, self.screen_height = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
191+
self.screen_width, self.screen_height = user32.GetSystemMetrics(
192+
0
193+
), user32.GetSystemMetrics(1)
174194

175195
if fullscreen:
176196
cv2.namedWindow("Video", cv2.WND_PROP_FULLSCREEN)
@@ -283,6 +303,9 @@ def handle_key(self):
283303
else:
284304
self.current_presentation.prev()
285305
self.state = State.PLAYING
306+
elif self.config.REVERSE.match(key):
307+
self.current_presentation.reverse_slide()
308+
self.state = State.PLAYING
286309
elif self.config.REWIND.match(key):
287310
self.current_presentation.rewind_slide()
288311
self.state = State.PLAYING
@@ -292,6 +315,31 @@ def quit(self):
292315
sys.exit()
293316

294317

318+
@click.command()
319+
@click.option(
320+
"--folder",
321+
default=FOLDER_PATH,
322+
type=click.Path(exists=True, file_okay=False),
323+
help="Set slides folder.",
324+
)
325+
@click.help_option("-h", "--help")
326+
def list_scenes(folder):
327+
"""List available scenes."""
328+
329+
for i, scene in enumerate(_list_scenes(folder), start=1):
330+
click.secho(f"{i}: {scene}", fg="green")
331+
332+
333+
def _list_scenes(folder):
334+
scenes = []
335+
336+
for file in os.listdir(folder):
337+
if file.endswith(".json"):
338+
scenes.append(os.path.basename(file)[:-5])
339+
340+
return scenes
341+
342+
295343
@click.command()
296344
@click.argument("scenes", nargs=-1)
297345
@config_path_option
@@ -312,6 +360,37 @@ def quit(self):
312360
def present(scenes, config_path, folder, start_paused, fullscreen, last_frame_next):
313361
"""Present the different scenes."""
314362

363+
if len(scenes) == 0:
364+
scene_choices = _list_scenes(folder)
365+
366+
scene_choices = dict(enumerate(scene_choices, start=1))
367+
368+
for i, scene in scene_choices.items():
369+
click.secho(f"{i}: {scene}", fg="green")
370+
371+
click.echo()
372+
373+
click.echo("Choose number corresponding to desired scene/arguments.")
374+
click.echo("(Use comma separated list for multiple entries)")
375+
376+
def value_proc(value: str):
377+
indices = list(map(int, value.strip().replace(" ", "").split(",")))
378+
379+
if not all(map(lambda i: 0 < i <= len(scene_choices), indices)):
380+
raise ValueError("Please only enter numbers displayed on the screen.")
381+
382+
return [scene_choices[i] for i in indices]
383+
384+
if len(scene_choices) == 0:
385+
raise ValueError("No scenes were found, are you in the correct directory?")
386+
387+
while True:
388+
try:
389+
scenes = click.prompt("Choice(s)", value_proc=value_proc)
390+
break
391+
except ValueError as e:
392+
click.secho(e, fg="red")
393+
315394
presentations = list()
316395
for scene in scenes:
317396
config_file = os.path.join(folder, f"{scene}.json")

manim_slides/slide.py

Lines changed: 64 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,36 @@
11
import json
22
import os
3+
import platform
34
import shutil
5+
import subprocess
46

5-
from manim import Scene, ThreeDScene, config
7+
from tqdm import tqdm
8+
9+
try:
10+
from .manim import Scene, ThreeDScene, config, logger
11+
except ImportError:
12+
Scene = ThreeDScene = config = logger = None
13+
# TODO: manage both manim and manimgl
14+
15+
try: # For manim<v0.16.0.post0
16+
from manim.constants import FFMPEG_BIN as ffmpeg_executable
17+
except ImportError:
18+
ffmpeg_executable = config.ffmpeg_executable
619

720
from .defaults import FOLDER_PATH
821

922

23+
def reverse_video_path(src: str) -> str:
24+
file, ext = os.path.splitext(src)
25+
return f"{file}_reversed{ext}"
26+
27+
28+
def reverse_video_file(src: str, dst: str):
29+
command = [config.ffmpeg_executable, "-i", src, "-vf", "reverse", dst]
30+
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
31+
process.communicate()
32+
33+
1034
class Slide(Scene):
1135
def __init__(self, *args, output_folder=FOLDER_PATH, **kwargs):
1236
super().__init__(*args, **kwargs)
@@ -72,21 +96,54 @@ def render(self, *args, **kwargs):
7296
scene_name = type(self).__name__
7397
scene_files_folder = os.path.join(files_folder, scene_name)
7498

75-
if os.path.exists(scene_files_folder):
76-
shutil.rmtree(scene_files_folder)
99+
old_animation_files = set()
77100

78101
if not os.path.exists(scene_files_folder):
79102
os.mkdir(scene_files_folder)
103+
else:
104+
old_animation_files.update(os.listdir(scene_files_folder))
80105

81106
files = list()
82-
for src_file in self.renderer.file_writer.partial_movie_files:
83-
dst_file = os.path.join(scene_files_folder, os.path.basename(src_file))
84-
shutil.copyfile(src_file, dst_file)
107+
for src_file in tqdm(
108+
self.renderer.file_writer.partial_movie_files,
109+
desc=f"Copying animation files to '{scene_files_folder}' and generating reversed animations",
110+
leave=config["progress_bar"] == "leave",
111+
ascii=True if platform.system() == "Windows" else None,
112+
disable=config["progress_bar"] == "none",
113+
):
114+
filename = os.path.basename(src_file)
115+
_hash, ext = os.path.splitext(filename)
116+
117+
rev_filename = f"{_hash}_reversed{ext}"
118+
119+
dst_file = os.path.join(scene_files_folder, filename)
120+
# We only copy animation if it was not present
121+
if filename in old_animation_files:
122+
old_animation_files.remove(filename)
123+
else:
124+
shutil.copyfile(src_file, dst_file)
125+
126+
# We only reverse video if it was not present
127+
if rev_filename in old_animation_files:
128+
old_animation_files.remove(rev_filename)
129+
else:
130+
rev_file = os.path.join(scene_files_folder, rev_filename)
131+
reverse_video_file(src_file, rev_file)
132+
85133
files.append(dst_file)
86134

87-
f = open(os.path.join(self.output_folder, "%s.json" % (scene_name,)), "w")
135+
logger.info(
136+
f"Copied {len(files)} animations to '{os.path.abspath(scene_files_folder)}' and generated reversed animations"
137+
)
138+
139+
slide_path = os.path.join(self.output_folder, "%s.json" % (scene_name,))
140+
141+
f = open(slide_path, "w")
88142
json.dump(dict(slides=self.slides, files=files), f)
89143
f.close()
144+
logger.info(
145+
f"Slide '{scene_name}' configuration written in '{os.path.abspath(slide_path)}'"
146+
)
90147

91148

92149
class ThreeDSlide(Slide, ThreeDScene):

setup.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@
22

33
import setuptools
44

5-
sys.path.append("manim_slides") # To avoid importing manim, which may not be installed
6-
7-
from __version__ import __version__ as version
5+
from manim_slides import __version__ as version
86

97
if sys.version_info < (3, 7):
108
raise RuntimeError("This package requires Python 3.7+")

0 commit comments

Comments
 (0)