Skip to main content
Version: Next

Custom provider example

Here you can find scripts for running custom provider using huggingface/speech-to-speech. Scripts are made for and tested on Apple Silicon only (M1 or later).

Client
│
▼
OpenAI Realtime WebSocket ws://HOST:8765/v1/realtime
│
▼
Silero VAD turn detection
│
▼
Parakeet-TDT speech → text
│
▼
Qwen3-4B Instruct text → reply
│
▼
Kokoro-82M reply → speech
│
▼
Client

Requirements​

  • macOS on Apple Silicon
  • About 8 GB unified memory minimum; 16 GB is comfortable
  • Homebrew
  • git (Xcode Command Line Tools: xcode-select --install)

./setup.sh installs uv, portaudio, and ffmpeg if they are missing. It also clones huggingface/speech-to-speech into speech-to-speech/ if that folder is not already there.

Do not copy speech-to-speech/.venv between Macs. It is not portable. Model weights land in ~/.cache/huggingface.

Models and memory​

Default stack. Weights stay loaded for the whole session.

StageWhatHugging Face idWeights
VADSilero v5bundled~2 MB
Turn detectSmart Turn v3pipecat-ai/smart-turn-v3~9 MB
STTParakeet-TDT 0.6Bmlx-community/parakeet-tdt-0.6b-v3~2.5 GB
LLMQwen3-4B Instruct 2507 4-bitmlx-community/Qwen3-4B-Instruct-2507-4bit~2.3 GB
TTSKokoro 82M bf16, voice bm_fablemlx-community/Kokoro-82M-bf16~0.2 GB
  • Disk: about 5 GB in ~/.cache/huggingface
  • While running: about 6–8 GB unified RAM (peak closer to 8–9 GB)
  • 16 GB Mac: fine
  • 8 GB Mac: it runs, but it will swap under load

TTS is British English (bm_fable). Replies are capped at 128 tokens.

A larger LLM:

./setup.sh --llm mlx-community/Qwen3-8B-Instruct-2507-4bit

That adds about 2 GB more for the language model.

Setup​

From this directory:

chmod +x setup.sh run.sh
./setup.sh

On a terminal, setup asks for STT, LLM, and TTS Hugging Face ids. Press Enter to keep the default (or the last values saved in .mac-run.env).

First run clones the engine, builds a Python 3.12 virtualenv, downloads weights, and smoke-tests the LLM. Expect several minutes plus model download time.

CommandWhat it does
./setup.shClone if needed, prompt for models, fetch weights
./setup.sh --defaultsNo prompts; compact stack (or STT_MODEL / LLM_MODEL / TTS_MODEL)
./setup.sh --no-modelsSkip weight downloads
./setup.sh --force-venvRebuild speech-to-speech/.venv
./setup.sh --stt <hf-id>STT weights
./setup.sh --llm <hf-id>LLM weights
./setup.sh --tts <hf-id>TTS weights
./setup.sh --helpFull flag list

Environment overrides:

S2S_REPO=https://github.com/huggingface/speech-to-speech.git S2S_REF=v0.2.10 ./setup.sh
PYTHON_VERSION=3.13 ./setup.sh

setup.sh and run.sh both source config.sh in the same folder. Copy all three files if you move this project.

Run​

./run.sh

Then create Custom Provider pointing to:

ws://localhost:8765/v1/realtime

First launch loads models from cache (about 20–40 seconds). Logs append to server.log. Ctrl+C stops the server.

CommandWhat it does
./run.shStart the server with the models from setup
./run.sh --askPrompt again for STT / LLM / TTS
./run.sh --llm <hf-id>Override the LLM for this launch
PORT=9000 ./run.shListen on port 9000
HOST=127.0.0.1 ./run.shLocalhost only (default 0.0.0.0 = all interfaces)
./run.sh --helpFull flag list

Models are chosen in this order: compact defaults → .mac-run.env from setup → flags / STT_MODEL / LLM_MODEL / TTS_MODEL.

./run.sh --stt mlx-community/parakeet-tdt-0.6b-v3 \
--llm mlx-community/Qwen3-8B-Instruct-2507-4bit \
--tts mlx-community/Kokoro-82M-bf16

LLM_MODEL=mlx-community/Qwen3-8B-Instruct-2507-4bit ./run.sh

Scripts​

setup.sh and run.sh are the only commands you need; config.sh is the shared helper both of them source. Full source is below.

