use std::path::{Path, PathBuf};
use eyre::{Result, eyre};
use hf_fetch::{Hub, HubError};
pub const MODEL_REPO: &str = "facebook/sam3";
pub const MODEL_FILES: [&str; 3] = ["vocab.json", "merges.txt", "model.safetensors"];
pub fn download_model() -> Result<PathBuf> {
let hub = Hub::from_env().map_err(|e| eyre!("set up Hugging Face downloads: {e}"))?;
let repo = hub.model(MODEL_REPO, "main");
let mut dir = None;
for file in MODEL_FILES {
let path = repo.get(file).map_err(|e| download_error(file, e))?;
dir = path.parent().map(Path::to_path_buf);
}
dir.ok_or_else(|| eyre!("Hugging Face returned no path for {MODEL_REPO}"))
}
fn download_error(file: &str, error: HubError) -> eyre::Report {
match error.status() {
Some(status @ (401 | 403)) => eyre!(
"{MODEL_REPO} is gated: accept Meta's SAM License at https://huggingface.co/{MODEL_REPO} while \
logged in, then run `hf auth login` or set HF_TOKEN to a token of that account \
(Hugging Face answered HTTP {status} for {file})"
),
_ => eyre!("download {MODEL_REPO}/{file}: {error}"),
}
}