fast-text-splitter 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.
- fast_text_splitter-0.1.0/.github/workflows/ci.yml +21 -0
- fast_text_splitter-0.1.0/.github/workflows/release.yml +52 -0
- fast_text_splitter-0.1.0/.gitignore +12 -0
- fast_text_splitter-0.1.0/CHANGELOG.md +11 -0
- fast_text_splitter-0.1.0/CMakeLists.txt +17 -0
- fast_text_splitter-0.1.0/LICENSE +21 -0
- fast_text_splitter-0.1.0/PKG-INFO +123 -0
- fast_text_splitter-0.1.0/README.md +100 -0
- fast_text_splitter-0.1.0/RELEASING.md +16 -0
- fast_text_splitter-0.1.0/bench/bench.py +151 -0
- fast_text_splitter-0.1.0/cpp/bindings.cpp +204 -0
- fast_text_splitter-0.1.0/cpp/splitter.cpp +341 -0
- fast_text_splitter-0.1.0/cpp/splitter.hpp +151 -0
- fast_text_splitter-0.1.0/docs/DESIGN.md +90 -0
- fast_text_splitter-0.1.0/pyproject.toml +42 -0
- fast_text_splitter-0.1.0/src/fast_text_splitter/__init__.py +11 -0
- fast_text_splitter-0.1.0/src/fast_text_splitter/langchain.py +209 -0
- fast_text_splitter-0.1.0/src/fast_text_splitter/py.typed +0 -0
- fast_text_splitter-0.1.0/tests/test_langchain_dropin.py +214 -0
- fast_text_splitter-0.1.0/tests/test_parity.py +82 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
name: tests
|
|
2
|
+
on:
|
|
3
|
+
push:
|
|
4
|
+
branches: [main]
|
|
5
|
+
pull_request:
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
test:
|
|
9
|
+
strategy:
|
|
10
|
+
fail-fast: false
|
|
11
|
+
matrix:
|
|
12
|
+
os: [ubuntu-latest, macos-latest, windows-latest]
|
|
13
|
+
python: ["3.10", "3.15"]
|
|
14
|
+
runs-on: ${{ matrix.os }}
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v7
|
|
17
|
+
- uses: actions/setup-python@v7
|
|
18
|
+
with:
|
|
19
|
+
python-version: ${{ matrix.python }}
|
|
20
|
+
- run: pip install ".[test]"
|
|
21
|
+
- run: pytest -q
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Builds wheels for every OS / Python and publishes to PyPI when you publish a
|
|
2
|
+
# GitHub Release. Uses PyPI "trusted publishing", so no API token is stored in
|
|
3
|
+
# the repo. One-time setup on pypi.org is described in RELEASING.md.
|
|
4
|
+
name: release
|
|
5
|
+
on:
|
|
6
|
+
release:
|
|
7
|
+
types: [published]
|
|
8
|
+
workflow_dispatch:
|
|
9
|
+
|
|
10
|
+
jobs:
|
|
11
|
+
wheels:
|
|
12
|
+
name: wheels (${{ matrix.os }})
|
|
13
|
+
runs-on: ${{ matrix.os }}
|
|
14
|
+
strategy:
|
|
15
|
+
fail-fast: false
|
|
16
|
+
matrix:
|
|
17
|
+
os: [ubuntu-latest, ubuntu-24.04-arm, macos-latest, windows-latest]
|
|
18
|
+
steps:
|
|
19
|
+
- uses: actions/checkout@v7
|
|
20
|
+
- uses: pypa/cibuildwheel@v4.3.5
|
|
21
|
+
env:
|
|
22
|
+
# macos-latest is Apple Silicon; build Intel wheels there too.
|
|
23
|
+
CIBW_ARCHS_MACOS: "x86_64 arm64"
|
|
24
|
+
CIBW_ENVIRONMENT: HYPOTHESIS_PROFILE=ci
|
|
25
|
+
- uses: actions/upload-artifact@v7
|
|
26
|
+
with:
|
|
27
|
+
name: wheels-${{ matrix.os }}
|
|
28
|
+
path: wheelhouse/*.whl
|
|
29
|
+
|
|
30
|
+
sdist:
|
|
31
|
+
runs-on: ubuntu-latest
|
|
32
|
+
steps:
|
|
33
|
+
- uses: actions/checkout@v7
|
|
34
|
+
- run: pipx run build --sdist
|
|
35
|
+
- uses: actions/upload-artifact@v7
|
|
36
|
+
with:
|
|
37
|
+
name: sdist
|
|
38
|
+
path: dist/*.tar.gz
|
|
39
|
+
|
|
40
|
+
publish:
|
|
41
|
+
needs: [wheels, sdist]
|
|
42
|
+
runs-on: ubuntu-latest
|
|
43
|
+
if: github.event_name == 'release'
|
|
44
|
+
environment: pypi
|
|
45
|
+
permissions:
|
|
46
|
+
id-token: write # required for trusted publishing
|
|
47
|
+
steps:
|
|
48
|
+
- uses: actions/download-artifact@v8
|
|
49
|
+
with:
|
|
50
|
+
path: dist
|
|
51
|
+
merge-multiple: true
|
|
52
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
- `RecursiveSplitter`: the C++ core, with no dependencies. Zero-copy reads of Python strings, and `split_texts` splits a batch in parallel across cores.
|
|
8
|
+
- `fast_text_splitter.langchain.RecursiveCharacterTextSplitter`: drop-in replacement for LangChain's class, with identical output (checked against LangChain with Hypothesis).
|
|
9
|
+
- `from_language(...)` uses the C++ path for all 27 of LangChain's languages. Plain-text separators are matched directly; regex separators (escapes, character classes, `\s`, greedy/lazy repeats of one character, non-capturing alternation, lookaheads, `$`) are translated by Python's regex parser into a small program that a backtracking matcher in C++ runs with `re`'s priorities. Anything outside that subset, and custom `length_function`s, fall back to LangChain.
|
|
10
|
+
- `bench/bench.py`, including `--language python|markdown|rst|vb6|latex` for code splitting.
|
|
11
|
+
- Wheels for Linux (x86_64, aarch64), macOS (Intel, Apple Silicon) and Windows, CPython 3.9 to 3.15.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
cmake_minimum_required(VERSION 3.15)
|
|
2
|
+
project(fast_text_splitter LANGUAGES CXX)
|
|
3
|
+
|
|
4
|
+
set(CMAKE_CXX_STANDARD 17)
|
|
5
|
+
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
|
6
|
+
if(NOT CMAKE_BUILD_TYPE)
|
|
7
|
+
set(CMAKE_BUILD_TYPE Release)
|
|
8
|
+
endif()
|
|
9
|
+
|
|
10
|
+
find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
|
|
11
|
+
find_package(pybind11 CONFIG REQUIRED)
|
|
12
|
+
find_package(Threads REQUIRED)
|
|
13
|
+
|
|
14
|
+
pybind11_add_module(_core cpp/bindings.cpp cpp/splitter.cpp)
|
|
15
|
+
target_include_directories(_core PRIVATE cpp)
|
|
16
|
+
target_link_libraries(_core PRIVATE Threads::Threads)
|
|
17
|
+
install(TARGETS _core DESTINATION fast_text_splitter)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 aarav-agarwal331
|
|
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.
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fast-text-splitter
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Drop-in C++ replacement for LangChain's RecursiveCharacterTextSplitter. Same chunks, much faster.
|
|
5
|
+
Keywords: text-splitter,chunking,rag,langchain,llm,embeddings,cpp,pybind11
|
|
6
|
+
Author: aarav-agarwal331
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: C++
|
|
10
|
+
Classifier: Topic :: Text Processing
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Project-URL: Homepage, https://github.com/aarav-agarwal331/fast-text-splitter
|
|
14
|
+
Project-URL: Issues, https://github.com/aarav-agarwal331/fast-text-splitter/issues
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Provides-Extra: langchain
|
|
17
|
+
Requires-Dist: langchain-text-splitters>=0.3; extra == "langchain"
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
20
|
+
Requires-Dist: hypothesis>=6; extra == "test"
|
|
21
|
+
Requires-Dist: langchain-text-splitters>=0.3; extra == "test"
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# fast-text-splitter
|
|
25
|
+
|
|
26
|
+
LangChain's `RecursiveCharacterTextSplitter`, rewritten in C++. Same chunks, 4 to 12x faster on one core, and up to ~50x when you split a batch of documents across cores.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install fast-text-splitter
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
# before
|
|
34
|
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
35
|
+
# after
|
|
36
|
+
from fast_text_splitter.langchain import RecursiveCharacterTextSplitter
|
|
37
|
+
|
|
38
|
+
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
|
39
|
+
docs = splitter.split_documents(docs) # everything else works the same
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
That's the whole migration. `split_documents`, `create_documents`, `add_start_index` and metadata all behave exactly like LangChain, because the class subclasses LangChain's and only swaps out the inner loop.
|
|
43
|
+
|
|
44
|
+
No LangChain? Use the core directly. It has no dependencies:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from fast_text_splitter import RecursiveSplitter
|
|
48
|
+
|
|
49
|
+
s = RecursiveSplitter(chunk_size=1000, chunk_overlap=200)
|
|
50
|
+
chunks = s.split_text(text)
|
|
51
|
+
batches = s.split_texts(list_of_texts) # parallel, uses every core
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Benchmarks
|
|
55
|
+
|
|
56
|
+
200 MB of generated paragraphs (mixed English, accented Latin and CJK), best of 3 runs. Every run also checks that the output is identical to LangChain's.
|
|
57
|
+
|
|
58
|
+
**Apple M5 Max, 18 cores, Python 3.15**
|
|
59
|
+
|
|
60
|
+
| chunk_size / overlap | langchain-text-splitters | fast-text-splitter, 1 thread | fast-text-splitter `split_texts`, 18 threads |
|
|
61
|
+
|---|---:|---:|---:|
|
|
62
|
+
| 200 / 20 | 6.80 s | 0.55 s (12.3x) | 0.14 s (49.9x) |
|
|
63
|
+
| 1000 / 200 | 1.19 s | 0.14 s (8.8x) | 0.04 s (28.8x) |
|
|
64
|
+
| 4000 / 200 | 0.22 s | 0.06 s (3.9x) | 0.02 s (9.6x) |
|
|
65
|
+
|
|
66
|
+
**4-core Intel Xeon @ 2.1 GHz (cloud VM), Python 3.13, 20 MB**
|
|
67
|
+
|
|
68
|
+
| chunk_size / overlap | langchain-text-splitters | fast-text-splitter, 1 thread | fast-text-splitter `split_texts`, 4 threads |
|
|
69
|
+
|---|---:|---:|---:|
|
|
70
|
+
| 200 / 20 | 1.71 s | 0.13 s (12.9x) | 0.06 s (29.5x) |
|
|
71
|
+
| 1000 / 200 | 0.33 s | 0.03 s (9.8x) | 0.02 s (17.1x) |
|
|
72
|
+
|
|
73
|
+
The win is biggest at small chunk sizes, which is where LangChain does the most work. Run it yourself with `python bench/bench.py --mb 200 --chunk-size 200 --overlap 20`.
|
|
74
|
+
|
|
75
|
+
## Is it really identical?
|
|
76
|
+
|
|
77
|
+
That's the point of the project, so it's tested hard. `tests/test_parity.py` uses [Hypothesis](https://hypothesis.readthedocs.io) to throw thousands of random texts at both splitters (runs of newlines, tabs, `\r\n`, non-breaking spaces, CJK, emoji) with random chunk sizes, overlaps, separator lists and `keep_separator` modes, and requires the output to match exactly.
|
|
78
|
+
|
|
79
|
+
## What's supported
|
|
80
|
+
|
|
81
|
+
| option | fast-text-splitter |
|
|
82
|
+
|---|---|
|
|
83
|
+
| `chunk_size`, `chunk_overlap` | yes |
|
|
84
|
+
| `separators` (plain strings) | yes |
|
|
85
|
+
| `keep_separator` (`True`, `False`, `"start"`, `"end"`) | yes |
|
|
86
|
+
| `strip_whitespace` | yes |
|
|
87
|
+
| `from_language(...)`, all 27 of LangChain's languages | yes (see below) |
|
|
88
|
+
| `is_separator_regex=True` with escapes, `.`, `[...]`, `\s`, repeats of one character (`+`, `*?`, `{1,6}`), `(?:a\|b)`, lookaheads, `$` | yes |
|
|
89
|
+
| `is_separator_regex=True` with anything else (`\w`, `\b`, `^`, lookbehinds, capturing or repeated groups, flags) | falls back to LangChain automatically |
|
|
90
|
+
| custom `length_function` (e.g. token counting) | falls back to LangChain automatically |
|
|
91
|
+
|
|
92
|
+
The fallback means the drop-in class is never wrong, just not faster in those two cases.
|
|
93
|
+
|
|
94
|
+
### Splitting code
|
|
95
|
+
|
|
96
|
+
`from_language` works on the drop-in class too, for all 27 languages. LangChain marks every language's separators as regexes, but most of them (`"\nclass "`, `"\ndef "`, `"\nfunction "`, ...) contain no regex syntax and are matched as plain text. The rest use a small part of the regex language: escapes (R's `"\nlibrary\("`), character classes and `.` (COBOL, Haskell), repeats of one character (Markdown's `"\n#{1,6} "`, RST's `"\n=+\n"`), `\s`, non-capturing alternation and lookaheads (VB6's `"\n(?!End\s)(?:Public|Private|...)\s+?Sub\s+"`) and the `$` anchor (LaTeX). Python's own regex parser translates those into a tiny program, and a backtracking matcher in C++ runs it with the same priorities as `re` (greedy vs. lazy, alternation order), so it finds exactly the same matches. Any separator outside that subset makes the splitter fall back to LangChain. With `keep_separator=False` LangChain re-joins pieces with the raw pattern text (e.g. a literal `$$` between pieces); the C++ path reproduces that too.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from langchain_text_splitters import Language
|
|
100
|
+
from fast_text_splitter.langchain import RecursiveCharacterTextSplitter
|
|
101
|
+
|
|
102
|
+
splitter = RecursiveCharacterTextSplitter.from_language(Language.PYTHON, chunk_size=1000, chunk_overlap=200)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
On the Python standard library's own source (50 MB, Apple M5 Max) it's 3.0x faster on one thread at 1000/200 and 4.3x at 200/20, and 17 to 20x with `split_texts`. Code files are small, so per-call overhead matters more than on long prose. `python bench/bench.py --language python` reproduces it, and `tests/test_langchain_dropin.py` checks parity with Hypothesis for every fast-path language. Synthetic documents (`--language markdown|rst|vb6|latex --mb 5`, one thread, 1000/200 and 200/20): Markdown 4.2x and 7.9x, RST 4.0x and 7.9x, LaTeX 10.8x and 10.4x, VB6 1.2x and 2.5x (VB6's 14 regex separators are mostly lookahead patterns tried at every newline; still 8 to 17x with `split_texts`). All four used to fall back to LangChain.
|
|
106
|
+
|
|
107
|
+
## How it works
|
|
108
|
+
|
|
109
|
+
Short version: it reads Python's internal string buffer directly instead of copying it, and it tracks chunks as index ranges instead of building substrings. The long version, with the bugs along the way, is in [docs/DESIGN.md](docs/DESIGN.md).
|
|
110
|
+
|
|
111
|
+
## Development
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
pip install -e ".[test]"
|
|
115
|
+
pytest
|
|
116
|
+
python bench/bench.py
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Wheels for Linux, macOS (Intel and Apple Silicon) and Windows, Python 3.9 to 3.15, are built by GitHub Actions on every release.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# fast-text-splitter
|
|
2
|
+
|
|
3
|
+
LangChain's `RecursiveCharacterTextSplitter`, rewritten in C++. Same chunks, 4 to 12x faster on one core, and up to ~50x when you split a batch of documents across cores.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install fast-text-splitter
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
# before
|
|
11
|
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
12
|
+
# after
|
|
13
|
+
from fast_text_splitter.langchain import RecursiveCharacterTextSplitter
|
|
14
|
+
|
|
15
|
+
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
|
16
|
+
docs = splitter.split_documents(docs) # everything else works the same
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
That's the whole migration. `split_documents`, `create_documents`, `add_start_index` and metadata all behave exactly like LangChain, because the class subclasses LangChain's and only swaps out the inner loop.
|
|
20
|
+
|
|
21
|
+
No LangChain? Use the core directly. It has no dependencies:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from fast_text_splitter import RecursiveSplitter
|
|
25
|
+
|
|
26
|
+
s = RecursiveSplitter(chunk_size=1000, chunk_overlap=200)
|
|
27
|
+
chunks = s.split_text(text)
|
|
28
|
+
batches = s.split_texts(list_of_texts) # parallel, uses every core
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Benchmarks
|
|
32
|
+
|
|
33
|
+
200 MB of generated paragraphs (mixed English, accented Latin and CJK), best of 3 runs. Every run also checks that the output is identical to LangChain's.
|
|
34
|
+
|
|
35
|
+
**Apple M5 Max, 18 cores, Python 3.15**
|
|
36
|
+
|
|
37
|
+
| chunk_size / overlap | langchain-text-splitters | fast-text-splitter, 1 thread | fast-text-splitter `split_texts`, 18 threads |
|
|
38
|
+
|---|---:|---:|---:|
|
|
39
|
+
| 200 / 20 | 6.80 s | 0.55 s (12.3x) | 0.14 s (49.9x) |
|
|
40
|
+
| 1000 / 200 | 1.19 s | 0.14 s (8.8x) | 0.04 s (28.8x) |
|
|
41
|
+
| 4000 / 200 | 0.22 s | 0.06 s (3.9x) | 0.02 s (9.6x) |
|
|
42
|
+
|
|
43
|
+
**4-core Intel Xeon @ 2.1 GHz (cloud VM), Python 3.13, 20 MB**
|
|
44
|
+
|
|
45
|
+
| chunk_size / overlap | langchain-text-splitters | fast-text-splitter, 1 thread | fast-text-splitter `split_texts`, 4 threads |
|
|
46
|
+
|---|---:|---:|---:|
|
|
47
|
+
| 200 / 20 | 1.71 s | 0.13 s (12.9x) | 0.06 s (29.5x) |
|
|
48
|
+
| 1000 / 200 | 0.33 s | 0.03 s (9.8x) | 0.02 s (17.1x) |
|
|
49
|
+
|
|
50
|
+
The win is biggest at small chunk sizes, which is where LangChain does the most work. Run it yourself with `python bench/bench.py --mb 200 --chunk-size 200 --overlap 20`.
|
|
51
|
+
|
|
52
|
+
## Is it really identical?
|
|
53
|
+
|
|
54
|
+
That's the point of the project, so it's tested hard. `tests/test_parity.py` uses [Hypothesis](https://hypothesis.readthedocs.io) to throw thousands of random texts at both splitters (runs of newlines, tabs, `\r\n`, non-breaking spaces, CJK, emoji) with random chunk sizes, overlaps, separator lists and `keep_separator` modes, and requires the output to match exactly.
|
|
55
|
+
|
|
56
|
+
## What's supported
|
|
57
|
+
|
|
58
|
+
| option | fast-text-splitter |
|
|
59
|
+
|---|---|
|
|
60
|
+
| `chunk_size`, `chunk_overlap` | yes |
|
|
61
|
+
| `separators` (plain strings) | yes |
|
|
62
|
+
| `keep_separator` (`True`, `False`, `"start"`, `"end"`) | yes |
|
|
63
|
+
| `strip_whitespace` | yes |
|
|
64
|
+
| `from_language(...)`, all 27 of LangChain's languages | yes (see below) |
|
|
65
|
+
| `is_separator_regex=True` with escapes, `.`, `[...]`, `\s`, repeats of one character (`+`, `*?`, `{1,6}`), `(?:a\|b)`, lookaheads, `$` | yes |
|
|
66
|
+
| `is_separator_regex=True` with anything else (`\w`, `\b`, `^`, lookbehinds, capturing or repeated groups, flags) | falls back to LangChain automatically |
|
|
67
|
+
| custom `length_function` (e.g. token counting) | falls back to LangChain automatically |
|
|
68
|
+
|
|
69
|
+
The fallback means the drop-in class is never wrong, just not faster in those two cases.
|
|
70
|
+
|
|
71
|
+
### Splitting code
|
|
72
|
+
|
|
73
|
+
`from_language` works on the drop-in class too, for all 27 languages. LangChain marks every language's separators as regexes, but most of them (`"\nclass "`, `"\ndef "`, `"\nfunction "`, ...) contain no regex syntax and are matched as plain text. The rest use a small part of the regex language: escapes (R's `"\nlibrary\("`), character classes and `.` (COBOL, Haskell), repeats of one character (Markdown's `"\n#{1,6} "`, RST's `"\n=+\n"`), `\s`, non-capturing alternation and lookaheads (VB6's `"\n(?!End\s)(?:Public|Private|...)\s+?Sub\s+"`) and the `$` anchor (LaTeX). Python's own regex parser translates those into a tiny program, and a backtracking matcher in C++ runs it with the same priorities as `re` (greedy vs. lazy, alternation order), so it finds exactly the same matches. Any separator outside that subset makes the splitter fall back to LangChain. With `keep_separator=False` LangChain re-joins pieces with the raw pattern text (e.g. a literal `$$` between pieces); the C++ path reproduces that too.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from langchain_text_splitters import Language
|
|
77
|
+
from fast_text_splitter.langchain import RecursiveCharacterTextSplitter
|
|
78
|
+
|
|
79
|
+
splitter = RecursiveCharacterTextSplitter.from_language(Language.PYTHON, chunk_size=1000, chunk_overlap=200)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
On the Python standard library's own source (50 MB, Apple M5 Max) it's 3.0x faster on one thread at 1000/200 and 4.3x at 200/20, and 17 to 20x with `split_texts`. Code files are small, so per-call overhead matters more than on long prose. `python bench/bench.py --language python` reproduces it, and `tests/test_langchain_dropin.py` checks parity with Hypothesis for every fast-path language. Synthetic documents (`--language markdown|rst|vb6|latex --mb 5`, one thread, 1000/200 and 200/20): Markdown 4.2x and 7.9x, RST 4.0x and 7.9x, LaTeX 10.8x and 10.4x, VB6 1.2x and 2.5x (VB6's 14 regex separators are mostly lookahead patterns tried at every newline; still 8 to 17x with `split_texts`). All four used to fall back to LangChain.
|
|
83
|
+
|
|
84
|
+
## How it works
|
|
85
|
+
|
|
86
|
+
Short version: it reads Python's internal string buffer directly instead of copying it, and it tracks chunks as index ranges instead of building substrings. The long version, with the bugs along the way, is in [docs/DESIGN.md](docs/DESIGN.md).
|
|
87
|
+
|
|
88
|
+
## Development
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
pip install -e ".[test]"
|
|
92
|
+
pytest
|
|
93
|
+
python bench/bench.py
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Wheels for Linux, macOS (Intel and Apple Silicon) and Windows, Python 3.9 to 3.15, are built by GitHub Actions on every release.
|
|
97
|
+
|
|
98
|
+
## License
|
|
99
|
+
|
|
100
|
+
MIT
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Releasing
|
|
2
|
+
|
|
3
|
+
One-time setup (5 minutes):
|
|
4
|
+
|
|
5
|
+
1. Make an account on https://pypi.org and turn on 2FA.
|
|
6
|
+
2. Go to https://pypi.org/manage/account/publishing/ and add a "pending publisher":
|
|
7
|
+
- PyPI project name: `fast-text-splitter`
|
|
8
|
+
- Owner: your GitHub username, Repository: `fast-text-splitter`
|
|
9
|
+
- Workflow: `release.yml`, Environment: `pypi`
|
|
10
|
+
3. On GitHub: repo Settings > Environments > New environment > `pypi`.
|
|
11
|
+
|
|
12
|
+
Every release after that:
|
|
13
|
+
|
|
14
|
+
1. Bump `version` in `pyproject.toml` and `src/fast_text_splitter/__init__.py`, add a line to CHANGELOG.md.
|
|
15
|
+
2. Commit, then on GitHub: Releases > Draft a new release > tag `v0.1.0` > Publish.
|
|
16
|
+
3. The `release` workflow builds ~40 wheels, tests each one, and uploads them to PyPI.
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Benchmark fast-text-splitter against LangChain on the same text and settings.
|
|
2
|
+
|
|
3
|
+
python bench/bench.py # prints a markdown table
|
|
4
|
+
python bench/bench.py --mb 50 # bigger corpus
|
|
5
|
+
python bench/bench.py --language python # code splitting via from_language
|
|
6
|
+
python bench/bench.py --language markdown # also rst, vb6, latex (synthetic)
|
|
7
|
+
|
|
8
|
+
Corpus: paragraphs of varied-length sentences with a fixed random seed, so the
|
|
9
|
+
run is reproducible. Every run also checks that both produce the same chunks.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import os
|
|
14
|
+
import random
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
from langchain_text_splitters import RecursiveCharacterTextSplitter as LC
|
|
18
|
+
|
|
19
|
+
from fast_text_splitter import RecursiveSplitter
|
|
20
|
+
from fast_text_splitter.langchain import RecursiveCharacterTextSplitter as FS
|
|
21
|
+
|
|
22
|
+
WORDS = ("the model retrieves relevant chunks from a vector store before generating "
|
|
23
|
+
"an answer embeddings attention token context window latency throughput "
|
|
24
|
+
"überprüfung naïve café 検索 拡張 生成").split()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def make_docs(total_mb: float, seed: int = 0) -> list[str]:
|
|
28
|
+
rng = random.Random(seed)
|
|
29
|
+
docs, size = [], 0
|
|
30
|
+
while size < total_mb * 1_000_000:
|
|
31
|
+
paras = []
|
|
32
|
+
for _ in range(rng.randint(3, 40)):
|
|
33
|
+
sents = [" ".join(rng.choices(WORDS, k=rng.randint(4, 30))).capitalize() + "."
|
|
34
|
+
for _ in range(rng.randint(1, 8))]
|
|
35
|
+
paras.append(" ".join(sents))
|
|
36
|
+
doc = "\n\n".join(paras)
|
|
37
|
+
docs.append(doc)
|
|
38
|
+
size += len(doc.encode())
|
|
39
|
+
return docs
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def make_python_docs(total_mb: float) -> list[str]:
|
|
43
|
+
"""Real code: the standard library's own .py files, in a fixed order."""
|
|
44
|
+
import sysconfig
|
|
45
|
+
from pathlib import Path
|
|
46
|
+
|
|
47
|
+
docs, size = [], 0
|
|
48
|
+
while size < total_mb * 1_000_000:
|
|
49
|
+
for path in sorted(Path(sysconfig.get_paths()["stdlib"]).glob("*.py")):
|
|
50
|
+
doc = path.read_text(encoding="utf-8", errors="replace")
|
|
51
|
+
docs.append(doc)
|
|
52
|
+
size += len(doc.encode())
|
|
53
|
+
if size >= total_mb * 1_000_000:
|
|
54
|
+
break
|
|
55
|
+
return docs
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def make_markup_docs(language: str, total_mb: float, seed: int = 0) -> list[str]:
|
|
59
|
+
"""Synthetic Markdown / RST / VB6 / LaTeX documents built from prose
|
|
60
|
+
paragraphs, so every separator of that language shows up."""
|
|
61
|
+
rng = random.Random(seed)
|
|
62
|
+
prose = make_docs(total_mb, seed)
|
|
63
|
+
para = [p for d in prose for p in d.split("\n\n")]
|
|
64
|
+
docs, size, k = [], 0, 0
|
|
65
|
+
|
|
66
|
+
def p():
|
|
67
|
+
nonlocal k
|
|
68
|
+
k += 1
|
|
69
|
+
return para[k % len(para)]
|
|
70
|
+
|
|
71
|
+
while size < total_mb * 1_000_000:
|
|
72
|
+
parts = []
|
|
73
|
+
for _ in range(rng.randint(5, 40)):
|
|
74
|
+
if language == "markdown":
|
|
75
|
+
parts.append(rng.choice([f"{'#' * rng.randint(1, 6)} {p()[:40]}", p(), p(),
|
|
76
|
+
"```\nx = 1\n```", "***", "---", f"- {p()[:60]}"]))
|
|
77
|
+
elif language == "rst":
|
|
78
|
+
title = p()[:30]
|
|
79
|
+
parts.append(rng.choice([f"{title}\n{'=' * len(title)}", f"{title}\n{'-' * len(title)}",
|
|
80
|
+
p(), p(), ".. note::", f"* {p()[:60]}"]))
|
|
81
|
+
elif language == "vb6":
|
|
82
|
+
name = "".join(rng.choices("abcdefgh", k=6))
|
|
83
|
+
body = "\n".join(f" ' {line}" for line in p()[:200].split(". "))
|
|
84
|
+
parts.append(rng.choice([
|
|
85
|
+
f"Public Sub {name}()\n{body}\nEnd Sub",
|
|
86
|
+
f"Private Function {name}() As Long\n If x Then\n{body}\n Else\n{body}\n End If\nEnd Function",
|
|
87
|
+
f"Public Property Get {name}()\n Select Case y\n Case 1\n{body}\n End Select\nEnd Property",
|
|
88
|
+
f"Sub {name}()\n For i = 1 To 10\n{body}\n Next\n Do While z\n Loop\nEnd Sub",
|
|
89
|
+
]))
|
|
90
|
+
else: # latex
|
|
91
|
+
parts.append(rng.choice([f"\\section{{{p()[:30]}}}", f"\\subsection{{{p()[:30]}}}", p(), p(),
|
|
92
|
+
f"\\begin{{itemize}}\n\\item {p()[:60]}\n\\end{{itemize}}"]))
|
|
93
|
+
doc = "\n\n".join(parts) + "\n"
|
|
94
|
+
docs.append(doc)
|
|
95
|
+
size += len(doc.encode())
|
|
96
|
+
return docs
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
LANGUAGES = {"python": "PYTHON", "markdown": "MARKDOWN", "rst": "RST", "vb6": "VISUALBASIC6", "latex": "LATEX"}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def timeit(fn, repeat=3):
|
|
103
|
+
best = float("inf")
|
|
104
|
+
for _ in range(repeat):
|
|
105
|
+
t = time.perf_counter()
|
|
106
|
+
out = fn()
|
|
107
|
+
best = min(best, time.perf_counter() - t)
|
|
108
|
+
return best, out
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def main():
|
|
112
|
+
p = argparse.ArgumentParser()
|
|
113
|
+
p.add_argument("--mb", type=float, default=20)
|
|
114
|
+
p.add_argument("--chunk-size", type=int, default=1000)
|
|
115
|
+
p.add_argument("--overlap", type=int, default=200)
|
|
116
|
+
p.add_argument("--language", choices=sorted(LANGUAGES), default=None,
|
|
117
|
+
help="use from_language: python = the stdlib's own source, others synthetic")
|
|
118
|
+
a = p.parse_args()
|
|
119
|
+
|
|
120
|
+
kw = dict(chunk_size=a.chunk_size, chunk_overlap=a.overlap)
|
|
121
|
+
if a.language:
|
|
122
|
+
from langchain_text_splitters import Language
|
|
123
|
+
|
|
124
|
+
lang = Language[LANGUAGES[a.language]]
|
|
125
|
+
docs = make_python_docs(a.mb) if a.language == "python" else make_markup_docs(a.language, a.mb)
|
|
126
|
+
lc = LC.from_language(lang, **kw)
|
|
127
|
+
fs = FS.from_language(lang, **kw)
|
|
128
|
+
assert fs._fast is not None
|
|
129
|
+
else:
|
|
130
|
+
docs = make_docs(a.mb)
|
|
131
|
+
lc = LC(**kw)
|
|
132
|
+
fs = RecursiveSplitter(**kw)
|
|
133
|
+
|
|
134
|
+
t_lc, out_lc = timeit(lambda: [lc.split_text(d) for d in docs])
|
|
135
|
+
t_fs, out_fs = timeit(lambda: [fs.split_text(d) for d in docs])
|
|
136
|
+
t_par, out_par = timeit(lambda: fs.split_texts(docs))
|
|
137
|
+
assert out_lc == out_fs == out_par, "outputs differ!"
|
|
138
|
+
|
|
139
|
+
cores = os.cpu_count()
|
|
140
|
+
kind = f"{a.language}" if a.language else "prose"
|
|
141
|
+
print(f"{len(docs)} docs ({kind}), {a.mb:g} MB, chunk_size={a.chunk_size}, overlap={a.overlap}, {cores} cores\n")
|
|
142
|
+
print("| splitter | time | MB/s | speedup |")
|
|
143
|
+
print("|---|---:|---:|---:|")
|
|
144
|
+
for name, t in [("langchain-text-splitters", t_lc), ("fast-text-splitter (1 thread)", t_fs),
|
|
145
|
+
(f"fast-text-splitter split_texts ({cores} threads)", t_par)]:
|
|
146
|
+
print(f"| {name} | {t:.2f}s | {a.mb / t:.1f} | {t_lc / t:.1f}x |")
|
|
147
|
+
print("\nOutputs identical: yes")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
if __name__ == "__main__":
|
|
151
|
+
main()
|