Skip to content

A research project focused on developing a lightweight neural voice cloning and speech synthesis system, optimized for deployment on edge devices.

Python

Add pause-trimmed length estimation mechanic

IgorSwat18b4ba8d7589
diff --git a/docs/usage.md b/docs/usage.md
index 2693f4d..0aa58b7 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -66,12 +66,16 @@ takes = [tts.generate(text, voice, language="en", seed=s) for s in range(4)] #
## Control the length
-The length is estimated from the text and the reference's speaking rate:
+The length is estimated from the text and the reference's speaking rate. The rate counts only the time the
+reference spends speaking: its silent edges and any pause over 0.2 s are left out, so a recording with long pauses
+doesn't make the takes slow. The recording itself is used whole.
+`pace="recording"` estimates from the whole recording instead, pauses included, as earlier versions did.
```python
audio = tts.generate(text, voice, language="en", speed=1.25) # length = estimate / 1.25 = 0.8x: faster speech
audio = tts.generate(text, voice, language="en", speed=0.9) # length = estimate / 0.9 = 1.11x: slower speech
audio = tts.generate(text, voice, language="en", duration=4.0) # length = 4 s, whatever the estimate
+audio = tts.generate(text, voice, language="en", speed=1.0, pace="recording") # the rate of the whole recording, pauses included
```
## Long texts
diff --git a/reverb_tts/audio.py b/reverb_tts/audio.py
index 50d2150..bed8072 100644
--- a/reverb_tts/audio.py
+++ b/reverb_tts/audio.py
@@ -1,5 +1,6 @@
"""
-Reference audio in, generated audio out: loading and resampling a recording, and trimming a take's silent edges.
+Reference audio in, generated audio out: loading and resampling a recording, measuring how long its speech lasts, and
+trimming a take's silent edges.
"""
from pathlib import Path
@@ -16,6 +17,8 @@ RESAMPLE = {"lowpass_filter_width": 64, "rolloff": 0.9475937167399596, "resampli
AudioInput = Union[str, Path, np.ndarray, torch.Tensor]
+SILENCE_DB = -50.0 # a 10 ms window quieter than this (dBFS) is silence
+
def load_audio(audio: AudioInput, sample_rate: Optional[int], target_rate: int) -> torch.Tensor:
"""
@@ -41,17 +44,15 @@ def load_audio(audio: AudioInput, sample_rate: Optional[int], target_rate: int)
def trim_silence(audio: np.ndarray, sample_rate: int, keep: float = 0.1) -> np.ndarray:
"""
- Cuts leading and trailing silence (10 ms windows under -50 dBFS), keeping `keep` seconds of it on each side.
+ Cuts leading and trailing silence (10 ms windows under SILENCE_DB), keeping `keep` seconds of it on each side.
"""
window = sample_rate // 100
- count = len(audio) // window
- if count == 0:
- return audio
- level = 20 * np.log10(np.sqrt((audio[: count * window].reshape(count, window) ** 2).mean(1)) + 1e-10)
- loud = np.flatnonzero(level >= -50)
+ level = _levels(audio, window)
+ loud = np.flatnonzero(level >= SILENCE_DB)
if len(loud) == 0:
return audio
+ count = len(level)
sounds = np.split(loud, np.flatnonzero(np.diff(loud) > 20) + 1) # separated by over 200 ms of silence
# A sound of at most 120 ms, alone at either edge, is a codec burst rather than speech.
if len(sounds) > 1 and len(sounds[0]) <= 12:
@@ -60,3 +61,35 @@ def trim_silence(audio: np.ndarray, sample_rate: int, keep: float = 0.1) -> np.n
sounds = sounds[:-1]
margin = round(keep * 100)
return audio[max(sounds[0][0] - margin, 0) * window: min(sounds[-1][-1] + 1 + margin, count) * window]
+
+
+def speech_length(audio: np.ndarray, sample_rate: int, max_pause: float = 0.2, lead: float = 0.1,
+ trail: float = 0.2) -> float:
+ """
+ Seconds of a reference recording that set the speaker's pace: the recording without its silent edges (keeping
+ `lead` and `trail` seconds) and with every pause inside the speech counted as at most `max_pause` seconds.
+ """
+
+ window = sample_rate // 100
+ count = len(audio) // window
+ if count == 0:
+ return len(audio) / sample_rate
+ x = np.asarray(audio[: count * window], dtype=np.float64)
+ level = _levels(x * 0.1 / max(float(np.sqrt(np.mean(x ** 2))), 1e-8), window)
+ loud = np.flatnonzero(level >= SILENCE_DB)
+ if len(loud) == 0:
+ return len(audio) / sample_rate
+ first, last = int(loud[0]), int(loud[-1])
+ gaps = np.diff(loud) - 1 # silent windows between consecutive loud ones
+ kept = len(loud) + int(np.minimum(gaps, round(max_pause * 100)).sum())
+ edges = min(first, round(lead * 100)) + min(count - 1 - last, round(trail * 100))
+
+ return (kept + edges) / 100
+
+
+def _levels(audio: np.ndarray, window: int) -> np.ndarray:
+ """The level of every whole `window` of samples, in dBFS."""
+
+ count = len(audio) // window
+
+ return 20 * np.log10(np.sqrt((audio[: count * window].reshape(count, window) ** 2).mean(1)) + 1e-10)
diff --git a/reverb_tts/tts.py b/reverb_tts/tts.py
index 89def40..a89cc6b 100644
--- a/reverb_tts/tts.py
+++ b/reverb_tts/tts.py
@@ -11,14 +11,14 @@ import logging
import random
from dataclasses import dataclass, replace
from pathlib import Path
-from typing import Any, List, Optional, Sequence, Tuple, TypeVar, Union
+from typing import Any, List, Literal, Optional, Sequence, Tuple, TypeVar, Union
import numpy as np
import torch
from huggingface_hub import hf_hub_download, list_repo_files, snapshot_download
from transformers import HiggsAudioV2TokenizerModel, Qwen2Tokenizer
-from reverb_tts.audio import AudioInput, load_audio, trim_silence
+from reverb_tts.audio import AudioInput, load_audio, speech_length, trim_silence
from reverb_tts.model import CODEBOOKS, MASK, Network
from reverb_tts.sampler import Batch, Prompt, SamplerConfig, sample
from reverb_tts.text import check_language, estimate_frames, prepare_text, split_text
@@ -33,6 +33,7 @@ FRAME_RATE = 25 # codec frames per second
LONGEST, PIECE = 30.0, 15.0 # seconds: a text estimated longer than LONGEST is spoken in pieces of about PIECE
END_CUT = 0.2 # seconds cut from every take's end, where the codec can leave a short burst of noise
LONG_REFERENCE = 15.0 # seconds: references longer than this are known to hurt
+PACES = ("speech", "recording") # what the length estimate takes as the reference's length: see generate()
T = TypeVar("T")
@@ -41,38 +42,56 @@ T = TypeVar("T")
class Voice:
"""
A reference voice: the recording's codec codes [8, frames] and its transcript, prepared for the model.
+ `speech_frames` is how many of those frames the speaker spends speaking (see `audio.speech_length`).
"""
codes: torch.Tensor
text: str
language: str
+ speech_frames: Optional[int] = None
@property
def duration(self) -> float:
return self.codes.size(1) / FRAME_RATE
+ @property
+ def pace_frames(self) -> int:
+ """
+ The reference length the target's length is estimated from: the speech frames, at most every frame.
+ """
+
+ frames = self.codes.size(1)
+ return frames if self.speech_frames is None else max(1, min(self.speech_frames, frames))
+
def save(self, path: Union[str, Path]) -> None:
"""
Writes the voice to an .npz file, so the recording needn't be encoded again.
"""
- np.savez(path, codes=self.codes.numpy().astype(np.int16), text=self.text, language=self.language)
+ extra = {} if self.speech_frames is None else {"speech_frames": self.speech_frames}
+ np.savez(path, codes=self.codes.numpy().astype(np.int16), text=self.text, language=self.language, **extra)
@classmethod
def load(cls, path: Union[str, Path]) -> "Voice":
"""
Reads a voice from an .npz file written by `save`, or from a preset .json file: {codes, transcript, language},
- the codes as 8 x frames integers, row-major, and the transcript already prepared.
+ the codes as 8 x frames integers, row-major, and the transcript already prepared, with an optional
+ speech_frames.
"""
if Path(path).suffix != ".json":
data = np.load(path)
- return cls(torch.from_numpy(data["codes"].astype(np.int64)), str(data["text"]), str(data["language"]))
+ speech = int(data["speech_frames"]) if "speech_frames" in data.files else None
+ return cls(torch.from_numpy(data["codes"].astype(np.int64)), str(data["text"]), str(data["language"]),
+ speech)
data = json.loads(Path(path).read_text())
codes = torch.tensor(data["codes"], dtype=torch.long)
if codes.numel() == 0 or codes.numel() % CODEBOOKS or not 0 <= int(codes.min()) <= int(codes.max()) < MASK:
raise ValueError(f"{path}: expected codes as {CODEBOOKS} x frames integers below {MASK}")
- return cls(codes.view(CODEBOOKS, -1), data["transcript"], check_language(data["language"]))
+ speech = data.get("speech_frames")
+ if speech is not None and (not isinstance(speech, int) or speech < 1):
+ raise ValueError(f"{path}: expected speech_frames as a positive integer")
+ return cls(codes.view(CODEBOOKS, -1), data["transcript"], check_language(data["language"]), speech)
class TTS:
@@ -171,7 +190,9 @@ class TTS:
if codes.size(1) / FRAME_RATE > LONG_REFERENCE:
logger.warning("the reference is %.1f s long; references over %.0f s tend to make worse takes",
codes.size(1) / FRAME_RATE, LONG_REFERENCE)
- return Voice(codes, prepare_text(text, language) if prepare else text, language)
+ # The recording stays whole; only the speaking time is measured, for the length estimate.
+ speech = round(speech_length(wav.numpy(), self.sample_rate) * FRAME_RATE)
+ return Voice(codes, prepare_text(text, language) if prepare else text, language, speech)
@torch.inference_mode()
def generate(
@@ -183,6 +204,7 @@ class TTS:
seed: Optional[int] = None,
speed: float = 1.0,
duration: Optional[float] = None,
+ pace: Literal["speech", "recording"] = "speech",
prepare: bool = True,
trim: bool = True,
sampler: Optional[SamplerConfig] = None,
@@ -195,6 +217,8 @@ class TTS:
- language: the text's language, one of LANGUAGES.
- seed: the take's seed; consecutive seeds go to the pieces of a list or a long text. None draws one.
- speed: a factor on the estimated length. duration: the length in seconds, in place of the estimate.
+ - pace: the reference length the estimate follows. "speech" counts only the time the reference spends speaking
+ (`Voice.speech_frames`: no silent edges, pauses capped at 0.2 s); "recording" counts the whole recording.
- prepare: verbalize the text first (turn off for text that already is).
- trim: cut the take's silent edges.
- sampler, overrides: sampler settings for this call, e.g. steps=12 or remasking=False.
@@ -207,13 +231,15 @@ class TTS:
voices, languages = _broadcast(voice, len(texts), "voice"), _broadcast(language, len(texts), "language")
config = replace(sampler or self.sampler, **overrides)
base = random.randrange(2**31) if seed is None else seed
+ if pace not in PACES:
+ raise ValueError(f"unknown pace {pace!r}, expected one of: {', '.join(PACES)}")
prompts: List[Prompt] = []
owners: List[int] = []
for i, (words, speaker, lang) in enumerate(zip(texts, voices, languages)):
check_language(lang)
words = prepare_text(words, lang) if prepare else words
- reference_frames = speaker.codes.size(1)
+ reference_frames = speaker.pace_frames if pace == "speech" else speaker.codes.size(1)
if duration is not None:
pieces = [(words, max(1, round(duration * FRAME_RATE)))]
else:
diff --git a/tests/test_audio.py b/tests/test_audio.py
index 826bb87..71e4ec7 100644
--- a/tests/test_audio.py
+++ b/tests/test_audio.py
@@ -2,7 +2,7 @@ import numpy as np
import pytest
import torch
-from reverb_tts.audio import load_audio, trim_silence
+from reverb_tts.audio import load_audio, speech_length, trim_silence
RATE = 24000
@@ -29,3 +29,33 @@ def test_load_audio_mixes_down_and_resamples() -> None:
def test_load_audio_needs_the_rate_of_raw_samples() -> None:
with pytest.raises(ValueError, match="sample_rate"):
load_audio(np.zeros(100, np.float32), None, RATE)
+
+
+def tone(seconds: float, amplitude: float = 0.3) -> np.ndarray:
+ return amplitude * np.sin(2 * np.pi * 220 * np.arange(round(seconds * RATE)) / RATE).astype(np.float32)
+
+
+def quiet(seconds: float) -> np.ndarray:
+ return np.zeros(round(seconds * RATE), np.float32)
+
+
+def test_speech_length_keeps_short_edges_and_caps_pauses() -> None:
+ # 1 s of edge silence on each side, a 1.5 s and a 0.1 s pause between 1 s sounds.
+ audio = np.concatenate([quiet(1), tone(1), quiet(1.5), tone(1), quiet(0.1), tone(1), quiet(1)])
+ # 3 s of sound, the long pause counted as 0.2 s, the short one whole, and 0.1 s + 0.2 s of the edges.
+ assert speech_length(audio, RATE) == pytest.approx(3 + 0.2 + 0.1 + 0.1 + 0.2, abs=0.02)
+
+
+def test_speech_length_of_clean_speech_is_its_length() -> None:
+ assert speech_length(tone(2), RATE) == pytest.approx(2, abs=0.01)
+
+
+def test_speech_length_levels_a_quiet_recording_first() -> None:
+ # The whole recording sits under -50 dBFS, yet its sounds are told from its silence.
+ audio = np.concatenate([tone(1, 1e-4), quiet(2), tone(1, 1e-4)])
+ assert speech_length(audio, RATE) == pytest.approx(2.2, abs=0.02)
+
+
+def test_speech_length_counts_a_silent_or_tiny_recording_whole() -> None:
+ assert speech_length(quiet(2), RATE) == 2
+ assert speech_length(np.zeros(10, np.float32), RATE) == 10 / RATE
diff --git a/tests/test_tts.py b/tests/test_tts.py
index b2f05b4..487c6c3 100644
--- a/tests/test_tts.py
+++ b/tests/test_tts.py
@@ -1,6 +1,6 @@
import json
from pathlib import Path
-from typing import List
+from typing import Any, List
import numpy as np
import pytest
@@ -25,13 +25,57 @@ def test_a_voice_holds_codes_and_a_prepared_transcript(voice: Voice) -> None:
def test_a_voice_survives_a_round_trip_to_disk(voice: Voice, tmp_path: Path) -> None:
+ voice = Voice(voice.codes, voice.text, voice.language, speech_frames=30)
voice.save(tmp_path / "voice.npz")
loaded = Voice.load(tmp_path / "voice.npz")
assert torch.equal(loaded.codes, voice.codes) and (loaded.text, loaded.language) == (voice.text, voice.language)
+ assert loaded.speech_frames == 30
-def write_preset(path: Path, codes: List[int], language: str = "en") -> Path:
- path.write_text(json.dumps({"name": path.stem, "language": language, "transcript": "Hello there.", "codes": codes}))
+def test_a_voice_saved_without_speech_frames_counts_every_frame(voice: Voice, tmp_path: Path) -> None:
+ np.savez(tmp_path / "old.npz", codes=voice.codes.numpy().astype(np.int16), text=voice.text, language="en")
+ loaded = Voice.load(tmp_path / "old.npz")
+ assert loaded.speech_frames is None and loaded.pace_frames == 50
+
+
+def test_a_voice_measures_its_speech_and_keeps_the_recording_whole(tts: TTS) -> None:
+ sound = 0.3 * np.sin(2 * np.pi * 220 * np.arange(RATE) / RATE).astype(np.float32)
+ silence = np.zeros(RATE, np.float32)
+ voice = tts.voice(np.concatenate([silence, sound, silence, sound, silence]), "Hello there.", "en", sample_rate=RATE)
+ assert voice.codes.size(1) == 125 # 5 s, nothing cut
+ assert voice.speech_frames == pytest.approx(25 * 2.5, abs=1) # 2 s of sound, a 0.2 s pause, 0.1 + 0.2 s of edges
+ assert voice.pace_frames == voice.speech_frames
+
+
+def test_the_length_estimate_follows_the_speech_frames(tts: TTS, voice: Voice,
+ monkeypatch: pytest.MonkeyPatch) -> None:
+ sampled: List[Prompt] = []
+ monkeypatch.setattr(TTS, "_sample", lambda self, prompts, config: sampled.extend(prompts) or
+ [torch.zeros(8, p.frames, dtype=torch.long) for p in prompts])
+ text = "A sentence long enough for a linear estimate, spoken in this voice."
+ tts.generate(text, voice, "en", seed=0)
+ tts.generate(text, Voice(voice.codes, voice.text, voice.language, speech_frames=25), "en", seed=0)
+ assert sampled[1].frames == pytest.approx(sampled[0].frames / 2, abs=1)
+
+
+def test_pace_recording_estimates_from_the_whole_recording(tts: TTS, voice: Voice,
+ monkeypatch: pytest.MonkeyPatch) -> None:
+ sampled: List[Prompt] = []
+ monkeypatch.setattr(TTS, "_sample", lambda self, prompts, config: sampled.extend(prompts) or
+ [torch.zeros(8, p.frames, dtype=torch.long) for p in prompts])
+ text = "A sentence long enough for a linear estimate, spoken in this voice."
+ paused = Voice(voice.codes, voice.text, voice.language, speech_frames=25)
+ tts.generate(text, voice, "en", seed=0)
+ tts.generate(text, paused, "en", seed=0, pace="recording")
+ tts.generate(text, paused, "en", seed=0, pace="speech")
+ assert sampled[1].frames == sampled[0].frames != sampled[2].frames
+ with pytest.raises(ValueError, match="pace"):
+ tts.generate(text, voice, "en", seed=0, pace="audio")
+
+
+def write_preset(path: Path, codes: List[int], language: str = "en", **extra: Any) -> Path:
+ path.write_text(json.dumps({"name": path.stem, "language": language, "transcript": "Hello there.", "codes": codes,
+ **extra}))
return path
@@ -39,6 +83,14 @@ def test_a_preset_file_loads_as_a_voice(tmp_path: Path) -> None:
loaded = Voice.load(write_preset(tmp_path / "anna.json", list(range(8 * 5))))
assert loaded.codes.shape == (8, 5) and loaded.codes[1, 0] == 5 # row-major: one codebook per row
assert (loaded.text, loaded.language) == ("Hello there.", "en")
+ assert loaded.speech_frames is None and loaded.pace_frames == 5
+
+
+def test_a_preset_file_carries_its_speech_frames(tmp_path: Path) -> None:
+ assert Voice.load(write_preset(tmp_path / "anna.json", list(range(8 * 5)), speech_frames=4)).pace_frames == 4
+ for bad in (0, 2.5, "4"):
+ with pytest.raises(ValueError, match="speech_frames"):
+ Voice.load(write_preset(tmp_path / "bad.json", list(range(8 * 5)), speech_frames=bad))
@pytest.mark.parametrize("codes, language", [(list(range(9)), "en"), ([1024] * 8, "en"), ([0] * 8, "xx")])