prompt-compressor 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,13 @@
1
+ """prompt-compressor — rule-based prompt compression, zero dependencies."""
2
+
3
+ from .compressor import compress, compress_text, CompressResult, Level, VALID_LEVELS
4
+ from .tokens import count_tokens
5
+
6
+ __all__ = [
7
+ "compress",
8
+ "compress_text",
9
+ "CompressResult",
10
+ "Level",
11
+ "VALID_LEVELS",
12
+ "count_tokens",
13
+ ]
@@ -0,0 +1 @@
1
+ from . import structural, language, code, deduplication, extractive, protection
@@ -0,0 +1,165 @@
1
+ """Code algorithms — risk level: low / medium"""
2
+
3
+ import re
4
+ import json
5
+
6
+
7
+ # ─── COMMENT STRIPPING ───────────────────────────────────────────────────────
8
+
9
+ def strip_code_comments(text: str) -> str:
10
+ """Remove single-line and inline // and # comments from code blocks."""
11
+ # Only operate inside fenced code blocks
12
+ def _strip_block(m: re.Match) -> str:
13
+ lang = m.group(1).lower() if m.group(1) else ""
14
+ code = m.group(2)
15
+ if lang in ("python", "py", "ruby", "rb", "sh", "bash", ""):
16
+ # Strip # comments (but not shebangs on line 1)
17
+ lines = code.split("\n")
18
+ out = []
19
+ for i, line in enumerate(lines):
20
+ if i == 0 and line.startswith("#!"):
21
+ out.append(line)
22
+ else:
23
+ stripped = re.sub(r"\s*#(?!{).*$", "", line)
24
+ out.append(stripped)
25
+ code = "\n".join(out)
26
+ if lang in ("javascript", "js", "typescript", "ts", "java", "c", "cpp", "go", "rust", ""):
27
+ code = re.sub(r"\s*//(?!/).*$", "", code, flags=re.MULTILINE)
28
+ # Block comments /* ... */
29
+ code = re.sub(r"/\*[\s\S]*?\*/", "", code)
30
+ return m.group(0)[:m.group(0).find(m.group(2))] + code + "```"
31
+
32
+ return re.sub(r"```(\w*)\n([\s\S]*?)```", _strip_block, text)
33
+
34
+
35
+ def strip_docstrings(text: str) -> str:
36
+ """Remove Python docstrings inside fenced code blocks."""
37
+ def _strip_block(m: re.Match) -> str:
38
+ lang = m.group(1).lower() if m.group(1) else ""
39
+ code = m.group(2)
40
+ if lang in ("python", "py", ""):
41
+ # Remove triple-quoted strings that are standalone statements
42
+ code = re.sub(r'^\s*"""[\s\S]*?"""\s*$', "", code, flags=re.MULTILINE)
43
+ code = re.sub(r"^\s*'''[\s\S]*?'''\s*$", "", code, flags=re.MULTILINE)
44
+ return m.group(0)[:m.group(0).find(m.group(2))] + code + "```"
45
+
46
+ return re.sub(r"```(\w*)\n([\s\S]*?)```", _strip_block, text)
47
+
48
+
49
+ # ─── JSON MINIFICATION ───────────────────────────────────────────────────────
50
+
51
+ def minify_json(text: str) -> str:
52
+ """Minify JSON code blocks."""
53
+ def _minify(m: re.Match) -> str:
54
+ try:
55
+ parsed = json.loads(m.group(1))
56
+ minified = json.dumps(parsed, separators=(",", ":"), ensure_ascii=False)
57
+ return f"```json\n{minified}\n```"
58
+ except (json.JSONDecodeError, ValueError):
59
+ return m.group(0)
60
+
61
+ return re.sub(r"```json\n([\s\S]*?)```", _minify, text)
62
+
63
+
64
+ def remove_null_json_fields(text: str) -> str:
65
+ """Remove null/None fields from JSON code blocks."""
66
+ def _remove_nulls(m: re.Match) -> str:
67
+ try:
68
+ parsed = json.loads(m.group(1))
69
+ if isinstance(parsed, dict):
70
+ cleaned = {k: v for k, v in parsed.items() if v is not None}
71
+ return f"```json\n{json.dumps(cleaned, indent=2, ensure_ascii=False)}\n```"
72
+ except (json.JSONDecodeError, ValueError):
73
+ pass
74
+ return m.group(0)
75
+
76
+ return re.sub(r"```json\n([\s\S]*?)```", _remove_nulls, text)
77
+
78
+
79
+ # ─── SQL MINIFICATION ────────────────────────────────────────────────────────
80
+
81
+ def minify_sql(text: str) -> str:
82
+ """Minify SQL code blocks — remove comments and extra whitespace."""
83
+ def _minify(m: re.Match) -> str:
84
+ sql = m.group(1)
85
+ # Remove -- comments
86
+ sql = re.sub(r"--[^\n]*", "", sql)
87
+ # Remove /* */ comments
88
+ sql = re.sub(r"/\*[\s\S]*?\*/", "", sql)
89
+ # Collapse whitespace
90
+ sql = re.sub(r"\s+", " ", sql).strip()
91
+ return f"```sql\n{sql}\n```"
92
+
93
+ return re.sub(r"```sql\n([\s\S]*?)```", _minify, text, flags=re.IGNORECASE)
94
+
95
+
96
+ # ─── CSS MINIFICATION ────────────────────────────────────────────────────────
97
+
98
+ def minify_css(text: str) -> str:
99
+ """Minify CSS code blocks."""
100
+ def _minify(m: re.Match) -> str:
101
+ css = m.group(1)
102
+ css = re.sub(r"/\*[\s\S]*?\*/", "", css) # comments
103
+ css = re.sub(r"\s*([{}:;,])\s*", r"\1", css)
104
+ css = re.sub(r"\s+", " ", css).strip()
105
+ return f"```css\n{css}\n```"
106
+
107
+ return re.sub(r"```css\n([\s\S]*?)```", _minify, text)
108
+
109
+
110
+ # ─── BASE64 / HEX STRIPPING ──────────────────────────────────────────────────
111
+
112
+ def strip_base64(text: str) -> str:
113
+ """Replace long base64 strings with a placeholder."""
114
+ return re.sub(
115
+ r"\b([A-Za-z0-9+/]{60,}={0,2})\b",
116
+ "[base64_data]",
117
+ text,
118
+ )
119
+
120
+
121
+ def strip_hex_dumps(text: str) -> str:
122
+ """Replace long hex strings with a placeholder."""
123
+ return re.sub(
124
+ r"\b([0-9a-fA-F]{40,})\b",
125
+ "[hex_data]",
126
+ text,
127
+ )
128
+
129
+
130
+ # ─── STACK TRACE TRUNCATION ──────────────────────────────────────────────────
131
+
132
+ def truncate_stack_traces(text: str, max_frames: int = 5) -> str:
133
+ """Keep only the first N frames of stack traces."""
134
+ def _truncate(m: re.Match) -> str:
135
+ frames = re.findall(r"^\s+(?:at |File )[^\n]+$", m.group(0), re.MULTILINE)
136
+ if len(frames) <= max_frames:
137
+ return m.group(0)
138
+ kept = frames[:max_frames]
139
+ truncated_count = len(frames) - max_frames
140
+ return m.group(0).split(frames[0])[0] + "\n".join(kept) + f"\n ... ({truncated_count} more frames)"
141
+
142
+ # Python-style tracebacks
143
+ text = re.sub(
144
+ r"Traceback \(most recent call last\):[\s\S]*?(?=\n\S|\Z)",
145
+ _truncate,
146
+ text,
147
+ )
148
+ return text
149
+
150
+
151
+ # ─── TYPESCRIPT TYPE ANNOTATION REMOVAL ─────────────────────────────────────
152
+
153
+ def strip_ts_types(text: str) -> str:
154
+ """Remove TypeScript type annotations from TS code blocks."""
155
+ def _strip(m: re.Match) -> str:
156
+ lang = m.group(1).lower() if m.group(1) else ""
157
+ code = m.group(2)
158
+ if lang in ("typescript", "ts"):
159
+ # Remove `: Type` annotations in function params/variables
160
+ code = re.sub(r":\s*[A-Z][A-Za-z<>\[\]|&, ]+(?=[,)=\n;])", "", code)
161
+ # Remove `<Type>` generics (basic)
162
+ code = re.sub(r"<[A-Z][A-Za-z<>\[\]|& ,]+>(?=\()", "", code)
163
+ return m.group(0)[:m.group(0).find(m.group(2))] + code + "```"
164
+
165
+ return re.sub(r"```(\w*)\n([\s\S]*?)```", _strip, text)
@@ -0,0 +1,247 @@
1
+ """Deduplication algorithms — risk level: low / medium"""
2
+
3
+ import re
4
+ from collections import Counter
5
+ from typing import List
6
+
7
+
8
+ # ─── EXACT LINE DEDUPLICATION ────────────────────────────────────────────────
9
+
10
+ def dedup_exact_lines(text: str) -> str:
11
+ """Remove consecutive duplicate lines."""
12
+ lines = text.split("\n")
13
+ result = [lines[0]] if lines else []
14
+ for line in lines[1:]:
15
+ if line.strip() and line == result[-1]:
16
+ continue
17
+ result.append(line)
18
+ return "\n".join(result)
19
+
20
+
21
+ # ─── EXACT SENTENCE DEDUPLICATION ───────────────────────────────────────────
22
+
23
+ def dedup_exact_sentences(text: str) -> str:
24
+ """Remove duplicate sentences (keep first occurrence)."""
25
+ sentences = re.split(r"(?<=[.!?])\s+", text)
26
+ seen = set()
27
+ result = []
28
+ for sent in sentences:
29
+ key = sent.strip().lower()
30
+ if key not in seen:
31
+ seen.add(key)
32
+ result.append(sent)
33
+ return " ".join(result)
34
+
35
+
36
+ # ─── FUZZY DEDUPLICATION (JACCARD) ──────────────────────────────────────────
37
+
38
+ def _tokenize(text: str) -> set:
39
+ return set(re.findall(r"\b\w+\b", text.lower()))
40
+
41
+
42
+ def _jaccard(a: set, b: set) -> float:
43
+ if not a or not b:
44
+ return 0.0
45
+ return len(a & b) / len(a | b)
46
+
47
+
48
+ def dedup_fuzzy(text: str, threshold: float = 0.85) -> str:
49
+ """Remove sentences that are ≥ threshold Jaccard similarity to a prior one."""
50
+ sentences = re.split(r"(?<=[.!?])\s+", text)
51
+ kept: List[str] = []
52
+ kept_tokens: List[set] = []
53
+
54
+ for sent in sentences:
55
+ tokens = _tokenize(sent)
56
+ if not tokens:
57
+ kept.append(sent)
58
+ continue
59
+ if any(_jaccard(tokens, prev) >= threshold for prev in kept_tokens):
60
+ continue
61
+ kept.append(sent)
62
+ kept_tokens.append(tokens)
63
+
64
+ return " ".join(kept)
65
+
66
+
67
+ # ─── N-GRAM SIMILARITY DEDUPLICATION ────────────────────────────────────────
68
+
69
+ def _ngrams(text: str, n: int = 3) -> set:
70
+ words = re.findall(r"\b\w+\b", text.lower())
71
+ return set(zip(*[words[i:] for i in range(n)])) if len(words) >= n else set()
72
+
73
+
74
+ def dedup_ngram(text: str, n: int = 3, threshold: float = 0.7) -> str:
75
+ """Remove sentences with high n-gram overlap to prior sentences."""
76
+ sentences = re.split(r"(?<=[.!?])\s+", text)
77
+ kept: List[str] = []
78
+ kept_ngrams: List[set] = []
79
+
80
+ for sent in sentences:
81
+ grams = _ngrams(sent, n)
82
+ if not grams:
83
+ kept.append(sent)
84
+ continue
85
+ similar = False
86
+ for prev_grams in kept_ngrams:
87
+ if not prev_grams:
88
+ continue
89
+ overlap = len(grams & prev_grams) / len(grams | prev_grams)
90
+ if overlap >= threshold:
91
+ similar = True
92
+ break
93
+ if not similar:
94
+ kept.append(sent)
95
+ kept_ngrams.append(grams)
96
+
97
+ return " ".join(kept)
98
+
99
+
100
+ # ─── LEVENSHTEIN DEDUPLICATION ───────────────────────────────────────────────
101
+
102
+ def _levenshtein(a: str, b: str) -> int:
103
+ """Classic Levenshtein distance."""
104
+ if len(a) > len(b):
105
+ a, b = b, a
106
+ prev = list(range(len(a) + 1))
107
+ for j, cb in enumerate(b):
108
+ curr = [j + 1]
109
+ for i, ca in enumerate(a):
110
+ curr.append(min(prev[i + 1] + 1, curr[-1] + 1, prev[i] + (ca != cb)))
111
+ prev = curr
112
+ return prev[-1]
113
+
114
+
115
+ def dedup_levenshtein(text: str, threshold: float = 0.15) -> str:
116
+ """
117
+ Remove sentences whose normalized Levenshtein distance to a prior sentence
118
+ is below threshold (i.e., very similar).
119
+ threshold=0.15 means ≤15% of characters differ.
120
+ """
121
+ sentences = re.split(r"(?<=[.!?])\s+", text)
122
+ kept: List[str] = []
123
+
124
+ for sent in sentences:
125
+ if len(sent) < 20: # too short to meaningfully compare
126
+ kept.append(sent)
127
+ continue
128
+ duplicate = False
129
+ for prev in kept:
130
+ max_len = max(len(sent), len(prev))
131
+ if max_len == 0:
132
+ continue
133
+ dist = _levenshtein(sent[:200], prev[:200]) # cap for performance
134
+ if dist / max(len(sent), len(prev)) < threshold:
135
+ duplicate = True
136
+ break
137
+ if not duplicate:
138
+ kept.append(sent)
139
+
140
+ return " ".join(kept)
141
+
142
+
143
+ # ─── FREQUENT PATTERN MINING (APRIORI-STYLE) ────────────────────────────────
144
+
145
+ def remove_frequent_patterns(text: str, min_freq: int = 3, min_len: int = 20) -> str:
146
+ """
147
+ Find phrases (5-15 word n-grams) that repeat ≥ min_freq times
148
+ and keep only the first occurrence.
149
+ """
150
+ words = re.findall(r"\S+", text)
151
+ phrase_counts: Counter = Counter()
152
+
153
+ for n in range(5, 16):
154
+ for i in range(len(words) - n + 1):
155
+ phrase = " ".join(words[i:i + n])
156
+ if len(phrase) >= min_len:
157
+ phrase_counts[phrase] += 1
158
+
159
+ # Sort longest first to avoid partial matches
160
+ repeated = sorted(
161
+ [p for p, c in phrase_counts.items() if c >= min_freq],
162
+ key=len, reverse=True
163
+ )
164
+
165
+ for phrase in repeated:
166
+ escaped = re.escape(phrase)
167
+ # Keep first, remove subsequent
168
+ occurrences = list(re.finditer(escaped, text))
169
+ if len(occurrences) > 1:
170
+ for m in reversed(occurrences[1:]):
171
+ text = text[:m.start()] + text[m.end():]
172
+
173
+ return text
174
+
175
+
176
+ # ─── TRIE PREFIX COMPRESSION ────────────────────────────────────────────────
177
+
178
+ def trie_prefix_compress(text: str) -> str:
179
+ """
180
+ Find lines that share long common prefixes and group them.
181
+ E.g.:
182
+ - The user should be able to login
183
+ - The user should be able to logout
184
+ - The user should be able to view
185
+ → The user should be able to: login, logout, view
186
+ """
187
+ lines = text.split("\n")
188
+ result = []
189
+ i = 0
190
+ while i < len(lines):
191
+ line = lines[i].rstrip()
192
+ if not line.startswith(("- ", "* ", " - ")):
193
+ result.append(lines[i])
194
+ i += 1
195
+ continue
196
+
197
+ prefix_len = 4 # minimum common prefix word count
198
+ words = line.split()
199
+ # look ahead for siblings
200
+ siblings = [line]
201
+ j = i + 1
202
+ while j < len(lines):
203
+ next_line = lines[j].rstrip()
204
+ if not next_line.startswith(("- ", "* ", " - ")):
205
+ break
206
+ next_words = next_line.split()
207
+ # find common prefix length
208
+ common = 0
209
+ for w1, w2 in zip(words, next_words):
210
+ if w1 == w2:
211
+ common += 1
212
+ else:
213
+ break
214
+ if common >= prefix_len:
215
+ siblings.append(next_line)
216
+ j += 1
217
+ else:
218
+ break
219
+
220
+ if len(siblings) >= 3:
221
+ # Extract common prefix and suffixes
222
+ first_words = siblings[0].split()
223
+ # Recompute actual common prefix
224
+ common = len(first_words)
225
+ for sib in siblings[1:]:
226
+ sib_words = sib.split()
227
+ c = 0
228
+ for w1, w2 in zip(first_words, sib_words):
229
+ if w1 == w2:
230
+ c += 1
231
+ else:
232
+ break
233
+ common = min(common, c)
234
+ if common >= prefix_len:
235
+ bullet = "- " if siblings[0].startswith("- ") else "* "
236
+ prefix_text = " ".join(first_words[:common])
237
+ suffixes = [" ".join(sib.split()[common:]) for sib in siblings]
238
+ suffixes = [s for s in suffixes if s]
239
+ if suffixes:
240
+ result.append(f"{bullet}{prefix_text}: {', '.join(suffixes)}")
241
+ i = j
242
+ continue
243
+
244
+ result.append(lines[i])
245
+ i += 1
246
+
247
+ return "\n".join(result)
@@ -0,0 +1,151 @@
1
+ """Extractive algorithms — risk level: medium"""
2
+
3
+ import re
4
+ import math
5
+ from collections import Counter
6
+ from typing import List, Dict, Tuple
7
+
8
+
9
+ def _split_sentences(text: str) -> List[str]:
10
+ return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
11
+
12
+
13
+ def _tokenize(text: str) -> List[str]:
14
+ return re.findall(r"\b[a-z]{2,}\b", text.lower())
15
+
16
+
17
+ STOPWORDS = {
18
+ "a", "an", "the", "and", "or", "but", "in", "on", "at", "to", "for",
19
+ "of", "with", "by", "from", "is", "was", "are", "were", "be", "been",
20
+ "have", "has", "had", "do", "does", "did", "will", "would", "could",
21
+ "should", "may", "might", "this", "that", "these", "those", "it", "its",
22
+ "as", "if", "then", "than", "so", "up", "out", "no", "not", "can",
23
+ "about", "into", "through", "during", "before", "after", "above", "below",
24
+ "between", "each", "more", "most", "other", "some", "such", "own",
25
+ "same", "both", "few", "more", "most", "other", "into", "through",
26
+ "i", "you", "we", "they", "he", "she", "me", "him", "her", "us", "them",
27
+ }
28
+
29
+
30
+ # ─── TF COMPRESSION ──────────────────────────────────────────────────────────
31
+
32
+ def tf_compress(text: str, keep_ratio: float = 0.6) -> str:
33
+ """
34
+ Score each sentence by the average term frequency of its non-stopword tokens.
35
+ Keep the top `keep_ratio` fraction of sentences (by score), preserving order.
36
+ """
37
+ sentences = _split_sentences(text)
38
+ if len(sentences) <= 3:
39
+ return text
40
+
41
+ # Compute TF over full document
42
+ all_tokens = _tokenize(text)
43
+ tf: Counter = Counter(t for t in all_tokens if t not in STOPWORDS)
44
+ total = sum(tf.values()) or 1
45
+
46
+ def _score(sent: str) -> float:
47
+ tokens = [t for t in _tokenize(sent) if t not in STOPWORDS]
48
+ if not tokens:
49
+ return 0.0
50
+ return sum(tf[t] / total for t in tokens) / len(tokens)
51
+
52
+ scored = [(i, s, _score(s)) for i, s in enumerate(sentences)]
53
+ threshold = sorted([x[2] for x in scored], reverse=True)[
54
+ max(0, int(len(scored) * keep_ratio) - 1)
55
+ ]
56
+ kept = [s for i, s, score in scored if score >= threshold]
57
+ return " ".join(kept)
58
+
59
+
60
+ # ─── TF-IDF COMPRESSION ──────────────────────────────────────────────────────
61
+
62
+ def tfidf_compress(text: str, keep_ratio: float = 0.6) -> str:
63
+ """
64
+ Score each sentence by TF-IDF, treating each sentence as a document.
65
+ Keep the top `keep_ratio` fraction.
66
+ """
67
+ sentences = _split_sentences(text)
68
+ if len(sentences) <= 3:
69
+ return text
70
+
71
+ # Tokenize per sentence
72
+ sent_tokens = [
73
+ [t for t in _tokenize(s) if t not in STOPWORDS]
74
+ for s in sentences
75
+ ]
76
+ N = len(sentences)
77
+
78
+ # IDF
79
+ df: Counter = Counter()
80
+ for tokens in sent_tokens:
81
+ for t in set(tokens):
82
+ df[t] += 1
83
+
84
+ def _idf(term: str) -> float:
85
+ return math.log((N + 1) / (df.get(term, 0) + 1)) + 1
86
+
87
+ def _score(tokens: List[str]) -> float:
88
+ if not tokens:
89
+ return 0.0
90
+ tf: Counter = Counter(tokens)
91
+ total = len(tokens)
92
+ return sum((tf[t] / total) * _idf(t) for t in tokens) / len(tokens)
93
+
94
+ scored = [(i, sentences[i], _score(sent_tokens[i])) for i in range(N)]
95
+ threshold = sorted([x[2] for x in scored], reverse=True)[
96
+ max(0, int(len(scored) * keep_ratio) - 1)
97
+ ]
98
+ kept = [s for i, s, score in scored if score >= threshold]
99
+ return " ".join(kept)
100
+
101
+
102
+ # ─── TEXTRANK COMPRESSION ────────────────────────────────────────────────────
103
+
104
+ def _similarity(tokens_a: set, tokens_b: set) -> float:
105
+ if not tokens_a or not tokens_b:
106
+ return 0.0
107
+ intersection = tokens_a & tokens_b
108
+ denom = math.log(len(tokens_a) + 1) + math.log(len(tokens_b) + 1)
109
+ return len(intersection) / denom if denom else 0.0
110
+
111
+
112
+ def textrank_compress(text: str, keep_ratio: float = 0.5, damping: float = 0.85, iterations: int = 30) -> str:
113
+ """
114
+ PageRank-style sentence scoring. Keep top `keep_ratio` sentences by rank.
115
+ """
116
+ sentences = _split_sentences(text)
117
+ if len(sentences) <= 3:
118
+ return text
119
+
120
+ sent_tokens = [
121
+ set(_tokenize(s)) - STOPWORDS
122
+ for s in sentences
123
+ ]
124
+ N = len(sentences)
125
+
126
+ # Build similarity matrix
127
+ sim: List[List[float]] = [[0.0] * N for _ in range(N)]
128
+ for i in range(N):
129
+ for j in range(N):
130
+ if i != j:
131
+ sim[i][j] = _similarity(sent_tokens[i], sent_tokens[j])
132
+
133
+ # Normalize rows
134
+ for i in range(N):
135
+ row_sum = sum(sim[i]) or 1
136
+ sim[i] = [v / row_sum for v in sim[i]]
137
+
138
+ # Power iteration
139
+ scores = [1.0 / N] * N
140
+ for _ in range(iterations):
141
+ new_scores = [
142
+ (1 - damping) / N + damping * sum(sim[j][i] * scores[j] for j in range(N))
143
+ for i in range(N)
144
+ ]
145
+ scores = new_scores
146
+
147
+ # Keep top keep_ratio sentences, preserve original order
148
+ n_keep = max(1, int(N * keep_ratio))
149
+ top_indices = set(sorted(range(N), key=lambda i: scores[i], reverse=True)[:n_keep])
150
+ kept = [sentences[i] for i in range(N) if i in top_indices]
151
+ return " ".join(kept)