use std::path::{Path, PathBuf};
use eyre::{Result, eyre};
use hf_fetch::{Hub, HubError, HubRepo};
pub const MODEL_REPO: &str = "avencera/sam3-safetensors";
pub const MODEL_REVISION: &str = "deb497b5bfe05a41845368e8d94e711da78c5b65";
pub const MODEL_FILES: [&str; 3] = ["vocab.json", "merges.txt", "model.safetensors"];
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ModelRepositoryId(&'static str);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ModelRevision(&'static str);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct PinnedModelRepository {
id: ModelRepositoryId,
revision: ModelRevision,
}
impl PinnedModelRepository {
const fn sam3() -> Self {
Self { id: ModelRepositoryId(MODEL_REPO), revision: ModelRevision(MODEL_REVISION) }
}
fn bind(self, hub: &Hub) -> HubRepo {
hub.model(self.id.0, self.revision.0)
}
}
const PINNED_MODEL_REPOSITORY: PinnedModelRepository = PinnedModelRepository::sam3();
#[derive(Clone)]
pub struct ModelManager {
repo: HubRepo,
}
impl std::fmt::Debug for ModelManager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ModelManager")
.field("repo", &MODEL_REPO)
.field("revision", &MODEL_REVISION)
.finish_non_exhaustive()
}
}
impl ModelManager {
pub fn new() -> Result<Self, HubError> {
Ok(Self::from_hub(&Hub::from_env()?))
}
pub fn with_cache_dir(cache_dir: PathBuf) -> Result<Self, HubError> {
Ok(Self::from_hub(&Hub::with_cache_dir(cache_dir)?))
}
fn from_hub(hub: &Hub) -> Self {
Self { repo: PINNED_MODEL_REPOSITORY.bind(hub) }
}
pub fn get(&self, filename: impl AsRef<str>) -> Result<PathBuf, HubError> {
self.repo.get(filename.as_ref())
}
pub fn ensure(&self) -> Result<PathBuf, HubError> {
let [first, rest @ ..] = MODEL_FILES;
let first = self.get(first)?;
for file in rest {
self.get(file)?;
}
Ok(first.parent().map_or_else(|| first.clone(), Path::to_path_buf))
}
}
pub fn download_model() -> Result<PathBuf> {
let manager = ModelManager::new().map_err(|e| eyre!("set up Hugging Face downloads: {e}"))?;
manager.ensure().map_err(download_error)
}
fn download_error(error: HubError) -> eyre::Report {
match error.status() {
Some(401) => eyre!(
"{error}: Hugging Face rejected the token in HF_TOKEN or `hf auth login`'s token \
file; no token is needed, so unset HF_TOKEN or run `hf auth logout`, or replace \
it with a valid one"
),
Some(403) => eyre!(
"{error}: access to {MODEL_REPO} was refused; retry the download, and if it keeps \
failing, unset HF_TOKEN or run `hf auth logout`, since no token is needed"
),
_ => eyre!(
"download {MODEL_REPO}: {error} (check the network connection, or pass a local \
model directory instead)"
),
}
}