Skip to content

Self-hosted AI workspace.

Python

STT: clean temp audio files on transcription failure

Tatlatat2942b377f836
diff --git a/services/stt/stt_service.py b/services/stt/stt_service.py
index 0587128e6..25faf5e5a 100644
--- a/services/stt/stt_service.py
+++ b/services/stt/stt_service.py
@@ -91,6 +91,7 @@ class STTService:
model = self._get_whisper()
if not model:
return None
+ tmp_path = None
try:
# Write to temp file (faster-whisper needs a file path or file-like)
with tempfile.NamedTemporaryFile(suffix=".webm", delete=False) as tmp:
@@ -104,14 +105,14 @@ class STTService:
segments, info = model.transcribe(tmp_path, **kwargs)
text = " ".join(seg.text.strip() for seg in segments)
- # Cleanup
- Path(tmp_path).unlink(missing_ok=True)
-
logger.info(f"Local STT: {len(text)} chars, lang={info.language}, prob={info.language_probability:.2f}")
return text
except Exception as e:
logger.error(f"Local STT transcription failed: {e}", exc_info=True)
return None
+ finally:
+ if tmp_path:
+ Path(tmp_path).unlink(missing_ok=True)
# ── API endpoint ──
diff --git a/tests/test_stt_leak.py b/tests/test_stt_leak.py
new file mode 100644
index 000000000..ff752badd
--- /dev/null
+++ b/tests/test_stt_leak.py
@@ -0,0 +1,30 @@
+import os
+import tempfile
+from services.stt.stt_service import STTService
+
+
+def test_stt_local_transcribe_leak_on_error():
+ service = STTService()
+
+ class MockWhisper:
+ def transcribe(self, *args, **kwargs):
+ raise ValueError("Simulated transcribe error")
+
+ service._get_whisper = lambda: MockWhisper()
+
+ # Track WebM files in the temp directory before running transcription
+ temp_dir = tempfile.gettempdir()
+ webm_before = {f for f in os.listdir(temp_dir) if f.endswith(".webm")}
+
+ # Run transcription, which will raise ValueError internally
+ result = service._transcribe_local(b"dummy_audio_data")
+
+ # Track WebM files in the temp directory after running transcription
+ webm_after = {f for f in os.listdir(temp_dir) if f.endswith(".webm")}
+
+ # Assert that it returned None (failure)
+ assert result is None
+
+ # Assert that no new temp files were leaked
+ leaked = webm_after - webm_before
+ assert len(leaked) == 0, f"Leaked files: {leaked}"