feat(tts): change the speech speed without a restart and keep fast speech clear
MeloTTS's own speed shortens every sound and slurred fast speech (Whisper large-v3 on five Korean sentences, three renders each: 5.5% character errors at 1.5 and 20% at 2.0, against 1.4% at 1.0). The MeloTTS child now speaks at most at its natural pace and makes faster speech with a WSOLA time stretch that keeps the pitch (1.9% at 1.5, 2.2% at 2.0, about 15 ms per 4 s of speech). A voice.tts.speed saved while the services run goes to the worker at once (new tts_speed message) and applies from the next sentence; the client sends it again whenever the worker connects again. Version 0.1.4. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
89
tests/test_voice_worker_melo_speed.py
Normal file
89
tests/test_voice_worker_melo_speed.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""How the MeloTTS child speeds speech up: the model never speaks faster than MODEL_SPEED_MAX (faster
|
||||
slurs), and the rest is a time stretch that keeps the pitch. And the engine sends its current speed
|
||||
with every sentence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import textwrap
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from voice_worker import melo_child, tts_melo
|
||||
from voice_worker.melo_child import MODEL_SPEED_MAX, split_speed, stretch
|
||||
|
||||
SR = 44100
|
||||
|
||||
|
||||
def sine(hz: float, seconds: float) -> np.ndarray:
|
||||
return np.sin(2 * np.pi * hz * np.arange(int(SR * seconds)) / SR)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_model_never_speaks_faster_than_its_limit_and_the_stretch_does_the_rest():
|
||||
for speed in (0.5, 0.8, MODEL_SPEED_MAX):
|
||||
assert split_speed(speed) == (speed, 1.0)
|
||||
for speed in (1.5, 1.75, 2.0):
|
||||
model, factor = split_speed(speed)
|
||||
assert model == MODEL_SPEED_MAX and factor > 1.0
|
||||
assert model * factor == pytest.approx(speed)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_stretch_shortens_by_the_factor_and_keeps_the_pitch():
|
||||
x = sine(220.0, 2.0)
|
||||
for factor in (1.2, 1.6, 2.0):
|
||||
y = stretch(x, factor, SR)
|
||||
assert len(y) == pytest.approx(len(x) / factor, abs=2)
|
||||
spectrum = np.abs(np.fft.rfft(y * np.hanning(len(y))))
|
||||
assert np.argmax(spectrum) * SR / len(y) == pytest.approx(220.0, abs=2.0)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_stretched_sound_stays_even_without_dips_or_clicks():
|
||||
# Badly joined pieces cancel each other (the level dips) or jump (clicks).
|
||||
x = 0.5 * sine(180.0, 1.5)
|
||||
y = stretch(x, 1.6, SR)
|
||||
middle = y[SR // 10: -SR // 10]
|
||||
frame = SR // 100
|
||||
levels = [np.sqrt(np.mean(middle[i:i + frame] ** 2)) for i in range(0, len(middle) - frame, frame)]
|
||||
assert min(levels) > 0.5 / np.sqrt(2) * 0.9 and max(levels) < 0.5 / np.sqrt(2) * 1.1
|
||||
assert np.max(np.abs(np.diff(middle))) < 2 * np.pi * 180.0 / SR * 0.5 * 1.5
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_no_stretch_leaves_the_sound_as_it_is():
|
||||
x = sine(300.0, 0.5)
|
||||
assert np.array_equal(stretch(x, 1.0, SR), x)
|
||||
assert len(stretch(np.zeros(0), 1.5, SR)) == 0
|
||||
|
||||
|
||||
FAKE_CHILD = textwrap.dedent("""
|
||||
import json, struct, sys
|
||||
out = sys.stdout.buffer
|
||||
def reply(h, payload=b""):
|
||||
raw = json.dumps(h).encode()
|
||||
out.write(struct.pack("<I", len(raw)) + raw + payload); out.flush()
|
||||
reply({"ready": True, "rate": 44100})
|
||||
for line in sys.stdin:
|
||||
req = json.loads(line)
|
||||
n = int(req["speed"] * 100)
|
||||
reply({"ok": True, "samples": n}, b"\\x00\\x00" * n)
|
||||
""")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_engine_sends_its_current_speed_with_every_sentence(tmp_path, monkeypatch):
|
||||
child = tmp_path / "fake_child.py"
|
||||
child.write_text(FAKE_CHILD)
|
||||
monkeypatch.setattr(tts_melo, "CHILD", str(child))
|
||||
engine = tts_melo.MeloEngine(sys.executable, "cpu", 1.5)
|
||||
try:
|
||||
assert len(engine.synthesize("하나", 48000)) == 150
|
||||
engine.speed = 1.8
|
||||
assert len(engine.synthesize("둘", 48000)) == 180
|
||||
finally:
|
||||
engine.close()
|
||||
@@ -43,6 +43,8 @@ class FakeTts:
|
||||
def __init__(self, delay: float = 0.0):
|
||||
self.delay = delay
|
||||
self.texts = []
|
||||
self.speed = 1.5
|
||||
self.speeds = []
|
||||
|
||||
def synthesize(self, text, rate):
|
||||
if self.delay:
|
||||
@@ -50,6 +52,7 @@ class FakeTts:
|
||||
if "FAIL" in text:
|
||||
raise RuntimeError("engine broke")
|
||||
self.texts.append(text)
|
||||
self.speeds.append(self.speed)
|
||||
return np.full(len(text) * 10, 1000, dtype=np.int16)
|
||||
|
||||
|
||||
@@ -272,6 +275,29 @@ def test_a_failing_sentence_ends_the_request_as_failed():
|
||||
assert tts.texts == ["첫 문장입니다."]
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_new_speech_speed_applies_to_the_sentences_made_after_it():
|
||||
tts = FakeTts()
|
||||
|
||||
async def body(url):
|
||||
async with connect(url) as ws:
|
||||
await hello(ws)
|
||||
await ws.send(json.dumps({"type": "tts", "id": "a", "text": "보통 속도 문장이에요."}))
|
||||
await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "tts_done")
|
||||
await ws.send(json.dumps({"type": "tts_speed", "speed": 1.8}))
|
||||
out = []
|
||||
for bad in (2.5, 0.2, "fast", True):
|
||||
await ws.send(json.dumps({"type": "tts_speed", "speed": bad}))
|
||||
out.append(json.loads(await ws.recv()))
|
||||
await ws.send(json.dumps({"type": "tts", "id": "b", "text": "빨라진 문장이에요."}))
|
||||
await recv_until(ws, lambda m: isinstance(m, dict) and m.get("type") == "tts_done")
|
||||
return out
|
||||
|
||||
errors = asyncio.run(with_worker(body, tts=tts))
|
||||
assert [e["code"] for e in errors] == ["bad_message"] * 4
|
||||
assert tts.speeds == [1.5, 1.8], "a refused speed leaves the last good one"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_tts_without_an_engine_reports_unavailable():
|
||||
async def body(url):
|
||||
|
||||
Reference in New Issue
Block a user