lightrag-section-anything 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.
- lightrag_section_anything-0.1.0/LICENSE +202 -0
- lightrag_section_anything-0.1.0/MANIFEST.in +2 -0
- lightrag_section_anything-0.1.0/NOTICE +7 -0
- lightrag_section_anything-0.1.0/PKG-INFO +78 -0
- lightrag_section_anything-0.1.0/README.md +50 -0
- lightrag_section_anything-0.1.0/pyproject.toml +54 -0
- lightrag_section_anything-0.1.0/setup.cfg +4 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything/__init__.py +3 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything/blocks.py +75 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything/core.py +28 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything/parser.py +108 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything/plugin.py +30 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything.egg-info/PKG-INFO +78 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything.egg-info/SOURCES.txt +18 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything.egg-info/dependency_links.txt +1 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything.egg-info/entry_points.txt +2 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything.egg-info/requires.txt +5 -0
- lightrag_section_anything-0.1.0/src/lightrag_section_anything.egg-info/top_level.txt +1 -0
- lightrag_section_anything-0.1.0/tests/test_blocks.py +73 -0
- lightrag_section_anything-0.1.0/tests/test_plugin.py +88 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
lightrag-section-anything
|
|
2
|
+
Copyright 2026 The Section Anything Authors
|
|
3
|
+
|
|
4
|
+
This product is licensed under the Apache License, Version 2.0 (see LICENSE).
|
|
5
|
+
|
|
6
|
+
It uses, without bundling, section-anything (Apache-2.0) and LightRAG
|
|
7
|
+
(lightrag-hku, MIT). Each is installed separately under its own licence.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lightrag-section-anything
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Section Anything PDF parser engines for LightRAG: accurate headings for heading-aware chunking, with a cost/accuracy dial.
|
|
5
|
+
Author: The Section Anything Authors
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Omniwot/section-anything/tree/main/packages/lightrag-section-anything
|
|
8
|
+
Project-URL: Repository, https://github.com/Omniwot/section-anything
|
|
9
|
+
Project-URL: Issues, https://github.com/Omniwot/section-anything/issues
|
|
10
|
+
Keywords: lightrag,parser,plugin,pdf,sections,headings,rag,chunking
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Text Processing :: General
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
License-File: NOTICE
|
|
23
|
+
Requires-Dist: section-anything<0.2,>=0.1.1
|
|
24
|
+
Requires-Dist: lightrag-hku<1.7,>=1.5.7
|
|
25
|
+
Provides-Extra: test
|
|
26
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# lightrag-section-anything
|
|
30
|
+
|
|
31
|
+
LightRAG parser engines that turn a PDF into heading-aware blocks (`.blocks.jsonl`) using the
|
|
32
|
+
[`section-anything`](https://github.com/Omniwot/section-anything) library, so LightRAG's
|
|
33
|
+
heading-based chunker ("P") and its heading context work on PDFs without a MinerU or Docling
|
|
34
|
+
service.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
pip install lightrag-section-anything
|
|
40
|
+
# latest from GitHub:
|
|
41
|
+
pip install "git+https://github.com/Omniwot/section-anything#subdirectory=packages/lightrag-section-anything"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Python 3.11+. Depends on `section-anything` and `lightrag-hku` (1.5.7 or later, below 1.7); the
|
|
45
|
+
LightRAG server needs `lightrag-hku[api]`. The engines register through LightRAG's
|
|
46
|
+
`lightrag.parsers` entry point, which the LightRAG server (`lightrag-server`) and the parser debug
|
|
47
|
+
CLI (`python -m lightrag.parser.cli`) load at startup. When you embed LightRAG as a library, call
|
|
48
|
+
`load_third_party_parsers()` from `lightrag.parser.plugins` first.
|
|
49
|
+
|
|
50
|
+
## Engines
|
|
51
|
+
|
|
52
|
+
| Engine | Runs | Cost per 1,000 pages |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| `sectionany_free` | rules (bookmarks, contents, typography) | $0 |
|
|
55
|
+
| `sectionany_quick` | rules + a small model reviewing candidate lines | about $0.07 |
|
|
56
|
+
| `sectionany_standard` | a model reading all lines | about $0.16 (gpt-6-luna) to $2.90 (gpt-6.1-sol) |
|
|
57
|
+
| `sectionany_local` | quick-style review on a local Ollama model (`SECTIONANY_LOCAL_MODEL`) | $0 |
|
|
58
|
+
| `sectionany` | the mode in `SECTIONANY_MODE` (default `free`) | |
|
|
59
|
+
|
|
60
|
+
## Use
|
|
61
|
+
|
|
62
|
+
Route PDFs to an engine with LightRAG's `LIGHTRAG_PARSER` rules, for example:
|
|
63
|
+
|
|
64
|
+
LIGHTRAG_PARSER=pdf:sectionany_quick-P,pdf:sectionany-P,*:native-teP,*:legacy-R
|
|
65
|
+
|
|
66
|
+
Settings are the library's `SECTIONANY_*` environment variables (see its README): API key
|
|
67
|
+
(`SECTIONANY_API_KEY`, else `OPENAI_API_KEY` for OpenAI's endpoint), models, prices,
|
|
68
|
+
`SECTIONANY_MAX_USD_PER_DOC` (default 0.50), `SECTIONANY_OVER_BUDGET=downgrade|fail`,
|
|
69
|
+
`SECTIONANY_MAX_PAGES` (500), `SECTIONANY_MAX_MB` (100), `SECTIONANY_EXTRACT_TIMEOUT_SECONDS`
|
|
70
|
+
(120). The plugin adds `SECTIONANY_MODE`, `SECTIONANY_SYNTHETIC_TITLES` and
|
|
71
|
+
`MAX_PARALLEL_PARSE_SECTIONANY` (default 2). Nothing is written to the process environment, so
|
|
72
|
+
LightRAG's own model settings are untouched. Cost, model and mode per document are reported in
|
|
73
|
+
LightRAG's document status (`parse_warnings`) and in `<name>.sectionany.json`.
|
|
74
|
+
|
|
75
|
+
Tests: `SECTIONANY_TEST_PDF=<some.pdf> pytest packages/lightrag-section-anything/tests`.
|
|
76
|
+
|
|
77
|
+
Not yet: tables as tables, images, OCR, re-levelling MinerU/Docling output, a section-path
|
|
78
|
+
prefix inside embeddings (needs LightRAG's chunker plugins, 1.5.8+).
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# lightrag-section-anything
|
|
2
|
+
|
|
3
|
+
LightRAG parser engines that turn a PDF into heading-aware blocks (`.blocks.jsonl`) using the
|
|
4
|
+
[`section-anything`](https://github.com/Omniwot/section-anything) library, so LightRAG's
|
|
5
|
+
heading-based chunker ("P") and its heading context work on PDFs without a MinerU or Docling
|
|
6
|
+
service.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
pip install lightrag-section-anything
|
|
12
|
+
# latest from GitHub:
|
|
13
|
+
pip install "git+https://github.com/Omniwot/section-anything#subdirectory=packages/lightrag-section-anything"
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Python 3.11+. Depends on `section-anything` and `lightrag-hku` (1.5.7 or later, below 1.7); the
|
|
17
|
+
LightRAG server needs `lightrag-hku[api]`. The engines register through LightRAG's
|
|
18
|
+
`lightrag.parsers` entry point, which the LightRAG server (`lightrag-server`) and the parser debug
|
|
19
|
+
CLI (`python -m lightrag.parser.cli`) load at startup. When you embed LightRAG as a library, call
|
|
20
|
+
`load_third_party_parsers()` from `lightrag.parser.plugins` first.
|
|
21
|
+
|
|
22
|
+
## Engines
|
|
23
|
+
|
|
24
|
+
| Engine | Runs | Cost per 1,000 pages |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| `sectionany_free` | rules (bookmarks, contents, typography) | $0 |
|
|
27
|
+
| `sectionany_quick` | rules + a small model reviewing candidate lines | about $0.07 |
|
|
28
|
+
| `sectionany_standard` | a model reading all lines | about $0.16 (gpt-6-luna) to $2.90 (gpt-6.1-sol) |
|
|
29
|
+
| `sectionany_local` | quick-style review on a local Ollama model (`SECTIONANY_LOCAL_MODEL`) | $0 |
|
|
30
|
+
| `sectionany` | the mode in `SECTIONANY_MODE` (default `free`) | |
|
|
31
|
+
|
|
32
|
+
## Use
|
|
33
|
+
|
|
34
|
+
Route PDFs to an engine with LightRAG's `LIGHTRAG_PARSER` rules, for example:
|
|
35
|
+
|
|
36
|
+
LIGHTRAG_PARSER=pdf:sectionany_quick-P,pdf:sectionany-P,*:native-teP,*:legacy-R
|
|
37
|
+
|
|
38
|
+
Settings are the library's `SECTIONANY_*` environment variables (see its README): API key
|
|
39
|
+
(`SECTIONANY_API_KEY`, else `OPENAI_API_KEY` for OpenAI's endpoint), models, prices,
|
|
40
|
+
`SECTIONANY_MAX_USD_PER_DOC` (default 0.50), `SECTIONANY_OVER_BUDGET=downgrade|fail`,
|
|
41
|
+
`SECTIONANY_MAX_PAGES` (500), `SECTIONANY_MAX_MB` (100), `SECTIONANY_EXTRACT_TIMEOUT_SECONDS`
|
|
42
|
+
(120). The plugin adds `SECTIONANY_MODE`, `SECTIONANY_SYNTHETIC_TITLES` and
|
|
43
|
+
`MAX_PARALLEL_PARSE_SECTIONANY` (default 2). Nothing is written to the process environment, so
|
|
44
|
+
LightRAG's own model settings are untouched. Cost, model and mode per document are reported in
|
|
45
|
+
LightRAG's document status (`parse_warnings`) and in `<name>.sectionany.json`.
|
|
46
|
+
|
|
47
|
+
Tests: `SECTIONANY_TEST_PDF=<some.pdf> pytest packages/lightrag-section-anything/tests`.
|
|
48
|
+
|
|
49
|
+
Not yet: tables as tables, images, OCR, re-levelling MinerU/Docling output, a section-path
|
|
50
|
+
prefix inside embeddings (needs LightRAG's chunker plugins, 1.5.8+).
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"] # SPDX licence expression and license-files
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "lightrag-section-anything"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Section Anything PDF parser engines for LightRAG: accurate headings for heading-aware chunking, with a cost/accuracy dial."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
12
|
+
requires-python = ">=3.11"
|
|
13
|
+
authors = [{ name = "The Section Anything Authors" }]
|
|
14
|
+
keywords = ["lightrag", "parser", "plugin", "pdf", "sections", "headings", "rag", "chunking"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Topic :: Text Processing :: General",
|
|
24
|
+
]
|
|
25
|
+
dependencies = [
|
|
26
|
+
"section-anything>=0.1.1,<0.2", # uses its body export (section_anything.export)
|
|
27
|
+
"lightrag-hku>=1.5.7,<1.7", # lightrag.parsers entry points and NativeParserBase, from 1.5.7
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/Omniwot/section-anything/tree/main/packages/lightrag-section-anything"
|
|
32
|
+
Repository = "https://github.com/Omniwot/section-anything"
|
|
33
|
+
Issues = "https://github.com/Omniwot/section-anything/issues"
|
|
34
|
+
|
|
35
|
+
[project.optional-dependencies]
|
|
36
|
+
test = ["pytest>=8"]
|
|
37
|
+
|
|
38
|
+
[project.entry-points."lightrag.parsers"]
|
|
39
|
+
sectionany = "lightrag_section_anything.plugin:register_parsers"
|
|
40
|
+
|
|
41
|
+
[tool.setuptools.packages.find]
|
|
42
|
+
where = ["src"]
|
|
43
|
+
|
|
44
|
+
[tool.pytest.ini_options]
|
|
45
|
+
testpaths = ["tests"]
|
|
46
|
+
|
|
47
|
+
[tool.ruff]
|
|
48
|
+
target-version = "py311"
|
|
49
|
+
line-length = 120
|
|
50
|
+
src = ["src", "tests"]
|
|
51
|
+
|
|
52
|
+
[tool.ruff.lint]
|
|
53
|
+
select = ["E", "F", "B", "UP", "ASYNC"]
|
|
54
|
+
ignore = ["E501", "E731"]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Section Anything sections -> LightRAG sidecar blocks.
|
|
2
|
+
|
|
3
|
+
One block per section: the heading line (``#`` x level + printed heading), then the section's
|
|
4
|
+
body reflowed into paragraphs (LightRAG's heading chunker treats every line as a paragraph, so
|
|
5
|
+
PDF lines must be joined). ``parent_headings`` holds ancestors only, from a level-keyed stack.
|
|
6
|
+
Text before the first heading is a ``preface`` block. Running headers and footers are dropped.
|
|
7
|
+
Positions: one bbox per page, PDF points with the origin at the bottom left.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
# Paragraph reflow, heading-line detection and heading text are shared with the library's
|
|
15
|
+
# Markdown export.
|
|
16
|
+
from section_anything.export import heading_lines as _heading_lines
|
|
17
|
+
from section_anything.export import heading_text
|
|
18
|
+
from section_anything.export import reflow as _reflow
|
|
19
|
+
|
|
20
|
+
__all__ = ["build_blocks", "heading_text"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _positions(lines: list[Any]) -> list[dict]:
|
|
24
|
+
pages: dict[int, list[float]] = {}
|
|
25
|
+
for ln in lines:
|
|
26
|
+
b = pages.setdefault(ln.page, [ln.x0, ln.y1, ln.x1, ln.y0])
|
|
27
|
+
b[0], b[1], b[2], b[3] = min(b[0], ln.x0), max(b[1], ln.y1), max(b[2], ln.x1), min(b[3], ln.y0)
|
|
28
|
+
return [{"type": "bbox", "anchor": str(p), "range": [round(v, 2) for v in r]} for p, r in sorted(pages.items())]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_blocks(ext: Any, sections: list[dict], furniture: set[int] | None = None,
|
|
32
|
+
synthetic_titles: bool = False) -> tuple[list[dict], str]:
|
|
33
|
+
"""Returns (blocks, document title). Each block: content, heading, level, parent_headings,
|
|
34
|
+
session_type, is_title_block, positions."""
|
|
35
|
+
from lightrag.parser._markdown import render_heading_line
|
|
36
|
+
|
|
37
|
+
furniture = furniture or set()
|
|
38
|
+
lines = ext.lines
|
|
39
|
+
body = [s for s in sections if "front_matter" not in s.get("flags", [])]
|
|
40
|
+
if not synthetic_titles: # headings the model invented for headingless text: fold into the previous block
|
|
41
|
+
body = [s for s in body if s.get("title_from_text", True) is not False]
|
|
42
|
+
body.sort(key=lambda s: s["first_line"])
|
|
43
|
+
doc_title = next((heading_text(s) for s in body if "doc_title" in s.get("flags", [])), "")
|
|
44
|
+
|
|
45
|
+
starts = [s["first_line"] for s in body]
|
|
46
|
+
blocks: list[dict] = []
|
|
47
|
+
|
|
48
|
+
def span(a: int, b: int) -> list[Any]:
|
|
49
|
+
return [ln for ln in lines[a:b] if ln.i not in furniture]
|
|
50
|
+
|
|
51
|
+
first = starts[0] if starts else len(lines)
|
|
52
|
+
pre = span(0, first)
|
|
53
|
+
if any(ln.text.strip() for ln in pre):
|
|
54
|
+
blocks.append({"content": "\n".join(_reflow(pre)), "heading": "", "level": 0, "parent_headings": [],
|
|
55
|
+
"session_type": "preface", "is_title_block": False, "positions": _positions(pre)})
|
|
56
|
+
|
|
57
|
+
stack: list[tuple[int, str]] = []
|
|
58
|
+
for k, sec in enumerate(body):
|
|
59
|
+
end = starts[k + 1] if k + 1 < len(starts) else len(lines)
|
|
60
|
+
seg = span(sec["first_line"], end)
|
|
61
|
+
head = heading_text(sec)
|
|
62
|
+
is_title = "doc_title" in sec.get("flags", [])
|
|
63
|
+
level = 0 if is_title else max(1, int(sec["level"]))
|
|
64
|
+
n_head = _heading_lines(seg, head)
|
|
65
|
+
if not is_title:
|
|
66
|
+
stack = [(lv, h) for lv, h in stack if lv < level]
|
|
67
|
+
parents = [h for _lv, h in stack]
|
|
68
|
+
heading_line = render_heading_line(max(level, 1), head)
|
|
69
|
+
paras = _reflow(seg[n_head:])
|
|
70
|
+
blocks.append({"content": "\n".join([heading_line, *paras]), "heading": head, "level": level,
|
|
71
|
+
"parent_headings": parents, "session_type": "body", "is_title_block": is_title,
|
|
72
|
+
"positions": _positions(seg)})
|
|
73
|
+
if not is_title:
|
|
74
|
+
stack.append((level, head))
|
|
75
|
+
return blocks, doc_title
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Section a PDF with the `section-anything` library, inside LightRAG's parser thread.
|
|
2
|
+
|
|
3
|
+
Settings come from the library (``SECTIONANY_*`` environment variables: API key, models, prices,
|
|
4
|
+
``SECTIONANY_MAX_USD_PER_DOC``, ``SECTIONANY_OVER_BUDGET``, page/size caps, extraction time limit).
|
|
5
|
+
The plugin adds ``SECTIONANY_MODE`` for the ``sectionany`` engine. Nothing is written to the
|
|
6
|
+
process environment, so LightRAG's own model settings are never touched.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from section_anything import SectionTree, Settings, section
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def resolve_mode(mode: str | None) -> str:
|
|
18
|
+
"""The engine's mode, or ``SECTIONANY_MODE`` (default free). Validated by the library."""
|
|
19
|
+
return (mode or os.getenv("SECTIONANY_MODE") or "free").strip()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def section_pdf(path: Path, mode: str | None = None, *, settings: Settings | None = None) -> SectionTree:
|
|
23
|
+
"""Section one PDF. Over-budget runs downgrade (standard -> quick -> free) unless
|
|
24
|
+
``SECTIONANY_OVER_BUDGET=fail``; unpriced cloud models are refused before the PDF is read."""
|
|
25
|
+
tree = section(path, resolve_mode(mode), settings=settings)
|
|
26
|
+
if not tree.text.strip(): # pragma: no cover - the library refuses text-less PDFs first
|
|
27
|
+
raise ValueError("no text layer; re-upload with an OCR engine, e.g. name.[mineru-P].pdf")
|
|
28
|
+
return tree
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""LightRAG parser engines: PDF -> Section Anything sections -> sidecar blocks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
|
+
|
|
10
|
+
from lightrag.parser.native_base import NativeExtractRuntime, NativeParserBase
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from lightrag.sidecar.ir import IRDoc
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SectionAnyParser(NativeParserBase):
|
|
17
|
+
"""Mode from ``SECTIONANY_MODE`` (free | quick | standard | local:<model>)."""
|
|
18
|
+
|
|
19
|
+
engine_name = "sectionany"
|
|
20
|
+
empty_content_label = "Section Anything"
|
|
21
|
+
mode: str | None = None # None: read SECTIONANY_MODE at parse time
|
|
22
|
+
|
|
23
|
+
def validate_source(self, source: Path, file_path: str) -> None:
|
|
24
|
+
super().validate_source(source, file_path)
|
|
25
|
+
if source.suffix.lower() != ".pdf":
|
|
26
|
+
raise ValueError(f"{self.engine_name} parses PDF files only: {file_path}")
|
|
27
|
+
|
|
28
|
+
def validate_source_blocking(self, source: Path, file_path: str) -> None:
|
|
29
|
+
"""Size and page caps (SECTIONANY_MAX_MB, SECTIONANY_MAX_PAGES), checked without parsing any
|
|
30
|
+
page content."""
|
|
31
|
+
from section_anything import PdfError, Settings, check_pdf
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
check_pdf(source, Settings())
|
|
35
|
+
except PdfError as e:
|
|
36
|
+
raise ValueError(f"{file_path}: {e}") from None
|
|
37
|
+
|
|
38
|
+
def extract(self, source: Path, *, parsed_dir: Path, asset_dir: Path, base_name: str,
|
|
39
|
+
runtime: NativeExtractRuntime | None = None) -> tuple[list[dict[str, Any]], dict[str, Any], dict[str, Any]]:
|
|
40
|
+
from section_anything.structure import furniture_of
|
|
41
|
+
|
|
42
|
+
from lightrag_section_anything import __version__
|
|
43
|
+
from lightrag_section_anything.blocks import build_blocks
|
|
44
|
+
from lightrag_section_anything.core import section_pdf
|
|
45
|
+
|
|
46
|
+
tree = section_pdf(source, self.mode)
|
|
47
|
+
ext = tree.extraction
|
|
48
|
+
blocks, doc_title = build_blocks(ext, tree.resolved, furniture_of(ext),
|
|
49
|
+
synthetic_titles=os.getenv("SECTIONANY_SYNTHETIC_TITLES") == "true")
|
|
50
|
+
if not any(b["content"].strip() for b in blocks):
|
|
51
|
+
raise ValueError("no text extracted; scanned PDFs need an OCR engine, e.g. name.[mineru-P].pdf")
|
|
52
|
+
usage = tree.usage
|
|
53
|
+
warnings = {
|
|
54
|
+
"sectionany_mode": tree.mode, "sectionany_model": tree.model or "", "sectionany_cost_usd": tree.cost_usd,
|
|
55
|
+
"sectionany_calls": usage.get("calls", 0), "sectionany_tokens_in": usage.get("input_tokens", 0),
|
|
56
|
+
"sectionany_tokens_out": usage.get("output_tokens", 0), "sectionany_seconds": tree.seconds,
|
|
57
|
+
"sectionany_sections": len(tree.sections),
|
|
58
|
+
"sectionany_flagged": sum(bool(s.get("flags")) for s in tree.sections),
|
|
59
|
+
}
|
|
60
|
+
if tree.downgraded:
|
|
61
|
+
warnings["sectionany_downgraded"] = tree.downgraded
|
|
62
|
+
audit = {**warnings, "pages": tree.pages,
|
|
63
|
+
"sections": [{k: s.get(k) for k in ("number", "title", "level", "page_start", "page_end", "flags")}
|
|
64
|
+
for s in tree.sections]}
|
|
65
|
+
(parsed_dir / f"{Path(base_name).name}.sectionany.json").write_text(json.dumps(audit, ensure_ascii=False, sort_keys=True, indent=1))
|
|
66
|
+
metadata = {"doc_title": doc_title, "split_option": {
|
|
67
|
+
"engine_version": __version__, "mode": tree.mode, "model": tree.model or "", "cost_usd": tree.cost_usd,
|
|
68
|
+
"sections": len(tree.sections)}}
|
|
69
|
+
return blocks, warnings, metadata
|
|
70
|
+
|
|
71
|
+
def build_ir(self, blocks: list[dict[str, Any]], *, document_name: str, asset_dir_name: str,
|
|
72
|
+
metadata: dict[str, Any]) -> IRDoc:
|
|
73
|
+
from lightrag.sidecar.ir import IRBlock, IRDoc, IRPosition
|
|
74
|
+
|
|
75
|
+
ir_blocks = [
|
|
76
|
+
IRBlock(content_template=b["content"], heading=b["heading"], level=b["level"],
|
|
77
|
+
parent_headings=list(b["parent_headings"]), session_type=b["session_type"],
|
|
78
|
+
is_title_block=b["is_title_block"],
|
|
79
|
+
positions=[IRPosition(type=p["type"], anchor=p["anchor"], range=p["range"]) for p in b["positions"]])
|
|
80
|
+
for b in blocks
|
|
81
|
+
]
|
|
82
|
+
return IRDoc(document_name=document_name, document_format="pdf",
|
|
83
|
+
doc_title=metadata.get("doc_title") or Path(document_name).stem,
|
|
84
|
+
split_option=metadata.get("split_option", {}), blocks=ir_blocks,
|
|
85
|
+
bbox_attributes={"origin": "LEFTBOTTOM"})
|
|
86
|
+
|
|
87
|
+
def surface_warnings(self, warnings: dict[str, Any], source: Path) -> dict[str, Any] | None:
|
|
88
|
+
return dict(warnings) # mode, model, cost and counts go to doc_status
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class FreeParser(SectionAnyParser):
|
|
92
|
+
engine_name = "sectionany_free"
|
|
93
|
+
mode = "free"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class QuickParser(SectionAnyParser):
|
|
97
|
+
engine_name = "sectionany_quick"
|
|
98
|
+
mode = "quick"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class StandardParser(SectionAnyParser):
|
|
102
|
+
engine_name = "sectionany_standard"
|
|
103
|
+
mode = "standard"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class LocalParser(SectionAnyParser):
|
|
107
|
+
engine_name = "sectionany_local"
|
|
108
|
+
mode = "local"
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Entry point for ``lightrag.parsers``: registers one engine per position of the dial.
|
|
2
|
+
Import-cheap: implementations load lazily through ``ParserSpec.impl``."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
IMPL = "lightrag_section_anything.parser:{}"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _has_key() -> bool:
|
|
12
|
+
return bool(os.getenv("SECTIONANY_API_KEY") or os.getenv("OPENAI_API_KEY"))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def register_parsers() -> None:
|
|
16
|
+
from lightrag.parser.registry import ParserSpec, register_parser
|
|
17
|
+
|
|
18
|
+
pdf = frozenset({"pdf"})
|
|
19
|
+
register_parser(ParserSpec(
|
|
20
|
+
engine_name="sectionany", impl=IMPL.format("SectionAnyParser"), suffixes=pdf, queue_group="sectionany",
|
|
21
|
+
concurrency=int(os.getenv("MAX_PARALLEL_PARSE_SECTIONANY", "2"))))
|
|
22
|
+
for mode, cls, ready, need in (
|
|
23
|
+
("free", "FreeParser", lambda: True, lambda: None),
|
|
24
|
+
("quick", "QuickParser", _has_key, lambda: "SECTIONANY_API_KEY or OPENAI_API_KEY"),
|
|
25
|
+
("standard", "StandardParser", _has_key, lambda: "SECTIONANY_API_KEY or OPENAI_API_KEY"),
|
|
26
|
+
("local", "LocalParser", lambda: bool(os.getenv("SECTIONANY_LOCAL_MODEL")), lambda: "SECTIONANY_LOCAL_MODEL"),
|
|
27
|
+
):
|
|
28
|
+
register_parser(ParserSpec(
|
|
29
|
+
engine_name=f"sectionany_{mode}", impl=IMPL.format(cls), suffixes=pdf, queue_group="sectionany",
|
|
30
|
+
endpoint_configured=ready, endpoint_requirement=need))
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lightrag-section-anything
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Section Anything PDF parser engines for LightRAG: accurate headings for heading-aware chunking, with a cost/accuracy dial.
|
|
5
|
+
Author: The Section Anything Authors
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Omniwot/section-anything/tree/main/packages/lightrag-section-anything
|
|
8
|
+
Project-URL: Repository, https://github.com/Omniwot/section-anything
|
|
9
|
+
Project-URL: Issues, https://github.com/Omniwot/section-anything/issues
|
|
10
|
+
Keywords: lightrag,parser,plugin,pdf,sections,headings,rag,chunking
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Text Processing :: General
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
License-File: NOTICE
|
|
23
|
+
Requires-Dist: section-anything<0.2,>=0.1.1
|
|
24
|
+
Requires-Dist: lightrag-hku<1.7,>=1.5.7
|
|
25
|
+
Provides-Extra: test
|
|
26
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# lightrag-section-anything
|
|
30
|
+
|
|
31
|
+
LightRAG parser engines that turn a PDF into heading-aware blocks (`.blocks.jsonl`) using the
|
|
32
|
+
[`section-anything`](https://github.com/Omniwot/section-anything) library, so LightRAG's
|
|
33
|
+
heading-based chunker ("P") and its heading context work on PDFs without a MinerU or Docling
|
|
34
|
+
service.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
pip install lightrag-section-anything
|
|
40
|
+
# latest from GitHub:
|
|
41
|
+
pip install "git+https://github.com/Omniwot/section-anything#subdirectory=packages/lightrag-section-anything"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Python 3.11+. Depends on `section-anything` and `lightrag-hku` (1.5.7 or later, below 1.7); the
|
|
45
|
+
LightRAG server needs `lightrag-hku[api]`. The engines register through LightRAG's
|
|
46
|
+
`lightrag.parsers` entry point, which the LightRAG server (`lightrag-server`) and the parser debug
|
|
47
|
+
CLI (`python -m lightrag.parser.cli`) load at startup. When you embed LightRAG as a library, call
|
|
48
|
+
`load_third_party_parsers()` from `lightrag.parser.plugins` first.
|
|
49
|
+
|
|
50
|
+
## Engines
|
|
51
|
+
|
|
52
|
+
| Engine | Runs | Cost per 1,000 pages |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| `sectionany_free` | rules (bookmarks, contents, typography) | $0 |
|
|
55
|
+
| `sectionany_quick` | rules + a small model reviewing candidate lines | about $0.07 |
|
|
56
|
+
| `sectionany_standard` | a model reading all lines | about $0.16 (gpt-6-luna) to $2.90 (gpt-6.1-sol) |
|
|
57
|
+
| `sectionany_local` | quick-style review on a local Ollama model (`SECTIONANY_LOCAL_MODEL`) | $0 |
|
|
58
|
+
| `sectionany` | the mode in `SECTIONANY_MODE` (default `free`) | |
|
|
59
|
+
|
|
60
|
+
## Use
|
|
61
|
+
|
|
62
|
+
Route PDFs to an engine with LightRAG's `LIGHTRAG_PARSER` rules, for example:
|
|
63
|
+
|
|
64
|
+
LIGHTRAG_PARSER=pdf:sectionany_quick-P,pdf:sectionany-P,*:native-teP,*:legacy-R
|
|
65
|
+
|
|
66
|
+
Settings are the library's `SECTIONANY_*` environment variables (see its README): API key
|
|
67
|
+
(`SECTIONANY_API_KEY`, else `OPENAI_API_KEY` for OpenAI's endpoint), models, prices,
|
|
68
|
+
`SECTIONANY_MAX_USD_PER_DOC` (default 0.50), `SECTIONANY_OVER_BUDGET=downgrade|fail`,
|
|
69
|
+
`SECTIONANY_MAX_PAGES` (500), `SECTIONANY_MAX_MB` (100), `SECTIONANY_EXTRACT_TIMEOUT_SECONDS`
|
|
70
|
+
(120). The plugin adds `SECTIONANY_MODE`, `SECTIONANY_SYNTHETIC_TITLES` and
|
|
71
|
+
`MAX_PARALLEL_PARSE_SECTIONANY` (default 2). Nothing is written to the process environment, so
|
|
72
|
+
LightRAG's own model settings are untouched. Cost, model and mode per document are reported in
|
|
73
|
+
LightRAG's document status (`parse_warnings`) and in `<name>.sectionany.json`.
|
|
74
|
+
|
|
75
|
+
Tests: `SECTIONANY_TEST_PDF=<some.pdf> pytest packages/lightrag-section-anything/tests`.
|
|
76
|
+
|
|
77
|
+
Not yet: tables as tables, images, OCR, re-levelling MinerU/Docling output, a section-path
|
|
78
|
+
prefix inside embeddings (needs LightRAG's chunker plugins, 1.5.8+).
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
NOTICE
|
|
4
|
+
README.md
|
|
5
|
+
pyproject.toml
|
|
6
|
+
src/lightrag_section_anything/__init__.py
|
|
7
|
+
src/lightrag_section_anything/blocks.py
|
|
8
|
+
src/lightrag_section_anything/core.py
|
|
9
|
+
src/lightrag_section_anything/parser.py
|
|
10
|
+
src/lightrag_section_anything/plugin.py
|
|
11
|
+
src/lightrag_section_anything.egg-info/PKG-INFO
|
|
12
|
+
src/lightrag_section_anything.egg-info/SOURCES.txt
|
|
13
|
+
src/lightrag_section_anything.egg-info/dependency_links.txt
|
|
14
|
+
src/lightrag_section_anything.egg-info/entry_points.txt
|
|
15
|
+
src/lightrag_section_anything.egg-info/requires.txt
|
|
16
|
+
src/lightrag_section_anything.egg-info/top_level.txt
|
|
17
|
+
tests/test_blocks.py
|
|
18
|
+
tests/test_plugin.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
lightrag_section_anything
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
from lightrag_section_anything.blocks import _heading_lines, _reflow, build_blocks
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class L: # minimal stand-in for app.sectioning.extract.Line
|
|
8
|
+
i: int
|
|
9
|
+
page: int
|
|
10
|
+
text: str
|
|
11
|
+
y1: float
|
|
12
|
+
size: float = 10.0
|
|
13
|
+
x0: float = 72.0
|
|
14
|
+
x1: float = 540.0
|
|
15
|
+
|
|
16
|
+
@property
|
|
17
|
+
def y0(self) -> float:
|
|
18
|
+
return self.y1 - self.size
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Ext:
|
|
23
|
+
lines: list
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _ext(texts):
|
|
27
|
+
lines, y, page = [], 760.0, 1
|
|
28
|
+
for _i, t in enumerate(texts):
|
|
29
|
+
if t == "<page>":
|
|
30
|
+
page, y = page + 1, 760.0
|
|
31
|
+
continue
|
|
32
|
+
lines.append(L(len(lines), page, t, y))
|
|
33
|
+
y -= 12.0
|
|
34
|
+
return Ext(lines)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def sec(first, level, title, number="", flags=()):
|
|
38
|
+
return {"first_line": first, "level": level, "title": title, "number": number, "flags": list(flags)}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_parents_are_ancestors_only_and_title_block():
|
|
42
|
+
ext = _ext(["My Paper", "intro text", "1 Introduction", "body a", "1.1 Scope", "body b", "2 Methods", "body c"])
|
|
43
|
+
blocks, title = build_blocks(ext, [sec(0, 1, "My Paper", flags=["doc_title"]), sec(2, 1, "Introduction", "1"),
|
|
44
|
+
sec(4, 2, "Scope", "1.1"), sec(6, 1, "Methods", "2")])
|
|
45
|
+
assert title == "My Paper"
|
|
46
|
+
by = {b["heading"]: b for b in blocks}
|
|
47
|
+
assert by["My Paper"]["level"] == 0 and by["My Paper"]["is_title_block"]
|
|
48
|
+
assert by["1 Introduction"]["parent_headings"] == []
|
|
49
|
+
assert by["1.1 Scope"]["parent_headings"] == ["1 Introduction"]
|
|
50
|
+
assert by["2 Methods"]["parent_headings"] == []
|
|
51
|
+
assert by["1.1 Scope"]["content"].startswith("## 1.1 Scope\n")
|
|
52
|
+
assert "body b" in by["1.1 Scope"]["content"] and "Scope\n1.1" not in by["1.1 Scope"]["content"]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_preface_and_wrapped_heading():
|
|
56
|
+
ext = _ext(["Copyright notice", "Article 9", "Freedom of association", "All Germans shall have the right"])
|
|
57
|
+
blocks, _ = build_blocks(ext, [sec(1, 2, "Article 9 Freedom of association")])
|
|
58
|
+
assert blocks[0]["session_type"] == "preface" and blocks[0]["level"] == 0
|
|
59
|
+
body = blocks[1]["content"].split("\n")
|
|
60
|
+
assert body[0] == "## Article 9 Freedom of association" and body[1] == "All Germans shall have the right"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_run_in_heading_keeps_its_line():
|
|
64
|
+
ext = _ext(["Short title. This Act may be cited as the Example Act."])
|
|
65
|
+
assert _heading_lines(ext.lines, "Short title.") == 0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_reflow_joins_lines_and_dehyphenates():
|
|
69
|
+
ext = _ext(["The quick brown fox jumps over the lazy dog and keeps run-", "ning until the end of the line.",
|
|
70
|
+
"<page>", "Next paragraph starts here."])
|
|
71
|
+
paras = _reflow(ext.lines)
|
|
72
|
+
assert paras[0] == "The quick brown fox jumps over the lazy dog and keeps running until the end of the line."
|
|
73
|
+
assert paras[1] == "Next paragraph starts here."
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
needs_pdf = pytest.mark.skipif(not os.getenv("SECTIONANY_TEST_PDF"),
|
|
8
|
+
reason="set SECTIONANY_TEST_PDF to a PDF for the end-to-end parse")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@pytest.fixture(autouse=True)
|
|
12
|
+
def clean_env(monkeypatch):
|
|
13
|
+
"""Library defaults, whatever the shell has set (the test PDF path excepted)."""
|
|
14
|
+
for key in list(os.environ):
|
|
15
|
+
if key.upper().startswith("SECTIONANY_") and key.upper() != "SECTIONANY_TEST_PDF":
|
|
16
|
+
monkeypatch.delenv(key)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_engines_register():
|
|
20
|
+
from lightrag.parser import registry
|
|
21
|
+
from lightrag.parser.plugins import load_third_party_parsers
|
|
22
|
+
|
|
23
|
+
load_third_party_parsers(force=True)
|
|
24
|
+
names = {"sectionany", "sectionany_free", "sectionany_quick", "sectionany_standard", "sectionany_local"}
|
|
25
|
+
assert names <= set(registry._REGISTRY)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_core_comes_from_the_library_not_the_web_app():
|
|
29
|
+
import lightrag_section_anything.core as core
|
|
30
|
+
import lightrag_section_anything.parser # noqa: F401
|
|
31
|
+
|
|
32
|
+
assert core.section.__module__ == "section_anything.api"
|
|
33
|
+
assert "app" not in sys.modules and "app.sectioning" not in sys.modules
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@needs_pdf
|
|
37
|
+
def test_free_parse_writes_sidecar(tmp_path):
|
|
38
|
+
from lightrag_section_anything.parser import FreeParser
|
|
39
|
+
|
|
40
|
+
src = Path(os.environ["SECTIONANY_TEST_PDF"])
|
|
41
|
+
blocks, warnings, meta = FreeParser().extract(src, parsed_dir=tmp_path, asset_dir=tmp_path / "a", base_name="t")
|
|
42
|
+
assert warnings["sectionany_mode"] == "free" and warnings["sectionany_cost_usd"] == 0
|
|
43
|
+
assert any(b["heading"] for b in blocks)
|
|
44
|
+
seen: list[tuple[int, str]] = []
|
|
45
|
+
for b in blocks: # parent_headings must be earlier, shallower headings
|
|
46
|
+
if b["level"] > 0:
|
|
47
|
+
for p in b["parent_headings"]:
|
|
48
|
+
assert any(h == p and lv < b["level"] for lv, h in seen)
|
|
49
|
+
seen.append((b["level"], b["heading"]))
|
|
50
|
+
assert (tmp_path / "t.sectionany.json").exists()
|
|
51
|
+
ir = FreeParser().build_ir(blocks, document_name=src.name, asset_dir_name="a", metadata=meta)
|
|
52
|
+
assert ir.document_format == "pdf" and len(ir.blocks) == len(blocks)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@needs_pdf
|
|
56
|
+
def test_unpriced_cloud_model_is_refused_before_any_call(monkeypatch):
|
|
57
|
+
from lightrag_section_anything.core import section_pdf
|
|
58
|
+
|
|
59
|
+
monkeypatch.setenv("SECTIONANY_QUICK_MODEL", "no-such-model")
|
|
60
|
+
with pytest.raises(ValueError, match="no price for model"):
|
|
61
|
+
section_pdf(Path(os.environ["SECTIONANY_TEST_PDF"]), "quick")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@needs_pdf
|
|
65
|
+
def test_file_size_cap(monkeypatch):
|
|
66
|
+
from lightrag_section_anything.parser import FreeParser
|
|
67
|
+
|
|
68
|
+
monkeypatch.setenv("SECTIONANY_MAX_MB", "0.001")
|
|
69
|
+
src = Path(os.environ["SECTIONANY_TEST_PDF"])
|
|
70
|
+
with pytest.raises(ValueError, match="SECTIONANY_MAX_MB"):
|
|
71
|
+
FreeParser().validate_source_blocking(src, src.name)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@needs_pdf
|
|
75
|
+
def test_page_cap(monkeypatch):
|
|
76
|
+
from lightrag_section_anything.parser import FreeParser
|
|
77
|
+
|
|
78
|
+
monkeypatch.setenv("SECTIONANY_MAX_PAGES", "1")
|
|
79
|
+
src = Path(os.environ["SECTIONANY_TEST_PDF"])
|
|
80
|
+
with pytest.raises(ValueError, match="SECTIONANY_MAX_PAGES"):
|
|
81
|
+
FreeParser().validate_source_blocking(src, src.name)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_bad_mode_is_a_value_error(tmp_path):
|
|
85
|
+
from lightrag_section_anything.core import section_pdf
|
|
86
|
+
|
|
87
|
+
with pytest.raises(ValueError, match="unknown mode"):
|
|
88
|
+
section_pdf(tmp_path / "x.pdf", "turbo")
|