troupekit_local/
catalog.rs1use crate::error::LocalError;
2use serde::Deserialize;
3use std::collections::HashSet;
4use std::sync::OnceLock;
5
6const BUILTIN: &str = include_str!("../catalog/local.toml");
7
8const ID_MAX_BYTES: usize = 64;
9const URL_MAX_BYTES: usize = 2_048;
10const ROWS_MAX: usize = 256;
11
12#[non_exhaustive]
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum DeviceClass {
19 Phone,
20 Pi,
21 #[default]
22 Desktop,
23}
24
25#[non_exhaustive]
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct LocalSpec {
31 id: String,
32 url: String,
33 sha256: String,
34 bytes: u64,
35 ram_bytes: u64,
36 context: usize,
37 class: DeviceClass,
38 licence: String,
39 embeddings: bool,
40 recommended: bool,
41}
42
43impl LocalSpec {
44 pub fn new(id: &str, url: &str, sha256: &str, bytes: u64) -> Result<Self, LocalError> {
48 let id_ok = !id.is_empty()
49 && id.len() <= ID_MAX_BYTES
50 && !id.starts_with('.')
51 && id.bytes().all(|b| {
52 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'_' | b'.')
53 });
54 if !id_ok {
55 return Err(LocalError::Catalog(format!(
56 "model id {id:?} is not a valid id"
57 )));
58 }
59 let url_ok = url.len() <= URL_MAX_BYTES
60 && url.len() > "https://".len()
61 && url.starts_with("https://")
62 && !url.bytes().any(|b| b.is_ascii_control() || b == b' ');
63 if !url_ok {
64 return Err(LocalError::Catalog(format!(
65 "model {id}: url must be an https URL"
66 )));
67 }
68 let hash_ok = sha256.len() == 64
69 && sha256
70 .bytes()
71 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
72 if !hash_ok {
73 return Err(LocalError::Catalog(format!(
74 "model {id}: sha256 must be 64 lowercase hex characters"
75 )));
76 }
77 if bytes == 0 {
78 return Err(LocalError::Catalog(format!(
79 "model {id}: bytes must be above 0"
80 )));
81 }
82 Ok(Self {
83 id: id.to_string(),
84 url: url.to_string(),
85 sha256: sha256.to_string(),
86 bytes,
87 ram_bytes: bytes,
88 context: 4_096,
89 class: DeviceClass::default(),
90 licence: String::new(),
91 embeddings: false,
92 recommended: false,
93 })
94 }
95
96 pub fn with_ram_bytes(mut self, ram_bytes: u64) -> Self {
100 self.ram_bytes = ram_bytes;
101 self
102 }
103
104 pub fn with_context(mut self, context: usize) -> Self {
108 self.context = context;
109 self
110 }
111
112 pub fn with_class(mut self, class: DeviceClass) -> Self {
116 self.class = class;
117 self
118 }
119
120 pub fn with_licence(mut self, licence: impl Into<String>) -> Self {
124 self.licence = licence.into();
125 self
126 }
127
128 pub fn with_embeddings(mut self, embeddings: bool) -> Self {
132 self.embeddings = embeddings;
133 self
134 }
135
136 pub fn with_recommended(mut self, recommended: bool) -> Self {
140 self.recommended = recommended;
141 self
142 }
143
144 pub fn id(&self) -> &str {
148 &self.id
149 }
150
151 pub fn url(&self) -> &str {
155 &self.url
156 }
157
158 pub fn sha256(&self) -> &str {
162 &self.sha256
163 }
164
165 pub fn bytes(&self) -> u64 {
169 self.bytes
170 }
171
172 pub fn ram_bytes(&self) -> u64 {
176 self.ram_bytes
177 }
178
179 pub fn context(&self) -> usize {
183 self.context
184 }
185
186 pub fn class(&self) -> DeviceClass {
190 self.class
191 }
192
193 pub fn licence(&self) -> &str {
197 &self.licence
198 }
199
200 pub fn embeddings(&self) -> bool {
204 self.embeddings
205 }
206
207 pub fn recommended(&self) -> bool {
211 self.recommended
212 }
213}
214
215#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct LocalCatalog {
220 rows: Vec<LocalSpec>,
221}
222
223#[derive(Deserialize)]
224#[serde(deny_unknown_fields)]
225struct File {
226 #[serde(default)]
227 model: Vec<Row>,
228}
229
230#[derive(Deserialize)]
231#[serde(deny_unknown_fields)]
232struct Row {
233 id: String,
234 url: String,
235 sha256: String,
236 bytes: u64,
237 ram_bytes: Option<u64>,
238 context: Option<usize>,
239 class: Option<DeviceClass>,
240 licence: Option<String>,
241 embeddings: Option<bool>,
242 recommended: Option<bool>,
243}
244
245impl LocalCatalog {
246 pub const MAX_BYTES: usize = 64 * 1024;
250
251 pub fn load(text: &str) -> Result<Self, LocalError> {
255 if text.len() > Self::MAX_BYTES {
256 return Err(LocalError::Catalog(format!(
257 "catalog is {} bytes, limit {}",
258 text.len(),
259 Self::MAX_BYTES
260 )));
261 }
262 let file: File =
263 toml::from_str(text).map_err(|e| LocalError::Catalog(e.message().to_string()))?;
264 let rows = file
265 .model
266 .into_iter()
267 .map(|r| {
268 let mut spec = LocalSpec::new(&r.id, &r.url, &r.sha256, r.bytes)?;
269 if let Some(v) = r.ram_bytes {
270 spec = spec.with_ram_bytes(v);
271 }
272 if let Some(v) = r.context {
273 spec = spec.with_context(v);
274 }
275 if let Some(v) = r.class {
276 spec = spec.with_class(v);
277 }
278 if let Some(v) = r.licence {
279 spec = spec.with_licence(v);
280 }
281 Ok(spec
282 .with_embeddings(r.embeddings.unwrap_or(false))
283 .with_recommended(r.recommended.unwrap_or(false)))
284 })
285 .collect::<Result<Vec<_>, LocalError>>()?;
286 Self::new(rows)
287 }
288
289 pub fn builtin() -> &'static LocalCatalog {
293 static CATALOG: OnceLock<LocalCatalog> = OnceLock::new();
294 CATALOG
295 .get_or_init(|| Self::load(BUILTIN).expect("the shipped catalog/local.toml is valid"))
296 }
297
298 pub fn new(rows: Vec<LocalSpec>) -> Result<Self, LocalError> {
302 if rows.len() > ROWS_MAX {
303 return Err(LocalError::Catalog(format!(
304 "{} rows, limit {ROWS_MAX}",
305 rows.len()
306 )));
307 }
308 let mut ids = HashSet::new();
309 let mut recommended = HashSet::new();
310 for row in &rows {
311 if !ids.insert(row.id.as_str()) {
312 return Err(LocalError::Catalog(format!(
313 "model id {} appears twice",
314 row.id
315 )));
316 }
317 if row.recommended && !recommended.insert(row.class) {
318 return Err(LocalError::Catalog(format!(
319 "two recommended rows for class {:?}",
320 row.class
321 )));
322 }
323 }
324 Ok(Self { rows })
325 }
326
327 pub fn get(&self, id: &str) -> Option<&LocalSpec> {
331 self.rows.iter().find(|r| r.id == id)
332 }
333
334 pub fn rows(&self) -> &[LocalSpec] {
338 &self.rows
339 }
340
341 pub fn pick(&self, class: DeviceClass, ram_budget_bytes: u64) -> Option<&LocalSpec> {
345 let fitting: Vec<&LocalSpec> = self
346 .rows
347 .iter()
348 .filter(|r| r.class == class && r.ram_bytes <= ram_budget_bytes)
349 .collect();
350 fitting
351 .iter()
352 .find(|r| r.recommended)
353 .or_else(|| fitting.iter().max_by_key(|r| (r.ram_bytes, r.bytes)))
354 .copied()
355 }
356}