setup.sh
#!/usr/bin/env bash
# One-time setup on any Apple Silicon Mac (M1 or later).
#
# You can copy just these scripts. setup.sh clones
# https://github.com/huggingface/speech-to-speech if speech-to-speech/ is missing.
# It still has to rebuild .venv and download models (neither is portable).
#
# Usage:
# ./setup.sh clone if needed, prompt for models, fetch them
# ./setup.sh --defaults skip prompts; use compact defaults (or env)
# ./setup.sh --no-models skip Hugging Face weight downloads
# ./setup.sh --force-venv delete and rebuild .venv even if it looks fine
# ./setup.sh --llm mlx-community/Qwen3-8B-Instruct-2507-4bit
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck disable=SC1091
. "$SCRIPT_DIR/config.sh"

REPO="$SCRIPT_DIR/speech-to-speech"
S2S_REPO="${S2S_REPO:-https://github.com/huggingface/speech-to-speech.git}"
S2S_REF="${S2S_REF:-}"
CONFIG_FILE="$SCRIPT_DIR/.mac-run.env"
FETCH_MODELS=1
FORCE_VENV=0
MAC_SKIP_PROMPTS=0
# onnxruntime (and several other wheels) have no cp314 builds yet.
PYTHON_VERSION="${PYTHON_VERSION:-3.12}"
OPT_STT_MODEL=""
OPT_LLM_MODEL=""
OPT_TTS_MODEL=""
OPT_STT=""
OPT_TTS=""
OPT_LLM_BACKEND=""

usage() {
cat <<'EOF'
One-time setup for Local Realtime Voice on Apple Silicon.

Usage:
./setup.sh clone huggingface/speech-to-speech if needed, then models
./setup.sh --defaults skip model prompts (compact stack, or STT_MODEL/LLM_MODEL/TTS_MODEL)
./setup.sh --no-models skip Hugging Face weight downloads
./setup.sh --force-venv always rebuild speech-to-speech/.venv
./setup.sh --stt <hf-id> STT weights (default: mlx-community/parakeet-tdt-0.6b-v3)
./setup.sh --llm <hf-id> LLM weights (default: mlx-community/Qwen3-4B-Instruct-2507-4bit)
./setup.sh --tts <hf-id> TTS weights (default: mlx-community/Kokoro-82M-bf16)
./setup.sh --stt-backend NAME STT backend (default: parakeet-tdt)
./setup.sh --llm-backend NAME LLM backend (default: mlx-lm)
./setup.sh --tts-backend NAME TTS backend (default: kokoro)
./setup.sh --help

S2S_REPO=... S2S_REF=v0.2.10 ./setup.sh clone a specific URL / git ref
PYTHON_VERSION=3.13 ./setup.sh override the pinned CPython (default 3.12)

On a TTY, setup asks for STT / LLM / TTS Hugging Face ids. Press Enter to keep
the default (or the last values from .mac-run.env). Flags and env vars skip the
prompt for that field.
EOF
exit 0
}

need_value() {
if [ -z "${2:-}" ]; then
echo "ERROR: $1 needs a value" >&2
exit 1
fi
}

while [ $# -gt 0 ]; do
case "$1" in
--no-models) FETCH_MODELS=0; shift ;;
--force-venv|--force) FORCE_VENV=1; shift ;;
--defaults|--no-prompt) MAC_SKIP_PROMPTS=1; shift ;;
--stt) need_value "$1" "${2:-}"; OPT_STT_MODEL="$2"; shift 2 ;;
--llm) need_value "$1" "${2:-}"; OPT_LLM_MODEL="$2"; shift 2 ;;
--tts) need_value "$1" "${2:-}"; OPT_TTS_MODEL="$2"; shift 2 ;;
--stt=*) OPT_STT_MODEL="${1#*=}"; shift ;;
--llm=*) OPT_LLM_MODEL="${1#*=}"; shift ;;
--tts=*) OPT_TTS_MODEL="${1#*=}"; shift ;;
--stt-backend) need_value "$1" "${2:-}"; OPT_STT="$2"; shift 2 ;;
--llm-backend) need_value "$1" "${2:-}"; OPT_LLM_BACKEND="$2"; shift 2 ;;
--tts-backend) need_value "$1" "${2:-}"; OPT_TTS="$2"; shift 2 ;;
--stt-backend=*) OPT_STT="${1#*=}"; shift ;;
--llm-backend=*) OPT_LLM_BACKEND="${1#*=}"; shift ;;
--tts-backend=*) OPT_TTS="${1#*=}"; shift ;;
-h|--help) usage ;;
*)
echo "ERROR: unknown argument: $1 (try --help)" >&2
exit 1
;;
esac
done

