#!/usr/bin/env bash
# Usage: stt/setup_voice.sh            (once per user; no sudo)
# Sets up voice typing for the biniKey IBus engine:
#   1. a Python venv at ~/.local/share/binikey/voice-venv with sherpa-onnx, numpy,
#      soundfile (and faster-whisper for the optional Whisper / PhoWhisper models);
#   2. the default model, zipformer-vi 30M int8 (k2-fsa release asr-models, sha256
#      checked; upstream model card hynt/Zipformer-30M-RNNT-6000h, licence
#      CC-BY-NC-ND-4.0: free, non-commercial use only), into ~/.local/share/binikey/models/;
#   3. ~/.config/binikey/config.json "voice_model" pointing at it (other keys kept).
# Why zipformer-vi: best WER on VIVOS (5.7 %) and 25x faster than Whisper large-v3-turbo
#   in stt/bench_stt.py (2026-12-04, asrock CPU, see the wiki page).
# 2026-12-04 · created · wiki: http://localhost:3000/wiki/apps/bogo#l1
set -euo pipefail
B=$HOME/.local/share/binikey
V=$B/voice-venv
M=$B/models
NAME=sherpa-onnx-zipformer-vi-30M-int8-2026-02-09
URL=https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/$NAME.tar.bz2
SHA=da8b637947091829d7ee9eda23da2a4ec7caa399233a3f4e34eb719fb2ea6b9b   # same as rock3a/a14/ai/fetch_ai.sh
mkdir -p "$M"
[[ -x $V/bin/python ]] || python3 -m venv "$V"
"$V/bin/pip" install -q --upgrade pip
"$V/bin/pip" install -q sherpa-onnx numpy soundfile "faster-whisper>=1.2"
if [[ ! -f $M/$NAME/tokens.txt ]]; then
  curl -fsSL -o "$M/$NAME.tar.bz2.part" "$URL"
  echo "$SHA  $M/$NAME.tar.bz2.part" | sha256sum -c --quiet
  tar xjf "$M/$NAME.tar.bz2.part" -C "$M" && rm "$M/$NAME.tar.bz2.part"
fi
mkdir -p "$HOME/.config/binikey"
"$V/bin/python" - "$HOME/.config/binikey/config.json" "sherpa:$M/$NAME" <<'PY'
import json, sys, os
p, m = sys.argv[1], sys.argv[2]
c = {}
if os.path.exists(p):
    try: c = json.load(open(p))
    except ValueError: pass
c["voice_model"] = m
json.dump(c, open(p, "w"), indent=1)
print("voice_model =", m)
PY
