Skip to content

AI Text Summarizer — Rust source

Paste any text and get an LLM summary — TL;DR, bullets, or detailed — using your own free Groq key, called straight from your browser.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! text-summarizer - prompt building, reply cleanup, and text stats.
//!
//! Language: Rust (std only - no external crates).
//! CosmoDev polyglot showcase port of the `text-summarizer` tool, ported from
//! src/lib/summarize.ts (the canonical TypeScript implementation).
//!
//! std has no regex, so the TS lib's two tiny patterns become a counting
//! scan (terminator runs) and a hand-rolled fence stripper; `chars` counts
//! UTF-16 code units via char::len_utf16, matching JS `.length` exactly.

/// Summary styles mirror the SummaryStyle union in the TS lib.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Style { Tldr, Bullets, Detailed }

impl Style {
    /// Wire name, as in the TS union ('tldr' | 'bullets' | 'detailed').
    fn name(self) -> &'static str {
        ["tldr", "bullets", "detailed"][self as usize]
    }
    /// Per-style system-prompt contract, byte-for-byte the TS STYLE_CONTRACT.
    fn contract(self) -> &'static str {
        match self {
            Style::Tldr => "Summarize the text as ONE sentence of at most 25 words. Plain text, no preamble, no bullets.",
            Style::Bullets => "Summarize the text as 3 to 6 markdown bullets, each starting with \"- \" and covering one distinct point. No preamble, no closing remark.",
            Style::Detailed => "Summarize the text as 2 to 4 short paragraphs: what it is about, the key facts, and the outcome or next step. No preamble, no headings.",
        }
    }
}

/// Word / sentence / character counts, tolerant of empty input.
pub struct TextStats {
    pub words: usize,
    pub sentences: usize,
    pub chars: usize,
}

/// One [role, content] chat message for the provider layer.
pub struct Message {
    pub role: &'static str,
    pub content: String,
}

/// Input cap: longer pastes are cut (and marked) before reaching the model.
pub const MAX_INPUT_CHARS: usize = 12000;

/// Count words / sentences / characters; tolerant of empty input. Sentences
/// count TERMINATOR runs (the body regex is quadratic on such input); chars
/// counts UTF-16 units like JS .length (astral chars = 2).
pub fn text_stats(text: &str) -> TextStats {
    TextStats {
        words: text.split_whitespace().count(),
        sentences: terminator_runs(text),
        chars: text.chars().map(|c| c.len_utf16()).sum(),
    }
}

/// Count non-overlapping terminator runs (the JS /[.!?]+/g match count).
fn terminator_runs(text: &str) -> usize {
    let (mut runs, mut in_run) = (0, false);
    for c in text.chars() {
        let stop = matches!(c, '.' | '!' | '?');
        runs += usize::from(stop && !in_run);
        in_run = stop;
    }
    runs
}

/// Build the [system, user] chat messages; long pastes are cut like JS `.slice`.
pub fn build_prompt_messages(text: &str, style: Style) -> Vec<Message> {
    let stats = text_stats(text);
    let body = slice_utf16(text, MAX_INPUT_CHARS, "… (text truncated)");
    vec![
        Message {
            role: "system",
            content: format!("You summarize text faithfully. {}", style.contract()),
        },
        Message {
            role: "user",
            content: format!(
                "Summarize the following text ({} style; {} words, {} sentences).\n\n{}",
                style.name(), stats.words, stats.sentences, body
            ),
        },
    ]
}

/// The TS `text.length > MAX ? text.slice(0, MAX) + "\n" + marker : text`,
/// with a UTF-16 unit budget that still lands the cut between runes.
fn slice_utf16(text: &str, max: usize, marker: &str) -> String {
    let (mut units, mut cut) = (0, None);
    for (i, c) in text.char_indices() {
        if units + c.len_utf16() > max { cut = Some(i); break; }
        units += c.len_utf16();
    }
    cut.map_or_else(|| text.to_string(), |i| format!("{}\n{}", &text[..i], marker))
}

/// Clean the model's reply into displayable summary text; None if empty.
pub fn parse_summary(text: &str) -> Option<String> {
    let cleaned = strip_code_fences(text).trim().to_string();
    (!cleaned.is_empty()).then_some(cleaned)
}

/// Remove every /```[a-z]*\n?/ match: a "```" opens a fence, optional
/// lowercase letters name the language, one optional newline closes it.
fn strip_code_fences(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i..].starts_with(b"```") {
            i += 3;
            while i < bytes.len() && bytes[i].is_ascii_lowercase() { i += 1; }
            if i < bytes.len() && bytes[i] == b'\n' { i += 1; }
        } else {
            let ch = text[i..].chars().next().unwrap(); // i is a char boundary
            out.push(ch);
            i += ch.len_utf8();
        }
    }
    out
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →