prompt-compressor 1.0.2 → 1.0.3
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 +173 -130
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 **23% 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.3 or later.** 1.0.2 and earlier could corrupt ```json blocks at `low` (repeated lines such as `}` or `"qty": 1` were removed as duplicates), and `medium` kept only about 22% of critical facts. Both are fixed and covered by the benchmark and tests.
|
|
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 | 4% avg (0–24%) |
|
|
37
|
+
| `'very-low'` | + Filler removal, phrase shortening, JSON/SQL minify | 9% avg (0–32%) |
|
|
38
|
+
| `'low'` | + Hedging removal, code comments, deduplication, stack trace truncation | **23% avg (2–59%)**, 100% of critical facts kept |
|
|
39
|
+
| `'medium'` | + Near-duplicate removal (fuzzy / n-gram / Levenshtein), TextRank on plain prose only | 24% avg (5–59%), 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 23%) 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
|
@@ -295,7 +295,7 @@ export function removeNullJsonFields(text) {
|
|
|
295
295
|
if (v === null || v === "" || (Array.isArray(v) && v.length === 0)) return undefined;
|
|
296
296
|
return v;
|
|
297
297
|
}));
|
|
298
|
-
return "```json\n" + JSON.stringify(cleaned
|
|
298
|
+
return "```json\n" + JSON.stringify(cleaned) + "\n```";
|
|
299
299
|
} catch { return _; }
|
|
300
300
|
});
|
|
301
301
|
}
|
|
@@ -359,21 +359,25 @@ export function stripBase64AndHex(text) {
|
|
|
359
359
|
* Catches: "Return JSON only\nReturn JSON only\nReturn JSON only" → one line.
|
|
360
360
|
* @risk low | @savings 5–30%
|
|
361
361
|
*/
|
|
362
|
+
// Lines that look like code or JSON legitimately repeat ("}", "qty": 1, return x;)
|
|
363
|
+
const CODE_LIKE_LINE = /^[\s\[\]{}(),;:"'`]*$|^\s*"[^"]*"\s*:|[{\[,;]\s*$|^\s*(?:return|break|continue|end|fi|done|else)\b/;
|
|
362
364
|
export function deduplicateLines(text) {
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
365
|
+
return outsideFences(text, (block) => {
|
|
366
|
+
const seen = new Set();
|
|
367
|
+
return block.split("\n").filter(line => {
|
|
368
|
+
const key = line.trim().toLowerCase();
|
|
369
|
+
if (key === "" || CODE_LIKE_LINE.test(line)) return true;
|
|
370
|
+
if (seen.has(key)) return false;
|
|
371
|
+
seen.add(key); return true;
|
|
372
|
+
}).join("\n");
|
|
373
|
+
});
|
|
370
374
|
}
|
|
371
375
|
|
|
372
376
|
/**
|
|
373
377
|
* Removes repeated sentences (exact match, case-insensitive).
|
|
374
378
|
* @risk low | @savings 5–15%
|
|
375
379
|
*/
|
|
376
|
-
|
|
380
|
+
function deduplicateSentencesBlock(text) {
|
|
377
381
|
// Split but keep each separator, so line breaks and paragraphs survive.
|
|
378
382
|
const parts = text.split(/((?<=[.!?])\s+)/);
|
|
379
383
|
const seen = new Set();
|
|
@@ -386,174 +390,213 @@ export function deduplicateSentences(text) {
|
|
|
386
390
|
}
|
|
387
391
|
return out.replace(/\n{3,}/g, "\n\n").trim();
|
|
388
392
|
}
|
|
393
|
+
export function deduplicateSentences(text) {
|
|
394
|
+
return outsideFences(text, deduplicateSentencesBlock);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// ─── Shared core for the 'medium' steps ─────────────────────
|
|
398
|
+
// Every medium step works on "units" (sentences / lines) and only ever
|
|
399
|
+
// REMOVES units it has positively chosen to drop. Everything else, including
|
|
400
|
+
// short units, line breaks and paragraph breaks, is kept as-is.
|
|
401
|
+
// Units inside ``` fenced blocks, structured lines (lists, headings, tables,
|
|
402
|
+
// "Key: value", JSON-ish, log lines) and "critical" sentences (rules,
|
|
403
|
+
// numbers, IDs, variables, emails, URLs) are never dropped.
|
|
404
|
+
|
|
405
|
+
const UNIT_SPLIT = /((?<=[.!?])[ \t]+|[ \t]*\n\s*)/;
|
|
406
|
+
// Chat transcript lines ("User: …", "Assistant: …") are prose, not structure
|
|
407
|
+
const SPEAKER = /^\s*(?:user|assistant|human|ai|system|customer|agent|bot)\s*:/i;
|
|
408
|
+
const STRUCTURED_RE = /^\s*(?:[-*+•>|#]|\d+[.)]\s|[\[{"'`]|[A-Za-z][\w .'-]{0,30}:\s|\d{4}-\d{2}-\d{2})/;
|
|
409
|
+
const STRUCTURED_LINE = { test: (line) => !SPEAKER.test(line) && STRUCTURED_RE.test(line) };
|
|
410
|
+
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;
|
|
411
|
+
|
|
412
|
+
function parseUnits(text) {
|
|
413
|
+
const parts = text.split(UNIT_SPLIT);
|
|
414
|
+
const units = [];
|
|
415
|
+
let lineStart = true, line = "";
|
|
416
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
417
|
+
const sepBefore = i === 0 ? "" : parts[i - 1];
|
|
418
|
+
if (i > 0 && sepBefore.includes("\n")) { lineStart = true; }
|
|
419
|
+
if (lineStart) {
|
|
420
|
+
// the full line this unit starts
|
|
421
|
+
let j = i, l = parts[i];
|
|
422
|
+
while (j + 2 < parts.length && !parts[j + 1].includes("\n")) { l += parts[j + 1] + parts[j + 2]; j += 2; }
|
|
423
|
+
line = l;
|
|
424
|
+
}
|
|
425
|
+
units.push({ text: parts[i], sepBefore, line });
|
|
426
|
+
lineStart = false;
|
|
427
|
+
}
|
|
428
|
+
return units;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function rebuild(units, keep) {
|
|
432
|
+
let out = "", pending = "";
|
|
433
|
+
units.forEach((u, i) => {
|
|
434
|
+
const sep = (pending.match(/\n/g) || []).length > (u.sepBefore.match(/\n/g) || []).length ? pending : u.sepBefore;
|
|
435
|
+
if (keep[i]) { out += (out ? sep : u.sepBefore) + u.text; pending = ""; }
|
|
436
|
+
else { pending = sep; }
|
|
437
|
+
});
|
|
438
|
+
return out.replace(/\n{3,}/g, "\n\n").trim();
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// Apply fn only outside ``` fenced blocks
|
|
442
|
+
function outsideFences(text, fn) {
|
|
443
|
+
return text.split(/(```[\s\S]*?```)/g).map(p => {
|
|
444
|
+
if (p.startsWith("```") || !p.trim()) return p;
|
|
445
|
+
const lead = p.match(/^\s*/)[0], trail = p.match(/\s*$/)[0];
|
|
446
|
+
return lead + fn(p.trim()) + trail;
|
|
447
|
+
}).join("");
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// Questions, direct requests and word-based deadlines are the task itself
|
|
451
|
+
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;
|
|
452
|
+
const isProtected = (u) =>
|
|
453
|
+
!u.text.trim() || STRUCTURED_LINE.test(u.line) || CRITICAL.test(u.text) || TASK.test(u.text);
|
|
454
|
+
|
|
455
|
+
// numbers/IDs must match for two units to count as duplicates
|
|
456
|
+
const numSig = (s) => (s.match(/[\w-]*\d[\w.\/-]*/g) || []).join("|");
|
|
457
|
+
|
|
458
|
+
function dedupBy(text, isDup, minLen) {
|
|
459
|
+
return outsideFences(text, (block) => {
|
|
460
|
+
const units = parseUnits(block);
|
|
461
|
+
const keep = units.map(() => true);
|
|
462
|
+
const seen = [];
|
|
463
|
+
units.forEach((u, i) => {
|
|
464
|
+
const t = u.text.trim();
|
|
465
|
+
if (t.length <= minLen || STRUCTURED_LINE.test(u.line)) return; // too short / structured: never compared, never dropped
|
|
466
|
+
if (seen.some(k => numSig(k) === numSig(t) && isDup(k, t))) keep[i] = false;
|
|
467
|
+
else seen.push(t);
|
|
468
|
+
});
|
|
469
|
+
return rebuild(units, keep);
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function summarizeBy(text, ratio, scoreFn) {
|
|
474
|
+
return outsideFences(text, (block) => {
|
|
475
|
+
const units = parseUnits(block);
|
|
476
|
+
const cand = units.map((u, i) => ({ u, i })).filter(({ u }) => !isProtected(u) && u.text.trim().length > 20);
|
|
477
|
+
if (cand.length < 3) return block;
|
|
478
|
+
const drop = Math.floor(cand.length * (1 - ratio));
|
|
479
|
+
if (drop <= 0) return block;
|
|
480
|
+
const scores = scoreFn(cand.map(c => c.u.text));
|
|
481
|
+
const dropIdx = new Set(cand.map((c, k) => ({ i: c.i, s: scores[k] }))
|
|
482
|
+
.sort((a, b) => a.s - b.s).slice(0, drop).map(x => x.i));
|
|
483
|
+
return rebuild(units, units.map((_, i) => !dropIdx.has(i)));
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const words = (s, min = 3) => s.toLowerCase().match(new RegExp(`\\b\\w{${min},}\\b`, "g")) || [];
|
|
389
488
|
|
|
390
489
|
/**
|
|
391
490
|
* Removes near-duplicate sentences using Jaccard similarity on word sets.
|
|
491
|
+
* Keeps line structure; sentences that differ in numbers/IDs are never duplicates.
|
|
392
492
|
* @param threshold - similarity threshold (0–1), default 0.75
|
|
393
|
-
* @risk medium | @savings
|
|
493
|
+
* @risk medium | @savings 0–20%
|
|
394
494
|
*/
|
|
395
495
|
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) || []);
|
|
496
|
+
const jaccard = (a, b) => {
|
|
497
|
+
const sa = new Set(words(a)), sb = new Set(words(b));
|
|
401
498
|
const inter = [...sa].filter(w => sb.has(w)).length;
|
|
402
499
|
const union = new Set([...sa, ...sb]).size;
|
|
403
500
|
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();
|
|
501
|
+
};
|
|
502
|
+
return dedupBy(text, (a, b) => jaccard(a, b) >= threshold, 20);
|
|
410
503
|
}
|
|
411
504
|
|
|
412
505
|
/**
|
|
413
|
-
*
|
|
414
|
-
*
|
|
415
|
-
* @param n - gram size (default 2)
|
|
416
|
-
* @param threshold - similarity threshold (default 0.6)
|
|
417
|
-
* @risk medium | @savings 5–20%
|
|
506
|
+
* N-gram overlap deduplication. Keeps line structure; numbers/IDs must match.
|
|
507
|
+
* @risk medium | @savings 0–15%
|
|
418
508
|
*/
|
|
419
509
|
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) || [];
|
|
510
|
+
const grams = (s) => {
|
|
511
|
+
const w = s.toLowerCase().match(/\b\w+\b/g) || [];
|
|
424
512
|
const gs = new Set();
|
|
425
|
-
for (let i = 0; i <=
|
|
513
|
+
for (let i = 0; i <= w.length - n; i++) gs.add(w.slice(i, i + n).join(" "));
|
|
426
514
|
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();
|
|
515
|
+
};
|
|
516
|
+
return dedupBy(text, (a, b) => {
|
|
517
|
+
const ga = grams(a), gb = grams(b);
|
|
518
|
+
const inter = [...ga].filter(g => gb.has(g)).length;
|
|
519
|
+
const union = new Set([...ga, ...gb]).size;
|
|
520
|
+
return union > 0 && inter / union >= threshold;
|
|
521
|
+
}, 15);
|
|
440
522
|
}
|
|
441
523
|
|
|
442
524
|
/**
|
|
443
525
|
* Edit-distance deduplication. Catches "Return JSON only." vs "Return JSON only!"
|
|
526
|
+
* Keeps line structure; numbers/IDs must match.
|
|
444
527
|
* @param threshold - max normalized edit distance (default 0.15)
|
|
445
|
-
* @risk medium | @savings
|
|
528
|
+
* @risk medium | @savings 0–15%
|
|
446
529
|
*/
|
|
447
530
|
export function levenshteinDeduplicate(text, threshold = 0.15) {
|
|
448
|
-
|
|
531
|
+
const lev = (a, b) => {
|
|
449
532
|
const m = a.length, n = b.length;
|
|
450
533
|
if (Math.abs(m - n) > Math.max(m, n) * 0.4) return Math.max(m, n);
|
|
451
534
|
const dp = Array.from({ length: m + 1 }, (_, i) => [i]);
|
|
452
535
|
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
453
536
|
for (let i = 1; i <= m; i++)
|
|
454
537
|
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]);
|
|
538
|
+
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
539
|
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();
|
|
540
|
+
};
|
|
541
|
+
return dedupBy(text, (a, b) => lev(a.toLowerCase(), b.toLowerCase()) / Math.max(a.length, b.length) <= threshold, 10);
|
|
466
542
|
}
|
|
467
543
|
|
|
468
544
|
// ════════════════════════════════════════════════════════════
|
|
469
545
|
// ADVANCED (EXTRACTIVE)
|
|
546
|
+
// Only plain prose is summarized. Code blocks, structured lines and
|
|
547
|
+
// critical sentences (rules, numbers, IDs, variables) are always kept.
|
|
470
548
|
// ════════════════════════════════════════════════════════════
|
|
471
549
|
|
|
472
550
|
/**
|
|
473
|
-
*
|
|
474
|
-
* @param ratio - fraction of sentences to keep (default 0.
|
|
475
|
-
* @risk medium | @savings
|
|
551
|
+
* Drops the lowest-scoring prose sentences by term frequency.
|
|
552
|
+
* @param ratio - fraction of droppable prose sentences to keep (default 0.75)
|
|
553
|
+
* @risk medium | @savings 0–30%
|
|
476
554
|
*/
|
|
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 };
|
|
555
|
+
export function extractiveCompress(text, ratio = 0.75) {
|
|
556
|
+
return summarizeBy(text, ratio, (sents) => {
|
|
557
|
+
const freq = {};
|
|
558
|
+
for (const w of words(sents.join(" "), 4)) freq[w] = (freq[w] || 0) + 1;
|
|
559
|
+
return sents.map(s => { const w = words(s, 4); return w.reduce((a, x) => a + (freq[x] || 0), 0) / (w.length || 1); });
|
|
487
560
|
});
|
|
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
561
|
}
|
|
492
562
|
|
|
493
563
|
/**
|
|
494
|
-
*
|
|
495
|
-
*
|
|
496
|
-
* @
|
|
497
|
-
* @risk medium | @savings 20–50%
|
|
564
|
+
* Drops the lowest-scoring prose sentences by TF-IDF.
|
|
565
|
+
* @param ratio - fraction of droppable prose sentences to keep (default 0.75)
|
|
566
|
+
* @risk medium | @savings 0–30%
|
|
498
567
|
*/
|
|
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 };
|
|
568
|
+
export function tfidfCompress(text, ratio = 0.75) {
|
|
569
|
+
return summarizeBy(text, ratio, (sents) => {
|
|
570
|
+
const n = sents.length, df = {};
|
|
571
|
+
const sw = sents.map(s => { const w = words(s); new Set(w).forEach(x => { df[x] = (df[x] || 0) + 1; }); return w; });
|
|
572
|
+
return sw.map(w => {
|
|
573
|
+
if (!w.length) return 0;
|
|
574
|
+
const f = {}; w.forEach(x => { f[x] = (f[x] || 0) + 1; });
|
|
575
|
+
return w.reduce((a, x) => a + (f[x] / w.length) * Math.log((n + 1) / ((df[x] || 0) + 1)), 0) / w.length;
|
|
576
|
+
});
|
|
520
577
|
});
|
|
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
578
|
}
|
|
525
579
|
|
|
526
580
|
/**
|
|
527
|
-
* TextRank — PageRank-style
|
|
528
|
-
*
|
|
529
|
-
* @param ratio - fraction of sentences to keep (default 0.
|
|
530
|
-
* @risk medium | @savings
|
|
581
|
+
* TextRank — PageRank-style ranking on the sentence similarity graph.
|
|
582
|
+
* Drops the least "central" prose sentences.
|
|
583
|
+
* @param ratio - fraction of droppable prose sentences to keep (default 0.75)
|
|
584
|
+
* @risk medium | @savings 0–30%
|
|
531
585
|
*/
|
|
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);
|
|
586
|
+
export function textRankCompress(text, ratio = 0.75, damping = 0.85, iterations = 20) {
|
|
587
|
+
return summarizeBy(text, ratio, (sents) => {
|
|
588
|
+
const n = sents.length;
|
|
589
|
+
const sets = sents.map(s => new Set(words(s)));
|
|
590
|
+
const sim = (i, j) => {
|
|
591
|
+
const a = sets[i], b = sets[j];
|
|
592
|
+
if (!a.size || !b.size) return 0;
|
|
593
|
+
return [...a].filter(w => b.has(w)).length / (Math.log(a.size + 1) + Math.log(b.size + 1));
|
|
594
|
+
};
|
|
595
|
+
const m = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (__, j) => (i === j ? 0 : sim(i, j))));
|
|
596
|
+
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); });
|
|
597
|
+
let sc = Array(n).fill(1 / n);
|
|
598
|
+
for (let it = 0; it < iterations; it++)
|
|
599
|
+
sc = sc.map((_, i) => (1 - damping) / n + damping * sc.reduce((acc, s, j) => acc + s * norm[j][i], 0));
|
|
600
|
+
return sc;
|
|
549
601
|
});
|
|
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
602
|
}
|