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.
Files changed (44) hide show
  1. section_anything-0.1.0/LICENSE +202 -0
  2. section_anything-0.1.0/MANIFEST.in +2 -0
  3. section_anything-0.1.0/NOTICE +9 -0
  4. section_anything-0.1.0/PKG-INFO +219 -0
  5. section_anything-0.1.0/README.md +182 -0
  6. section_anything-0.1.0/pyproject.toml +65 -0
  7. section_anything-0.1.0/setup.cfg +4 -0
  8. section_anything-0.1.0/src/section_anything/__init__.py +90 -0
  9. section_anything-0.1.0/src/section_anything/__main__.py +5 -0
  10. section_anything-0.1.0/src/section_anything/_worker.py +66 -0
  11. section_anything-0.1.0/src/section_anything/api.py +267 -0
  12. section_anything-0.1.0/src/section_anything/bridge.py +70 -0
  13. section_anything-0.1.0/src/section_anything/cli.py +77 -0
  14. section_anything-0.1.0/src/section_anything/config.py +131 -0
  15. section_anything-0.1.0/src/section_anything/errors.py +42 -0
  16. section_anything-0.1.0/src/section_anything/evaluate.py +72 -0
  17. section_anything-0.1.0/src/section_anything/export.py +94 -0
  18. section_anything-0.1.0/src/section_anything/extract.py +336 -0
  19. section_anything-0.1.0/src/section_anything/isolate.py +153 -0
  20. section_anything-0.1.0/src/section_anything/llm.py +298 -0
  21. section_anything-0.1.0/src/section_anything/markers.py +117 -0
  22. section_anything-0.1.0/src/section_anything/outline_check.py +255 -0
  23. section_anything-0.1.0/src/section_anything/pipeline.py +284 -0
  24. section_anything-0.1.0/src/section_anything/py.typed +0 -0
  25. section_anything-0.1.0/src/section_anything/strategies/__init__.py +1 -0
  26. section_anything-0.1.0/src/section_anything/strategies/base.py +51 -0
  27. section_anything-0.1.0/src/section_anything/strategies/llm_text.py +255 -0
  28. section_anything-0.1.0/src/section_anything/strategies/rules.py +232 -0
  29. section_anything-0.1.0/src/section_anything/structure.py +402 -0
  30. section_anything-0.1.0/src/section_anything.egg-info/PKG-INFO +219 -0
  31. section_anything-0.1.0/src/section_anything.egg-info/SOURCES.txt +42 -0
  32. section_anything-0.1.0/src/section_anything.egg-info/dependency_links.txt +1 -0
  33. section_anything-0.1.0/src/section_anything.egg-info/entry_points.txt +2 -0
  34. section_anything-0.1.0/src/section_anything.egg-info/requires.txt +13 -0
  35. section_anything-0.1.0/src/section_anything.egg-info/top_level.txt +1 -0
  36. section_anything-0.1.0/tests/conftest.py +111 -0
  37. section_anything-0.1.0/tests/test_api.py +100 -0
  38. section_anything-0.1.0/tests/test_cli.py +33 -0
  39. section_anything-0.1.0/tests/test_costs.py +151 -0
  40. section_anything-0.1.0/tests/test_isolation.py +77 -0
  41. section_anything-0.1.0/tests/test_modes.py +82 -0
  42. section_anything-0.1.0/tests/test_outline_check.py +170 -0
  43. section_anything-0.1.0/tests/test_settings.py +88 -0
  44. section_anything-0.1.0/tests/test_structure.py +70 -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,2 @@