mac_add_common_paths
mac_require_apple_silicon
mac_detect
mac_capture_env_overrides
mac_select_profile
mac_load_run_env "$CONFIG_FILE" || true
mac_apply_model_overrides
mac_prompt_models

echo "==> Checking this Mac"
mac_print_machine
if [ "$MAC_MEM_GB" -lt 8 ]; then
echo "ERROR: ${MAC_MEM_GB}GB is too small. Need about 8GB+ unified memory." >&2
exit 1
fi

echo "==> Checking prerequisites"
if ! command -v git >/dev/null 2>&1; then
echo "ERROR: git not found. Install Xcode Command Line Tools: xcode-select --install" >&2
exit 1
fi
if ! command -v brew >/dev/null 2>&1; then
echo "ERROR: Homebrew not found. Install from https://brew.sh then re-run." >&2
echo " Apple Silicon brew lives in /opt/homebrew; Intel would be /usr/local — this stack needs Apple Silicon." >&2
exit 1
fi
for pkg in portaudio ffmpeg; do
if brew list "$pkg" >/dev/null 2>&1; then
echo " $pkg already installed"
else
echo " installing $pkg"
brew install "$pkg"
fi
done

UV="$(command -v uv || true)"
if [ -z "$UV" ]; then
for cand in "$HOME/.local/bin/uv" "$HOME/.cargo/bin/uv" "$HOME/.langflow/uv/uv"; do
if [ -x "$cand" ]; then
UV="$cand"
break
fi
done
fi
if [ -z "$UV" ]; then
echo " uv not found; installing to ~/.local/bin"
curl -LsSf https://astral.sh/uv/install.sh | sh
mac_add_common_paths
UV="$(command -v uv || true)"
fi
if [ -z "$UV" ]; then
echo "ERROR: uv install finished but uv is not on PATH. Open a new terminal or add ~/.local/bin to PATH." >&2
exit 1
fi
echo " uv: $UV"

echo "==> speech-to-speech checkout"
if [ -f "$REPO/pyproject.toml" ]; then
echo " using existing $REPO"
elif [ -e "$REPO" ]; then
echo "ERROR: $REPO exists but is not a speech-to-speech checkout (no pyproject.toml)." >&2
echo " Move it aside or delete it, then re-run." >&2
exit 1
else
echo " cloning $S2S_REPO"
if [ -n "$S2S_REF" ]; then
git clone --depth 1 --branch "$S2S_REF" "$S2S_REPO" "$REPO"
else
git clone --depth 1 "$S2S_REPO" "$REPO"
fi
echo " cloned $(git -C "$REPO" rev-parse --short HEAD)"
fi

echo "==> Virtualenv (CPython $PYTHON_VERSION)"
cd "$REPO"
VENV_OK=0
if [ "$FORCE_VENV" -eq 0 ] && [ -x .venv/bin/python ] && [ -x .venv/bin/speech-to-speech ]; then
VENV_PY_MM="$(.venv/bin/python -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || true)"
if [ "$VENV_PY_MM" = "$PYTHON_VERSION" ] && .venv/bin/python -c "import mlx, mlx_lm" >/dev/null 2>&1; then
VENV_OK=1
elif [ -n "$VENV_PY_MM" ]; then
echo " existing .venv is Python $VENV_PY_MM; need $PYTHON_VERSION"
fi
fi
if [ "$VENV_OK" -eq 1 ]; then
echo " reusing existing .venv ($(.venv/bin/python --version))"
else
if [ -e .venv ]; then
echo " removing stale .venv"
rm -rf .venv
fi
echo " installing CPython $PYTHON_VERSION via uv (Homebrew 3.14 cannot run onnxruntime)"
"$UV" python install "$PYTHON_VERSION"
"$UV" python pin "$PYTHON_VERSION"
"$UV" sync --python "$PYTHON_VERSION"
if [ ! -x .venv/bin/speech-to-speech ]; then
echo "ERROR: uv sync finished but .venv/bin/speech-to-speech is missing." >&2
exit 1
fi
echo " venv built: $(.venv/bin/python --version)"
fi
mac_ensure_kokoro_deps
mac_tune_engine "$REPO"

mac_write_run_env "$CONFIG_FILE"
echo " wrote $CONFIG_FILE"

if [ "$FETCH_MODELS" -eq 1 ]; then
echo "==> Fetching models (skipped if already cached)"
.venv/bin/python - "$LLM_MODEL" "$STT_MODEL" "$TTS_MODEL" <<'PY'
import sys
from huggingface_hub import snapshot_download

