#!/usr/bin/env bash
# One-time setup for the Real-ESRGAN upscaler: Python environment + model weights (about 1 GB of packages, 72 MB of weights).
# Safe to re-run; it only downloads what is missing. Needs python3 (3.9+) or uv, curl, and an internet connection.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
cd "$here"

if [ ! -x venv/bin/python ]; then
  if command -v uv >/dev/null 2>&1; then
    uv venv --python 3.11 venv >/dev/null
    uv pip install --python venv/bin/python -r requirements.txt
  else
    python3 -m venv venv
    venv/bin/pip install --quiet --upgrade pip
    venv/bin/pip install --quiet -r requirements.txt
  fi
fi

mkdir -p weights
dl() {  # name url sha256
  if [ ! -f "weights/$1" ]; then
    echo "downloading $1"
    curl -fsSL --retry 3 -o "weights/$1.part" "$2" && mv "weights/$1.part" "weights/$1"
  fi
  got="$(shasum -a 256 "weights/$1" | cut -d' ' -f1)"
  if [ "$got" != "$3" ]; then echo "checksum mismatch for $1 — delete weights/$1 and run again"; exit 1; fi
}
dl RealESRGAN_x4plus.pth     https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth     4fa0d38905f75ac06eb49a7951b426670021be3018265fd191d2125df9d682f1
dl realesr-general-x4v3.pth  https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth 8dc7edb9ac80ccdc30c3a5dca6616509367f05fbc184ad95b731f05bece96292

venv/bin/python -c "import torch, cv2; print('upscaler ready: torch', torch.__version__, '| gpu:', 'mps' if torch.backends.mps.is_available() else ('cuda' if torch.cuda.is_available() else 'cpu'))"
