#!/bin/bash
# pepito transcription command, example based on whisper.cpp (whisper-cli).
# Requires pepito 26.61 or later.
#
# Set the path of this file as the transcription command in pepito (or a
# command line that runs it). pepito passes the job in environment
# variables (PEPITO_INPUT_PATH, PEPITO_OUTPUT_PATH, ...).
# It must write an SRT file to PEPITO_OUTPUT_PATH and exit 0.
# Any non-zero exit code is reported by pepito as a failed transcription,
# with the end of stderr as the message.
#
# This script never downloads anything: install whisper.cpp and copy the
# model beforehand (see the page that publishes this file).
#
# Not used here: PEPITO_TASK and the other variables of the recording
# (absent when Settings runs the Test button).
set -euo pipefail

# Model file. WHISPER_MODEL is specific to this script (outside the PEPITO_
# namespace, which pepito reserves and clears); pepito ignores it.
MODEL="${WHISPER_MODEL:-$HOME/Library/Application Support/whisper/ggml-large-v3-turbo.bin}"

# Preflight checks.
if ! command -v whisper-cli >/dev/null 2>&1; then
  echo "whisper-cli not found in PATH (brew install whisper.cpp)" >&2
  exit 1
fi
if [ ! -f "$MODEL" ]; then
  echo "model not found: $MODEL" >&2
  exit 1
fi
case "${PEPITO_OUTPUT_PATH:-}" in
  *.srt) ;;
  *)
    echo "PEPITO_OUTPUT_PATH must end with .srt: ${PEPITO_OUTPUT_PATH:-<unset>}" >&2
    exit 1
    ;;
esac

# Language: whisper-cli defaults to English, so always pass it.
# PEPITO_LANGUAGE_CODE is an ISO 639-1 code ("fr") or "auto", which whisper-cli
# understands as is.
#
# -osrt -of <base>: whisper-cli appends ".srt" to the base name.
# -np: no progress or diagnostic output; whisper-cli still prints the
# segments on stdout, hence >/dev/null (pepito logs stdout privately, but
# there is no reason to print the transcript). Errors stay on stderr.
whisper-cli -m "$MODEL" -f "$PEPITO_INPUT_PATH" -l "$PEPITO_LANGUAGE_CODE" \
  -osrt -of "${PEPITO_OUTPUT_PATH%.srt}" -np >/dev/null