for repo in sys.argv[1:]:
print(f" {repo}", flush=True)
snapshot_download(repo_id=repo)
print(" all models cached")
PY
else
echo "==> Skipping model download (--no-models)"
fi

if [ "$LLM_BACKEND" = "mlx-lm" ]; then
echo "==> Smoke test: load the LLM and generate a few tokens"
.venv/bin/python - "$LLM_MODEL" <<'PY'
import sys, time
from mlx_lm import load, stream_generate

model, tok = load(sys.argv[1])
msgs = [{"role": "user", "content": "Say hello in five words."}]
kwargs = {"tokenize": False, "add_generation_prompt": True}
try:
p = tok.apply_chat_template(msgs, enable_thinking=False, **kwargs)
except TypeError:
p = tok.apply_chat_template(msgs, **kwargs)
t0 = time.time(); n = 0; out = []
for r in stream_generate(model, tok, p, max_tokens=16):
out.append(r.text); n += 1
dt = time.time() - t0
print(f" reply: {''.join(out).strip()!r}")
print(f" {n} tokens in {dt:.2f}s (~{n/dt:.0f} tok/s incl. prefill)")
PY
else
echo "==> Skipping mlx-lm smoke test (LLM backend is $LLM_BACKEND)"
fi

cat <<EOF

==> Setup complete.
$PROFILE_NOTE

Start the server: ./run.sh
Then connect to: ws://localhost:8765/v1/realtime

First launch loads models from cache (~20-40s).
EOF
run.sh
#!/usr/bin/env bash
# Local Realtime Voice server — OpenAI Realtime API at ws://HOST:PORT/v1/realtime
#
# Works on any Apple Silicon Mac. Compact defaults, or whatever setup.sh saved:
# ./run.sh
# ./run.sh --llm mlx-community/Qwen3-8B-Instruct-2507-4bit
# LLM_MODEL=mlx-community/Qwen3-8B-Instruct-2507-4bit ./run.sh
#
# PORT=9000 ./run.sh listen on 9000
# HOST=127.0.0.1 ./run.sh localhost only (default 0.0.0.0 = all interfaces)
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck disable=SC1091
. "$SCRIPT_DIR/config.sh"

LOG_FILE="$SCRIPT_DIR/server.log"
CONFIG_FILE="$SCRIPT_DIR/.mac-run.env"
PORT="${PORT:-8765}"
HOST="${HOST:-0.0.0.0}"
MAC_SKIP_PROMPTS=1
OPT_STT_MODEL=""
OPT_LLM_MODEL=""
OPT_TTS_MODEL=""
OPT_STT=""
OPT_TTS=""
OPT_LLM_BACKEND=""

usage() {
cat <<'EOF'
Local Realtime Voice server (OpenAI Realtime WebSocket).

Usage:
./run.sh
./run.sh --stt <hf-id> --llm <hf-id> --tts <hf-id>
./run.sh --ask prompt for STT / LLM / TTS (Enter keeps current)
PORT=9000 ./run.sh
HOST=127.0.0.1 ./run.sh localhost only; default binds all interfaces

Models default to the compact stack, then .mac-run.env from setup.sh, then
flags / STT_MODEL / LLM_MODEL / TTS_MODEL env vars.
EOF
exit 0
}

need_value() {
if [ -z "${2:-}" ]; then
echo "ERROR: $1 needs a value" >&2
exit 1
fi
}

while [ $# -gt 0 ]; do
case "$1" in
--ask|--prompt) MAC_SKIP_PROMPTS=0; shift ;;
--stt) need_value "$1" "${2:-}"; OPT_STT_MODEL="$2"; shift 2 ;;
--llm) need_value "$1" "${2:-}"; OPT_LLM_MODEL="$2"; shift 2 ;;
--tts) need_value "$1" "${2:-}"; OPT_TTS_MODEL="$2"; shift 2 ;;
--stt=*) OPT_STT_MODEL="${1#*=}"; shift ;;
--llm=*) OPT_LLM_MODEL="${1#*=}"; shift ;;
--tts=*) OPT_TTS_MODEL="${1#*=}"; shift ;;
--stt-backend) need_value "$1" "${2:-}"; OPT_STT="$2"; shift 2 ;;
--llm-backend) need_value "$1" "${2:-}"; OPT_LLM_BACKEND="$2"; shift 2 ;;
--tts-backend) need_value "$1" "${2:-}"; OPT_TTS="$2"; shift 2 ;;
--stt-backend=*) OPT_STT="${1#*=}"; shift ;;
--llm-backend=*) OPT_LLM_BACKEND="${1#*=}"; shift ;;
--tts-backend=*) OPT_TTS="${1#*=}"; shift ;;
-h|--help) usage ;;
*)
echo "ERROR: unknown argument: $1 (try --help)" >&2
exit 1
;;
esac
done

