#!/usr/bin/env bash
# Transcribe with whisper.cpp (CPU, Apple Metal, CUDA, Vulkan...). Produces .txt, .srt and .vtt.
#
# One-time setup:
#   git clone https://github.com/ggml-org/whisper.cpp && cd whisper.cpp
#   cmake -B build && cmake --build build -j --config Release
#   sh ./models/download-ggml-model.sh large-v3-turbo   # or base.en, small, medium ...
#
# Usage:
#   WHISPER_CPP=~/whisper.cpp scripts/transcribe_whispercpp.sh interview.mp3 [model] [language]
set -euo pipefail

in="${1:?usage: transcribe_whispercpp.sh <audio> [model-name] [language|auto]}"
model="${2:-large-v3-turbo}"
lang="${3:-auto}"
root="${WHISPER_CPP:-$HOME/whisper.cpp}"
bin="$root/build/bin/whisper-cli"
mfile="$root/models/ggml-${model}.bin"

[[ -x "$bin" ]] || { echo "whisper-cli not found at $bin (build whisper.cpp first)" >&2; exit 1; }
[[ -f "$mfile" ]] || { echo "model not found: $mfile (run models/download-ggml-model.sh $model)" >&2; exit 1; }
command -v ffmpeg >/dev/null || { echo "ffmpeg is required to convert audio" >&2; exit 1; }

base="${in%.*}"
wav="$(mktemp -t stt).wav"
trap 'rm -f "$wav"' EXIT

# whisper.cpp expects 16 kHz mono 16-bit PCM WAV
ffmpeg -hide_banner -loglevel error -y -i "$in" -ar 16000 -ac 1 -c:a pcm_s16le "$wav"

"$bin" -m "$mfile" -f "$wav" -l "$lang" -otxt -osrt -ovtt -of "$base"
echo "wrote $base.txt $base.srt $base.vtt"
