Skip to content

The agent that grows with you

fix(stt): opt-in 16 kHz mono normalization for command STT providers

Brooklyn Nicholson4f91c5a46218
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 10e4c0e3bf3..f2f487e448c 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -1709,6 +1709,15 @@ stt:
# # by the `stt` surface tag — leave `model` blank to take the first
# # live result. Pin only when you need a specific Whisper variant.
# model: ""
+ # Custom command providers (stt.providers.<name>: type: command) can
+ # normalize browser WebM/Opus and other input formats to 16 kHz mono m4a
+ # before substituting {input_path}. This is opt-in so CLIs that already
+ # accept arbitrary containers (e.g. whisper.cpp) remain unchanged.
+ # providers:
+ # custom-asr:
+ # type: "command"
+ # command: "custom-asr --input {input_path} --output {output_path}"
+ # normalize: true # requires ffmpeg; default false
# Text-to-speech. Only the deepinfra block is documented here — the
# remaining providers (edge, openai, xai, minimax, mistral, gemini,
diff --git a/tests/tools/test_transcription_command_providers.py b/tests/tools/test_transcription_command_providers.py
index 831d350972e..9a7607b2cc4 100644
--- a/tests/tools/test_transcription_command_providers.py
+++ b/tests/tools/test_transcription_command_providers.py
@@ -18,11 +18,15 @@ identically on Linux, macOS, and Windows (with minor quoting differences).
from __future__ import annotations
+import shutil
+import subprocess
import sys
import wave
from pathlib import Path
from unittest.mock import patch
+import pytest
+
from tools.transcription_common import BUILTIN_STT_PROVIDERS
from tools.transcription_command import (
@@ -77,6 +81,23 @@ def _python_emit_stdout_command(transcript_text: str) -> str:
return f'"{interpreter}" -c "{payload}"'
+def _python_echo_input_command() -> str:
+ """Return a portable shell command that writes the received {input_path} to {output_path}."""
+ interpreter = sys.executable
+ payload = "import sys; open(sys.argv[2], 'w', encoding='utf-8').write(sys.argv[1])"
+ return f'"{interpreter}" -c "{payload}" {{input_path}} {{output_path}}'
+
+
+def _python_copy_input_command(copy_dest: str) -> str:
+ """Command that copies the received {input_path} to *copy_dest* and echoes the path
+ to {output_path} — lets a test inspect the exact bytes the provider received even
+ after the runner's temp dir is cleaned up."""
+ interpreter = sys.executable
+ payload = ("import sys, shutil; shutil.copyfile(sys.argv[1], sys.argv[3]); "
+ "open(sys.argv[2], 'w', encoding='utf-8').write(sys.argv[1])")
+ return f'"{interpreter}" -c "{payload}" {{input_path}} {{output_path}} {copy_dest}'
+
+
# ---------------------------------------------------------------------------
# _resolve_command_stt_provider_config / built-in precedence
# ---------------------------------------------------------------------------
@@ -353,3 +374,119 @@ class TestCommandWinsOverPlugin:
assert result["success"] is True
assert result["transcript"] == "FROM_PLUGIN"
+
+
+# ---------------------------------------------------------------------------
+# normalize: opt-in ffmpeg transcode (16 kHz mono) before the command runs
+# ---------------------------------------------------------------------------
+
+
+class TestNormalizeCommandSTTInput:
+ """``stt.providers.<name>.normalize: true`` hands the command a 16 kHz mono
+ m4a instead of the raw container (desktop voice notes are WebM/Opus 48 kHz;
+ providers with container/sample-rate contracts reject the raw file — #81811).
+
+ The flag is opt-in: providers that accept any container (whisper CLIs) must
+ keep receiving the original file untouched.
+ """
+
+ def test_normalize_false_passes_original_file(self, tmp_path):
+ import tools.transcription_command as mod
+
+ audio = _make_silent_wav(tmp_path / "input.wav")
+ cfg = {"type": "command", "command": _python_echo_input_command()}
+ with patch.object(mod, "_transcode_audio_for_stt") as transcode:
+ result = _transcribe_command_stt(str(audio), "fake-cli", cfg, {})
+ transcode.assert_not_called()
+ assert result["success"] is True
+ assert Path(result["transcript"]) == audio
+
+ def test_normalize_true_passes_transcoded_file(self, tmp_path):
+ import tools.transcription_command as mod
+
+ audio = _make_silent_wav(tmp_path / "input.wav")
+ converted = tmp_path / "converted" / "input-stt.m4a"
+ converted.parent.mkdir()
+ converted.write_bytes(b"fake m4a")
+ cfg = {
+ "type": "command",
+ "command": _python_echo_input_command(),
+ "normalize": True,
+ }
+ with patch.object(mod, "_transcode_audio_for_stt",
+ return_value=(str(converted), None)) as transcode:
+ result = _transcribe_command_stt(str(audio), "fake-cli", cfg, {})
+ transcode.assert_called_once()
+ assert result["success"] is True
+ assert Path(result["transcript"]) == converted
+ # The original file is never modified.
+ assert audio.read_bytes() != b"fake m4a"
+
+ def test_normalize_transcode_failure_returns_error(self, tmp_path):
+ import tools.transcription_command as mod
+
+ audio = _make_silent_wav(tmp_path / "input.wav")
+ cfg = {
+ "type": "command",
+ "command": _python_echo_input_command(),
+ "normalize": True,
+ }
+ with patch.object(mod, "_transcode_audio_for_stt",
+ return_value=(None, "ffmpeg was not found")):
+ result = _transcribe_command_stt(str(audio), "fake-cli", cfg, {})
+ assert result["success"] is False
+ assert "normalize" in result["error"]
+ assert "ffmpeg was not found" in result["error"]
+
+ def test_normalize_string_false_passes_original_file(self, tmp_path):
+ import tools.transcription_command as mod
+
+ audio = _make_silent_wav(tmp_path / "input.wav")
+ cfg = {
+ "type": "command",
+ "command": _python_echo_input_command(),
+ "normalize": "false",
+ }
+ with patch.object(mod, "_transcode_audio_for_stt") as transcode:
+ result = _transcribe_command_stt(str(audio), "fake-cli", cfg, {})
+ transcode.assert_not_called()
+ assert result["success"] is True
+ assert Path(result["transcript"]) == audio
+
+
+_HAS_FFMPEG = bool(shutil.which("ffmpeg")) and bool(shutil.which("ffprobe"))
+
+
+def _make_opus_webm(path: Path) -> Path:
+ """Write a minimal WebM/Opus file (48 kHz), like a desktop voice recording."""
+ silent_wav = _make_silent_wav(path.with_suffix(".wav"), seconds=0.2)
+ subprocess.run(
+ ["ffmpeg", "-y", "-loglevel", "error", "-i", str(silent_wav),
+ "-c:a", "libopus", "-b:a", "32k", str(path)],
+ check=True, timeout=60)
+ return path
+
+
[email protected](not _HAS_FFMPEG, reason="ffmpeg/ffprobe not installed")
+class TestNormalizeCommandSTTRealFFmpeg:
+ def test_webm_normalized_to_16k_mono_m4a(self, tmp_path):
+ audio = _make_opus_webm(tmp_path / "voice.webm")
+ received_copy = str(tmp_path / "received.m4a")
+ cfg = {
+ "type": "command",
+ "command": _python_copy_input_command(received_copy),
+ "normalize": True,
+ }
+ result = _transcribe_command_stt(str(audio), "fake-cli", cfg, {})
+ assert result["success"] is True, result
+ received = Path(result["transcript"])
+ assert received != audio
+ assert received.suffix == ".m4a"
+ probe = subprocess.run(
+ ["ffprobe", "-v", "error", "-select_streams", "a:0",
+ "-show_entries", "stream=sample_rate,channels", "-of",
+ "default=noprint_wrappers=1:nokey=1", received_copy],
+ check=True, capture_output=True, text=True, timeout=30)
+ sample_rate, channels = probe.stdout.split()
+ assert int(sample_rate) == 16000
+ assert int(channels) == 1
diff --git a/tools/transcription_command.py b/tools/transcription_command.py
index a98b59ea902..5723d399d3e 100644
--- a/tools/transcription_command.py
+++ b/tools/transcription_command.py
@@ -21,8 +21,10 @@ from tools.tts_command_provider import (
_named_provider_config, _resolve_command_config, command_env_passthrough as _command_stt_env_passthrough,
command_failure_detail, render_command_template as _render_command_stt_template,
run_command_provider as _run_command_stt)
+from tools.transcription_audio import _transcode_audio_for_stt
from tools.transcription_common import (
BUILTIN_STT_PROVIDERS, _error_result, _log_prompt_unsupported, _ok_result)
+from utils import is_truthy_value
# Log-record parity with the origin module.
logger = logging.getLogger("tools.transcription_tools")
@@ -65,13 +67,33 @@ def _read_command_stt_output(output_path: Path, stdout: str, fmt: str) -> str:
raise RuntimeError(f"Command STT provider wrote no output file at {output_path} and produced no stdout")
+def _normalize_command_stt_input(audio: Path, tmpdir: str, provider_name: str,
+ config: Dict[str, Any]) -> tuple[Optional[str], Optional[str]]:
+ """Resolve the file handed to a command STT provider. ``stt.providers.<name>.normalize``
+ (default off) transcodes to 16 kHz mono m4a first — desktop voice notes arrive as
+ WebM/Opus 48 kHz and providers with container/sample-rate contracts (Tencent 16k_zh)
+ reject the raw container. Failure is an error, not a silent pass-through: the user
+ opted into normalization, so feeding the raw file would reproduce the bug. Returns
+ ``(input_path, None)`` or ``(None, error)``."""
+ if not is_truthy_value(config.get("normalize"), default=False):
+ return str(audio.resolve()), None
+ converted_path, transcode_error = _transcode_audio_for_stt(str(audio.resolve()), tmpdir)
+ if transcode_error or not converted_path:
+ return None, (f"stt.providers.{provider_name}.normalize: true but the audio could not be "
+ f"normalized for the command provider: {transcode_error or 'unknown ffmpeg failure'}")
+ logger.info("Normalized %s to 16 kHz mono for command STT provider '%s'",
+ audio.name, provider_name)
+ return converted_path, None
+
+
def _transcribe_command_stt(
file_path: str, provider_name: str, config: Dict[str, Any], stt_config: Dict[str, Any],
model_override: Optional[str] = None, language_override: Optional[str] = None,
prompt: Optional[str] = None) -> Dict[str, Any]:
"""Transcribe via a user-declared ``stt.providers.<name>: type: command``. Placeholders
- (shell-quote-aware; ``{{``/``}}`` stay literal): ``{input_path}``, ``{output_path}`` (transcript
- file), ``{output_dir}``, ``{format}`` txt/json/srt/vtt, ``{language}`` (default ``en``),
+ (shell-quote-aware; ``{{``/``}}`` stay literal): ``{input_path}`` (the original file, or a
+ 16 kHz mono m4a when ``normalize: true``), ``{output_path}`` (transcript file),
+ ``{output_dir}``, ``{format}`` txt/json/srt/vtt, ``{language}`` (default ``en``),
``{model}`` (empty when unset)."""
from tools.transcription_tools import _resolve_stt_language
if prompt:
@@ -91,9 +113,12 @@ def _transcribe_command_stt(
or _resolve_stt_language(provider_name, stt_config) or DEFAULT_COMMAND_STT_LANGUAGE)
try:
with tempfile.TemporaryDirectory(prefix=f"hermes-cmd-stt-{provider_name}-") as tmpdir:
+ input_path, normalize_error = _normalize_command_stt_input(audio, tmpdir, provider_name, config)
+ if normalize_error:
+ return fail(normalize_error)
output_path = Path(tmpdir) / f"transcript.{output_format}"
command = _render_command_stt_template(command_template, {
- "input_path": str(audio.resolve()), "output_path": str(output_path),
+ "input_path": input_path, "output_path": str(output_path),
"output_dir": str(output_path.parent), "format": output_format,
"language": str(language), "model": str(model_override or config.get("model") or ""),
})
diff --git a/website/docs/user-guide/features/tts.md b/website/docs/user-guide/features/tts.md
index c0b57016bc5..ee27f91ebb5 100644
--- a/website/docs/user-guide/features/tts.md
+++ b/website/docs/user-guide/features/tts.md
@@ -616,7 +616,7 @@ Your command template can reference these placeholders. Hermes substitutes them
| Placeholder | Meaning |
|-------------------|----------------------------------------------------------------------|
-| `{input_path}` | Absolute path to the input audio file (original location, read-only) |
+| `{input_path}` | Absolute path to the input audio file (original location, read-only; a 16 kHz mono m4a when `normalize: true`) |
| `{output_path}` | Absolute path the command should write the transcript to |
| `{output_dir}` | Parent directory of `{output_path}` (handy for whisper-style tools) |
| `{format}` | Configured output format: `txt` / `json` / `srt` / `vtt` |
@@ -645,6 +645,7 @@ For `format: json` / `srt` / `vtt`, Hermes returns the raw file content as the `
| `format` | `txt` | One of `txt` / `json` / `srt` / `vtt`. Sets the extension of `{output_path}`. |
| `language` | `en` | Forwarded to `{language}`. Defaults to `stt.language` then `en`. |
| `model` | empty | Forwarded to `{model}`. The `model=` argument to `transcribe_audio()` overrides this. |
+| `normalize` | `false` | Transcode the input to 16 kHz mono m4a (ffmpeg) before the command runs; `{input_path}` then points at the normalized file. |
#### STT command-provider behavior notes