mac_add_common_paths
mac_require_apple_silicon
mac_detect
mac_capture_env_overrides
mac_select_profile
if mac_load_run_env "$CONFIG_FILE"; then
echo "==> loaded $CONFIG_FILE"
fi
mac_apply_model_overrides
mac_prompt_models
echo "==> $PROFILE_NOTE"

if [ ! -f "$SCRIPT_DIR/speech-to-speech/pyproject.toml" ]; then
echo "ERROR: speech-to-speech/ is missing." >&2
echo "Run ./setup.sh — it clones https://github.com/huggingface/speech-to-speech" >&2
exit 1
fi

cd "$SCRIPT_DIR/speech-to-speech"

if [ ! -x .venv/bin/speech-to-speech ]; then
echo "ERROR: .venv is missing or not built for this machine." >&2
echo "Run ./setup.sh first (the venv is NOT portable between Macs)." >&2
exit 1
fi
mac_ensure_kokoro_deps
mac_tune_engine "$SCRIPT_DIR/speech-to-speech"

CMD=(
.venv/bin/speech-to-speech
serve
--stt "$STT"
--llm_backend "$LLM_BACKEND"
--model_name "$LLM_MODEL"
--tts "$TTS"
--device "$DEVICE"
--host "$HOST"
--port "$PORT"
--llm_gen_max_new_tokens "$LLM_MAX_NEW_TOKENS"
)
mac_add_model_cli_args

if grep -q llm_prompt_cache arguments_classes/language_model_arguments.py src/speech_to_speech/arguments_classes/language_model_arguments.py 2>/dev/null; then
CMD+=(--llm_prompt_cache)
fi

echo "==> ws://${HOST}:${PORT}/v1/realtime"

# Do not use `cmd | tee`: Ctrl+C kills tee, Python's non-daemon threads keep
# running, and speech-to-speech's SIGINT handler ignores a second Ctrl+C.
SERVER_PID=""
stop_server() {
_pid="${SERVER_PID:-}"
SERVER_PID=""
trap - INT TERM
if [ -n "$_pid" ]; then
echo "==> Stopping..." >&2
kill -INT "$_pid" 2>/dev/null || true
_n=0
while [ "$_n" -lt 20 ]; do
kill -0 "$_pid" 2>/dev/null || break
sleep 0.1
_n=$((_n + 1))
done
if kill -0 "$_pid" 2>/dev/null; then
echo "==> Force kill" >&2
kill -KILL "$_pid" 2>/dev/null || true
fi
wait "$_pid" 2>/dev/null || true
fi
exit 130
}
trap stop_server INT TERM

"${CMD[@]}" > >(trap '' INT; tee -a "$LOG_FILE") 2>&1 &
SERVER_PID=$!
_status=0
wait "$SERVER_PID" || _status=$?
trap - INT TERM
exit "$_status"
config.sh
#!/usr/bin/env bash
# Shared Mac detection + model stack. Sourced by setup.sh and run.sh.
# Written for macOS's stock bash 3.2 — no bash 4+ constructs.

mac_add_common_paths() {
PATH="/opt/homebrew/bin:/usr/local/bin:${HOME}/.local/bin:${HOME}/.cargo/bin:${PATH:-}"
export PATH
}

mac_require_apple_silicon() {
if [ "$(uname -s)" != "Darwin" ]; then
echo "ERROR: this stack runs on macOS only." >&2
exit 1
fi
if [ "$(uname -m)" != "arm64" ]; then
echo "ERROR: Apple Silicon (M1 or later) is required." >&2
echo "STT, the local LLM, and TTS all run on MLX/Metal, which does not exist on Intel Macs." >&2
exit 1
fi
}

mac_detect() {
MAC_CHIP="$(sysctl -n machdep.cpu.brand_string 2>/dev/null || echo unknown)"
MAC_MEM_GB=$(( $(sysctl -n hw.memsize) / 1024 / 1024 / 1024 ))
MAC_GPU_CORES="$(system_profiler SPDisplaysDataType 2>/dev/null | awk -F': ' '/Total Number of Cores/{print $2; exit}')"
}

