prompt-compressor 1.0.2 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +14 -8
- package/index.js +11 -5
- package/package.json +1 -1
- package/src/algorithms.js +210 -151
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tom Ketter
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
|
|
7
7
|
⭐ **Find it useful? [Star it on GitHub](https://github.com/kettertom/prompt-compressor)** · 🐛 **Found a bug or have an idea? [Open an issue](https://github.com/kettertom/prompt-compressor/issues/new)**
|
|
8
8
|
|
|
9
|
+
**No model. No API key. Deterministic. Zero dependencies. Your data never leaves your machine.** At the default level it cut **22% of tokens across 8 real-world prompt types while keeping 94/94 critical instructions**. See the [benchmark](https://github.com/kettertom/prompt-compressor#benchmark).
|
|
10
|
+
|
|
11
|
+
> 🔧 **Upgrade to 1.0.4 or later.** 1.0.3 and earlier could delete a rule or ID written after a colon ("Here is the account to use: ACC-7781.") and stripped indentation inside code blocks, which breaks Python/YAML. 1.0.2 and earlier also corrupted ```json blocks at `low` and kept only ~22% of critical facts at `medium`. All fixed and covered by tests and the benchmark.
|
|
12
|
+
|
|
9
13
|
## Install
|
|
10
14
|
|
|
11
15
|
```bash
|
|
@@ -27,12 +31,12 @@ console.log(stats);
|
|
|
27
31
|
|
|
28
32
|
Pick a level — every algorithm at or below that risk runs automatically.
|
|
29
33
|
|
|
30
|
-
| Level | What runs |
|
|
34
|
+
| Level | What runs | Measured saving ([benchmark](https://github.com/kettertom/prompt-compressor#benchmark)) |
|
|
31
35
|
|---|---|---|
|
|
32
|
-
| `'none'` | Whitespace, unicode normalization, indentation |
|
|
33
|
-
| `'very-low'` | + Filler removal, phrase shortening, JSON/SQL minify |
|
|
34
|
-
| `'low'` | + Hedging removal, code comments, deduplication, stack trace truncation |
|
|
35
|
-
| `'medium'` | +
|
|
36
|
+
| `'none'` | Whitespace, unicode normalization, indentation | 2% avg (0–16%) |
|
|
37
|
+
| `'very-low'` | + Filler removal, phrase shortening, JSON/SQL minify | 8% avg (0–32%) |
|
|
38
|
+
| `'low'` | + Hedging removal, code comments, deduplication, stack trace truncation | **22% avg (2–56%)**, 100% of critical facts kept |
|
|
39
|
+
| `'medium'` | + Near-duplicate removal (fuzzy / n-gram / Levenshtein), TextRank on plain prose only | 24% avg (5–56%), 100% of critical facts kept |
|
|
36
40
|
|
|
37
41
|
```js
|
|
38
42
|
compress(text, 'none') // safest
|
|
@@ -41,6 +45,8 @@ compress(text, 'low') // recommended default
|
|
|
41
45
|
compress(text, 'medium') // most aggressive
|
|
42
46
|
```
|
|
43
47
|
|
|
48
|
+
> **`medium` = `low` + near-duplicate removal + light summarization of plain prose.** Code blocks, lists, tables, `Key: value` lines, questions, and any sentence with a rule, number, ID or variable are never removed. On the dense prompts in the benchmark it saves about the same as `low` (24% vs 22%) and kept 94/94 critical facts. It helps most on long, chatty prose. *(Before 1.0.3, `medium` chained three summarizers and kept only 22% of critical facts. Upgrade if you used it.)*
|
|
49
|
+
|
|
44
50
|
## Custom options
|
|
45
51
|
|
|
46
52
|
Override specific algorithms or parameters:
|
|
@@ -153,9 +159,9 @@ compress("Please {{user_name}}, utilize this in order to process {context}", 'lo
|
|
|
153
159
|
| `fuzzyDeduplicate` | medium | Jaccard-based near-duplicate removal |
|
|
154
160
|
| `ngramDeduplicate` | medium | Bigram/trigram near-duplicate removal |
|
|
155
161
|
| `levenshteinDeduplicate` | medium | Edit-distance near-duplicate removal |
|
|
156
|
-
| `tfidfCompress` |
|
|
157
|
-
| `textRankCompress` | medium |
|
|
158
|
-
| `extractiveCompress` |
|
|
162
|
+
| `tfidfCompress` | opt-in | Drop lowest TF-IDF prose sentences (keeps code, lists, rules, numbers) |
|
|
163
|
+
| `textRankCompress` | medium | Drop least central prose sentences (keeps code, lists, rules, numbers) |
|
|
164
|
+
| `extractiveCompress` | opt-in | Drop lowest term-frequency prose sentences (keeps code, lists, rules, numbers) |
|
|
159
165
|
|
|
160
166
|
## License
|
|
161
167
|
|
package/index.js
CHANGED
|
@@ -52,18 +52,24 @@ export const LEVELS = {
|
|
|
52
52
|
'base64Hex', 'stackTraces',
|
|
53
53
|
'lineDedup', 'sentenceDedup',
|
|
54
54
|
],
|
|
55
|
+
// One summarizer only (they used to be chained, compounding to ~25% kept).
|
|
56
|
+
// tfidf / extractive remain available as opt-in options.
|
|
55
57
|
medium: [
|
|
56
58
|
'fuzzyDedup', 'ngram', 'levenshtein',
|
|
57
|
-
'
|
|
59
|
+
'textrank',
|
|
58
60
|
],
|
|
59
61
|
};
|
|
60
62
|
|
|
63
|
+
// Opt-in steps that are not part of any level by default
|
|
64
|
+
const OPTIONAL_STEPS = ['tfidf', 'extractive'];
|
|
65
|
+
|
|
61
66
|
// Ordered from safest to riskiest for pipeline execution
|
|
62
67
|
const ALL_STEPS_ORDERED = [
|
|
63
68
|
...LEVELS.none,
|
|
64
69
|
...LEVELS['very-low'],
|
|
65
70
|
...LEVELS.low,
|
|
66
71
|
...LEVELS.medium,
|
|
72
|
+
...OPTIONAL_STEPS,
|
|
67
73
|
];
|
|
68
74
|
|
|
69
75
|
// Steps eligible for each level (cumulative)
|
|
@@ -71,15 +77,15 @@ function stepsForLevel(level) {
|
|
|
71
77
|
if (level === 'none') return [...LEVELS.none];
|
|
72
78
|
if (level === 'very-low') return [...LEVELS.none, ...LEVELS['very-low']];
|
|
73
79
|
if (level === 'low') return [...LEVELS.none, ...LEVELS['very-low'], ...LEVELS.low];
|
|
74
|
-
if (level === 'medium') return
|
|
80
|
+
if (level === 'medium') return [...LEVELS.none, ...LEVELS['very-low'], ...LEVELS.low, ...LEVELS.medium];
|
|
75
81
|
throw new Error(`Unknown level: "${level}". Use 'none', 'very-low', 'low', or 'medium'.`);
|
|
76
82
|
}
|
|
77
83
|
|
|
78
84
|
// ─── Default params ───────────────────────────────────────────
|
|
79
85
|
const DEFAULTS = {
|
|
80
|
-
extractiveRatio: 0.
|
|
81
|
-
tfidfRatio: 0.
|
|
82
|
-
textrankRatio: 0.
|
|
86
|
+
extractiveRatio: 0.75,
|
|
87
|
+
tfidfRatio: 0.75,
|
|
88
|
+
textrankRatio: 0.75,
|
|
83
89
|
fuzzyThreshold: 0.75,
|
|
84
90
|
ngramSize: 2,
|
|
85
91
|
ngramThreshold: 0.6,
|
package/package.json
CHANGED
package/src/algorithms.js
CHANGED
|
@@ -13,11 +13,16 @@
|
|
|
13
13
|
* @risk none | @savings 5–15%
|
|
14
14
|
*/
|
|
15
15
|
export function compressWhitespace(text) {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
.
|
|
20
|
-
.
|
|
16
|
+
// Code blocks keep their indentation (Python/YAML break without it);
|
|
17
|
+
// only trailing spaces are trimmed inside ``` fences.
|
|
18
|
+
return text.replace(/\r\n?/g, "\n")
|
|
19
|
+
.split(/(```[\s\S]*?```)/g)
|
|
20
|
+
.map(p => p.startsWith("```")
|
|
21
|
+
? p.replace(/[ \t]+\n/g, "\n")
|
|
22
|
+
: p.replace(/\t/g, " ").replace(/[ \t]+/g, " ")
|
|
23
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
24
|
+
.replace(/[ \t]+\n/g, "\n").replace(/\n[ \t]+/g, "\n"))
|
|
25
|
+
.join("")
|
|
21
26
|
.trim();
|
|
22
27
|
}
|
|
23
28
|
|
|
@@ -46,7 +51,7 @@ export function cleanPunctuation(text) {
|
|
|
46
51
|
return text
|
|
47
52
|
.replace(/!{2,}/g, "!").replace(/\?{2,}/g, "?")
|
|
48
53
|
.replace(/\.{4,}/g, "...").replace(/,{2,}/g, ",")
|
|
49
|
-
.replace(/ {2,}/g, " ");
|
|
54
|
+
.replace(/(\S) {2,}/g, "$1 ");
|
|
50
55
|
}
|
|
51
56
|
|
|
52
57
|
/**
|
|
@@ -100,7 +105,7 @@ export function removeFiller(text) {
|
|
|
100
105
|
for (const [p, r] of words) out = out.replace(p, r);
|
|
101
106
|
out = out.replace(/\u0000CAP(\s*)(\S)/g, (_, ws, ch) => ws + ch.toUpperCase()).replace(/\u0000CAP/g, "");
|
|
102
107
|
// collapse runs of spaces/tabs only — keep newlines and paragraph structure
|
|
103
|
-
return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
108
|
+
return out.replace(/(\S)[ \t]{2,}/g, "$1 ").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
104
109
|
}
|
|
105
110
|
|
|
106
111
|
/**
|
|
@@ -132,7 +137,7 @@ export function shortenPhrases(text) {
|
|
|
132
137
|
[/\bfor the reason that\b/gi, "because"],
|
|
133
138
|
];
|
|
134
139
|
let out = text;
|
|
135
|
-
for (const [p, r] of map) out = out.replace(p, r);
|
|
140
|
+
for (const [p, r] of map) out = out.replace(p, (m) => (/^[A-Z]/.test(m) && r ? r[0].toUpperCase() + r.slice(1) : r));
|
|
136
141
|
return out;
|
|
137
142
|
}
|
|
138
143
|
|
|
@@ -171,7 +176,7 @@ export function removeHedging(text) {
|
|
|
171
176
|
];
|
|
172
177
|
let out = text;
|
|
173
178
|
for (const [p, r] of patterns) out = out.replace(p, r);
|
|
174
|
-
return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+\n/g, "\n").trim();
|
|
179
|
+
return out.replace(/(\S)[ \t]{2,}/g, "$1 ").replace(/[ \t]+\n/g, "\n").trim();
|
|
175
180
|
}
|
|
176
181
|
|
|
177
182
|
/**
|
|
@@ -179,16 +184,23 @@ export function removeHedging(text) {
|
|
|
179
184
|
* Examples: "Here is a...", "I hope this helps", "I'd be happy to help"
|
|
180
185
|
* @risk low | @savings 5–15%
|
|
181
186
|
*/
|
|
187
|
+
// A lead-in that carries a rule, number, ID or variable is content, not fluff.
|
|
188
|
+
const KEEP_LEADIN = /\b(?:must|never|always|only|not|don't|do not|cannot|can't|required?)\b|\d|\{\{?|\$\{|%\w+%|\x00/i;
|
|
189
|
+
const unlessCritical = (m) => (KEEP_LEADIN.test(m) ? m : "");
|
|
190
|
+
|
|
182
191
|
export function removeMetaCommentary(text) {
|
|
183
192
|
const patterns = [
|
|
184
|
-
|
|
185
|
-
[/^(
|
|
186
|
-
[/^(
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
[
|
|
190
|
-
[
|
|
191
|
-
[
|
|
193
|
+
// "Sure," / "Of course!" — only with punctuation, so "Surely…"/"Great care…" stay
|
|
194
|
+
[/^(?:sure|of course|absolutely|certainly)[,!.][ \t]*/gim, ""],
|
|
195
|
+
[/^i(?:'d| would) be happy to (?:help|assist)[^.!?\n]*[.!?][ \t]*/gim, unlessCritical],
|
|
196
|
+
// "Here is …" / "The following …" / "Below is …": only a whole lead-in sentence
|
|
197
|
+
// ending in "." or a line that ends in ":" (never "…: <content>")
|
|
198
|
+
[/^here(?:'s| is| are) (?:a |an |the )?[^.!?:\n]*(?:\.[ \t]*|:[ \t]*$)/gim, unlessCritical],
|
|
199
|
+
[/^the following (?:is|are|provides)[^.!?:\n]*(?:\.[ \t]*|:[ \t]*$)/gim, unlessCritical],
|
|
200
|
+
[/^below (?:is|are)[^.!?:\n]*(?:\.[ \t]*|:[ \t]*$)/gim, unlessCritical],
|
|
201
|
+
[/i hope (?:this|that) (?:helps?|is helpful)[^.!?\n]*[.!?][ \t]*/gi, unlessCritical],
|
|
202
|
+
[/please (?:let me know|don't hesitate to ask)[^.!?\n]*[.!?][ \t]*/gi, unlessCritical],
|
|
203
|
+
[/if you have (?:any )?(?:further )?questions?[^.!?\n]*[.!?][ \t]*/gi, unlessCritical],
|
|
192
204
|
];
|
|
193
205
|
let out = text;
|
|
194
206
|
for (const [p, r] of patterns) out = out.replace(p, r);
|
|
@@ -209,7 +221,7 @@ export function removeParentheticals(text) {
|
|
|
209
221
|
];
|
|
210
222
|
let out = text;
|
|
211
223
|
for (const p of patterns) out = out.replace(p, "");
|
|
212
|
-
return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+\n/g, "\n").trim();
|
|
224
|
+
return out.replace(/(\S)[ \t]{2,}/g, "$1 ").replace(/[ \t]+\n/g, "\n").trim();
|
|
213
225
|
}
|
|
214
226
|
|
|
215
227
|
/**
|
|
@@ -295,7 +307,7 @@ export function removeNullJsonFields(text) {
|
|
|
295
307
|
if (v === null || v === "" || (Array.isArray(v) && v.length === 0)) return undefined;
|
|
296
308
|
return v;
|
|
297
309
|
}));
|
|
298
|
-
return "```json\n" + JSON.stringify(cleaned
|
|
310
|
+
return "```json\n" + JSON.stringify(cleaned) + "\n```";
|
|
299
311
|
} catch { return _; }
|
|
300
312
|
});
|
|
301
313
|
}
|
|
@@ -316,9 +328,13 @@ export function minifySQL(text) {
|
|
|
316
328
|
* @risk none | @savings 3–15%
|
|
317
329
|
*/
|
|
318
330
|
export function normalizeIndentation(text) {
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
331
|
+
// 4-space → 2-space, only for blocks indented in steps of 4 (halving a
|
|
332
|
+
// 2-space block would merge nesting levels).
|
|
333
|
+
return text.replace(/```[\s\S]*?```/g, block => {
|
|
334
|
+
const indents = block.split("\n").map(l => (l.match(/^ +/) || [""])[0].length).filter(n => n > 0);
|
|
335
|
+
if (!indents.length || indents.some(n => n % 4 !== 0)) return block;
|
|
336
|
+
return block.replace(/^( )+/gm, m => " ".repeat(m.length / 4));
|
|
337
|
+
});
|
|
322
338
|
}
|
|
323
339
|
|
|
324
340
|
/**
|
|
@@ -359,21 +375,25 @@ export function stripBase64AndHex(text) {
|
|
|
359
375
|
* Catches: "Return JSON only\nReturn JSON only\nReturn JSON only" → one line.
|
|
360
376
|
* @risk low | @savings 5–30%
|
|
361
377
|
*/
|
|
378
|
+
// Lines that look like code or JSON legitimately repeat ("}", "qty": 1, return x;)
|
|
379
|
+
const CODE_LIKE_LINE = /^[\s\[\]{}(),;:"'`]*$|^\s*"[^"]*"\s*:|[{\[,;]\s*$|^\s*(?:return|break|continue|end|fi|done|else)\b/;
|
|
362
380
|
export function deduplicateLines(text) {
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
381
|
+
return outsideFences(text, (block) => {
|
|
382
|
+
const seen = new Set();
|
|
383
|
+
return block.split("\n").filter(line => {
|
|
384
|
+
const key = line.trim().toLowerCase();
|
|
385
|
+
if (key === "" || CODE_LIKE_LINE.test(line)) return true;
|
|
386
|
+
if (seen.has(key)) return false;
|
|
387
|
+
seen.add(key); return true;
|
|
388
|
+
}).join("\n");
|
|
389
|
+
});
|
|
370
390
|
}
|
|
371
391
|
|
|
372
392
|
/**
|
|
373
393
|
* Removes repeated sentences (exact match, case-insensitive).
|
|
374
394
|
* @risk low | @savings 5–15%
|
|
375
395
|
*/
|
|
376
|
-
|
|
396
|
+
function deduplicateSentencesBlock(text) {
|
|
377
397
|
// Split but keep each separator, so line breaks and paragraphs survive.
|
|
378
398
|
const parts = text.split(/((?<=[.!?])\s+)/);
|
|
379
399
|
const seen = new Set();
|
|
@@ -386,174 +406,213 @@ export function deduplicateSentences(text) {
|
|
|
386
406
|
}
|
|
387
407
|
return out.replace(/\n{3,}/g, "\n\n").trim();
|
|
388
408
|
}
|
|
409
|
+
export function deduplicateSentences(text) {
|
|
410
|
+
return outsideFences(text, deduplicateSentencesBlock);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// ─── Shared core for the 'medium' steps ─────────────────────
|
|
414
|
+
// Every medium step works on "units" (sentences / lines) and only ever
|
|
415
|
+
// REMOVES units it has positively chosen to drop. Everything else, including
|
|
416
|
+
// short units, line breaks and paragraph breaks, is kept as-is.
|
|
417
|
+
// Units inside ``` fenced blocks, structured lines (lists, headings, tables,
|
|
418
|
+
// "Key: value", JSON-ish, log lines) and "critical" sentences (rules,
|
|
419
|
+
// numbers, IDs, variables, emails, URLs) are never dropped.
|
|
420
|
+
|
|
421
|
+
const UNIT_SPLIT = /((?<=[.!?])[ \t]+|[ \t]*\n\s*)/;
|
|
422
|
+
// Chat transcript lines ("User: …", "Assistant: …") are prose, not structure
|
|
423
|
+
const SPEAKER = /^\s*(?:user|assistant|human|ai|system|customer|agent|bot)\s*:/i;
|
|
424
|
+
const STRUCTURED_RE = /^\s*(?:[-*+•>|#]|\d+[.)]\s|[\[{"'`]|[A-Za-z][\w .'-]{0,30}:\s|\d{4}-\d{2}-\d{2})/;
|
|
425
|
+
const STRUCTURED_LINE = { test: (line) => !SPEAKER.test(line) && STRUCTURED_RE.test(line) };
|
|
426
|
+
const CRITICAL = /\d|\{\{?|\$\{|%\w+%|@|https?:\/\/|`|\b(?:must|never|always|only|not|don't|do not|cannot|can't|required?|forbidden|no later than|deadline|exactly|at least|at most)\b/i;
|
|
427
|
+
|
|
428
|
+
function parseUnits(text) {
|
|
429
|
+
const parts = text.split(UNIT_SPLIT);
|
|
430
|
+
const units = [];
|
|
431
|
+
let lineStart = true, line = "";
|
|
432
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
433
|
+
const sepBefore = i === 0 ? "" : parts[i - 1];
|
|
434
|
+
if (i > 0 && sepBefore.includes("\n")) { lineStart = true; }
|
|
435
|
+
if (lineStart) {
|
|
436
|
+
// the full line this unit starts
|
|
437
|
+
let j = i, l = parts[i];
|
|
438
|
+
while (j + 2 < parts.length && !parts[j + 1].includes("\n")) { l += parts[j + 1] + parts[j + 2]; j += 2; }
|
|
439
|
+
line = l;
|
|
440
|
+
}
|
|
441
|
+
units.push({ text: parts[i], sepBefore, line });
|
|
442
|
+
lineStart = false;
|
|
443
|
+
}
|
|
444
|
+
return units;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function rebuild(units, keep) {
|
|
448
|
+
let out = "", pending = "";
|
|
449
|
+
units.forEach((u, i) => {
|
|
450
|
+
const sep = (pending.match(/\n/g) || []).length > (u.sepBefore.match(/\n/g) || []).length ? pending : u.sepBefore;
|
|
451
|
+
if (keep[i]) { out += (out ? sep : u.sepBefore) + u.text; pending = ""; }
|
|
452
|
+
else { pending = sep; }
|
|
453
|
+
});
|
|
454
|
+
return out.replace(/\n{3,}/g, "\n\n").trim();
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// Apply fn only outside ``` fenced blocks
|
|
458
|
+
function outsideFences(text, fn) {
|
|
459
|
+
return text.split(/(```[\s\S]*?```)/g).map(p => {
|
|
460
|
+
if (p.startsWith("```") || !p.trim()) return p;
|
|
461
|
+
const lead = p.match(/^\s*/)[0], trail = p.match(/\s*$/)[0];
|
|
462
|
+
return lead + fn(p.trim()) + trail;
|
|
463
|
+
}).join("");
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// Questions, direct requests and word-based deadlines are the task itself
|
|
467
|
+
const TASK = /\?\s*$|\b(?:could|can|would|will) you\b|\b(?:today|tomorrow|tonight|by (?:the )?end of|eod|eow|asap|due|by (?:monday|tuesday|wednesday|thursday|friday|saturday|sunday))\b/i;
|
|
468
|
+
const isProtected = (u) =>
|
|
469
|
+
!u.text.trim() || STRUCTURED_LINE.test(u.line) || CRITICAL.test(u.text) || TASK.test(u.text);
|
|
470
|
+
|
|
471
|
+
// numbers/IDs must match for two units to count as duplicates
|
|
472
|
+
const numSig = (s) => (s.match(/[\w-]*\d[\w.\/-]*/g) || []).join("|");
|
|
473
|
+
|
|
474
|
+
function dedupBy(text, isDup, minLen) {
|
|
475
|
+
return outsideFences(text, (block) => {
|
|
476
|
+
const units = parseUnits(block);
|
|
477
|
+
const keep = units.map(() => true);
|
|
478
|
+
const seen = [];
|
|
479
|
+
units.forEach((u, i) => {
|
|
480
|
+
const t = u.text.trim();
|
|
481
|
+
if (t.length <= minLen || STRUCTURED_LINE.test(u.line)) return; // too short / structured: never compared, never dropped
|
|
482
|
+
if (seen.some(k => numSig(k) === numSig(t) && isDup(k, t))) keep[i] = false;
|
|
483
|
+
else seen.push(t);
|
|
484
|
+
});
|
|
485
|
+
return rebuild(units, keep);
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function summarizeBy(text, ratio, scoreFn) {
|
|
490
|
+
return outsideFences(text, (block) => {
|
|
491
|
+
const units = parseUnits(block);
|
|
492
|
+
const cand = units.map((u, i) => ({ u, i })).filter(({ u }) => !isProtected(u) && u.text.trim().length > 20);
|
|
493
|
+
if (cand.length < 3) return block;
|
|
494
|
+
const drop = Math.floor(cand.length * (1 - ratio));
|
|
495
|
+
if (drop <= 0) return block;
|
|
496
|
+
const scores = scoreFn(cand.map(c => c.u.text));
|
|
497
|
+
const dropIdx = new Set(cand.map((c, k) => ({ i: c.i, s: scores[k] }))
|
|
498
|
+
.sort((a, b) => a.s - b.s).slice(0, drop).map(x => x.i));
|
|
499
|
+
return rebuild(units, units.map((_, i) => !dropIdx.has(i)));
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const words = (s, min = 3) => s.toLowerCase().match(new RegExp(`\\b\\w{${min},}\\b`, "g")) || [];
|
|
389
504
|
|
|
390
505
|
/**
|
|
391
506
|
* Removes near-duplicate sentences using Jaccard similarity on word sets.
|
|
507
|
+
* Keeps line structure; sentences that differ in numbers/IDs are never duplicates.
|
|
392
508
|
* @param threshold - similarity threshold (0–1), default 0.75
|
|
393
|
-
* @risk medium | @savings
|
|
509
|
+
* @risk medium | @savings 0–20%
|
|
394
510
|
*/
|
|
395
511
|
export function fuzzyDeduplicate(text, threshold = 0.75) {
|
|
396
|
-
const
|
|
397
|
-
|
|
398
|
-
function jaccard(a, b) {
|
|
399
|
-
const sa = new Set(a.toLowerCase().match(/\b\w{3,}\b/g) || []);
|
|
400
|
-
const sb = new Set(b.toLowerCase().match(/\b\w{3,}\b/g) || []);
|
|
512
|
+
const jaccard = (a, b) => {
|
|
513
|
+
const sa = new Set(words(a)), sb = new Set(words(b));
|
|
401
514
|
const inter = [...sa].filter(w => sb.has(w)).length;
|
|
402
515
|
const union = new Set([...sa, ...sb]).size;
|
|
403
516
|
return union === 0 ? 0 : inter / union;
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
for (const s of sentences) {
|
|
407
|
-
if (!kept.some(k => jaccard(k, s) >= threshold)) kept.push(s);
|
|
408
|
-
}
|
|
409
|
-
return kept.join(" ").trim();
|
|
517
|
+
};
|
|
518
|
+
return dedupBy(text, (a, b) => jaccard(a, b) >= threshold, 20);
|
|
410
519
|
}
|
|
411
520
|
|
|
412
521
|
/**
|
|
413
|
-
*
|
|
414
|
-
*
|
|
415
|
-
* @param n - gram size (default 2)
|
|
416
|
-
* @param threshold - similarity threshold (default 0.6)
|
|
417
|
-
* @risk medium | @savings 5–20%
|
|
522
|
+
* N-gram overlap deduplication. Keeps line structure; numbers/IDs must match.
|
|
523
|
+
* @risk medium | @savings 0–15%
|
|
418
524
|
*/
|
|
419
525
|
export function ngramDeduplicate(text, n = 2, threshold = 0.6) {
|
|
420
|
-
const
|
|
421
|
-
|
|
422
|
-
function grams(s) {
|
|
423
|
-
const words = s.toLowerCase().match(/\b\w+\b/g) || [];
|
|
526
|
+
const grams = (s) => {
|
|
527
|
+
const w = s.toLowerCase().match(/\b\w+\b/g) || [];
|
|
424
528
|
const gs = new Set();
|
|
425
|
-
for (let i = 0; i <=
|
|
529
|
+
for (let i = 0; i <= w.length - n; i++) gs.add(w.slice(i, i + n).join(" "));
|
|
426
530
|
return gs;
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
const
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
const union = new Set([...a, ...b]).size;
|
|
435
|
-
return union > 0 && inter / union >= threshold;
|
|
436
|
-
});
|
|
437
|
-
if (!isDup) kept.push(i);
|
|
438
|
-
}
|
|
439
|
-
return kept.map(i => sentences[i]).join(" ").trim();
|
|
531
|
+
};
|
|
532
|
+
return dedupBy(text, (a, b) => {
|
|
533
|
+
const ga = grams(a), gb = grams(b);
|
|
534
|
+
const inter = [...ga].filter(g => gb.has(g)).length;
|
|
535
|
+
const union = new Set([...ga, ...gb]).size;
|
|
536
|
+
return union > 0 && inter / union >= threshold;
|
|
537
|
+
}, 15);
|
|
440
538
|
}
|
|
441
539
|
|
|
442
540
|
/**
|
|
443
541
|
* Edit-distance deduplication. Catches "Return JSON only." vs "Return JSON only!"
|
|
542
|
+
* Keeps line structure; numbers/IDs must match.
|
|
444
543
|
* @param threshold - max normalized edit distance (default 0.15)
|
|
445
|
-
* @risk medium | @savings
|
|
544
|
+
* @risk medium | @savings 0–15%
|
|
446
545
|
*/
|
|
447
546
|
export function levenshteinDeduplicate(text, threshold = 0.15) {
|
|
448
|
-
|
|
547
|
+
const lev = (a, b) => {
|
|
449
548
|
const m = a.length, n = b.length;
|
|
450
549
|
if (Math.abs(m - n) > Math.max(m, n) * 0.4) return Math.max(m, n);
|
|
451
550
|
const dp = Array.from({ length: m + 1 }, (_, i) => [i]);
|
|
452
551
|
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
453
552
|
for (let i = 1; i <= m; i++)
|
|
454
553
|
for (let j = 1; j <= n; j++)
|
|
455
|
-
dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] : 1 + Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
|
|
554
|
+
dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
|
|
456
555
|
return dp[m][n];
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
if (sentences.length <= 2) return text;
|
|
460
|
-
const kept = [];
|
|
461
|
-
for (const s of sentences) {
|
|
462
|
-
if (!kept.some(k => lev(s.toLowerCase(), k.toLowerCase()) / Math.max(s.length, k.length) <= threshold))
|
|
463
|
-
kept.push(s);
|
|
464
|
-
}
|
|
465
|
-
return kept.join(" ").trim();
|
|
556
|
+
};
|
|
557
|
+
return dedupBy(text, (a, b) => lev(a.toLowerCase(), b.toLowerCase()) / Math.max(a.length, b.length) <= threshold, 10);
|
|
466
558
|
}
|
|
467
559
|
|
|
468
560
|
// ════════════════════════════════════════════════════════════
|
|
469
561
|
// ADVANCED (EXTRACTIVE)
|
|
562
|
+
// Only plain prose is summarized. Code blocks, structured lines and
|
|
563
|
+
// critical sentences (rules, numbers, IDs, variables) are always kept.
|
|
470
564
|
// ════════════════════════════════════════════════════════════
|
|
471
565
|
|
|
472
566
|
/**
|
|
473
|
-
*
|
|
474
|
-
* @param ratio - fraction of sentences to keep (default 0.
|
|
475
|
-
* @risk medium | @savings
|
|
567
|
+
* Drops the lowest-scoring prose sentences by term frequency.
|
|
568
|
+
* @param ratio - fraction of droppable prose sentences to keep (default 0.75)
|
|
569
|
+
* @risk medium | @savings 0–30%
|
|
476
570
|
*/
|
|
477
|
-
export function extractiveCompress(text, ratio = 0.
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
for (const w of allWords) freq[w] = (freq[w] || 0) + 1;
|
|
483
|
-
const scored = sentences.map((s, i) => {
|
|
484
|
-
const words = s.toLowerCase().match(/\b\w{4,}\b/g) || [];
|
|
485
|
-
const score = words.reduce((acc, w) => acc + (freq[w] || 0), 0) / (words.length || 1);
|
|
486
|
-
return { s, score, i };
|
|
571
|
+
export function extractiveCompress(text, ratio = 0.75) {
|
|
572
|
+
return summarizeBy(text, ratio, (sents) => {
|
|
573
|
+
const freq = {};
|
|
574
|
+
for (const w of words(sents.join(" "), 4)) freq[w] = (freq[w] || 0) + 1;
|
|
575
|
+
return sents.map(s => { const w = words(s, 4); return w.reduce((a, x) => a + (freq[x] || 0), 0) / (w.length || 1); });
|
|
487
576
|
});
|
|
488
|
-
const keepCount = Math.max(2, Math.round(sentences.length * ratio));
|
|
489
|
-
return scored.sort((a, b) => b.score - a.score).slice(0, keepCount)
|
|
490
|
-
.sort((a, b) => a.i - b.i).map(x => x.s).join(" ").trim();
|
|
491
577
|
}
|
|
492
578
|
|
|
493
579
|
/**
|
|
494
|
-
*
|
|
495
|
-
*
|
|
496
|
-
* @
|
|
497
|
-
* @risk medium | @savings 20–50%
|
|
580
|
+
* Drops the lowest-scoring prose sentences by TF-IDF.
|
|
581
|
+
* @param ratio - fraction of droppable prose sentences to keep (default 0.75)
|
|
582
|
+
* @risk medium | @savings 0–30%
|
|
498
583
|
*/
|
|
499
|
-
export function tfidfCompress(text, ratio = 0.
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
});
|
|
509
|
-
const scored = sentences.map((s, i) => {
|
|
510
|
-
const words = sentWords[i];
|
|
511
|
-
if (!words.length) return { s, score: 0, i };
|
|
512
|
-
const freq = {};
|
|
513
|
-
words.forEach(w => { freq[w] = (freq[w] || 0) + 1; });
|
|
514
|
-
const score = words.reduce((acc, w) => {
|
|
515
|
-
const tf = freq[w] / words.length;
|
|
516
|
-
const idf = Math.log((n + 1) / ((docFreq[w] || 0) + 1));
|
|
517
|
-
return acc + tf * idf;
|
|
518
|
-
}, 0) / words.length;
|
|
519
|
-
return { s, score, i };
|
|
584
|
+
export function tfidfCompress(text, ratio = 0.75) {
|
|
585
|
+
return summarizeBy(text, ratio, (sents) => {
|
|
586
|
+
const n = sents.length, df = {};
|
|
587
|
+
const sw = sents.map(s => { const w = words(s); new Set(w).forEach(x => { df[x] = (df[x] || 0) + 1; }); return w; });
|
|
588
|
+
return sw.map(w => {
|
|
589
|
+
if (!w.length) return 0;
|
|
590
|
+
const f = {}; w.forEach(x => { f[x] = (f[x] || 0) + 1; });
|
|
591
|
+
return w.reduce((a, x) => a + (f[x] / w.length) * Math.log((n + 1) / ((df[x] || 0) + 1)), 0) / w.length;
|
|
592
|
+
});
|
|
520
593
|
});
|
|
521
|
-
const keepCount = Math.max(2, Math.round(n * ratio));
|
|
522
|
-
return scored.sort((a, b) => b.score - a.score).slice(0, keepCount)
|
|
523
|
-
.sort((a, b) => a.i - b.i).map(x => x.s).join(" ").trim();
|
|
524
594
|
}
|
|
525
595
|
|
|
526
596
|
/**
|
|
527
|
-
* TextRank — PageRank-style
|
|
528
|
-
*
|
|
529
|
-
* @param ratio - fraction of sentences to keep (default 0.
|
|
530
|
-
* @risk medium | @savings
|
|
597
|
+
* TextRank — PageRank-style ranking on the sentence similarity graph.
|
|
598
|
+
* Drops the least "central" prose sentences.
|
|
599
|
+
* @param ratio - fraction of droppable prose sentences to keep (default 0.75)
|
|
600
|
+
* @risk medium | @savings 0–30%
|
|
531
601
|
*/
|
|
532
|
-
export function textRankCompress(text, ratio = 0.
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
const sum = row.reduce((a, b) => a + b, 0);
|
|
548
|
-
return sum === 0 ? row.map(() => 1 / n) : row.map(v => v / sum);
|
|
602
|
+
export function textRankCompress(text, ratio = 0.75, damping = 0.85, iterations = 20) {
|
|
603
|
+
return summarizeBy(text, ratio, (sents) => {
|
|
604
|
+
const n = sents.length;
|
|
605
|
+
const sets = sents.map(s => new Set(words(s)));
|
|
606
|
+
const sim = (i, j) => {
|
|
607
|
+
const a = sets[i], b = sets[j];
|
|
608
|
+
if (!a.size || !b.size) return 0;
|
|
609
|
+
return [...a].filter(w => b.has(w)).length / (Math.log(a.size + 1) + Math.log(b.size + 1));
|
|
610
|
+
};
|
|
611
|
+
const m = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (__, j) => (i === j ? 0 : sim(i, j))));
|
|
612
|
+
const norm = m.map(r => { const s = r.reduce((a, b) => a + b, 0); return s === 0 ? r.map(() => 1 / n) : r.map(v => v / s); });
|
|
613
|
+
let sc = Array(n).fill(1 / n);
|
|
614
|
+
for (let it = 0; it < iterations; it++)
|
|
615
|
+
sc = sc.map((_, i) => (1 - damping) / n + damping * sc.reduce((acc, s, j) => acc + s * norm[j][i], 0));
|
|
616
|
+
return sc;
|
|
549
617
|
});
|
|
550
|
-
let scores = Array(n).fill(1 / n);
|
|
551
|
-
for (let iter = 0; iter < iterations; iter++)
|
|
552
|
-
scores = scores.map((_, i) =>
|
|
553
|
-
(1 - damping) / n + damping * scores.reduce((acc, s, j) => acc + s * normalized[j][i], 0)
|
|
554
|
-
);
|
|
555
|
-
const keepCount = Math.max(2, Math.round(n * ratio));
|
|
556
|
-
return sentences.map((s, i) => ({ s, score: scores[i], i }))
|
|
557
|
-
.sort((a, b) => b.score - a.score).slice(0, keepCount)
|
|
558
|
-
.sort((a, b) => a.i - b.i).map(x => x.s).join(" ").trim();
|
|
559
618
|
}
|