#!/bin/sh
# Continuous dictation: types each phrase into the focused window when you pause. Run again to stop.
set -eu
model=${WHISPER_DICTATE_MODEL:-large-v3-turbo}
lang=${WHISPER_DICTATE_LANG:-auto}
vth=${WHISPER_DICTATE_VAD:-0.6}
sil=${WHISPER_DICTATE_SILENCE:-0.003}
data=${XDG_DATA_HOME:-$HOME/.local/share}/whisper
run=${XDG_RUNTIME_DIR:?}/whisper-dictate
bin=$data/ggml-$model.bin
mkdir -p "$data" "$run"

note() { command -v notify-send >/dev/null && notify-send -a whisper-dictate -t 1500 "$1" || true; }

if [ -f "$run/pgid" ]; then
	kill -TERM -- "-$(cat "$run/pgid")" 2>/dev/null || true
	rm -f "$run/pgid"
	note "Dictation off"
	exit 0
fi

if [ ! -f "$bin" ]; then
	note "Downloading Whisper model $model"
	curl -fL -o "$bin.part" "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-$model.bin"
	mv "$bin.part" "$bin"
fi

export bin lang vth sil
setsid sh -c '
	whisper-stream -m "$bin" -l "$lang" --step 0 --length 8000 -ac 512 -vth "$vth" --silence-thold "$sil" 2>/dev/null |
	sed -un "s/^\[[^]]*-->[^]]*\] *//; T; s/^- *//; p" |
	while IFS= read -r text; do
		case $text in "" | "["* | "("* | "*"* | "Thank you." | "Thanks for watching!" | "Takk for meg." ) continue ;; esac
		wtype -- "$text "
	done
' &
echo $! >"$run/pgid"
note "Dictation on"
