The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): collapse tts delivery profile/packing locals, speaker aligner tail, wrap long import
Tekniumf0cac15ad1c2
diff --git a/tools/tts_tool.py b/tools/tts_tool.pyindex 5a78e3196d5..41a6ab890a3 100644--- a/tools/tts_tool.py+++ b/tools/tts_tool.py@@ -60,8 +60,8 @@ from tools.tts_tool_delivery import ( # noqa: F401 — historical names re-expoFALLBACK_MAX_TEXT_LENGTH, PROVIDER_MAX_TEXT_LENGTH, _resolve_max_text_length,AudioDeliveryProfile, _build_audio_delivery_files, _concat_audio_files, _convert_to_opus,_pack_audio_files_for_delivery, _remove_quietly, _repair_ogg_container,- _resolve_audio_delivery_profile, _sniff_audio_container, _split_oversized_sentence, _split_text_for_tts, _wrap_pcm_as_wav,-)+ _resolve_audio_delivery_profile, _sniff_audio_container, _split_oversized_sentence,+ _split_text_for_tts, _wrap_pcm_as_wav)from tools.tts_tool_providers import ( # noqa: F401 — historical names re-exportedDEFAULT_ELEVENLABS_MODEL_ID, DEFAULT_ELEVENLABS_VOICE_ID, DEFAULT_GEMINI_TTS_MODEL,DEFAULT_GEMINI_TTS_VOICE, DEFAULT_MINIMAX_BASE_URL, DEFAULT_MINIMAX_CN_BASE_URL,diff --git a/tools/tts_tool_delivery.py b/tools/tts_tool_delivery.pyindex f823e06101c..5cb5cd69172 100644--- a/tools/tts_tool_delivery.py+++ b/tools/tts_tool_delivery.py@@ -139,13 +139,13 @@ def _resolve_audio_delivery_profile("""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"])- profiles = (tts_config or {}).get("delivery_profiles")- 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"]+ overrides = _section(_section(tts_config, "delivery_profiles"), key)+ 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:+ if (isinstance(safety_ratio, bool) or not isinstance(safety_ratio, (int, float))+ or not 0 < safety_ratio <= 1):safety_ratio = 0.85return AudioDeliveryProfile(platform=key, max_file_bytes=max_file_bytes, safety_ratio=float(safety_ratio))@@ -189,10 +189,7 @@ def _split_text_for_tts(text: str, max_chars: int) -> List[str]:if len(normalized) <= max_chars:return [normalized]expanded: List[str] = []- for sentence in re.split(r"(?<=[.!?;:,])\s+", normalized):- sentence = sentence.strip()- if not sentence:- continue+ for sentence in filter(None, (s.strip() for s in re.split(r"(?<=[.!?;:,])\s+", normalized))):if len(sentence) <= max_chars:expanded.append(sentence)else:@@ -204,20 +201,15 @@ def _pack_audio_files_for_delivery(audio_paths: List[str], profile: AudioDeliver"""Group final-encoded chunks under the size target; never mixes suffixes (can't concat-copy)."""groups: List[List[str]] = []current: List[str] = []- current_size = 0- current_suffix = ""+ current_size, current_suffix = 0, ""for path in audio_paths:- size = Path(path).stat().st_size- suffix = Path(path).suffix.lower()+ size, suffix = Path(path).stat().st_size, Path(path).suffix.lower()if current and (current_size + size > profile.target_file_bytes or suffix != current_suffix):groups.append(current)current, current_size = [], 0current.append(path)- current_size += size- current_suffix = suffix- if current:- groups.append(current)- return groups+ current_size, current_suffix = current_size + size, suffix+ return groups + [current] if current else groups# --- ffmpeg encoding helpers ---@@ -225,10 +217,8 @@ def _ffmpeg_run(ffmpeg: str, args: List[str], *, timeout: int = 30, check: bool = False, capture: bool = True,) -> subprocess.CompletedProcess:"""Run ``ffmpeg <args>`` headless (no stdin, hidden window on Windows)."""- return subprocess.run(- [ffmpeg, *args],- capture_output=capture, check=check, timeout=timeout, stdin=subprocess.DEVNULL, creationflags=windows_hide_flags(),- )+ return subprocess.run([ffmpeg, *args], capture_output=capture, check=check, timeout=timeout,+ stdin=subprocess.DEVNULL, creationflags=windows_hide_flags())def _remove_quietly(path: Optional[str]) -> None:@@ -251,13 +241,12 @@ def _finalize_wav_output(wav_path: str, output_path: str) -> str:if wav_path == output_path:return output_pathffmpeg = shutil.which("ffmpeg")- if ffmpeg:- _ffmpeg_run(- ffmpeg, ["-i", wav_path, "-y", "-loglevel", "error", output_path], check=True,- capture=False)- _remove_quietly(wav_path)- else:+ if not ffmpeg:os.rename(wav_path, output_path)+ return output_path+ _ffmpeg_run(ffmpeg, ["-i", wav_path, "-y", "-loglevel", "error", output_path],+ check=True, capture=False)+ _remove_quietly(wav_path)return output_path@@ -318,7 +307,7 @@ def _ffmpeg_transcode_to_opus(input_path: str, ogg_path: str) -> Optional[str]:result = _ffmpeg_run("ffmpeg", ["-i", input_path, *_OPUS_VOICE_ARGS, "-f", "ogg", work_path, "-y"])if result.returncode != 0:logger.warning("ffmpeg conversion failed with return code %d: %s",- result.returncode, result.stderr.decode('utf-8', errors='ignore')[:200])+ result.returncode, result.stderr.decode('utf-8', errors='ignore')[:200])return Noneif os.path.exists(work_path) and os.path.getsize(work_path) > 0:if in_place:@@ -401,8 +390,7 @@ def _concat_audio_files(audio_paths: List[str], output_path: str, *, voice_compaargs += ["-c:a", "libopus", "-ac", "1", "-b:a", "64k", "-vbr", "off"]elif suffix == ".mp3" and all(Path(path).suffix.lower() == ".mp3" for path in audio_paths):args += ["-c:a", "copy"]- args.append(str(temp_output))- result = _ffmpeg_run(ffmpeg, args, timeout=120)+ result = _ffmpeg_run(ffmpeg, [*args, str(temp_output)], timeout=120)if result.returncode == 0 and temp_output.exists() and temp_output.stat().st_size > 0:os.replace(temp_output, destination)return str(destination)@@ -433,8 +421,7 @@ def _build_audio_delivery_files(f"limit ({size} > {profile.max_file_bytes} bytes): {path}")base = Path(output_path)scratch_outputs: List[str] = []- combined_any = False- combine_index = 0+ combined_any, combine_index = False, 0def emit(group: List[str]) -> List[str]:nonlocal combined_any, combine_indexdiff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.pyindex 32bc8e524ce..2c5a2247590 100644--- a/tools/tts_tool_speaker.py+++ b/tools/tts_tool_speaker.py@@ -34,7 +34,7 @@ def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event, *, paligned_len = len(buf) - (len(buf) % 2)if aligned_len >= 2:yield buf[:aligned_len]- leftover = buf[aligned_len:] if aligned_len < len(buf) else b""+ leftover = buf[aligned_len:]if leftover and pad_tail:yield b"\x00"@@ -219,7 +219,6 @@ class _StreamerPlayback:def _write_pcm(self, buf: bytes) -> None:self._current_stream.write(self._np.frombuffer(buf, dtype="<i2").reshape(-1, 1))-def _recover_stream(self) -> bool:"""Close the broken PortAudio stream and open a fresh one after a failed write; False once``_MAX_REINIT`` is exhausted (remaining sentences go through temp files)."""@@ -265,9 +264,7 @@ class _StreamerPlayback:from tools.voice_mode import mark_audio_output_activeexcept Exception:mark_audio_output_active = lambda _active: None # noqa: E731- self._np = _np- self._reinit_count = 0- self._current_stream = self.output_stream+ self._np, self._reinit_count, self._current_stream = _np, 0, self.output_streammark_audio_output_active(True)try:self._for_each_sentence(self._play_sentence_via_stream)