tessera-command 0.4.19

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
//! `models`: known architectures and the weights recipes pin.

use crate::source::Stop;
use std::fmt::Write;
use std::path::Path;
use tessera_frontend::frontend_settings::HUB;
use tessera_frontend::recipe::{Catalog, Recipe};

/// The README heading whose section `--readme` rewrites.
const HEADING: &str = "## Supported Models";

/// Model folders that load outside the architecture list.
const OTHER: [(&str, &str); 1] = [("spacy", "a spaCy pipeline folder, for `task tag`")];

/// `models` prints the list. `models --readme <path>` rewrites its section.
pub fn run(args: &[String]) -> Result<(), Stop> {
    match args {
        [] => {
            print!("{}", table(&[]));
            Ok(())
        }
        [flag, path] if flag == "--readme" => readme(Path::new(path)),
        _ => Err(Stop::Usage),
    }
}

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(())
}

/// Example recipes with Hugging Face weights, by path from `root`.
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)
}

/// Markdown: catalog picks, `examples`, then architectures.
pub fn table(examples: &[(String, Recipe)]) -> String {
    let mut out = String::new();
    out.push_str("Each recipe pins a supported Hugging Face weight set. ");
    out.push_str("Run it with `tessera --recipe <recipe>`.\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(", ")
}

/// `text` with the body under `HEADING` set to `body`.
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..]))
}