# Compact defaults so any Apple Silicon Mac can run it. Callers may then load a
# saved .mac-run.env, apply CLI/env overrides, and optionally prompt.
mac_select_profile() {
PROFILE=compact
STT=parakeet-tdt
STT_MODEL=mlx-community/parakeet-tdt-0.6b-v3
LLM_BACKEND=mlx-lm
LLM_MODEL=mlx-community/Qwen3-4B-Instruct-2507-4bit
TTS=kokoro
TTS_MODEL=mlx-community/Kokoro-82M-bf16
DEVICE=mps
LANGUAGE=en
KOKORO_LANG_CODE=b
KOKORO_VOICE=bm_fable
LLM_MAX_NEW_TOKENS=128
QWEN3_TTS_QUANT=""
QWEN3_TTS_SPEAKER=""
mac_refresh_profile_note
}

mac_refresh_profile_note() {
PROFILE_NOTE="$LLM_MODEL | STT $STT_MODEL | TTS $TTS_MODEL"
}

mac_trim() {
echo "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'
}

mac_require_nonempty() {
_label="$1"
_val="$2"
if [ -z "$_val" ]; then
echo "ERROR: $_label must not be empty." >&2
exit 1
fi
}

# Capture CLI/env overrides before mac_select_profile overwrites the names.
# Call once at the top of setup.sh / run.sh after parsing flags into OPT_*.
mac_capture_env_overrides() {
[ -n "${OPT_STT_MODEL:-}" ] || OPT_STT_MODEL="${STT_MODEL:-}"
[ -n "${OPT_LLM_MODEL:-}" ] || OPT_LLM_MODEL="${LLM_MODEL:-}"
[ -n "${OPT_TTS_MODEL:-}" ] || OPT_TTS_MODEL="${TTS_MODEL:-}"
[ -n "${OPT_STT:-}" ] || OPT_STT="${STT:-}"
[ -n "${OPT_TTS:-}" ] || OPT_TTS="${TTS:-}"
[ -n "${OPT_LLM_BACKEND:-}" ] || OPT_LLM_BACKEND="${LLM_BACKEND:-}"
}

mac_apply_model_overrides() {
[ -n "${OPT_STT:-}" ] && STT="$OPT_STT"
[ -n "${OPT_TTS:-}" ] && TTS="$OPT_TTS"
[ -n "${OPT_LLM_BACKEND:-}" ] && LLM_BACKEND="$OPT_LLM_BACKEND"
[ -n "${OPT_STT_MODEL:-}" ] && STT_MODEL="$OPT_STT_MODEL"
[ -n "${OPT_LLM_MODEL:-}" ] && LLM_MODEL="$OPT_LLM_MODEL"
[ -n "${OPT_TTS_MODEL:-}" ] && TTS_MODEL="$OPT_TTS_MODEL"
mac_refresh_profile_note
}

# Prompt for STT / LLM / TTS Hugging Face ids. Enter keeps the current value.
# Skips when stdin is not a TTY, when MAC_SKIP_PROMPTS=1 (--defaults), or when
# that field was already set on the command line / environment.
mac_prompt_models() {
if [ "${MAC_SKIP_PROMPTS:-0}" -eq 1 ]; then
return 0
fi
if [ ! -t 0 ]; then
return 0
fi

echo "==> Models — press Enter to keep the default, or type a Hugging Face id"
[ -z "${OPT_STT_MODEL:-}" ] && mac_prompt_one STT_MODEL "STT"
[ -z "${OPT_LLM_MODEL:-}" ] && mac_prompt_one LLM_MODEL "LLM"
[ -z "${OPT_TTS_MODEL:-}" ] && mac_prompt_one TTS_MODEL "TTS"
mac_refresh_profile_note
}

mac_prompt_one() {
_var="$1"
_label="$2"
eval "_def=\"\$$_var\""
printf " %s [%s]: " "$_label" "$_def" >&2
_ans=""
read -r _ans || _ans=""
_ans="$(mac_trim "$_ans")"
if [ -n "$_ans" ]; then
eval "$_var=\"\$_ans\""
fi
eval "_now=\"\$$_var\""
mac_require_nonempty "$_label" "$_now"
}

mac_print_machine() {
echo " $MAC_CHIP | ${MAC_MEM_GB}GB RAM | GPU cores: ${MAC_GPU_CORES:-unknown}"
echo " models: $PROFILE_NOTE"
}

