#!/usr/bin/env bash
#
# Downloads the face models from their authors and converts them into the
# ONNX files FaceMaker runs, in this folder.
#
# Usage:  ./models/download.sh           everything that's missing
#         ./models/download.sh --check   list what's here and what isn't
#
# Every checkpoint comes from the place its authors publish it (NVIDIA's CDN,
# GitHub releases, or the Google Drive links in the authors' READMEs), and is
# converted here with the authors' own model code, cloned at a fixed commit.
# Nothing is redistributed, so each model keeps its own licence: see the
# README for which are non-commercial.
#
# Needs Python 3.10 to 3.13, git, curl and about 6 GB of free space. The
# converters run in a virtual environment, models/.venv, and the downloads
# and the authors' code are kept in models/.work, which can be deleted once
# the models are made.
#
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
WORK="$HERE/.work"
DOWNLOADS="$WORK/downloads"
REPOS="$WORK/repos"
VENV="$HERE/.venv"
PY="$VENV/bin/python"

# The files the app reads
OUTPUTS=(
	mobilestylegan_ffhq_v2-map.onnx mobilestylegan_ffhq_v2-synth.onnx
	stylegan2-ffhq-map.onnx stylegan2-ffhq-synth.onnx stylegan2-ffhq-wavg.f32
	stylegan_ffhq_age_w_boundary.fp32.f32 stylegan_ffhq_gender_w_boundary.fp32.f32
	stylegan_ffhq_smile_w_boundary.fp32.f32 stylegan_ffhq_eyeglasses_w_boundary.fp32.f32
	stylegan_ffhq_pose_w_boundary.fp32.f32
	stylegan2-metfaces-map.onnx stylegan2-metfaces-synth.onnx
	gancontrol-ffhq-map.onnx gancontrol-ffhq-synth.onnx gancontrol-ffhq-orientation.onnx
	gancontrol-ffhq-age.onnx gancontrol-ffhq-hair.onnx gancontrol-ffhq-gamma.onnx
	gancontrol-ffhq-expression.onnx
	semantic-celeba-synth.onnx
	e4e-ffhq-encoder.onnx
	w600k_r50.onnx
)

if [ "${1:-}" = "--check" ]; then
	missing=0
	for file in "${OUTPUTS[@]}"; do
		if [ -f "$HERE/$file" ]; then echo "  ✓ $file"; else echo "  ✗ $file"; missing=1; fi
	done
	exit $missing
fi

mkdir -p "$DOWNLOADS" "$REPOS"

# ---------------------------------------------------------------------------
# The Python environment for the converters
# ---------------------------------------------------------------------------
if [ ! -x "$PY" ]; then
	PYTHON=""
	for candidate in python3.13 python3.12 python3.11 python3.10 python3; do
		if command -v "$candidate" >/dev/null 2>&1 \
			&& "$candidate" -c 'import sys; sys.exit(not ((3, 10) <= sys.version_info[:2] <= (3, 13)))'; then
			PYTHON="$candidate"
			break
		fi
	done
	[ -n "$PYTHON" ] || { echo "✗ needs Python 3.10 to 3.13 (PyTorch 2.8 has no wheels for newer ones)"; exit 1; }
	echo "→ making the Python environment with $PYTHON"
	"$PYTHON" -m venv "$VENV"
fi
"$PY" -m pip install --quiet --upgrade pip
"$PY" -m pip install --quiet -r "$HERE/convert/requirements.txt"

# ---------------------------------------------------------------------------
# Downloads
# ---------------------------------------------------------------------------

# download <file> <url>: fetch a direct link, unless it's already here
download() {
	if [ -s "$DOWNLOADS/$1" ]; then return; fi
	echo "→ $1"
	curl -fL --progress-bar -o "$DOWNLOADS/$1.part" "$2"
	mv "$DOWNLOADS/$1.part" "$DOWNLOADS/$1"
}

# drive <file> <id>: fetch from Google Drive, where the authors publish some checkpoints
drive() {
	if [ -s "$DOWNLOADS/$1" ]; then return; fi
	echo "→ $1 (Google Drive)"
	"$VENV/bin/gdown" --quiet "$2" -O "$DOWNLOADS/$1.part"
	mv "$DOWNLOADS/$1.part" "$DOWNLOADS/$1"
}

# clone <name> <github repo> <commit>: the authors' model code, at a fixed commit
clone() {
	if [ ! -d "$REPOS/$1/.git" ]; then
		echo "→ $2"
		git clone --quiet "https://github.com/$2.git" "$REPOS/$1"
	fi
	git -C "$REPOS/$1" checkout --quiet "$3"
}

NVIDIA="https://nvlabs-fi-cdn.nvidia.com"
download stylegan2-ffhq-config-f.pkl "$NVIDIA/stylegan2/networks/stylegan2-ffhq-config-f.pkl"
download metfaces.pkl "$NVIDIA/stylegan2-ada-pytorch/pretrained/metfaces.pkl"
download CelebAMask-HQ-512x512.pt \
	"https://github.com/seasonSH/SemanticStyleGAN/releases/download/1.0.0/CelebAMask-HQ-512x512.pt"
