Metadata-Version: 2.4
Name: section-anything-haystack
Version: 0.1.0
Summary: Haystack converter for Section Anything: one Document per PDF section, with its heading path, pages and character span.
Author: The Section Anything Authors
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/Omniwot/section-anything/tree/main/packages/section-anything-haystack
Project-URL: Repository, https://github.com/Omniwot/section-anything
Project-URL: Issues, https://github.com/Omniwot/section-anything/issues
Keywords: haystack,converter,pdf,sections,headings,rag,chunking
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Text Processing :: General
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: section-anything<0.2,>=0.1.13
Requires-Dist: haystack-ai<4,>=2.20
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Dynamic: license-file

# section-anything-haystack

A Haystack converter for [Section Anything](https://github.com/Omniwot/section-anything): it
finds the sections of a PDF (every heading, its level, its pages and its exact text) and returns
**one `Document` per section**, with the heading path in the metadata. The default mode runs
locally with rules only, calls no model and costs nothing.

## Install

```sh
pip install section-anything-haystack
# latest from GitHub:
pip install "git+https://github.com/Omniwot/section-anything#subdirectory=packages/section-anything-haystack"
```

Python 3.11+. Depends on `section-anything` and `haystack-ai` (2.20 or newer, 3.x included) only.

## Example

```python
from haystack_integrations.components.converters.section_anything import SectionAnythingConverter

converter = SectionAnythingConverter()  # mode="free": rules only, no model, $0
docs = converter.run(sources=["paper.pdf"])["documents"]  # file paths or ByteStreams

doc = docs[2]
print(repr(doc.content[:59]))    # '### 1.1 Scope\n\nSectioning splits a long document into parts'
print(doc.meta["heading_path"])  # 1 Introduction > 1.1 Scope
print(doc.meta["page_start"], doc.meta["page_end"])  # 1 1
```

In an indexing pipeline, with sections split at 1,500 characters:

```python
from haystack import Pipeline
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.components.writers import DocumentWriter
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack_integrations.components.converters.section_anything import SectionAnythingConverter

store = InMemoryDocumentStore()
indexing = Pipeline()
indexing.add_component("converter", SectionAnythingConverter(chunk={"max_chars": 1500}))
indexing.add_component("writer", DocumentWriter(document_store=store))
indexing.connect("converter.documents", "writer.documents")
print(indexing.run({"converter": {"sources": ["paper.pdf"]}}))  # {'writer': {'documents_written': 6}}

hit = InMemoryBM25Retriever(document_store=store).run(query="data")["documents"][0]
print(hit.meta["heading_path"], hit.meta["page_start"])  # 2 Methods > 2.1 Data 2
```

To embed each section with its place in the document, give the embedder
`meta_fields_to_embed=["heading_path"]`; with `chunk`, the text already starts with the heading path.
Pipelines that use the converter save and load as YAML (`Pipeline.dumps`, `Pipeline.loads`): it lives
in the `haystack_integrations` namespace, which Haystack 3 trusts by default, and an API key is
saved only as the name of its environment variable.

## Options

`SectionAnythingConverter(mode="free", *, include_heading=True, chunk=False, store_full_path=False, api_key=None, section_kwargs=None)`,
then `run(sources, meta=None)` (also `run_async`).

- `mode`: `free` (bookmarks, table of contents and typography rules; nothing leaves the machine),
  `quick` (a small model reviews candidate heading lines, about $0.07 per 1,000 pages),
  `standard` (a model reads every line), `auto` (free, then quick when Free is unsure) or
  `local:<ollama model>`. Over the per-document cost cap (default $0.50) a run is downgraded
  (standard → quick → free) or refused.
- `include_heading`: start each Document with its heading as a Markdown line (`## 1 Introduction`).
  With `False`, sections with no text of their own (a heading directly followed by a subheading)
  are skipped.
- `chunk`: size-capped chunks instead of whole sections (`SectionTree.chunks`): `True` for its
  defaults (at most 2,000 characters, sibling sections under 200 merged), or a dict of its options
  (`max_chars`, `min_chars`, `overlap_chars`, `length`, `prefix`, `lead_in`). Each Document's text
  then starts with the chunk's heading path (`3 Method > 3.1 Data`) unless `prefix` is `False`, and
  its metadata adds `chunk_index` and `lead_in`. `lead_in` is off by default; with `True`, a chunk
  that starts inside a list carries the line that introduces the list, for example "Apply the
  following changes to the method:", in its `lead_in` metadata and, with `prefix`, in its text under
  the heading path.
- `store_full_path`: keep each source's full path in `file_path`; by default only the file name.
- `api_key`: for the paid modes, a `Secret` (`Secret.from_env_var("SECTIONANY_API_KEY")`), so the
  key is never written to a pipeline file. By default the library reads its own environment
  variables (`SECTIONANY_API_KEY`, or `OPENAI_API_KEY`, or `ANTHROPIC_API_KEY` for Claude models).
  Keys are never logged or put in metadata.
- `section_kwargs`: other options for `section_anything.section`: `model`, `base_url`, `provider`,
  `max_usd`, `prices`, `over_budget`, `max_pages`, `extract_timeout`, `progress`, `settings`.
  Anything not given falls back to the `SECTIONANY_*` environment variables; see the
  [library README](https://github.com/Omniwot/section-anything/tree/main/packages/section-anything#configuration).
  Unknown option names fail when the converter is built, not after a PDF is read.

A source that cannot be sectioned (not a PDF, damaged, over a size cap, no text layer, a failed
model call) is skipped with a warning, as Haystack's other converters do. A configuration error
(unknown mode, no API key, a model with no price) is raised, since it would fail every source.

## Text and metadata

A Document's text is the section's own text, from its heading to the next heading, reflowed into
paragraphs with running headers and footers removed (the same text as `section-anything --body`).
Text before the first heading is a Document of its own (flag `front_matter`).

Metadata is flat (str, int, float or None), so it works with every document store and with an
embedder's `meta_fields_to_embed`. A ByteStream's own `meta` and the `meta` passed to `run` are
kept; the keys below take precedence over them.

| Key | Meaning |
|---|---|
| `file_path` | the PDF's file name (its path with `store_full_path=True`), or a ByteStream's own `file_path` |
| `section_index` | position in the document's section list (0-based) |
| `title`, `number`, `level` | heading text, numbering as printed (`"3.1"` or `""`), 1 = top level |
| `heading_path` | headings from the outermost section down to this one, joined with `" > "` |
| `page_start`, `page_end` | 1-based pages; `page_number` repeats `page_start`, under the key Haystack's splitters use |
| `heading_page`, `heading_bbox` | where the heading is printed: its page and `"x0,y0,x1,y1"` in PDF points from the page's bottom-left corner (None when nothing is printed) |
| `start`, `end` | character range in the library's extracted text |
| `flags` | comma-separated, for example `doc_title`, `front_matter`, `generated_title` |
| `document_title` | the document's title, if found |
| `mode`, `model`, `document_cost_usd` | how the document was sectioned (after any downgrade) and what the whole document cost |

To cap sizes, use `chunk` rather than a `DocumentSplitter` after the converter: chunks keep their
own pages and heading path, while `DocumentSplitter` counts `page_number` from 1 again in each
Document it splits.

## Licence

Apache-2.0. See `LICENSE` and `NOTICE`.
