Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Synchronize audio with scenes

apoogdkcafecdb1cea1
diff --git a/src/manimgx/audio/__init__.py b/src/manimgx/audio/__init__.py
new file mode 100644
index 00000000..fd25206f
--- /dev/null
+++ b/src/manimgx/audio/__init__.py
@@ -0,0 +1,38 @@
+"""Audio: editable sounds, timed speech, and the voices that produce it.
+
+A voice is any function from text to [`Speech`][manimgx.audio.Speech]: a sound that knows its
+words and when each is said. [`Scene.say`][manimgx.Scene.say] speaks through the scene's voice
+and plays animations during the words they belong to: `self.say("Here is [a circle].",
+m.Create(circle))` draws the circle as "a circle" is said, and the film waits for the sentence.
+What a voice says is kept (`cached`), so a scene renders again without speaking again.
+
+The voices manimgx brings are text-to-speech services', a module each: [`fal`][manimgx.audio.fal]
+(fal.ai's models, [`Fal`][manimgx.audio.fal.Fal]). Any other is a few lines away (see
+[`Voice`][manimgx.audio.Voice]).
+"""
+
+from manimgx.audio.fal import Fal
+from manimgx.audio.sound import (
+ Speech,
+ Voice,
+ Word,
+ cached,
+ estimate,
+ lines,
+ spans,
+ timed,
+ times,
+)
+
+__all__ = [
+ "Fal",
+ "Speech",
+ "Voice",
+ "Word",
+ "cached",
+ "estimate",
+ "lines",
+ "spans",
+ "timed",
+ "times",
+]
diff --git a/src/manimgx/audio/sound.py b/src/manimgx/audio/sound.py
new file mode 100644
index 00000000..75d36b2f
--- /dev/null
+++ b/src/manimgx/audio/sound.py
@@ -0,0 +1,639 @@
+"""Sounds and timed speech: sources, edits, placement and soundtrack mixing."""
+
+import dataclasses
+import math
+import os
+from collections.abc import Callable
+from dataclasses import dataclass
+from fractions import Fraction
+from pathlib import Path
+from typing import TYPE_CHECKING, ClassVar, Self
+
+import numpy as np
+
+from manimgx.animation import clock
+from manimgx.animation.easing import linear
+from manimgx.animation.timeline import Animation, AnimationOptions
+from manimgx.caches import Memo
+from manimgx.mobject import Mobject
+
+if TYPE_CHECKING:
+ from manimgx.scene import Scene
+import json
+import re
+from collections.abc import Sequence
+
+RATE = 48_000
+"""The soundtrack's sample rate: 48,000 samples a second, as video's sound has."""
+CUT = 0.005
+"""How long a sound cut short fades out, at least, in seconds: a cut mid-wave clicks."""
+DUCK_ATTACK, DUCK_RELEASE = 0.15, 0.5
+"""How long a ducking sound takes to dip before speech, and to come back after it (s)."""
+BITRATE = 224_000
+"""The sound track's bitrate, a channel: AAC-LC at 224 kbps a channel, which PEAQ (ITU-R
+BS.1387) finds no listener could tell from the original, for speech, effects and music."""
+
+type Source = str | os.PathLike[str] | bytes | np.ndarray
+"""What a sound is made from: a file's path, a file's bytes (any common audio file: WAV, AIFF,
+MP3, AAC/M4A, Opus, Vorbis, FLAC, ALAC; a video's sound too), or samples (float, -1 to 1: one
+column per channel)."""
+
+_DECODED: Memo[int, np.ndarray] = Memo(64)
+
+
+@dataclass(frozen=True, slots=True)
+class _Edit:
+ """How a sound is made from its source: in the order applied."""
+
+ start: float = 0.0 # the source trimmed to [start, end) seconds
+ end: float | None = None
+ speed: float = 1.0 # played faster (and higher) or slower (and lower)
+ loop: float | None = None # repeated to last this long (inf: until stopped)
+ gain: float = 0.0 # in decibels
+ fade_in: float = 0.0
+ fade_out: float = 0.0
+ pan: float = 0.0 # -1 left, 0 center, 1 right
+ duck: float = 0.0 # decibels it dips by while anything speaks
+
+
+class Sound(Animation[Mobject]):
+ """A sound a film plays.
+
+ Make one from a file, the bytes of one, or samples; edit it (each edit makes a new
+ sound); place it in a scene: [`add_sound`][manimgx.Scene.add_sound] starts it now and
+ takes no time, while [`play`][manimgx.Scene.play] plays it as a part of the play, which
+ then lasts at least as long as the sound. In a composition it starts when its window
+ opens: `LaggedStart(*(AnimationGroup(FadeIn(d), click) for d in dots))` clicks as each
+ dot appears. It changes nothing on screen, and a play's `run_time` does not change it:
+ a sound lasts its [`duration`][manimgx.audio.sound.Sound.duration].
+
+ Args:
+ source: A file's path, a file's bytes, or samples: floats from -1 to 1, one
+ column per channel (a 1-D array is mono).
+ rate: The samples' rate, in samples a second; only for samples.
+ """
+
+ defaults: ClassVar[AnimationOptions] = {"rate_func": linear}
+ speaks: ClassVar[bool] = False # speech ducks what is set to duck
+
+ def __init__(self, source: Source, *, rate: int | None = None) -> None:
+ if isinstance(source, np.ndarray) != (rate is not None):
+ raise ValueError("give a rate with samples, and only with samples")
+ if isinstance(source, str | os.PathLike) and not Path(source).is_file():
+ raise FileNotFoundError(f"no sound file at {os.fspath(source)!r}")
+ self.source = source
+ self.rate = rate
+ self._edit = _Edit()
+ super().__init__(None)
+
+ # ── edits: each makes a new sound ─────────────────────────────────────────
+ def _but(self, **changes: float | None) -> Self:
+ other = object.__new__(type(self))
+ other.__dict__.update(self.__dict__)
+ other._edit = dataclasses.replace(self._edit, **changes)
+ other.__dict__.pop("_made", None)
+ return other
+
+ def gain(self, decibels: float) -> Self:
+ """This sound louder by `decibels` (quieter if negative: -6 halves it)."""
+ return self._but(gain=self._edit.gain + decibels)
+
+ def fade_in(self, seconds: float) -> Self:
+ """This sound fading in from silence over its first `seconds`."""
+ return self._but(fade_in=seconds)
+
+ def fade_out(self, seconds: float) -> Self:
+ """This sound fading out to silence over its last `seconds`."""
+ return self._but(fade_out=seconds)
+
+ def trim(self, start: float = 0.0, end: float | None = None) -> Self:
+ """The part of this sound from `start` to `end` seconds (None: its end)."""
+ return self._but(start=start, end=end)
+
+ def loop(self, duration: float | None = None) -> Self:
+ """This sound repeated to last `duration` seconds; None: until the film ends, or
+ until its clip is [stopped][manimgx.audio.sound.Clip.stop]."""
+ return self._but(loop=math.inf if duration is None else duration)
+
+ def speed(self, factor: float) -> Self:
+ """This sound played `factor` times as fast, as a tape is: higher and shorter."""
+ return self._but(speed=self._edit.speed * factor)
+
+ def pan(self, position: float) -> Self:
+ """This sound placed from -1 (left) through 0 (center) to 1 (right)."""
+ return self._but(pan=position)
+
+ def duck(self, decibels: float = 12) -> Self:
+ """This sound dipping by `decibels` while anything speaks (while a
+ [`Speech`][manimgx.audio.Speech] plays): music under a narration. It eases down
+ `DUCK_ATTACK` seconds before the speech and back up over `DUCK_RELEASE` after.
+ """
+ return self._but(duck=decibels)
+
+ @classmethod
+ def of(
+ cls, function: Callable[[np.ndarray], np.ndarray], duration: float
+ ) -> "Sound":
+ """A sound made by a function of time: `function(t)`, given the times of its
+ samples (seconds, an array), returns their values (-1 to 1).
+
+ Examples:
+ `Sound.of(lambda t: 0.3 * np.sin(2 * np.pi * 440 * t), 1)`: a second of A.
+ """
+ t = np.arange(round(duration * RATE)) / RATE
+ return cls(np.asarray(function(t), np.float32), rate=RATE)
+
+ # ── what it is ──────────────────────────────────────────────────────────────
+ @property
+ def samples(self) -> np.ndarray:
+ """Its samples at `RATE`: floats, one column per channel (1 or 2)."""
+ made = self.__dict__.get("_made")
+ if made is None:
+ made = self.__dict__["_made"] = _make(self)
+ return made
+
+ @property
+ def duration(self) -> float:
+ """How long it lasts, in seconds (inf for a sound looped until stopped)."""
+ if self._edit.loop is not None:
+ return self._edit.loop
+ return len(self.samples) / RATE
+
+ @property
+ def run_time(self) -> float:
+ """Its duration: a sound plays for as long as it lasts. An endless one (`loop()`)
+ cannot be played: add it ([`add_sound`][manimgx.Scene.add_sound]), and stop it.
+ """
+ if self._edit.loop == math.inf:
+ raise ValueError(
+ "an endless sound (loop()) never ends: add it with add_sound, and stop"
+ " its clip, instead of playing it"
+ )
+ return self.duration
+
+ @run_time.setter
+ def run_time(self, value: float) -> None:
+ pass # a play's run_time sets its animations', not its sounds'
+
+ # ── as an animation: it changes nothing on screen ─────────────────────────
+ def begin(self) -> None: ...
+ def finish(self) -> None: ...
+ def clean_up_from_scene(self, scene: "Scene") -> None: ...
+ def advance(self, t: Fraction) -> None: ...
+ def interpolate(self, alpha: float) -> None: ...
+
+
+@dataclass(eq=False)
+class Clip:
+ """A sound as a film plays it: from `start`, in seconds of scene time, until it ends
+ or is stopped. [`add_sound`][manimgx.Scene.add_sound] returns it."""
+
+ sound: Sound
+ start: Fraction
+ end: Fraction | None = (
+ None # stopped: silent from here, having faded out over `fade`
+ )
+ fade: float = 0.0
+
+ def stop(self, fade: float = 0.05) -> None:
+ """Stop the sound: it fades out from now (the instant the scene is computing) over
+ `fade` seconds, and is silent after."""
+ self.end, self.fade = clock.now + Fraction(fade).limit_denominator(RATE), fade
+
+
+def _source_samples(sound: Sound) -> np.ndarray:
+ """Source samples at RATE (2-D), possibly borrowed; consumers must not mutate them."""
+ source = sound.source
+ if isinstance(source, np.ndarray):
+ data = source.astype(np.float32, copy=False).reshape(len(source), -1)
+ rate = sound.rate or RATE
+ return data if rate == RATE else _resample(data, rate, RATE)
+ raw = source if isinstance(source, bytes) else Path(source).read_bytes()
+ from manimgx._engine import digest
+
+ key = digest(raw)
+ return _DECODED.recall(key, lambda: _decode(raw))
+
+
+def _decode(raw: bytes) -> np.ndarray:
+ from manimgx._engine import decode_audio
+
+ samples, channels = decode_audio(raw, RATE)
+ return np.frombuffer(samples, np.float32).reshape(-1, channels)
+
+
+def _resample(data: np.ndarray, rate: float, to: float) -> np.ndarray:
+ """Samples at `rate` resampled to `to`: band-limited (the engine's windowed sinc)."""
+ from manimgx._engine import resample_audio
+
+ channels = data.shape[1]
+ out = resample_audio(np.ascontiguousarray(data).tobytes(), channels, rate, to)
+ return np.frombuffer(out, np.float32).reshape(-1, channels)
+
+
+def _make(sound: Sound) -> np.ndarray:
+ """The sound's samples: its source trimmed, sped, looped, its gain, fades and pan. An
+ endless loop is one round of it, without fades: the mix repeats it for as long as its
+ clip plays, and fades it where the clip starts and ends."""
+ e = sound._edit
+ data = _source_samples(sound)
+ data = data[round(e.start * RATE) : None if e.end is None else round(e.end * RATE)]
+ if e.speed != 1:
+ data = _resample(data, RATE * e.speed, RATE)
+ if e.loop is not None and math.isfinite(e.loop) and len(data):
+ n = round(e.loop * RATE)
+ data = np.tile(data, (-(-n // len(data)), 1))[:n]
+ data = data * np.float32(10 ** (e.gain / 20))
+ if e.loop != math.inf:
+ _ramp(data, e.fade_in, e.fade_out)
+ if e.pan:
+ if data.shape[1] == 1:
+ data = np.repeat(data, 2, axis=1)
+ data[:, 0] *= min(1.0, 1 - e.pan)
+ data[:, 1] *= min(1.0, 1 + e.pan)
+ return data
+
+
+def _ramp(data: np.ndarray, fade_in: float, fade_out: float) -> None:
+ """Fade the ends of `data` in place: linear ramps of those lengths."""
+ for seconds, head in ((fade_in, True), (fade_out, False)):
+ n = min(len(data), round(seconds * RATE))
+ if n:
+ ramp = np.linspace(0, 1, n, endpoint=False, dtype=np.float32)[:, None]
+ if head:
+ data[:n] *= ramp
+ else:
+ data[len(data) - n :] *= ramp[::-1]
+
+
+def mix(clips: list[Clip], duration: Fraction) -> np.ndarray | None:
+ """The soundtrack of a film `duration` seconds long: its clips mixed, at RATE (one
+ column per channel: mono when every clip is mono and centered); None if it has none.
+
+ A clip plays from its start until its sound ends, it is stopped, or the film ends; a
+ sound cut short fades out over its stop's fade, or `CUT` at least (a cut mid-wave
+ clicks). An endless loop fades in where its clip starts and out where it ends.
+ """
+ if not clips:
+ return None
+ total = round(duration * RATE)
+ channels = max(c.sound.samples.shape[1] for c in clips)
+ out = np.zeros((total, channels), np.float32)
+ for clip in clips:
+ at = round(clip.start * RATE)
+ if at >= total:
+ continue
+ e, data = clip.sound._edit, clip.sound.samples
+ span = (total if clip.end is None else min(total, round(clip.end * RATE))) - at
+ stop = 0.0 if clip.end is None else clip.fade
+ if e.loop == math.inf and len(data):
+ data = np.tile(data, (-(-span // len(data)), 1))[:span]
+ _ramp(data, e.fade_in, max(e.fade_out, stop, CUT))
+ elif len(data) > span:
+ data = data[:span].copy()
+ _ramp(data, 0, max(stop, CUT))
+ if e.duck:
+ data = data * _ducked(clips, e.duck, at, len(data))[:, None]
+ out[at : at + len(data)] += data # mono into each channel of stereo
+ return out
+
+
+def _ducked(clips: list[Clip], decibels: float, at: int, length: int) -> np.ndarray:
+ """The gain of a ducking sound placed at sample `at` for `length` samples: 1, dipping
+ by `decibels` while any speech among `clips` plays (eased on a 10 ms grid)."""
+ low, hop = 10 ** (-decibels / 20), RATE // 100
+ grid = np.arange(at, at + length + hop, hop, dtype=np.float64) / RATE
+ gain = np.ones(len(grid))
+ for clip in clips:
+ if clip.sound.speaks:
+ a = float(clip.start)
+ b = a + clip.sound.duration
+ ease_in = np.clip((grid - (a - DUCK_ATTACK)) / DUCK_ATTACK, 0, 1)
+ ease_out = np.clip(((b + DUCK_RELEASE) - grid) / DUCK_RELEASE, 0, 1)
+ gain = np.minimum(gain, 1 - (1 - low) * np.minimum(ease_in, ease_out))
+ return np.interp(np.arange(length) / hop, np.arange(len(grid)), gain).astype(
+ np.float32
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class Word:
+ """A word of a speech, and when it is said: from `start` to `end`, in seconds from the
+ speech's start."""
+
+ text: str
+ start: float
+ end: float
+
+
+class Speech(Sound):
+ """Speech: a sound that knows what it says and when it says each word.
+
+ A voice returns one. It plays as any sound does; [`Scene.say`][manimgx.Scene.say]
+ also times animations by its words.
+
+ Args:
+ source: The audio: a file's path, a file's bytes, or samples.
+ text: What it says.
+ words: Each word and when it is said, if the voice knows; otherwise they are
+ estimated from the audio.
+ rate: The samples' rate; only for samples.
+ """
+
+ speaks: ClassVar[bool] = True
+
+ def __init__(
+ self,
+ source: Source,
+ *,
+ text: str,
+ words: Sequence[Word] = (),
+ rate: int | None = None,
+ ) -> None:
+ super().__init__(source, rate=rate)
+ self.text = text
+ self._words = tuple(words) # the source's: before trims and speed
+
+ @property
+ def words(self) -> tuple[Word, ...]:
+ """Its words, in order, with when each is said (in seconds from its start): the
+ voice's, or estimated from the audio; a trim or a change of speed moves them with
+ the audio."""
+ if not self._words:
+ self._words = estimate(self.text, _source_samples(self))
+ e = self._edit
+ if e.start == 0 and e.speed == 1:
+ return self._words
+ end = math.inf if e.end is None else e.end
+ return tuple(
+ Word(w.text, (w.start - e.start) / e.speed, (w.end - e.start) / e.speed)
+ for w in self._words
+ if e.start <= w.start < end
+ )
+
+
+type Voice = Callable[[str], Speech]
+"""Anything that speaks: a function from text to [`Speech`][manimgx.audio.Speech]. Bring any
+text-to-speech: wrap its call in a function that returns `Speech(audio, text=text)`."""
+
+
+# ── timing ───────────────────────────────────────────────────────────────────────────────
+
+
+_WORD = re.compile(r"\S+")
+
+
+def estimate(text: str, samples: np.ndarray) -> tuple[Word, ...]:
+ """When each word of `text` is said in `samples`, estimated: the audio's voiced span
+ shared among the words by their letters, with a share more for the pause after a comma or
+ a full stop. Against voices' own times, it is off by about 0.1 s on average."""
+ words = _WORD.findall(text)
+ if not words:
+ return ()
+ level = np.abs(samples).max(axis=1) if samples.ndim > 1 else np.abs(samples)
+ hop = RATE // 100 # 10 ms
+ frames = len(level) // hop
+ loud = level[: frames * hop].reshape(frames, hop).max(axis=1) > 0.02
+ voiced = np.flatnonzero(loud)
+ if not len(voiced):
+ total = len(samples) / RATE
+ return tuple(
+ Word(w, total * i / len(words), total * (i + 1) / len(words))
+ for i, w in enumerate(words)
+ )
+ first, last = voiced[0], voiced[-1] + 1
+ # weight: letters, plus a pause after a comma or a full stop
+ weights = []
+ for w in words:
+ weights.append(len(w) + (6 if w[-1] in ".!?:;" else 3 if w[-1] == "," else 1))
+ total_weight = sum(weights)
+ edges = np.concatenate([[0], np.cumsum(weights)]) / total_weight
+ span = (last - first) / 100
+ times = first / 100 + edges * span
+ return tuple(
+ Word(
+ w,
+ float(times[i]),
+ float(times[i + 1] - (weights[i] - len(w)) / total_weight * span),
+ )
+ for i, w in enumerate(words)
+ )
+
+
+def lines(speech: Speech, width: int = 42) -> list[tuple[float, float, str]]:
+ """A speech as captions: its words in lines of at most `width` characters, a line ending
+ at the end of a sentence, each shown from its first word's start until the next line's
+ (or its last word's end), in seconds from the speech's start."""
+ out: list[tuple[float, float, str]] = []
+ line: list[Word] = []
+ for word in speech.words:
+ if line and len(" ".join(w.text for w in line)) + 1 + len(word.text) > width:
+ out.append((line[0].start, word.start, " ".join(w.text for w in line)))
+ line = []
+ line.append(word)
+ if word.text[-1] in ".!?":
+ out.append((line[0].start, word.end, " ".join(w.text for w in line)))
+ line = []
+ if line:
+ out.append((line[0].start, line[-1].end, " ".join(w.text for w in line)))
+ return out
+
+
+# ── the script: [spans] in the text ─────────────────────────────────────────────────────
+
+_SPAN = re.compile(r"\[([^\[\]]*)\]")
+
+
+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)])`."""
+ text, found, at = [], [], 0
+ shift = 0
+ for m in _SPAN.finditer(script):
+ text.append(script[at : m.start()])
+ begin = m.start() - shift
+ found.append((begin, begin + len(m.group(1))))
+ text.append(m.group(1))
+ at, shift = m.end(), shift + 2
+ text.append(script[at:])
+ return "".join(text), found
+
+
+def times(speech: Speech, span: tuple[int, int]) -> tuple[float, float]:
+ """When the characters `span` of a speech's text are said: from the start of its first
+ word to the end of its last; an empty span, the start of the word it comes before.
+ """
+ begin, end = span
+ words = speech.words
+ located = [(m.start(), m.end()) for m in _WORD.finditer(speech.text)]
+ inside = [i for i, (a, b) in enumerate(located) if a < end and b > begin] or [
+ next((i for i, (a, _) in enumerate(located) if a >= begin), len(words) - 1)
+ ]
+ first, last = inside[0], inside[-1]
+ if begin == end:
+ return words[first].start, words[first].start
+ return words[first].start, words[last].end
+
+
+# ── the cache: what a voice said, kept ──────────────────────────────────────────────────
+
+
+def cached(voice: Voice, text: str, folder: Path) -> Speech:
+ """What `voice` says for `text`: spoken once, then kept in `folder` as its audio and a
+ JSON of its words, named by the text and a digest of the voice and the text.
+
+ The audio may be replaced (a recording of the same words, in any format the engine
+ reads, under the same name): its words are then timed again, from it.
+ """
+ from manimgx._engine import digest
+
+ identity = _identity(voice)
+ key = f"{digest(identity.encode(), b'\0', text.encode()):016x}"
+ slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:40]
+ stem = folder / f"{slug}-{key[:10]}"
+ meta = stem.with_suffix(".json")
+ if meta.exists():
+ record = json.loads(meta.read_text(encoding="utf-8"))
+ audio = stem.with_suffix(record["suffix"]).read_bytes()
+ same = record.get("audio") == f"{digest(audio):016x}"
+ words = [Word(*w) for w in record["words"]] if same else []
+ return Speech(audio, text=text, words=words)
+ speech = voice(text)
+ folder.mkdir(parents=True, exist_ok=True)
+ suffix, data = _stored(speech)
+ stem.with_suffix(suffix).write_bytes(data)
+ meta.write_text(
+ json.dumps(
+ {
+ "text": text,
+ "voice": identity,
+ "suffix": suffix,
+ "audio": f"{digest(data):016x}",
+ "words": [[w.text, w.start, w.end] for w in speech._words],
+ },
+ indent=1,
+ ),
+ encoding="utf-8",
+ )
+ return speech
+
+
+def _identity(voice: Voice) -> str:
+ """What names a voice in the cache: what decides what it says. A dataclass's repr (its
+ settings; a key is left out of it); a function's name, its code and the plain values it
+ holds (in its closure, its defaults, and the fields of the object a method is bound
+ to); another callable's type and plain fields. A plain value is immutable: a string, a
+ number, a boolean, None, or a tuple of them — a voice's settings, not its state (a
+ client, a list it appends to)."""
+ if hasattr(voice, "__dataclass_fields__"):
+ return repr(voice)
+ fn = getattr(
+ voice, "__func__", voice
+ ) # a bound method: its function, and its object
+ code = getattr(fn, "__code__", None)
+ if code is None: # an object with __call__
+ return f"{type(voice).__module__}.{type(voice).__qualname__}{_fields(voice)!r}"
+ from manimgx._engine import digest
+
+ body = digest(code.co_code, repr(code.co_consts).encode())
+ cells = tuple(c.cell_contents for c in getattr(fn, "__closure__", None) or ())
+ defaults = getattr(fn, "__defaults__", None) or ()
+ keywords = getattr(fn, "__kwdefaults__", None) or {}
+ held = (
+ _plain(cells),
+ _plain(defaults),
+ _plain(tuple(sorted(keywords.items()))),
+ _fields(getattr(voice, "__self__", None)),
+ )
+ name = f"{getattr(fn, '__module__', '')}.{getattr(fn, '__qualname__', '')}"
+ return f"{name}#{body:016x}{held!r}"
+
+
+def _fields(owner: object) -> tuple[tuple[str, object], ...]:
+ """An object's plain fields, in order of their names."""
+ plain = ((k, _plain(v)) for k, v in sorted(getattr(owner, "__dict__", {}).items()))
+ return tuple((k, v) for k, v in plain if v is not _OTHER)
+
+
+def _plain(value: object) -> object:
+ """`value` if it is plain (immutable: a string, number, boolean, None, or a tuple of
+ them, whose other items are left out); else `_OTHER`."""
+ if value is None or isinstance(value, str | int | float | bool | bytes):
+ return value
+ if isinstance(value, tuple):
+ return tuple(v for v in map(_plain, value) if v is not _OTHER)
+ return _OTHER
+
+
+_OTHER = object() # not a plain value: left out of a voice's name
+
+
+def _stored(speech: Speech) -> tuple[str, bytes]:
+ source = speech.source
+ if isinstance(source, bytes):
+ return _sniff(source), source
+ if isinstance(source, np.ndarray):
+ return ".wav", _wav(speech.samples)
+ path = Path(source)
+ return path.suffix or ".bin", path.read_bytes()
+
+
+def _sniff(data: bytes) -> str:
+ if data[:4] == b"RIFF":
+ return ".wav"
+ if data[:4] == b"fLaC":
+ return ".flac"
+ if data[:4] == b"OggS":
+ return ".ogg"
+ if data[4:8] == b"ftyp":
+ return ".m4a"
+ return ".mp3"
+
+
+def _wav(samples: np.ndarray) -> bytes:
+ """Float samples at RATE as a 32-bit float WAV file."""
+ data = np.ascontiguousarray(samples, np.float32)
+ channels = data.shape[1] if data.ndim > 1 else 1
+ body = data.tobytes()
+ header = b"".join(
+ [
+ b"RIFF",
+ (36 + len(body)).to_bytes(4, "little"),
+ b"WAVEfmt ",
+ (16).to_bytes(4, "little"),
+ (3).to_bytes(2, "little"), # IEEE float
+ channels.to_bytes(2, "little"),
+ RATE.to_bytes(4, "little"),
+ (RATE * 4 * channels).to_bytes(4, "little"),
+ (4 * channels).to_bytes(2, "little"),
+ (32).to_bytes(2, "little"),
+ b"data",
+ len(body).to_bytes(4, "little"),
+ ]
+ )
+ return header + body
+
+
+def timed(text: str, pieces: Sequence[tuple[str, float, float]]) -> tuple[Word, ...]:
+ """The words of `text`, timed by a voice's timed pieces of it, in order (its characters,
+ or its tokens): each word from the start of the piece its first letter is in to the end
+ of the piece its last letter is in. Empty if the pieces don't spell the text's letters
+ (a voice that said "two" for "2"): its words are then estimated."""
+ owner: list[tuple[float, float]] = (
+ []
+ ) # each letter of the pieces: its piece's times
+ for piece, a, b in pieces:
+ owner += [(a, b)] * sum(c.isalnum() for c in piece)
+ letters = [c.lower() for c in text if c.isalnum()]
+ spelled = [c.lower() for piece, _, _ in pieces for c in piece if c.isalnum()]
+ if letters != spelled:
+ return ()
+ words, k = [], 0
+ for m in _WORD.finditer(text):
+ n = sum(c.isalnum() for c in m.group())
+ if n:
+ words.append(Word(m.group(), owner[k][0], owner[k + n - 1][1]))
+ k += n
+ elif words: # a word of no letters ("—"): at the end of the one before
+ words.append(Word(m.group(), words[-1].end, words[-1].end))
+ return tuple(words)
diff --git a/tests/unit/audio/test_sound.py b/tests/unit/audio/test_sound.py
new file mode 100644
index 00000000..b9105f4e
--- /dev/null
+++ b/tests/unit/audio/test_sound.py
@@ -0,0 +1,610 @@
+"""Sound placement and edits, and speech timing, captions and voices."""
+
+from fractions import Fraction
+from pathlib import Path
+
+import numpy as np
+import pytest
+from hypothesis import example, given, settings
+from hypothesis import strategies as st
+
+import manimgx as m
+from manimgx.animation import clock
+from manimgx.audio import sound as voices
+from manimgx.audio.sound import (
+ CUT,
+ RATE,
+ Clip,
+ Speech,
+ Word,
+ cached,
+ estimate,
+ lines,
+ mix,
+ spans,
+ timed,
+ times,
+)
+from manimgx.config import config
+
+
+def tone(seconds: float = 0.1, level: float = 0.5) -> m.Sound:
+ t = np.arange(round(seconds * RATE)) / RATE
+ return m.Sound((level * np.sin(2 * np.pi * 440 * t)).astype(np.float32), rate=RATE)
+
+
+def click() -> m.Sound:
+ x = np.zeros(480, np.float32)
+ x[0] = 1.0
+ return m.Sound(x, rate=RATE)
+
+
+def starts(scene: type[m.Scene], fps: float) -> list[Fraction]:
+ saved = config.frame_rate
+ config.frame_rate = fps
+ try:
+ return [clip.start for clip in scene().render().clips]
+ finally:
+ config.frame_rate = saved
+
+
+class TestPlacement:
+ @settings(max_examples=40)
+ @given(
+ lag=st.sampled_from([0.0, 0.25, 0.3, 0.5, 1.0]),
+ run_time=st.sampled_from([0.3, 0.55, 1.0, 1.3]),
+ count=st.integers(1, 5),
+ )
+ def test_a_sound_in_a_composition_starts_as_its_window_opens(
+ self, lag: float, run_time: float, count: int
+ ) -> None:
+ class Clicks(m.Scene):
+ def construct(self) -> None:
+ dots = [m.Dot(i * m.RIGHT) for i in range(count)]
+ self.wait(0.37) # a start between frames
+ self.play(
+ m.LaggedStart(
+ *(
+ m.AnimationGroup(m.FadeIn(d, run_time=run_time), click())
+ for d in dots
+ ),
+ lag_ratio=lag,
+ )
+ )
+
+ begin = Fraction(37, 100)
+ span = Fraction(run_time).limit_denominator(10**6)
+ step = span * Fraction(lag).limit_denominator(10**6)
+ want = [begin + i * step for i in range(count)]
+ assert starts(Clicks, 30) == want
+ assert starts(Clicks, 10) == want
+ assert starts(Clicks, 24) == want
+
+ def test_a_sound_added_by_an_updater_starts_at_its_step(self) -> None:
+ class Bounce(m.Scene):
+ def construct(self) -> None:
+ ball = m.Dot(2 * m.UP)
+ state = {"v": 0.0}
+
+ def fall(mob: m.Mobject, dt: float) -> None:
+ state["v"] -= 9.8 * dt
+ mob.shift(state["v"] * dt * m.UP)
+ if mob.get_y() < -2 and state["v"] < 0:
+ state["v"] = -0.8 * state["v"]
+ self.add_sound(click())
+
+ ball.add_updater(fall)
+ self.add(ball)
+ self.wait(3)
+
+ at_60, at_10 = starts(Bounce, 60), starts(Bounce, 10)
+ assert at_60
+ assert at_60 == at_10 # on the simulation clock, not the frames
+ assert all((t * 60).denominator == 1 for t in at_60)
+
+ def test_a_play_of_sounds_lasts_as_long_as_its_longest(self) -> None:
+ class Sounds(m.Scene):
+ def construct(self) -> None:
+ self.play(tone(0.25), tone(0.75))
+
+ film = Sounds().render()
+ assert film.plays[0].end == Fraction(3, 4)
+ assert [c.start for c in film.clips] == [0, 0]
+
+ def test_a_play_run_time_does_not_stretch_a_sound(self) -> None:
+ class Sounds(m.Scene):
+ def construct(self) -> None:
+ self.play(m.FadeIn(m.Dot()), tone(0.75), run_time=0.25)
+
+ film = Sounds().render()
+ assert film.plays[0].end == Fraction(3, 4)
+ assert film.clips[0].sound.duration == 0.75
+
+ def test_add_sound_takes_no_time(self) -> None:
+ class Added(m.Scene):
+ def construct(self) -> None:
+ self.wait(0.5)
+ self.add_sound(tone(2.0), time_offset=0.25)
+ self.wait(0.5)
+
+ film = Added().render()
+ assert film.clips[0].start == Fraction(3, 4)
+ assert film.plays[-1].end == 1
+
+ def test_an_endless_sound_is_added_not_played(self) -> None:
+ class Endless(m.Scene):
+ def construct(self) -> None:
+ self.play(tone().loop())
+
+ with pytest.raises(ValueError, match="never ends: add it with add_sound"):
+ Endless().render()
+
+ def test_a_missing_file_fails_where_it_is_given(self) -> None:
+ with pytest.raises(FileNotFoundError, match="no sound file"):
+ m.Sound("no/such/sound.wav")
+
+
+class TestEdits:
+ @given(decibels=st.floats(-60, 60), more=st.floats(-60, 60))
+ def test_gain_is_decibels(self, decibels: float, more: float) -> None:
+ a = tone()
+ np.testing.assert_allclose(
+ a.gain(decibels).samples, a.samples * 10 ** (decibels / 20), rtol=1e-6
+ )
+ np.testing.assert_allclose(
+ a.gain(decibels).gain(more).samples,
+ a.gain(decibels + more).samples,
+ rtol=1e-6,
+ )
+
+ def test_fades_ramp_from_and_to_silence(self) -> None:
+ x = m.Sound(np.ones(RATE, np.float32), rate=RATE).fade_in(0.5).fade_out(0.25)
+ s = x.samples[:, 0]
+ assert s[0] == 0
+ assert abs(s[RATE // 4] - 0.5) < 1e-3
+ assert s[RATE // 2] == 1
+ assert abs(s[-RATE // 8] - 0.5) < 1e-3
+ assert s[-1] < 1e-3
+
+ @given(start=st.floats(0, 1), end=st.none() | st.floats(0, 1))
+ def test_a_trim_is_the_span_of_the_source(
+ self, start: float, end: float | None
+ ) -> None:
+ x = m.Sound(np.arange(RATE, dtype=np.float32) / RATE, rate=RATE)
+ span = slice(round(start * RATE), None if end is None else round(end * RATE))
+ trimmed = x.trim(start, end)
+ np.testing.assert_array_equal(trimmed.samples, x.samples[span])
+ assert trimmed.duration == len(x.samples[span]) / RATE
+
+ def test_a_loop_repeats_to_its_duration(self) -> None:
+ looped = tone(0.1).loop(0.35)
+ assert looped.duration == 0.35
+ assert len(looped.samples) == round(0.35 * RATE)
+ assert np.array_equal(looped.samples[:4800], looped.samples[4800:9600])
+
+ def test_speed_shortens_the_sound(self) -> None:
+ assert tone(1.0).speed(2).duration == pytest.approx(0.5, abs=1 / RATE)
+
+ def test_pan_balances_left_and_right(self) -> None:
+ left = tone().pan(-1).samples
+ assert left.shape[1] == 2
+ assert np.abs(left[:, 1]).max() == 0
+ assert np.allclose(left[:, 0], tone().samples[:, 0])
+
+
+class TestMix:
+ @settings(max_examples=50)
+ @given(
+ starts=st.lists(
+ st.fractions(0, 2).map(lambda f: f.limit_denominator(600)),
+ min_size=1,
+ max_size=4,
+ )
+ )
+ def test_each_clip_lands_on_its_sample_and_the_mix_is_their_sum(
+ self, starts: list[Fraction]
+ ) -> None:
+ clips = [Clip(click(), start) for start in starts]
+ track = mix(clips, Fraction(3))
+ assert track is not None
+ want = np.zeros(3 * RATE, np.float32)
+ for start in starts:
+ want[round(start * RATE)] += 1.0
+ assert np.array_equal(track[:, 0], want)
+
+ def test_mono_clips_make_a_mono_track_and_a_stereo_one_stereo(self) -> None:
+ mono = mix([Clip(tone(), Fraction(0))], Fraction(1))
+ stereo = mix(
+ [Clip(tone(), Fraction(0)), Clip(tone().pan(1), Fraction(0))], Fraction(1)
+ )
+ assert mono is not None
+ assert mono.shape[1] == 1
+ assert stereo is not None
+ assert stereo.shape[1] == 2
+ assert mix([], Fraction(1)) is None
+
+ def test_a_stopped_clip_fades_from_the_stop(self) -> None:
+ bed = Clip(m.Sound(np.ones(RATE, np.float32), rate=RATE).loop(), Fraction(0))
+ bed.end, bed.fade = Fraction(3, 2), 0.5
+ track = mix([bed], Fraction(3))
+ assert track is not None
+ s = track[:, 0]
+ assert s[RATE - 1] == 1
+ assert abs(s[5 * RATE // 4] - 0.5) < 1e-3
+ assert not s[3 * RATE // 2 :].any()
+
+ def test_an_endless_loop_fades_where_its_clip_starts_and_ends(self) -> None:
+ one = m.Sound(np.ones(RATE // 2, np.float32), rate=RATE)
+ bed = Clip(one.fade_in(0.25).fade_out(0.5).loop(), Fraction(0))
+ track = mix([bed], Fraction(3))
+ assert track is not None
+ s = track[:, 0]
+ assert s[RATE // 8] == pytest.approx(0.5, abs=1e-3) # the start's fade, once
+ assert s[RATE // 2 + RATE // 8] == 1 # not again at the second round
+ assert s[5 * RATE // 2] == pytest.approx(1.0, abs=1e-3) # the end's fade begins
+ assert s[-RATE // 4] == pytest.approx(0.5, abs=1e-3)
+
+ def test_a_sound_the_film_cuts_short_fades_as_it_is_cut(self) -> None:
+ tone_ = Clip(m.Sound(np.ones(2 * RATE, np.float32), rate=RATE), Fraction(0))
+ track = mix([tone_], Fraction(1))
+ assert track is not None
+ assert track[-1, 0] < 0.01 # no click at the cut
+ assert track[RATE - round(CUT * RATE) - 1, 0] == 1
+
+ def test_a_ducking_clip_dips_under_speech_and_only_there(self) -> None:
+ bed = Clip(
+ m.Sound(np.ones(RATE, np.float32), rate=RATE).loop().duck(12), Fraction(0)
+ )
+ words = Speech(np.zeros(RATE, np.float32), text="quiet", rate=RATE)
+ track = mix([bed, Clip(words, Fraction(2))], Fraction(5))
+ assert track is not None
+ s = track[:, 0]
+ low = 10 ** (-12 / 20)
+ assert s[RATE] == pytest.approx(1) # long before
+ assert s[5 * RATE // 2] == pytest.approx(low, rel=1e-3) # during
+ assert s[9 * RATE // 2] == pytest.approx(1) # long after
+
+
+def memory(a: np.ndarray) -> list[np.ndarray]:
+ """The arrays an array's values live in: a masked array's data and its mask."""
+ return [np.ma.getdata(a), np.ma.getmaskarray(a)] if np.ma.isMaskedArray(a) else [a]
+
+
+def shares(a: np.ndarray, b: np.ndarray) -> bool:
+ return any(np.shares_memory(x, y) for x in memory(a) for y in memory(b))
+
+
+SOURCES = ("an array", "a view", "reversed", "read-only", "masked", "mapped")
+
+
[email protected]("speaks", [False, True], ids=["sound", "speech"])
[email protected]("kind", SOURCES)
+def test_a_sounds_samples_are_its_own(kind: str, speaks: bool, tmp_path: Path) -> None:
+ """A sound holds its samples as a value, from when it is made: making them (a speech's
+ words too) leaves the source as it was; the source changing, before they are first
+ read or after, changes them not, nor its edits'; they changing changes not the source;
+ an edit is samples of its own."""
+ values = np.linspace(-0.5, 0.5, 96, dtype=np.float32).reshape(48, 2)
+ base = (
+ np.memmap(tmp_path / "samples.bin", np.float32, "w+", shape=(48, 2))
+ if kind == "mapped"
+ else values.copy()
+ )
+ base[:] = values
+ source = {
+ "an array": base,
+ "a view": base.view(),
+ "reversed": base[::-1],
+ "read-only": base.view(),
+ "masked": np.ma.array(base, mask=np.zeros(base.shape, bool)),
+ "mapped": base,
+ }[kind]
+ source.flags.writeable = kind != "read-only"
+ held = np.array(source)
+ sound = (
+ Speech(source, text="one, two.", rate=RATE)
+ if speaks
+ else m.Sound(source, rate=RATE)
+ )
+ base[:] = 3 # the source changing before its samples are first read
+ samples = sound.samples
+ if isinstance(sound, Speech):
+ assert [w.text for w in sound.words] == ["one,", "two."]
+ np.testing.assert_array_equal(samples, held)
+ assert not shares(samples, source)
+
+ base[:] = 2
+ if np.ma.isMaskedArray(source):
+ np.ma.getmaskarray(source)[0, 0] = True # its own mask, not a copy
+ np.testing.assert_array_equal(samples, held)
+ assert not np.ma.getmaskarray(samples).any()
+ samples[:] = 4
+ np.testing.assert_array_equal(base, np.full((48, 2), 2, np.float32))
+ edited = sound.gain(0).samples
+ np.testing.assert_array_equal(np.ma.getdata(edited), held)
+ assert not shares(edited, samples)
+ assert not shares(edited, source)
+
+
+SECONDS_PER_LETTER = 0.05
+HOP = RATE // 100 # the estimate hears loudness in 10 ms hops
+PAUSES = {".": 6, "!": 6, "?": 6, ":": 6, ";": 6, ",": 3} # letters' worth after a word
+
+
+def said(text: str) -> Speech:
+ """A voice that takes 0.05 s a letter (a space too) and knows when it says each word."""
+ words, at = [], 0.0
+ for word in text.split():
+ start = text.index(word, round(at / SECONDS_PER_LETTER))
+ words.append(
+ Word(
+ word,
+ start * SECONDS_PER_LETTER,
+ (start + len(word)) * SECONDS_PER_LETTER,
+ )
+ )
+ at = words[-1].end
+ samples = np.full(round(len(text) * SECONDS_PER_LETTER * RATE), 0.1, np.float32)
+ return Speech(samples, text=text, words=words, rate=RATE)
+
+
+def cache_here(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setattr("manimgx.scene._voice_folder", lambda scene: tmp_path / "voice")
+ return tmp_path / "voice"
+
+
+class Begun(m.Animation):
+ """An animation that notes the instant it begins."""
+
+ def __init__(self, log: list[Fraction], run_time: float = 1.0) -> None:
+ super().__init__(None, run_time=run_time)
+ self.log = log
+
+ def begin(self) -> None:
+ self.log.append(clock.now)
+
+
[email protected]("cache_here")
+class TestScript:
+ @given(st.lists(st.text("abc ", min_size=0, max_size=6), min_size=1, max_size=5))
+ @example(["Here is ", "a circle", " and ", "a square", "."])
+ @example(["No spans."])
+ @example(["An empty ", "", " span."])
+ def test_the_text_is_the_script_without_its_brackets(
+ self, parts: list[str]
+ ) -> None:
+ script = "".join(f"[{p}]" if i % 2 else p for i, p in enumerate(parts))
+ text, found = spans(script)
+ assert text == script.replace("[", "").replace("]", "")
+ for (a, b), part in zip(found, parts[1::2], strict=True):
+ assert text[a:b] == part
+
+ 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")
+ assert text == speech.text
+ a, b = times(speech, span)
+ x, squared = speech.words[3], speech.words[4]
+ assert (a, b) == (x.start, squared.end)
+
+
[email protected]("cache_here")
+class TestSay:
+ def test_each_animation_starts_as_its_words_start(self) -> None:
+ begun: list[Fraction] = []
+ spoken: list[Speech] = []
+
+ class Say(m.Scene):
+ voice = staticmethod(said)
+
+ def construct(self) -> None:
+ self.wait(0.37) # between frames
+ spoken.append(
+ self.say(
+ "here is [a dot] and [a square too]",
+ Begun(begun),
+ Begun(begun, 0.1),
+ )
+ )
+
+ film = Say().render()
+ (speech,) = spoken
+ want = [times(speech, (8, 13))[0], times(speech, (18, 30))[0]]
+ assert [float(t) - 0.37 for t in begun] == pytest.approx(want)
+ # the second lasts as long as its words (longer than its 0.1 s), the first 1 s
+ end = max(speech.duration, want[0] + 1, times(speech, (18, 30))[1])
+ assert float(film.plays[-1].end) - 0.37 == pytest.approx(end)
+
+ def test_the_play_lasts_as_long_as_the_speech_or_its_animations(self) -> None:
+ class Long(m.Scene):
+ voice = staticmethod(said)
+
+ def construct(self) -> None:
+ self.say("a long sentence with many letters in it", m.FadeIn(m.Dot()))
+
+ film = Long().render()
+ speech = film.clips[0].sound
+ assert float(film.plays[0].end) == pytest.approx(speech.duration)
+
+ def test_one_animation_per_span(self) -> None:
+ class Wrong(m.Scene):
+ voice = staticmethod(said)
+
+ def construct(self) -> None:
+ self.say("[one] and [two]", m.FadeIn(m.Dot()))
+
+ with pytest.raises(ValueError, match="2 bracketed spans for 1 animations"):
+ Wrong().render()
+
+
[email protected]("cache_here")
+class TestVoice:
+ def test_a_function_set_on_the_scene_is_its_voice(self) -> None:
+ class Plain(m.Scene):
+ voice = said # a plain function: not a method of the scene
+
+ def construct(self) -> None:
+ self.say("plain words")
+
+ (clip,) = Plain().render().clips
+ assert isinstance(clip.sound, Speech)
+ assert clip.sound.text == "plain words"
+
+
[email protected]("cache_here")
+class TestCache:
+ def test_a_voice_speaks_each_text_once(self, cache_here: Path) -> None:
+ calls: list[str] = []
+
+ def counted(text: str) -> Speech:
+ calls.append(text)
+ return said(text)
+
+ for _ in range(2):
+ speech = cached(counted, "hello there", cache_here)
+ assert calls == ["hello there"]
+ assert [w.text for w in speech.words] == ["hello", "there"]
+ assert (
+ len(list(cache_here.glob("hello-there-*"))) == 2
+ ) # the audio and its words
+ (words,) = cache_here.glob("hello-there-*.json")
+ assert words.read_text(encoding="utf-8").endswith("}\n") # a text file's end
+
+ def test_a_recording_in_its_place_is_timed_again(self, cache_here: Path) -> None:
+ cached(said, "hello there", cache_here)
+ (audio,) = cache_here.glob("hello-there-*.wav")
+ silence_then_sound = np.concatenate(
+ [np.zeros(RATE, np.float32), np.full(RATE, 0.5, np.float32)]
+ )
+ audio.write_bytes(voices._wav(silence_then_sound[:, None]))
+ again = cached(said, "hello there", cache_here)
+ assert again.words[0].start >= 0.9 # estimated from the recording, not kept
+
+ def test_a_voice_is_named_by_what_it_holds_not_where(self) -> None:
+ def speaking(pace: float): # a voice factory: closures with the same name
+ def voice(text: str) -> Speech:
+ return said(text).speed(pace)
+
+ return voice
+
+ slow, fast, again = speaking(1.0), speaking(1.5), speaking(1.0)
+ assert voices._identity(slow) != voices._identity(fast)
+ assert voices._identity(slow) == voices._identity(again)
+
+ class Called: # a callable object: named by its fields, not its address
+ def __init__(self, voice_id: str) -> None:
+ self.voice_id = voice_id
+
+ def __call__(self, text: str) -> Speech:
+ return said(text)
+
+ assert voices._identity(Called("a")) == voices._identity(Called("a"))
+ assert voices._identity(Called("a")) != voices._identity(Called("b"))
+
+
[email protected]("cache_here")
+class TestWords:
+ def test_pieces_time_the_words(self) -> None:
+ pieces = [(c, i * 0.1, i * 0.1 + 0.1) for i, c in enumerate("hi, you")]
+ hi, you = timed("hi, you", pieces)
+ assert (hi.text, hi.start, hi.end) == ("hi,", 0.0, pytest.approx(0.2))
+ assert (you.start, you.end) == (pytest.approx(0.4), pytest.approx(0.7))
+
+ def test_other_letters_are_not_the_words(self) -> None:
+ assert timed("2x", [("two", 0, 0.3), ("x", 0.3, 0.5)]) == ()
+
+ @given(
+ words=st.lists(
+ st.builds(
+ str.__add__,
+ st.text("aé世", min_size=1, max_size=6),
+ st.sampled_from(["", ",", ".", "!", "?", ":", ";"]),
+ ),
+ min_size=1,
+ max_size=8,
+ ),
+ separator=st.sampled_from([" ", "\t\n", "\u00a0", "\u2003"]),
+ hops=st.tuples(st.integers(0, 20), st.integers(0, 60), st.integers(0, 20)),
+ rest=st.integers(0, HOP - 1),
+ loud_rest=st.booleans(),
+ channels=st.integers(1, 2),
+ )
+ @example( # a voiced span from 0.1 s to 0.9 s, its words weighed 2, 6 and 10
+ words=["A", "bb,", "ccc."],
+ separator=" ",
+ hops=(10, 80, 10),
+ rest=0,
+ loud_rest=False,
+ channels=1,
+ )
+ @example( # audio shorter than a hop, voiced: none heard
+ words=["one", "two"],
+ separator=" ",
+ hops=(0, 0, 0),
+ rest=HOP - 1,
+ loud_rest=True,
+ channels=1,
+ )
+ def test_an_estimate_shares_the_voiced_span_by_letters_and_pauses(
+ self,
+ words: list[str],
+ separator: str,
+ hops: tuple[int, int, int],
+ rest: int,
+ loud_rest: bool,
+ channels: int,
+ ) -> None:
+ """The audio is heard in hops of 10 ms; its words share the span of the hops heard (or
+ all of it, if none is), each its letters and a pause after it: 6 letters' worth after
+ a full stop (. ! ? : ;), 3 after a comma, 1 otherwise."""
+ before, voiced, after = hops
+ audio = np.zeros(((before + voiced + after) * HOP + rest, channels), np.float32)
+ audio[before * HOP : (before + voiced) * HOP] = 0.1
+ audio[len(audio) - rest :] = 0.1 if loud_rest else 0
+ got = estimate(separator.join(words), audio)
+ assert [w.text for w in got] == words
+ if voiced:
+ weights = [len(w) + PAUSES.get(w[-1], 1) for w in words]
+ edges = np.cumsum([0, *weights]) / sum(weights)
+ pauses = np.array(weights) - [len(w) for w in words]
+ span = voiced / 100
+ starts = before / 100 + edges[:-1] * span
+ ends = before / 100 + (edges[1:] - pauses / sum(weights)) * span
+ else:
+ shares = np.arange(len(words) + 1) / len(words) * len(audio) / RATE
+ starts, ends = shares[:-1], shares[1:]
+ np.testing.assert_allclose([w.start for w in got], starts, atol=1e-12)
+ np.testing.assert_allclose([w.end for w in got], ends, atol=1e-12)
+
+ @pytest.mark.parametrize("kind", ["timed by its voice", "estimated"])
+ @given(cut=st.floats(0, 1), factor=st.floats(0.25, 4))
+ def test_words_move_with_trims_and_speed(
+ self, kind: str, cut: float, factor: float
+ ) -> None:
+ text = "One two. Three four!"
+ speech = (
+ said(text)
+ if kind == "timed by its voice"
+ else Speech(np.full((RATE, 2), 0.1, np.float32), text=text, rate=RATE)
+ )
+ start = cut * speech.duration
+ edited = speech.trim(start).speed(factor)
+ kept = [w for w in speech.words if w.start >= start]
+ assert [w.text for w in edited.words] == [w.text for w in kept]
+ np.testing.assert_allclose(
+ [(w.start, w.end) for w in edited.words],
+ [((w.start - start) / factor, (w.end - start) / factor) for w in kept],
+ atol=1e-12,
+ )
+
+ def test_a_trim_keeps_the_words_it_holds(self) -> None:
+ speech = said("one two three") # two starts at 0.2 s
+ assert [w.text for w in speech.trim(0, 0.2).words] == ["one"]
+
+ def test_captions_break_at_sentences(self) -> None:
+ speech = said("One two. Three four five.")
+ assert [text for _, _, text in lines(speech)] == [
+ "One two.",
+ "Three four five.",
+ ]