preembed 0.1.1__tar.gz → 0.2.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.
- preembed-0.2.0/PKG-INFO +275 -0
- preembed-0.2.0/README.md +226 -0
- {preembed-0.1.1 → preembed-0.2.0}/pyproject.toml +30 -5
- {preembed-0.1.1 → preembed-0.2.0}/python/preembed/__init__.py +11 -1
- preembed-0.2.0/python/preembed/__main__.py +8 -0
- preembed-0.2.0/python/preembed/cli.py +421 -0
- preembed-0.2.0/python/preembed/integrations/__init__.py +5 -0
- preembed-0.2.0/python/preembed/integrations/_common.py +122 -0
- preembed-0.2.0/python/preembed/integrations/langchain.py +159 -0
- preembed-0.2.0/python/preembed/integrations/llamaindex.py +122 -0
- {preembed-0.1.1 → preembed-0.2.0}/python/preembed/pipeline.py +60 -104
- preembed-0.2.0/python/preembed/preembed_core.pyi +28 -0
- {preembed-0.1.1 → preembed-0.2.0}/python/preembed/report.py +3 -1
- preembed-0.2.0/python/preembed/text.py +558 -0
- {preembed-0.1.1 → preembed-0.2.0}/python/preembed/types.py +2 -0
- {preembed-0.1.1 → preembed-0.2.0}/rust/Cargo.lock +287 -94
- {preembed-0.1.1 → preembed-0.2.0}/rust/Cargo.toml +8 -2
- preembed-0.2.0/rust/benches/primitives.rs +82 -0
- preembed-0.2.0/rust/proptest-regressions/dedupe.txt +7 -0
- preembed-0.2.0/rust/src/chunk.rs +184 -0
- preembed-0.2.0/rust/src/clean.rs +270 -0
- preembed-0.2.0/rust/src/dedupe.rs +539 -0
- preembed-0.2.0/rust/src/fasthash.rs +27 -0
- {preembed-0.1.1 → preembed-0.2.0}/rust/src/lib.rs +133 -17
- preembed-0.2.0/rust/src/rules.rs +66 -0
- {preembed-0.1.1 → preembed-0.2.0}/rust/src/score.rs +53 -10
- preembed-0.1.1/PKG-INFO +0 -164
- preembed-0.1.1/README.md +0 -129
- preembed-0.1.1/python/preembed/text.py +0 -360
- preembed-0.1.1/rust/src/chunk.rs +0 -114
- preembed-0.1.1/rust/src/clean.rs +0 -109
- preembed-0.1.1/rust/src/dedupe.rs +0 -307
- {preembed-0.1.1 → preembed-0.2.0}/LICENSE +0 -0
- {preembed-0.1.1 → preembed-0.2.0}/python/preembed/py.typed +0 -0
- {preembed-0.1.1 → preembed-0.2.0}/rust/src/error.rs +0 -0
preembed-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: preembed
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
5
|
+
Classifier: Environment :: Console
|
|
6
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
7
|
+
Classifier: Operating System :: OS Independent
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Classifier: Topic :: Text Processing
|
|
16
|
+
Requires-Dist: beautifulsoup4 ; extra == 'bench'
|
|
17
|
+
Requires-Dist: langchain-text-splitters ; extra == 'bench'
|
|
18
|
+
Requires-Dist: semchunk ; extra == 'bench'
|
|
19
|
+
Requires-Dist: chonkie ; extra == 'bench'
|
|
20
|
+
Requires-Dist: tiktoken ; extra == 'bench'
|
|
21
|
+
Requires-Dist: datasketch ; extra == 'bench'
|
|
22
|
+
Requires-Dist: hypothesis>=6 ; extra == 'dev'
|
|
23
|
+
Requires-Dist: maturin>=1.9,<2 ; extra == 'dev'
|
|
24
|
+
Requires-Dist: pytest>=8 ; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest-cov>=5 ; extra == 'dev'
|
|
26
|
+
Requires-Dist: langchain-text-splitters>=0.3 ; extra == 'langchain'
|
|
27
|
+
Requires-Dist: langchain-core>=0.3 ; extra == 'langchain'
|
|
28
|
+
Requires-Dist: ruff==0.15.12 ; extra == 'lint'
|
|
29
|
+
Requires-Dist: mypy>=1.9 ; extra == 'lint'
|
|
30
|
+
Requires-Dist: llama-index-core>=0.12 ; extra == 'llamaindex'
|
|
31
|
+
Provides-Extra: bench
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Provides-Extra: langchain
|
|
34
|
+
Provides-Extra: lint
|
|
35
|
+
Provides-Extra: llamaindex
|
|
36
|
+
License-File: LICENSE
|
|
37
|
+
Summary: High-performance document preparation toolkit for LLM and RAG pipelines.
|
|
38
|
+
Keywords: llm,rag,chunking,document-processing,embeddings
|
|
39
|
+
Home-Page: https://github.com/AdityaMunot/preembed
|
|
40
|
+
Author: Aditya Munot
|
|
41
|
+
Requires-Python: >=3.10
|
|
42
|
+
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
43
|
+
Project-URL: Changelog, https://github.com/AdityaMunot/preembed/blob/main/CHANGELOG.md
|
|
44
|
+
Project-URL: Documentation, https://github.com/AdityaMunot/preembed#readme
|
|
45
|
+
Project-URL: Homepage, https://github.com/AdityaMunot/preembed
|
|
46
|
+
Project-URL: Issues, https://github.com/AdityaMunot/preembed/issues
|
|
47
|
+
Project-URL: Repository, https://github.com/AdityaMunot/preembed
|
|
48
|
+
|
|
49
|
+
# preembed
|
|
50
|
+
|
|
51
|
+
<p align="center">
|
|
52
|
+
<picture>
|
|
53
|
+
<img src="https://raw.githubusercontent.com/AdityaMunot/preembed/main/assets/logo.png" alt="preembed" width="400">
|
|
54
|
+
</picture>
|
|
55
|
+
</p>
|
|
56
|
+
|
|
57
|
+
> Clean, chunk, deduplicate, and score documents before embedding.
|
|
58
|
+
|
|
59
|
+
**preembed** is a Rust-powered toolkit that sits between your raw documents and your vector database. It turns messy HTML, markdown, logs, and exports into high-quality, LLM-ready chunks — so your RAG pipeline retrieves better context and hallucinates less.
|
|
60
|
+
|
|
61
|
+
[](LICENSE)
|
|
62
|
+
[](https://www.python.org)
|
|
63
|
+
[](https://www.rust-lang.org)
|
|
64
|
+
|
|
65
|
+
## Why
|
|
66
|
+
|
|
67
|
+
Most RAG pipelines embed documents directly — noise, duplicates, and all. The result: wasted tokens, bloated vector stores, and retrieval that returns boilerplate instead of answers.
|
|
68
|
+
|
|
69
|
+
preembed fixes the data before it enters the pipeline:
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
raw documents → clean → chunk → dedupe → score → embed
|
|
73
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
74
|
+
preembed handles this
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Install
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pip install preembed
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
For development (requires Rust toolchain):
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pip install -e ".[dev]"
|
|
87
|
+
maturin develop --release
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Validate your corpus in 60 seconds
|
|
91
|
+
|
|
92
|
+
No code required. Point the CLI at a folder of `.md`, `.txt`, `.html`, `.log`, `.json`, or `.csv` files:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
pip install preembed
|
|
96
|
+
preembed check path/to/docs --report report.html
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
```
|
|
100
|
+
documents: 6
|
|
101
|
+
chunks: 6
|
|
102
|
+
avg chunk size: 103.2 words
|
|
103
|
+
duplicate ratio: 25.00%
|
|
104
|
+
low quality: 0 (0.00%, score < 0.5)
|
|
105
|
+
top warnings: low_information_density=2
|
|
106
|
+
|
|
107
|
+
worst chunks:
|
|
108
|
+
0.63 logs/worker.log#0 [low_information_density]
|
|
109
|
+
2026-11-25T10:00:00Z worker-1 status ok heartbeat ok 2026-11-25T10:01:00Z wor...
|
|
110
|
+
...
|
|
111
|
+
|
|
112
|
+
PASS
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`preembed check` exits `0` when thresholds pass, `1` when they fail, and `2` on bad input, so it works as a CI gate:
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
preembed check docs/ --min-score 0.5 --max-low-quality-ratio 0.2 --max-duplicate-ratio 0.1
|
|
119
|
+
preembed check docs/ --format json # machine-readable summary
|
|
120
|
+
preembed export docs/ -o chunks.jsonl --min-score 0.5 # streamed, one chunk per line
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Try it on the bundled messy corpus in [`examples/`](examples/) (duplicates, HTML boilerplate, noisy logs).
|
|
124
|
+
|
|
125
|
+
## Quickstart
|
|
126
|
+
|
|
127
|
+
### Pipeline (recommended)
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from preembed import Pipeline
|
|
131
|
+
|
|
132
|
+
result = Pipeline(chunk_size=512, overlap=64).run("path/to/documents/")
|
|
133
|
+
result.save_report("report.json")
|
|
134
|
+
|
|
135
|
+
print(f"{result.stats.total_chunks} chunks, {result.stats.duplicate_ratio:.0%} duplicates removed")
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Individual primitives
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
from preembed import clean_text, chunk_text, dedupe_chunks, score_chunks
|
|
142
|
+
|
|
143
|
+
text = clean_text("<html><script>tracking()</script><p>Actual content here.</p></html>")
|
|
144
|
+
# → "Actual content here."
|
|
145
|
+
|
|
146
|
+
chunks = chunk_text(text, chunk_size=512, overlap=64)
|
|
147
|
+
chunks = dedupe_chunks(chunks)
|
|
148
|
+
scored = score_chunks(chunks)
|
|
149
|
+
# Each chunk gets a 0-1 quality score + warning labels
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Streaming (memory-efficient)
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
for batch in Pipeline().stream("huge_corpus/", batch_size=50):
|
|
156
|
+
upload_to_vector_db(batch.scored_chunks)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Documents are read and processed one batch at a time. Exact and normalized duplicates are removed across batches (near-duplicates within a batch); the cross-batch filter keeps a 16-byte hash per unique chunk, so memory grows with unique chunks, not with document size. A batch whose chunks were all duplicates is still yielded with no chunks, `duplicate_ratio == 1.0`, and the warning `all_chunks_duplicate`.
|
|
160
|
+
|
|
161
|
+
### Custom scoring
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
from preembed import register_scorer
|
|
165
|
+
|
|
166
|
+
@register_scorer("domain_relevance", weight=0.15)
|
|
167
|
+
def domain_scorer(chunk: str) -> float:
|
|
168
|
+
return 1.0 if "patient" in chunk.lower() else 0.3
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Blends with the built-in scoring engine. Errors default to neutral (0.5) — won't crash your pipeline.
|
|
172
|
+
|
|
173
|
+
### Regex rules (compiled once, run in Rust)
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
from preembed import register_cleaner, register_score_rule
|
|
177
|
+
|
|
178
|
+
register_cleaner(r"Page \d+ of \d+") # remove page footers
|
|
179
|
+
register_cleaner(r"(\w+)@example\.com", "$1@redacted") # Rust regex replacement syntax
|
|
180
|
+
register_score_rule(r"(?i)impressum|datenschutz", -0.3, warning="boilerplate")
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Cleaners run inside `clean_text` (and therefore `Pipeline`). Score rules add their weight to matching chunks and can label them, which is how to cover boilerplate the built-in English heuristics miss.
|
|
184
|
+
|
|
185
|
+
### Real token budgets
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
import tiktoken
|
|
189
|
+
from preembed import Pipeline
|
|
190
|
+
|
|
191
|
+
encode = tiktoken.get_encoding("cl100k_base").encode_ordinary # special-token text stays plain text
|
|
192
|
+
result = Pipeline(chunk_size=512, overlap=64, tokenizer=encode).run("docs/")
|
|
193
|
+
# chunk_size/overlap are now tokens, and Chunk.tokens is the real token count
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Without a tokenizer, sizes and `Chunk.tokens` are whitespace word counts.
|
|
197
|
+
|
|
198
|
+
### LangChain and LlamaIndex
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
from preembed.integrations.langchain import PreembedTextSplitter, PreembedDocumentTransformer
|
|
202
|
+
from preembed.integrations.llamaindex import PreembedNodeParser, PreembedFilter
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Drop-in splitters plus a dedupe/score filter for both frameworks (`pip install "preembed[langchain]"` or `"preembed[llamaindex]"`). See [docs/integrations.md](docs/integrations.md).
|
|
206
|
+
|
|
207
|
+
## How it works
|
|
208
|
+
|
|
209
|
+
| Stage | What it does |
|
|
210
|
+
|---|---|
|
|
211
|
+
| **Clean** | Strip HTML tags plus `script`, `style`, `nav`, `footer`, `noscript`, `template`, and `svg` blocks. Normalize whitespace and unicode. In the pipeline, paragraph and block boundaries are kept for chunking. |
|
|
212
|
+
| **Chunk** | Structure-aware splitting on headings, code fences, and paragraphs. Never exceeds `chunk_size` words (or tokens with a tokenizer). Each chunk is an exact slice of the cleaned text, so line breaks and code indentation are kept. Configurable overlap. |
|
|
213
|
+
| **Dedupe** | Exact, normalized, and near-duplicate removal via fingerprint similarity. |
|
|
214
|
+
| **Score** | Quality score (0–1) based on length, density, structure, duplicates. Warning labels for boilerplate, too-short/long, low-density. |
|
|
215
|
+
| **Report** | JSON, Markdown, or HTML diagnostics with per-chunk scores and recommendations. |
|
|
216
|
+
|
|
217
|
+
## API
|
|
218
|
+
|
|
219
|
+
```python
|
|
220
|
+
# Core primitives
|
|
221
|
+
clean_text(text: str, *, preserve_structure=False) -> str
|
|
222
|
+
chunk_text(text: str, chunk_size=512, overlap=64, mode="word", tokenizer=None) -> list[str]
|
|
223
|
+
chunk_spans(text: str, chunk_size=512, overlap=64, mode="word", tokenizer=None) -> list[tuple[int, int]]
|
|
224
|
+
dedupe_chunks(chunks, return_stats=False, near_duplicate_threshold=0.9) -> list[str] | DedupeResult
|
|
225
|
+
score_chunks(chunks, tokenizer=None) -> list[Chunk]
|
|
226
|
+
|
|
227
|
+
# Pipeline
|
|
228
|
+
Pipeline(chunk_size=512, overlap=64, clean=True, dedupe=True, score=True, tokenizer=None)
|
|
229
|
+
Pipeline.run(source, progress=None) -> PipelineResult
|
|
230
|
+
Pipeline.stream(source, batch_size=50, progress=None) -> Iterator[PipelineResult]
|
|
231
|
+
|
|
232
|
+
# Extensibility
|
|
233
|
+
register_scorer(name, weight=0.1)(fn)
|
|
234
|
+
register_cleaner(pattern, replacement="")
|
|
235
|
+
register_score_rule(pattern, weight, warning=None)
|
|
236
|
+
clear_scorers(); clear_cleaners(); clear_score_rules()
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
### CLI
|
|
240
|
+
|
|
241
|
+
```text
|
|
242
|
+
preembed check SOURCE [--chunk-size N] [--overlap N] [--no-clean] [--no-dedupe]
|
|
243
|
+
[--min-score F] [--max-low-quality-ratio F] [--max-duplicate-ratio F]
|
|
244
|
+
[--report PATH] [--format text|json] [--tokenizer tiktoken:ENCODING]
|
|
245
|
+
preembed export SOURCE -o OUT.jsonl [--chunk-size N] [--overlap N] [--no-clean]
|
|
246
|
+
[--no-dedupe] [--min-score F] [--tokenizer tiktoken:ENCODING]
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Chunk offsets (`start_offset`/`end_offset`) index into `clean_text(document, preserve_structure=True)`, or the raw document when `clean=False`.
|
|
250
|
+
|
|
251
|
+
## Benchmarks
|
|
252
|
+
|
|
253
|
+
A reproducible benchmark against BeautifulSoup, LangChain, semchunk, chonkie, and datasketch, with speed and quality (duplicate removal, boilerplate leakage) results, lives in [benchmarks/](benchmarks/README.md). In short: cleaning and word chunking are the fastest tested; exact near-duplicate removal is far more thorough than exact-match baselines and ~13x faster than datasketch MinHash; end-to-end runs take ~1.3x a minimal bs4 + LangChain recipe while also deduplicating near copies and scoring every chunk.
|
|
254
|
+
|
|
255
|
+
```bash
|
|
256
|
+
pip install -e ".[bench]"
|
|
257
|
+
python benchmarks/run_benchmarks.py --docs 2000 # or --source path/to/your/docs
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
## Development
|
|
261
|
+
|
|
262
|
+
```bash
|
|
263
|
+
python -m venv .venv && source .venv/bin/activate
|
|
264
|
+
pip install -e ".[dev,lint]"
|
|
265
|
+
pytest
|
|
266
|
+
cargo test --manifest-path rust/Cargo.toml
|
|
267
|
+
ruff check python tests examples benchmarks tools && mypy python
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
Maintainer automation (orchestrator, research, code, and review agents driving an external coding-agent CLI in isolated worktrees) lives in [tools/agents/](tools/agents/README.md).
|
|
271
|
+
|
|
272
|
+
## License
|
|
273
|
+
|
|
274
|
+
[MIT](LICENSE)
|
|
275
|
+
|
preembed-0.2.0/README.md
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
# preembed
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<picture>
|
|
5
|
+
<img src="https://raw.githubusercontent.com/AdityaMunot/preembed/main/assets/logo.png" alt="preembed" width="400">
|
|
6
|
+
</picture>
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
> Clean, chunk, deduplicate, and score documents before embedding.
|
|
10
|
+
|
|
11
|
+
**preembed** is a Rust-powered toolkit that sits between your raw documents and your vector database. It turns messy HTML, markdown, logs, and exports into high-quality, LLM-ready chunks — so your RAG pipeline retrieves better context and hallucinates less.
|
|
12
|
+
|
|
13
|
+
[](LICENSE)
|
|
14
|
+
[](https://www.python.org)
|
|
15
|
+
[](https://www.rust-lang.org)
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
|
|
19
|
+
Most RAG pipelines embed documents directly — noise, duplicates, and all. The result: wasted tokens, bloated vector stores, and retrieval that returns boilerplate instead of answers.
|
|
20
|
+
|
|
21
|
+
preembed fixes the data before it enters the pipeline:
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
raw documents → clean → chunk → dedupe → score → embed
|
|
25
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
26
|
+
preembed handles this
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install preembed
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
For development (requires Rust toolchain):
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install -e ".[dev]"
|
|
39
|
+
maturin develop --release
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Validate your corpus in 60 seconds
|
|
43
|
+
|
|
44
|
+
No code required. Point the CLI at a folder of `.md`, `.txt`, `.html`, `.log`, `.json`, or `.csv` files:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install preembed
|
|
48
|
+
preembed check path/to/docs --report report.html
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
documents: 6
|
|
53
|
+
chunks: 6
|
|
54
|
+
avg chunk size: 103.2 words
|
|
55
|
+
duplicate ratio: 25.00%
|
|
56
|
+
low quality: 0 (0.00%, score < 0.5)
|
|
57
|
+
top warnings: low_information_density=2
|
|
58
|
+
|
|
59
|
+
worst chunks:
|
|
60
|
+
0.63 logs/worker.log#0 [low_information_density]
|
|
61
|
+
2026-11-25T10:00:00Z worker-1 status ok heartbeat ok 2026-11-25T10:01:00Z wor...
|
|
62
|
+
...
|
|
63
|
+
|
|
64
|
+
PASS
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`preembed check` exits `0` when thresholds pass, `1` when they fail, and `2` on bad input, so it works as a CI gate:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
preembed check docs/ --min-score 0.5 --max-low-quality-ratio 0.2 --max-duplicate-ratio 0.1
|
|
71
|
+
preembed check docs/ --format json # machine-readable summary
|
|
72
|
+
preembed export docs/ -o chunks.jsonl --min-score 0.5 # streamed, one chunk per line
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Try it on the bundled messy corpus in [`examples/`](examples/) (duplicates, HTML boilerplate, noisy logs).
|
|
76
|
+
|
|
77
|
+
## Quickstart
|
|
78
|
+
|
|
79
|
+
### Pipeline (recommended)
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from preembed import Pipeline
|
|
83
|
+
|
|
84
|
+
result = Pipeline(chunk_size=512, overlap=64).run("path/to/documents/")
|
|
85
|
+
result.save_report("report.json")
|
|
86
|
+
|
|
87
|
+
print(f"{result.stats.total_chunks} chunks, {result.stats.duplicate_ratio:.0%} duplicates removed")
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Individual primitives
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from preembed import clean_text, chunk_text, dedupe_chunks, score_chunks
|
|
94
|
+
|
|
95
|
+
text = clean_text("<html><script>tracking()</script><p>Actual content here.</p></html>")
|
|
96
|
+
# → "Actual content here."
|
|
97
|
+
|
|
98
|
+
chunks = chunk_text(text, chunk_size=512, overlap=64)
|
|
99
|
+
chunks = dedupe_chunks(chunks)
|
|
100
|
+
scored = score_chunks(chunks)
|
|
101
|
+
# Each chunk gets a 0-1 quality score + warning labels
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Streaming (memory-efficient)
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
for batch in Pipeline().stream("huge_corpus/", batch_size=50):
|
|
108
|
+
upload_to_vector_db(batch.scored_chunks)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Documents are read and processed one batch at a time. Exact and normalized duplicates are removed across batches (near-duplicates within a batch); the cross-batch filter keeps a 16-byte hash per unique chunk, so memory grows with unique chunks, not with document size. A batch whose chunks were all duplicates is still yielded with no chunks, `duplicate_ratio == 1.0`, and the warning `all_chunks_duplicate`.
|
|
112
|
+
|
|
113
|
+
### Custom scoring
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from preembed import register_scorer
|
|
117
|
+
|
|
118
|
+
@register_scorer("domain_relevance", weight=0.15)
|
|
119
|
+
def domain_scorer(chunk: str) -> float:
|
|
120
|
+
return 1.0 if "patient" in chunk.lower() else 0.3
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Blends with the built-in scoring engine. Errors default to neutral (0.5) — won't crash your pipeline.
|
|
124
|
+
|
|
125
|
+
### Regex rules (compiled once, run in Rust)
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
from preembed import register_cleaner, register_score_rule
|
|
129
|
+
|
|
130
|
+
register_cleaner(r"Page \d+ of \d+") # remove page footers
|
|
131
|
+
register_cleaner(r"(\w+)@example\.com", "$1@redacted") # Rust regex replacement syntax
|
|
132
|
+
register_score_rule(r"(?i)impressum|datenschutz", -0.3, warning="boilerplate")
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Cleaners run inside `clean_text` (and therefore `Pipeline`). Score rules add their weight to matching chunks and can label them, which is how to cover boilerplate the built-in English heuristics miss.
|
|
136
|
+
|
|
137
|
+
### Real token budgets
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
import tiktoken
|
|
141
|
+
from preembed import Pipeline
|
|
142
|
+
|
|
143
|
+
encode = tiktoken.get_encoding("cl100k_base").encode_ordinary # special-token text stays plain text
|
|
144
|
+
result = Pipeline(chunk_size=512, overlap=64, tokenizer=encode).run("docs/")
|
|
145
|
+
# chunk_size/overlap are now tokens, and Chunk.tokens is the real token count
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Without a tokenizer, sizes and `Chunk.tokens` are whitespace word counts.
|
|
149
|
+
|
|
150
|
+
### LangChain and LlamaIndex
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
from preembed.integrations.langchain import PreembedTextSplitter, PreembedDocumentTransformer
|
|
154
|
+
from preembed.integrations.llamaindex import PreembedNodeParser, PreembedFilter
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Drop-in splitters plus a dedupe/score filter for both frameworks (`pip install "preembed[langchain]"` or `"preembed[llamaindex]"`). See [docs/integrations.md](docs/integrations.md).
|
|
158
|
+
|
|
159
|
+
## How it works
|
|
160
|
+
|
|
161
|
+
| Stage | What it does |
|
|
162
|
+
|---|---|
|
|
163
|
+
| **Clean** | Strip HTML tags plus `script`, `style`, `nav`, `footer`, `noscript`, `template`, and `svg` blocks. Normalize whitespace and unicode. In the pipeline, paragraph and block boundaries are kept for chunking. |
|
|
164
|
+
| **Chunk** | Structure-aware splitting on headings, code fences, and paragraphs. Never exceeds `chunk_size` words (or tokens with a tokenizer). Each chunk is an exact slice of the cleaned text, so line breaks and code indentation are kept. Configurable overlap. |
|
|
165
|
+
| **Dedupe** | Exact, normalized, and near-duplicate removal via fingerprint similarity. |
|
|
166
|
+
| **Score** | Quality score (0–1) based on length, density, structure, duplicates. Warning labels for boilerplate, too-short/long, low-density. |
|
|
167
|
+
| **Report** | JSON, Markdown, or HTML diagnostics with per-chunk scores and recommendations. |
|
|
168
|
+
|
|
169
|
+
## API
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
# Core primitives
|
|
173
|
+
clean_text(text: str, *, preserve_structure=False) -> str
|
|
174
|
+
chunk_text(text: str, chunk_size=512, overlap=64, mode="word", tokenizer=None) -> list[str]
|
|
175
|
+
chunk_spans(text: str, chunk_size=512, overlap=64, mode="word", tokenizer=None) -> list[tuple[int, int]]
|
|
176
|
+
dedupe_chunks(chunks, return_stats=False, near_duplicate_threshold=0.9) -> list[str] | DedupeResult
|
|
177
|
+
score_chunks(chunks, tokenizer=None) -> list[Chunk]
|
|
178
|
+
|
|
179
|
+
# Pipeline
|
|
180
|
+
Pipeline(chunk_size=512, overlap=64, clean=True, dedupe=True, score=True, tokenizer=None)
|
|
181
|
+
Pipeline.run(source, progress=None) -> PipelineResult
|
|
182
|
+
Pipeline.stream(source, batch_size=50, progress=None) -> Iterator[PipelineResult]
|
|
183
|
+
|
|
184
|
+
# Extensibility
|
|
185
|
+
register_scorer(name, weight=0.1)(fn)
|
|
186
|
+
register_cleaner(pattern, replacement="")
|
|
187
|
+
register_score_rule(pattern, weight, warning=None)
|
|
188
|
+
clear_scorers(); clear_cleaners(); clear_score_rules()
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### CLI
|
|
192
|
+
|
|
193
|
+
```text
|
|
194
|
+
preembed check SOURCE [--chunk-size N] [--overlap N] [--no-clean] [--no-dedupe]
|
|
195
|
+
[--min-score F] [--max-low-quality-ratio F] [--max-duplicate-ratio F]
|
|
196
|
+
[--report PATH] [--format text|json] [--tokenizer tiktoken:ENCODING]
|
|
197
|
+
preembed export SOURCE -o OUT.jsonl [--chunk-size N] [--overlap N] [--no-clean]
|
|
198
|
+
[--no-dedupe] [--min-score F] [--tokenizer tiktoken:ENCODING]
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Chunk offsets (`start_offset`/`end_offset`) index into `clean_text(document, preserve_structure=True)`, or the raw document when `clean=False`.
|
|
202
|
+
|
|
203
|
+
## Benchmarks
|
|
204
|
+
|
|
205
|
+
A reproducible benchmark against BeautifulSoup, LangChain, semchunk, chonkie, and datasketch, with speed and quality (duplicate removal, boilerplate leakage) results, lives in [benchmarks/](benchmarks/README.md). In short: cleaning and word chunking are the fastest tested; exact near-duplicate removal is far more thorough than exact-match baselines and ~13x faster than datasketch MinHash; end-to-end runs take ~1.3x a minimal bs4 + LangChain recipe while also deduplicating near copies and scoring every chunk.
|
|
206
|
+
|
|
207
|
+
```bash
|
|
208
|
+
pip install -e ".[bench]"
|
|
209
|
+
python benchmarks/run_benchmarks.py --docs 2000 # or --source path/to/your/docs
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
## Development
|
|
213
|
+
|
|
214
|
+
```bash
|
|
215
|
+
python -m venv .venv && source .venv/bin/activate
|
|
216
|
+
pip install -e ".[dev,lint]"
|
|
217
|
+
pytest
|
|
218
|
+
cargo test --manifest-path rust/Cargo.toml
|
|
219
|
+
ruff check python tests examples benchmarks tools && mypy python
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Maintainer automation (orchestrator, research, code, and review agents driving an external coding-agent CLI in isolated worktrees) lives in [tools/agents/](tools/agents/README.md).
|
|
223
|
+
|
|
224
|
+
## License
|
|
225
|
+
|
|
226
|
+
[MIT](LICENSE)
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["maturin>=1.
|
|
2
|
+
requires = ["maturin>=1.9,<2"]
|
|
3
3
|
build-backend = "maturin"
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "preembed"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "High-performance document preparation toolkit for LLM and RAG pipelines."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -22,28 +22,48 @@ classifiers = [
|
|
|
22
22
|
"Programming Language :: Python :: 3.10",
|
|
23
23
|
"Programming Language :: Python :: 3.11",
|
|
24
24
|
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Programming Language :: Python :: 3.14",
|
|
25
27
|
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
26
28
|
"Topic :: Text Processing",
|
|
27
29
|
]
|
|
28
30
|
|
|
31
|
+
[project.scripts]
|
|
32
|
+
preembed = "preembed.cli:main"
|
|
33
|
+
|
|
29
34
|
[project.urls]
|
|
30
35
|
Homepage = "https://github.com/AdityaMunot/preembed"
|
|
31
36
|
Repository = "https://github.com/AdityaMunot/preembed"
|
|
32
|
-
Documentation = "https://github.com/AdityaMunot/preembed
|
|
37
|
+
Documentation = "https://github.com/AdityaMunot/preembed#readme"
|
|
33
38
|
Issues = "https://github.com/AdityaMunot/preembed/issues"
|
|
34
39
|
Changelog = "https://github.com/AdityaMunot/preembed/blob/main/CHANGELOG.md"
|
|
35
40
|
|
|
36
41
|
[project.optional-dependencies]
|
|
37
42
|
dev = [
|
|
38
43
|
"hypothesis>=6",
|
|
39
|
-
"maturin>=1.
|
|
44
|
+
"maturin>=1.9,<2",
|
|
40
45
|
"pytest>=8",
|
|
41
46
|
"pytest-cov>=5",
|
|
42
47
|
]
|
|
48
|
+
bench = [
|
|
49
|
+
"beautifulsoup4",
|
|
50
|
+
"langchain-text-splitters",
|
|
51
|
+
"semchunk",
|
|
52
|
+
"chonkie",
|
|
53
|
+
"tiktoken",
|
|
54
|
+
"datasketch",
|
|
55
|
+
]
|
|
43
56
|
lint = [
|
|
44
|
-
"ruff
|
|
57
|
+
"ruff==0.15.12",
|
|
45
58
|
"mypy>=1.9",
|
|
46
59
|
]
|
|
60
|
+
langchain = [
|
|
61
|
+
"langchain-text-splitters>=0.3",
|
|
62
|
+
"langchain-core>=0.3",
|
|
63
|
+
]
|
|
64
|
+
llamaindex = [
|
|
65
|
+
"llama-index-core>=0.12",
|
|
66
|
+
]
|
|
47
67
|
|
|
48
68
|
[tool.setuptools.package-data]
|
|
49
69
|
preembed = ["py.typed"]
|
|
@@ -54,6 +74,11 @@ python-source = "python"
|
|
|
54
74
|
module-name = "preembed.preembed_core"
|
|
55
75
|
features = ["pyo3/extension-module"]
|
|
56
76
|
|
|
77
|
+
# The lint job installs only ruff and mypy; the optional frameworks may be absent.
|
|
78
|
+
[[tool.mypy.overrides]]
|
|
79
|
+
module = ["langchain_core.*", "langchain_text_splitters.*", "llama_index.*", "tiktoken.*"]
|
|
80
|
+
ignore_missing_imports = true
|
|
81
|
+
|
|
57
82
|
[tool.pytest.ini_options]
|
|
58
83
|
testpaths = ["tests"]
|
|
59
84
|
pythonpath = ["python"]
|
|
@@ -10,10 +10,15 @@ __all__ = [
|
|
|
10
10
|
"PreembedError",
|
|
11
11
|
"Scorer",
|
|
12
12
|
"Tokenizer",
|
|
13
|
-
"
|
|
13
|
+
"chunk_spans",
|
|
14
14
|
"chunk_text",
|
|
15
|
+
"clean_text",
|
|
16
|
+
"clear_cleaners",
|
|
17
|
+
"clear_score_rules",
|
|
15
18
|
"clear_scorers",
|
|
16
19
|
"dedupe_chunks",
|
|
20
|
+
"register_cleaner",
|
|
21
|
+
"register_score_rule",
|
|
17
22
|
"register_scorer",
|
|
18
23
|
"score_chunks",
|
|
19
24
|
]
|
|
@@ -21,10 +26,15 @@ __all__ = [
|
|
|
21
26
|
from .pipeline import Pipeline
|
|
22
27
|
from .text import (
|
|
23
28
|
PreembedError,
|
|
29
|
+
chunk_spans,
|
|
24
30
|
chunk_text,
|
|
25
31
|
clean_text,
|
|
32
|
+
clear_cleaners,
|
|
33
|
+
clear_score_rules,
|
|
26
34
|
clear_scorers,
|
|
27
35
|
dedupe_chunks,
|
|
36
|
+
register_cleaner,
|
|
37
|
+
register_score_rule,
|
|
28
38
|
register_scorer,
|
|
29
39
|
score_chunks,
|
|
30
40
|
)
|