Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Added basic support for adding subcaptions via :meth:`.Scene.add_subcaption` (#2314)

Benjamin Hackl2949710d5da3
diff --git a/manim/scene/scene.py b/manim/scene/scene.py
index afbfa73cf..ee2c38787 100644
--- a/manim/scene/scene.py
+++ b/manim/scene/scene.py
@@ -3,6 +3,7 @@
__all__ = ["Scene"]
import copy
+import datetime
import inspect
import platform
import random
@@ -12,6 +13,8 @@ import types
from queue import Queue
from typing import List, Optional
+import srt
+
from manim.scene.section import DefaultSectionType
try:
@@ -899,8 +902,50 @@ class Scene:
else:
return np.max([animation.run_time for animation in animations])
- def play(self, *args, **kwargs):
+ def play(
+ self,
+ *args,
+ subcaption=None,
+ subcaption_duration=None,
+ subcaption_offset=0,
+ **kwargs,
+ ):
+ r"""Plays an animation in this scene.
+
+ Parameters
+ ----------
+
+ args
+ Animations to be played.
+ subcaption
+ The content of the external subcaption that should
+ be added during the animation.
+ subcaption_duration
+ The duration for which the specified subcaption is
+ added. If ``None`` (the default), the run time of the
+ animation is taken.
+ subcaption_offset
+ An offset (in seconds) for the start time of the
+ added subcaption.
+ kwargs
+ All other keywords are passed to the renderer.
+
+ """
+ start_time = self.renderer.time
self.renderer.play(self, *args, **kwargs)
+ run_time = self.renderer.time - start_time
+ if subcaption:
+ if subcaption_duration is None:
+ subcaption_duration = run_time
+ # The start of the subcaption needs to be offset by the
+ # run_time of the animation because it is added after
+ # the animation has already been played (and Scene.renderer.time
+ # has already been updated).
+ self.add_subcaption(
+ content=subcaption,
+ duration=subcaption_duration,
+ offset=-run_time + subcaption_offset,
+ )
def wait(self, duration=DEFAULT_WAIT_TIME, stop_condition=None):
self.play(Wait(run_time=duration, stop_condition=stop_condition))
@@ -1242,6 +1287,55 @@ class Scene:
self.update_meshes(dt)
self.update_self(dt)
+ def add_subcaption(
+ self, content: str, duration: float = 1, offset: float = 0
+ ) -> None:
+ r"""Adds an entry in the corresponding subcaption file
+ at the current time stamp.
+
+ The current time stamp is obtained from ``Scene.renderer.time``.
+
+ Parameters
+ ----------
+
+ content
+ The subcaption content.
+ duration
+ The duration (in seconds) for which the subcaption is shown.
+ offset
+ This offset (in seconds) is added to the starting time stamp
+ of the subcaption.
+
+ Examples
+ --------
+
+ This example illustrates both possibilities for adding
+ subcaptions to Manimations::
+
+ class SubcaptionExample(Scene):
+ def construct(self):
+ square = Square()
+ circle = Circle()
+
+ # first option: via the add_subcaption method
+ self.add_subcaption("Hello square!", duration=1)
+ self.play(Create(square))
+
+ # second option: within the call to Scene.play
+ self.play(
+ Transform(square, circle),
+ subcaption="The square transforms."
+ )
+
+ """
+ subtitle = srt.Subtitle(
+ index=len(self.renderer.file_writer.subcaptions),
+ content=content,
+ start=datetime.timedelta(seconds=self.renderer.time + offset),
+ end=datetime.timedelta(seconds=self.renderer.time + offset + duration),
+ )
+ self.renderer.file_writer.subcaptions.append(subtitle)
+
def add_sound(self, sound_file, time_offset=0, gain=None, **kwargs):
"""
This method is used to add a sound to the animation.
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.py
index 2b04e2292..0a30c6c64 100644
--- a/manim/scene/scene_file_writer.py
+++ b/manim/scene/scene_file_writer.py
@@ -12,6 +12,7 @@ from time import sleep
from typing import Any, Dict, List, Optional
import numpy as np
+import srt
from PIL import Image
from pydub import AudioSegment
@@ -71,6 +72,7 @@ class SceneFileWriter:
self.init_audio()
self.frame_count = 0
self.partial_movie_files: List[str] = []
+ self.subcaptions: List[srt.Subtitle] = []
self.sections: List[Section] = []
# first section gets automatically created for convenience
# if you need the first section to be skipped, add a first section by hand, it will replace this one
@@ -449,6 +451,8 @@ class SceneFileWriter:
elif is_png_format() and not config["dry_run"]:
target_dir, _ = os.path.splitext(self.image_file_path)
logger.info("\n%i images ready at %s\n", self.frame_count, target_dir)
+ if self.subcaptions:
+ self.write_subcaption_file()
def open_movie_pipe(self, file_path=None):
"""
@@ -712,6 +716,13 @@ class SceneFileWriter:
{"par_dir": self.partial_movie_directory},
)
+ def write_subcaption_file(self):
+ """Writes the subcaption file."""
+ subcaption_file = Path(config.output_file).with_suffix(".srt")
+ with open(subcaption_file, "w") as f:
+ f.write(srt.compose(self.subcaptions))
+ logger.info(f"Subcaption file has been written as {subcaption_file}")
+
def print_file_ready_message(self, file_path):
"""Prints the "File Ready" message to STDOUT."""
config["output_file"] = file_path
diff --git a/poetry.lock b/poetry.lock
index 23efeb5f9..554956804 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -1977,6 +1977,14 @@ python-versions = ">=3.6"
[package.dependencies]
sphinx = ">=2.0"
+[[package]]
+name = "srt"
+version = "3.5.0"
+description = "A tiny library for parsing, modifying, and composing SRT files."
+category = "main"
+optional = false
+python-versions = ">=2.7"
+
[[package]]
name = "terminado"
version = "0.12.1"
@@ -2163,7 +2171,7 @@ webgl_renderer = ["grpcio", "grpcio-tools"]
[metadata]
lock-version = "1.1"
python-versions = "^3.7"
-content-hash = "9edc33b7502b40d0b2bcd06d48e40ec743d468d45d4f38178bd009a4aa596d10"
+content-hash = "4c12c12b7be3fb2cb13d5b511fe613a92b53b458ad58ed3505766019be3d93ef"
[metadata.files]
alabaster = [
@@ -3589,6 +3597,9 @@ sphinxext-opengraph = [
{file = "sphinxext-opengraph-0.4.2.tar.gz", hash = "sha256:5da1a6eaab25e377b841f506ef7d7c44b539428f3d6094ccc16d1dfd3ef65501"},
{file = "sphinxext_opengraph-0.4.2-py3-none-any.whl", hash = "sha256:a51f2604f9a5b6c0d25d3a88e694d5c02e20812dc0e482adf96c8628f9109357"},
]
+srt = [
+ {file = "srt-3.5.0.tar.gz", hash = "sha256:9378e67fcc7c110eca7ec12bdb17a174085f67e3b371f7e586a4c68a0dda245b"},
+]
terminado = [
{file = "terminado-0.12.1-py3-none-any.whl", hash = "sha256:09fdde344324a1c9c6e610ee4ca165c4bb7f5bbf982fceeeb38998a988ef8452"},
{file = "terminado-0.12.1.tar.gz", hash = "sha256:b20fd93cc57c1678c799799d117874367cc07a3d2d55be95205b1a88fa08393f"},
diff --git a/pyproject.toml b/pyproject.toml
index a36e4a9bd..fe3a3b4f1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -55,6 +55,7 @@ dearpygui = { version = "^0.8", optional = true }
screeninfo = "^0.6.7"
skia-pathops = "^0.7.0"
isosurfaces = "0.1.0"
+srt = "^3.5.0"
[tool.poetry.extras]
webgl_renderer = ["grpcio","grpcio-tools"]
diff --git a/tests/test_scene.py b/tests/test_scene.py
index f842864df..be9f3223c 100644
--- a/tests/test_scene.py
+++ b/tests/test_scene.py
@@ -1,6 +1,9 @@
+import datetime
+
import pytest
from manim import Circle, FadeIn, Mobject, Scene, Square, config, tempconfig
+from manim.animation.animation import Wait
def test_scene_add_remove():
@@ -46,3 +49,25 @@ def test_scene_time():
scene.renderer._original_skipping_status = True
scene.play(FadeIn(Square()), run_time=5) # this animation gets skipped.
assert pytest.approx(scene.renderer.time) == 7.5
+
+
+def test_subcaption():
+ with tempconfig({"dry_run": True}):
+ scene = Scene()
+ scene.add_subcaption("Testing add_subcaption", duration=1, offset=0)
+ scene.wait()
+ scene.play(
+ Wait(),
+ run_time=2,
+ subcaption="Testing Scene.play subcaption interface",
+ subcaption_duration=1.5,
+ subcaption_offset=0.5,
+ )
+ subcaptions = scene.renderer.file_writer.subcaptions
+ assert len(subcaptions) == 2
+ assert subcaptions[0].start == datetime.timedelta(seconds=0)
+ assert subcaptions[0].end == datetime.timedelta(seconds=1)
+ assert subcaptions[0].content == "Testing add_subcaption"
+ assert subcaptions[1].start == datetime.timedelta(seconds=1.5)
+ assert subcaptions[1].end == datetime.timedelta(seconds=3)
+ assert subcaptions[1].content == "Testing Scene.play subcaption interface"