AI Text Summarizer — Java 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 Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// text-summarizer — prompt building, reply cleanup, and text stats.
//
// Language: Java (17, standard library only)
// CosmoDev polyglot showcase port of the `text-summarizer` tool, ported
// from src/lib/summarize.ts (the canonical TypeScript implementation).
//
// java.util.regex carries the TS lib's two patterns verbatim, and the JVM
// string is UTF-16, so length() IS the JS .length — chars and the
// truncation cut need no unit juggling. The class is non-public so the
// file can keep the showcase's language-named filename.
//
// display source — part of CosmoDev's polyglot tool pages.
//
// Run: java java.java (single-file source launch, Java 11+)
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final class TextSummarizer {
/** Styles, mirroring the TS SummaryStyle union. */
static final List<String> STYLES = List.of("tldr", "bullets", "detailed");
/** Input cap: longer pastes are cut (and marked) before reaching the model. */
static final int MAX_INPUT_CHARS = 12000;
/** Word / sentence / character counts, tolerant of empty input. */
record Stats(int words, int sentences, int chars) {}
/** One [role, content] chat message for the provider layer. */
record Message(String role, String content) {}
/** The per-style system-prompt contract, byte-for-byte the TS lib's. */
static final Map<String, String> STYLE_CONTRACT = Map.of(
"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.");
static final Pattern TERMINATOR_RUNS = Pattern.compile("[.!?]+");
static final Pattern CODE_FENCES = Pattern.compile("```[a-z]*\n?");
/**
* Count words / sentences / characters; tolerant of empty input. Chars
* is length() — UTF-16 code units, like JS .length, so astral characters
* (emoji, etc.) count 2 with no extra code. Sentences count TERMINATOR
* runs, never the quadratic body regex, the trap the TS lib's comment
* documents.
*/
static Stats textStats(String text) {
String trimmed = text.trim();
int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
Matcher runs = TERMINATOR_RUNS.matcher(text);
int sentences = 0;
while (runs.find()) sentences++;
return new Stats(words, sentences, text.length());
}
/**
* Build the [system, user] chat messages for the provider layer; long
* pastes are cut at MAX_INPUT_CHARS UTF-16 units — exactly the JS
* slice(0, limit) — and marked with a visible truncation note.
*
* @throws IllegalArgumentException on a style outside STYLES (the TS
* union makes that state unrepresentable; Java throws instead).
*/
static List<Message> buildPromptMessages(String text, String style) {
String contract = STYLE_CONTRACT.get(style);
if (contract == null)
throw new IllegalArgumentException("unknown style: " + style);
Stats stats = textStats(text);
String body = text.length() > MAX_INPUT_CHARS
? text.substring(0, MAX_INPUT_CHARS) + "\n… (text truncated)"
: text;
return List.of(
new Message("system", "You summarize text faithfully. " + contract),
new Message("user",
"Summarize the following text (" + style + " style; " + stats.words()
+ " words, " + stats.sentences() + " sentences).\n\n" + body));
}
/**
* Clean the model's reply into displayable summary text — any non-empty
* cleaned text is the summary; null only when nothing survives.
*/
static String parseSummary(String text) {
String cleaned = CODE_FENCES.matcher(text).replaceAll("").trim();
return cleaned.isEmpty() ? null : cleaned;
}
public static void main(String[] args) {
Stats s = textStats("Hello world. Hi! Am I tidy? ");
System.out.println("words=" + s.words() + " sentences=" + s.sentences() + " chars=" + s.chars());
for (Message m : buildPromptMessages("paste here", "tldr"))
System.out.println(m.role() + ": " + m.content());
System.out.println(parseSummary("```text\nthe summary\n```")); // the summary
System.out.println(parseSummary(" \n")); // null
try {
buildPromptMessages("x", "haiku");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
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 →