#!/usr/bin/env bash
# piper student — train FROM SCRATCH on the OmniVoice-generated dataset.
# run on the workstation (gfx1100, ROCm) AFTER the LLM CPT frees the GPU.
#
# prereq: piper-train installed from rhasspy/piper (src/python): torch + pytorch-lightning.
#         espeak-ng installed. piper/dataset/ built (build_dataset.py) & sanity-checked.
set -euo pipefail
cd "$(dirname "$0")/../.."          # → esp32-whisper-fine-tune/
export HSA_OVERRIDE_GFX_VERSION=11.0.0

DATASET=tts/piper/dataset
TRAIN=tts/piper/train

# 1. preprocess: text → espeak-ng phonemes → training cache
python -m piper_train.preprocess \
  --language ru --input-dir "$DATASET" --output-dir "$TRAIN" \
  --dataset-format ljspeech --single-speaker --sample-rate 22050

# 2. train from scratch (NO --resume_from_checkpoint), medium = CPU-real-time target
python -m piper_train \
  --dataset-dir "$TRAIN" --accelerator gpu --devices 1 \
  --batch-size 16 --quality medium --precision 32 \
  --max_epochs 4000 --checkpoint-epochs 100 --validation-split 0.02

# 3. export best checkpoint → ONNX (adjust version_/last.ckpt path to your run)
CKPT=$(ls -t "$TRAIN"/lightning_logs/version_*/checkpoints/*.ckpt | head -1)
python -m piper_train.export_onnx "$CKPT" tts/piper/maven.onnx
cp "$TRAIN"/config.json tts/piper/maven.onnx.json
echo "[✓] exported → tts/piper/maven.onnx (+ .json). scp both to homesrv."
