The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Time and caption speech in the pieces Unicode breaks a line into
Don Yinf8d7b47f25a9
diff --git a/docs/content/changelog.md b/docs/content/changelog.mdindex 6a997e3c..6d883df1 100644--- a/docs/content/changelog.md+++ b/docs/content/changelog.md@@ -43,6 +43,7 @@ The notable changes to ManimGX, release by release. The format follows- 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)).+- Time and caption speech in the pieces Unicode lets a line break between, so a `say` span in Chinese, Japanese or Thai, written without spaces, is timed by its own characters or words, where the whole sentence was one word ([#40](https://github.com/academa-labs/manimgx/issues/40)). Captions are the text as it is written, at most 42 columns wide (a Chinese or Japanese character takes two); a line never starts with a closing mark such as `,` or `」`, and ends where a sentence does, a quoted one too. A speech's words are found in its text by themselves, so a trimmed speech, or a voice that cuts its words its own way, no longer fails or mistimes a span; and an empty span after the last word starts where that word ends.- 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 8d3ac5d4..59142b5f 100644--- a/docs/content/user-guide/sound-and-voice.md+++ b/docs/content/user-guide/sound-and-voice.md@@ -62,7 +62,9 @@ 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.+Brackets come in pairs and don't nest; any other bracket is an error. Text written without+spaces works the same: a span can start on any Chinese or Japanese character, or any Thai+word, so `这是一个[圆]。` starts the animation on 圆.## Voicesdiff --git a/rust/Cargo.lock b/rust/Cargo.lockindex e59c3717..3a10a3e9 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2078,6 +2078,7 @@ dependencies = ["dirs 7.0.0","dxc","ffmpeg",+ "icu_segmenter","js-sys","libc","memmap2",diff --git a/rust/engine/Cargo.toml b/rust/engine/Cargo.tomlindex 0f6a1f49..771d73a5 100644--- a/rust/engine/Cargo.toml+++ b/rust/engine/Cargo.toml@@ -20,7 +20,7 @@ default = ["python", "render", "export", "typeset", "window"]python = ["dep:pyo3", "dep:ffmpeg", "dep:wasm-bindgen-cli-support", "dep:zstd"]render = ["dep:wgpu", "dep:ash", "dep:libc", "dep:dxc", "dep:windows-sys"]export = ["render", "dep:rusty_aac", "dep:x264"]-typeset = ["dep:typst", "dep:typst-kit", "dep:typst-layout", "dep:ttf-parser", "dep:unicode-segmentation", "dep:mitex", "dep:mitex-spec-gen", "dep:bincode", "dep:memmap2", "dep:dirs"]+typeset = ["dep:typst", "dep:typst-kit", "dep:typst-layout", "dep:ttf-parser", "dep:unicode-segmentation", "dep:icu_segmenter", "dep:mitex", "dep:mitex-spec-gen", "dep:bincode", "dep:memmap2", "dep:dirs"]# the player (src/player.rs): takes played on a clock, with a face and a sound, on any screenplayer = ["render", "dep:ruzstd", "dep:serde", "dep:serde_json", "dep:rustybuzz", "dep:ttf-parser", "dep:unicode-bidi", "dep:unicode-segmentation", "dep:web-time"]window = ["python", "typeset", "player", "dep:winit", "dep:cpal"]@@ -37,6 +37,7 @@ typst-kit = { version = "0.15.1", default-features = false, features = ["embeddetypst-layout = { version = "0.15.1", optional = true }ttf-parser = { version = "0.25.1", optional = true } # glyph outlines and ligature carets, from the fonts Typst loadedunicode-segmentation = { version = "1.12", optional = true } # graphemes: the characters a ligature's colors divide+icu_segmenter = { version = "2.3", optional = true } # where text breaks, by the segmenter Typst breaks lines withbincode = { version = "1.3", optional = true } # the system fonts' scan, cached on diskmemmap2 = { version = "0.9", optional = true } # system fonts mapped, not read whole (a CJK font is 60 MB)dirs = { version = "7", optional = true } # the current user's cache directorydiff --git a/rust/engine/src/python.rs b/rust/engine/src/python.rsindex 0e89c256..f3e8ac96 100644--- a/rust/engine/src/python.rs+++ b/rust/engine/src/python.rs@@ -431,6 +431,13 @@ mod typesetting {core::graphemes(text)}+ /// Where Unicode lets `text` break, in characters from 0 to its length: where a line may+ /// break (UAX #14) and where a sentence ends (UAX #29).+ #[pyfunction]+ pub(super) fn segments(text: &str) -> (Vec<usize>, Vec<usize>) {+ core::segments(text)+ }+/// LaTeX math as Typst math (mitex's conversion; its default command spec).#[pyfunction]pub(super) fn mitex_math(latex: &str) -> PyResult<String> {@@ -543,6 +550,7 @@ fn _engine(m: &Bound<'_, PyModule>) -> PyResult<()> {m.add_function(wrap_pyfunction!(glyph_outlines, m)?)?;m.add_function(wrap_pyfunction!(ligature_carets, m)?)?;m.add_function(wrap_pyfunction!(graphemes, m)?)?;+ m.add_function(wrap_pyfunction!(segments, m)?)?;m.add_function(wrap_pyfunction!(mitex_math, m)?)?;m.add_function(wrap_pyfunction!(mitex_text, m)?)?;m.add_function(wrap_pyfunction!(system_fonts_fingerprint, m)?)?;diff --git a/rust/engine/src/typeset.rs b/rust/engine/src/typeset.rsindex 8e363a14..e3b65834 100644--- a/rust/engine/src/typeset.rs+++ b/rust/engine/src/typeset.rs@@ -11,6 +11,8 @@ use std::collections::HashMap;use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex, OnceLock};+use icu_segmenter::options::LineBreakOptions;+use icu_segmenter::{LineSegmenter, SentenceSegmenter};use typst::diag::{FileError, FileResult, Severity, SourceDiagnostic};use typst::foundations::{Bytes, Datetime, Duration};use typst::introspection::{Location, Tag};@@ -748,6 +750,27 @@ pub fn graphemes(text: &str) -> Vec<usize> {.collect()}+/// Where Unicode lets `text` break, in characters from 0 to its length: where a line may break+/// (UAX #14, by the segmenter Typst breaks lines with, which finds the words of Thai and the+/// scripts like it by a model of them), and where a sentence ends (UAX #29).+pub fn segments(text: &str) -> (Vec<usize>, Vec<usize>) {+ let lines = LineSegmenter::new_lstm(LineBreakOptions::default());+ let sentences = SentenceSegmenter::new(Default::default());+ (in_characters(text, lines.segment_str(text)), in_characters(text, sentences.segment_str(text)))+}++/// Offsets into `text` in bytes, in order, as offsets in characters.+fn in_characters(text: &str, bytes: impl Iterator<Item = usize>) -> Vec<usize> {+ let (mut at, mut chars) = (0, 0);+ bytes+ .map(|byte| {+ chars += text[at..byte].chars().count();+ at = byte;+ chars+ })+ .collect()+}+/// LaTeX math as Typst math (mitex's conversion; its default command spec).pub fn mitex_math(latex: &str) -> Result<String, String> {mitex::convert_math(latex, None)diff --git a/src/manimgx/_engine.pyi b/src/manimgx/_engine.pyiindex b072c2a1..f8869129 100644--- a/src/manimgx/_engine.pyi+++ b/src/manimgx/_engine.pyi@@ -268,6 +268,10 @@ def ligature_carets(key: int) -> list[float]:def graphemes(text: str) -> list[int]:"""Where `text`'s graphemes start, in characters."""+def segments(text: str) -> tuple[list[int], list[int]]:+ """Where Unicode lets `text` break, in characters from 0 to its length: where a line may+ break (UAX #14) and where a sentence ends (UAX #29)."""+def mitex_math(latex: str) -> str:"""LaTeX math as Typst math (mitex); raises TypstError on what it can't convert."""diff --git a/src/manimgx/audio/sound.py b/src/manimgx/audio/sound.pyindex db572229..4b17a0f8 100644--- a/src/manimgx/audio/sound.py+++ b/src/manimgx/audio/sound.py@@ -4,9 +4,11 @@ import dataclassesimport marshalimport mathimport os+import unicodedatafrom collections.abc import Callablefrom dataclasses import dataclassfrom fractions import Fraction+from itertools import pairwisefrom pathlib import Pathfrom types import CodeTypefrom typing import TYPE_CHECKING, ClassVar, Self@@ -348,7 +350,9 @@ def _ducked(clips: list[Clip], decibels: float, at: int, length: int) -> np.ndar@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."""+ speech's start. The words of a speech are pieces of its text, in order: those Unicode lets+ a line break between (a word, a Chinese or Japanese character, a Thai word, each with the+ marks that go with it), unless its voice gives its own."""text: strstart: float@@ -364,8 +368,8 @@ class Speech(Sound):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.+ words: Each word and when it is said, if the voice knows ([`timed`][manimgx.audio.timed]+ makes them from a voice's own timing); otherwise they are estimated from the audio.rate: The samples' rate; only for samples."""@@ -382,6 +386,8 @@ class Speech(Sound):super().__init__(source, rate=rate)self.text = textself._words = tuple(words) # the source's: before trims and speed+ if self._words:+ _located(self) # refuses words that are not pieces of the text@propertydef words(self) -> tuple[Word, ...]:@@ -409,14 +415,33 @@ text-to-speech: wrap its call in a function that returns `Speech(audio, text=tex# ── timing ───────────────────────────────────────────────────────────────────────────────-_WORD = re.compile(r"\S+")+def _pieces(text: str) -> list[tuple[int, int, bool]]:+ """The pieces a text is timed and shown in: what lies between two places Unicode lets a+ line break, without its spaces (a word, a Chinese or Japanese character, a Thai word, each+ with the marks that go with it), as the characters (begin, end) it spells, and whether a+ sentence ends with it. An opening bracket or quote that the end of a sentence takes with it+ (`。「`) begins the next sentence, as it begins the next line."""+ from manimgx._engine import segments++ breaks, sentences = segments(text)+ ends = set()+ for end in sentences:+ while end and unicodedata.category(text[end - 1]) in ("Ps", "Pi"):+ end -= 1+ ends.add(end)+ pieces = []+ for a, b in pairwise(breaks):+ if piece := text[a:b].strip():+ begin = text.index(piece, a)+ pieces.append((begin, begin + len(piece), b in ends))+ return piecesdef estimate(text: str, samples: np.ndarray) -> tuple[Word, ...]:"""When each word of `text` is said in `samples`, estimated: the audio's voiced spanshared among the words by their letters, with a share more for the pause after a comma ora full stop."""- words = _WORD.findall(text)+ words = [text[a:b] for a, b, _ in _pieces(text)]if not words:return ()level = np.abs(samples).max(axis=1) if samples.ndim > 1 else np.abs(samples)@@ -449,24 +474,50 @@ def estimate(text: str, samples: np.ndarray) -> tuple[Word, ...]:)+def _located(speech: Speech) -> list[tuple[int, int]]:+ """Where each word of a speech is in its text, as the characters (begin, end) it spells.+ The words are pieces of the text, in order: each is found after the one before."""+ text, at, found = speech.text, 0, []+ for word in speech.words:+ begin = text.find(word.text, at)+ if begin < 0:+ raise ValueError(+ f"the word {word.text!r} is not in {text!r} after character {at}: a"+ " speech's words are pieces of its text, in order"+ )+ at = begin + len(word.text)+ found.append((begin, at))+ return found+++def _columns(text: str) -> int:+ """How wide a text is shown, in columns: its spaces as one, and a wide character (Chinese,+ Japanese, Korean) as two."""+ return sum(+ 1 + (unicodedata.east_asian_width(c) in "WF") for c in " ".join(text.split())+ )++@deprecated("ManimGX's machinery: the captions call it", category=None)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+ """A speech as captions: its text in lines at most `width` columns wide (a Chinese or+ Japanese character takes two), broken where Unicode lets a line break, a line ending where+ a sentence does. A line is shown from when it begins to be said until the next one does,+ or, ending a sentence, until it has been said; in seconds from the speech's start."""+ text = speech.text+ # each line's characters, and whether a sentence ends it+ cut: list[tuple[int, int, bool]] = []+ for a, b, ends in _pieces(text):+ if cut and not cut[-1][2] and _columns(text[cut[-1][0] : b]) <= width:+ cut[-1] = (cut[-1][0], b, ends)+ else:+ cut.append((a, b, ends))+ said = [times(speech, (a, b)) for a, b, _ in cut]+ shown = []+ for k, ((a, b, ends), (start, end)) in enumerate(zip(cut, said, strict=True)):+ until = end if ends or k + 1 == len(cut) else said[k + 1][0]+ shown.append((start, until, " ".join(text[a:b].split())))+ return shown# ── the script: [spans] in the text ─────────────────────────────────────────────────────@@ -499,18 +550,16 @@ def spans(script: str) -> tuple[str, list[tuple[int, int]]]:@deprecated("ManimGX's machinery: say calls it", category=None)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.- """+ word to the end of its last; an empty span, the start of the word it comes before (the+ end of the last, if it comes after them all)."""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+ words, places = speech.words, _located(speech)+ inside = [w for w, (a, b) in zip(words, places) if a < end and b > begin]+ if begin < end and inside:+ return inside[0].start, inside[-1].end+ ahead = (w.start for w, (_, b) in zip(words, places) if b > begin)+ start = next(ahead, words[-1].end)+ return start, start# ── the cache: what a voice said, kept ──────────────────────────────────────────────────@@ -682,12 +731,12 @@ def timed(text: str, pieces: Sequence[tuple[str, float, float]]) -> tuple[Word,if not letters or letters != spelled:return ()words, k = [], 0- for m in _WORD.finditer(text):- n = sum(c.isalnum() for c in m.group())+ for a, b, _ in _pieces(text):+ n = sum(c.isalnum() for c in text[a:b])if n:- words.append(Word(m.group(), owner[k][0], owner[k + n - 1][1]))+ words.append(Word(text[a:b], owner[k][0], owner[k + n - 1][1]))k += nelse: # punctuation: beside the preceding word, or the first following wordat = words[-1].end if words else owner[0][0]- words.append(Word(m.group(), at, at))+ words.append(Word(text[a:b], at, at))return tuple(words)diff --git a/src/manimgx/scene.py b/src/manimgx/scene.pyindex ff3b0481..c997a42c 100644--- a/src/manimgx/scene.py+++ b/src/manimgx/scene.py@@ -1612,7 +1612,9 @@ class Scene:lasting 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 playduring 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).+ `]`, so a nested, unclosed or stray bracket is an error (a ValueError). Text is+ timed in the pieces Unicode lets a line break between, so in text written without+ spaces a span can start on any Chinese or Japanese character, or any Thai word.Args:script: What to say, with a bracketed span for each animation (or none).diff --git a/tests/unit/audio/test_fal.py b/tests/unit/audio/test_fal.pyindex 6feb57c9..b0046fd2 100644--- a/tests/unit/audio/test_fal.py+++ b/tests/unit/audio/test_fal.py@@ -175,6 +175,25 @@ class TestTiming:("you", pytest.approx(0.03), pytest.approx(0.06)),)+ def test_elevenlabs_alignment_times_each_chinese_character(+ self, service: Service+ ) -> None:+ text = "这是一个圆。"+ service.reply = {+ "timestamps": [+ {+ "characters": list(text),+ "character_start_times_seconds": [i / 10 for i in range(len(text))],+ "character_end_times_seconds": [+ (i + 1) / 10 for i in range(len(text))+ ],+ }+ ]+ }+ words = Fal()(text).words+ assert [w.text for w in words] == ["这", "是", "一", "个", "圆。"]+ assert words[4].start == pytest.approx(0.4) # 圆's own time, kept+def test_timed_words_time_the_words(self, service: Service) -> None:items = [{"text": "hi", "start": 0.0, "end": 0.02},diff --git a/tests/unit/audio/test_sound.py b/tests/unit/audio/test_sound.pyindex 0089a207..7af43fd3 100644--- a/tests/unit/audio/test_sound.py+++ b/tests/unit/audio/test_sound.py@@ -1,7 +1,9 @@"""Sound placement and edits, and speech timing, captions and voices."""import re+import unicodedatafrom fractions import Fraction+from itertools import pairwisefrom pathlib import Pathfrom typing import cast@@ -19,6 +21,7 @@ from manimgx.audio.sound import (Clip,Speech,Word,+ _pieces,cached,estimate,lines,@@ -388,6 +391,19 @@ def said(text: str) -> Speech:return Speech(samples, text=text, words=words, rate=RATE)+def untimed(text: str) -> Speech:+ """A voice that takes 0.25 s a character and times none: its words are estimated."""+ return Speech(+ np.full(round(len(text) / 4 * RATE), 0.1, np.float32), text=text, rate=RATE+ )+++def spelled(text: str) -> Speech:+ """A voice that takes 0.25 s a character and times each one: Chinese or Japanese, say."""+ pieces = [(c, i / 4, (i + 1) / 4) for i, c in enumerate(text)]+ return Speech(untimed(text).source, text=text, words=timed(text, pieces), rate=RATE)++@pytest.fixturedef cache_here(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:monkeypatch.setattr("manimgx.scene._voice_folder", lambda scene: tmp_path / "voice")@@ -524,6 +540,26 @@ class TestSay:assert said_texts == []assert not cache_here.exists()+ @pytest.mark.parametrize("speaker", [spelled, untimed], ids=["timed", "estimated"])+ def test_an_animation_starts_on_its_character_in_text_without_spaces(+ self, speaker: voices.Voice+ ) -> None:+ begun: list[Fraction] = []+ spoken: list[Speech] = []++ class Say(m.Scene):+ voice = staticmethod(speaker)++ def construct(self) -> None:+ self.wait(0.37) # between frames+ spoken.append(self.say("这是一个[圆]。", Begun(begun)))++ Say().render()+ (speech,) = spoken+ start = float(begun[0]) - 0.37+ assert start == pytest.approx(speech.words[4].start) # on 圆, not the sentence+ assert 0.6 < start < 1.2 # (said from 1.0 s, at 0.25 s a character)+@pytest.mark.usefixtures("cache_here")class TestVoice:@@ -676,17 +712,134 @@ class TestWords:def test_other_letters_are_not_the_words(self) -> None:assert timed("2x", [("two", 0, 0.3), ("x", 0.3, 0.5)]) == ()+ @pytest.mark.parametrize(+ ("text", "words"),+ [+ ("Here is a circle.", ["Here", "is", "a", "circle."]),+ ("forty-two and/or 3.14", ["forty-", "two", "and/", "or", "3.14"]),+ ("10\u00a0km away", ["10\u00a0km", "away"]),+ ("这是一个圆。", ["这", "是", "一", "个", "圆。"]),+ ("「はい」。コーヒー", ["「は", "い」。", "コー", "ヒー"]),+ (+ "使用 Python 编写,第1章",+ ["使", "用", "Python", "编", "写,", "第", "1", "章"],+ ),+ ("วันนี้เราจะเรียน", ["วัน", "นี้", "เรา", "จะ", "เรียน"]),+ ],+ ids=[+ "English",+ "hyphen and slash",+ "no-break space",+ "Chinese",+ "Japanese",+ "mixed",+ "Thai",+ ],+ )+ def test_the_words_are_the_pieces_unicode_breaks_a_line_into(+ self, text: str, words: list[str]+ ) -> None:+ """A word goes up to where a line may break: after a space (not a no-break space), a+ hyphen or a slash; between two Chinese or Japanese characters, each with the marks that go with it (an+ opening bracket with the one after it, any other mark and ー with the one before);+ between two Thai words."""+ speech = Speech(np.full(RATE, 0.1, np.float32), text=text, rate=RATE)+ assert [w.text for w in speech.words] == words++ @pytest.mark.parametrize(+ ("script", "when"),+ [+ ("这是一个[圆]。", (1.0, 1.25)),+ ("这是[一个圆]。", (0.5, 1.25)),+ ("ここに[円]があります。", (0.75, 1.0)),+ ("使用 [Python] 编写", (0.75, 2.25)),+ ("เราจะเรียน[แคลคูลัส]", (2.5, 4.5)),+ ],+ ids=["one character", "three", "Japanese", "mixed", "Thai"],+ )+ def test_a_span_of_text_without_spaces_is_said_by_its_characters_or_words(+ self, script: str, when: tuple[float, float]+ ) -> None:+ text, (span,) = spans(script)+ assert times(spelled(text), span) == pytest.approx(when)++ @given(data=st.data())+ def test_a_span_is_said_when_the_pieces_it_touches_are_whatever_their_grain(+ self, data: st.DataObject+ ) -> None:+ """A voice cuts its text as it likes (words, characters, phrases, or all of it, as an+ old cache did for text without spaces): a span is said from the start of the first+ piece it touches to the end of the last."""+ text = data.draw(st.text("ab 这是。\n", min_size=2, max_size=16))+ cuts = data.draw(st.sets(st.integers(1, len(text) - 1)))+ pieces = list(pairwise([0, *sorted(cuts), len(text)]))+ n = 2 * len(pieces)+ stamps = sorted(data.draw(st.lists(st.floats(0, 9), min_size=n, max_size=n)))+ words = [+ Word(text[a:b], stamps[2 * i], stamps[2 * i + 1])+ for i, (a, b) in enumerate(pieces)+ ]+ begin = data.draw(st.integers(0, len(text) - 1))+ end = data.draw(st.integers(begin + 1, len(text)))+ touched = [w for w, (a, b) in zip(words, pieces) if a < end and b > begin]+ speech = Speech(np.zeros(RATE, np.float32), text=text, words=words, rate=RATE)+ assert times(speech, (begin, end)) == (touched[0].start, touched[-1].end)++ def test_a_trim_leaves_the_places_of_the_words_it_keeps(self) -> None:+ speech = said("one two three four") # three is said from 0.4 s, four from 0.7 s+ assert times(speech.trim(0.3), (8, 18)) == pytest.approx((0.1, 0.6))++ @pytest.mark.parametrize(+ "words",+ [+ [Word("I", 0, 0.1), Word("have", 0.1, 0.3), Word("two", 0.3, 0.5)],+ [Word("have", 0, 0.2), Word("I", 0.2, 0.3)],+ ],+ ids=["spelled otherwise", "out of order"],+ )+ def test_words_that_are_not_the_pieces_of_the_text_in_order_are_refused(+ self, words: list[Word]+ ) -> None:+ with pytest.raises(ValueError, match="pieces of its text, in order"):+ Speech(+ np.zeros(RATE, np.float32),+ text="I have 2 apples.",+ words=words,+ rate=RATE,+ )++ @pytest.mark.parametrize(+ ("span", "when"),+ [+ ((3, 3), 0.2), # between words: where the next is said+ ((5, 5), 0.2), # inside a word: where it is said from+ ((11, 11), 0.55), # after them all: where the last has been said+ ((3, 4), 0.2), # of nothing but a space: as empty+ ],+ )+ def test_a_span_with_no_word_starts_where_it_stands(+ self, span: tuple[int, int], when: float+ ) -> None:+ # of is said from 0.2 s, text from 0.35 s to 0.55 s+ speech = said("end of text")+ assert times(speech, span) == (pytest.approx(when), pytest.approx(when))+@given(words=st.lists(- st.builds(- str.__add__,- st.text("aé世", min_size=1, max_size=6),- st.sampled_from(["", ",", ".", "!", "?", ":", ";"]),+ st.one_of(+ st.builds(+ str.__add__,+ st.text("aé", min_size=1, max_size=6),+ st.sampled_from(["", ",", ".", "!", "?", ":", ";"]),+ ),+ st.sampled_from("世あ"), # a character of Chinese or Japanese: a word),min_size=1,max_size=8,),- separator=st.sampled_from([" ", "\t\n", "\u00a0", "\u2003"]),+ separator=st.sampled_from(+ [" ", "\t\n", "\u3000", "\u2003"]+ ), # a line breaks therehops=st.tuples(st.integers(0, 20), st.integers(0, 60), st.integers(0, 20)),rest=st.integers(0, HOP - 1),loud_rest=st.booleans(),@@ -770,3 +923,45 @@ class TestWords:"One two.","Three four five.",]++ def test_captions_are_the_text_as_it_is_written(self) -> None:+ speech = spelled("这是一个圆!使用 Python 编写,第1章。")+ assert [text for _, _, text in lines(speech)] == [+ "这是一个圆!",+ "使用 Python 编写,第1章。",+ ]+ # a line is 42 columns wide, and a Chinese character takes two+ assert [len(text) for _, _, text in lines(spelled("一" * 50))] == [21, 21, 8]++ def test_a_caption_never_starts_with_a_closing_mark(self) -> None:+ assert [text for _, _, text in lines(spelled("一" * 41 + ",二二二。"))] == [+ "一" * 21,+ "一" * 20 + ",",+ "二二二。",+ ]++ @pytest.mark.parametrize(+ ("text", "captions"),+ [+ ('He said "Hello." She left.', ['He said "Hello."', "She left."]),+ ("「はい」。「いいえ」。", ["「はい」。", "「いいえ」。"]),+ ],+ ids=["English", "Japanese"],+ )+ def test_a_quoted_sentence_ends_its_caption(+ self, text: str, captions: list[str]+ ) -> None:+ assert [caption for _, _, caption in lines(spelled(text))] == captions++ @given(st.text("a b这是。!?\n\t", min_size=1, max_size=120))+ def test_captions_keep_the_text_its_order_and_its_spaces(self, text: str) -> None:+ speech = Speech(np.full(RATE, 0.1, np.float32), text=text, rate=RATE)+ captions = [caption for _, _, caption in lines(speech)]+ assert "".join("".join(c.split()) for c in captions) == "".join(text.split())+ assert all(c in " ".join(text.split()) for c in captions) # spaced as it is+ wide = [+ c+ for c in captions+ if sum(1 + (unicodedata.east_asian_width(x) in "WF") for x in c) > 42+ ]+ assert all(len(_pieces(c)) == 1 for c in wide) # unless it can't break