1
+ include LICENSE NOTICE README.md
2
+ recursive-include tests *.py
@@ -0,0 +1,9 @@
1
+ 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, pdfplumber and pdfminer.six (MIT), pypdfium2 and
7
+ PDFium (Apache-2.0 / BSD-3-Clause), RapidFuzz (MIT), the OpenAI Python library
8
+ (Apache-2.0) and pydantic (MIT). Each is installed separately under its own
9
+ licence.
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: section-anything
3
+ Version: 0.1.0
4
+ Summary: Find the sections of a PDF (headings, levels, page and character spans), from free rules to LLM review, with hard cost caps.
5
+ Author: The Section Anything Authors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://omniwot.github.io/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: pdf,headings,sections,table of contents,document structure,rag,chunking
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Text Processing :: General
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ License-File: NOTICE
25
+ Requires-Dist: pdfplumber>=0.11.8
26
+ Requires-Dist: pdfminer.six>=20251107
27
+ Requires-Dist: pypdfium2>=4.30
28
+ Requires-Dist: rapidfuzz>=3.9
29
+ Requires-Dist: openai>=1.99
30
+ Requires-Dist: pydantic>=2.7
31
+ Requires-Dist: pydantic-settings>=2.6
32
+ Provides-Extra: langfuse
33
+ Requires-Dist: langfuse>=2.57; extra == "langfuse"
34
+ Provides-Extra: test
35
+ Requires-Dist: pytest>=8; extra == "test"
36
+ Dynamic: license-file
37
+
38
+ # section-anything
39
+
40
+ > **Pre-release (0.1).** The API may change before 1.0.
41
+
42
+ Find the sections of a PDF: every heading, its level, the pages it spans and its exact
43
+ character range in the extracted text. One call, with a dial from free rules to an LLM that
44
+ reads the whole document, and a hard cost cap on every paid run.
45
+
46
+ ```python
47
+ import section_anything
48
+
49
+ tree = section_anything.section("paper.pdf", mode="quick")
50
+ print(tree.to_markdown())
51
+ # # A Study of Sectioning
52
+ # ## 1 Introduction
53
+ # ### 1.1 Scope
54
+ # ## 2 Methods
55
+ print(tree.sections[1])
56
+ # {'number': '1', 'title': 'Introduction', 'level': 1, 'page_start': 1, 'page_end': 1,
57
+ # 'start': 22, 'end': 484, 'flags': []}
58
+ print(tree.summary()) # mode, model, pages, sections, calls, tokens, cost_usd, seconds
59
+ ```
60
+
61
+ ## Install
62
+
63
+ Python 3.11+:
64
+
65
+ ```sh
66
+ pip install section-anything
67
+ pip install "section-anything[langfuse]" # optional Langfuse tracing
68
+ # latest from GitHub:
69
+ pip install "git+https://github.com/Omniwot/section-anything#subdirectory=packages/section-anything"
70
+ # from a checkout of the repository:
71
+ pip install -e ./packages/section-anything
72
+ ```
73
+
74
+ Dependencies: pdfplumber and pdfminer.six (MIT), pypdfium2 (Apache-2.0 / BSD-3-Clause),
75
+ RapidFuzz (MIT), openai (Apache-2.0), pydantic and pydantic-settings (MIT). No PyMuPDF (AGPL).
76
+
77
+ ## Modes
78
+
79
+ | Mode | What runs | Sent to a model | Cost per 1,000 pages |
80
+ |---|---|---|---|
81
+ | `free` (default) | PDF bookmarks or the printed table of contents as the outline, then typography and numbering rules; headings a complete-looking outline does not list are dropped | nothing | $0 |
82
+ | `quick` | the rules propose candidate heading lines; a small model keeps the real ones and sets levels | candidate lines and a 70-character peek at the next line | about $0.07 (`gpt-6-luna`) |
83
+ | `standard` | a model reads every line, with font hints, and marks where sections start and end | the document text | about $0.16 (`gpt-6-luna`), $2.90 (`gpt-6.1-sol`, the default) |
84
+ | `local:<model>` | `quick`, answered by a local [Ollama](https://ollama.com) model | nothing leaves the machine | $0 |
85
+
86
+ Costs are measured averages at the built-in list prices; your documents may differ.
87
+
88
+ ## Command line
89
+
90
+ ```sh
91
+ section-anything paper.pdf # free, Markdown headings
92
+ section-anything paper.pdf --mode quick --format json # JSON with spans and cost
93
+ section-anything paper.pdf --mode standard --max-usd 0.5 # cap this document at $0.50
94
+ section-anything paper.pdf --mode local:qwen3:4b --body # headings plus section text
95
+ ```
96
+
97
+ The result goes to stdout (or `-o FILE`), a one-line summary with the cost to stderr. Exit codes:
98
+ 0 done, 2 configuration (for example no API key), 3 refused by the cost cap, 4 the PDF could not
99
+ be read. API keys are read from the environment only, never from the command line.
100
+
101
+ ## Output
102
+
103
+ `tree.sections` is a list of dicts in reading order:
104
+
105
+ | Key | Meaning |
106
+ |---|---|
107
+ | `number`, `title` | numbering as printed (`"2.3"`, `"Chapter 4"`, or `""`) and the heading text |
108
+ | `level` | 1 = top level, 2 = its subsections, ... |
109
+ | `page_start`, `page_end` | 1-based physical pages |
110
+ | `start`, `end` | character range of the section's own text in `tree.text` (up to the next heading) |
111
+ | `flags` | `doc_title` (the document's own title), `front_matter` (text before the first heading), `generated_title` (`standard` wrote a title for text that has no printed heading), and checks such as `start_marker_fuzzy`, `title_not_in_text`, `end_mismatch` |
112
+
113
+ - `tree.to_markdown()`: the document title as `#`, every other heading as `#` x (level + 1),
114
+ capped at six. `to_markdown(body=True)` adds each section's text, reflowed into paragraphs,
115
+ with running headers and footers removed.
116
+ - `tree.to_json()` / `tree.to_dict()`: the sections plus mode, model, pages, calls, tokens,
117
+ cost and any downgrades.
118
+ - `tree.extraction` holds the lines with their boxes (PDF points), for highlighting.
119
+
120
+ ## Configuration
121
+
122
+ Every setting can be passed in code or set as an environment variable `SECTIONANY_<NAME>`.
123
+ Arguments win over the environment. **No `.env` file is read, and nothing is ever written to
124
+ `os.environ`.**
125
+
126
+ | Setting | Default | |
127
+ |---|---|---|
128
+ | `SECTIONANY_API_KEY` / `api_key=` | (none) | Falls back to `OPENAI_API_KEY` only while `base_url` is OpenAI's own endpoint |
129
+ | `SECTIONANY_BASE_URL` / `base_url=` | `https://api.openai.com/v1` | Any OpenAI-compatible endpoint with JSON-schema outputs; always passed explicitly to the client |
130
+ | `SECTIONANY_QUICK_MODEL`, `SECTIONANY_STANDARD_MODEL` / `model=` | `gpt-6-luna`, `gpt-6.1-sol` | |
131
+ | `SECTIONANY_LOCAL_MODEL` | (none) | Ollama tag for `local` |
132
+ | `SECTIONANY_OLLAMA_BASE_URL` | `http://localhost:11434/v1` | |
133
+ | `SECTIONANY_PRICES` / `prices=` | built-in list | JSON `{"model": {"input": 2.0, "output": 10.0, "cached": 0.1}}`, USD per 1M tokens, merged over the built-in list |
134
+ | `SECTIONANY_MAX_USD_PER_DOC` / `max_usd=` | `0.50` | hard per-document cap |
135
+ | `SECTIONANY_OVER_BUDGET` / `over_budget=` | `downgrade` | or `fail` |
136
+ | `SECTIONANY_MAX_PAGES`, `SECTIONANY_MAX_CHARS`, `SECTIONANY_MAX_MB` | 500, 5,000,000, 100 | refused above these |
137
+ | `SECTIONANY_DEMOTE_UNLISTED_HEADINGS` / `demote_unlisted_headings=` | `["free"]` | modes in which sections that a complete-looking PDF outline does not list are dropped (JSON list; `[]` turns it off) |
138
+ | `SECTIONANY_EXTRACT_TIMEOUT_SECONDS` / `extract_timeout=` | 120 | extraction worker is killed after this |
139
+ | `SECTIONANY_EXTRACT_MEMORY_MB` | 4096 | worker memory limit (Linux only; 0 = none) |
140
+ | `SECTIONANY_ISOLATE_EXTRACTION` | `true` | run extraction in a separate process |
141
+ | `SECTIONANY_DEMOTE_UNLISTED_HEADINGS` | `[]` (off) | JSON list of modes (`free`, `quick`, `standard`): when the PDF's bookmarks look complete, drop sections they do not list (`section_anything.outline_check`) |
142
+ | `SECTIONANY_LLM_TIMEOUT_SECONDS`, `SECTIONANY_LOCAL_TIMEOUT_SECONDS` | 300, 600 | per model call |
143
+ | `SECTIONANY_STORE_PROMPTS` | `false` | keep prompt text in call records passed to a `Usage(sink=...)` |
144
+ | `SECTIONANY_LANGFUSE` | `false` | trace calls with Langfuse (needs the `langfuse` extra and Langfuse's own keys) |
145
+
146
+ Or build a `Settings` object once: `section(pdf, "quick", settings=Settings(max_usd_per_doc=1.0))`.
147
+ Async code can `await section_anything.asection(...)`.
148
+
149
+ ## Costs and caps
150
+
151
+ - **Unknown prices are refused.** A cloud model with no price (built-in, `SECTIONANY_PRICES` or
152
+ `prices=`) is refused before the PDF is read, so the cap can always be enforced. Local models
153
+ are free.
154
+ - **Estimate first.** Before a paid mode runs, its cost is estimated from the document. Over
155
+ `max_usd`, the run is downgraded (standard -> quick -> free) and the downgrade is reported in
156
+ `tree.downgraded`, or refused with `CostCapExceeded` when `over_budget="fail"`.
157
+ - **Hard cap while running.** The cap is re-checked before every model call, and each call's
158
+ output tokens are limited to what the remaining budget can pay for. A downgrade continues the
159
+ same budget. The SDK's own retries are off; one retry on an unusable answer is counted.
160
+ - The built-in prices are list prices from October 2026. Check your provider's prices and
161
+ override them with `SECTIONANY_PRICES`.
162
+
163
+ ## Handling untrusted PDFs
164
+
165
+ - File size and page count are checked first, from the PDF's page tree, without parsing any
166
+ page content.
167
+ - Text extraction runs in a separate Python process: the text size is counted (PDFium) before
168
+ layout analysis starts, the process is killed at the time limit, has a memory limit on Linux,
169
+ runs in an empty temporary directory, and inherits no API keys. It returns JSON, not pickles.
170
+ - Document text is treated as untrusted in every prompt; model output is validated against a
171
+ schema and clipped (strings to 300 characters, lists to 2,000 items). In `quick`, a heading
172
+ title the model rewrote is replaced by the printed line; in `standard`, titles the model wrote
173
+ for headingless text are flagged `generated_title`.
174
+ - Log messages and errors name the error type, HTTP status and error code, never prompt or
175
+ response text.
176
+
177
+ ## Benchmarks (summary)
178
+
179
+ Heading-tree similarity (TEDS, 0-100, higher is better) with
180
+ [READoc](https://github.com/icip-cas/READoc)'s own scoring code, October 2026. The full tables,
181
+ methods and per-document results are in the repository: `site/data/results.js` (rendered by the
182
+ project site in `site/`) and `corpus/results/`.
183
+
184
+ | READoc arXiv papers not used during development | Docs | Score |
185
+ |---|---|---|
186
+ | Section Anything `standard` (gpt-6-luna) | 905 | **70.0** |
187
+ | Section Anything `quick` (gpt-6-luna) | 905 | 63.9 |
188
+ | Section Anything `free` | 905 | 54.8 |
189
+ | Docling 2.140 (heading hierarchy on) | 905 | 49.4 |
190
+
191
+ On the 313 of those papers that MinerU's cloud service had processed: our `standard` 71.6,
192
+ MinerU + its LLM title levels (gpt-6.1-sol) 67.2 (+4.4 for us, 95% CI 2.5 to 6.4), our `quick`
193
+ 66.1, MinerU cloud alone 57.3, Docling 49.2.
194
+
195
+ On 1,112 bookmarked READoc GitHub READMEs not used in development, `free` scores 81.9 against
196
+ Docling's 75.5. On 27 UK government reports never used in development (answer keys from each report's HTML version), the outline check improved `free` by +5.7 (95% CI +0.4 to +12.2; 43.1 → 48.8).
197
+
198
+ Where others win: our `quick` and `standard` only tie with Docling on READMEs (about 75); Nougat, an OCR model trained on arXiv, scores far higher
199
+ on arXiv papers (88.5, published).
200
+
201
+ ## Limitations
202
+
203
+ - Reads the PDF's text layer. Scanned PDFs need OCR first.
204
+ - Tables, figures and equations are not structured; their text is part of the section text.
205
+ - `free` relies on bookmarks or a printed table of contents for its best results; without them it
206
+ is weaker than `quick` on papers. When the bookmarks look complete it drops headings they do not
207
+ list, so bookmarks that stop at the top levels lose real deeper headings (about 6% of READMEs
208
+ lose more than 5 points); set `SECTIONANY_DEMOTE_UNLISTED_HEADINGS='[]'` to turn this off.
209
+ - `quick` and `standard` send text to the provider you configure; results vary slightly between
210
+ runs.
211
+ - `local` uses Ollama's OpenAI-compatible endpoint, whose default context is small (4k tokens on
212
+ most laptops) and truncates silently. Candidate batches are kept small, but give the model a
213
+ larger context (for example a Modelfile with `num_ctx 8192`) for long documents. Quality with
214
+ local models has not been measured.
215
+ - Python 3.11 or newer.
216
+
217
+ ## Licence
218
+
219
+ Apache-2.0. See `LICENSE` and `NOTICE`.
@@ -0,0 +1,182 @@
1
+ # section-anything
2
+
3
+ > **Pre-release (0.1).** The API may change before 1.0.
4
+
5
+ Find the sections of a PDF: every heading, its level, the pages it spans and its exact
6
+ character range in the extracted text. One call, with a dial from free rules to an LLM that
7
+ reads the whole document, and a hard cost cap on every paid run.
8
+
9
+ ```python
10
+ import section_anything
11
+
12
+ tree = section_anything.section("paper.pdf", mode="quick")
13
+ print(tree.to_markdown())
14
+ # # A Study of Sectioning
15
+ # ## 1 Introduction
16
+ # ### 1.1 Scope
17
+ # ## 2 Methods
18
+ print(tree.sections[1])
19
+ # {'number': '1', 'title': 'Introduction', 'level': 1, 'page_start': 1, 'page_end': 1,
20
+ # 'start': 22, 'end': 484, 'flags': []}
21
+ print(tree.summary()) # mode, model, pages, sections, calls, tokens, cost_usd, seconds
22
+ ```
23
+
24
+ ## Install
25
+
26
+ Python 3.11+:
27
+
28
+ ```sh
29
+ pip install section-anything
30
+ pip install "section-anything[langfuse]" # optional Langfuse tracing
31
+ # latest from GitHub:
32
+ pip install "git+https://github.com/Omniwot/section-anything#subdirectory=packages/section-anything"
33
+ # from a checkout of the repository:
34
+ pip install -e ./packages/section-anything
35
+ ```
36
+
37
+ Dependencies: pdfplumber and pdfminer.six (MIT), pypdfium2 (Apache-2.0 / BSD-3-Clause),
38
+ RapidFuzz (MIT), openai (Apache-2.0), pydantic and pydantic-settings (MIT). No PyMuPDF (AGPL).
39
+
40
+ ## Modes
41
+
42
+ | Mode | What runs | Sent to a model | Cost per 1,000 pages |
43
+ |---|---|---|---|
44
+ | `free` (default) | PDF bookmarks or the printed table of contents as the outline, then typography and numbering rules; headings a complete-looking outline does not list are dropped | nothing | $0 |
45
+ | `quick` | the rules propose candidate heading lines; a small model keeps the real ones and sets levels | candidate lines and a 70-character peek at the next line | about $0.07 (`gpt-6-luna`) |
46
+ | `standard` | a model reads every line, with font hints, and marks where sections start and end | the document text | about $0.16 (`gpt-6-luna`), $2.90 (`gpt-6.1-sol`, the default) |
47
+ | `local:<model>` | `quick`, answered by a local [Ollama](https://ollama.com) model | nothing leaves the machine | $0 |
48
+
49
+ Costs are measured averages at the built-in list prices; your documents may differ.
50
+
51
+ ## Command line
52
+
53
+ ```sh
54
+ section-anything paper.pdf # free, Markdown headings
55
+ section-anything paper.pdf --mode quick --format json # JSON with spans and cost
56
+ section-anything paper.pdf --mode standard --max-usd 0.5 # cap this document at $0.50
57
+ section-anything paper.pdf --mode local:qwen3:4b --body # headings plus section text
58
+ ```
59
+
60
+ The result goes to stdout (or `-o FILE`), a one-line summary with the cost to stderr. Exit codes:
61
+ 0 done, 2 configuration (for example no API key), 3 refused by the cost cap, 4 the PDF could not
62
+ be read. API keys are read from the environment only, never from the command line.
63
+
64
+ ## Output
65
+
66
+ `tree.sections` is a list of dicts in reading order:
67
+
68
+ | Key | Meaning |
69
+ |---|---|
70
+ | `number`, `title` | numbering as printed (`"2.3"`, `"Chapter 4"`, or `""`) and the heading text |
71
+ | `level` | 1 = top level, 2 = its subsections, ... |
72
+ | `page_start`, `page_end` | 1-based physical pages |
73
+ | `start`, `end` | character range of the section's own text in `tree.text` (up to the next heading) |
74
+ | `flags` | `doc_title` (the document's own title), `front_matter` (text before the first heading), `generated_title` (`standard` wrote a title for text that has no printed heading), and checks such as `start_marker_fuzzy`, `title_not_in_text`, `end_mismatch` |
75
+
76
+ - `tree.to_markdown()`: the document title as `#`, every other heading as `#` x (level + 1),
77
+ capped at six. `to_markdown(body=True)` adds each section's text, reflowed into paragraphs,
78
+ with running headers and footers removed.
79
+ - `tree.to_json()` / `tree.to_dict()`: the sections plus mode, model, pages, calls, tokens,
80
+ cost and any downgrades.
81
+ - `tree.extraction` holds the lines with their boxes (PDF points), for highlighting.
82
+
83
+ ## Configuration
84
+
85
+ Every setting can be passed in code or set as an environment variable `SECTIONANY_<NAME>`.
86
+ Arguments win over the environment. **No `.env` file is read, and nothing is ever written to
87
+ `os.environ`.**
88
+
89
+ | Setting | Default | |
90
+ |---|---|---|
91
+ | `SECTIONANY_API_KEY` / `api_key=` | (none) | Falls back to `OPENAI_API_KEY` only while `base_url` is OpenAI's own endpoint |
92
+ | `SECTIONANY_BASE_URL` / `base_url=` | `https://api.openai.com/v1` | Any OpenAI-compatible endpoint with JSON-schema outputs; always passed explicitly to the client |
93
+ | `SECTIONANY_QUICK_MODEL`, `SECTIONANY_STANDARD_MODEL` / `model=` | `gpt-6-luna`, `gpt-6.1-sol` | |
94
+ | `SECTIONANY_LOCAL_MODEL` | (none) | Ollama tag for `local` |
95
+ | `SECTIONANY_OLLAMA_BASE_URL` | `http://localhost:11434/v1` | |
96
+ | `SECTIONANY_PRICES` / `prices=` | built-in list | JSON `{"model": {"input": 2.0, "output": 10.0, "cached": 0.1}}`, USD per 1M tokens, merged over the built-in list |
97
+ | `SECTIONANY_MAX_USD_PER_DOC` / `max_usd=` | `0.50` | hard per-document cap |
98
+ | `SECTIONANY_OVER_BUDGET` / `over_budget=` | `downgrade` | or `fail` |
99
+ | `SECTIONANY_MAX_PAGES`, `SECTIONANY_MAX_CHARS`, `SECTIONANY_MAX_MB` | 500, 5,000,000, 100 | refused above these |
100
+ | `SECTIONANY_DEMOTE_UNLISTED_HEADINGS` / `demote_unlisted_headings=` | `["free"]` | modes in which sections that a complete-looking PDF outline does not list are dropped (JSON list; `[]` turns it off) |
101
+ | `SECTIONANY_EXTRACT_TIMEOUT_SECONDS` / `extract_timeout=` | 120 | extraction worker is killed after this |
102
+ | `SECTIONANY_EXTRACT_MEMORY_MB` | 4096 | worker memory limit (Linux only; 0 = none) |
103
+ | `SECTIONANY_ISOLATE_EXTRACTION` | `true` | run extraction in a separate process |
104
+ | `SECTIONANY_DEMOTE_UNLISTED_HEADINGS` | `[]` (off) | JSON list of modes (`free`, `quick`, `standard`): when the PDF's bookmarks look complete, drop sections they do not list (`section_anything.outline_check`) |
105
+ | `SECTIONANY_LLM_TIMEOUT_SECONDS`, `SECTIONANY_LOCAL_TIMEOUT_SECONDS` | 300, 600 | per model call |
106
+ | `SECTIONANY_STORE_PROMPTS` | `false` | keep prompt text in call records passed to a `Usage(sink=...)` |
107
+ | `SECTIONANY_LANGFUSE` | `false` | trace calls with Langfuse (needs the `langfuse` extra and Langfuse's own keys) |
108
+
109
+ Or build a `Settings` object once: `section(pdf, "quick", settings=Settings(max_usd_per_doc=1.0))`.
110
+ Async code can `await section_anything.asection(...)`.
111
+
112
+ ## Costs and caps
113
+
114
+ - **Unknown prices are refused.** A cloud model with no price (built-in, `SECTIONANY_PRICES` or
115
+ `prices=`) is refused before the PDF is read, so the cap can always be enforced. Local models
116
+ are free.
117
+ - **Estimate first.** Before a paid mode runs, its cost is estimated from the document. Over
118
+ `max_usd`, the run is downgraded (standard -> quick -> free) and the downgrade is reported in
119
+ `tree.downgraded`, or refused with `CostCapExceeded` when `over_budget="fail"`.
120
+ - **Hard cap while running.** The cap is re-checked before every model call, and each call's
121
+ output tokens are limited to what the remaining budget can pay for. A downgrade continues the
122
+ same budget. The SDK's own retries are off; one retry on an unusable answer is counted.
123
+ - The built-in prices are list prices from October 2026. Check your provider's prices and
124
+ override them with `SECTIONANY_PRICES`.
125
+
126
+ ## Handling untrusted PDFs
127
+
128
+ - File size and page count are checked first, from the PDF's page tree, without parsing any
129
+ page content.
130
+ - Text extraction runs in a separate Python process: the text size is counted (PDFium) before
131
+ layout analysis starts, the process is killed at the time limit, has a memory limit on Linux,
132
+ runs in an empty temporary directory, and inherits no API keys. It returns JSON, not pickles.
133
+ - Document text is treated as untrusted in every prompt; model output is validated against a
134
+ schema and clipped (strings to 300 characters, lists to 2,000 items). In `quick`, a heading
135
+ title the model rewrote is replaced by the printed line; in `standard`, titles the model wrote
136
+ for headingless text are flagged `generated_title`.
137
+ - Log messages and errors name the error type, HTTP status and error code, never prompt or
138
+ response text.
139
+
140
+ ## Benchmarks (summary)
141
+
142
+ Heading-tree similarity (TEDS, 0-100, higher is better) with
143
+ [READoc](https://github.com/icip-cas/READoc)'s own scoring code, October 2026. The full tables,
144
+ methods and per-document results are in the repository: `site/data/results.js` (rendered by the
145
+ project site in `site/`) and `corpus/results/`.
146
+
147
+ | READoc arXiv papers not used during development | Docs | Score |
148
+ |---|---|---|
149
+ | Section Anything `standard` (gpt-6-luna) | 905 | **70.0** |
150
+ | Section Anything `quick` (gpt-6-luna) | 905 | 63.9 |
151
+ | Section Anything `free` | 905 | 54.8 |
152
+ | Docling 2.140 (heading hierarchy on) | 905 | 49.4 |
153
+
154
+ On the 313 of those papers that MinerU's cloud service had processed: our `standard` 71.6,
155
+ MinerU + its LLM title levels (gpt-6.1-sol) 67.2 (+4.4 for us, 95% CI 2.5 to 6.4), our `quick`
156
+ 66.1, MinerU cloud alone 57.3, Docling 49.2.
157
+
158
+ On 1,112 bookmarked READoc GitHub READMEs not used in development, `free` scores 81.9 against
159
+ Docling's 75.5. On 27 UK government reports never used in development (answer keys from each report's HTML version), the outline check improved `free` by +5.7 (95% CI +0.4 to +12.2; 43.1 → 48.8).
160
+
161
+ Where others win: our `quick` and `standard` only tie with Docling on READMEs (about 75); Nougat, an OCR model trained on arXiv, scores far higher
162
+ on arXiv papers (88.5, published).
163
+
164
+ ## Limitations
165
+
166
+ - Reads the PDF's text layer. Scanned PDFs need OCR first.
167
+ - Tables, figures and equations are not structured; their text is part of the section text.
168
+ - `free` relies on bookmarks or a printed table of contents for its best results; without them it
169
+ is weaker than `quick` on papers. When the bookmarks look complete it drops headings they do not
170
+ list, so bookmarks that stop at the top levels lose real deeper headings (about 6% of READMEs
171
+ lose more than 5 points); set `SECTIONANY_DEMOTE_UNLISTED_HEADINGS='[]'` to turn this off.
172
+ - `quick` and `standard` send text to the provider you configure; results vary slightly between
173
+ runs.
174
+ - `local` uses Ollama's OpenAI-compatible endpoint, whose default context is small (4k tokens on
175
+ most laptops) and truncates silently. Candidate batches are kept small, but give the model a
176
+ larger context (for example a Modelfile with `num_ctx 8192`) for long documents. Quality with
177
+ local models has not been measured.
178
+ - Python 3.11 or newer.
179
+
180
+ ## Licence
181
+
182
+ Apache-2.0. See `LICENSE` and `NOTICE`.