1use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13
14use ffai_core::error::{Error, Result};
15use serde::Deserialize;
16use sha2::{Digest, Sha256};
17
18#[derive(Debug, Clone)]
20pub struct ResolvedModel {
21 pub name: String,
22 pub license: String,
24 pub files: BTreeMap<String, PathBuf>,
26}
27
28impl ResolvedModel {
29 pub fn file(&self, name: &str) -> Result<&Path> {
31 self.files
32 .get(name)
33 .map(PathBuf::as_path)
34 .ok_or_else(|| Error::Model(format!("model `{}` has no file `{name}`", self.name)))
35 }
36}
37
38#[cfg(feature = "fetch")]
42fn hub_download(repo: &str, filename: &str, cache_only: bool) -> Result<PathBuf> {
43 let (owner, name) = repo
44 .split_once('/')
45 .ok_or_else(|| Error::Model(format!("hf_repo `{repo}` is not in `owner/name` form")))?;
46 let client = hf_hub::HFClientSync::new()
47 .map_err(|e| Error::Model(format!("hugging face client init failed: {e}")))?;
48 client
49 .model(owner, name)
50 .download_file()
51 .filename(filename)
52 .local_files_only(cache_only)
53 .send()
54 .map_err(|e| Error::Model(format!("{repo}/{filename}: {e}")))
55}
56
57#[cfg(not(feature = "fetch"))]
60fn hub_download(repo: &str, filename: &str, _cache_only: bool) -> Result<PathBuf> {
61 Err(Error::Model(format!(
62 "{repo}/{filename} is not present locally and this build has the `fetch` feature disabled — place the file in the model directory, or enable `ffai-models/fetch` to download it"
63 )))
64}
65
66fn verify_checksum(path: &Path, file: &ModelFile) -> Result<()> {
70 let Some(expected) = &file.sha256 else {
71 return Ok(());
72 };
73 let bytes = std::fs::read(path)?;
74 let actual: String = Sha256::digest(&bytes)
75 .iter()
76 .map(|b| format!("{b:02x}"))
77 .collect();
78 if actual != expected.to_ascii_lowercase() {
79 return Err(Error::Model(format!(
80 "checksum mismatch for {}: manifest says {expected}, file is {actual}",
81 path.display()
82 )));
83 }
84 Ok(())
85}
86
87#[derive(Debug, Clone, Deserialize)]
89pub struct ModelFile {
90 pub name: String,
92 pub sha256: Option<String>,
94}
95
96#[derive(Debug, Clone, Deserialize)]
98pub struct ModelManifest {
99 pub name: String,
100 pub task: String,
102 pub description: Option<String>,
103 pub license: String,
106 pub hf_repo: Option<String>,
108 #[serde(default)]
109 pub files: Vec<ModelFile>,
110}
111
112impl ModelManifest {
113 pub fn from_toml(text: &str) -> Result<Self> {
114 toml::from_str(text).map_err(|e| Error::Model(format!("bad manifest: {e}")))
115 }
116
117 pub fn load(path: &Path) -> Result<Self> {
118 let text = std::fs::read_to_string(path)?;
119 Self::from_toml(&text)
120 }
121
122 #[must_use]
124 pub fn cache_path(&self) -> PathBuf {
125 cache_dir().join("models").join(&self.name)
126 }
127
128 #[must_use]
130 pub fn is_cached(&self) -> bool {
131 !self.files.is_empty()
132 && self
133 .files
134 .iter()
135 .all(|f| self.local_path(&f.name).is_some())
136 }
137
138 #[must_use]
143 pub fn local_path(&self, name: &str) -> Option<PathBuf> {
144 let manual = self.cache_path().join(name);
145 if manual.exists() {
146 return Some(manual);
147 }
148 hub_download(self.hf_repo.as_ref()?, name, true).ok()
149 }
150
151 pub fn fetch(&self) -> Result<ResolvedModel> {
157 let mut files = BTreeMap::new();
158 for file in &self.files {
159 if let Some(path) = self.local_path(&file.name) {
160 verify_checksum(&path, file)?;
161 files.insert(file.name.clone(), path);
162 continue;
163 }
164 let repo = self.hf_repo.as_ref().ok_or_else(|| {
165 Error::Model(format!(
166 "model `{}` declares no hf_repo and `{}` is not present under {}",
167 self.name,
168 file.name,
169 self.cache_path().display()
170 ))
171 })?;
172 let path = hub_download(repo, &file.name, false)?;
173 verify_checksum(&path, file)?;
174 files.insert(file.name.clone(), path);
175 }
176 Ok(ResolvedModel {
177 name: self.name.clone(),
178 license: self.license.clone(),
179 files,
180 })
181 }
182
183 pub fn resolve_in(&self, root: &Path) -> Result<ResolvedModel> {
192 let all: Vec<&str> = self.files.iter().map(|f| f.name.as_str()).collect();
193 self.resolve_only_in(root, &all)
194 }
195
196 pub fn resolve_only_in(&self, root: &Path, needed: &[&str]) -> Result<ResolvedModel> {
205 let dir = root.join(&self.name);
206 let mut files = BTreeMap::new();
207 for name in needed {
208 if !self.files.iter().any(|f| f.name == *name) {
209 return Err(Error::Model(format!(
210 "model `{}` declares no file `{name}` — it has no checksum to verify against",
211 self.name
212 )));
213 }
214 }
215 for file in self
216 .files
217 .iter()
218 .filter(|f| needed.contains(&f.name.as_str()))
219 {
220 let path = dir.join(&file.name);
221 if !path.is_file() {
222 return Err(Error::Model(format!(
223 "model `{}` needs `{}`, expected at {} — not present (offline resolution \
224 never downloads)",
225 self.name,
226 file.name,
227 path.display()
228 )));
229 }
230 verify_checksum(&path, file)?;
231 files.insert(file.name.clone(), path);
232 }
233 Ok(ResolvedModel {
234 name: self.name.clone(),
235 license: self.license.clone(),
236 files,
237 })
238 }
239
240 pub fn verify(&self) -> Result<ResolvedModel> {
244 let mut files = BTreeMap::new();
245 for file in &self.files {
246 let path = self.local_path(&file.name).ok_or_else(|| {
247 Error::Model(format!(
248 "model `{}` is missing `{}` (looked under {}{})",
249 self.name,
250 file.name,
251 self.cache_path().display(),
252 if self.hf_repo.is_some() {
253 " and the Hugging Face cache"
254 } else {
255 ""
256 }
257 ))
258 })?;
259 verify_checksum(&path, file)?;
260 files.insert(file.name.clone(), path);
261 }
262 Ok(ResolvedModel {
263 name: self.name.clone(),
264 license: self.license.clone(),
265 files,
266 })
267 }
268}
269
270pub fn load_dir(dir: &Path) -> Result<Vec<ModelManifest>> {
277 let mut out = Vec::new();
278 let entries = std::fs::read_dir(dir).map_err(|e| {
279 Error::Model(format!(
280 "cannot read model manifest directory {}: {e}",
281 dir.display()
282 ))
283 })?;
284 for entry in entries {
285 let path = entry?.path();
286 if path.extension().and_then(|e| e.to_str()) == Some("toml") {
287 out.push(
288 ModelManifest::load(&path)
289 .map_err(|e| Error::Model(format!("{}: {e}", path.display())))?,
290 );
291 }
292 }
293 out.sort_by(|a, b| a.task.cmp(&b.task).then_with(|| a.name.cmp(&b.name)));
294 Ok(out)
295}
296
297pub fn cache_dir() -> PathBuf {
299 if let Ok(dir) = std::env::var("FFAI_CACHE") {
300 return PathBuf::from(dir);
301 }
302 dirs::cache_dir()
303 .unwrap_or_else(std::env::temp_dir)
304 .join("ffai")
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310
311 #[test]
312 fn manifest_parses_and_surfaces_license() {
313 let m = ModelManifest::from_toml(
314 r#"
315 name = "whisper-tiny"
316 task = "asr"
317 license = "Apache-2.0"
318 hf_repo = "openai/whisper-tiny"
319
320 [[files]]
321 name = "model.safetensors"
322 "#,
323 )
324 .unwrap();
325 assert_eq!(m.name, "whisper-tiny");
326 assert_eq!(m.license, "Apache-2.0");
327 assert_eq!(m.files.len(), 1);
328 assert!(!m.is_cached());
329 }
330
331 fn scratch(tag: &str) -> PathBuf {
332 let d = std::env::temp_dir().join(format!("ffai-models-{tag}-{}", std::process::id()));
333 let _ = std::fs::remove_dir_all(&d);
334 std::fs::create_dir_all(&d).unwrap();
335 d
336 }
337
338 fn manifest_for(sha: &str) -> ModelManifest {
339 ModelManifest::from_toml(&format!(
340 r#"
341 name = "tiny-test"
342 task = "ocr"
343 license = "MIT"
344
345 [[files]]
346 name = "w.bin"
347 sha256 = "{sha}"
348 "#
349 ))
350 .unwrap()
351 }
352
353 const ABC: &str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
355
356 #[test]
357 fn resolve_in_names_the_exact_missing_path_and_never_fetches() {
358 let root = scratch("missing");
359 let err = manifest_for(ABC).resolve_in(&root).unwrap_err().to_string();
360 let want = root.join("tiny-test").join("w.bin");
361 assert!(
362 err.contains(&want.display().to_string()),
363 "error must name {}: {err}",
364 want.display()
365 );
366 assert!(err.contains("never downloads"), "{err}");
367 let _ = std::fs::remove_dir_all(&root);
368 }
369
370 #[test]
371 fn resolve_in_finds_and_checksums_a_placed_file() {
372 let root = scratch("present");
373 std::fs::create_dir_all(root.join("tiny-test")).unwrap();
374 std::fs::write(root.join("tiny-test").join("w.bin"), b"abc").unwrap();
375 let r = manifest_for(ABC).resolve_in(&root).unwrap();
376 assert_eq!(
377 r.file("w.bin").unwrap(),
378 root.join("tiny-test").join("w.bin")
379 );
380
381 let bad = manifest_for(&"0".repeat(64))
383 .resolve_in(&root)
384 .unwrap_err()
385 .to_string();
386 assert!(bad.contains("checksum mismatch"), "{bad}");
387 let _ = std::fs::remove_dir_all(&root);
388 }
389
390 #[test]
391 fn load_dir_names_a_missing_directory() {
392 let missing = std::env::temp_dir().join("ffai-models-definitely-absent-dir");
393 let err = load_dir(&missing).unwrap_err().to_string();
394 assert!(err.contains(&missing.display().to_string()), "{err}");
395 }
396
397 #[test]
401 fn resolve_only_in_needs_just_the_named_files_and_refuses_undeclared_ones() {
402 let root = scratch("subset");
403 std::fs::create_dir_all(root.join("tiny-test")).unwrap();
404 std::fs::write(root.join("tiny-test").join("w.bin"), b"abc").unwrap();
405 let m = ModelManifest::from_toml(&format!(
406 r#"
407 name = "tiny-test"
408 task = "ocr"
409 license = "MIT"
410
411 [[files]]
412 name = "w.bin"
413 sha256 = "{ABC}"
414
415 [[files]]
416 name = "train-only.bin"
417 "#
418 ))
419 .unwrap();
420 assert!(
421 m.resolve_in(&root).is_err(),
422 "the full set includes an absent file"
423 );
424 let r = m.resolve_only_in(&root, &["w.bin"]).unwrap();
425 assert_eq!(r.files.len(), 1);
426 let err = m
427 .resolve_only_in(&root, &["nope.bin"])
428 .unwrap_err()
429 .to_string();
430 assert!(err.contains("declares no file `nope.bin`"), "{err}");
431 let _ = std::fs::remove_dir_all(&root);
432 }
433}