use std::path::{Path, PathBuf};
use super::{LicenceGate, ModelFile, ModelManifest};
use crate::digest::Digest;
use crate::error::{Result, VisionError};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VerifiedFile {
path: PathBuf,
digest: Digest,
size: u64,
}
impl VerifiedFile {
pub fn check(path: &Path, expected: &ModelFile) -> Result<Self> {
let size =
std::fs::metadata(path).map_err(|e| VisionError::io("could not read", path, e))?.len();
if size != expected.size {
return Err(VisionError::SizeMismatch {
path: path.to_path_buf(),
expected: expected.size,
actual: size,
});
}
let (digest, _) = Digest::of_file(path)?;
if digest != expected.sha256 {
tracing::warn!(
model.file = %path.display(),
expected = %expected.sha256,
actual = %digest,
"model file rejected"
);
return Err(VisionError::DigestMismatch {
path: path.to_path_buf(),
expected: expected.sha256,
actual: digest,
});
}
Ok(Self { path: path.to_path_buf(), digest, size })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn digest(&self) -> Digest {
self.digest
}
pub fn size(&self) -> u64 {
self.size
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct VerifiedModel {
manifest: ModelManifest,
files: Vec<(String, VerifiedFile)>,
}
impl VerifiedModel {
pub(crate) fn new(manifest: ModelManifest, files: Vec<(String, VerifiedFile)>) -> Self {
Self { manifest, files }
}
pub fn check_dir(manifest: &ModelManifest, dir: &Path, gate: &LicenceGate<'_>) -> Result<Self> {
manifest.validate()?;
gate.check(manifest)?;
let mut files = Vec::with_capacity(manifest.files.len());
for file in &manifest.files {
let path = dir.join(&file.path);
files.push((file.path.clone(), VerifiedFile::check(&path, file)?));
}
tracing::info!(model.id = %manifest.id, model.files = files.len(), "model verified");
Ok(Self::new(manifest.clone(), files))
}
pub fn manifest(&self) -> &ModelManifest {
&self.manifest
}
pub fn files(&self) -> impl Iterator<Item = &VerifiedFile> {
self.files.iter().map(|(_, f)| f)
}
pub fn file(&self, path: &str) -> Option<&VerifiedFile> {
self.files.iter().find(|(p, _)| p == path).map(|(_, f)| f)
}
#[cfg(any(feature = "ocr-vl", feature = "mistralrs"))]
pub(crate) fn dir_of(&self, required: &[&str]) -> Result<PathBuf> {
let id = &self.manifest().id;
let invalid = |reason: String| VisionError::Manifest { id: id.clone(), reason };
let mut dir: Option<PathBuf> = None;
for path in required {
let file = self.file(path).ok_or_else(|| {
invalid(format!("the manifest pins no `{path}`, which the loader reads"))
})?;
let parent = file.path().parent().map(Path::to_path_buf).unwrap_or_default();
match &dir {
None => dir = Some(parent),
Some(d) if *d != parent => {
return Err(invalid(format!("`{path}` is not beside the model's other files")));
}
Some(_) => {}
}
}
let dir = dir.ok_or_else(|| invalid("no file to load".into()))?;
let entries =
std::fs::read_dir(&dir).map_err(|e| VisionError::io("could not read", &dir, e))?;
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name.ends_with(".safetensors") && self.file(&name).is_none() {
return Err(invalid(format!(
"`{name}` in {} is not in the manifest and would load unverified; remove it",
dir.display()
)));
}
}
Ok(dir)
}
}