1use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10use crate::catalog::ModelSpec;
11use crate::gguf::{self, GgufInfo};
12use crate::token::HfToken;
13use crate::{Error, Result};
14pub fn check_repo(id: &str) -> Result<()> {
16 let ok = |p: &str| !p.is_empty() && p != "." && p != ".." && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
17 match id.split_once('/') {
18 Some((o, n)) if ok(o) && ok(n) => Ok(()),
19 _ => Err(Error::BadRepo(id.to_string())),
20 }
21}
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct RepoFile {
26 pub name: String,
27 pub size: u64,
28 pub sha256: Option<String>,
29}
30
31pub fn repo_files(hub: &str, repo: &str) -> Result<Vec<RepoFile>> {
35 Hub::new(hub).repo_files(repo)
36}
37
38pub fn parse_files(v: &Value) -> Vec<RepoFile> {
40 v["siblings"]
41 .as_array()
42 .into_iter()
43 .flatten()
44 .filter_map(|s| {
45 let name = s["rfilename"].as_str()?;
46 let file = name.rsplit('/').next().unwrap_or(name);
47 let lower = file.to_ascii_lowercase();
48 if !lower.ends_with(".gguf") || lower.starts_with("mmproj") || lower.starts_with("mtp-") {
49 return None;
50 }
51 Some(RepoFile { name: name.to_string(), size: s["size"].as_u64().unwrap_or(0), sha256: s["lfs"]["sha256"].as_str().map(str::to_string) })
52 })
53 .collect()
54}
55
56impl ModelSpec {
57 pub fn from_repo_file(repo: &str, file: &RepoFile) -> Result<Self> {
59 check_repo(repo)?;
60 let name = file.name.rsplit('/').next().unwrap_or(&file.name);
61 let stem = name.strip_suffix(".gguf").or_else(|| name.strip_suffix(".GGUF")).unwrap_or(name);
62 Ok(Self {
63 id: stem.to_string(),
64 label: stem.to_string(),
65 repo: repo.to_string(),
66 file: file.name.clone(),
67 size: file.size,
68 sha256: file.sha256.clone(),
69 })
70 }
71}
72
73pub fn check_file(name: &str) -> Result<()> {
75 let ok = !name.is_empty()
76 && !name.starts_with('/')
77 && !name.contains('\\')
78 && name.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && !p.contains(':'));
79 if ok { Ok(()) } else { Err(Error::Model(format!("{name:?} is not a file name inside a repo"))) }
80}
81
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84#[non_exhaustive]
85pub struct Search {
86 pub query: String,
87 pub limit: usize,
89 pub gguf_only: bool,
91}
92
93impl Search {
94 pub fn new(query: impl Into<String>) -> Self {
95 Self { query: query.into(), limit: 20, gguf_only: true }
96 }
97
98 pub fn with_limit(mut self, limit: usize) -> Self {
99 self.limit = limit;
100 self
101 }
102
103 pub fn with_gguf_only(mut self, on: bool) -> Self {
104 self.gguf_only = on;
105 self
106 }
107}
108
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111#[non_exhaustive]
112pub struct SearchHit {
113 pub id: String,
115 pub downloads: u64,
116 pub likes: u64,
117 pub gated: bool,
119 pub pipeline_tag: Option<String>,
120 pub last_modified: Option<String>,
121}
122
123pub fn parse_search(v: &Value) -> Vec<SearchHit> {
125 v.as_array()
126 .into_iter()
127 .flatten()
128 .filter_map(|m| {
129 let id = m["id"].as_str().or_else(|| m["modelId"].as_str())?;
130 check_repo(id).ok()?;
131 Some(SearchHit {
132 id: id.to_string(),
133 downloads: m["downloads"].as_u64().unwrap_or(0),
134 likes: m["likes"].as_u64().unwrap_or(0),
135 gated: match &m["gated"] {
136 Value::Bool(b) => *b,
137 Value::String(s) => !s.is_empty() && s != "false",
138 _ => false,
139 },
140 pipeline_tag: m["pipeline_tag"].as_str().map(str::to_string),
141 last_modified: m["lastModified"].as_str().map(str::to_string),
142 })
143 })
144 .collect()
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150#[non_exhaustive]
151pub struct RepoModel {
152 pub id: String,
154 pub quant: Option<String>,
156 pub parts: Vec<RepoFile>,
158 pub size: u64,
160 pub complete: bool,
162}
163
164impl RepoModel {
165 pub fn first(&self) -> &RepoFile {
167 &self.parts[0]
168 }
169
170 pub fn is_split(&self) -> bool {
171 self.parts.len() > 1
172 }
173
174 pub fn specs(&self, repo: &str) -> Result<Vec<ModelSpec>> {
177 check_repo(repo)?;
178 self.parts
179 .iter()
180 .map(|f| {
181 check_file(&f.name)?;
182 Ok(ModelSpec {
183 id: self.id.clone(),
184 label: self.id.clone(),
185 repo: repo.to_string(),
186 file: f.name.clone(),
187 size: f.size,
188 sha256: f.sha256.clone(),
189 })
190 })
191 .collect()
192 }
193}
194
195pub fn split_part(name: &str) -> Option<(&str, u32, u32)> {
197 let file = name.rsplit('/').next().unwrap_or(name);
198 let stem = file.strip_suffix(".gguf").or_else(|| file.strip_suffix(".GGUF"))?;
199 let (rest, of) = stem.rsplit_once("-of-")?;
200 let (base, part) = rest.rsplit_once('-')?;
201 let digits = |s: &str| s.len() == 5 && s.chars().all(|c| c.is_ascii_digit());
202 if !digits(part) || !digits(of) || base.is_empty() {
203 return None;
204 }
205 let (part, of): (u32, u32) = (part.parse().ok()?, of.parse().ok()?);
206 (part >= 1 && part <= of).then_some((base, part, of))
207}
208
209const QUANTS: &[&str] = &[
211 "IQ1_S", "IQ1_M", "IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ2_M", "IQ3_XXS", "IQ3_XS", "IQ3_S", "IQ3_M", "IQ4_XS", "IQ4_NL", "TQ1_0", "TQ2_0", "Q2_K_XL",
212 "Q2_K_L", "Q2_K_S", "Q3_K_XL", "Q3_K_L", "Q3_K_M", "Q3_K_S", "Q4_K_XL", "Q4_K_L", "Q4_K_M", "Q4_K_S", "Q5_K_XL", "Q5_K_L", "Q5_K_M", "Q5_K_S",
213 "Q6_K_XL", "Q6_K_L", "Q8_K_XL", "Q2_K", "Q3_K", "Q4_K", "Q5_K", "Q6_K", "Q4_0", "Q4_1", "Q5_0", "Q5_1", "Q8_0", "MXFP4", "BF16", "F16", "F32",
214];
215
216pub fn quant_of(name: &str) -> Option<String> {
218 let file = name.rsplit('/').next().unwrap_or(name).to_ascii_uppercase();
219 let stem = file.strip_suffix(".GGUF").unwrap_or(&file);
220 let bounded = |at: usize, len: usize| {
221 let before = stem[..at].chars().next_back();
222 let after = stem[at + len..].chars().next();
223 before.is_none_or(|c| !c.is_ascii_alphanumeric()) && after.is_none_or(|c| !c.is_ascii_alphanumeric())
224 };
225 QUANTS.iter().find(|q| stem.match_indices(**q).any(|(at, _)| bounded(at, q.len()))).map(|q| q.to_string())
226}
227
228pub fn group_files(files: &[RepoFile]) -> Vec<RepoModel> {
231 let mut singles = Vec::new();
232 let mut splits: std::collections::BTreeMap<(String, u32), Vec<(u32, RepoFile)>> = Default::default();
233 for f in files {
234 match split_part(&f.name) {
235 Some((base, part, of)) => {
236 let dir = f.name.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
237 splits.entry((format!("{dir}{base}"), of)).or_default().push((part, f.clone()));
238 }
239 None => singles.push(f.clone()),
240 }
241 }
242 let mut out: Vec<RepoModel> = singles
243 .into_iter()
244 .map(|f| {
245 let file = f.name.rsplit('/').next().unwrap_or(&f.name);
246 let id = file.strip_suffix(".gguf").or_else(|| file.strip_suffix(".GGUF")).unwrap_or(file).to_string();
247 RepoModel { id, quant: quant_of(&f.name), size: f.size, parts: vec![f], complete: true }
248 })
249 .collect();
250 for ((path, of), mut parts) in splits {
251 parts.sort_by_key(|(n, _)| *n);
252 parts.dedup_by_key(|(n, _)| *n);
253 let complete = parts.len() as u32 == of && parts[0].0 == 1;
254 let id = path.rsplit('/').next().unwrap_or(&path).to_string();
255 let parts: Vec<RepoFile> = parts.into_iter().map(|(_, f)| f).collect();
256 let size = parts.iter().map(|p| p.size).sum();
257 out.push(RepoModel { id, quant: quant_of(&format!("{path}.gguf")), size, parts, complete });
258 }
259 out.sort_by(|a, b| a.size.cmp(&b.size).then_with(|| a.id.cmp(&b.id)));
260 out
261}
262
263#[derive(Debug, Clone, PartialEq, Eq)]
265pub struct Hub {
266 url: String,
267 token: Option<HfToken>,
268}
269
270impl Hub {
271 pub fn new(url: impl Into<String>) -> Self {
273 Self { url: url.into().trim_end_matches('/').to_string(), token: None }
274 }
275
276 pub fn with_token(mut self, token: Option<HfToken>) -> Self {
278 self.token = token;
279 self
280 }
281
282 pub fn url(&self) -> &str {
283 &self.url
284 }
285
286 pub fn has_token(&self) -> bool {
287 self.token.is_some()
288 }
289
290 pub(crate) fn agent() -> ureq::Agent {
291 ureq::Agent::config_builder().http_status_as_error(false).redirect_auth_headers(ureq::config::RedirectAuthHeaders::SameHost).build().into()
292 }
293
294 pub(crate) fn get(&self, url: &str) -> ureq::RequestBuilder<ureq::typestate::WithoutBody> {
295 let req = Self::agent().get(url);
296 match &self.token {
297 Some(t) => req.header("Authorization", t.bearer()),
298 None => req,
299 }
300 }
301
302 fn json(&self, req: ureq::RequestBuilder<ureq::typestate::WithoutBody>, what: &str) -> Result<Value> {
303 let mut resp = req.header("Accept", "application/json").call().map_err(|e| Error::Http(e.to_string()))?;
304 match resp.status().as_u16() {
305 200 => {}
306 s @ (401 | 403) => {
307 let hint = if self.token.is_some() { "the token has no access" } else { "it may be gated or private; set HF_TOKEN on this node" };
308 return Err(Error::Http(format!("the Hub answered {s} for {what} ({hint})")));
309 }
310 s => return Err(Error::Http(format!("the Hub answered {s} for {what}"))),
311 }
312 let text = resp.body_mut().read_to_string().map_err(|e| Error::Http(e.to_string()))?;
313 serde_json::from_str(&text).map_err(|e| Error::Http(format!("the Hub's answer is not JSON: {e}")))
314 }
315
316 pub fn search(&self, search: &Search) -> Result<Vec<SearchHit>> {
318 let mut req = self
319 .get(&format!("{}/api/models", self.url))
320 .query("search", search.query.trim())
321 .query("sort", "downloads")
322 .query("direction", "-1")
323 .query("limit", search.limit.clamp(1, 100).to_string());
324 if search.gguf_only {
325 req = req.query("filter", "gguf");
326 }
327 Ok(parse_search(&self.json(req, "the search")?))
328 }
329
330 pub fn repo_files(&self, repo: &str) -> Result<Vec<RepoFile>> {
332 check_repo(repo)?;
333 let v = self.json(self.get(&format!("{}/api/models/{repo}?blobs=true", self.url)), repo)?;
334 Ok(parse_files(&v))
335 }
336
337 pub fn models(&self, repo: &str) -> Result<Vec<RepoModel>> {
339 Ok(group_files(&self.repo_files(repo)?))
340 }
341
342 pub fn gguf_info(&self, repo: &str, file: &str) -> Result<GgufInfo> {
345 check_repo(repo)?;
346 check_file(file)?;
347 let url = format!("{}/{repo}/resolve/main/{file}", self.url);
348 let mut resp =
349 self.get(&url).header("Range", format!("bytes=0-{}", gguf::HEADER_LIMIT - 1)).call().map_err(|e| Error::Http(e.to_string()))?;
350 match resp.status().as_u16() {
351 200 | 206 => {}
352 s => return Err(Error::Http(format!("the Hub answered {s} for {file}"))),
353 }
354 gguf::read_info(resp.body_mut().as_reader())
355 }
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361 use crate::testing::MockHub;
362
363 const REPO_JSON: &str = r#"{"id":"o/n","siblings":[
364 {"rfilename":"README.md","size":10},
365 {"rfilename":"m-Q4_0.gguf","size":100,"lfs":{"sha256":"abc"}},
366 {"rfilename":"mmproj-m-BF16.gguf","size":5,"lfs":{"sha256":"d"}},
367 {"rfilename":"mtp-m-Q4_0.gguf","size":6},
368 {"rfilename":"sub/m-Q8_0.GGUF","size":200}]}"#;
369
370 #[test]
371 fn repo_ids_must_look_like_owner_slash_name() {
372 assert!(check_repo("ggml-org/gemma-4-E2B-it-GGUF").is_ok());
373 for bad in ["", "a", "a/b/c", "../x", "a/..", "a b/c", "/x"] {
374 assert!(check_repo(bad).is_err(), "{bad}");
375 }
376 }
377
378 #[test]
379 fn only_model_ggufs_are_listed() {
380 let files = parse_files(&serde_json::from_str(REPO_JSON).unwrap());
381 assert_eq!(files.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["m-Q4_0.gguf", "sub/m-Q8_0.GGUF"]);
382 assert_eq!(files[0].sha256.as_deref(), Some("abc"));
383 assert_eq!(files[1].sha256, None);
384 let spec = ModelSpec::from_repo_file("o/n", &files[1]).unwrap();
385 assert_eq!((spec.id.as_str(), spec.file.as_str(), spec.size), ("m-Q8_0", "sub/m-Q8_0.GGUF", 200));
386 }
387
388 #[test]
389 fn file_names_stay_inside_the_repo() {
390 for ok in ["m.gguf", "Q4_K_M/m-00001-of-00002.gguf"] {
391 assert!(check_file(ok).is_ok(), "{ok}");
392 }
393 for bad in ["", "/m.gguf", "../m.gguf", "a/../m.gguf", "a//m.gguf", "a\\m.gguf", "C:m.gguf", "./m.gguf"] {
394 assert!(check_file(bad).is_err(), "{bad}");
395 }
396 }
397
398 #[test]
399 fn quants_come_from_file_names() {
400 assert_eq!(quant_of("Qwen3-8B-Q4_K_M.gguf").as_deref(), Some("Q4_K_M"));
401 assert_eq!(quant_of("gpt-oss-20b-MXFP4.gguf").as_deref(), Some("MXFP4"));
402 assert_eq!(quant_of("Q8_0/Big-Q8_0-00001-of-00002.gguf").as_deref(), Some("Q8_0"));
403 assert_eq!(quant_of("m-UD-Q4_K_XL.gguf").as_deref(), Some("Q4_K_XL"));
404 assert_eq!(quant_of("m-iq4_xs.gguf").as_deref(), Some("IQ4_XS"));
405 assert_eq!(quant_of("m-bf16.gguf").as_deref(), Some("BF16"));
406 assert_eq!(quant_of("model.gguf"), None);
407 assert_eq!(quant_of("XQ4_0Y.gguf"), None);
408 }
409
410 fn rf(name: &str, size: u64) -> RepoFile {
411 RepoFile { name: name.into(), size, sha256: None }
412 }
413
414 #[test]
415 fn split_files_group_into_one_model() {
416 assert_eq!(split_part("d/m-Q4_K_M-00002-of-00003.gguf"), Some(("m-Q4_K_M", 2, 3)));
417 assert_eq!(split_part("m-00004-of-00003.gguf"), None);
418 assert_eq!(split_part("m-1-of-3.gguf"), None);
419 let files = vec![
420 rf("Q8_0/m-Q8_0-00002-of-00002.gguf", 20),
421 rf("m-Q4_K_M.gguf", 10),
422 rf("Q8_0/m-Q8_0-00001-of-00002.gguf", 25),
423 rf("BF16/m-BF16-00001-of-00003.gguf", 30),
424 rf("BF16/m-BF16-00003-of-00003.gguf", 30),
425 ];
426 let models = group_files(&files);
427 assert_eq!(
428 models.iter().map(|m| (m.id.as_str(), m.size, m.complete)).collect::<Vec<_>>(),
429 [("m-Q4_K_M", 10, true), ("m-Q8_0", 45, true), ("m-BF16", 60, false)]
430 );
431 let q8 = &models[1];
432 assert!(q8.is_split());
433 assert_eq!(q8.first().name, "Q8_0/m-Q8_0-00001-of-00002.gguf");
434 assert_eq!(q8.quant.as_deref(), Some("Q8_0"));
435 let specs = q8.specs("o/n").unwrap();
436 assert_eq!(
437 specs.iter().map(|s| (s.id.as_str(), s.file.as_str())).collect::<Vec<_>>(),
438 [("m-Q8_0", "Q8_0/m-Q8_0-00001-of-00002.gguf"), ("m-Q8_0", "Q8_0/m-Q8_0-00002-of-00002.gguf")]
439 );
440 let mut bad = q8.clone();
441 bad.parts[1].name = "../x.gguf".into();
442 assert!(bad.specs("o/n").is_err());
443 }
444
445 const SEARCH_JSON: &str = r#"[
446 {"id":"o/a-GGUF","downloads":50,"likes":3,"gated":false,"pipeline_tag":"text-generation","lastModified":"2026-11-01T00:00:00.000Z"},
447 {"id":"o/b-GGUF","downloads":7,"gated":"manual"},
448 {"id":"../bad","downloads":1}]"#;
449
450 #[test]
451 fn searches_send_the_query_and_the_token() {
452 let hub = MockHub::start_with(vec![("/api/models".into(), "application/json", SEARCH_JSON.as_bytes().to_vec())]);
453 let client = Hub::new(hub.url()).with_token(HfToken::new("hf_x"));
454 let hits = client.search(&Search::new("qwen 3").with_limit(500)).unwrap();
455 assert_eq!(hits.iter().map(|h| (h.id.as_str(), h.downloads, h.gated)).collect::<Vec<_>>(), [("o/a-GGUF", 50, false), ("o/b-GGUF", 7, true)]);
456 assert_eq!(hits[0].pipeline_tag.as_deref(), Some("text-generation"));
457 let seen = hub.seen();
458 let path = &seen[0].path;
459 assert!(
460 path.contains("search=qwen") && path.contains("filter=gguf") && path.contains("limit=100") && path.contains("sort=downloads"),
461 "{path}"
462 );
463 assert_eq!(seen[0].auth.as_deref(), Some("Bearer hf_x"));
464 Hub::new(hub.url()).search(&Search::new("q").with_gguf_only(false)).unwrap();
465 let seen = hub.seen();
466 assert!(!seen[1].path.contains("filter=gguf"));
467 assert_eq!(seen[1].auth, None, "no token, no header");
468 }
469
470 #[test]
471 fn missing_repos_report_the_status() {
472 let hub = MockHub::start_with(vec![]);
473 let err = Hub::new(hub.url()).repo_files("o/n").unwrap_err();
474 assert!(err.to_string().contains("404"), "{err}");
475 }
476
477 #[test]
478 fn reads_a_header_with_a_range_request() {
479 let mut body = crate::gguf::header(&[
480 ("general.architecture", serde_json::json!("llama")),
481 ("llama.block_count", serde_json::json!(2)),
482 ("llama.attention.head_count", serde_json::json!(4)),
483 ("llama.attention.head_count_kv", serde_json::json!(2)),
484 ("llama.attention.key_length", serde_json::json!(16)),
485 ]);
486 body.extend(vec![0u8; 1000]);
487 let hub = MockHub::start("/o/n/resolve/main/d/m.gguf", body);
488 let info = Hub::new(hub.url()).gguf_info("o/n", "d/m.gguf").unwrap();
489 assert_eq!(info.kv_bytes_per_token(), 2 * 2 * 32 * 2);
490 assert_eq!(hub.last_range().as_deref(), Some("bytes=0-67108863"));
491 assert!(Hub::new(hub.url()).gguf_info("o/n", "../m.gguf").is_err());
492 }
493
494 #[test]
495 fn reads_a_repo_from_the_hub_api() {
496 let hub = MockHub::start_with(vec![("/api/models/o/n".into(), "application/json", REPO_JSON.as_bytes().to_vec())]);
497 assert_eq!(repo_files(hub.url(), "o/n").unwrap().len(), 2);
498 assert!(matches!(repo_files(hub.url(), "o/missing"), Err(Error::Http(ref m)) if m.contains("404")));
499 assert!(matches!(repo_files(hub.url(), "bad"), Err(Error::BadRepo(_))));
500 }
501
502 #[test]
504 #[ignore = "uses the network"]
505 fn live_hub() {
506 let hub = Hub::new(crate::store::HUB).with_token(HfToken::from_env());
507 let hits = hub.search(&Search::new("Qwen3-0.6B").with_limit(5)).unwrap();
508 assert!(!hits.is_empty());
509 let models = hub.models("ggml-org/gemma-4-E2B-it-GGUF").unwrap();
510 let q4 = models.iter().find(|m| m.quant.as_deref() == Some("Q4_0")).expect("a Q4_0 file");
511 let info = hub.gguf_info("ggml-org/gemma-4-E2B-it-GGUF", &q4.first().name).unwrap();
512 assert!(info.layers > 0 && info.kv_bytes_per_token() > 0, "{info:?}");
513 let fit = crate::fit::choose(
514 &models,
515 &crate::hw::Budget { pool_bytes: 0, reserve_bytes: 0, usable_bytes: 8 << 30 },
516 &crate::fit::FitOptions::default().with_info(&info),
517 );
518 assert!(fit.is_some());
519 eprintln!("{} hits; {} models; {info:?}; best {:?}", hits.len(), models.len(), fit.map(|f| (f.model.id, f.footprint)));
520 }
521}