Skip to content

The agent that grows with you

refactor(tools): AST-neutral layout compaction of tts modules (hug brackets, join closers)

Teknium282d714837d0
diff --git a/tools/tts_tool.py b/tools/tts_tool.py
index b41d4c3b77f..c43e591518f 100644
--- a/tools/tts_tool.py
+++ b/tools/tts_tool.py
@@ -53,11 +53,9 @@ from tools.tts_command_provider import ( # noqa: F401 — historical names re-e
_is_command_tts_voice_compatible, _iter_command_providers, _resolve_command_provider_config,
command_env_passthrough as _command_provider_env_passthrough,
render_command_template as _render_command_tts_template,
- run_command_provider as _run_command_tts, shell_quote_context as _shell_quote_context,
-)
+ run_command_provider as _run_command_tts, shell_quote_context as _shell_quote_context)
from tools.tool_backend_helpers import ( # noqa: F401 — seams patched by tests, resolved via tts_tool_openai._origin()
- NOUS_MANAGED_PROVIDER, managed_nous_tools_enabled, read_selection, resolve_openai_audio_api_key,
-)
+ NOUS_MANAGED_PROVIDER, managed_nous_tools_enabled, read_selection, resolve_openai_audio_api_key)
from tools.tts_tool_delivery import ( # noqa: F401 — historical names re-exported
FALLBACK_MAX_TEXT_LENGTH, PROVIDER_MAX_TEXT_LENGTH, _resolve_max_text_length,
AudioDeliveryProfile, _build_audio_delivery_files, _concat_audio_files, _convert_to_opus,
@@ -70,28 +68,23 @@ from tools.tts_tool_providers import ( # noqa: F401 — historical names re-exp
TTS_RESPONSE_BODY_LIMIT_BYTES, _XAI_FIRST_SENTENCE_RE, _XAI_INLINE_SPEECH_TAGS,
_XAI_WRAPPING_SPEECH_TAGS, _apply_xai_auto_speech_tags, _elevenlabs_environment_kwargs,
_generate_edge_tts, _generate_elevenlabs, _generate_gemini_tts, _generate_minimax_tts,
- _generate_mistral_tts, _generate_xai_tts, _resolve_minimax_tts_runtime,
-)
+ _generate_mistral_tts, _generate_xai_tts, _resolve_minimax_tts_runtime)
from tools.tts_tool_local import ( # noqa: F401 — historical names re-exported
DEFAULT_PIPER_VOICE, _LOCAL_TTS_MODEL_CACHES, _TTS_MODEL_CACHE_MAX, _generate_kittentts,
_generate_neutts, _generate_piper_tts, _kittentts_model_cache, _piper_voice_cache,
- _resolve_piper_voice_path, _tts_cache_get_or_load,
-)
+ _resolve_piper_voice_path, _tts_cache_get_or_load)
from tools.tts_tool_speaker import stream_tts_to_speaker # noqa: F401 — historical name re-exported
from tools.tts_text_normalize import _strip_markdown_for_tts # noqa: F401 — historical name re-exported
from tools.tts_tool_plugins import ( # noqa: F401 — historical names re-exported
_dispatch_to_plugin_provider, _plugin_provider_is_available,
- _plugin_provider_is_voice_compatible,
-)
+ _plugin_provider_is_voice_compatible)
from tools.tts_tool_openai import ( # noqa: F401 — historical names re-exported
DEFAULT_OPENAI_BASE_URL, DEFAULT_OPENAI_MODEL, DEFAULT_OPENAI_VOICE, MANAGED_OPENAI_TTS_MODELS,
_generate_deepinfra_tts, _generate_openai_tts, _has_openai_audio_backend,
- _resolve_openai_audio_client_config,
-)
+ _resolve_openai_audio_client_config)
from tools.tts_tool_lifecycle import ( # noqa: F401 — historical names re-exported
_local_tts_warmers, _reset_tts_leases_for_tests, acquire_tts_lease, release_tts_lease,
- release_tts_provider, tts_lease_holders, warm_tts_provider,
-)
+ release_tts_provider, tts_lease_holders, warm_tts_provider)
# --- Lazy SDK importers -- providers import only when used (headless boxes lack PortAudio etc.) ---
@@ -219,8 +212,7 @@ _BUILTIN_DISPATCH: Dict[str, tuple] = {
"piper": (lambda: _importable(_import_piper), "Piper (local)", "_generate_piper_tts",
"Piper provider selected but 'piper-tts' package not installed. "
"Run 'hermes tools' and select Piper under TTS, or install manually: "
- "pip install piper-tts"),
-}
+ "pip install piper-tts")}
def _error_json(message: str) -> str:
@@ -251,8 +243,7 @@ def _select_builtin_engine(provider: str) -> tuple:
return "neutts", None
return provider, _error_json(
"No TTS provider available. Install edge-tts (pip install edge-tts) "
- "or set up NeuTTS for local synthesis."
- )
+ "or set up NeuTTS for local synthesis.")
def _synthesize_builtin(engine: str, text: str, file_str: str, tts_config: Dict[str, Any], instructions: Optional[str]) -> None:
@@ -326,8 +317,7 @@ def _resolve_output_base(
return None, _error_json(
f"output_path contains '..' traversal component: {output_path}. "
"Use an absolute path or one relative to the current directory "
- "without '..'."
- )
+ "without '..'.")
file_path = Path(output_path).expanduser()
if command_provider_config is not None:
file_path = _configured_command_tts_output_path(file_path, command_provider_config)
@@ -335,8 +325,7 @@ def _resolve_output_base(
if is_write_denied(str(file_path)) or is_write_approval_required(str(file_path)):
return None, _error_json(
f"output_path targets a protected credential or system path: "
- f"{file_path}. Choose a normal audio output location."
- )
+ f"{file_path}. Choose a normal audio output location.")
else:
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
out_dir = Path(_default_output_dir())
@@ -441,8 +430,7 @@ def _synthesize_chunks(chunks: List[str], base_path: Path, generated_artifacts:
def text_to_speech_tool(
text: str, output_path: Optional[str] = None, speed: Optional[float] = None,
- instructions: Optional[str] = None, provider: Optional[str] = None,
-) -> str:
+ instructions: Optional[str] = None, provider: Optional[str] = None) -> str:
"""Convert text to speech with long-form chunking; returns the JSON result envelope.
Text is normalized, split into provider-safe chunks (never silently truncated), synthesized
@@ -482,13 +470,11 @@ def text_to_speech_tool(
encoded_paths, chunk_results = _synthesize_chunks(
chunks, base_path, generated_artifacts, provider=provider, tts_config=tts_config,
command_provider_config=command_provider_config, want_opus=want_opus,
- instructions=instructions,
- )
+ instructions=instructions)
voice_compatible = bool(chunk_results) and all(bool(r.get("voice_compatible")) for r in chunk_results)
delivery_base = base_path.with_suffix(Path(encoded_paths[0]).suffix)
final_paths, combined_chunks = _build_audio_delivery_files(
- encoded_paths, str(delivery_base), delivery_profile, voice_compatible=voice_compatible,
- )
+ encoded_paths, str(delivery_base), delivery_profile, voice_compatible=voice_compatible)
for path in final_paths:
logger.info("TTS audio saved: %s (%s bytes, provider: %s)", path, f"{os.path.getsize(path):,}", provider)
return json.dumps({
@@ -499,8 +485,7 @@ def text_to_speech_tool(
"combined_chunks": bool(combined_chunks),
"delivery_profile": {
"platform": delivery_profile.platform, "max_file_bytes": delivery_profile.max_file_bytes,
- "target_file_bytes": delivery_profile.target_file_bytes,
- },
+ "target_file_bytes": delivery_profile.target_file_bytes},
}, ensure_ascii=False)
except _ChunkFailed as exc:
return tool_error(str(exc), success=False)
@@ -547,8 +532,7 @@ _BUILTIN_REQUIREMENTS: Dict[str, Callable[[], bool]] = {
"mistral": lambda: _importable(_import_mistral_client) and bool(_resolve_provider_key("MISTRAL_API_KEY", "mistral")),
"neutts": lambda: _check_neutts_available(),
"kittentts": lambda: _check_kittentts_available(),
- "piper": lambda: _check_piper_available(),
-}
+ "piper": lambda: _check_piper_available()}
def check_tts_requirements() -> bool:
@@ -616,5 +600,4 @@ registry.register(
text=args.get("text", ""),
**{k: args.get(k) for k in ("output_path", "speed", "instructions", "provider")}),
check_fn=check_tts_requirements,
- emoji="🔊",
-)
+ emoji="🔊")
diff --git a/tools/tts_tool_delivery.py b/tools/tts_tool_delivery.py
index ced0d9b9b56..eb3781e768d 100644
--- a/tools/tts_tool_delivery.py
+++ b/tools/tts_tool_delivery.py
@@ -24,11 +24,8 @@ from typing import Any, Dict, List, Optional, Tuple
from hermes_cli._subprocess_compat import windows_hide_flags
from tools.tts_command_provider import (
- BUILTIN_TTS_PROVIDERS,
- DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH,
- _get_named_provider_config,
- _is_command_provider_config,
-)
+ BUILTIN_TTS_PROVIDERS, DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH, _get_named_provider_config,
+ _is_command_provider_config)
logger = logging.getLogger("tools.tts_tool")
@@ -73,8 +70,7 @@ ELEVENLABS_MODEL_MAX_TEXT_LENGTH: Dict[str, int] = {
"eleven_english_sts_v2": 10000,
"eleven_english_sts_v1": 10000,
"eleven_flash_v2": 30000,
- "eleven_flash_v2_5": 40000,
-}
+ "eleven_flash_v2_5": 40000}
def _positive_int(value: Any) -> Optional[int]:
@@ -122,8 +118,7 @@ GEMINI_TTS_SAMPLE_WIDTH = 2
# ffmpeg args producing the Ogg/Opus voice-bubble encoding Telegram & co expect.
_OPUS_VOICE_ARGS = [
"-acodec", "libopus", "-ac", "1", "-b:a", "48k", "-vbr", "on",
- "-application", "voip", "-compression_level", "10",
-]
+ "-application", "voip", "-compression_level", "10"]
# --- Text chunking and delivery profiles ---
@@ -145,13 +140,11 @@ class AudioDeliveryProfile:
_PLATFORM_AUDIO_DEFAULTS: Dict[str, Dict[str, Any]] = {
"discord": {"max_file_bytes": 10 * 1024 * 1024, "safety_ratio": 0.85},
"telegram": {"max_file_bytes": 50 * 1024 * 1024, "safety_ratio": 0.85},
- "default": {"max_file_bytes": 10 * 1024 * 1024, "safety_ratio": 0.85},
-}
+ "default": {"max_file_bytes": 10 * 1024 * 1024, "safety_ratio": 0.85}}
def _resolve_audio_delivery_profile(
- platform: Optional[str], tts_config: Optional[Dict[str, Any]] = None,
-) -> AudioDeliveryProfile:
+ platform: Optional[str], tts_config: Optional[Dict[str, Any]] = None) -> AudioDeliveryProfile:
"""Resolve upload constraints, including optional ``tts.delivery_profiles`` overrides."""
key = (platform or "default").lower().strip() or "default"
defaults = dict(_PLATFORM_AUDIO_DEFAULTS.get(key) or _PLATFORM_AUDIO_DEFAULTS["default"])
@@ -283,11 +276,8 @@ def _finalize_wav_output(wav_path: str, output_path: str) -> str:
def _wrap_pcm_as_wav(
- pcm_bytes: bytes,
- sample_rate: int = GEMINI_TTS_SAMPLE_RATE,
- channels: int = GEMINI_TTS_CHANNELS,
- sample_width: int = GEMINI_TTS_SAMPLE_WIDTH,
-) -> bytes:
+ pcm_bytes: bytes, sample_rate: int = GEMINI_TTS_SAMPLE_RATE,
+ channels: int = GEMINI_TTS_CHANNELS, sample_width: int = GEMINI_TTS_SAMPLE_WIDTH) -> bytes:
"""Wrap raw signed-little-endian PCM (e.g. Gemini's L16) with a minimal WAV RIFF header."""
byte_rate = sample_rate * channels * sample_width
block_align = channels * sample_width
@@ -402,8 +392,7 @@ def _repair_ogg_container(file_str: str) -> str:
os.replace(file_str, honest)
logger.warning(
"Could not transcode %s to Ogg/Opus — renamed to %s so the "
- "file is delivered with its real format", file_str, honest,
- )
+ "file is delivered with its real format", file_str, honest)
return honest
except OSError:
return file_str
@@ -473,8 +462,7 @@ def _build_audio_delivery_files(
if size > profile.max_file_bytes:
raise ValueError(
f"Final-encoded TTS chunk exceeds {profile.platform} delivery "
- f"limit ({size} > {profile.max_file_bytes} bytes): {path}"
- )
+ f"limit ({size} > {profile.max_file_bytes} bytes): {path}")
base = Path(output_path)
scratch_outputs: List[str] = []
diff --git a/tools/tts_tool_lifecycle.py b/tools/tts_tool_lifecycle.py
index 3443dea0587..84179d0329a 100644
--- a/tools/tts_tool_lifecycle.py
+++ b/tools/tts_tool_lifecycle.py
@@ -16,17 +16,12 @@ import time
from typing import Any, Callable, Dict, List, Optional
from tools.tts_command_provider import (
- BUILTIN_TTS_PROVIDERS,
- _get_command_tts_timeout,
- _get_named_provider_config,
- _is_command_provider_config,
- command_env_passthrough as _command_provider_env_passthrough,
- render_command_template as _render_command_tts_template,
-)
+ BUILTIN_TTS_PROVIDERS, _get_command_tts_timeout, _get_named_provider_config,
+ _is_command_provider_config, command_env_passthrough as _command_provider_env_passthrough,
+ render_command_template as _render_command_tts_template)
from tools.tts_tool_delivery import _origin
from tools.tts_tool_local import (
- _LOCAL_TTS_MODEL_CACHES, _load_kittentts_model_for_config, _load_piper_voice_for_config,
-)
+ _LOCAL_TTS_MODEL_CACHES, _load_kittentts_model_for_config, _load_piper_voice_for_config)
from tools.tts_tool_plugins import _lookup_plugin_provider
logger = logging.getLogger("tools.tts_tool")
@@ -39,8 +34,7 @@ def _local_tts_warmers() -> Dict[str, Callable[[Dict[str, Any]], Any]]:
"""Provider name → loader populating that engine's cache slot (same key synthesis uses)."""
return {
"piper": lambda cfg: _load_piper_voice_for_config(cfg)[0],
- "kittentts": lambda cfg: _load_kittentts_model_for_config(cfg)[0],
- }
+ "kittentts": lambda cfg: _load_kittentts_model_for_config(cfg)[0]}
# tools.lazy_deps feature key for providers whose SDK installs on first use.
@@ -64,8 +58,7 @@ def _signal_user_tts_provider(name: str, tts_config: Dict[str, Any], hook: str)
command = _render_command_tts_template(template, {
"voice": str(cfg.get("voice", "")),
"model": str(cfg.get("model", "")),
- "speed": str(cfg.get("speed", tts_config.get("speed", ""))),
- })
+ "speed": str(cfg.get("speed", tts_config.get("speed", "")))})
def _run() -> None:
try:
@@ -110,10 +103,8 @@ def warm_tts_provider(tts_config: Optional[Dict[str, Any]] = None, provider: Opt
return result
after = len(cache) if cache is not None else 0
result.update(
- warmed=True,
- action="loaded" if after > before else "cached",
- elapsed_ms=int((time.monotonic() - started) * 1000),
- )
+ warmed=True, action="loaded" if after > before else "cached",
+ elapsed_ms=int((time.monotonic() - started) * 1000))
logger.info("[TTS] warm-up %s: %s in %dms", name, result["action"], result["elapsed_ms"])
return result
diff --git a/tools/tts_tool_local.py b/tools/tts_tool_local.py
index f32785a95aa..6a810a334a8 100644
--- a/tools/tts_tool_local.py
+++ b/tools/tts_tool_local.py
@@ -69,8 +69,7 @@ def _generate_neutts(text: str, output_path: str, tts_config: Dict[str, Any]) ->
"--ref-audio", neutts_config.get("ref_audio", "") or str(_NEUTTS_SAMPLES / "jo.wav"),
"--ref-text", neutts_config.get("ref_text", "") or str(_NEUTTS_SAMPLES / "jo.txt"),
"--model", neutts_config.get("model", "neuphonic/neutts-air-q4-gguf"),
- "--device", neutts_config.get("device", "cpu"),
- ]
+ "--device", neutts_config.get("device", "cpu")]
result = _run_helper(cmd, 120)
if result.returncode != 0:
# The synth script reports success lines as "OK:" on stderr too.
@@ -115,8 +114,7 @@ def _resolve_piper_voice_path(voice: str, download_dir: Path) -> str:
raise RuntimeError(
f"Piper voice download completed but {cached} is missing — "
f"check voice name (see: https://github.com/OHF-Voice/piper1-gpl/"
- f"blob/main/docs/VOICES.md)"
- )
+ f"blob/main/docs/VOICES.md)")
return str(cached)
@@ -169,8 +167,7 @@ def _generate_piper_tts(text: str, output_path: str, tts_config: Dict[str, Any])
noise_w_scale=float(piper_config.get("noise_w_scale", 0.8)),
volume=float(piper_config.get("volume", 1.0)),
normalize_audio=bool(piper_config.get("normalize_audio", True)),
- speaker_id=speaker_id,
- )
+ speaker_id=speaker_id)
except ImportError:
logger.warning("[Piper] SynthesisConfig not available in this piper-tts version — advanced knobs ignored")
diff --git a/tools/tts_tool_openai.py b/tools/tts_tool_openai.py
index 725b71b264c..59fda1b7d7d 100644
--- a/tools/tts_tool_openai.py
+++ b/tools/tts_tool_openai.py
@@ -15,8 +15,7 @@ from typing import Any, Dict, Optional
from urllib.parse import urljoin
from tools.tool_backend_helpers import (
- NOUS_MANAGED_PROVIDER, nous_tool_gateway_unavailable_message, selection_error,
-)
+ NOUS_MANAGED_PROVIDER, nous_tool_gateway_unavailable_message, selection_error)
from tools.tts_tool_delivery import _origin, _section
from tools.tts_tool_providers import _tts_response_format_from_path
@@ -53,8 +52,7 @@ def _resolve_openai_audio_client_config() -> tuple[str, str, bool]:
if route is None:
raise ValueError(selection_error(
"tts", NOUS_MANAGED_PROVIDER,
- "the Nous Tool Gateway is not available (not entitled or unreachable)",
- ))
+ "the Nous Tool Gateway is not available (not entitled or unreachable)"))
return route
direct_api_key = openai_cfg.get("api_key") or origin.resolve_openai_audio_api_key()
@@ -87,8 +85,7 @@ def _has_openai_audio_backend() -> bool:
def _generate_openai_tts(
text: str, output_path: str, tts_config: Dict[str, Any], *, api_key: Optional[str] = None,
base_url: Optional[str] = None, model: Optional[str] = None, voice: Optional[str] = None,
- speed: Optional[float] = None, instructions: Optional[str] = None,
-) -> str:
+ speed: Optional[float] = None, instructions: Optional[str] = None) -> str:
"""Generate audio via the OpenAI ``audio.speech.create`` SDK shape.
Explicit kwargs let OpenAI-compatible backends (DeepInfra) supply credentials/model/voice
@@ -122,8 +119,7 @@ def _generate_openai_tts(
"TTS: managed OpenAI audio gateway does not support model %r; "
"falling back to %s. Set VOICE_TOOLS_OPENAI_KEY or OPENAI_API_KEY "
"to use %r directly.",
- model, DEFAULT_OPENAI_MODEL, model,
- )
+ model, DEFAULT_OPENAI_MODEL, model)
model = DEFAULT_OPENAI_MODEL
OpenAIClient = _origin()._import_openai_client()
@@ -134,8 +130,7 @@ def _generate_openai_tts(
"voice": voice,
"input": text,
"response_format": _tts_response_format_from_path(output_path),
- "extra_headers": {"x-idempotency-key": str(uuid.uuid4())},
- }
+ "extra_headers": {"x-idempotency-key": str(uuid.uuid4())}}
if speed != 1.0:
create_kwargs["speed"] = max(0.25, min(4.0, speed))
if instructions:
@@ -169,11 +164,9 @@ def _generate_deepinfra_tts(text: str, output_path: str, tts_config: Dict[str, A
raise ValueError(
"No DeepInfra TTS model available. Pin one in config.yaml "
"under tts.deepinfra.model, or check connectivity to "
- "api.deepinfra.com so the live catalog can be fetched."
- )
+ "api.deepinfra.com so the live catalog can be fetched.")
model = candidates[0]
return _origin()._generate_openai_tts(
text, output_path, tts_config, api_key=api_key, base_url=deepinfra_base_url(di_config),
model=model, voice=di_config.get("voice", DEFAULT_DEEPINFRA_TTS_VOICE),
- speed=float(di_config.get("speed", tts_config.get("speed", 1.0))),
- )
+ speed=float(di_config.get("speed", tts_config.get("speed", 1.0))))
diff --git a/tools/tts_tool_plugins.py b/tools/tts_tool_plugins.py
index 42c94573453..0dd8d8c83bd 100644
--- a/tools/tts_tool_plugins.py
+++ b/tools/tts_tool_plugins.py
@@ -12,11 +12,8 @@ import logging
from typing import Any, Dict, Optional
from tools.tts_command_provider import (
- BUILTIN_TTS_PROVIDERS,
- DEFAULT_COMMAND_TTS_OUTPUT_FORMAT,
- _get_named_provider_config,
- _is_command_provider_config,
-)
+ BUILTIN_TTS_PROVIDERS, DEFAULT_COMMAND_TTS_OUTPUT_FORMAT, _get_named_provider_config,
+ _is_command_provider_config)
logger = logging.getLogger("tools.tts_tool")
@@ -66,12 +63,10 @@ def _dispatch_to_plugin_provider(text: str, output_path: str, provider: str, tts
fmt = cfg.get("output_format", DEFAULT_COMMAND_TTS_OUTPUT_FORMAT)
logger.info("Generating speech with plugin TTS provider '%s'...", key)
written = plugin_provider.synthesize(
- text, output_path,
- voice=voice if isinstance(voice, str) and voice else None,
+ text, output_path, voice=voice if isinstance(voice, str) and voice else None,
model=model if isinstance(model, str) and model else None,
speed=float(speed) if isinstance(speed, (int, float)) else None,
- format=str(fmt).lower() if fmt else "mp3",
- )
+ format=str(fmt).lower() if fmt else "mp3")
# Contract: returns the (possibly rewritten) output path; tolerate None.
return written if isinstance(written, str) and written else output_path
diff --git a/tools/tts_tool_providers.py b/tools/tts_tool_providers.py
index 53e0587bd8d..b85af2460c1 100644
--- a/tools/tts_tool_providers.py
+++ b/tools/tts_tool_providers.py
@@ -205,10 +205,8 @@ def _rewrite_with_auxiliary_model(
task=GEMINI_AUDIO_TAG_REWRITE_TASK,
messages=[
{"role": "system", "content": system_prompt},
- {"role": "user", "content": user_prompt},
- ],
- temperature=0.7,
- )
+ {"role": "user", "content": user_prompt}],
+ temperature=0.7)
return _strip_code_fence(_extract_auxiliary_message_content(response)) or fallback
except Exception as exc:
logger.log(level, "%s audio tag rewrite failed; using %s: %s", label, fallback_label, exc)
@@ -246,11 +244,9 @@ def _generate_elevenlabs(text: str, output_path: str, tts_config: Dict[str, Any]
el_config = tts_config.get("elevenlabs") or {}
client = _origin()._import_elevenlabs()(api_key=api_key, **_elevenlabs_environment_kwargs(el_config))
audio_generator = client.text_to_speech.convert(
- text=text,
- voice_id=el_config.get("voice_id", DEFAULT_ELEVENLABS_VOICE_ID),
+ text=text, voice_id=el_config.get("voice_id", DEFAULT_ELEVENLABS_VOICE_ID),
model_id=el_config.get("model_id", DEFAULT_ELEVENLABS_MODEL_ID),
- output_format="opus_48000_64" if output_path.endswith(".ogg") else "mp3_44100_128",
- )
+ output_format="opus_48000_64" if output_path.endswith(".ogg") else "mp3_44100_128")
with open(output_path, "wb") as f:
for chunk in audio_generator:
f.write(chunk)
@@ -260,16 +256,13 @@ def _generate_elevenlabs(text: str, output_path: str, tts_config: Dict[str, Any]
# --- xAI TTS (dedicated /v1/tts endpoint, not the OpenAI audio shape) ---
_XAI_INLINE_SPEECH_TAGS = (
"pause", "long-pause", "hum-tune", "laugh", "chuckle", "giggle", "cry", "tsk",
- "tongue-click", "lip-smack", "breath", "inhale", "exhale", "sigh",
-)
+ "tongue-click", "lip-smack", "breath", "inhale", "exhale", "sigh")
_XAI_WRAPPING_SPEECH_TAGS = (
"soft", "whisper", "loud", "build-intensity", "decrease-intensity", "higher-pitch",
- "lower-pitch", "slow", "fast", "sing-song", "singing", "laugh-speak", "emphasis",
-)
+ "lower-pitch", "slow", "fast", "sing-song", "singing", "laugh-speak", "emphasis")
_XAI_SPEECH_TAG_RE = re.compile(
r"(\[(?:" + "|".join(_XAI_INLINE_SPEECH_TAGS) + r")\]|</?(?:" + "|".join(_XAI_WRAPPING_SPEECH_TAGS) + r")>)",
- flags=re.IGNORECASE,
-)
+ flags=re.IGNORECASE)
_XAI_FIRST_SENTENCE_RE = re.compile(r"^(.{12,120}?[.!?…])\s+(?=\S)", flags=re.DOTALL)
@@ -301,8 +294,7 @@ def _apply_xai_auto_speech_tags(text: str) -> str:
"- Use wrapping `[tag]...[/tag]` for sustained effects (whisper, soft, slow, fast, loud, etc.).\n"
"- Do not use angle-bracket tags like `<tag>...</tag>` — xAI uses BBCode-style closing tags with `[/tag]`.\n"
"- Do not use SSML.\n"
- + _TAG_REWRITE_TAIL
- )
+ + _TAG_REWRITE_TAIL)
return _rewrite_with_auxiliary_model(
system_prompt, f"TRANSCRIPT TO TAG:\n{local}", local, label="xAI TTS", fallback_label="locally-tagged text", level=logging.DEBUG,
)
@@ -377,8 +369,7 @@ def _generate_xai_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -
response = _post_json(f"{base_url}/tts", payload, {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
- "User-Agent": hermes_xai_user_agent(),
- })
+ "User-Agent": hermes_xai_user_agent()})
response.raise_for_status()
return _write_bytes(output_path, _read_tts_response_bytes(response, label="xAI TTS"))
@@ -398,8 +389,7 @@ class _MiniMaxTTSRuntime:
_MINIMAX_ENDPOINTS = {"global": DEFAULT_MINIMAX_BASE_URL, "cn": DEFAULT_MINIMAX_CN_BASE_URL}
_MINIMAX_OFFICIAL_HOSTS = {
"global": frozenset({"api.minimax.io", "api.minimax.chat"}),
- "cn": frozenset({"api.minimaxi.com"}),
-}
+ "cn": frozenset({"api.minimaxi.com"})}
def _resolve_minimax_tts_runtime(tts_config: Dict[str, Any]) -> _MiniMaxTTSRuntime:
@@ -451,8 +441,7 @@ def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any
# URL): config or MINIMAX_GROUP_ID, attached only when absent from the URL.
group_id = (
str(mm_config.get("group_id") or "").strip()
- or (_origin().get_env_value("MINIMAX_GROUP_ID") or "").strip()
- )
+ or (_origin().get_env_value("MINIMAX_GROUP_ID") or "").strip())
if group_id and "GroupId=" not in base_url:
base_url = f"{base_url}{'&' if '?' in base_url else '?'}GroupId={group_id}"
@@ -473,8 +462,7 @@ def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any
payload = {"model": model, "text": text, "voice_id": voice_id}
response = _post_json(base_url, payload, {
- "Content-Type": "application/json", "Authorization": f"Bearer {runtime.api_key}"
- })
+ "Content-Type": "application/json", "Authorization": f"Bearer {runtime.api_key}"})
if is_t2a_v2:
response.raise_for_status()
@@ -513,11 +501,9 @@ def _generate_mistral_tts(text: str, output_path: str, tts_config: Dict[str, Any
try:
with Mistral(**client_kwargs) as client:
response = client.audio.speech.complete(
- model=mi_config.get("model", DEFAULT_MISTRAL_TTS_MODEL),
- input=text,
+ model=mi_config.get("model", DEFAULT_MISTRAL_TTS_MODEL), input=text,
voice_id=mi_config.get("voice_id") or DEFAULT_MISTRAL_TTS_VOICE_ID,
- response_format=_tts_response_format_from_path(output_path),
- )
+ response_format=_tts_response_format_from_path(output_path))
audio_bytes = base64.b64decode(response.audio_data)
except ValueError:
raise
@@ -561,8 +547,7 @@ def _gemini_audio_tags_enabled(gemini_config: Dict[str, Any], model: str) -> boo
logger.warning(
"Gemini TTS audio_tags enabled, but model %s is not known to support "
"Gemini audio tags; skipping hidden tag rewrite",
- model,
- )
+ model)
return False
@@ -583,8 +568,7 @@ def _rewrite_gemini_tts_audio_tags(text: str, persona_prompt: str = "") -> str:
+ _TAG_REWRITE_RULES +
"- Use square brackets for every audio tag.\n"
"- Do not use SSML or XML tags.\n"
- + _TAG_REWRITE_TAIL
- )
+ + _TAG_REWRITE_TAIL)
context = persona_prompt.strip() or "(none)"
user_prompt = f"PERSONA AND DIRECTOR CONTEXT:\n{context}\n\nTRANSCRIPT TO TAG:\n{transcript}"
return _rewrite_with_auxiliary_model(
@@ -604,8 +588,7 @@ def _compose_gemini_tts_prompt(text: str, gemini_config: Dict[str, Any], persona
preamble = (
"Synthesize speech from the TRANSCRIPT only. Treat AUDIO PROFILE, "
"SCENE, DIRECTOR'S NOTES, and SAMPLE CONTEXT as performance direction; "
- "do not speak those sections aloud."
- )
+ "do not speak those sections aloud.")
for pattern in (r"\{\{\s*transcript\s*\}\}", r"\{\s*transcript\s*\}"):
compiled = re.compile(pattern, flags=re.IGNORECASE)
if compiled.search(persona_prompt):
@@ -649,8 +632,7 @@ def _generate_gemini_tts(text: str, output_path: str, tts_config: Dict[str, Any]
"Gemini TTS composed prompt exceeds the provider request limit "
f"({len(prompt_text)} > {max_len} chars). Reduce the persona/audio-tag "
"prompt or lower tts.gemini.max_text_length so long-form text is "
- "split with enough prompt headroom."
- )
+ "split with enough prompt headroom.")
payload: Dict[str, Any] = {
"contents": [{"parts": [{"text": prompt_text}]}],
diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.py
index fe134761074..1914d8ba42f 100644
--- a/tools/tts_tool_speaker.py
+++ b/tools/tts_tool_speaker.py
@@ -240,8 +240,7 @@ class _StreamerPlayback:
if self._reinit_count >= self._MAX_REINIT:
logger.warning(
"TTS: PortAudio reinit exhausted after %d attempts, falling back to tempfile for remaining sentences",
- self._MAX_REINIT,
- )
+ self._MAX_REINIT)
self._current_stream = None
return False
self._reinit_count += 1
@@ -303,8 +302,7 @@ class _StreamerPlayback:
def stream_tts_to_speaker(
text_queue: queue.Queue, stop_event: threading.Event, tts_done_event: threading.Event,
- display_callback: Optional[Callable[[str], None]] = None, provider: Optional[str] = None,
-):
+ display_callback: Optional[Callable[[str], None]] = None, provider: Optional[str] = None):
"""Consume text deltas from *text_queue*, cut into sentences, speak each the moment it's ready.
A registered streaming provider plays chunked PCM; every other provider is spoken