The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Reject nested, unclosed and stray brackets in a say script
Mert Kaya9da0772a3137
diff --git a/docs/content/changelog.md b/docs/content/changelog.mdindex 4b0c995a..6a997e3c 100644--- a/docs/content/changelog.md+++ b/docs/content/changelog.md@@ -42,6 +42,7 @@ The notable changes to ManimGX, release by release. The format follows- Redraw a shape that empties with `always_redraw` without a RecursionError, and keep a mobject's updaters off the member its points move into when a transform aligns it, so a relative updater such as `always_shift` no longer runs twice on them ([#32](https://github.com/academa-labs/manimgx/issues/32)).- Measure a text's size in `inspect` and `render` at 1080p, which is 1080 px on a video's short side, so a tall video (1080x1920) no longer reports readable text as small ([#37](https://github.com/academa-labs/manimgx/issues/37)).- Make the folder a video or a storyboard is written in when it is missing (`render -o new/out.mp4`, `inspect -o new/sheet.png` and `Scene.render`), instead of failing with "No such file or directory" ([#34](https://github.com/academa-labs/manimgx/issues/34)).+- Raise a ValueError, naming where it is, for a nested, unclosed or stray bracket in a `say` script, which was spoken and captioned ([#39](https://github.com/academa-labs/manimgx/issues/39)).- Keep resources needed by queued video frames until their transparency retries finish, fixing render failures during cache cleanup ([#16](https://github.com/academa-labs/manimgx/issues/16)).- Draw a storyboard picture without dropping the frame the film holds back, fixing `manimgx render` failures ("unknown shape") under memory pressure.- Draw a vectorized curve whose function gives a component as one number (`use_vectorized` with `lambda t: (t, t**2, 0)`), which failed with numpy's inhomogeneous-shape error.diff --git a/docs/content/user-guide/sound-and-voice.md b/docs/content/user-guide/sound-and-voice.mdindex 06051a31..8d3ac5d4 100644--- a/docs/content/user-guide/sound-and-voice.md+++ b/docs/content/user-guide/sound-and-voice.md@@ -62,6 +62,8 @@ class Derivative(m.Scene):Each animation starts with the first of its words. The scene waits until the line ends,so lines don't overlap. If you change the words, the animations follow the new words.+Brackets come in pairs and don't nest; any other bracket is an error.+## VoicesThe default voice is ElevenLabs' Eleven v3, on [fal.ai](https://fal.ai). It needs yourdiff --git a/src/manimgx/audio/sound.py b/src/manimgx/audio/sound.pyindex b986b489..db572229 100644--- a/src/manimgx/audio/sound.py+++ b/src/manimgx/audio/sound.py@@ -471,20 +471,26 @@ def lines(speech: Speech, width: int = 42) -> list[tuple[float, float, str]]:# ── the script: [spans] in the text ─────────────────────────────────────────────────────-_SPAN = re.compile(r"\[([^\[\]]*)\]")+_MARK = re.compile(r"\[([^\[\]]*)\]|([\[\]])") # a span, or a bracket that is no span's@deprecated("ManimGX's machinery: say calls it", category=None)def spans(script: str) -> tuple[str, list[tuple[int, int]]]:"""The text of a script, its brackets taken out, and each bracketed span's characters- in that text: `"Here is [a circle]."` is `("Here is a circle.", [(8, 16)])`."""+ in that text: `"Here is [a circle]."` is `("Here is a circle.", [(8, 16)])`. A span is+ one `[` and the `]` after it, with no bracket between: any other bracket is an error."""text, found, at = [], [], 0shift = 0- for m in _SPAN.finditer(script):+ for m in _MARK.finditer(script):+ if m[2]:+ raise ValueError(+ f"the {m[2]!r} at character {m.start()} of {script!r} is not part of a"+ " span: a span is one [ and the ] after it, with no bracket between"+ )text.append(script[at : m.start()])begin = m.start() - shift- found.append((begin, begin + len(m.group(1))))- text.append(m.group(1))+ found.append((begin, begin + len(m[1])))+ text.append(m[1])at, shift = m.end(), shift + 2text.append(script[at:])return "".join(text), founddiff --git a/src/manimgx/scene.py b/src/manimgx/scene.pyindex 7ccc3a1f..ff3b0481 100644--- a/src/manimgx/scene.py+++ b/src/manimgx/scene.py@@ -1611,7 +1611,8 @@ class Scene:in order, during the bracketed words, each starting as its words start andlasting as long as they take to say, or its own run time if that is longer (anempty `[]` starts one where it stands). Without brackets, the animations play- during the whole speech. The brackets are not spoken.+ during the whole speech. The brackets are not spoken: a span is one `[` and its+ `]`, so a nested, unclosed or stray bracket is an error (a ValueError).Args:script: What to say, with a bracketed span for each animation (or none).diff --git a/tests/unit/audio/test_sound.py b/tests/unit/audio/test_sound.pyindex b16ba10a..0089a207 100644--- a/tests/unit/audio/test_sound.py+++ b/tests/unit/audio/test_sound.py@@ -1,5 +1,6 @@"""Sound placement and edits, and speech timing, captions and voices."""+import refrom fractions import Fractionfrom pathlib import Pathfrom typing import cast@@ -419,6 +420,26 @@ class TestScript:for (a, b), part in zip(found, parts[1::2], strict=True):assert text[a:b] == part+ @given(st.text("ab []", max_size=12))+ @example("Outer [inner [deep] bit] done.")+ @example("An open [bracket never closes.")+ @example("A stray] close.")+ @example("Closed] before [open.")+ def test_a_span_is_one_pair_of_brackets_and_any_other_bracket_is_an_error(+ self, script: str+ ) -> None:+ brackets = "".join(c for c in script if c in "[]")+ if re.fullmatch(r"(\[\])*", brackets): # opened, closed, opened, closed…+ assert len(spans(script)[1]) == len(brackets) // 2+ else:+ with pytest.raises(ValueError, match="not part of a span"):+ spans(script)++ def test_the_error_says_where_the_bracket_is(self) -> None:+ script = "Outer [inner [deep] bit] done."+ with pytest.raises(ValueError, match=r"the '\[' at character 6 of"):+ spans(script)+def test_a_span_is_said_from_its_first_word_to_its_last(self) -> None:speech = said("the derivative of x squared is two x")text, (span,) = spans("the derivative of [x squared] is two x")@@ -476,6 +497,33 @@ class TestSay:with pytest.raises(ValueError, match="2 bracketed spans for 1 animations"):Wrong().render()+ @pytest.mark.parametrize(+ "script",+ [+ "Outer [inner [deep] bit] done.",+ "An open [bracket never closes.",+ "A stray] close.",+ ],+ )+ def test_brackets_that_are_no_span_are_refused_before_anything_is_said(+ self, script: str, cache_here: Path+ ) -> None:+ said_texts: list[str] = []++ def voice(text: str) -> Speech:+ said_texts.append(text)+ return said(text)++ class Refused(m.Scene):+ def construct(self) -> None:+ self.say(script, m.Wait())++ Refused.voice = staticmethod(voice)+ with pytest.raises(ValueError, match="not part of a span"):+ Refused().render()+ assert said_texts == []+ assert not cache_here.exists()+@pytest.mark.usefixtures("cache_here")class TestVoice: