Skip to content

A TTS that fits in your CPU (and pocket)

Python

Fix audio and state edge cases (#210)

Kushidace03c061fb84
diff --git a/pocket_tts/data/audio.py b/pocket_tts/data/audio.py
index e2d26dc..a5358b4 100644
--- a/pocket_tts/data/audio.py
+++ b/pocket_tts/data/audio.py
@@ -29,18 +29,25 @@ def audio_read(filepath: str | Path) -> tuple[torch.Tensor, int]:
with wave.open(str(filepath), "rb") as wav_file:
sample_rate = wav_file.getframerate()
n_channels = wav_file.getnchannels()
+ sample_width = wav_file.getsampwidth()
+ if sample_width != 2:
+ return _audio_read_with_soundfile(filepath)
raw_data = wav_file.readframes(-1)
samples = np.frombuffer(raw_data, dtype=np.int16).astype(np.float32) / 32768.0
if n_channels > 1:
samples = samples.reshape(-1, n_channels).mean(axis=1)
return torch.from_numpy(samples).unsqueeze(0), sample_rate
- # For non-WAV formats, use soundfile (optional dependency)
+ return _audio_read_with_soundfile(filepath)
+
+
+def _audio_read_with_soundfile(filepath: Path) -> tuple[torch.Tensor, int]:
+ # For non-WAV and non-16-bit WAV formats, use soundfile (optional dependency)
try:
import soundfile as sf
except ImportError as e:
raise ImportError(
- "soundfile is required to read non-WAV audio files. "
+ "soundfile is required to read non-WAV or non-16-bit WAV audio files. "
"Install with: `pip install soundfile` or `uvx --with soundfile`"
) from e
@@ -60,6 +67,7 @@ class StreamingWAVWriter:
self.sample_rate = sample_rate
self.wave_writer = None
self.first_chunk_buffer = []
+ self.is_seekable = _is_seekable(output_stream)
def write_header(self, sample_rate: int):
"""Initialize WAV writer with header."""
@@ -69,7 +77,8 @@ class StreamingWAVWriter:
self.wave_writer.setnchannels(1) # Mono
self.wave_writer.setsampwidth(2) # 16-bit
self.wave_writer.setframerate(sample_rate)
- self.wave_writer.setnframes(1_000_000_000)
+ if not self.is_seekable:
+ self.wave_writer.setnframes(1_000_000_000)
def write_pcm_data(self, audio_chunk: torch.Tensor):
"""Write PCM data using wave module."""
@@ -108,7 +117,8 @@ class StreamingWAVWriter:
if self.wave_writer:
# do not update the header for unseekable streams
- self.wave_writer._patchheader = lambda: None
+ if not self.is_seekable:
+ self.wave_writer._patchheader = lambda: None
self.wave_writer.close()
@@ -117,6 +127,16 @@ def is_file_like(obj):
return all(hasattr(obj, attr) for attr in ["write", "close"])
+def _is_seekable(obj) -> bool:
+ seekable = getattr(obj, "seekable", None)
+ if seekable is not None:
+ try:
+ return bool(seekable())
+ except OSError:
+ return False
+ return all(hasattr(obj, attr) for attr in ("seek", "tell"))
+
+
def stream_audio_chunks(
path: str | Path | None | Any, audio_chunks: Iterator[torch.Tensor], sample_rate: int
):
diff --git a/pocket_tts/models/tts_model.py b/pocket_tts/models/tts_model.py
index 6ad3254..0e752d4 100644
--- a/pocket_tts/models/tts_model.py
+++ b/pocket_tts/models/tts_model.py
@@ -8,6 +8,7 @@ import threading
import time
from functools import lru_cache
from pathlib import Path
+from urllib.parse import urlsplit
import safetensors
import safetensors.torch
@@ -628,7 +629,7 @@ class TTSModel(nn.Module):
)
yield from self._generate_audio_stream_short_text(
model_state=model_state,
- text_to_generate=chunk,
+ text_to_generate=text_to_generate,
frames_after_eos=effective_frames,
copy_state=copy_state,
)
@@ -734,12 +735,13 @@ class TTSModel(nn.Module):
)
except Exception as e:
logger.error(f"Error in autoregressive generation: {e}")
+ # Report the generation error before stopping the decoder. Otherwise
+ # the decoder can publish "done" first and hide the exception.
+ if result_queue is not None:
+ result_queue.put(("error", e))
# Signal decoder to stop by putting None (completion sentinel)
if latents_queue is not None:
latents_queue.put(None)
- # Report error to main thread
- if result_queue is not None:
- result_queue.put(("error", e))
generation_thread = threading.Thread(target=run_generation, daemon=True)
generation_thread.start()
@@ -845,8 +847,8 @@ class TTSModel(nn.Module):
- Processing time is logged for performance monitoring
- The state preserves speaker characteristics for voice cloning
"""
- if isinstance(audio_conditioning, (str, Path)) and str(audio_conditioning).endswith(
- ".safetensors"
+ if isinstance(audio_conditioning, (str, Path)) and _is_safetensors_source(
+ audio_conditioning
):
if isinstance(audio_conditioning, str):
audio_conditioning = download_if_necessary(audio_conditioning)
@@ -1055,6 +1057,15 @@ def export_model_state(model_state: dict[str, dict[str, torch.Tensor]], dest: st
safetensors.torch.save_file(dict_to_store, dest)
+def _is_safetensors_source(source: str | Path) -> bool:
+ source_text = str(source)
+ if source_text.startswith(("http://", "https://")):
+ source_text = urlsplit(source_text).path
+ elif source_text.startswith("hf://"):
+ source_text = source_text.rsplit("@", 1)[0]
+ return source_text.endswith(".safetensors")
+
+
def _import_model_state(
source: str | Path, device: torch.device
) -> dict[str, dict[str, torch.Tensor]]:
diff --git a/pocket_tts/utils/utils.py b/pocket_tts/utils/utils.py
index 41c83db..5bda58e 100644
--- a/pocket_tts/utils/utils.py
+++ b/pocket_tts/utils/utils.py
@@ -3,6 +3,7 @@ import logging
import os
import time
from pathlib import Path
+from urllib.parse import urlparse
import requests
import torch
@@ -95,9 +96,8 @@ class display_execution_time:
def download_if_necessary(file_path: str) -> Path:
if file_path.startswith("http://") or file_path.startswith("https://"):
cache_dir = make_cache_directory()
- cached_file = cache_dir / (
- hashlib.sha256(file_path.encode()).hexdigest() + "." + file_path.split(".")[-1]
- )
+ suffix = Path(urlparse(file_path).path).suffix
+ cached_file = cache_dir / (hashlib.sha256(file_path.encode()).hexdigest() + suffix)
if not cached_file.exists():
response = requests.get(file_path)
response.raise_for_status()
diff --git a/tests/test_audio.py b/tests/test_audio.py
new file mode 100644
index 0000000..b36b898
--- /dev/null
+++ b/tests/test_audio.py
@@ -0,0 +1,31 @@
+import wave
+
+import torch
+
+from pocket_tts.data.audio import audio_read, stream_audio_chunks
+
+
+def test_stream_audio_chunks_patches_seekable_wav_header(tmp_path):
+ output_file = tmp_path / "output.wav"
+ samples = torch.zeros(24000)
+
+ stream_audio_chunks(output_file, iter([samples]), sample_rate=24000)
+
+ with wave.open(str(output_file), "rb") as wav_file:
+ assert wav_file.getframerate() == 24000
+ assert wav_file.getnframes() == 28800
+
+
+def test_audio_read_uses_soundfile_for_8_bit_wav(tmp_path):
+ output_file = tmp_path / "silence_u8.wav"
+ with wave.open(str(output_file), "wb") as wav_file:
+ wav_file.setnchannels(1)
+ wav_file.setsampwidth(1)
+ wav_file.setframerate(8000)
+ wav_file.writeframes(bytes([128] * 16))
+
+ audio, sample_rate = audio_read(output_file)
+
+ assert sample_rate == 8000
+ assert audio.shape == (1, 16)
+ assert torch.allclose(audio, torch.zeros_like(audio))
diff --git a/tests/test_generation_regressions.py b/tests/test_generation_regressions.py
new file mode 100644
index 0000000..ce43227
--- /dev/null
+++ b/tests/test_generation_regressions.py
@@ -0,0 +1,86 @@
+import queue
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+import pocket_tts.models.tts_model as tts_model_module
+from pocket_tts.conditioners.base import TokenizedText
+from pocket_tts.models.tts_model import TTSModel, _is_safetensors_source
+
+
+def test_generate_audio_stream_uses_prepared_chunk_text(monkeypatch):
+ calls = []
+
+ def fake_split_into_best_sentences(
+ tokenizer, text_to_generate, max_tokens, pad_with_spaces_for_short_inputs, remove_semicolons
+ ):
+ assert text_to_generate == "hi"
+ assert pad_with_spaces_for_short_inputs is True
+ return ["hi"]
+
+ def fake_generate_audio_stream_short_text(**kwargs):
+ calls.append(kwargs)
+ yield torch.tensor([0.0])
+
+ monkeypatch.setattr(
+ tts_model_module, "split_into_best_sentences", fake_split_into_best_sentences
+ )
+ model = SimpleNamespace(
+ flow_lm=SimpleNamespace(conditioner=SimpleNamespace(tokenizer=object())),
+ model_recommended_frames_after_eos=None,
+ pad_with_spaces_for_short_inputs=True,
+ remove_semicolons=False,
+ _generate_audio_stream_short_text=fake_generate_audio_stream_short_text,
+ )
+
+ chunks = list(TTSModel.generate_audio_stream(model, {}, "hi"))
+
+ assert len(chunks) == 1
+ assert torch.equal(chunks[0], torch.tensor([0.0]))
+ assert calls[0]["text_to_generate"] == " Hi."
+ assert calls[0]["frames_after_eos"] == 5
+
+
+def test_generate_reports_autoregressive_errors_before_decoder_done():
+ error = RuntimeError("generation failed")
+
+ def raise_generation(*args, **kwargs):
+ raise error
+
+ model = SimpleNamespace(
+ _flow_lm_current_end=lambda model_state: 0,
+ _expand_kv_cache=lambda model_state, sequence_length: None,
+ _run_flow_lm_and_increment_step=lambda model_state, text_tokens: None,
+ _autoregressive_generation=raise_generation,
+ )
+ latents_queue = queue.Queue()
+ result_queue = queue.Queue()
+
+ TTSModel._generate(
+ model,
+ model_state={},
+ prepared=TokenizedText(torch.zeros((1, 1), dtype=torch.long)),
+ max_gen_len=1,
+ frames_after_eos=1,
+ latents_queue=latents_queue,
+ result_queue=result_queue,
+ )
+
+ kind, value = result_queue.get(timeout=1)
+ assert kind == "error"
+ assert value is error
+ assert latents_queue.get(timeout=1) is None
+
+
+ ("source", "expected"),
+ [
+ ("voice.safetensors", True),
+ ("hf://owner/repo/voices/voice.safetensors@abcdef", True),
+ ("https://example.com/voice.safetensors?download=1", True),
+ ("https://example.com/voice.wav?format=safetensors", False),
+ ],
+)
+def test_is_safetensors_source_handles_revisions_and_query_strings(source, expected):
+ assert _is_safetensors_source(source) is expected
diff --git a/tests/test_utils.py b/tests/test_utils.py
new file mode 100644
index 0000000..615e52a
--- /dev/null
+++ b/tests/test_utils.py
@@ -0,0 +1,19 @@
+from pocket_tts.utils import utils
+
+
+def test_download_http_cache_suffix_ignores_query_string(monkeypatch, tmp_path):
+ class Response:
+ content = b"data"
+
+ def raise_for_status(self):
+ pass
+
+ monkeypatch.setattr(utils, "make_cache_directory", lambda: tmp_path)
+ monkeypatch.setattr(utils.requests, "get", lambda url: Response())
+
+ cached_file = utils.download_if_necessary("https://example.com/audio.wav?download=true")
+
+ assert cached_file.parent == tmp_path
+ assert cached_file.suffix == ".wav"
+ assert "?" not in cached_file.name
+ assert cached_file.read_bytes() == b"data"