Skip to content

AI Text Summarizer — Python 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 Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""text-summarizer — prompt building, reply cleanup, and text stats.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `text-summarizer` tool, ported from
src/lib/summarize.ts (the canonical TypeScript implementation).

The TS lib is a thin pure core around an AI provider call, so ``re`` and
``str`` primitives carry the port almost verbatim. The one semantic wrinkle
is ``chars``: JS ``.length`` counts UTF-16 code units, so the helpers below
count the same way (astral code points — emoji etc. — count 2).

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import re

SUMMARY_STYLES = ("tldr", "bullets", "detailed")

STYLE_CONTRACT = {
    "tldr": "Summarize the text as ONE sentence of at most 25 words. Plain text, no preamble, no bullets.",
    "bullets": 'Summarize the text as 3 to 6 markdown bullets, each starting with "- " and covering one distinct point. No preamble, no closing remark.',
    "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.",
}

MAX_INPUT_CHARS = 12000


def _utf16_units(ch: str) -> int:
    """Width of one code point in UTF-16 code units (2 for astral, else 1)."""
    return 2 if ord(ch) > 0xFFFF else 1


def _utf16_length(text: str) -> int:
    """JS ``text.length``: the UTF-16 code unit count of ``text``."""
    return sum(_utf16_units(ch) for ch in text)


def text_stats(text: str) -> dict[str, int]:
    """Count words / sentences / characters; tolerant of empty input.

    Sentences count TERMINATOR runs (``[.!?]+``), not sentence bodies — the
    body regex is quadratic on terminator-free input, the trap the TS lib's
    comment documents. ``str.split()`` matches the JS trim-then-split on
    Unicode whitespace, and yields ``[]`` (0 words) for empty input.
    """
    return {
        "words": len(text.split()),
        "sentences": len(re.findall(r"[.!?]+", text)),
        "chars": _utf16_length(text),
    }


def _truncate(text: str) -> str:
    """Cut to the first MAX_INPUT_CHARS UTF-16 code units, marking the cut."""
    units = 0
    for i, ch in enumerate(text):
        if units + _utf16_units(ch) > MAX_INPUT_CHARS:
            return text[:i] + "\n… (text truncated)"
        units += _utf16_units(ch)
    return text


def build_prompt_messages(
    text: str, style: str = "tldr"
) -> list[dict[str, str]]:
    """Build the [system, user] chat messages for the provider layer.

    Pastes past MAX_INPUT_CHARS are cut (in UTF-16 units, like JS ``slice``)
    with a visible marker.

    Raises:
        ValueError: on a style outside SUMMARY_STYLES (the TS union type
            makes that state unrepresentable; Python raises instead).
    """
    if style not in STYLE_CONTRACT:
        raise ValueError(f"unknown style: {style!r}")
    stats = text_stats(text)
    body = _truncate(text) if _utf16_length(text) > MAX_INPUT_CHARS else text
    return [
        {"role": "system", "content": f"You summarize text faithfully. {STYLE_CONTRACT[style]}"},
        {
            "role": "user",
            "content": (
                f"Summarize the following text ({style} style; "
                f"{stats['words']} words, {stats['sentences']} sentences).\n\n{body}"
            ),
        },
    ]


def parse_summary(text: str) -> str | None:
    """Clean the model's reply into displayable summary text.

    Unlike the commit-message parser there is no strict format contract —
    any non-empty cleaned text is the summary; None only when nothing
    survives the code-fence strip and trim.
    """
    cleaned = re.sub(r"```[a-z]*\n?", "", text).strip()
    return cleaned if cleaned else None

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 →