Skip to content

Personal AI, On Personal Devices

Python

fix: stop TTS falsy defaults overriding backend defaults (#983)

Abideen Ayinde40cba530c4b5
diff --git a/src/openjarvis/tools/text_to_speech.py b/src/openjarvis/tools/text_to_speech.py
index 9cb12ea3..c5133245 100644
--- a/src/openjarvis/tools/text_to_speech.py
+++ b/src/openjarvis/tools/text_to_speech.py
@@ -2,7 +2,9 @@
from __future__ import annotations
+import re
import tempfile
+import uuid
from pathlib import Path
from typing import Any
@@ -78,7 +80,11 @@ class TextToSpeechTool(BaseTool):
_ALIASES = {"openai": "openai_tts"}
backend_key = _ALIASES.get(backend_key, backend_key)
output_dir = params.get("output_dir", "")
- speed = float(params.get("speed", 1.0))
+ # Read speed without a falsy default so "the caller did not set speed"
+ # stays distinct from a real value. Note 0 is a legitimate value and
+ # must not be discarded here.
+ raw_speed = params.get("speed")
+ speed = float(raw_speed) if raw_speed not in (None, "") else None
if not text:
return ToolResult(
@@ -97,7 +103,17 @@ class TextToSpeechTool(BaseTool):
backend_cls = TTSRegistry.get(backend_key)
backend = backend_cls()
- result = backend.synthesize(text, voice_id=voice_id, speed=speed)
+ # Only forward parameters the caller (or config) actually set. Passing
+ # voice_id="" or speed=1.0 unconditionally overrides each backend's own
+ # default value: kokoro's synthesize() defaults voice_id to "af_heart",
+ # and an empty string overrides it so the local backend is asked for a
+ # voice named "" and 404s while paid backends happen to tolerate it.
+ synth_kwargs: dict[str, Any] = {}
+ if voice_id:
+ synth_kwargs["voice_id"] = voice_id
+ if speed is not None:
+ synth_kwargs["speed"] = speed
+ result = backend.synthesize(text, **synth_kwargs)
# Save to file
if output_dir:
@@ -107,7 +123,12 @@ class TextToSpeechTool(BaseTool):
out_dir.mkdir(parents=True, exist_ok=True)
ext = result.format or "mp3"
- audio_path = out_dir / f"digest.{ext}"
+ # Name each file uniquely so several lines saved to one output_dir do
+ # not overwrite each other. A random token (not a timestamp) guarantees
+ # uniqueness even for back-to-back calls with identical text and voice.
+ slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:40] or "line"
+ voice_tag = (result.voice_id or "")[:8] or backend_key
+ audio_path = out_dir / f"{slug}-{voice_tag}-{uuid.uuid4().hex[:8]}.{ext}"
result.save(audio_path)
return ToolResult(
diff --git a/tests/tools/test_text_to_speech.py b/tests/tools/test_text_to_speech.py
index 8adb9f60..6341163c 100644
--- a/tests/tools/test_text_to_speech.py
+++ b/tests/tools/test_text_to_speech.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from pathlib import Path
from unittest.mock import MagicMock, patch
from openjarvis.core.registry import ToolRegistry
@@ -40,9 +41,11 @@ def test_tts_tool_execute(tmp_path):
)
assert result.success is True
- assert "digest.mp3" in result.content
- assert (tmp_path / "digest.mp3").exists()
- assert (tmp_path / "digest.mp3").read_bytes() == b"fake-audio-data"
+ saved = Path(result.content)
+ assert saved.parent == tmp_path
+ assert saved.suffix == ".mp3"
+ assert saved.exists()
+ assert saved.read_bytes() == b"fake-audio-data"
def test_tts_tool_empty_text():
@@ -51,3 +54,105 @@ def test_tts_tool_empty_text():
tool = TextToSpeechTool()
result = tool.execute(text="")
assert result.success is False
+
+
+def _mock_backend(voice_id="af_heart", fmt="wav"):
+ """A registry whose backend echoes the voice_id it was actually called with."""
+ from openjarvis.speech.tts import TTSResult
+
+ backend = MagicMock()
+
+ def _synthesize(text, **kwargs):
+ return TTSResult(
+ audio=b"fake-audio-data",
+ format=fmt,
+ voice_id=kwargs.get("voice_id", voice_id),
+ duration_seconds=1.0,
+ )
+
+ backend.synthesize.side_effect = _synthesize
+ backend_cls = MagicMock(return_value=backend)
+
+ registry = MagicMock()
+ registry.contains.return_value = True
+ registry.get.return_value = backend_cls
+ return registry, backend
+
+
+def test_tts_omits_unset_voice_id_and_speed(tmp_path):
+ """Unset optional params must not be forwarded, so the backend's own
+ defaults win. Forwarding voice_id="" / speed=1.0 is the #971 bug: it makes
+ kokoro (which defaults voice_id to "af_heart") 404 on an empty voice."""
+ from openjarvis.tools.text_to_speech import TextToSpeechTool
+
+ tool = TextToSpeechTool()
+ registry, backend = _mock_backend()
+
+ # Neutralize the config fallback so this test exercises the pure param path
+ # regardless of any speech config on the host.
+ with (
+ patch("openjarvis.tools.text_to_speech.TTSRegistry", registry),
+ patch(
+ "openjarvis.core.config.load_config",
+ side_effect=RuntimeError("no config"),
+ ),
+ ):
+ result = tool.execute(text="hello", backend="kokoro", output_dir=str(tmp_path))
+
+ assert result.success is True
+ call_kwargs = backend.synthesize.call_args.kwargs
+ assert "voice_id" not in call_kwargs
+ assert "speed" not in call_kwargs
+
+
+def test_tts_forwards_explicit_voice_id_and_speed(tmp_path):
+ from openjarvis.tools.text_to_speech import TextToSpeechTool
+
+ tool = TextToSpeechTool()
+ registry, backend = _mock_backend()
+
+ with patch("openjarvis.tools.text_to_speech.TTSRegistry", registry):
+ tool.execute(
+ text="hello",
+ backend="kokoro",
+ voice_id="bf_emma",
+ speed=1.3,
+ output_dir=str(tmp_path),
+ )
+
+ call_kwargs = backend.synthesize.call_args.kwargs
+ assert call_kwargs["voice_id"] == "bf_emma"
+ assert call_kwargs["speed"] == 1.3
+
+
+def test_tts_forwards_zero_speed(tmp_path):
+ """0 is a legitimate value, not "unset", and must be forwarded."""
+ from openjarvis.tools.text_to_speech import TextToSpeechTool
+
+ tool = TextToSpeechTool()
+ registry, backend = _mock_backend()
+
+ with patch("openjarvis.tools.text_to_speech.TTSRegistry", registry):
+ tool.execute(text="hello", backend="kokoro", speed=0, output_dir=str(tmp_path))
+
+ assert backend.synthesize.call_args.kwargs["speed"] == 0.0
+
+
+def test_tts_unique_filenames_no_overwrite(tmp_path):
+ """Two calls with identical text and voice into one dir must not collide."""
+ from openjarvis.tools.text_to_speech import TextToSpeechTool
+
+ tool = TextToSpeechTool()
+ registry, _ = _mock_backend()
+
+ with patch("openjarvis.tools.text_to_speech.TTSRegistry", registry):
+ first = tool.execute(
+ text="same line", backend="kokoro", output_dir=str(tmp_path)
+ )
+ second = tool.execute(
+ text="same line", backend="kokoro", output_dir=str(tmp_path)
+ )
+
+ assert first.content != second.content
+ assert Path(first.content).exists()
+ assert Path(second.content).exists()