use std::path::{Path, PathBuf};
use std::sync::Arc;
use hf_hub::api::sync::{ApiBuilder, ApiError};
use hf_hub::{Cache, Repo, RepoType};
use crate::error::{Result, VisionError};
use crate::manifest::{
AcceptanceStore, LicenceGate, LicencePolicy, ModelManifest, ModelSource, VerifiedFile,
VerifiedModel,
};
const DEFAULT_ENDPOINT: &str = "https://huggingface.co";
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct FetchConfig {
pub cache_dir: PathBuf,
pub endpoint: String,
pub token: Option<String>,
pub offline: bool,
}
impl std::fmt::Debug for FetchConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FetchConfig")
.field("cache_dir", &self.cache_dir)
.field("endpoint", &self.endpoint)
.field("token", &self.token.as_ref().map(|_| "<redacted>"))
.field("offline", &self.offline)
.finish()
}
}
impl FetchConfig {
pub fn from_env() -> Self {
Self::from_lookup(|key| std::env::var(key).ok())
}
pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Self {
let set = |key: &str| lookup(key).filter(|v| !v.trim().is_empty());
let cache_dir = set("HF_HUB_CACHE").map(PathBuf::from).unwrap_or_else(|| {
set("HF_HOME").map(|home| PathBuf::from(home).join("hub")).unwrap_or_else(|| {
std::env::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(".cache")
.join("huggingface")
.join("hub")
})
});
let offline = set("HF_HUB_OFFLINE").is_some_and(|v| {
matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")
});
Self {
cache_dir,
endpoint: set("HF_ENDPOINT").unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()),
token: set("HF_TOKEN"),
offline,
}
}
pub fn with_cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.cache_dir = dir.into();
self
}
pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = endpoint.into();
self
}
pub fn with_offline(mut self, offline: bool) -> Self {
self.offline = offline;
self
}
pub fn with_token(mut self, token: Option<String>) -> Self {
self.token = token;
self
}
}
#[derive(Clone)]
pub struct ModelFetcher {
config: FetchConfig,
policy: LicencePolicy,
acceptances: Arc<dyn AcceptanceStore>,
}
impl std::fmt::Debug for ModelFetcher {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ModelFetcher")
.field("config", &self.config)
.field("policy", &self.policy)
.finish_non_exhaustive()
}
}
impl ModelFetcher {
pub fn new(config: FetchConfig, acceptances: Arc<dyn AcceptanceStore>) -> Self {
Self { config, policy: LicencePolicy::new(), acceptances }
}
pub fn with_policy(mut self, policy: LicencePolicy) -> Self {
self.policy = policy;
self
}
pub fn config(&self) -> &FetchConfig {
&self.config
}
pub async fn fetch(&self, manifest: &ModelManifest) -> Result<VerifiedModel> {
let fetcher = self.clone();
let manifest = manifest.clone();
tokio::task::spawn_blocking(move || fetcher.fetch_blocking(&manifest)).await.map_err(
|e| VisionError::Backend {
backend: "fetch".into(),
message: format!("fetch task failed: {e}"),
},
)?
}
pub fn fetch_blocking(&self, manifest: &ModelManifest) -> Result<VerifiedModel> {
manifest.validate()?;
let gate = LicenceGate::new(&self.policy, self.acceptances.as_ref());
gate.check(manifest)?;
match &manifest.source {
ModelSource::Local { dir } => VerifiedModel::check_dir(manifest, dir, &gate),
ModelSource::HuggingFace { repo, revision } => {
let mut files = Vec::with_capacity(manifest.files.len());
for file in &manifest.files {
let path = self.hugging_face_file(manifest, repo, revision, &file.path)?;
files.push((file.path.clone(), VerifiedFile::check(&path, file)?));
}
tracing::info!(model.id = %manifest.id, model.revision = %revision, "model verified");
Ok(VerifiedModel::new(manifest.clone(), files))
}
ModelSource::ModelScope { .. } | ModelSource::Url { .. } => {
Err(VisionError::Unsupported(format!(
"model `{}`: ModelScope and URL sources arrive with the backends that need them; \
download the files and use a `local` source",
manifest.id
)))
}
}
}
pub fn cached(&self, repo: &str, revision: &str, file: &str) -> Option<PathBuf> {
let repo = Repo::with_revision(repo.to_string(), RepoType::Model, revision.to_string());
Cache::new(self.config.cache_dir.clone()).repo(repo).get(file)
}
fn hugging_face_file(
&self,
manifest: &ModelManifest,
repo: &str,
revision: &str,
file: &str,
) -> Result<PathBuf> {
if let Some(path) = self.cached(repo, revision, file) {
tracing::debug!(model.id = %manifest.id, model.file = file, "model file cached");
return Ok(path);
}
if self.config.offline {
return Err(VisionError::Offline {
model: manifest.id.clone(),
file: file.to_string(),
});
}
let fetch_error = |message: String| VisionError::Fetch {
model: manifest.id.clone(),
file: file.to_string(),
message,
};
let api = ApiBuilder::from_cache(Cache::new(self.config.cache_dir.clone()))
.with_endpoint(self.config.endpoint.clone())
.with_token(self.config.token.clone())
.with_progress(false)
.with_user_agent("adk-vision", env!("CARGO_PKG_VERSION"))
.build()
.map_err(|e| fetch_error(format!("the hub client failed to start: {e}")))?;
let hub_repo = Repo::with_revision(repo.to_string(), RepoType::Model, revision.to_string());
tracing::info!(model.id = %manifest.id, model.file = file, model.revision = revision, "fetching model file");
let path = api.repo(hub_repo).download(file).map_err(|err| match status_of(&err) {
Some(401 | 403) => VisionError::LicenceAcceptanceRequired {
model: manifest.id.clone(),
licence_url: format!("{}/{repo}", self.config.endpoint.trim_end_matches('/')),
},
Some(404) => fetch_error(format!("not found at revision {revision}")),
_ => fetch_error(err.to_string()),
})?;
if !in_snapshot(&path, revision) {
return Err(fetch_error(format!(
"the hub answered a different commit than revision {revision}"
)));
}
Ok(path)
}
}
fn status_of(err: &ApiError) -> Option<u16> {
match err {
ApiError::RequestError(inner) => match inner.as_ref() {
ureq::Error::StatusCode(code) => Some(*code),
_ => None,
},
ApiError::TooManyRetries(inner) => status_of(inner),
_ => None,
}
}
fn in_snapshot(path: &Path, revision: &str) -> bool {
path.components().any(|c| c.as_os_str() == revision)
}