Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Introduced API for scene sections via :meth:`.Scene.next_section` (#2152)

Christopher Besch3ce4c133dd49
diff --git a/docs/source/tutorials/a_deeper_look.rst b/docs/source/tutorials/a_deeper_look.rst
index f954ec5f3..72ba1f26a 100644
--- a/docs/source/tutorials/a_deeper_look.rst
+++ b/docs/source/tutorials/a_deeper_look.rst
@@ -137,6 +137,126 @@ resolutions, e.g. ``-s -ql``, ``-s -qh``
+Sections
+********
+
+In addition to the movie output file one can use sections. Each section produces
+its own output video. The cuts between two sections can be set like this:
+
+.. code-block:: python
+
+ def construct(self):
+ # play the first animations...
+ # you don't need a section in the very beginning as it gets created automatically
+ self.next_section()
+ # play more animations...
+ self.next_section("this is an optional name that doesn't have to be unique")
+ # play even more animations...
+ self.next_section("this is a section without any animations, it will be removed")
+
+All the animations between two of these cuts get concatenated into a single output
+video file.
+Be aware that you need at least one animation in each section. For example this wouldn't create an output video:
+
+.. code-block:: python
+
+ def construct(self):
+ self.next_section()
+ # this section doesn't have any animations and will be removed
+ # but no error will be thrown
+ # feel free to tend your flock of empty sections if you so desire
+ self.add(Circle())
+ self.next_section()
+
+One way of fixing this is to wait a little:
+
+.. code-block:: python
+
+ def construct(self):
+ self.next_section()
+ self.add(Circle())
+ # now we wait 1sec and have an animation to satisfy the section
+ self.wait()
+ self.next_section()
+
+For videos to be created for each section you have to add the ``--use_sections`` flag to the Manim call like this:
+
+.. code-block:: bash
+
+ manim --use_sections scene.py
+
+If you do this, the ``media`` folder will look like this:
+
+.. code-block:: bash
+
+ media
+ ├── images
+ │ └── simple_scenes
+ └── videos
+ └── simple_scenes
+ └── 480p15
+ ├── ElaborateSceneWithSections.mp4
+ ├── partial_movie_files
+ │ └── ElaborateSceneWithSections
+ │ ├── 2201830969_104169243_1331664314.mp4
+ │ ├── 2201830969_398514950_125983425.mp4
+ │ ├── 2201830969_398514950_3447021159.mp4
+ │ ├── 2201830969_398514950_4144009089.mp4
+ │ ├── 2201830969_4218360830_1789939690.mp4
+ │ ├── 3163782288_524160878_1793580042.mp4
+ │ └── partial_movie_file_list.txt
+ └── sections
+ ├── ElaborateSceneWithSections_0000.mp4
+ ├── ElaborateSceneWithSections_0001.mp4
+ ├── ElaborateSceneWithSections_0002.mp4
+ └── ElaborateSceneWithSections.json
+
+As you can see each section receives their own output video in the ``sections`` directory.
+The JSON file in here contains some useful information for each section:
+
+.. code-block:: json
+
+ [
+ {
+ "name": "create square",
+ "type": "default.normal",
+ "video": "ElaborateSceneWithSections_0000.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "2.000000",
+ "nb_frames": "30"
+ },
+ {
+ "name": "transform to circle",
+ "type": "default.normal",
+ "video": "ElaborateSceneWithSections_0001.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "2.000000",
+ "nb_frames": "30"
+ },
+ {
+ "name": "fade out",
+ "type": "default.normal",
+ "video": "ElaborateSceneWithSections_0002.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "2.000000",
+ "nb_frames": "30"
+ }
+ ]
+
+This data can be used by third party applications, like a presentation system or automated video editing tool.
+
+
+
+
Some command line flags
***********************
diff --git a/manim/__init__.py b/manim/__init__.py
index 4e73da36d..9adb2002c 100644
--- a/manim/__init__.py
+++ b/manim/__init__.py
@@ -28,6 +28,8 @@ for i, arg in enumerate(sys.argv):
elif arg == "--use_webgl_renderer":
config.renderer = "webgl"
+# many scripts depend on this -> has to be loaded first
+from .utils.commands import * # isort:skip
from .animation.animation import *
from .animation.composition import *
@@ -87,11 +89,11 @@ from .scene.reconfigurable_scene import *
from .scene.sample_space_scene import *
from .scene.scene import *
from .scene.scene_file_writer import *
+from .scene.section import *
from .scene.three_d_scene import *
from .scene.vector_space_scene import *
from .scene.zoomed_scene import *
-from .utils import color as color
-from .utils import rate_functions, unit
+from .utils import color, rate_functions, unit
from .utils.bezier import *
from .utils.color import *
from .utils.config_ops import *
diff --git a/manim/_config/default.cfg b/manim/_config/default.cfg
index 0beb33374..4f0083a75 100644
--- a/manim/_config/default.cfg
+++ b/manim/_config/default.cfg
@@ -38,6 +38,9 @@ zero_pad = 4
# -i, --save_as_gif
save_as_gif = False
+# --save_sections
+save_sections = False
+
# -p, --preview
preview = False
@@ -84,6 +87,7 @@ assets_dir = ./
# the following do not have CLI arguments but depend on media_dir
video_dir = {media_dir}/videos/{module_name}/{quality}
+sections_dir = {video_dir}/sections
images_dir = {media_dir}/images/{module_name}
tex_dir = {media_dir}/Tex
text_dir = {media_dir}/texts
@@ -164,6 +168,7 @@ plugins =
[custom_folders]
media_dir = videos
video_dir = {media_dir}
+sections_dir = {media_dir}
images_dir = {media_dir}
text_dir = {media_dir}/temp_files
tex_dir = {media_dir}/temp_files
diff --git a/manim/_config/utils.py b/manim/_config/utils.py
index 090f2c82c..ad43b7a63 100644
--- a/manim/_config/utils.py
+++ b/manim/_config/utils.py
@@ -273,6 +273,7 @@ class ManimConfig(MutableMapping):
"preview",
"progress_bar",
"save_as_gif",
+ "save_sections",
"save_last_frame",
"save_pngs",
"scene_names",
@@ -290,6 +291,7 @@ class ManimConfig(MutableMapping):
"use_projection_stroke_shaders",
"verbosity",
"video_dir",
+ "sections_dir",
"fullscreen",
"window_position",
"window_size",
@@ -528,6 +530,7 @@ class ManimConfig(MutableMapping):
"write_all",
"save_pngs",
"save_as_gif",
+ "save_sections",
"preview",
"show_in_file_browser",
"log_to_file",
@@ -566,6 +569,7 @@ class ManimConfig(MutableMapping):
"media_dir",
"log_dir",
"video_dir",
+ "sections_dir",
"images_dir",
"text_dir",
"tex_dir",
@@ -676,6 +680,7 @@ class ManimConfig(MutableMapping):
"save_last_frame",
"save_pngs",
"save_as_gif",
+ "save_sections",
"write_all",
"disable_caching",
"format",
@@ -751,6 +756,7 @@ class ManimConfig(MutableMapping):
for opt in [
"media_dir",
"video_dir",
+ "sections_dir",
"images_dir",
"text_dir",
"tex_dir",
@@ -890,6 +896,12 @@ class ManimConfig(MutableMapping):
doc="Whether to save the rendered scene in .gif format (-i).",
)
+ save_sections = property(
+ lambda self: self._d["save_sections"],
+ lambda self, val: self._set_boolean("save_sections", val),
+ doc="Whether to save single videos for each section in addition to the movie file.",
+ )
+
enable_wireframe = property(
lambda self: self._d["enable_wireframe"],
lambda self, val: self._set_boolean("enable_wireframe", val),
@@ -1410,6 +1422,7 @@ class ManimConfig(MutableMapping):
"assets_dir",
"media_dir",
"video_dir",
+ "sections_dir",
"images_dir",
"text_dir",
"tex_dir",
@@ -1467,6 +1480,12 @@ class ManimConfig(MutableMapping):
doc="Directory to place videos (no flag). See :meth:`ManimConfig.get_dir`.",
)
+ sections_dir = property(
+ lambda self: self._d["sections_dir"],
+ lambda self, val: self._set_dir("sections_dir", val),
+ doc="Directory to place section videos (no flag). See :meth:`ManimConfig.get_dir`.",
+ )
+
images_dir = property(
lambda self: self._d["images_dir"],
lambda self, val: self._set_dir("images_dir", val),
diff --git a/manim/cli/render/render_options.py b/manim/cli/render/render_options.py
index f700c1298..e66f1c288 100644
--- a/manim/cli/render/render_options.py
+++ b/manim/cli/render/render_options.py
@@ -122,6 +122,12 @@ render_options = option_group(
is_flag=True,
help="Save as a gif (Deprecated).",
),
+ option(
+ "--save_sections",
+ default=None,
+ is_flag=True,
+ help="Save section videos in addition to movie file.",
+ ),
option(
"-s",
"--save_last_frame",
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index 82dfa3ced..c854748a2 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -10,6 +10,9 @@ import threading
import time
import types
from queue import Queue
+from typing import List, Optional
+
+from manim.scene.section import DefaultSectionType
try:
import dearpygui.dearpygui as dpg
@@ -69,7 +72,6 @@ class Scene:
It is not recommended to override the ``__init__`` method in user Scenes. For code
that should be ran before a Scene is rendered, use :meth:`Scene.setup` instead.
-
Examples
--------
Override the :meth:`Scene.construct` method with your code.
@@ -288,6 +290,16 @@ class Scene:
"""
pass # To be implemented in subclasses
+ def next_section(
+ self,
+ name: str = "unnamed",
+ type: str = DefaultSectionType.NORMAL,
+ ) -> None:
+ """Create separation here; the last section gets finished and a new one gets created.
+ Refer to :doc:`the documentation</tutorials/a_deeper_look>` on how to use sections.
+ """
+ self.renderer.file_writer.next_section(name, type)
+
def __str__(self):
return self.__class__.__name__
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.py
index b8c41b311..c9aa80eac 100644
--- a/manim/scene/scene_file_writer.py
+++ b/manim/scene/scene_file_writer.py
@@ -3,11 +3,13 @@
__all__ = ["SceneFileWriter"]
import datetime
+import json
import os
import shutil
import subprocess
from pathlib import Path
from time import sleep
+from typing import Any, Dict, List, Optional
import numpy as np
from PIL import Image
@@ -28,6 +30,7 @@ from ..utils.file_ops import (
write_to_movie,
)
from ..utils.sounds import get_full_sound_file_path
+from .section import DefaultSectionType, Section
class SceneFileWriter:
@@ -38,6 +41,17 @@ class SceneFileWriter:
have to use the methods for this class, unless tinkering with the very
fabric of Manim's reality.
+ Attributes
+ ----------
+ sections : list of :class:`.Section`
+ used to segment scene
+
+ sections_output_dir : str
+ where are section videos stored
+
+ output_name : str
+ name of movie without extension and basis for section video names
+
Some useful attributes are:
"write_to_movie" (bool=False)
Whether or not to write the animations into a video file.
@@ -56,7 +70,10 @@ class SceneFileWriter:
self.init_output_directories(scene_name)
self.init_audio()
self.frame_count = 0
- self.partial_movie_files = []
+ self.partial_movie_files: List[str] = []
+ self.sections: List[Section] = []
+ # first section gets automatically created for convenience
+ self.next_section("autocreated", DefaultSectionType.NORMAL)
def init_output_directories(self, scene_name):
"""Initialise output directories.
@@ -77,37 +94,50 @@ class SceneFileWriter:
module_name = ""
if SceneFileWriter.force_output_as_scene_name:
- default_name = Path(scene_name)
+ self.output_name = Path(scene_name)
elif config["output_file"] and not config["write_all"]:
- default_name = config.get_dir("output_file")
+ self.output_name = config.get_dir("output_file")
else:
- default_name = Path(scene_name)
+ self.output_name = Path(scene_name)
if config["media_dir"]:
image_dir = guarantee_existence(
- config.get_dir("images_dir", module_name=module_name),
+ config.get_dir(
+ "images_dir", module_name=module_name, scene_name=scene_name
+ ),
)
self.image_file_path = os.path.join(
image_dir,
- add_extension_if_not_present(default_name, ".png"),
+ add_extension_if_not_present(self.output_name, ".png"),
)
if write_to_movie():
movie_dir = guarantee_existence(
- config.get_dir("video_dir", module_name=module_name),
+ config.get_dir(
+ "video_dir", module_name=module_name, scene_name=scene_name
+ ),
)
self.movie_file_path = os.path.join(
movie_dir,
add_extension_if_not_present(
- default_name,
+ self.output_name,
config["movie_file_extension"],
),
)
+ # TODO: /dev/null would be good in case sections_output_dir is used without bein set (doesn't work on Windows), everyone likes defensive programming, right?
+ self.sections_output_dir = ""
+ if config.save_sections:
+ self.sections_output_dir = guarantee_existence(
+ config.get_dir(
+ "sections_dir", module_name=module_name, scene_name=scene_name
+ )
+ )
+
if is_gif_format():
self.gif_file_path = os.path.join(
movie_dir,
- add_extension_if_not_present(default_name, GIF_FILE_EXTENSION),
+ add_extension_if_not_present(self.output_name, GIF_FILE_EXTENSION),
)
self.partial_movie_directory = guarantee_existence(
@@ -118,8 +148,32 @@ class SceneFileWriter:
),
)
+ def finish_last_section(self) -> None:
+ """Delete current section if it is empty."""
+ if len(self.sections) and self.sections[-1].is_empty():
+ self.sections.pop()
+
+ def next_section(self, name: str, type: str) -> None:
+ """Create segmentation cut here."""
+ self.finish_last_section()
+
+ # images don't support sections
+ section_video: Optional[str] = None
+ if not config.dry_run and write_to_movie() and config.save_sections:
+ # relative to index file
+ section_video = f"{self.output_name}_{len(self.sections):04}{config.movie_file_extension}"
+
+ self.sections.append(
+ Section(
+ type,
+ section_video,
+ name,
+ ),
+ )
+
def add_partial_movie_file(self, hash_animation):
- """Adds a new partial movie file path to scene.partial_movie_files from an hash. This method will compute the path from the hash.
+ """Adds a new partial movie file path to `scene.partial_movie_files` and current section from a hash.
+ This method will compute the path from the hash. In addition to that it adds the new animation to the current section.
Parameters
----------
@@ -133,12 +187,14 @@ class SceneFileWriter:
# i.e if an animation is skipped, scene.num_plays is still incremented and we add an element to partial_movie_file be even with num_plays.
if hash_animation is None:
self.partial_movie_files.append(None)
- return
- new_partial_movie_file = os.path.join(
- self.partial_movie_directory,
- f"{hash_animation}{config['movie_file_extension']}",
- )
- self.partial_movie_files.append(new_partial_movie_file)
+ self.sections[-1].partial_movie_files.append(None)
+ else:
+ new_partial_movie_file = os.path.join(
+ self.partial_movie_directory,
+ f"{hash_animation}{config['movie_file_extension']}",
+ )
+ self.partial_movie_files.append(new_partial_movie_file)
+ self.sections[-1].partial_movie_files.append(new_partial_movie_file)
def get_resolution_directory(self):
"""Get the name of the resolution directory directly containing
@@ -373,7 +429,9 @@ class SceneFileWriter:
if write_to_movie():
if hasattr(self, "writing_process"):
self.writing_process.terminate()
- self.combine_movie_files(partial_movie_files=partial_movie_files)
+ self.combine_to_movie(partial_movie_files=partial_movie_files)
+ if config.save_sections:
+ self.combine_to_section_videos()
if config["flush_cache"]:
self.flush_cache_directory()
else:
@@ -465,41 +523,27 @@ class SceneFileWriter:
)
return os.path.exists(path)
- def combine_movie_files(self, partial_movie_files=None):
- """
- Used internally by Manim to combine the separate
- partial movie files that make up a Scene into a single
- video file for that Scene.
- """
- # Manim renders the scene as many smaller movie files which are then
- # concatenated to a larger one. The reason for this is that sometimes
- # video-editing is made easier when one works with the broken up scene,
- # which effectively has cuts at all the places you might want. But for
- # viewing the scene as a whole, one of course wants to see it as a
- # single piece.
- partial_movie_files = [el for el in self.partial_movie_files if el is not None]
- # NOTE : Here we should do a check and raise an exception if partial
- # movie file is empty. We can't, as a lot of stuff (in particular, in
- # tests) use scene initialization, and this error would be raised as
- # it's just an empty scene initialized.
-
- # Write a file partial_file_list.txt containing all partial movie
- # files. This is used by FFMPEG.
+ def combine_files(
+ self,
+ input_files: List[str],
+ output_file: str,
+ create_gif=False,
+ includes_sound=False,
+ ):
file_list = os.path.join(
self.partial_movie_directory,
"partial_movie_file_list.txt",
)
logger.debug(
- f"Partial movie files to combine ({len(partial_movie_files)} files): %(p)s",
- {"p": partial_movie_files[:5]},
+ f"Partial movie files to combine ({len(input_files)} files): %(p)s",
+ {"p": input_files[:5]},
)
with open(file_list, "w") as fp:
fp.write("# This file is used internally by FFMPEG.\n")
- for pf_path in partial_movie_files:
+ for pf_path in input_files:
if os.name == "nt":
pf_path = pf_path.replace("\\", "/")
fp.write(f"file 'file:{pf_path}'\n")
- movie_file_path = self.movie_file_path
commands = [
FFMPEG_BIN,
"-y", # overwrite output file if it exists
@@ -510,32 +554,53 @@ class SceneFileWriter:
"-i",
file_list,
"-loglevel",
- config["ffmpeg_loglevel"].lower(),
+ config.ffmpeg_loglevel.lower(),
"-metadata",
f"comment=Rendered with Manim Community v{__version__}",
"-nostdin",
]
- if write_to_movie() and not is_gif_format():
- commands += ["-c", "copy", movie_file_path]
-
- if is_gif_format():
- if not config["output_file"]:
- self.gif_file_path = str(
- add_version_before_extension(self.gif_file_path),
- )
+ if create_gif:
commands += [
"-vf",
f"fps={np.clip(config['frame_rate'], 1, 50)},split[s0][s1];[s0]palettegen=stats_mode=diff[p];[s1][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle",
- self.gif_file_path,
]
+ else:
+ commands += ["-c", "copy"]
- if not self.includes_sound:
- commands.insert(-1, "-an")
+ if not includes_sound:
+ commands += ["-an"]
+
+ commands += [output_file]
combine_process = subprocess.Popen(commands)
combine_process.wait()
+ def combine_to_movie(self, partial_movie_files=None):
+ """Used internally by Manim to combine the separate
+ partial movie files that make up a Scene into a single
+ video file for that Scene.
+ """
+ # TODO: remove partial_movie_files from parameter <- gets immediately overwritten
+ partial_movie_files = [el for el in self.partial_movie_files if el is not None]
+ # NOTE: Here we should do a check and raise an exception if partial
+ # movie file is empty. We can't, as a lot of stuff (in particular, in
+ # tests) use scene initialization, and this error would be raised as
+ # it's just an empty scene initialized.
+
+ # determine output path
+ movie_file_path = self.movie_file_path
+ if is_gif_format() and not config["output_file"]:
+ movie_file_path = str(add_version_before_extension(self.gif_file_path))
+ logger.info("Combining to Movie file.")
+ self.combine_files(
+ partial_movie_files,
+ movie_file_path,
+ is_gif_format(),
+ self.includes_sound,
+ )
+
+ # handle sound
if self.includes_sound:
extension = config["movie_file_extension"]
sound_file_path = movie_file_path.replace(extension, ".wav")
@@ -566,7 +631,7 @@ class SceneFileWriter:
"-map",
"1:a:0",
"-loglevel",
- config["ffmpeg_loglevel"].lower(),
+ config.ffmpeg_loglevel.lower(),
"-metadata",
f"comment=Rendered with Manim Community v{__version__}",
# "-shortest",
@@ -576,14 +641,31 @@ class SceneFileWriter:
shutil.move(temp_file_path, movie_file_path)
os.remove(sound_file_path)
- self.print_file_ready_message(
- self.gif_file_path if is_gif_format() else movie_file_path,
- )
+ self.print_file_ready_message(movie_file_path)
if write_to_movie():
for file_path in partial_movie_files:
# We have to modify the accessed time so if we have to clean the cache we remove the one used the longest.
modify_atime(file_path)
+ def combine_to_section_videos(self) -> None:
+ """Concatenate partial movie files for each section."""
+
+ self.finish_last_section()
+ sections_index: List[Dict[str, Any]] = []
+ for section in self.sections:
+ # only if section does want to be saved
+ if section.video is not None:
+ logger.info(f"Combining partial files for section '{section.name}'")
+ self.combine_files(
+ section.get_clean_partial_movie_files(),
+ os.path.join(self.sections_output_dir, section.video),
+ )
+ sections_index.append(section.get_dict(self.sections_output_dir))
+ with open(
+ os.path.join(self.sections_output_dir, f"{self.output_name}.json"), "w"
+ ) as file:
+ json.dump(sections_index, file, indent=4)
+
def clean_cache(self):
"""Will clean the cache by removing the oldest partial_movie_files."""
cached_partial_movies = [
diff --git a/manim/scene/section.py b/manim/scene/section.py
new file mode 100644
index 000000000..a3cb69c5e
--- /dev/null
+++ b/manim/scene/section.py
@@ -0,0 +1,95 @@
+"""building blocks of segmented video API"""
+
+import os
+from enum import Enum
+from typing import Any, Dict, List, Optional
+
+from manim import get_video_metadata
+
+
+class DefaultSectionType(str, Enum):
+ """The type of a section can be used for third party applications.
+ A presentation system could for example use the types to created loops.
+
+ Examples
+ --------
+ This class can be reimplemented for more types::
+
+ class PresentationSectionType(str, Enum):
+ # start, end, wait for continuation by user
+ NORMAL = "presentation.normal"
+ # start, end, immediately continue to next section
+ SKIP = "presentation.skip"
+ # start, end, restart, immediately continue to next section when continued by user
+ LOOP = "presentation.loop"
+ # start, end, restart, finish animation first when user continues
+ COMPLETE_LOOP = "presentation.complete_loop"
+ """
+
+ NORMAL = "default.normal"
+
+
+class Section:
+ """A :class:`.Scene` can be segmented into multiple Sections.
+ It consists of multiple animations.
+
+ ...
+ Attributes
+ ----------
+ type
+ Can be used by a third party applications to classify different types of sections.
+ name
+ Human readable, non-unique name for this section.
+ partial_movie_files
+ Animations belonging to this section.
+ video
+ Path to video file with animations belonging to section relative to sections directory.
+ If ``None``, then the section will not be saved.
+
+ See Also
+ --------
+ :class:`.DefaultSectionType`
+ """
+
+ def __init__(self, type: str, video: Optional[str], name: str):
+ self.type = type
+ # None when not to be saved -> still keeps section alive
+ self.video: Optional[str] = video
+ self.name = name
+ self.partial_movie_files: List[Optional[str]] = []
+
+ def is_empty(self) -> bool:
+ """Check whether this section is empty.
+
+ Note that animations represented by ``None`` are also counted.
+ """
+ return len(self.partial_movie_files) == 0
+
+ def get_clean_partial_movie_files(self) -> List[str]:
+ """Return all partial movie files that are not ``None``."""
+ return [el for el in self.partial_movie_files if el is not None]
+
+ def get_dict(self, sections_dir: str) -> Dict[str, Any]:
+ """Get dictionary representation with metadata of output video.
+
+ The output from this function is used from every section to build the sections index file.
+ The output video must have been created in the ``sections_dir`` before executing this method.
+ This is the main part of the Segmented Video API.
+ """
+ if self.video is None:
+ raise ValueError(
+ f"Section '{self.name}' cannot be exported as dict, it does not have a video path assigned to it"
+ )
+
+ video_metadata = get_video_metadata(os.path.join(sections_dir, self.video))
+ return dict(
+ {
+ "name": self.name,
+ "type": self.type,
+ "video": self.video,
+ },
+ **video_metadata,
+ )
+
+ def __repr__(self):
+ return f"<Section '{self.name}' stored in '{self.video}'>"
diff --git a/manim/utils/commands.py b/manim/utils/commands.py
new file mode 100644
index 000000000..9bd00bcd6
--- /dev/null
+++ b/manim/utils/commands.py
@@ -0,0 +1,43 @@
+import json
+import os
+from subprocess import run
+from typing import Any, Dict, List
+
+__all__ = [
+ "capture",
+ "get_video_metadata",
+ "get_dir_layout",
+]
+
+
+def capture(command, cwd=None, command_input=None):
+ p = run(command, cwd=cwd, input=command_input, capture_output=True, text=True)
+ out, err = p.stdout, p.stderr
+ return out, err, p.returncode
+
+
+def get_video_metadata(path_to_video: str) -> Dict[str, Any]:
+ command = [
+ "ffprobe",
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "stream=width,height,nb_frames,duration,avg_frame_rate,codec_name",
+ "-print_format",
+ "json",
+ path_to_video,
+ ]
+ config, err, exitcode = capture(command)
+ assert exitcode == 0, f"FFprobe error: {err}"
+ return json.loads(config)["streams"][0]
+
+
+def get_dir_layout(dirpath: str) -> List[str]:
+ """Get list of paths relative to dirpath of all files in dir and subdirs recursively."""
+ index_files: List[str] = []
+ for root, dirs, files in os.walk(dirpath):
+ for file in files:
+ index_files.append(f"{os.path.relpath(os.path.join(root, file), dirpath)}")
+ return index_files
diff --git a/manim/utils/file_ops.py b/manim/utils/file_ops.py
index dfb692d45..173025e07 100644
--- a/manim/utils/file_ops.py
+++ b/manim/utils/file_ops.py
@@ -3,6 +3,7 @@
__all__ = [
"add_extension_if_not_present",
"guarantee_existence",
+ "guarantee_empty_existence",
"seek_full_path_from_defaults",
"modify_atime",
"open_file",
@@ -16,6 +17,7 @@ __all__ = [
import os
import platform
+import shutil
import subprocess as sp
import time
from pathlib import Path
@@ -132,6 +134,13 @@ def guarantee_existence(path):
return os.path.abspath(path)
+def guarantee_empty_existence(path):
+ if os.path.exists(path):
+ shutil.rmtree(path)
+ os.makedirs(path)
+ return os.path.abspath(path)
+
+
def seek_full_path_from_defaults(file_name, default_dir, extensions):
possible_paths = [file_name]
possible_paths += [
diff --git a/tests/assert_utils.py b/tests/assert_utils.py
index 039b57369..a71d439f3 100644
--- a/tests/assert_utils.py
+++ b/tests/assert_utils.py
@@ -1,11 +1,11 @@
-import typing
-from os import PathLike
+import os
from pathlib import Path
from pprint import pformat
+from typing import Dict, List, Union
-def assert_file_exists(filepath: typing.Union[str, PathLike]) -> None:
- """Assert if filepath points to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath.
+def assert_file_exists(filepath: Union[str, os.PathLike]) -> None:
+ """Assert that filepath points to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath.
This is mostly to have better assert message than using a raw assert os.path.isfile(filepath).
@@ -21,5 +21,107 @@ def assert_file_exists(filepath: typing.Union[str, PathLike]) -> None:
"""
path = Path(filepath)
if not path.is_file():
- message = f"{path.absolute()} is not a file. Other elements in the parent directory are \n{pformat([path.name for path in list(path.parent.iterdir())])}"
+ elems = pformat([path.name for path in list(path.parent.iterdir())])
+ message = f"{path.absolute()} is not a file. Other elements in the parent directory are \n{elems}"
raise AssertionError(message)
+
+
+def assert_dir_exists(dirpath: Union[str, os.PathLike]) -> None:
+ """Assert that directory exists.
+
+ Parameters
+ ----------
+ dirpath
+ Path to directory to check.
+
+ Raises
+ ------
+ AssertionError
+ If dirpath does not point to a directory (if the file does exist or it's a file).
+ """
+ path = Path(dirpath)
+ if not path.is_dir():
+ elems = pformat([path.name for path in list(path.parent.iterdir())])
+ message = f"{path.absolute()} is not a directory. Other elements in the parent directory are \n{elems}"
+ raise AssertionError(message)
+
+
+def assert_dir_filled(dirpath: Union[str, os.PathLike]) -> None:
+ """Assert that directory exists and contains at least one file or directory (or file like objects like symlinks on Linux).
+
+ Parameters
+ ----------
+ dirpath
+ Path to directory to check.
+
+ Raises
+ ------
+ AssertionError
+ If dirpath does not point to a directory (if the file does exist or it's a file) or the directory is empty.
+ """
+ if len(os.listdir(dirpath)) == 0:
+ raise AssertionError(f"{dirpath} is an empty directory.")
+
+
+def assert_file_not_exists(filepath: Union[str, os.PathLike]) -> None:
+ """Assert that filepath does not point to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath.
+
+ This is mostly to have better assert message than using a raw assert os.path.isfile(filepath).
+
+ Parameters
+ ----------
+ filepath
+ Filepath to check.
+
+ Raises
+ ------
+ AssertionError
+ If filepath does point to a file.
+ """
+ path = Path(filepath)
+ if path.is_file():
+ elems = pformat([path.name for path in list(path.parent.iterdir())])
+ message = f"{path.absolute()} is a file. Other elements in the parent directory are \n{elems}"
+ raise AssertionError(message)
+
+
+def assert_dir_not_exists(dirpath: Union[str, os.PathLike]) -> None:
+ """Assert that directory does not exist.
+
+ Parameters
+ ----------
+ dirpath
+ Path to directory to check.
+
+ Raises
+ ------
+ AssertionError
+ If dirpath points to a directory.
+ """
+ path = Path(dirpath)
+ if path.is_dir():
+ elems = pformat([path.name for path in list(path.parent.iterdir())])
+ message = f"{path.absolute()} is a directory. Other elements in the parent directory are \n{elems}"
+ raise AssertionError(message)
+
+
+def assert_shallow_dict_compare(a: Dict, b: Dict, message_start: str) -> None:
+ """Assert that Directories ``a`` and ``b`` are the same.
+
+ ``b`` is treated as the expected values that ``a`` shall abide by.
+ Print helpful error with custom message start.
+ """
+ mismatch: List[str] = []
+
+ for b_key, b_value in b.items():
+ if b_key not in a:
+ mismatch.append(f"Missing item {b_key}: {b_value}")
+ elif b_value != a[b_key]:
+ mismatch.append(f"For {b_key} got {a[b_key]}, expected {b_value}")
+
+ for a_key, a_value in a.items():
+ if a_key not in b:
+ mismatch.append(f"Extraneous item {a_key}: {a_value}")
+
+ mismatch_str = "\n".join(mismatch)
+ assert len(mismatch) == 0, f"{message_start}\n{mismatch_str}"
diff --git a/tests/control_data/graphical_units_data/boolean_ops/intersection_3_mobjects.npz b/tests/control_data/graphical_units_data/boolean_ops/intersection_3_mobjects.npz
index 6a751cc25..61a46e7c2 100644
Binary files a/tests/control_data/graphical_units_data/boolean_ops/intersection_3_mobjects.npz and b/tests/control_data/graphical_units_data/boolean_ops/intersection_3_mobjects.npz differ
diff --git a/tests/control_data/graphical_units_data/coordinate_system/implicit_graph.npz b/tests/control_data/graphical_units_data/coordinate_system/implicit_graph.npz
index 6d37ffbd5..9e290fb38 100644
Binary files a/tests/control_data/graphical_units_data/coordinate_system/implicit_graph.npz and b/tests/control_data/graphical_units_data/coordinate_system/implicit_graph.npz differ
diff --git a/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz b/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz
index 3ca51a4ad..bc61eb4ca 100644
Binary files a/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz and b/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz differ
diff --git a/tests/control_data/graphical_units_data/functions/ImplicitFunction.npz b/tests/control_data/graphical_units_data/functions/ImplicitFunction.npz
index 3ec761219..b9dbe9ec9 100644
Binary files a/tests/control_data/graphical_units_data/functions/ImplicitFunction.npz and b/tests/control_data/graphical_units_data/functions/ImplicitFunction.npz differ
diff --git a/tests/control_data/graphical_units_data/geometry/AngledArrowTip.npz b/tests/control_data/graphical_units_data/geometry/AngledArrowTip.npz
index b58c267c9..77a28aa9d 100644
Binary files a/tests/control_data/graphical_units_data/geometry/AngledArrowTip.npz and b/tests/control_data/graphical_units_data/geometry/AngledArrowTip.npz differ
diff --git a/tests/control_data/graphical_units_data/numbers/set_value_with_updaters.npz b/tests/control_data/graphical_units_data/numbers/set_value_with_updaters.npz
index 9f6bbd239..f0cbfa5f6 100644
Binary files a/tests/control_data/graphical_units_data/numbers/set_value_with_updaters.npz and b/tests/control_data/graphical_units_data/numbers/set_value_with_updaters.npz differ
diff --git a/tests/control_data/graphical_units_data/opengl/Circle.npz b/tests/control_data/graphical_units_data/opengl/Circle.npz
index 7d0da35b4..5dd50f220 100644
Binary files a/tests/control_data/graphical_units_data/opengl/Circle.npz and b/tests/control_data/graphical_units_data/opengl/Circle.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/custom_coordinates.npz b/tests/control_data/graphical_units_data/plot/custom_coordinates.npz
index c809a9c8b..1072beb40 100644
Binary files a/tests/control_data/graphical_units_data/plot/custom_coordinates.npz and b/tests/control_data/graphical_units_data/plot/custom_coordinates.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_axis_labels.npz b/tests/control_data/graphical_units_data/plot/get_axis_labels.npz
index 045e01fc5..13efe929c 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_axis_labels.npz and b/tests/control_data/graphical_units_data/plot/get_axis_labels.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_derivative_graph.npz b/tests/control_data/graphical_units_data/plot/get_derivative_graph.npz
index da26cc739..f5d5675bd 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_derivative_graph.npz and b/tests/control_data/graphical_units_data/plot/get_derivative_graph.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_graph.npz b/tests/control_data/graphical_units_data/plot/get_graph.npz
index 95f55bd68..24c2c89c4 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_graph.npz and b/tests/control_data/graphical_units_data/plot/get_graph.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_graph_label.npz b/tests/control_data/graphical_units_data/plot/get_graph_label.npz
index 2d5378ac6..62f1b9412 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_graph_label.npz and b/tests/control_data/graphical_units_data/plot/get_graph_label.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_line_graph.npz b/tests/control_data/graphical_units_data/plot/get_line_graph.npz
index a184d41bd..f0abcb64c 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_line_graph.npz and b/tests/control_data/graphical_units_data/plot/get_line_graph.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_lines_to_point.npz b/tests/control_data/graphical_units_data/plot/get_lines_to_point.npz
index 28c7320a6..f56f66165 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_lines_to_point.npz and b/tests/control_data/graphical_units_data/plot/get_lines_to_point.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_riemann_rectangles.npz b/tests/control_data/graphical_units_data/plot/get_riemann_rectangles.npz
index fe6f3b25f..ec8b72487 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_riemann_rectangles.npz and b/tests/control_data/graphical_units_data/plot/get_riemann_rectangles.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_x_axis_label.npz b/tests/control_data/graphical_units_data/plot/get_x_axis_label.npz
index 00a86ad16..2a40a89eb 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_x_axis_label.npz and b/tests/control_data/graphical_units_data/plot/get_x_axis_label.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_y_axis_label.npz b/tests/control_data/graphical_units_data/plot/get_y_axis_label.npz
index 85b66917b..c77c1af89 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_y_axis_label.npz and b/tests/control_data/graphical_units_data/plot/get_y_axis_label.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/get_z_axis_label.npz b/tests/control_data/graphical_units_data/plot/get_z_axis_label.npz
index 5c895fb07..ef0d5c9b6 100644
Binary files a/tests/control_data/graphical_units_data/plot/get_z_axis_label.npz and b/tests/control_data/graphical_units_data/plot/get_z_axis_label.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/plot_functions.npz b/tests/control_data/graphical_units_data/plot/plot_functions.npz
index cbc827053..b35cdc6d5 100644
Binary files a/tests/control_data/graphical_units_data/plot/plot_functions.npz and b/tests/control_data/graphical_units_data/plot/plot_functions.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/t_label.npz b/tests/control_data/graphical_units_data/plot/t_label.npz
index 20c9f633c..275b005c1 100644
Binary files a/tests/control_data/graphical_units_data/plot/t_label.npz and b/tests/control_data/graphical_units_data/plot/t_label.npz differ
diff --git a/tests/control_data/graphical_units_data/polyhedra/Dodecahedron.npz b/tests/control_data/graphical_units_data/polyhedra/Dodecahedron.npz
index eb55f0b8a..efcffa9be 100644
Binary files a/tests/control_data/graphical_units_data/polyhedra/Dodecahedron.npz and b/tests/control_data/graphical_units_data/polyhedra/Dodecahedron.npz differ
diff --git a/tests/control_data/graphical_units_data/polyhedra/Icosahedron.npz b/tests/control_data/graphical_units_data/polyhedra/Icosahedron.npz
index 35c305c45..5d92be49d 100644
Binary files a/tests/control_data/graphical_units_data/polyhedra/Icosahedron.npz and b/tests/control_data/graphical_units_data/polyhedra/Icosahedron.npz differ
diff --git a/tests/control_data/graphical_units_data/polyhedra/Octahedron.npz b/tests/control_data/graphical_units_data/polyhedra/Octahedron.npz
index d3c68c71c..5693a5148 100644
Binary files a/tests/control_data/graphical_units_data/polyhedra/Octahedron.npz and b/tests/control_data/graphical_units_data/polyhedra/Octahedron.npz differ
diff --git a/tests/control_data/graphical_units_data/polyhedra/Tetrahedron.npz b/tests/control_data/graphical_units_data/polyhedra/Tetrahedron.npz
index 726d27498..ac08a2e95 100644
Binary files a/tests/control_data/graphical_units_data/polyhedra/Tetrahedron.npz and b/tests/control_data/graphical_units_data/polyhedra/Tetrahedron.npz differ
diff --git a/tests/control_data/graphical_units_data/tables/DecimalTable.npz b/tests/control_data/graphical_units_data/tables/DecimalTable.npz
index d286f69fc..1ad152996 100644
Binary files a/tests/control_data/graphical_units_data/tables/DecimalTable.npz and b/tests/control_data/graphical_units_data/tables/DecimalTable.npz differ
diff --git a/tests/control_data/graphical_units_data/tables/IntegerTable.npz b/tests/control_data/graphical_units_data/tables/IntegerTable.npz
index 4b48a4cb1..a05f0b48f 100644
Binary files a/tests/control_data/graphical_units_data/tables/IntegerTable.npz and b/tests/control_data/graphical_units_data/tables/IntegerTable.npz differ
diff --git a/tests/control_data/graphical_units_data/tables/MathTable.npz b/tests/control_data/graphical_units_data/tables/MathTable.npz
index d9caa4257..dce2ae8db 100644
Binary files a/tests/control_data/graphical_units_data/tables/MathTable.npz and b/tests/control_data/graphical_units_data/tables/MathTable.npz differ
diff --git a/tests/control_data/graphical_units_data/tables/MobjectTable.npz b/tests/control_data/graphical_units_data/tables/MobjectTable.npz
index 8922f42b4..7662aa068 100644
Binary files a/tests/control_data/graphical_units_data/tables/MobjectTable.npz and b/tests/control_data/graphical_units_data/tables/MobjectTable.npz differ
diff --git a/tests/control_data/graphical_units_data/tables/Table.npz b/tests/control_data/graphical_units_data/tables/Table.npz
index 458376b0e..008730faf 100644
Binary files a/tests/control_data/graphical_units_data/tables/Table.npz and b/tests/control_data/graphical_units_data/tables/Table.npz differ
diff --git a/tests/control_data/graphical_units_data/threed/CameraMove.npz b/tests/control_data/graphical_units_data/threed/CameraMove.npz
index 1f4226c6f..a24c4b77e 100644
Binary files a/tests/control_data/graphical_units_data/threed/CameraMove.npz and b/tests/control_data/graphical_units_data/threed/CameraMove.npz differ
diff --git a/tests/control_data/graphical_units_data/threed/CameraMoveAxes.npz b/tests/control_data/graphical_units_data/threed/CameraMoveAxes.npz
index 741d59601..a8257cdd3 100644
Binary files a/tests/control_data/graphical_units_data/threed/CameraMoveAxes.npz and b/tests/control_data/graphical_units_data/threed/CameraMoveAxes.npz differ
diff --git a/tests/control_data/graphical_units_data/threed/Dot3D.npz b/tests/control_data/graphical_units_data/threed/Dot3D.npz
index e946ae235..084c5ec0e 100644
Binary files a/tests/control_data/graphical_units_data/threed/Dot3D.npz and b/tests/control_data/graphical_units_data/threed/Dot3D.npz differ
diff --git a/tests/control_data/graphical_units_data/threed/Sphere.npz b/tests/control_data/graphical_units_data/threed/Sphere.npz
index a0dcfc426..67ae84bdd 100644
Binary files a/tests/control_data/graphical_units_data/threed/Sphere.npz and b/tests/control_data/graphical_units_data/threed/Sphere.npz differ
diff --git a/tests/control_data/graphical_units_data/vector_scene/vector_to_coords.npz b/tests/control_data/graphical_units_data/vector_scene/vector_to_coords.npz
index 93fb2408a..d473bdb36 100644
Binary files a/tests/control_data/graphical_units_data/vector_scene/vector_to_coords.npz and b/tests/control_data/graphical_units_data/vector_scene/vector_to_coords.npz differ
diff --git a/tests/control_data/logs_data/BasicSceneLoggingTest.txt b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
index ef2f418b7..de56ea93c 100644
--- a/tests/control_data/logs_data/BasicSceneLoggingTest.txt
+++ b/tests/control_data/logs_data/BasicSceneLoggingTest.txt
@@ -4,6 +4,7 @@
{"levelname": "DEBUG", "module": "hashing", "message": "Hash generated : <>"}
{"levelname": "DEBUG", "module": "cairo_renderer", "message": "List of the first few animation hashes of the scene: <>"}
{"levelname": "INFO", "module": "scene_file_writer", "message": "Animation 0 : Partial movie file written in <>"}
+{"levelname": "INFO", "module": "scene_file_writer", "message": "Combining to Movie file."}
{"levelname": "DEBUG", "module": "scene_file_writer", "message": "Partial movie files to combine (1 files): <>"}
{"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/control_data/videos_data/SceneWithDisabledSections.json b/tests/control_data/videos_data/SceneWithDisabledSections.json
new file mode 100644
index 000000000..e524af09c
--- /dev/null
+++ b/tests/control_data/videos_data/SceneWithDisabledSections.json
@@ -0,0 +1,13 @@
+{
+ "name": "SceneWithDisabledSections",
+ "movie_metadata": {
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "1.000000",
+ "nb_frames": "15"
+ },
+ "section_dir_layout": [],
+ "section_index": []
+}
diff --git a/tests/control_data/videos_data/SceneWithEnabledSections.json b/tests/control_data/videos_data/SceneWithEnabledSections.json
new file mode 100644
index 000000000..7f0656b81
--- /dev/null
+++ b/tests/control_data/videos_data/SceneWithEnabledSections.json
@@ -0,0 +1,29 @@
+{
+ "name": "SceneWithEnabledSections",
+ "movie_metadata": {
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "1.000000",
+ "nb_frames": "15"
+ },
+ "section_dir_layout": [
+ "SquareToCircle.json",
+ "SquareToCircle_0000.mp4",
+ "."
+ ],
+ "section_index": [
+ {
+ "name": "autocreated",
+ "type": "default.normal",
+ "video": "SquareToCircle_0000.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "1.000000",
+ "nb_frames": "15"
+ }
+ ]
+}
diff --git a/tests/control_data/videos_data/SceneWithMultipleCallsWithNFlag.json b/tests/control_data/videos_data/SceneWithMultipleCallsWithNFlag.json
index 134f5c9b4..55b511f84 100644
--- a/tests/control_data/videos_data/SceneWithMultipleCallsWithNFlag.json
+++ b/tests/control_data/videos_data/SceneWithMultipleCallsWithNFlag.json
@@ -1,11 +1,13 @@
{
"name": "SceneWithMultipleCallsWithNFlag",
- "config": {
+ "movie_metadata": {
"codec_name": "h264",
"width": 1920,
"height": 1080,
"avg_frame_rate": "60/1",
"duration": "4.000000",
"nb_frames": "240"
- }
+ },
+ "section_dir_layout": [],
+ "section_index": []
}
diff --git a/tests/control_data/videos_data/SceneWithMultiplePlayCallsWithNFlag.json b/tests/control_data/videos_data/SceneWithMultiplePlayCallsWithNFlag.json
index 90249f75b..d7117145f 100644
--- a/tests/control_data/videos_data/SceneWithMultiplePlayCallsWithNFlag.json
+++ b/tests/control_data/videos_data/SceneWithMultiplePlayCallsWithNFlag.json
@@ -1,11 +1,13 @@
{
"name": "SceneWithMultiplePlayCallsWithNFlag",
- "config": {
+ "movie_metadata": {
"codec_name": "h264",
"width": 854,
"height": 480,
"avg_frame_rate": "15/1",
"duration": "7.000000",
"nb_frames": "105"
- }
+ },
+ "section_dir_layout": [],
+ "section_index": []
}
diff --git a/tests/control_data/videos_data/SceneWithMultipleWaitCallsWithNFlag.json b/tests/control_data/videos_data/SceneWithMultipleWaitCallsWithNFlag.json
index 7b221eff4..9640c3cc3 100644
--- a/tests/control_data/videos_data/SceneWithMultipleWaitCallsWithNFlag.json
+++ b/tests/control_data/videos_data/SceneWithMultipleWaitCallsWithNFlag.json
@@ -1,11 +1,13 @@
{
"name": "SceneWithMultipleWaitCallsWithNFlag",
- "config": {
+ "movie_metadata": {
"codec_name": "h264",
"width": 854,
"height": 480,
"avg_frame_rate": "15/1",
"duration": "5.000000",
"nb_frames": "75"
- }
+ },
+ "section_dir_layout": [],
+ "section_index": []
}
diff --git a/tests/control_data/videos_data/SceneWithSections.json b/tests/control_data/videos_data/SceneWithSections.json
new file mode 100644
index 000000000..4b56d518e
--- /dev/null
+++ b/tests/control_data/videos_data/SceneWithSections.json
@@ -0,0 +1,77 @@
+{
+ "name": "SceneWithSections",
+ "movie_metadata": {
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "7.000000",
+ "nb_frames": "105"
+ },
+ "section_dir_layout": [
+ "SceneWithSections_0004.mp4",
+ "SceneWithSections_0003.mp4",
+ "SceneWithSections_0002.mp4",
+ "SceneWithSections_0001.mp4",
+ "SceneWithSections.json",
+ "SceneWithSections_0000.mp4",
+ "."
+ ],
+ "section_index": [
+ {
+ "name": "autocreated",
+ "type": "default.normal",
+ "video": "SceneWithSections_0000.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "1.000000",
+ "nb_frames": "15"
+ },
+ {
+ "name": "unnamed",
+ "type": "default.normal",
+ "video": "SceneWithSections_0001.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "2.000000",
+ "nb_frames": "30"
+ },
+ {
+ "name": "test",
+ "type": "default.normal",
+ "video": "SceneWithSections_0002.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "1.000000",
+ "nb_frames": "15"
+ },
+ {
+ "name": "Prepare For Unforeseen Consequences.",
+ "type": "default.normal",
+ "video": "SceneWithSections_0003.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "2.000000",
+ "nb_frames": "30"
+ },
+ {
+ "name": "unnamed",
+ "type": "presentation.skip",
+ "video": "SceneWithSections_0004.mp4",
+ "codec_name": "h264",
+ "width": 854,
+ "height": 480,
+ "avg_frame_rate": "15/1",
+ "duration": "1.000000",
+ "nb_frames": "15"
+ }
+ ]
+}
diff --git a/tests/control_data/videos_data/SquareToCircleWithDefaultValues.json b/tests/control_data/videos_data/SquareToCircleWithDefaultValues.json
index 8e836445c..9625ff36c 100644
--- a/tests/control_data/videos_data/SquareToCircleWithDefaultValues.json
+++ b/tests/control_data/videos_data/SquareToCircleWithDefaultValues.json
@@ -1,11 +1,13 @@
{
- "name": "SquareToCircle",
- "config": {
+ "name": "SquareToCircleWithDefaultValues",
+ "movie_metadata": {
"codec_name": "h264",
"width": 1920,
"height": 1080,
"avg_frame_rate": "60/1",
"duration": "1.000000",
"nb_frames": "60"
- }
+ },
+ "section_dir_layout": [],
+ "section_index": []
}
diff --git a/tests/control_data/videos_data/SquareToCircleWithlFlag.json b/tests/control_data/videos_data/SquareToCircleWithlFlag.json
index 4473dd980..ce3ef9387 100644
--- a/tests/control_data/videos_data/SquareToCircleWithlFlag.json
+++ b/tests/control_data/videos_data/SquareToCircleWithlFlag.json
@@ -1,11 +1,13 @@
{
"name": "SquareToCircleWithlFlag",
- "config": {
+ "movie_metadata": {
"codec_name": "h264",
"width": 854,
"height": 480,
"avg_frame_rate": "15/1",
"duration": "1.000000",
"nb_frames": "15"
- }
+ },
+ "section_dir_layout": [],
+ "section_index": []
}
diff --git a/tests/helpers/video_utils.py b/tests/helpers/video_utils.py
index 64c413049..03380fa19 100644
--- a/tests/helpers/video_utils.py
+++ b/tests/helpers/video_utils.py
@@ -2,43 +2,43 @@
import json
import os
-import subprocess
+import pathlib
+from typing import Any, Dict, List
-from manim import logger
+from manim import get_dir_layout, get_video_metadata, logger
-def capture(command):
- proc = subprocess.Popen(
- command,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- encoding="utf8",
- )
- out, err = proc.communicate()
- return out, err, proc.returncode
-
-
-def get_config_from_video(path_to_video):
- command = [
- "ffprobe",
- "-v",
- "error",
- "-select_streams",
- "v:0",
- "-show_entries",
- "stream=width,height,nb_frames,duration,avg_frame_rate,codec_name",
- "-print_format",
- "json",
- path_to_video,
- ]
- config, err, exitcode = capture(command)
- assert exitcode == 0, err
- return config
-
-
-def save_control_data_from_video(path_to_video, name):
- """Helper used to set up a new test that will compare videos. This will create a new .json file in control_data/videos_data that contains
- information tested of the video, including its hash. Refer to the wiki for more information.
+def get_section_dir_layout(dirpath: str) -> List[str]:
+ """Return a list of all files in the sections directory."""
+ # test if sections have been created in the first place, doesn't work with multiple scene but this isn't an issue with tests
+ if not os.path.isdir(dirpath):
+ return []
+ files = get_dir_layout(dirpath)
+ # indicate that the sections directory has been created
+ files.append(".")
+ return files
+
+
+def get_section_index(metapath: str) -> List[Dict[str, Any]]:
+ """Return content of sections index file."""
+ parent_folder = pathlib.Path(metapath).parent.absolute()
+ # test if sections have been created in the first place
+ if not os.path.isdir(parent_folder):
+ return []
+ with open(metapath) as file:
+ index = json.load(file)
+ return index
+
+
+def save_control_data_from_video(path_to_video: str, name: str) -> None:
+ """Helper used to set up a new test that will compare videos.
+
+ This will create a new ``.json`` file in ``control_data/videos_data`` that contains:
+ - the name of the video,
+ - the metadata of the video, like fps and resolution and
+ - the paths of all files in the sections subdirectory (like section videos).
+
+ Refer to the documentation for more information.
Parameters
----------
@@ -46,13 +46,29 @@ def save_control_data_from_video(path_to_video, name):
Path to the video to extract information from.
name : :class:`str`
Name of the test. The .json file will be named with it.
+
+ See Also
+ --------
+ tests/utils/video_tester.py : read control data and compare with output of test
"""
+ path_to_sections = os.path.join(
+ pathlib.Path(path_to_video).parent.absolute(), "sections"
+ )
tests_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
path_control_data = os.path.join(tests_directory, "control_data", "videos_data")
- config_video = get_config_from_video(path_to_video)
+ # this is the name of the section used in the test, not the name of the test itself, it can be found as a parameter of this function
+ scene_name = "".join(os.path.basename(path_to_video).split(".")[:-1])
+
+ movie_metadata = get_video_metadata(path_to_video)
+ section_dir_layout = get_section_dir_layout(path_to_sections)
+ section_index = get_section_index(
+ os.path.join(path_to_sections, f"{scene_name}.json")
+ )
data = {
"name": name,
- "config": json.loads(config_video)["streams"][0],
+ "movie_metadata": movie_metadata,
+ "section_dir_layout": section_dir_layout,
+ "section_index": section_index,
}
path_saved = os.path.join(path_control_data, f"{name}.json")
with open(path_saved, "w") as f:
diff --git a/tests/test_commands.py b/tests/test_commands.py
index 7358f9044..e9f537840 100644
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -4,15 +4,11 @@ from textwrap import dedent
from click.testing import CliRunner
-from manim import __version__
+from manim import __version__, capture
from manim.__main__ import main
-from .utils.video_tester import *
-
def test_manim_version():
- command = ["--version"]
-
command = [
sys.executable,
"-m",
diff --git a/tests/test_config.py b/tests/test_config.py
index e4cd1b390..3d57f6a03 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -1,9 +1,11 @@
+import os
import tempfile
from pathlib import Path
import numpy as np
-from manim import WHITE, Scene, Square, config, tempconfig
+from manim import WHITE, Scene, Square, Tex, Text, config, tempconfig
+from tests.assert_utils import assert_dir_exists, assert_dir_filled, assert_file_exists
def test_tempconfig():
@@ -32,6 +34,8 @@ def test_tempconfig():
class MyScene(Scene):
def construct(self):
self.add(Square())
+ self.add(Text("Prepare for unforeseen consequencesλ"))
+ self.add(Tex(r"$\lambda$"))
self.wait(1)
@@ -73,6 +77,7 @@ def test_digest_file(tmp_path):
[CLI]
media_dir = this_is_my_favorite_path
video_dir = {media_dir}/videos
+ sections_dir = {media_dir}/{scene_name}/prepare_for_unforeseen_consequences
frame_height = 10
""",
)
@@ -81,6 +86,50 @@ def test_digest_file(tmp_path):
assert config.get_dir("media_dir") == Path("this_is_my_favorite_path")
assert config.get_dir("video_dir") == Path("this_is_my_favorite_path/videos")
+ assert config.get_dir("sections_dir", scene_name="test") == Path(
+ "this_is_my_favorite_path/test/prepare_for_unforeseen_consequences"
+ )
+
+
+def test_custom_dirs(tmp_path):
+ with tempconfig(
+ {
+ "media_dir": tmp_path,
+ "save_sections": True,
+ "frame_rate": 15,
+ "pixel_height": 854,
+ "pixel_width": 480,
+ "save_sections": True,
+ "sections_dir": "{media_dir}/test_sections",
+ "video_dir": "{media_dir}/test_video",
+ "partial_movie_dir": "{media_dir}/test_partial_movie_dir",
+ "images_dir": "{media_dir}/test_images",
+ "text_dir": "{media_dir}/test_text",
+ "tex_dir": "{media_dir}/test_tex",
+ }
+ ):
+ scene = MyScene()
+ scene.render()
+
+ assert_dir_filled(os.path.join(tmp_path, "test_sections"))
+ assert_file_exists(os.path.join(tmp_path, "test_sections", "MyScene.json"))
+
+ assert_dir_filled(os.path.join(tmp_path, "test_video"))
+ assert_file_exists(os.path.join(tmp_path, "test_video", "MyScene.mp4"))
+
+ assert_dir_filled(os.path.join(tmp_path, "test_partial_movie_dir"))
+ assert_file_exists(
+ os.path.join(
+ tmp_path, "test_partial_movie_dir", "partial_movie_file_list.txt"
+ )
+ )
+
+ # TODO: another example with image output would be nice
+ assert_dir_exists(os.path.join(tmp_path, "test_images"))
+
+ assert_dir_filled(os.path.join(tmp_path, "test_text"))
+ assert_dir_filled(os.path.join(tmp_path, "test_tex"))
+ # TODO: testing the log dir would be nice but it doesn't get generated for some reason and test crashes when setting "log_to_file" to True
def test_frame_size(tmp_path):
diff --git a/tests/test_file_ops.py b/tests/test_file_ops.py
new file mode 100644
index 000000000..3be484d60
--- /dev/null
+++ b/tests/test_file_ops.py
@@ -0,0 +1,30 @@
+import os
+
+from manim import *
+
+from .assert_utils import assert_dir_exists, assert_file_not_exists
+from .utils.video_tester import *
+
+
+def test_guarantee_existence(tmp_path):
+ test_dir = os.path.join(tmp_path, "test")
+ guarantee_existence(test_dir)
+ # test if file dir got created
+ assert_dir_exists(test_dir)
+ f = open(os.path.join(test_dir, "test.txt"), "x")
+ f.close()
+ # test if file didn't get deleted
+ guarantee_existence(test_dir)
+
+
+def test_guarantee_empty_existence(tmp_path):
+ test_dir = os.path.join(tmp_path, "test")
+ os.mkdir(test_dir)
+ f = open(os.path.join(test_dir, "test.txt"), "x")
+ f.close()
+
+ guarantee_empty_existence(test_dir)
+ # test if dir got created
+ assert_dir_exists(test_dir)
+ # test if dir got cleaned
+ assert_file_not_exists(os.path.join(test_dir, "test.txt"))
diff --git a/tests/test_graphical_units/testing/_test_class_makers.py b/tests/test_graphical_units/testing/_test_class_makers.py
index 39947332c..3f0174ffd 100644
--- a/tests/test_graphical_units/testing/_test_class_makers.py
+++ b/tests/test_graphical_units/testing/_test_class_makers.py
@@ -44,6 +44,9 @@ class DummySceneFileWriter(SceneFileWriter):
def init_output_directories(self, scene_name):
pass
+ def next_section(self, type, name=None):
+ pass
+
def add_partial_movie_file(self, hash_animation):
pass
@@ -53,7 +56,11 @@ class DummySceneFileWriter(SceneFileWriter):
def end_animation(self, allow_write):
pass
- def combine_movie_files(self, partial_movie_files):
+ # TODO: remove redundant partial_movie_files parameter
+ def combine_to_movie(self, partial_movie_files):
+ pass
+
+ def combine_to_section_videos(self):
pass
def clean_cache(self):
diff --git a/tests/test_graphical_units/testing/frames_comparison.py b/tests/test_graphical_units/testing/frames_comparison.py
index 0ebe42ecf..83607f054 100644
--- a/tests/test_graphical_units/testing/frames_comparison.py
+++ b/tests/test_graphical_units/testing/frames_comparison.py
@@ -118,7 +118,7 @@ def frames_comparison(
size_frame=(config_tests["pixel_height"], config_tests["pixel_width"]),
)
- # Isolate the config used for the test, to avoid a modifying the global config during the test run.
+ # Isolate the config used for the test, to avoid modifying the global config during the test run.
with tempconfig({**config_tests, **custom_config}):
real_test()
diff --git a/tests/test_logging/test_logging.py b/tests/test_logging/test_logging.py
index 354b35f3c..78c3849d9 100644
--- a/tests/test_logging/test_logging.py
+++ b/tests/test_logging/test_logging.py
@@ -2,7 +2,8 @@ import os
import re
from pathlib import Path
-from ..utils.commands import capture
+from manim import capture
+
from ..utils.logging_tester import *
diff --git a/tests/test_plugins/test_plugins.py b/tests/test_plugins/test_plugins.py
index 641c8ce80..42bdfefe1 100644
--- a/tests/test_plugins/test_plugins.py
+++ b/tests/test_plugins/test_plugins.py
@@ -6,7 +6,7 @@ from pathlib import Path
import pytest
-from ..utils.commands import capture
+from manim import capture
plugin_pyproject_template = textwrap.dedent(
"""\
diff --git a/tests/test_scene_rendering/opengl/test_caching_related_opengl.py b/tests/test_scene_rendering/opengl/test_caching_related_opengl.py
index 63e0b43dd..0e1dc163c 100644
--- a/tests/test_scene_rendering/opengl/test_caching_related_opengl.py
+++ b/tests/test_scene_rendering/opengl/test_caching_related_opengl.py
@@ -1,6 +1,10 @@
import sys
-from ...utils.video_tester import *
+import pytest
+
+from manim import capture
+
+from ...utils.video_tester import video_comparison
@pytest.mark.slow
diff --git a/tests/test_scene_rendering/opengl/test_cli_flags_opengl.py b/tests/test_scene_rendering/opengl/test_cli_flags_opengl.py
index 17beb207b..68023a33f 100644
--- a/tests/test_scene_rendering/opengl/test_cli_flags_opengl.py
+++ b/tests/test_scene_rendering/opengl/test_cli_flags_opengl.py
@@ -1,12 +1,14 @@
import sys
import numpy as np
+import pytest
from click.testing import CliRunner
from PIL import Image
+from manim import capture
from manim.__main__ import main
from manim.utils.file_ops import add_version_before_extension
-from tests.utils.video_tester import *
+from tests.utils.video_tester import video_comparison
@pytest.mark.slow
diff --git a/tests/test_scene_rendering/simple_scenes.py b/tests/test_scene_rendering/simple_scenes.py
index ff0d2e5cb..94a92c183 100644
--- a/tests/test_scene_rendering/simple_scenes.py
+++ b/tests/test_scene_rendering/simple_scenes.py
@@ -48,3 +48,56 @@ class SceneWithNonStaticWait(Scene):
s.add_updater(lambda mob, dt: None)
self.add(s)
self.wait()
+
+
+class SceneWithSections(Scene):
+ def construct(self):
+ # this would be defined in a third party application using the segmented video API
+ class PresentationSectionType(str, Enum):
+ # start, end, wait for continuation by user
+ NORMAL = "presentation.normal"
+ # start, end, immediately continue to next section
+ SKIP = "presentation.skip"
+ # start, end, restart, immediately continue to next section when continued by user
+ LOOP = "presentation.loop"
+ # start, end, restart, finish animation first when user continues
+ COMPLETE_LOOP = "presentation.complete_loop"
+
+ # this animation is part of the first, automatically created section
+ self.wait()
+
+ self.next_section()
+ self.wait(2)
+
+ self.next_section(name="test")
+ self.wait()
+
+ self.next_section(
+ "Prepare For Unforeseen Consequences.", DefaultSectionType.NORMAL
+ )
+ self.wait(2)
+
+ self.next_section(type=PresentationSectionType.SKIP)
+ self.wait()
+
+ self.next_section(
+ name="this section should be removed as it doesn't contain any animations"
+ )
+
+
+class ElaborateSceneWithSections(Scene):
+ def construct(self):
+ # the first automatically created section should be deleted <- it's empty
+ self.next_section("create square")
+ square = Square()
+ self.play(FadeIn(square))
+ self.wait()
+
+ self.next_section("transform to circle")
+ circle = Circle()
+ self.play(Transform(square, circle))
+ self.wait()
+
+ self.next_section("fade out")
+ self.play(FadeOut(square))
+ self.wait()
diff --git a/tests/test_scene_rendering/test_caching_related.py b/tests/test_scene_rendering/test_caching_related.py
index daa4c34bd..f9ad587af 100644
--- a/tests/test_scene_rendering/test_caching_related.py
+++ b/tests/test_scene_rendering/test_caching_related.py
@@ -4,7 +4,8 @@ import sys
import pytest
-from ..utils.commands import capture
+from manim import capture
+
from ..utils.video_tester import *
diff --git a/tests/test_scene_rendering/test_cli_flags.py b/tests/test_scene_rendering/test_cli_flags.py
index 14a041cea..ef90e69a9 100644
--- a/tests/test_scene_rendering/test_cli_flags.py
+++ b/tests/test_scene_rendering/test_cli_flags.py
@@ -6,10 +6,11 @@ import pytest
from click.testing import CliRunner
from PIL import Image
+from manim import capture
from manim.__main__ import main
from manim.utils.file_ops import add_version_before_extension
-from ..utils.video_tester import *
+from ..utils.video_tester import video_comparison
@pytest.mark.slow
diff --git a/tests/test_scene_rendering/test_sections.py b/tests/test_scene_rendering/test_sections.py
new file mode 100644
index 000000000..559e9c906
--- /dev/null
+++ b/tests/test_scene_rendering/test_sections.py
@@ -0,0 +1,82 @@
+import os
+import sys
+
+import pytest
+
+from manim import capture
+from tests.assert_utils import assert_dir_exists, assert_dir_not_exists
+
+from ..utils.video_tester import video_comparison
+
+
+@video_comparison(
+ "SceneWithDisabledSections.json",
+ "videos/simple_scenes/480p15/SquareToCircle.mp4",
+)
+def test_no_sections(tmp_path, manim_cfg_file, simple_scenes_path):
+ scene_name = "SquareToCircle"
+ command = [
+ sys.executable,
+ "-m",
+ "manim",
+ "-ql",
+ "--media_dir",
+ str(tmp_path),
+ simple_scenes_path,
+ scene_name,
+ ]
+ _, err, exit_code = capture(command)
+ assert exit_code == 0, err
+
+ scene_dir = os.path.join(tmp_path, "videos", "simple_scenes", "480p15")
+ assert_dir_exists(scene_dir)
+ assert_dir_not_exists(os.path.join(scene_dir, "sections"))
+
+
+@video_comparison(
+ "SceneWithEnabledSections.json",
+ "videos/simple_scenes/480p15/SquareToCircle.mp4",
+)
+def test_sections(tmp_path, manim_cfg_file, simple_scenes_path):
+ scene_name = "SquareToCircle"
+ command = [
+ sys.executable,
+ "-m",
+ "manim",
+ "-ql",
+ "--save_sections",
+ "--media_dir",
+ str(tmp_path),
+ simple_scenes_path,
+ scene_name,
+ ]
+ _, err, exit_code = capture(command)
+ assert exit_code == 0, err
+
+ scene_dir = os.path.join(tmp_path, "videos", "simple_scenes", "480p15")
+ assert_dir_exists(scene_dir)
+ assert_dir_exists(os.path.join(scene_dir, "sections"))
+
+
+@video_comparison(
+ "SceneWithSections.json",
+ "videos/simple_scenes/480p15/SceneWithSections.mp4",
+)
+def test_many_sections(tmp_path, manim_cfg_file, simple_scenes_path):
+ scene_name = "SceneWithSections"
+ command = [
+ sys.executable,
+ "-m",
+ "manim",
+ "-ql",
+ "--save_sections",
+ "--media_dir",
+ str(tmp_path),
+ simple_scenes_path,
+ scene_name,
+ ]
+ _, err, exit_code = capture(command)
+ assert exit_code == 0, err
diff --git a/tests/utils/commands.py b/tests/utils/commands.py
deleted file mode 100644
index 572b55eb6..000000000
--- a/tests/utils/commands.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from subprocess import run
-
-
-def capture(command, cwd=None, command_input=None):
- p = run(command, cwd=cwd, input=command_input, capture_output=True, text=True)
- out, err = p.stdout, p.stderr
- return out, err, p.returncode
diff --git a/tests/utils/video_tester.py b/tests/utils/video_tester.py
index 4fef59a24..df7e02395 100644
--- a/tests/utils/video_tester.py
+++ b/tests/utils/video_tester.py
@@ -1,55 +1,84 @@
import json
import os
-import subprocess
+import pathlib
from functools import wraps
-import pytest
+from manim import get_video_metadata
-from ..utils.commands import capture
+from ..assert_utils import assert_shallow_dict_compare
+from ..helpers.video_utils import (
+ get_section_dir_layout,
+ get_section_index,
+ save_control_data_from_video,
+)
-def _get_config_from_video(path_to_video):
- command = [
- "ffprobe",
- "-v",
- "error",
- "-select_streams",
- "v:0",
- "-show_entries",
- "stream=width,height,nb_frames,duration,avg_frame_rate,codec_name",
- "-print_format",
- "json",
- path_to_video,
- ]
- config, err, exitcode = capture(command)
- assert exitcode == 0, err
- return json.loads(config)["streams"][0]
-
-
-def _load_video_data(path_to_data):
+def load_control_data(path_to_data):
with open(path_to_data) as f:
return json.load(f)
-def _check_video_data(path_control_data, path_to_video_generated):
- control_data = _load_video_data(path_control_data)
- config_generated = _get_config_from_video(path_to_video_generated)
- config_expected = control_data["config"]
- diff_keys = [
- d1[0]
- for d1, d2 in zip(config_expected.items(), config_generated.items())
- if d1[1] != d2[1]
- ]
- # \n does not work in f-strings.
- newline = "\n"
- assert (
- len(diff_keys) == 0
- ), f"Config don't match. : \n{newline.join([f'For {key}, got {config_generated[key]}, expected : {config_expected[key]}.' for key in diff_keys])}"
+def check_video_data(path_control_data, path_video_gen):
+ """Compare control data with generated output.
+ Used abbreviations:
+ exp -> expected
+ gen -> generated
+ sec -> section
+ meta -> metadata
+ """
+ # movie file specification
+ path_sec_gen = os.path.join(
+ pathlib.Path(path_video_gen).parent.absolute(),
+ "sections",
+ )
+ control_data = load_control_data(path_control_data)
+ movie_meta_gen = get_video_metadata(path_video_gen)
+ movie_meta_exp = control_data["movie_metadata"]
+
+ assert_shallow_dict_compare(
+ movie_meta_gen, movie_meta_exp, "Movie file metadata mismatch:"
+ )
+
+ # sections directory layout
+ sec_dir_layout_gen = set(get_section_dir_layout(path_sec_gen))
+ sec_dir_layout_exp = set(control_data["section_dir_layout"])
+
+ unexp_gen = sec_dir_layout_gen - sec_dir_layout_exp
+ ungen_exp = sec_dir_layout_exp - sec_dir_layout_gen
+ if len(unexp_gen) or len(ungen_exp):
+ dif = [f"'{dif}' got unexpectedly generated" for dif in unexp_gen] + [
+ f"'{dif}' didn't get generated" for dif in ungen_exp
+ ]
+ mismatch = "\n".join(dif)
+ raise AssertionError(f"Sections don't match:\n{mismatch}")
+
+ # sections index file
+ scene_name = "".join(os.path.basename(path_video_gen).split(".")[:-1])
+ path_sec_index_gen = os.path.join(path_sec_gen, f"{scene_name}.json")
+ sec_index_gen = get_section_index(path_sec_index_gen)
+ sec_index_exp = control_data["section_index"]
+
+ if len(sec_index_gen) != len(sec_index_exp):
+ raise AssertionError(
+ f"expected {len(sec_index_exp)} sections ({', '.join([el['name'] for el in sec_index_exp])}), but {len(sec_index_gen)} ({', '.join([el['name'] for el in sec_index_gen])}) got generated (in '{path_sec_index_gen}')"
+ )
+ # check individual sections
+ for sec_gen, sec_exp in zip(sec_index_gen, sec_index_exp):
+ assert_shallow_dict_compare(
+ sec_gen,
+ sec_exp,
+ # using json to pretty print dicts
+ f"Section {json.dumps(sec_gen, indent=4)} (in '{path_sec_index_gen}') doesn't match expected Section (in '{json.dumps(sec_exp, indent=4)}'):",
+ )
def video_comparison(control_data_file, scene_path_from_media_dir):
"""Decorator used for any test that needs to check a rendered scene/video.
+ .. warning::
+ The directories, such as the movie dir or sections dir, are expected to abide by the default.
+ This requirement could be dropped if the manim config were to be accessible from ``wrapper`` like in ``frames_comparison.py``.
+
Parameters
----------
control_data_file : :class:`str`
@@ -58,6 +87,10 @@ def video_comparison(control_data_file, scene_path_from_media_dir):
scene_path_from_media_dir : :class:`str`
The path of the scene generated, from the media dir. Example: /videos/1080p60/SquareToCircle.mp4.
+
+ See Also
+ --------
+ tests/helpers/video_utils.py : create control data
"""
def decorator(f):
@@ -75,15 +108,16 @@ def video_comparison(control_data_file, scene_path_from_media_dir):
"videos_data",
control_data_file,
)
- path_video_generated = tmp_path / scene_path_from_media_dir
- if not os.path.exists(path_video_generated):
- for parent in reversed(path_video_generated.parents):
+ path_video_gen = tmp_path / scene_path_from_media_dir
+ if not os.path.exists(path_video_gen):
+ for parent in reversed(path_video_gen.parents):
if not parent.exists():
- pytest.fail(
+ raise AssertionError(
f"'{parent.name}' does not exist in '{parent.parent}' (which exists). ",
)
- break
- _check_video_data(path_control_data, str(path_video_generated))
+ # TODO: use when pytest --set_test option
+ # save_control_data_from_video(path_video_gen, control_data_file[:-5])
+ check_video_data(path_control_data, str(path_video_gen))
return result
return wrapper