use crate::source::Stop;
use std::fmt::Write;
use std::path::{Path, PathBuf};
use tessera_frontend::frontend_settings::HUB;
use tessera_frontend::recipe::{Catalog, Recipe};
use tessera_frontend::tasks::Error;
use tessera_frontend::tasks::task::{Run, Shown, Sink, Task};
const HEADING: &str = "## Supported Models";
const OTHER: [(&str, &str); 1] = [("spacy", "a spaCy pipeline folder, for `task tag`")];
#[derive(Task)]
pub(crate) struct Models {
#[arg(value = "<path>", cli_only)]
pub readme: Option<PathBuf>,
}
impl Run<()> for Models {
fn run(self, _: (), sink: &mut dyn Sink) -> Result<(), Error> {
match self.readme {
None => {
let table = table(&[]);
if !sink.show(Shown::Markdown(&table)) {
sink.text(&table);
}
Ok(())
}
Some(path) => Ok(readme(&path)?),
}
}
}
crate::task::register!(Models, crate::task::OnMachine, "", false);
fn readme(path: &Path) -> Result<(), Stop> {
let failed = |e: std::io::Error| Stop::Failed(format!("{}: {e}", path.display()));
let root = path.parent().unwrap_or(Path::new("."));
let text = std::fs::read_to_string(path).map_err(failed)?;
let new = splice(&text, &table(&examples(root)?))?;
if new != text {
std::fs::write(path, new).map_err(failed)?;
}
Ok(())
}
pub fn examples(root: &Path) -> Result<Vec<(String, Recipe)>, Stop> {
let dir = root.join("examples/recipes");
let failed = |e: std::io::Error| Stop::Failed(format!("{}: {e}", dir.display()));
let mut out = Vec::new();
for entry in std::fs::read_dir(&dir).map_err(failed)? {
let path = entry.map_err(failed)?.path();
if !path.join("recipe.toml").exists() {
continue;
}
let recipe = Recipe::read(&path)?;
if recipe.weights.hf.is_none() {
continue;
}
let name = path.file_name().unwrap_or_default().to_string_lossy();
out.push((format!("examples/recipes/{name}"), recipe));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
Ok(out)
}
pub fn table(examples: &[(String, Recipe)]) -> String {
let mut out = String::new();
out.push_str("Run recipes with `tessera --recipe <recipe>`. ");
out.push_str("Recipes include a pinned set of huggingface weights ");
out.push_str("that are tested and approved by Kindling.\n\n");
out.push_str("| Recipe | Weights | About |\n| --- | --- | --- |\n");
if let Ok(catalog) = Catalog::embedded() {
for family in &catalog.families {
for pick in &family.picks {
if let Ok(recipe) = pick.recipe() {
row(&mut out, &family.family, &recipe);
}
}
}
}
for (path, recipe) in examples {
row(&mut out, path, recipe);
}
out.push_str("\nOther weights can be automatically loaded with ");
out.push_str("`tessera --model hf:<owner>/<name>` ");
out.push_str("based on their `config.json` architecture.\n\n");
out.push_str("| Architecture | `model_type` | `architectures` or `_class_name` |\n");
out.push_str("| --- | --- | --- |\n");
for known in tessera_frontend::bundle::architectures() {
let mut types = code(&known.types);
for probe in known.probes {
types.push_str(probe);
}
let classes = code(&known.classes);
let _ = writeln!(out, "| `{}` | {types} | {classes} |", known.name);
}
for (name, about) in OTHER {
let _ = writeln!(out, "| `{name}` | {about} | |");
}
out
}
fn row(out: &mut String, run: &str, recipe: &Recipe) {
let Some(hf) = &recipe.weights.hf else {
return;
};
let (repo, commit) = hf.split_once('@').unwrap_or((hf, "main"));
let short = &commit[..commit.len().min(7)];
let link = format!("[{repo}@{short}](https://{HUB}/{repo}/tree/{commit})");
let about = recipe.about.as_deref().unwrap_or("").replace('|', "\\|");
let _ = writeln!(out, "| `{run}` | {link} | {about} |");
}
fn code(words: &[&str]) -> String {
let quoted: Vec<String> = words.iter().map(|w| format!("`{w}`")).collect();
quoted.join(", ")
}
pub fn splice(text: &str, body: &str) -> Result<String, Stop> {
let missing = || Stop::Failed(format!("no `{HEADING}` heading"));
let start = text.find(&format!("\n{HEADING}\n")).ok_or_else(missing)? + HEADING.len() + 2;
let end = match text[start..].find("\n## ") {
Some(at) => start + at + 1,
None => text.len(),
};
Ok(format!("{}\n{body}\n{}", &text[..start], &text[end..]))
}