mod licence;
mod verify;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
pub use licence::{
AcceptanceStore, FileAcceptanceStore, InMemoryAcceptanceStore, LicenceAcceptance, LicenceGate,
LicencePolicy,
};
pub use verify::{VerifiedFile, VerifiedModel};
use crate::digest::Digest;
use crate::error::{Result, VisionError};
use crate::geometry::Letterbox;
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum VisionTask {
Detect,
Segment,
Read,
Embed,
Describe,
AnalyzeVideo,
Edit,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum ModelSource {
HuggingFace {
repo: String,
revision: String,
},
ModelScope {
repo: String,
revision: String,
},
Url {
base: String,
},
Local {
dir: PathBuf,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelFile {
pub path: String,
pub sha256: Digest,
pub size: u64,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum LicenceClass {
Permissive,
UseRestricted,
NonCommercial,
Copyleft,
}
impl std::fmt::Display for LicenceClass {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Permissive => "permissive",
Self::UseRestricted => "use-restricted",
Self::NonCommercial => "non-commercial",
Self::Copyleft => "copyleft",
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LicenceInfo {
pub id: String,
pub url: String,
pub class: LicenceClass,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum RuntimeSpec {
Ort {
opset: u32,
},
Candle,
MistralRs {
architecture: String,
},
Native,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InputSpec {
pub width: u32,
pub height: u32,
pub letterbox: Letterbox,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IoSpec {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input: Option<InputSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mean: Option<[f32; 3]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub std: Option<[f32; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub labels: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelManifest {
pub id: String,
pub task: VisionTask,
pub source: ModelSource,
pub files: Vec<ModelFile>,
pub licence: LicenceInfo,
pub runtime: RuntimeSpec,
#[serde(default)]
pub io: IoSpec,
}
impl ModelManifest {
pub fn from_json(text: &str) -> Result<Self> {
let manifest: Self = serde_json::from_str(text).map_err(|e| VisionError::Manifest {
id: "<unparsed>".into(),
reason: e.to_string(),
})?;
manifest.validate()?;
Ok(manifest)
}
pub fn validate(&self) -> Result<()> {
let invalid = |reason: String| VisionError::Manifest { id: self.id.clone(), reason };
if self.id.is_empty()
|| !self
.id
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
{
return Err(invalid(
"the id must be lowercase letters, digits, `.`, `_` and `-`".into(),
));
}
match &self.source {
ModelSource::HuggingFace { repo, revision } => {
if repo.split('/').count() != 2 || repo.split('/').any(str::is_empty) {
return Err(invalid(format!("`{repo}` is not an `owner/name` repository")));
}
if revision.len() != 40 || !revision.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(invalid(format!(
"revision `{revision}` is not a 40-digit commit hash; pin a commit, never a branch"
)));
}
}
ModelSource::ModelScope { repo, revision } => {
if repo.is_empty() || revision.is_empty() {
return Err(invalid(
"a ModelScope source needs a repository and a revision".into(),
));
}
}
ModelSource::Url { base } => {
if !base.starts_with("https://") {
return Err(invalid(format!("`{base}` is not an https URL")));
}
}
ModelSource::Local { .. } => {}
}
if self.files.is_empty() {
return Err(invalid("the manifest pins no file".into()));
}
for file in &self.files {
let path = &file.path;
if path.is_empty()
|| path.starts_with('/')
|| path.contains('\\')
|| path.split('/').any(|part| part.is_empty() || part == "." || part == "..")
{
return Err(invalid(format!("file path `{path}` must be relative, with no `..`")));
}
}
if self.licence.id.is_empty() || self.licence.url.is_empty() {
return Err(invalid("the licence needs an id and a URL".into()));
}
Ok(())
}
pub fn file(&self, path: &str) -> Option<&ModelFile> {
self.files.iter().find(|f| f.path == path)
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ManifestSet {
manifests: BTreeMap<String, ModelManifest>,
}
const BUILTIN: &str = include_str!("../../manifests/builtin.json");
impl ManifestSet {
pub fn new() -> Self {
Self::default()
}
pub fn builtin() -> Result<Self> {
let entries: Vec<ModelManifest> = serde_json::from_str(BUILTIN)
.map_err(|e| VisionError::Manifest { id: "<builtin>".into(), reason: e.to_string() })?;
let mut set = Self::new();
for manifest in entries {
if matches!(
manifest.licence.class,
LicenceClass::NonCommercial | LicenceClass::Copyleft
) {
return Err(VisionError::Manifest {
id: manifest.id.clone(),
reason: format!(
"a {} model cannot be built in; it belongs in a user manifest",
manifest.licence.class
),
});
}
set = set.with(manifest)?;
}
Ok(set)
}
pub fn with(mut self, manifest: ModelManifest) -> Result<Self> {
manifest.validate()?;
if self.manifests.contains_key(&manifest.id) {
return Err(VisionError::Manifest {
id: manifest.id.clone(),
reason: "another manifest already uses this id".into(),
});
}
self.manifests.insert(manifest.id.clone(), manifest);
Ok(self)
}
pub fn with_dir(mut self, dir: &Path) -> Result<Self> {
let entries =
std::fs::read_dir(dir).map_err(|e| VisionError::io("could not read", dir, e))?;
let mut paths: Vec<PathBuf> = entries
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|ext| ext == "json"))
.collect();
paths.sort();
for path in paths {
let text = std::fs::read_to_string(&path)
.map_err(|e| VisionError::io("could not read", &path, e))?;
self = self.with(ModelManifest::from_json(&text)?)?;
}
Ok(self)
}
pub fn get(&self, id: &str) -> Option<&ModelManifest> {
self.manifests.get(id)
}
pub fn iter(&self) -> impl Iterator<Item = &ModelManifest> {
self.manifests.values()
}
pub fn len(&self) -> usize {
self.manifests.len()
}
pub fn is_empty(&self) -> bool {
self.manifests.is_empty()
}
}