1use 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#[derive(Clone, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct FetchConfig {
40 pub cache_dir: PathBuf,
42 pub endpoint: String,
44 pub token: Option<String>,
46 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 pub fn from_env() -> Self {
65 Self::from_lookup(|key| std::env::var(key).ok())
66 }
67
68 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 pub fn with_cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
93 self.cache_dir = dir.into();
94 self
95 }
96
97 pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
99 self.endpoint = endpoint.into();
100 self
101 }
102
103 pub fn with_offline(mut self, offline: bool) -> Self {
105 self.offline = offline;
106 self
107 }
108
109 pub fn with_token(mut self, token: Option<String>) -> Self {
111 self.token = token;
112 self
113 }
114}
115
116#[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 pub fn new(config: FetchConfig, acceptances: Arc<dyn AcceptanceStore>) -> Self {
157 Self { config, policy: LicencePolicy::new(), acceptances }
158 }
159
160 pub fn with_policy(mut self, policy: LicencePolicy) -> Self {
162 self.policy = policy;
163 self
164 }
165
166 pub fn config(&self) -> &FetchConfig {
168 &self.config
169 }
170
171 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 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 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}