Skip to content

A TTS that fits in your CPU (and pocket)

Python

Close the WAV writer when a generation fails or is interrupted (#451)

Toma Stefan Ionescu9c26eb08dcdc
diff --git a/pocket_tts/data/audio.py b/pocket_tts/data/audio.py
index 6fe01c9..11a555c 100644
--- a/pocket_tts/data/audio.py
+++ b/pocket_tts/data/audio.py
@@ -80,7 +80,7 @@ class StreamingWAVWriter:
"""Initialize WAV writer with header."""
# For stdout streaming, we need to handle the unseekable stream case
# The wave module supports unseekable streams since Python 3.4
- # Closed with the underlying stream by the caller's `with f:` block.
+ # Closed by finalize(), which the caller runs in a `finally:` before closing the stream.
self.wave_writer = wave.open(self.output_stream, "wb") # noqa: SIM115
self.wave_writer.setnchannels(1) # Mono
self.wave_writer.setsampwidth(2) # 16-bit
@@ -115,19 +115,21 @@ class StreamingWAVWriter:
def finalize(self):
"""Close the wave writer."""
- self._flush()
-
- # Let's add 200ms of silence to ensure proper playback
- silence_duration_sec = 0.2
- num_silence_samples = int(self.sample_rate * silence_duration_sec)
-
writer = self._writer
- writer.writeframesraw(bytes(num_silence_samples * 2))
+ try:
+ self._flush()
- if not self.is_seekable:
- # do not update the header for unseekable streams
- writer._patchheader = lambda: None # ty: ignore[unresolved-attribute]
- writer.close()
+ # Let's add 200ms of silence to ensure proper playback
+ silence_duration_sec = 0.2
+ num_silence_samples = int(self.sample_rate * silence_duration_sec)
+ writer.writeframesraw(bytes(num_silence_samples * 2))
+ finally:
+ # Even when the stream broke: an unclosed writer patches the header from its
+ # __del__, after the caller closed the stream ("I/O operation on closed file").
+ if not self.is_seekable:
+ # do not update the header for unseekable streams
+ writer._patchheader = lambda: None # ty: ignore[unresolved-attribute]
+ writer.close()
def is_file_like(obj: object) -> TypeIs[BinaryIO]:
@@ -165,10 +167,13 @@ def stream_audio_chunks(
writer = StreamingWAVWriter(f, sample_rate)
writer.write_header(sample_rate)
- for chunk in audio_chunks:
- # Then write to file
+ try:
+ for chunk in audio_chunks:
+ # Then write to file
+ if path is not None:
+ writer.write_pcm_data(chunk)
+ finally:
+ # Also when the generation fails or is interrupted: the header then gives the
+ # length of the audio written so far.
if path is not None:
- writer.write_pcm_data(chunk)
-
- if path is not None:
- writer.finalize()
+ writer.finalize()
diff --git a/tests/test_audio.py b/tests/test_audio.py
index b4b5aad..940d375 100644
--- a/tests/test_audio.py
+++ b/tests/test_audio.py
@@ -1,6 +1,8 @@
import wave
+from collections.abc import Iterator
from pathlib import Path
+import pytest
import torch
from pocket_tts.data.audio import audio_read, stream_audio_chunks
@@ -30,3 +32,20 @@ def test_audio_read_uses_soundfile_for_8_bit_wav(tmp_path: Path):
assert sample_rate == 8000
assert audio.shape == (1, 16)
assert torch.allclose(audio, torch.zeros_like(audio))
+
+
+def test_stream_audio_chunks_closes_the_wav_when_the_generation_fails(tmp_path: Path):
+ output_file = tmp_path / "output.wav"
+
+ def failing_chunks() -> Iterator[torch.Tensor]:
+ yield torch.zeros(24000)
+ yield torch.zeros(24000)
+ raise RuntimeError("generation failed")
+
+ with pytest.raises(RuntimeError, match="generation failed"):
+ stream_audio_chunks(output_file, failing_chunks(), sample_rate=24000)
+
+ # The header gives both chunks plus the 200 ms of silence, not only the first write: the
+ # writer was closed before its file.
+ with wave.open(str(output_file), "rb") as wav_file:
+ assert wav_file.getnframes() == 52800