AI Text Summarizer — C 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 C implementation — the same logic the interactive tool runs, in a shareable, citable form.
/*
* text-summarizer — prompt building, reply cleanup, and text stats.
*
* Language: C (C11, 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's regexes become byte scans: terminator runs (counted, never
* matched — the body regex is quadratic on terminator-free input) and a
* hand-rolled fence stripper. chars counts UTF-16 code units so astral
* characters count 2, exactly like JS .length; multi-byte UTF-8 sequences
* never contain ASCII bytes, so the byte scans are UTF-8 safe.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** Summary styles, mirroring the TS SummaryStyle union. */
typedef enum { TS_TLDR, TS_BULLETS, TS_DETAILED } ts_style;
/** Input cap: longer pastes are cut (and marked) before reaching the model. */
#define TS_MAX_INPUT_CHARS 12000
/** Word / sentence / character counts, tolerant of empty input. */
typedef struct { size_t words, sentences, chars; } ts_stats;
/* chars is UTF-16 code units, like JS .length. */
/** The [system, user] chat messages for the provider layer; each string is
* malloc'd and the caller frees both. */
typedef struct { char *system, *user; } ts_prompt;
/** Wire name + system-prompt contract per style, byte-for-byte the TS lib. */
static const struct { const char *name, *contract; }
TS_STYLES[] = {
[TS_TLDR] = { "tldr",
"Summarize the text as ONE sentence of at most 25 words. "
"Plain text, no preamble, no bullets." },
[TS_BULLETS] = { "bullets",
"Summarize the text as 3 to 6 markdown bullets, each starting with "
"\"- \" and covering one distinct point. No preamble, no closing remark." },
[TS_DETAILED] = { "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." },
};
/* The six whitespace characters JavaScript's \s and C's isspace() share. */
static bool ts_is_space(unsigned char b)
{
return b == ' ' || b == '\t' || b == '\n'
|| b == '\v' || b == '\f' || b == '\r';
}
static char *ts_strdup(const char *s)
{
size_t n = strlen(s) + 1;
char *out = malloc(n);
if (out != NULL) memcpy(out, s, n);
return out;
}
/** Byte length of the UTF-8 sequence led by b (stray bytes ride as one). */
static size_t ts_utf8_len(unsigned char b)
{
if ((b & 0x80) == 0) return 1;
if ((b & 0xE0) == 0xC0) return 2;
if ((b & 0xF0) == 0xE0) return 3;
return (b & 0xF8) == 0xF0 ? 4 : 1;
}
/** UTF-16 width of the code point at p: 2 for astral, 1 otherwise. */
static size_t ts_utf16_width(const unsigned char *p, size_t n)
{
uint32_t cp = (n == 1) ? p[0]
: (n == 2) ? ((uint32_t)(p[0] & 0x1F) << 6) | (p[1] & 0x3F)
: (n == 3) ? ((uint32_t)(p[0] & 0x0F) << 12)
| ((uint32_t)(p[1] & 0x3F) << 6) | (p[2] & 0x3F)
: (((uint32_t)(p[0] & 0x07) << 18) | ((uint32_t)(p[1] & 0x3F) << 12)
| ((uint32_t)(p[2] & 0x3F) << 6) | (p[3] & 0x3F));
return cp >= 0x10000 ? 2 : 1;
}
/**
* 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.
*/
ts_stats ts_text_stats(const char *text)
{
const unsigned char *p = (const unsigned char *)text;
size_t len = strlen(text);
ts_stats st = {0, 0, 0};
bool in_word = false; /* trim().split(/\s+/), in one pass */
for (size_t i = 0; i < len; i++) {
if (ts_is_space(p[i])) in_word = false;
else if (!in_word) { in_word = true; st.words++; }
}
bool in_run = false; /* count [.!?]+ runs, not sentence bodies */
for (size_t i = 0; i < len; i++) {
bool stop = p[i] == '.' || p[i] == '!' || p[i] == '?';
if (stop && !in_run) st.sentences++;
in_run = stop;
}
for (size_t i = 0; i < len; ) {
size_t n = ts_utf8_len(p[i]);
st.chars += ts_utf16_width(p + i, n);
i += n;
}
return st;
}
/** The TS text.slice(0, limit) with a UTF-16 unit budget, so the cut lands
* between runes. Returns a malloc'd string, or NULL on allocation failure. */
static char *ts_slice_utf16(const char *text, size_t limit)
{
const unsigned char *p = (const unsigned char *)text;
size_t len = strlen(text), units = 0, cut = len;
for (size_t i = 0; i < len; ) {
size_t n = ts_utf8_len(p[i]), w = ts_utf16_width(p + i, n);
if (units + w > limit) { cut = i; break; }
units += w;
i += n;
}
char *out = malloc(cut + 1);
if (out != NULL) {
memcpy(out, text, cut);
out[cut] = '\0';
}
return out;
}
/**
* Build the [system, user] chat messages for the provider layer; long pastes
* are truncated with a visible marker. Returns a ts_prompt whose two strings
* are malloc'd (caller frees both), or {NULL, NULL} on allocation failure.
*/
ts_prompt ts_build_prompt_messages(const char *text, ts_style style)
{
const char *PREFIX =
"Summarize the following text (%s style; %zu words, %zu sentences).\n\n";
const char *MARKER = "\n… (text truncated)"; /* 21 bytes */
ts_stats st = ts_text_stats(text);
bool truncated = st.chars > TS_MAX_INPUT_CHARS;
char *body = truncated ? ts_slice_utf16(text, TS_MAX_INPUT_CHARS)
: ts_strdup(text);
if (body == NULL) return (ts_prompt){NULL, NULL};
ts_prompt out = {NULL, NULL};
int head = snprintf(NULL, 0, PREFIX, TS_STYLES[style].name, st.words, st.sentences);
out.system = malloc(strlen("You summarize text faithfully. ")
+ strlen(TS_STYLES[style].contract) + 1);
if (head >= 0) out.user = malloc((size_t)head + strlen(body)
+ (truncated ? strlen(MARKER) : 0) + 1);
if (out.system == NULL || out.user == NULL) {
free(out.system);
free(out.user);
free(body);
return (ts_prompt){NULL, NULL};
}
snprintf(out.system, strlen("You summarize text faithfully. ")
+ strlen(TS_STYLES[style].contract) + 1,
"You summarize text faithfully. %s", TS_STYLES[style].contract);
snprintf(out.user, (size_t)head + 1, PREFIX, TS_STYLES[style].name, st.words, st.sentences);
strcat(out.user, body);
if (truncated) strcat(out.user, MARKER);
free(body);
return out;
}
/**
* Clean the model's reply into displayable summary text — any non-empty
* cleaned text is the summary; NULL only when nothing survives. Returns a
* malloc'd string the caller frees.
*/
char *ts_parse_summary(const char *text)
{
const unsigned char *p = (const unsigned char *)text;
size_t len = strlen(text);
char *out = malloc(len + 1);
if (out == NULL) return NULL;
/* Drop every /```[a-z]*\n?/ match: "```" opens a fence, optional
* lowercase letters name the language, one optional newline ends it. */
size_t o = 0;
for (size_t i = 0; i < len; ) {
if (i + 3 <= len && memcmp(p + i, "```", 3) == 0) {
i += 3;
while (i < len && p[i] >= 'a' && p[i] <= 'z') i++;
if (i < len && p[i] == '\n') i++;
} else {
out[o++] = (char)p[i++];
}
}
/* trim() — both ends, the six whitespace characters. */
size_t start = 0, end = o;
while (start < end && ts_is_space((unsigned char)out[start])) start++;
while (end > start && ts_is_space((unsigned char)out[end - 1])) end--;
memmove(out, out + start, end - start);
out[end - start] = '\0';
if (start == end) { free(out); return NULL; }
return 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 →