mac_write_run_env() {
_cfg="$1"
mac_refresh_profile_note
cat > "$_cfg" <<EOF
# Generated by setup.sh for this Mac. Re-run setup.sh to refresh.
PROFILE='$PROFILE'
LLM_MODEL='$LLM_MODEL'
STT='$STT'
STT_MODEL='$STT_MODEL'
LLM_BACKEND='$LLM_BACKEND'
TTS='$TTS'
TTS_MODEL='$TTS_MODEL'
DEVICE='$DEVICE'
LANGUAGE='$LANGUAGE'
KOKORO_LANG_CODE='$KOKORO_LANG_CODE'
KOKORO_VOICE='$KOKORO_VOICE'
LLM_MAX_NEW_TOKENS='$LLM_MAX_NEW_TOKENS'
QWEN3_TTS_QUANT='$QWEN3_TTS_QUANT'
QWEN3_TTS_SPEAKER='$QWEN3_TTS_SPEAKER'
PROFILE_NOTE='$PROFILE_NOTE'
EOF
}

mac_load_run_env() {
_cfg="$1"
if [ -f "$_cfg" ]; then
# shellcheck disable=SC1090
. "$_cfg"
mac_refresh_profile_note
return 0
fi
return 1
}

# Append handler-specific model flags onto the CMD array in the caller.
mac_add_model_cli_args() {
case "$STT" in
parakeet-tdt)
[ -n "$STT_MODEL" ] && CMD+=(--parakeet_tdt_model_name "$STT_MODEL")
if [ -n "${LANGUAGE:-}" ] && [ "$LANGUAGE" != "auto" ]; then
CMD+=(--parakeet_tdt_language "$LANGUAGE")
fi
;;
whisper|whisper-mlx)
[ -n "$STT_MODEL" ] && CMD+=(--stt_model_name "$STT_MODEL")
;;
mlx-audio-whisper)
[ -n "$STT_MODEL" ] && CMD+=(--mlx_audio_whisper_model_name "$STT_MODEL")
;;
esac
case "$TTS" in
kokoro)
[ -n "$TTS_MODEL" ] && CMD+=(--kokoro_model_name "$TTS_MODEL")
CMD+=(--kokoro_lang_code "${KOKORO_LANG_CODE:-b}")
CMD+=(--kokoro_voice "${KOKORO_VOICE:-bm_fable}")
;;
qwen3)
[ -n "$TTS_MODEL" ] && CMD+=(--qwen3_tts_model_name "$TTS_MODEL")
[ -n "${QWEN3_TTS_QUANT:-}" ] && CMD+=(--qwen3_tts_mlx_quantization "$QWEN3_TTS_QUANT")
[ -n "${QWEN3_TTS_SPEAKER:-}" ] && CMD+=(--qwen3_tts_speaker "$QWEN3_TTS_SPEAKER")
;;
esac
}

mac_find_uv() {
if [ -n "${UV:-}" ] && [ -x "$UV" ]; then
return 0
fi
UV="$(command -v uv || true)"
if [ -z "$UV" ]; then
for cand in "$HOME/.local/bin/uv" "$HOME/.cargo/bin/uv" "$HOME/.langflow/uv/uv"; do
if [ -x "$cand" ]; then
UV="$cand"
break
fi
done
fi
[ -n "$UV" ] && [ -x "$UV" ]
}

# misaki is installed, but Hugging Face does not pull misaki[en] → num2words.
# Kokoro on MLX imports misaki.en and crashes without it.
mac_ensure_kokoro_deps() {
if .venv/bin/python -c "import num2words, misaki.en" >/dev/null 2>&1; then
return 0
fi
echo "==> Installing Kokoro TTS extras (num2words)"
if ! mac_find_uv; then
echo "ERROR: uv not found; cannot install num2words for Kokoro." >&2
echo "Re-run ./setup.sh after uv is on PATH." >&2
exit 1
fi
"$UV" pip install --python .venv/bin/python "num2words>=0.5.14"
if ! .venv/bin/python -c "import num2words, misaki.en" >/dev/null 2>&1; then
echo "ERROR: Kokoro still cannot import misaki.en after installing num2words." >&2
echo "Try: uv pip install --python speech-to-speech/.venv/bin/python 'misaki[en]'" >&2
exit 1
fi
}

