llm-text-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,207 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
@@ -0,0 +1,5 @@
1
+ {
2
+ "python-envs.defaultEnvManager": "ms-python.python:conda",
3
+ "python-envs.defaultPackageManager": "ms-python.python:conda",
4
+ "python-envs.pythonProjects": []
5
+ }
@@ -0,0 +1,171 @@
1
+ # AGENTS.md
2
+
3
+ ## Project overview
4
+
5
+ `llm-text-compressor` is a pure Python library (zero dependencies) that removes characters from text while keeping it understandable by LLMs. It compresses text at 4 graduated levels — from light (doubled letter removal) to maximum (sentence pruning + aggressive trim) — while automatically preserving structured data like URLs, emails, IDs, code blocks, JSON, and XML.
6
+
7
+ The project includes a production-ready FastAPI REST API with Redis caching support for high-performance deployments.
8
+
9
+ The full technical specification is in `SPECS.md`.
10
+
11
+ ## Setup commands
12
+
13
+ ### Core Library
14
+
15
+ - Install in editable mode: `pip install -e ".[dev]"`
16
+ - Run tests: `pytest`
17
+ - Lint: `ruff check src/ tests/`
18
+ - Type check: `mypy src/`
19
+ - Run benchmarks: `python benchmarks/run_benchmark.py`
20
+
21
+ ### REST API
22
+
23
+ - Install API dependencies: `pip install -r api/requirements.txt`
24
+ - Start API locally: `uvicorn api.main:app --reload`
25
+ - Start with Docker Compose: `docker compose up --build`
26
+ - Stop containers: `docker compose down`
27
+ - View API docs: `http://localhost:8000/docs`
28
+
29
+ ## Project structure
30
+
31
+ ```
32
+ src/llm_text_compressor/
33
+ __init__.py # Public API re-exports (compress, compress_with_stats, compress_stream, compress_file, CompressionResult, PreservedSpan)
34
+ compressor.py # All compression logic — single module, ~1200 lines
35
+ tests/
36
+ test_compressor.py # 124 tests across 16 test classes
37
+ benchmarks/
38
+ run_benchmark.py # CLI benchmark runner
39
+ corpus/ # Sample .txt files for benchmarking
40
+ api/
41
+ main.py # FastAPI application with Redis caching (~450 lines)
42
+ requirements.txt # API dependencies (fastapi, uvicorn, redis)
43
+ README.md # API documentation
44
+ .env.example # Environment variable template
45
+ docker-compose.yml # Docker Compose config (API + Redis)
46
+ Dockerfile # Container image for API
47
+ ```
48
+
49
+ The **core library** is a single-module design. All compression logic lives in `compressor.py`. Do not split it into multiple modules without explicit instruction.
50
+
51
+ The **REST API** is a separate FastAPI application in the `api/` directory with Redis caching support.
52
+
53
+ ## Code style
54
+
55
+ - Python 3.10+ required (uses `slots=True` on dataclasses, `X | Y` union syntax)
56
+ - Ruff linter with rules: `E`, `F`, `I`, `N`, `W`, `UP`
57
+ - Line length: 120
58
+ - mypy strict mode enabled
59
+ - Use `from __future__ import annotations` only where needed
60
+ - Dataclasses use `frozen=True, slots=True`
61
+ - Type all function signatures — no `Any` unless unavoidable
62
+ - Prefer compiled regex (`re.compile`) stored as module-level constants prefixed with `_`
63
+ - Private functions and constants prefixed with `_`
64
+
65
+ ## Testing instructions
66
+
67
+ - All tests are in `tests/test_compressor.py`
68
+ - Run the full suite: `pytest`
69
+ - Run a specific test class: `pytest tests/test_compressor.py::TestCompress`
70
+ - Run a specific test: `pytest tests/test_compressor.py::TestCompress::test_level2_removes_vowels`
71
+ - Tests must pass before any commit. Fix failures before finishing a task.
72
+ - Add or update tests for any code change, even if not explicitly asked.
73
+ - Test classes follow the pattern `Test<FeatureName>` with descriptive method names `test_<behaviour>`
74
+
75
+ ### Test classes and what they cover
76
+
77
+ | Class | Feature |
78
+ | ----------------------------- | -------------------------------------------- |
79
+ | `TestCompress` | Core compression at all levels, edge cases |
80
+ | `TestPreserveEmails` | Email address preservation |
81
+ | `TestPreserveURLs` | URL preservation |
82
+ | `TestPreservePhoneNumbers` | Phone number preservation |
83
+ | `TestPreserveIDs` | UUID, hex ID, alphanumeric ID preservation |
84
+ | `TestPreserveProperNouns` | Capitalised words, acronyms |
85
+ | `TestCompressorOffTags` | `[COMPRESSOR_OFF]` opt-out regions |
86
+ | `TestWhitespaceNormalization` | Space collapse, blank line limits |
87
+ | `TestPreserveStructuredData` | JSON, XML, code blocks |
88
+ | `TestCompressionStats` | `CompressionResult` fields and spans |
89
+ | `TestCustomPreservePatterns` | User regex patterns |
90
+ | `TestCustomPreserveWords` | User word sets |
91
+ | `TestMarkdownMode` | Markdown-aware compression |
92
+ | `TestLocaleSupport` | French, Spanish, German, Portuguese, Italian |
93
+ | `TestStreamCompression` | `compress_stream` and `compress_file` |
94
+ | `TestSentencePruning` | Level 4 filler removal and line dedup |
95
+
96
+ ## Architecture and conventions
97
+
98
+ - **Public API** is defined in `__init__.py` via `__all__`. Only add exports there if introducing a new public function or dataclass.
99
+ - **Compression pipeline order**: whitespace normalization → COMPRESSOR_OFF extraction → markdown routing or standard compression → preserve pattern detection → word-level compression.
100
+ - **Level 4** applies `_prune_sentences()` first, then delegates to level 3 compression. The variable `effective_level` is set to `3` when `level == 4`.
101
+ - **Preservation spans** are detected at three layers: structured data (`_extract_structured_data_spans`), built-in regex (`_PRESERVE_PATTERNS`), and custom patterns. All are merged, sorted, and deduplicated before compression fills the gaps.
102
+ - **Overlap resolution**: when preserved spans overlap, the earlier span wins and the later one is discarded.
103
+ - The **`_PRESERVE_WORDS`** set contains ~48 common English stop words plus Python keywords (`def`, `class`, `return`, `import`, `from`). These words are never compressed regardless of level.
104
+ - **Locale stop words** (`_LOCALE_STOP_WORDS`) are merged into the preserve-words set at call time; they don't modify the global state.
105
+ - **`_compress_word()`** is the core per-word transform. It checks guards (short word, stop word, special chars, acronym, proper noun) before applying level-specific transforms.
106
+
107
+ ## Important warnings
108
+
109
+ - Never modify preserved spans or the order of pattern evaluation without updating tests.
110
+ - The `_PRESERVE_PATTERNS` regex uses alternation (`|`) with patterns ordered from most specific to least specific. Changing order can break preservation.
111
+ - `CompressionResult.preserved_spans` positions are in **compressed output** coordinates, not original text coordinates.
112
+ - Streaming (`compress_stream`) splits at word boundaries. Output is not guaranteed to be character-identical to non-streaming `compress()` on the same input due to whitespace normalization differences at chunk boundaries.
113
+ - `_normalize_whitespace` preserves leading indentation but collapses interior space runs. This is important for code-like content.
114
+
115
+ ## PR and commit guidelines
116
+
117
+ - Run `pytest`, `ruff check src/ tests/`, and `mypy src/` before committing.
118
+ - Keep the single-module structure unless explicitly told to refactor.
119
+ - Bump version in `pyproject.toml` for any user-facing change.
120
+
121
+ ## REST API architecture
122
+
123
+ ### Components
124
+
125
+ - **FastAPI application** (`api/main.py`) — async REST endpoints with OpenAPI documentation
126
+ - **Redis caching** — optional, automatic fallback if unavailable
127
+ - **Docker Compose** — multi-container setup (API + Redis 7)
128
+ - **Health checks** — container-level health monitoring
129
+
130
+ ### API endpoints
131
+
132
+ | Method | Path | Description |
133
+ | ------ | ------------------ | ------------------------------------ |
134
+ | GET | `/health` | Health check with cache status |
135
+ | GET | `/cache/stats` | Cache statistics (keys, memory, TTL) |
136
+ | POST | `/compress` | Compress text (cached) |
137
+ | POST | `/compress/stats` | Compress with statistics (cached) |
138
+ | POST | `/compress/batch` | Batch compression (not cached) |
139
+ | POST | `/compress/stream` | Streaming compression (not cached) |
140
+
141
+ ### Caching strategy
142
+
143
+ - **Cache keys** generated from SHA-256 hash of request parameters
144
+ - **TTL** configurable via `CACHE_TTL` env var (default: 3600s)
145
+ - **Prefixes**: `compress:*` and `compress_stats:*`
146
+ - **Graceful degradation**: API works without Redis
147
+ - Batch and streaming endpoints do not use cache
148
+
149
+ ### Environment variables
150
+
151
+ - `REDIS_URL` — Redis connection URL (default: `redis://redis:6379`)
152
+ - `CACHE_TTL` — Cache TTL in seconds (default: `3600`)
153
+ - `PYTHONUNBUFFERED` — Set to `1` for Docker logs
154
+
155
+ ### Code style (API)
156
+
157
+ - Python 3.10+ with FastAPI and async/await
158
+ - Pydantic models for request/response validation
159
+ - Type hints on all functions
160
+ - redis.asyncio (aioredis) for async Redis client
161
+ - Follow same ruff/mypy rules as core library
162
+
163
+ ### API development workflow
164
+
165
+ 1. Make changes to `api/main.py`
166
+ 2. Test locally: `uvicorn api.main:app --reload`
167
+ 3. Test with Docker: `docker compose up --build`
168
+ 4. Verify health: `curl http://localhost:8000/health`
169
+ 5. Check cache: `curl http://localhost:8000/cache/stats`
170
+ 6. Test compression: `curl -X POST http://localhost:8000/compress -H "Content-Type: application/json" -d '{"text": "test", "level": 2}'`
171
+ 7. Stop: `docker compose down`
@@ -0,0 +1,21 @@
1
+ FROM python:3.12-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install curl for healthcheck
6
+ RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
7
+
8
+ # Install the library first (leverages Docker cache)
9
+ COPY pyproject.toml README.md LICENSE ./
10
+ COPY src/ src/
11
+ RUN pip install --no-cache-dir .
12
+
13
+ # Install API dependencies
14
+ COPY api/requirements.txt api/requirements.txt
15
+ RUN pip install --no-cache-dir -r api/requirements.txt
16
+
17
+ COPY api/ api/
18
+
19
+ EXPOSE 8000
20
+
21
+ CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000"]
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aslan Vatsaev
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.