#!/usr/bin/env bash
# TBDub Student V1.1: give an existing talking-head clip a NEW line of dialogue.
# What the LEJ Video Lab ran on a DGX Spark (GB10, aarch64), Nov 14 2026.
# Usage: tbdub-revoice.sh <source.mp4> <new-line.wav> <out-dir> [seconds]
#   TBDUB_DIR   = your clone of https://github.com/TaoLiveAIGC/TBDub (with the detector patch below)
#   TBDUB_PY    = python of a venv with TBDub's requirements, mediapipe==0.10.18 on aarch64
#   TBDUB_CKPT  = folder with tbdub_student.safetensors, Wan2.2_VAE.safetensors, HuBERT (as safetensors), face_landmarker.task
# Detector patch (one line in TBDub's preprocessing): make the MediaPipe FaceDetection model_selection read
#   int(os.environ.get("TBDUB_MP_MODEL_SELECTION", "1")) so 0 (short-range) can be chosen for close-framed hosts.
set -euo pipefail
SRC="$1"; WAV="$2"; OUT="$3"; LEN="${4:-6}"
mkdir -p "$OUT"
# trim picture (no audio) and the new line to the same length
ffmpeg -loglevel error -y -i "$SRC" -t "$LEN" -an -c:v libx264 -crf 14 -pix_fmt yuv420p "$OUT/source.mp4"
ffmpeg -loglevel error -y -i "$WAV" -t "$LEN" "$OUT/driving.wav"
t0=$(date +%s)
( cd "$TBDUB_DIR" && TBDUB_MP_MODEL_SELECTION=0 "$TBDUB_PY" inference.py \
    --video "$OUT/source.mp4" --audio "$OUT/driving.wav" \
    --inference-mode student --num-student-steps 2 --sigma-shift 1.0 --motion-from-latents --seed 42 \
    --checkpoint-dir "$TBDUB_CKPT" --output-dir "$OUT/out" )
echo "wall $(( $(date +%s) - t0 )) s for ${LEN} s of audio (model load included)"
