prompt-compressor 0.1.0__tar.gz

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,33 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*.*.*"
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: read
11
+ id-token: write
12
+
13
+ jobs:
14
+ build-and-publish:
15
+ runs-on: ubuntu-latest
16
+
17
+ steps:
18
+ - name: Checkout
19
+ uses: actions/checkout@v4
20
+
21
+ - name: Set up Python
22
+ uses: actions/setup-python@v5
23
+ with:
24
+ python-version: "3.11"
25
+
26
+ - name: Install build tools
27
+ run: pip install hatch
28
+
29
+ - name: Build distribution
30
+ run: hatch build
31
+
32
+ - name: Publish to PyPI
33
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,196 @@
1
+ Metadata-Version: 2.4
2
+ Name: prompt-compressor
3
+ Version: 0.1.0
4
+ Summary: Rule-based LLM prompt compression — 30+ algorithms, zero dependencies
5
+ Project-URL: Homepage, https://prompt-compressor.com
6
+ Project-URL: Repository, https://github.com/kettertom/prompt-compressor
7
+ Project-URL: Bug Tracker, https://github.com/kettertom/prompt-compressor/issues
8
+ Author: Tom Ketter
9
+ License: MIT
10
+ Keywords: anthropic,bedrock,compression,llm,openai,prompt,tokens
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Text Processing
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+
24
+ # prompt-compressor
25
+
26
+ > Rule-based LLM prompt compression — 30+ algorithms, zero dependencies.
27
+
28
+ [![PyPI version](https://badge.fury.io/py/prompt-compressor.svg)](https://pypi.org/project/prompt-compressor/)
29
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
30
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
31
+
32
+ Compress prompts **before** sending them to any LLM API. No model required, no API calls, zero overhead. Works with OpenAI, Anthropic, AWS Bedrock, Cohere, or any token-based API.
33
+
34
+ 🌐 **Web app**: [prompt-compressor.com](https://prompt-compressor.com)
35
+ 📦 **npm**: [prompt-compressor](https://www.npmjs.com/package/prompt-compressor)
36
+
37
+ ---
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install prompt-compressor
43
+ ```
44
+
45
+ ## Python API
46
+
47
+ ```python
48
+ from prompt_compressor import compress
49
+
50
+ result = compress(system_prompt, level="low")
51
+
52
+ print(result.output) # compressed text
53
+ print(result.tokens_before) # e.g. 1200
54
+ print(result.tokens_after) # e.g. 820
55
+ print(result.saved) # 380
56
+ print(result.reduction_pct) # 31.7
57
+ ```
58
+
59
+ ### Convenience function
60
+
61
+ ```python
62
+ from prompt_compressor import compress_text
63
+
64
+ compressed = compress_text(my_prompt, level="very-low")
65
+ ```
66
+
67
+ ### With AWS Bedrock
68
+
69
+ ```python
70
+ import boto3
71
+ from prompt_compressor import compress
72
+
73
+ bedrock = boto3.client("bedrock-runtime", region_name="us-east-1")
74
+
75
+ result = compress(system_prompt, level="low")
76
+
77
+ response = bedrock.invoke_model(
78
+ modelId="anthropic.claude-3-5-sonnet-20241022-v2:0",
79
+ body=json.dumps({
80
+ "anthropic_version": "bedrock-2023-05-31",
81
+ "system": result.output, # compressed!
82
+ "messages": [{"role": "user", "content": user_message}],
83
+ "max_tokens": 1024,
84
+ }),
85
+ )
86
+ ```
87
+
88
+ ---
89
+
90
+ ## CLI
91
+
92
+ ```bash
93
+ # Compress a file
94
+ prompt-compressor system_prompt.txt --level low
95
+
96
+ # With stats
97
+ prompt-compressor system_prompt.txt --level medium --stats
98
+
99
+ # Pipe
100
+ cat my_prompt.txt | prompt-compressor --level very-low
101
+
102
+ # Save to file
103
+ prompt-compressor input.txt --level low --output compressed.txt
104
+ ```
105
+
106
+ ---
107
+
108
+ ## Levels
109
+
110
+ | Level | Algorithms | Typical Reduction |
111
+ |-------|-----------|-------------------|
112
+ | `none` | Whitespace, unicode, ANSI, punctuation | 5–15% |
113
+ | `very-low` | + Filler removal, phrase shortening, JSON/SQL minify, license headers | 15–30% |
114
+ | `low` | + Hedging, meta-commentary, transitions, number normalization, code comments, exact dedup | 25–45% |
115
+ | `medium` | + Fuzzy/ngram/Levenshtein dedup, frequent patterns, TF-IDF, TextRank | 30–70% |
116
+
117
+ ## Variable Protection
118
+
119
+ Variables in `{{var}}`, `{var}`, `<tag>`, and `${var}` format are **always protected** by default:
120
+
121
+ ```python
122
+ result = compress("Hello {{name}}, query: {user_query}", level="medium")
123
+ # {{name}} and {user_query} are preserved exactly
124
+ ```
125
+
126
+ Disable with `protect_vars=False`.
127
+
128
+ ---
129
+
130
+ ## Algorithm Reference
131
+
132
+ ### Structural (none / very-low)
133
+ | Algorithm | Description |
134
+ |-----------|-------------|
135
+ | `normalize_whitespace` | Collapse spaces, trailing whitespace, blank lines |
136
+ | `normalize_unicode` | Replace fancy quotes, dashes, NBSP with ASCII |
137
+ | `strip_ansi` | Remove ANSI escape codes |
138
+ | `normalize_punctuation` | Remove `!!!!` → `!`, `....` → `...` |
139
+ | `strip_license_headers` | Remove MIT/Apache/GPL header blocks |
140
+ | `normalize_indentation` | 4-space → 2-space indent |
141
+
142
+ ### Language (very-low / low)
143
+ | Algorithm | Description |
144
+ |-----------|-------------|
145
+ | `remove_fillers` | "It is important to note that", "basically", "actually" |
146
+ | `shorten_phrases` | "in order to" → "to", "make use of" → "use" (50+ rules) |
147
+ | `remove_hedging` | "I think that", "In my opinion" |
148
+ | `remove_meta_commentary` | "Sure, I'd be happy to help!", "Let me know if..." |
149
+ | `remove_transitions` | Redundant "Furthermore,", "Additionally," |
150
+ | `remove_parentheticals` | Cross-reference parentheses |
151
+ | `normalize_numbers` | "twenty" → "20", "five" → "5" |
152
+ | `normalize_dates` | "January 5th, 2024" → "2024-01-05" |
153
+
154
+ ### Code (low)
155
+ | Algorithm | Description |
156
+ |-----------|-------------|
157
+ | `strip_code_comments` | `#` and `//` comments in fenced blocks |
158
+ | `strip_docstrings` | Python triple-quoted docstrings |
159
+ | `minify_json` | JSON code blocks → minified |
160
+ | `remove_null_json_fields` | Remove `null` fields from JSON |
161
+ | `minify_sql` | SQL blocks → whitespace-collapsed |
162
+ | `minify_css` | CSS blocks → minified |
163
+ | `strip_base64` | Long base64 strings → `[base64_data]` |
164
+ | `strip_hex_dumps` | Long hex strings → `[hex_data]` |
165
+ | `truncate_stack_traces` | Keep first 5 frames |
166
+ | `strip_ts_types` | TypeScript type annotations |
167
+
168
+ ### Deduplication (low / medium)
169
+ | Algorithm | Description |
170
+ |-----------|-------------|
171
+ | `dedup_exact_lines` | Consecutive duplicate lines |
172
+ | `dedup_exact_sentences` | Exact duplicate sentences |
173
+ | `dedup_fuzzy` | Jaccard similarity ≥ 0.85 |
174
+ | `dedup_ngram` | N-gram overlap ≥ 0.7 |
175
+ | `dedup_levenshtein` | Edit distance < 15% |
176
+ | `remove_frequent_patterns` | Apriori-style repeated phrases |
177
+ | `trie_prefix_compress` | Bullet groups with shared prefix |
178
+
179
+ ### Extractive (medium)
180
+ | Algorithm | Description |
181
+ |-----------|-------------|
182
+ | `tf_compress` | Keep sentences by term frequency |
183
+ | `tfidf_compress` | Keep sentences by TF-IDF score |
184
+ | `textrank_compress` | PageRank-style sentence scoring |
185
+
186
+ ---
187
+
188
+ ## Zero Dependencies
189
+
190
+ `prompt-compressor` uses only the Python standard library. No `numpy`, `nltk`, `spacy`, `tiktoken`, or anything else to install.
191
+
192
+ ---
193
+
194
+ ## License
195
+
196
+ MIT © Tom Ketter
@@ -0,0 +1,173 @@
1
+ # prompt-compressor
2
+
3
+ > Rule-based LLM prompt compression — 30+ algorithms, zero dependencies.
4
+
5
+ [![PyPI version](https://badge.fury.io/py/prompt-compressor.svg)](https://pypi.org/project/prompt-compressor/)
6
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
8
+
9
+ Compress prompts **before** sending them to any LLM API. No model required, no API calls, zero overhead. Works with OpenAI, Anthropic, AWS Bedrock, Cohere, or any token-based API.
10
+
11
+ 🌐 **Web app**: [prompt-compressor.com](https://prompt-compressor.com)
12
+ 📦 **npm**: [prompt-compressor](https://www.npmjs.com/package/prompt-compressor)
13
+
14
+ ---
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install prompt-compressor
20
+ ```
21
+
22
+ ## Python API
23
+
24
+ ```python
25
+ from prompt_compressor import compress
26
+
27
+ result = compress(system_prompt, level="low")
28
+
29
+ print(result.output) # compressed text
30
+ print(result.tokens_before) # e.g. 1200
31
+ print(result.tokens_after) # e.g. 820
32
+ print(result.saved) # 380
33
+ print(result.reduction_pct) # 31.7
34
+ ```
35
+
36
+ ### Convenience function
37
+
38
+ ```python
39
+ from prompt_compressor import compress_text
40
+
41
+ compressed = compress_text(my_prompt, level="very-low")
42
+ ```
43
+
44
+ ### With AWS Bedrock
45
+
46
+ ```python
47
+ import boto3
48
+ from prompt_compressor import compress
49
+
50
+ bedrock = boto3.client("bedrock-runtime", region_name="us-east-1")
51
+
52
+ result = compress(system_prompt, level="low")
53
+
54
+ response = bedrock.invoke_model(
55
+ modelId="anthropic.claude-3-5-sonnet-20241022-v2:0",
56
+ body=json.dumps({
57
+ "anthropic_version": "bedrock-2023-05-31",
58
+ "system": result.output, # compressed!
59
+ "messages": [{"role": "user", "content": user_message}],
60
+ "max_tokens": 1024,
61
+ }),
62
+ )
63
+ ```
64
+
65
+ ---
66
+
67
+ ## CLI
68
+
69
+ ```bash
70
+ # Compress a file
71
+ prompt-compressor system_prompt.txt --level low
72
+
73
+ # With stats
74
+ prompt-compressor system_prompt.txt --level medium --stats
75
+
76
+ # Pipe
77
+ cat my_prompt.txt | prompt-compressor --level very-low
78
+
79
+ # Save to file
80
+ prompt-compressor input.txt --level low --output compressed.txt
81
+ ```
82
+
83
+ ---
84
+
85
+ ## Levels
86
+
87
+ | Level | Algorithms | Typical Reduction |
88
+ |-------|-----------|-------------------|
89
+ | `none` | Whitespace, unicode, ANSI, punctuation | 5–15% |
90
+ | `very-low` | + Filler removal, phrase shortening, JSON/SQL minify, license headers | 15–30% |
91
+ | `low` | + Hedging, meta-commentary, transitions, number normalization, code comments, exact dedup | 25–45% |
92
+ | `medium` | + Fuzzy/ngram/Levenshtein dedup, frequent patterns, TF-IDF, TextRank | 30–70% |
93
+
94
+ ## Variable Protection
95
+
96
+ Variables in `{{var}}`, `{var}`, `<tag>`, and `${var}` format are **always protected** by default:
97
+
98
+ ```python
99
+ result = compress("Hello {{name}}, query: {user_query}", level="medium")
100
+ # {{name}} and {user_query} are preserved exactly
101
+ ```
102
+
103
+ Disable with `protect_vars=False`.
104
+
105
+ ---
106
+
107
+ ## Algorithm Reference
108
+
109
+ ### Structural (none / very-low)
110
+ | Algorithm | Description |
111
+ |-----------|-------------|
112
+ | `normalize_whitespace` | Collapse spaces, trailing whitespace, blank lines |
113
+ | `normalize_unicode` | Replace fancy quotes, dashes, NBSP with ASCII |
114
+ | `strip_ansi` | Remove ANSI escape codes |
115
+ | `normalize_punctuation` | Remove `!!!!` → `!`, `....` → `...` |
116
+ | `strip_license_headers` | Remove MIT/Apache/GPL header blocks |
117
+ | `normalize_indentation` | 4-space → 2-space indent |
118
+
119
+ ### Language (very-low / low)
120
+ | Algorithm | Description |
121
+ |-----------|-------------|
122
+ | `remove_fillers` | "It is important to note that", "basically", "actually" |
123
+ | `shorten_phrases` | "in order to" → "to", "make use of" → "use" (50+ rules) |
124
+ | `remove_hedging` | "I think that", "In my opinion" |
125
+ | `remove_meta_commentary` | "Sure, I'd be happy to help!", "Let me know if..." |
126
+ | `remove_transitions` | Redundant "Furthermore,", "Additionally," |
127
+ | `remove_parentheticals` | Cross-reference parentheses |
128
+ | `normalize_numbers` | "twenty" → "20", "five" → "5" |
129
+ | `normalize_dates` | "January 5th, 2024" → "2024-01-05" |
130
+
131
+ ### Code (low)
132
+ | Algorithm | Description |
133
+ |-----------|-------------|
134
+ | `strip_code_comments` | `#` and `//` comments in fenced blocks |
135
+ | `strip_docstrings` | Python triple-quoted docstrings |
136
+ | `minify_json` | JSON code blocks → minified |
137
+ | `remove_null_json_fields` | Remove `null` fields from JSON |
138
+ | `minify_sql` | SQL blocks → whitespace-collapsed |
139
+ | `minify_css` | CSS blocks → minified |
140
+ | `strip_base64` | Long base64 strings → `[base64_data]` |
141
+ | `strip_hex_dumps` | Long hex strings → `[hex_data]` |
142
+ | `truncate_stack_traces` | Keep first 5 frames |
143
+ | `strip_ts_types` | TypeScript type annotations |
144
+
145
+ ### Deduplication (low / medium)
146
+ | Algorithm | Description |
147
+ |-----------|-------------|
148
+ | `dedup_exact_lines` | Consecutive duplicate lines |
149
+ | `dedup_exact_sentences` | Exact duplicate sentences |
150
+ | `dedup_fuzzy` | Jaccard similarity ≥ 0.85 |
151
+ | `dedup_ngram` | N-gram overlap ≥ 0.7 |
152
+ | `dedup_levenshtein` | Edit distance < 15% |
153
+ | `remove_frequent_patterns` | Apriori-style repeated phrases |
154
+ | `trie_prefix_compress` | Bullet groups with shared prefix |
155
+
156
+ ### Extractive (medium)
157
+ | Algorithm | Description |
158
+ |-----------|-------------|
159
+ | `tf_compress` | Keep sentences by term frequency |
160
+ | `tfidf_compress` | Keep sentences by TF-IDF score |
161
+ | `textrank_compress` | PageRank-style sentence scoring |
162
+
163
+ ---
164
+
165
+ ## Zero Dependencies
166
+
167
+ `prompt-compressor` uses only the Python standard library. No `numpy`, `nltk`, `spacy`, `tiktoken`, or anything else to install.
168
+
169
+ ---
170
+
171
+ ## License
172
+
173
+ MIT © Tom Ketter
@@ -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)