# Hugging Face hardcodes extra Kokoro languages and a chat-template kwarg that
# crashes this stack. Apply small, idempotent edits to the clone — no extra files.
mac_tune_engine() {
_root="$1"
_py="$_root/.venv/bin/python"
if [ ! -x "$_py" ]; then
_py="$(command -v python3 || true)"
fi
if [ -z "$_py" ]; then
echo "ERROR: python3 not found; cannot tune speech-to-speech checkout." >&2
exit 1
fi
echo "==> Tuning speech-to-speech (English Kokoro, Qwen chat template)"
"$_py" - "$_root" <<'PY'
from __future__ import annotations

import sys
from pathlib import Path

root = Path(sys.argv[1])
done: list[str] = []
missing: list[str] = []


def locate(*rel: str) -> Path | None:
for name in rel:
path = root / name
if path.is_file():
return path
return None


def patch(path: Path | None, marker: str, old: str, new: str, label: str) -> None:
if path is None:
missing.append(label)
return
text = path.read_text()
if marker in text:
done.append(f"{label} (already)")
return
if old not in text:
missing.append(label)
return
path.write_text(text.replace(old, new, 1))
done.append(label)


kokoro = locate(
"src/speech_to_speech/TTS/kokoro_handler.py",
"TTS/kokoro_handler.py",
)
if kokoro is None:
missing.append("kokoro-preload-noop")
else:
text = kokoro.read_text()
marker = "lrv-tune: skip multilingual preload"
if marker in text:
done.append("kokoro-preload-noop (already)")
else:
replaced = False
for old in (
" def _preload_multilingual_voices(self) -> None:\n",
" def _preload_multilingual_voices(self):\n",
):
if old in text:
kokoro.write_text(
text.replace(old, old + f" return # {marker}\n", 1)
)
done.append("kokoro-preload-noop")
replaced = True
break
if not replaced:
missing.append("kokoro-preload-noop")

sig = locate(
"src/speech_to_speech/LLM/tool_call/signature_from_schema.py",
"LLM/tool_call/signature_from_schema.py",
)
patch(
sig,
"lrv-tune: required params first",
" return inspect.Signature(params)",
" params.sort(key=lambda p: p.default is not inspect.Parameter.empty) # lrv-tune: required params first\n return inspect.Signature(params)",
"tool-signature",
)

ft = locate(
"src/speech_to_speech/LLM/tool_call/function_tool.py",
"LLM/tool_call/function_tool.py",
)
patch(
ft,
"lrv-tune: tool signature fallback",
" signature = signature_from_schema(self.parameters)",
""" try: # lrv-tune: tool signature fallback
signature = signature_from_schema(self.parameters)
except ValueError:
signature = "()" """,
"tool-signature-fallback",
)

lm = locate(
"src/speech_to_speech/LLM/language_model.py",
"LLM/language_model.py",
)
patch(
lm,
"lrv-tune: skip invalid tools",
' function_tools = [FunctionTool(**t.model_dump()) for t in raw_tools if t.type == "function"]',
""" function_tools = [] # lrv-tune: skip invalid tools
for t in raw_tools:
try:
if t.type != "function":
continue
function_tools.append(FunctionTool(**t.model_dump()))
except (TypeError, ValueError, AttributeError):
continue""",
"llm-tools",
)
patch(
lm,
"lrv-tune: empty chat",
" chat_messages = chat.to_transformers_chat()\n chat_input = self.tokenizer.apply_chat_template(chat_messages, tokenize=True)",
""" chat_messages = chat.to_transformers_chat()
if not chat_messages:
return # lrv-tune: empty chat
chat_input = self.tokenizer.apply_chat_template(chat_messages, tokenize=True)""",
"llm-empty-chat",
)
patch(
lm,
"lrv-tune: chat-template",
""" chat_prompt = self.tokenizer.apply_chat_template(
chat_messages, tokenize=False, add_generation_prompt=True, enable_thinking=False
)""",
""" try: # lrv-tune: chat-template
chat_prompt = self.tokenizer.apply_chat_template(
chat_messages, tokenize=False, add_generation_prompt=True, enable_thinking=False
)
except (TypeError, ValueError):
chat_prompt = self.tokenizer.apply_chat_template(
chat_messages, tokenize=False, add_generation_prompt=True
)""",
"llm-chat-template",
)

log = locate(
"src/speech_to_speech/pipeline/transcript_logging.py",
"pipeline/transcript_logging.py",
)
patch(
log,
"lrv-tune: log exc message",
' target.log(level, "%s (%s)", message, type(exc).__name__)',
' target.log(level, "%s (%s): %s", message, type(exc).__name__, exc) # lrv-tune: log exc message',
"log-exc",
)

print(" " + ", ".join(done) if done else " no changes")
if missing:
print(" skipped (pattern not in this checkout): " + ", ".join(missing))
PY
}