Skip to content

The agent that grows with you

refactor(tools): squeeze in-body and banner blank lines in tts modules

Tekniumdf4547570a8e
diff --git a/tools/tts_tool.py b/tools/tts_tool.py
index a03962924dd..9b82f51632a 100644
--- a/tools/tts_tool.py
+++ b/tools/tts_tool.py
@@ -88,7 +88,6 @@ from tools.tts_tool_lifecycle import ( # noqa: F401 — historical names re-exp
# --- Lazy SDK importers -- providers import only when used (headless boxes lack PortAudio etc.) ---
-
def _sdk_importer(module: str, attr: Optional[str] = None, feature: Optional[str] = None) -> Callable[[], Any]:
"""Lazy SDK importer: returns ``module`` (or ``module.attr``), raising ImportError when absent.
@@ -274,7 +273,6 @@ def _finalize_voice_delivery(
return file_str, want_opus and file_str.endswith(".ogg")
else:
return file_str, False
-
if not opted_in:
return file_str, False
if not file_str.endswith(".ogg"):
@@ -283,7 +281,6 @@ def _finalize_voice_delivery(
# --- Main tool function ---
-
def _apply_call_overrides(tts_config: Dict[str, Any], speed: Optional[float], provider: Optional[str]):
"""Apply per-call ``speed`` (clamped, on a shallow copy) and resolve the provider name."""
if speed is not None:
@@ -368,7 +365,6 @@ def _text_to_speech_single(
if error:
return error
_synthesize_builtin(provider, text, file_str, tts_config, instructions)
-
if not os.path.exists(file_str) or os.path.getsize(file_str) == 0:
return _error_json(f"TTS generation produced no output (provider: {provider})")
@@ -433,14 +429,12 @@ def text_to_speech_tool(
if not text or not text.strip():
return tool_error("Text is required", success=False)
try: # shared cleaner: markdown, emoji, think blocks, verifier footer, units, newlines
-
from tools.tts_text_normalize import prepare_spoken_text
text = prepare_spoken_text(text, max_chars=None)
except Exception:
text = text.strip()
if not text:
return tool_error("Text is empty after TTS cleanup", success=False)
-
tts_config, provider = _apply_call_overrides(_load_tts_config(), speed, provider)
command_provider_config = _resolve_command_provider_config(provider, tts_config)
max_len = _resolve_max_text_length(provider, tts_config)
@@ -450,13 +444,11 @@ def text_to_speech_tool(
if len(chunks) > 1:
logger.info("TTS text for provider %s split into %d chunks (input=%d chars, cap=%d)",
provider, len(chunks), len(text), max_len)
-
platform, want_opus = _session_platform()
delivery_profile = _resolve_audio_delivery_profile(platform, tts_config)
base_path, error = _resolve_output_base(output_path, provider, command_provider_config, want_opus)
if error:
return error
-
generated_artifacts: set[str] = set()
final_paths: List[str] = []
try:
@@ -494,7 +486,6 @@ def text_to_speech_tool(
# --- check_fn ---
-
def _minimax_requirements() -> bool:
try:
_resolve_minimax_tts_runtime(_load_tts_config())
diff --git a/tools/tts_tool_delivery.py b/tools/tts_tool_delivery.py
index a28d1ea3178..0abba118ecd 100644
--- a/tools/tts_tool_delivery.py
+++ b/tools/tts_tool_delivery.py
@@ -32,7 +32,6 @@ logger = logging.getLogger("tools.tts_tool")
def _origin():
"""``tools.tts_tool``, resolved per call so seams monkeypatched there still apply."""
from tools import tts_tool
-
return tts_tool
@@ -115,7 +114,6 @@ _OPUS_VOICE_ARGS = [
# --- Text chunking and delivery profiles ---
-
@dataclass(frozen=True)
class AudioDeliveryProfile:
"""Destination-platform constraints for generated TTS audio."""
@@ -145,7 +143,6 @@ def _resolve_audio_delivery_profile(
overrides = profiles.get(key, {}) if isinstance(profiles, dict) else {}
if isinstance(overrides, dict):
defaults.update({k: v for k, v in overrides.items() if v is not None})
-
max_file_bytes = _positive_int(defaults.get("max_file_bytes")) or _PLATFORM_AUDIO_DEFAULTS["default"]["max_file_bytes"]
safety_ratio = defaults.get("safety_ratio", 0.85)
if isinstance(safety_ratio, bool) or not isinstance(safety_ratio, (int, float)) or not 0 < safety_ratio <= 1:
@@ -191,7 +188,6 @@ def _split_text_for_tts(text: str, max_chars: int) -> List[str]:
return []
if len(normalized) <= max_chars:
return [normalized]
-
expanded: List[str] = []
for sentence in re.split(r"(?<=[.!?;:,])\s+", normalized):
sentence = sentence.strip()
@@ -225,7 +221,6 @@ def _pack_audio_files_for_delivery(audio_paths: List[str], profile: AudioDeliver
# --- ffmpeg encoding helpers ---
-
def _ffmpeg_run(
ffmpeg: str, args: List[str], *, timeout: int = 30, check: bool = False, capture: bool = True,
) -> subprocess.CompletedProcess:
@@ -377,7 +372,6 @@ def _repair_ogg_container(file_str: str) -> str:
# --- Long-form audio combination and delivery packing ---
-
def _concat_audio_files(audio_paths: List[str], output_path: str, *, voice_compatible: bool = False) -> Optional[str]:
"""Combine independently encoded chunks with ffmpeg (never byte-joined). OGG/Opus is always
re-encoded (even without voice opt-in); matching MP3 chunks keep their frames (``-c:a copy``).
@@ -455,7 +449,6 @@ def _build_audio_delivery_files(
_remove_quietly(combined)
midpoint = max(1, len(group) // 2)
return emit(group[:midpoint]) + emit(group[midpoint:])
-
groups = _pack_audio_files_for_delivery(audio_paths, profile)
packed = [path for group in groups for path in emit(group)]
final_paths: List[str] = []
diff --git a/tools/tts_tool_lifecycle.py b/tools/tts_tool_lifecycle.py
index da65e96b9ef..4b93e9f4b93 100644
--- a/tools/tts_tool_lifecycle.py
+++ b/tools/tts_tool_lifecycle.py
@@ -65,7 +65,6 @@ def _signal_user_tts_provider(name: str, tts_config: Dict[str, Any], hook: str)
env_passthrough=_command_provider_env_passthrough(cfg))
except Exception as exc: # noqa: BLE001 — best-effort hook
logger.debug("[TTS] %s_command for %s failed: %s", hook, name, exc)
-
threading.Thread(target=_run, name=f"tts-{hook}-{name}", daemon=True).start()
return hook
plugin_provider = _lookup_plugin_provider(name)
@@ -87,7 +86,6 @@ def warm_tts_provider(tts_config: Optional[Dict[str, Any]] = None, provider: Opt
tts_config = _origin()._load_tts_config()
name = (provider or _origin()._get_provider(tts_config) or "").lower().strip()
result: Dict[str, Any] = {"provider": name, "warmed": False, "action": "noop"}
-
warmer = _local_tts_warmers().get(name)
if warmer is not None:
cache = _LOCAL_TTS_MODEL_CACHES.get(name, {})
@@ -104,13 +102,11 @@ def warm_tts_provider(tts_config: Optional[Dict[str, Any]] = None, provider: Opt
elapsed_ms=int((time.monotonic() - started) * 1000))
logger.info("[TTS] warm-up %s: %s in %dms", name, result["action"], result["elapsed_ms"])
return result
-
signalled = _signal_user_tts_provider(name, tts_config, "warm")
if signalled is not None:
ok = signalled != "error"
result.update(warmed=ok, action="warmed" if ok else "error")
return result
-
feature = _LAZY_SDK_FEATURES.get(name)
if feature is not None:
try:
diff --git a/tools/tts_tool_local.py b/tools/tts_tool_local.py
index ed0452465b7..ffa2e93557d 100644
--- a/tools/tts_tool_local.py
+++ b/tools/tts_tool_local.py
@@ -56,7 +56,6 @@ def _run_helper(cmd: list, timeout: int) -> subprocess.CompletedProcess:
# --- NeuTTS (subprocess via tools/neutts_synth.py so the ~500MB model exits after use) ---
-
def _generate_neutts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
neutts_config = tts_config.get("neutts") or {}
wav_path = _wav_sidecar_path(output_path)
@@ -76,7 +75,6 @@ def _generate_neutts(text: str, output_path: str, tts_config: Dict[str, Any]) ->
# --- Piper (local neural VITS, 44 languages) ---
-
def _get_piper_voices_dir() -> Path:
"""``<HERMES_HOME>/cache/piper-voices/`` so voice downloads follow profile boundaries."""
from hermes_constants import get_hermes_dir
@@ -140,7 +138,6 @@ _PIPER_ADVANCED_KNOBS = ("length_scale", "noise_scale", "noise_w_scale", "volume
def _generate_piper_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
import wave
-
voice, piper_config = _load_piper_voice_for_config(tts_config)
# Bad speaker_id drops to 0 (Piper's default); bools are rejected (they'd coerce to 1/0).
_raw_speaker = piper_config.get("speaker_id", 0)
@@ -160,7 +157,6 @@ def _generate_piper_tts(text: str, output_path: str, tts_config: Dict[str, Any])
speaker_id=speaker_id)
except ImportError:
logger.warning("[Piper] SynthesisConfig not available in this piper-tts version — advanced knobs ignored")
-
wav_path = _wav_sidecar_path(output_path)
with wave.open(wav_path, "wb") as wav_file:
if syn_config is not None:
@@ -171,7 +167,6 @@ def _generate_piper_tts(text: str, output_path: str, tts_config: Dict[str, Any])
# --- KittenTTS (local ONNX, 25-80MB models, CPU only) ---
-
def _load_kittentts_model_for_config(tts_config: Dict[str, Any]) -> Tuple[Any, Dict[str, Any]]:
"""Load (or fetch from cache) the KittenTTS model; returns ``(model, kittentts_config)``."""
KittenTTS = _origin()._import_kittentts()
@@ -183,7 +178,6 @@ def _load_kittentts_model_for_config(tts_config: Dict[str, Any]) -> Tuple[Any, D
m = KittenTTS(model_name)
logger.info("[KittenTTS] Model loaded successfully")
return m
-
return _tts_cache_get_or_load(_kittentts_model_cache, model_name, _load_kittentts_model), kt_config
@@ -192,7 +186,6 @@ def _generate_kittentts(text: str, output_path: str, tts_config: Dict[str, Any])
audio = model.generate( # numpy array at 24kHz
text, voice=kt_config.get("voice", DEFAULT_KITTENTTS_VOICE),
speed=kt_config.get("speed", 1.0), clean_text=kt_config.get("clean_text", True))
-
import soundfile as sf
wav_path = _wav_sidecar_path(output_path)
sf.write(wav_path, audio, 24000)
diff --git a/tools/tts_tool_openai.py b/tools/tts_tool_openai.py
index 501b3a788e4..a8727980532 100644
--- a/tools/tts_tool_openai.py
+++ b/tools/tts_tool_openai.py
@@ -113,7 +113,6 @@ def _generate_openai_tts(
"to use %r directly.",
model, DEFAULT_OPENAI_MODEL, model)
model = DEFAULT_OPENAI_MODEL
-
create_kwargs: Dict[str, Any] = {
"model": model, "voice": voice, "input": text,
"response_format": _tts_response_format_from_path(output_path),
diff --git a/tools/tts_tool_providers.py b/tools/tts_tool_providers.py
index 7b0004e4195..42a5d3d26bf 100644
--- a/tools/tts_tool_providers.py
+++ b/tools/tts_tool_providers.py
@@ -84,7 +84,6 @@ def _require_key(env_var: str, provider_id: str, hint: str) -> str:
# --- Bounded upstream response reading ---
-
def _response_has_explicit_stream(response: Any) -> bool:
"""True for real ``requests`` responses (or doubles defining ``iter_content`` themselves)."""
if not callable(getattr(response, "iter_content", None)):
@@ -153,12 +152,10 @@ def _write_bytes(output_path: str, audio_bytes: bytes) -> str:
def _post_json(url: str, payload: Dict[str, Any], headers: Dict[str, str], **extra: Any):
"""Streaming ``requests.post`` with the shared 60s timeout (body read via the bounded readers)."""
import requests
-
return requests.post(url, headers=headers, json=payload, timeout=60, stream=True, **extra)
# --- Auxiliary-model speech-tag rewrites ---
-
def _auxiliary_reply_text(response: Any) -> str:
"""The first choice's message content with any ```fence``` unwrapped ("" when unreadable)."""
try:
@@ -196,7 +193,6 @@ def _rewrite_with_auxiliary_model(
# --- Edge TTS (free default) ---
-
async def _generate_edge_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
_edge_tts = _origin()._import_edge_tts()
edge_config = tts_config.get("edge") or {}
@@ -209,7 +205,6 @@ async def _generate_edge_tts(text: str, output_path: str, tts_config: Dict[str,
# --- ElevenLabs ---
-
def _elevenlabs_environment_kwargs(el_config: Dict[str, Any]) -> Dict[str, Any]:
"""SDK client kwargs for ``tts.elevenlabs.base_url``/``wss_url``; empty (SDK default) without a
base_url. ``wss_url`` defaults to the base_url host with a ``ws(s)://`` scheme."""
@@ -337,7 +332,6 @@ def _generate_xai_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -
payload["optimize_streaming_latency"] = optimize_streaming_latency
if text_normalization:
payload["text_normalization"] = True
-
response = _post_json(f"{base_url}/tts", payload, {
"Authorization": f"Bearer {api_key}", "Content-Type": "application/json",
"User-Agent": hermes_xai_user_agent()})
@@ -346,7 +340,6 @@ def _generate_xai_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -
# --- MiniMax TTS ---
-
@dataclass(frozen=True)
class _MiniMaxTTSRuntime:
"""A region-bound MiniMax endpoint and credential (key excluded from ``repr``)."""
@@ -434,7 +427,6 @@ def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any
if not hex_audio:
raise RuntimeError("MiniMax TTS returned empty audio data")
return _write_bytes(output_path, bytes.fromhex(hex_audio))
-
content_type = response.headers.get("Content-Type", "")
if "audio/" in content_type:
return _write_bytes(output_path, _read_tts_response_bytes(response, label="MiniMax TTS"))
@@ -451,7 +443,6 @@ def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any
# --- Mistral (Voxtral TTS) — base64 audio, native Opus for voice bubbles ---
-
def _generate_mistral_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
api_key = _require_key("MISTRAL_API_KEY", "mistral", "Get one at https://console.mistral.ai/")
mi_config = tts_config.get("mistral") or {}
@@ -475,7 +466,6 @@ def _generate_mistral_tts(text: str, output_path: str, tts_config: Dict[str, Any
# --- Google Gemini TTS ---
-
def _read_gemini_persona_prompt(gemini_config: Dict[str, Any]) -> str:
"""Read ``tts.gemini.persona_prompt_file`` (relative -> under HERMES_HOME), failing soft."""
raw = gemini_config.get("persona_prompt_file")
@@ -600,12 +590,10 @@ def _generate_gemini_tts(text: str, output_path: str, tts_config: Dict[str, Any]
if urlparse(base_url).hostname == "generativelanguage.googleapis.com":
try:
import hermes_cli
-
version = str(hermes_cli.__version__)
except Exception:
version = "0.0.0"
headers["X-Goog-Api-Client"] = f"hermes-agent/{version}" # partner-integration guidance
-
response = _post_json(f"{base_url}/models/{model}:generateContent", payload, headers, params={"key": api_key})
if response.status_code != 200:
raise RuntimeError(f"Gemini TTS API error (HTTP {response.status_code}): {_gemini_error_detail(response)}")
diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.py
index 5001d093728..15810b65c2f 100644
--- a/tools/tts_tool_speaker.py
+++ b/tools/tts_tool_speaker.py
@@ -328,7 +328,6 @@ def stream_tts_to_speaker(
if stream_max_len and len(cleaned) > stream_max_len:
cleaned = cleaned[:stream_max_len]
playback.speak(cleaned)
-
while not stop_event.is_set():
try:
delta = text_queue.get(timeout=0.5)
@@ -341,11 +340,9 @@ def stream_tts_to_speaker(
_speak_sentence(sentence)
if delta is None:
break
-
with contextlib.suppress(queue.Empty):
while True:
text_queue.get_nowait()
-
except Exception as exc:
logger.warning("Streaming TTS pipeline error: %s", exc)
finally: