AI Text Summarizer — Swift 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 Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// text-summarizer — prompt building, reply cleanup, and text stats.
//
// Language: Swift (5, Foundation allowed)
// CosmoDev polyglot showcase port of the `text-summarizer` tool, ported
// from src/lib/summarize.ts (the canonical TypeScript implementation).
//
// Foundation's NSRegularExpression-free path carries the TS lib: the two
// regexes run through replacingOccurrences(options: .regularExpression).
// Swift strings are grapheme-cluster collections, so the one semantic
// wrinkle is chars — counted (and the truncation cut) in UTF-16 units via
// .utf16, because JS .length counts code units and astral characters
// (emoji, etc.) count 2.
//
// display source — part of CosmoDev's polyglot tool pages.
//
// Run: swift swift.swift
import Foundation
/// Styles, mirroring the TS SummaryStyle union.
let summarizerStyles = ["tldr", "bullets", "detailed"]
/// Input cap: longer pastes are cut (and marked) before reaching the model.
let maxInputChars = 12000
/// The per-style system-prompt contract, byte-for-byte the TS lib's.
let styleContract = [
"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.",
]
/// Word / sentence / character counts, tolerant of empty input.
struct TextStats {
let words: Int
let sentences: Int
let chars: Int
}
/// One [role, content] chat message for the provider layer.
struct Message {
let role: String
let content: String
}
/// A failed prompt build — the TS union makes unknown styles unrepresentable;
/// Swift throws instead.
enum SummarizerError: Error, CustomStringConvertible {
case unknownStyle(String)
var description: String {
switch self {
case .unknownStyle(let style): return "unknown style: \(style)"
}
}
}
/// Count words / sentences / characters; tolerant of empty input.
///
/// Sentences count TERMINATOR runs ([.!?]+), never the quadratic body
/// regex, the trap the TS lib's comment documents; chars is text.utf16.count,
/// the JS .length, so astral characters count 2.
func textStats(_ text: String) -> TextStats {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
let words = trimmed.isEmpty
? 0
: trimmed.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty }.count
var sentences = 0
var inRun = false
for ch in text {
let stop = ch == "." || ch == "!" || ch == "?"
if stop && !inRun { sentences += 1 }
inRun = stop
}
return TextStats(words: words, sentences: sentences, chars: text.utf16.count)
}
/// Build the [system, user] chat messages for the provider layer; long
/// pastes are cut at maxInputChars UTF-16 units — the JS slice(0, limit) —
/// and marked with a visible truncation note.
func buildPromptMessages(_ text: String, style: String = "tldr") throws -> [Message] {
guard let contract = styleContract[style] else {
throw SummarizerError.unknownStyle(style)
}
let stats = textStats(text)
let body = text.utf16.count > maxInputChars
? String(decoding: text.utf16.prefix(maxInputChars), as: UTF16.self)
+ "\n… (text truncated)"
: text
return [
Message(role: "system", content: "You summarize text faithfully. \(contract)"),
Message(
role: "user",
content: "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; nil only when nothing survives.
func parseSummary(_ text: String) -> String? {
let cleaned = text.replacingOccurrences(
of: "```[a-z]*\n?", with: "", options: .regularExpression
).trimmingCharacters(in: .whitespacesAndNewlines)
return cleaned.isEmpty ? nil : cleaned
}
// Demo — `swift swift.swift`
let s = textStats("Hello world. Hi! Am I tidy? ")
print("words=\(s.words) sentences=\(s.sentences) chars=\(s.chars)")
do {
for m in try buildPromptMessages("paste here") {
print("\(m.role): \(m.content)")
}
print(parseSummary("```text\nthe summary\n```")!) // the summary
print(parseSummary(" \n") ?? "nil") // nil
} catch {
print("unexpected failure: \(error)")
}
do {
_ = try buildPromptMessages("x", style: "haiku")
} catch {
print(error) // unknown style: haiku
}
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 →