Skip to main content

adk_vision/
fetch.rs

1//! The model fetcher (spec 3.7 ยง7.4), feature `fetch`.
2//!
3//! Downloads from Hugging Face by revision only, through `hf-hub`'s cache layout so other
4//! tools share it, and checks every file's SHA-256 after download and before each load.
5//! With `HF_HUB_OFFLINE=1` it opens no socket: a cached file is checked and returned, a
6//! missing one is an error.
7
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11use hf_hub::api::sync::{ApiBuilder, ApiError};
12use hf_hub::{Cache, Repo, RepoType};
13
14use crate::error::{Result, VisionError};
15use crate::manifest::{
16    AcceptanceStore, LicenceGate, LicencePolicy, ModelManifest, ModelSource, VerifiedFile,
17    VerifiedModel,
18};
19
20const DEFAULT_ENDPOINT: &str = "https://huggingface.co";
21
22/// Where and how the fetcher reads and downloads.
23///
24/// # Example
25///
26/// ```
27/// use std::collections::HashMap;
28/// use adk_vision::FetchConfig;
29///
30/// let env: HashMap<&str, &str> =
31///     [("HF_HOME", "/data/hf"), ("HF_HUB_OFFLINE", "1"), ("HF_TOKEN", "hf_x")].into();
32/// let config = FetchConfig::from_lookup(|key| env.get(key).map(|v| v.to_string()));
33/// assert_eq!(config.cache_dir, std::path::PathBuf::from("/data/hf/hub"));
34/// assert!(config.offline);
35/// assert_eq!(config.token.as_deref(), Some("hf_x"));
36/// ```
37#[derive(Clone, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct FetchConfig {
40    /// The hub cache: `HF_HUB_CACHE`, else `$HF_HOME/hub`, else `~/.cache/huggingface/hub`.
41    pub cache_dir: PathBuf,
42    /// The hub endpoint: `HF_ENDPOINT`, else `https://huggingface.co`.
43    pub endpoint: String,
44    /// The access token: `HF_TOKEN`.
45    pub token: Option<String>,
46    /// `HF_HUB_OFFLINE` is `1`, `true`, `yes` or `on`: no socket is opened.
47    pub offline: bool,
48}
49
50impl std::fmt::Debug for FetchConfig {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("FetchConfig")
53            .field("cache_dir", &self.cache_dir)
54            .field("endpoint", &self.endpoint)
55            .field("token", &self.token.as_ref().map(|_| "<redacted>"))
56            .field("offline", &self.offline)
57            .finish()
58    }
59}
60
61impl FetchConfig {
62    /// The configuration from the process environment, by Python's `huggingface_hub`
63    /// conventions; the `hf-hub` crate reads none of them itself.
64    pub fn from_env() -> Self {
65        Self::from_lookup(|key| std::env::var(key).ok())
66    }
67
68    /// The configuration from a variable lookup.
69    pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Self {
70        let set = |key: &str| lookup(key).filter(|v| !v.trim().is_empty());
71        let cache_dir = set("HF_HUB_CACHE").map(PathBuf::from).unwrap_or_else(|| {
72            set("HF_HOME").map(|home| PathBuf::from(home).join("hub")).unwrap_or_else(|| {
73                std::env::home_dir()
74                    .unwrap_or_else(|| PathBuf::from("."))
75                    .join(".cache")
76                    .join("huggingface")
77                    .join("hub")
78            })
79        });
80        let offline = set("HF_HUB_OFFLINE").is_some_and(|v| {
81            matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")
82        });
83        Self {
84            cache_dir,
85            endpoint: set("HF_ENDPOINT").unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()),
86            token: set("HF_TOKEN"),
87            offline,
88        }
89    }
90
91    /// Uses `dir` as the hub cache.
92    pub fn with_cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
93        self.cache_dir = dir.into();
94        self
95    }
96
97    /// Downloads from `endpoint`.
98    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
99        self.endpoint = endpoint.into();
100        self
101    }
102
103    /// Sets offline mode.
104    pub fn with_offline(mut self, offline: bool) -> Self {
105        self.offline = offline;
106        self
107    }
108
109    /// Sets the access token.
110    pub fn with_token(mut self, token: Option<String>) -> Self {
111        self.token = token;
112        self
113    }
114}
115
116/// Fetches a model's files by revision and verifies them.
117///
118/// The licence gate runs before any request: a use-restricted model needs a person's
119/// recorded acceptance, and a non-commercial or copyleft one a policy that names it. A
120/// 401 or 403 from the hub is a gated repository and becomes
121/// [`VisionError::LicenceAcceptanceRequired`] naming the repository page.
122///
123/// # Example
124///
125/// ```no_run
126/// use std::sync::Arc;
127/// use adk_vision::{FetchConfig, InMemoryAcceptanceStore, ManifestSet, ModelFetcher};
128///
129/// # async fn demo(manifests: ManifestSet) -> adk_vision::Result<()> {
130/// let fetcher = ModelFetcher::new(FetchConfig::from_env(), Arc::new(InMemoryAcceptanceStore::new()));
131/// let model = fetcher.fetch(manifests.get("rf-detr-n-q4f16").unwrap()).await?;
132/// for file in model.files() {
133///     println!("{} {}", file.path().display(), file.digest());
134/// }
135/// # Ok(())
136/// # }
137/// ```
138#[derive(Clone)]
139pub struct ModelFetcher {
140    config: FetchConfig,
141    policy: LicencePolicy,
142    acceptances: Arc<dyn AcceptanceStore>,
143}
144
145impl std::fmt::Debug for ModelFetcher {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        f.debug_struct("ModelFetcher")
148            .field("config", &self.config)
149            .field("policy", &self.policy)
150            .finish_non_exhaustive()
151    }
152}
153
154impl ModelFetcher {
155    /// A fetcher with a configuration and a licence acceptance store.
156    pub fn new(config: FetchConfig, acceptances: Arc<dyn AcceptanceStore>) -> Self {
157        Self { config, policy: LicencePolicy::new(), acceptances }
158    }
159
160    /// Allows the non-commercial and copyleft models the policy names.
161    pub fn with_policy(mut self, policy: LicencePolicy) -> Self {
162        self.policy = policy;
163        self
164    }
165
166    /// The configuration.
167    pub fn config(&self) -> &FetchConfig {
168        &self.config
169    }
170
171    /// Fetches and verifies on a blocking thread. See [`fetch_blocking`](Self::fetch_blocking).
172    ///
173    /// # Errors
174    ///
175    /// As [`fetch_blocking`](Self::fetch_blocking).
176    pub async fn fetch(&self, manifest: &ModelManifest) -> Result<VerifiedModel> {
177        let fetcher = self.clone();
178        let manifest = manifest.clone();
179        tokio::task::spawn_blocking(move || fetcher.fetch_blocking(&manifest)).await.map_err(
180            |e| VisionError::Backend {
181                backend: "fetch".into(),
182                message: format!("fetch task failed: {e}"),
183            },
184        )?
185    }
186
187    /// Fetches every file of `manifest` that is not cached and verifies every file.
188    ///
189    /// # Errors
190    ///
191    /// The licence gate's refusal before any request; [`VisionError::Offline`] for a file
192    /// missing from the cache in offline mode; [`VisionError::LicenceAcceptanceRequired`]
193    /// for a 401 or 403; [`VisionError::Fetch`] for other download failures;
194    /// [`VisionError::DigestMismatch`] or [`VisionError::SizeMismatch`] for a file that does
195    /// not match; [`VisionError::Unsupported`] for ModelScope and URL sources, which arrive
196    /// with the backends that need them.
197    pub fn fetch_blocking(&self, manifest: &ModelManifest) -> Result<VerifiedModel> {
198        manifest.validate()?;
199        let gate = LicenceGate::new(&self.policy, self.acceptances.as_ref());
200        gate.check(manifest)?;
201        match &manifest.source {
202            ModelSource::Local { dir } => VerifiedModel::check_dir(manifest, dir, &gate),
203            ModelSource::HuggingFace { repo, revision } => {
204                let mut files = Vec::with_capacity(manifest.files.len());
205                for file in &manifest.files {
206                    let path = self.hugging_face_file(manifest, repo, revision, &file.path)?;
207                    files.push((file.path.clone(), VerifiedFile::check(&path, file)?));
208                }
209                tracing::info!(model.id = %manifest.id, model.revision = %revision, "model verified");
210                Ok(VerifiedModel::new(manifest.clone(), files))
211            }
212            ModelSource::ModelScope { .. } | ModelSource::Url { .. } => {
213                Err(VisionError::Unsupported(format!(
214                    "model `{}`: ModelScope and URL sources arrive with the backends that need them; \
215                     download the files and use a `local` source",
216                    manifest.id
217                )))
218            }
219        }
220    }
221
222    /// The cached path of a Hugging Face file, if it is in the cache. Opens no socket.
223    pub fn cached(&self, repo: &str, revision: &str, file: &str) -> Option<PathBuf> {
224        let repo = Repo::with_revision(repo.to_string(), RepoType::Model, revision.to_string());
225        Cache::new(self.config.cache_dir.clone()).repo(repo).get(file)
226    }
227
228    fn hugging_face_file(
229        &self,
230        manifest: &ModelManifest,
231        repo: &str,
232        revision: &str,
233        file: &str,
234    ) -> Result<PathBuf> {
235        if let Some(path) = self.cached(repo, revision, file) {
236            tracing::debug!(model.id = %manifest.id, model.file = file, "model file cached");
237            return Ok(path);
238        }
239        if self.config.offline {
240            return Err(VisionError::Offline {
241                model: manifest.id.clone(),
242                file: file.to_string(),
243            });
244        }
245        let fetch_error = |message: String| VisionError::Fetch {
246            model: manifest.id.clone(),
247            file: file.to_string(),
248            message,
249        };
250        let api = ApiBuilder::from_cache(Cache::new(self.config.cache_dir.clone()))
251            .with_endpoint(self.config.endpoint.clone())
252            .with_token(self.config.token.clone())
253            .with_progress(false)
254            .with_user_agent("adk-vision", env!("CARGO_PKG_VERSION"))
255            .build()
256            .map_err(|e| fetch_error(format!("the hub client failed to start: {e}")))?;
257        let hub_repo = Repo::with_revision(repo.to_string(), RepoType::Model, revision.to_string());
258        tracing::info!(model.id = %manifest.id, model.file = file, model.revision = revision, "fetching model file");
259        let path = api.repo(hub_repo).download(file).map_err(|err| match status_of(&err) {
260            Some(401 | 403) => VisionError::LicenceAcceptanceRequired {
261                model: manifest.id.clone(),
262                licence_url: format!("{}/{repo}", self.config.endpoint.trim_end_matches('/')),
263            },
264            Some(404) => fetch_error(format!("not found at revision {revision}")),
265            _ => fetch_error(err.to_string()),
266        })?;
267        if !in_snapshot(&path, revision) {
268            return Err(fetch_error(format!(
269                "the hub answered a different commit than revision {revision}"
270            )));
271        }
272        Ok(path)
273    }
274}
275
276fn status_of(err: &ApiError) -> Option<u16> {
277    match err {
278        ApiError::RequestError(inner) => match inner.as_ref() {
279            ureq::Error::StatusCode(code) => Some(*code),
280            _ => None,
281        },
282        ApiError::TooManyRetries(inner) => status_of(inner),
283        _ => None,
284    }
285}
286
287fn in_snapshot(path: &Path, revision: &str) -> bool {
288    path.components().any(|c| c.as_os_str() == revision)
289}