Skip to main content

adk_vision/manifest/
mod.rs

1//! Model manifests (spec 3.7 §7.4): every weight file pinned by revision and SHA-256, with
2//! its licence.
3//!
4//! Licence is data: a [`ModelManifest`] names its licence and [`LicenceClass`]. A
5//! use-restricted model loads only after a person's recorded acceptance
6//! ([`LicenceGate`]); non-commercial and copyleft models are never in the built-in
7//! manifest (V-I12) and load only when the configuration names them. No model file loads
8//! unless its SHA-256 matches (V-I10): backends take a [`VerifiedModel`], which only
9//! verification constructs.
10
11mod licence;
12mod verify;
13
14use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16
17use serde::{Deserialize, Serialize};
18
19pub use licence::{
20    AcceptanceStore, FileAcceptanceStore, InMemoryAcceptanceStore, LicenceAcceptance, LicenceGate,
21    LicencePolicy,
22};
23pub use verify::{VerifiedFile, VerifiedModel};
24
25use crate::digest::Digest;
26use crate::error::{Result, VisionError};
27use crate::geometry::Letterbox;
28
29/// What a model or backend does.
30#[non_exhaustive]
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
32#[serde(rename_all = "camelCase")]
33pub enum VisionTask {
34    /// Object detection.
35    Detect,
36    /// Segmentation.
37    Segment,
38    /// Document reading.
39    Read,
40    /// Image and text embedding.
41    Embed,
42    /// Description, structured extraction and grounding.
43    Describe,
44    /// Video analysis.
45    AnalyzeVideo,
46    /// Image editing.
47    Edit,
48}
49
50/// Where a model's files come from.
51#[non_exhaustive]
52#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "camelCase", tag = "kind")]
54pub enum ModelSource {
55    /// A Hugging Face repository at a commit.
56    HuggingFace {
57        /// `owner/name`.
58        repo: String,
59        /// A 40-digit commit hash, never a branch.
60        revision: String,
61    },
62    /// A ModelScope repository at a revision.
63    ModelScope {
64        /// `owner/name`.
65        repo: String,
66        /// The revision.
67        revision: String,
68    },
69    /// Files at `<base>/<path>`.
70    Url {
71        /// The base URL.
72        base: String,
73    },
74    /// Files the user placed in a directory, such as their own RF-DETR export.
75    Local {
76        /// The directory.
77        dir: PathBuf,
78    },
79}
80
81/// One file of a model, pinned by SHA-256 and size.
82#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "camelCase")]
84pub struct ModelFile {
85    /// The path inside the source, with `/` separators.
86    pub path: String,
87    /// The file's SHA-256.
88    pub sha256: Digest,
89    /// The file's size in bytes.
90    pub size: u64,
91}
92
93/// How freely a model's weights may be used.
94#[non_exhaustive]
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
96#[serde(rename_all = "camelCase")]
97pub enum LicenceClass {
98    /// Apache-2.0, MIT, BSD: may be fetched by default.
99    Permissive,
100    /// Commercial use with restrictions (the SAM License): fetched only after a person
101    /// accepts.
102    UseRestricted,
103    /// Never in the built-in manifest; a user's configuration must allow it by name.
104    NonCommercial,
105    /// Never in the built-in manifest; a user's configuration must allow it by name.
106    Copyleft,
107}
108
109impl std::fmt::Display for LicenceClass {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.write_str(match self {
112            Self::Permissive => "permissive",
113            Self::UseRestricted => "use-restricted",
114            Self::NonCommercial => "non-commercial",
115            Self::Copyleft => "copyleft",
116        })
117    }
118}
119
120/// A model's licence.
121#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(rename_all = "camelCase")]
123pub struct LicenceInfo {
124    /// An SPDX identifier, or `LicenseRef-<name>` for a custom licence such as Meta's SAM
125    /// License.
126    pub id: String,
127    /// Where a person reads it.
128    pub url: String,
129    /// Its class.
130    pub class: LicenceClass,
131}
132
133/// The runtime that executes a model.
134#[non_exhaustive]
135#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
136#[serde(rename_all = "camelCase", tag = "kind")]
137pub enum RuntimeSpec {
138    /// ONNX Runtime through `ort`.
139    Ort {
140        /// The ONNX opset.
141        opset: u32,
142    },
143    /// Candle.
144    Candle,
145    /// mistral.rs.
146    MistralRs {
147        /// The mistral.rs architecture name.
148        architecture: String,
149    },
150    /// Rust code compiled into the program, such as the `sam-3.1` mask codec
151    /// (`sam-mask-codec`): its files pin the source the code was ported from, and nothing
152    /// loads them at run time. Its manifest entry exists for the licence acceptance.
153    Native,
154}
155
156/// A model's fixed input size and how an image is fitted into it.
157#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(rename_all = "camelCase")]
159pub struct InputSpec {
160    /// Input width.
161    pub width: u32,
162    /// Input height.
163    pub height: u32,
164    /// How an image is fitted.
165    pub letterbox: Letterbox,
166}
167
168/// A model's input size, normalisation and labels.
169#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
170#[serde(rename_all = "camelCase")]
171pub struct IoSpec {
172    /// The fixed input, for models that take one.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub input: Option<InputSpec>,
175    /// Per-channel mean subtracted from RGB values in `[0, 1]`.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub mean: Option<[f32; 3]>,
178    /// Per-channel standard deviation RGB values are divided by.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub std: Option<[f32; 3]>,
181    /// Class labels, by output index.
182    #[serde(default, skip_serializing_if = "Vec::is_empty")]
183    pub labels: Vec<String>,
184}
185
186/// A model: its task, where its files come from, each file's SHA-256 and size, its
187/// licence, its runtime and its input and output.
188///
189/// # Example
190///
191/// ```
192/// use adk_vision::{LicenceClass, ModelManifest};
193///
194/// let manifest = ModelManifest::from_json(r#"{
195///     "id": "rf-detr-n-q4f16",
196///     "task": "detect",
197///     "source": {
198///         "kind": "huggingFace",
199///         "repo": "onnx-community/rfdetr_nano-ONNX",
200///         "revision": "eae21cee0687a91bcf9fa071605c48d7705d2d91"
201///     },
202///     "files": [{
203///         "path": "onnx/model_q4f16.onnx",
204///         "sha256": "sha256:42d8072bc00975405531e4e7f20dda40a6cb5ed67e345ecd764f92748463a996",
205///         "size": 18996625
206///     }],
207///     "licence": {
208///         "id": "Apache-2.0",
209///         "url": "https://www.apache.org/licenses/LICENSE-2.0",
210///         "class": "permissive"
211///     },
212///     "runtime": { "kind": "ort", "opset": 17 }
213/// }"#).unwrap();
214/// assert_eq!(manifest.licence.class, LicenceClass::Permissive);
215///
216/// // A branch is not a revision.
217/// let branch = r#"{"id":"m","task":"detect","source":{"kind":"huggingFace","repo":"a/b","revision":"main"},
218///   "files":[],"licence":{"id":"MIT","url":"https://x","class":"permissive"},"runtime":{"kind":"candle"}}"#;
219/// assert!(ModelManifest::from_json(branch).is_err());
220/// ```
221#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase")]
223pub struct ModelManifest {
224    /// Stable identifier, for example `rf-detr-m`.
225    pub id: String,
226    /// What the model does.
227    pub task: VisionTask,
228    /// Where its files come from.
229    pub source: ModelSource,
230    /// Every file with its SHA-256 and size.
231    pub files: Vec<ModelFile>,
232    /// Its licence.
233    pub licence: LicenceInfo,
234    /// The runtime that executes it.
235    pub runtime: RuntimeSpec,
236    /// Input size, normalisation and labels.
237    #[serde(default)]
238    pub io: IoSpec,
239}
240
241impl ModelManifest {
242    /// Parses and validates a manifest.
243    ///
244    /// # Errors
245    ///
246    /// [`VisionError::Manifest`] for invalid JSON or a manifest [`validate`](Self::validate)
247    /// refuses.
248    pub fn from_json(text: &str) -> Result<Self> {
249        let manifest: Self = serde_json::from_str(text).map_err(|e| VisionError::Manifest {
250            id: "<unparsed>".into(),
251            reason: e.to_string(),
252        })?;
253        manifest.validate()?;
254        Ok(manifest)
255    }
256
257    /// Checks the manifest: an id of lowercase letters, digits, `.`, `_` and `-`; a
258    /// Hugging Face revision that is a 40-digit commit hash; at least one file; relative
259    /// file paths with no `..`; and a licence with an id and a URL.
260    ///
261    /// # Errors
262    ///
263    /// [`VisionError::Manifest`] naming the first problem.
264    pub fn validate(&self) -> Result<()> {
265        let invalid = |reason: String| VisionError::Manifest { id: self.id.clone(), reason };
266        if self.id.is_empty()
267            || !self
268                .id
269                .bytes()
270                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
271        {
272            return Err(invalid(
273                "the id must be lowercase letters, digits, `.`, `_` and `-`".into(),
274            ));
275        }
276        match &self.source {
277            ModelSource::HuggingFace { repo, revision } => {
278                if repo.split('/').count() != 2 || repo.split('/').any(str::is_empty) {
279                    return Err(invalid(format!("`{repo}` is not an `owner/name` repository")));
280                }
281                if revision.len() != 40 || !revision.bytes().all(|b| b.is_ascii_hexdigit()) {
282                    return Err(invalid(format!(
283                        "revision `{revision}` is not a 40-digit commit hash; pin a commit, never a branch"
284                    )));
285                }
286            }
287            ModelSource::ModelScope { repo, revision } => {
288                if repo.is_empty() || revision.is_empty() {
289                    return Err(invalid(
290                        "a ModelScope source needs a repository and a revision".into(),
291                    ));
292                }
293            }
294            ModelSource::Url { base } => {
295                if !base.starts_with("https://") {
296                    return Err(invalid(format!("`{base}` is not an https URL")));
297                }
298            }
299            ModelSource::Local { .. } => {}
300        }
301        if self.files.is_empty() {
302            return Err(invalid("the manifest pins no file".into()));
303        }
304        for file in &self.files {
305            let path = &file.path;
306            if path.is_empty()
307                || path.starts_with('/')
308                || path.contains('\\')
309                || path.split('/').any(|part| part.is_empty() || part == "." || part == "..")
310            {
311                return Err(invalid(format!("file path `{path}` must be relative, with no `..`")));
312            }
313        }
314        if self.licence.id.is_empty() || self.licence.url.is_empty() {
315            return Err(invalid("the licence needs an id and a URL".into()));
316        }
317        Ok(())
318    }
319
320    /// The file at `path`, if the manifest pins one.
321    pub fn file(&self, path: &str) -> Option<&ModelFile> {
322        self.files.iter().find(|f| f.path == path)
323    }
324}
325
326/// A set of manifests by id: the built-in entries plus the user's own.
327///
328/// # Example
329///
330/// ```
331/// use adk_vision::ManifestSet;
332///
333/// let builtin = ManifestSet::builtin().unwrap();
334/// // V-I12: nothing non-commercial or copyleft is built in.
335/// assert!(builtin.iter().all(|m| matches!(
336///     m.licence.class,
337///     adk_vision::LicenceClass::Permissive | adk_vision::LicenceClass::UseRestricted
338/// )));
339/// ```
340#[derive(Clone, Debug, Default, PartialEq)]
341pub struct ManifestSet {
342    manifests: BTreeMap<String, ModelManifest>,
343}
344
345/// The built-in manifest. Entries arrive with each backend's workstream, pinned by the
346/// benchmark run that accepts the model (spec 3.7 §7.4).
347const BUILTIN: &str = include_str!("../../manifests/builtin.json");
348
349impl ManifestSet {
350    /// An empty set.
351    pub fn new() -> Self {
352        Self::default()
353    }
354
355    /// The built-in manifest.
356    ///
357    /// # Errors
358    ///
359    /// [`VisionError::Manifest`] when an entry is invalid or is non-commercial or copyleft;
360    /// the crate's tests keep this from shipping.
361    pub fn builtin() -> Result<Self> {
362        let entries: Vec<ModelManifest> = serde_json::from_str(BUILTIN)
363            .map_err(|e| VisionError::Manifest { id: "<builtin>".into(), reason: e.to_string() })?;
364        let mut set = Self::new();
365        for manifest in entries {
366            if matches!(
367                manifest.licence.class,
368                LicenceClass::NonCommercial | LicenceClass::Copyleft
369            ) {
370                return Err(VisionError::Manifest {
371                    id: manifest.id.clone(),
372                    reason: format!(
373                        "a {} model cannot be built in; it belongs in a user manifest",
374                        manifest.licence.class
375                    ),
376                });
377            }
378            set = set.with(manifest)?;
379        }
380        Ok(set)
381    }
382
383    /// Adds a manifest.
384    ///
385    /// # Errors
386    ///
387    /// [`VisionError::Manifest`] when it is invalid or its id is already in the set.
388    pub fn with(mut self, manifest: ModelManifest) -> Result<Self> {
389        manifest.validate()?;
390        if self.manifests.contains_key(&manifest.id) {
391            return Err(VisionError::Manifest {
392                id: manifest.id.clone(),
393                reason: "another manifest already uses this id".into(),
394            });
395        }
396        self.manifests.insert(manifest.id.clone(), manifest);
397        Ok(self)
398    }
399
400    /// Adds every `*.json` manifest in `dir`, the user's own models.
401    ///
402    /// # Errors
403    ///
404    /// [`VisionError::Io`] when the directory cannot be read, or the error of the first
405    /// manifest that does not parse or clashes.
406    pub fn with_dir(mut self, dir: &Path) -> Result<Self> {
407        let entries =
408            std::fs::read_dir(dir).map_err(|e| VisionError::io("could not read", dir, e))?;
409        let mut paths: Vec<PathBuf> = entries
410            .filter_map(|e| e.ok().map(|e| e.path()))
411            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
412            .collect();
413        paths.sort();
414        for path in paths {
415            let text = std::fs::read_to_string(&path)
416                .map_err(|e| VisionError::io("could not read", &path, e))?;
417            self = self.with(ModelManifest::from_json(&text)?)?;
418        }
419        Ok(self)
420    }
421
422    /// The manifest with this id.
423    pub fn get(&self, id: &str) -> Option<&ModelManifest> {
424        self.manifests.get(id)
425    }
426
427    /// Every manifest, by id.
428    pub fn iter(&self) -> impl Iterator<Item = &ModelManifest> {
429        self.manifests.values()
430    }
431
432    /// The number of manifests.
433    pub fn len(&self) -> usize {
434        self.manifests.len()
435    }
436
437    /// `true` when the set is empty.
438    pub fn is_empty(&self) -> bool {
439        self.manifests.is_empty()
440    }
441}