download buffalo_l.zip "https://github.com/deepinsight/insightface/releases/download/v0.7/buffalo_l.zip"
for attribute in age gender smile eyeglasses pose; do
	download "stylegan_ffhq_${attribute}_w_boundary.npy" \
		"https://raw.githubusercontent.com/genforce/interfacegan/master/boundaries/stylegan_ffhq_${attribute}_w_boundary.npy"
done
drive mobilestylegan_ffhq.ckpt 11Kja0XGE8liLb6R5slNZjF3j3v_6xydt
drive e4e_ffhq_encode.pt 1cUv_reLE6k3604or78EranS7XzuVMWeO
drive gan-control-ffhq.tar.gz 19v0lX69fV6zQv2HbbYUVr9gZ8ZKvUzHq

clone stylegan2-ada-pytorch NVlabs/stylegan2-ada-pytorch d72cc7d041b42ec8e806021a205ed9349f87c6a4
clone MobileStyleGAN.pytorch bes-dev/MobileStyleGAN.pytorch a9776ff8f05a868b2d3b637bda14eca4c074d2a3
clone gan-control amazon-science/gan-control bf56937c497146ce594567b570c07c0eaec259bf
clone encoder4editing omertov/encoder4editing 99ea50578695d2e8a1cf7259d8ee89b23eea942b
clone SemanticStyleGAN seasonSH/SemanticStyleGAN 5be7c3e07b02f7c687efc9ae4d0ac8041b7fa7f3

# ---------------------------------------------------------------------------
# Conversions, each skipped when its files are already here
# ---------------------------------------------------------------------------
cd "$HERE/convert"

# made <file>...: true when every file is already here
made() {
	for file in "$@"; do [ -f "$HERE/$file" ] || return 1; done
}

made mobilestylegan_ffhq_v2-map.onnx mobilestylegan_ffhq_v2-synth.onnx || {
	echo "→ MobileStyleGAN FFHQ"
	"$PY" mobilestylegan.py "$DOWNLOADS/mobilestylegan_ffhq.ckpt" "$REPOS/MobileStyleGAN.pytorch" \
		"$HERE/mobilestylegan_ffhq_v2" 2>"$WORK/mobilestylegan.log"
}

made stylegan2-ffhq-map.onnx stylegan2-ffhq-synth.onnx || {
	echo "→ StyleGAN2 FFHQ"
	"$PY" stylegan2.py "$DOWNLOADS/stylegan2-ffhq-config-f.pkl" "$REPOS/stylegan2-ada-pytorch" \
		"$HERE/stylegan2-ffhq" 2>"$WORK/stylegan2-ffhq.log"
}

made stylegan2-metfaces-map.onnx stylegan2-metfaces-synth.onnx || {
	echo "→ StyleGAN2 MetFaces"
	"$PY" stylegan2.py "$DOWNLOADS/metfaces.pkl" "$REPOS/stylegan2-ada-pytorch" \
		"$HERE/stylegan2-metfaces" 2>"$WORK/stylegan2-metfaces.log"
}

made stylegan_ffhq_age_w_boundary.fp32.f32 stylegan_ffhq_pose_w_boundary.fp32.f32 || {
	echo "→ InterFaceGAN directions"
	"$PY" directions.py "$DOWNLOADS"/stylegan_ffhq_*_w_boundary.npy "$HERE"
}

made gancontrol-ffhq-map.onnx gancontrol-ffhq-synth.onnx gancontrol-ffhq-expression.onnx || {
	echo "→ GAN-Control FFHQ"
	mkdir -p "$WORK/gan-control"
	[ -d "$WORK/gan-control/controller_age015id025exp02hai04ori02gam15_temp" ] \
		|| tar -xzf "$DOWNLOADS/gan-control-ffhq.tar.gz" -C "$WORK/gan-control"
	"$PY" gancontrol.py "$WORK/gan-control/controller_age015id025exp02hai04ori02gam15_temp" \
		"$REPOS/gan-control" "$HERE/gancontrol-ffhq" 2>"$WORK/gan-control.log"
}

made semantic-celeba-synth.onnx || {
	echo "→ SemanticStyleGAN CelebAMask-HQ"
	"$PY" semantic.py "$DOWNLOADS/CelebAMask-HQ-512x512.pt" "$REPOS/SemanticStyleGAN" \
		"$HERE/semantic-celeba-synth.onnx" 2>"$WORK/semantic.log"
}

made e4e-ffhq-encoder.onnx stylegan2-ffhq-wavg.f32 || {
	echo "→ e4e encoder"
	"$PY" e4e.py "$DOWNLOADS/e4e_ffhq_encode.pt" "$REPOS/encoder4editing" "$HERE" 2>"$WORK/e4e.log"
}

made w600k_r50.onnx || {
	echo "→ ArcFace (InsightFace buffalo_l)"
	unzip -o -q "$DOWNLOADS/buffalo_l.zip" w600k_r50.onnx -d "$HERE"
}

echo
if "$HERE/download.sh" --check >/dev/null; then
	echo "✓ all the models are in $HERE"
	echo "  ($WORK holds the downloads and the authors' code, and can be deleted)"
else
	"$HERE/download.sh" --check || true
	exit 1
fi
