Metadata-Version: 2.5
Name: snaprag
Version: 0.1.0
Summary: Local, CPU-only RAG with two core calls: index() and retrieve().
License-Expression: MIT
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: chromadb<1.6,>=1.5.9
Requires-Dist: fastembed<0.10,>=0.9.1
Requires-Dist: snaprag-model==1.0.0
Requires-Dist: tokenizers<0.24,>=0.23
Requires-Dist: xberg<1.6,>=1.5.4
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# snaprag

![snaprag](https://raw.githubusercontent.com/Dipanshu3108/snaprag/main/assets/banner.png)

Local, CPU-only retrieval for RAG: `index()` your documents, then `retrieve()` the relevant chunks.
Parsing uses [xberg](https://github.com/xberg-io/xberg), embeddings use fastembed and storage uses ChromaDB.
The embedding model (`bge-small-en-v1.5`, for English) is installed by pip, so nothing is downloaded the first time you run it.

## Install

```powershell
pip install snaprag
```

Requires Python 3.11 or later. Tested on Windows with Python 3.13.

## Install from source

Name both folders in one command, so pip takes the model package from disk:

```powershell
python -m pip install -e .\model_package -e ".[dev]"
```

Python 3.11 or later. In a fresh clone, first run `python model_package/fetch_model.py` to restore the model files.

## Quick start

```python
from snaprag import index, retrieve

result = index("handbook.pdf")
print(result.file_ids)          # for example ['handbook_483920184756']

for hit in retrieve("How many leave days carry over?"):
    print(hit.file_name, hit.page, hit.page_end, hit.text)  # page numbers are for PDFs
```

## `index()`

| Argument | Default | Meaning |
|---|---|---|
| `file_path` | | One file. Pass this or `folder_path`. |
| `folder_path` | | Every file in a folder. |
| `file_id` | generated | Your ID for a single file. Not allowed with `folder_path`. |
| `metadata` | `None` | Added to every chunk, and embedded with its text. |
| `collection_name` | `"default"` | 3 to 512 characters: letters, digits, `.`, `_`, `-`. |
| `recursive` | `True` | Include subfolders. |
| `ocr_images` | `False` | Also read the text in pictures inside documents. Much slower. See [OCR](#ocr). |
| `db_path` | `./.snaprag` | Where the database lives. |

It returns an `IndexResult` with `indexed`, `skipped`, `failed`, `file_ids` and `ok`.
Wrong arguments raise an error. A file that cannot be indexed does **not** raise: check `result.failed`.

- The generated ID is the first word of the file name plus 12 random digits.
- Indexing a file again skips it if its content, metadata and index settings, including `ocr_images`, are unchanged. Otherwise its chunks are replaced and it keeps its `file_id`.
- Pass the same `metadata` and `ocr_images` each time. Leaving them out means no metadata and no image OCR, so the file is indexed again without them.
- If re-indexing fails, the previous version stays searchable.
- Files are identified by their full path. A moved or renamed file counts as a new file.
- Deleting a file from disk does not remove it from the index. Use `delete()`.
- Folder indexing skips hidden files and folders (names starting with `.`) and Office lock files (`~$`). Everything else is attempted, so point it at a document folder, not a whole code project.

Metadata values can be `str`, `int`, `float`, `bool`, or a non-empty list of one of these types.
`None` and nested dictionaries are rejected, as are these reserved keys:
`file_id`, `file_name`, `source_path`, `chunk_index`, `chunk_count`, `fingerprint`, `heading`, `page`, `page_end`.
Embedded metadata is limited to 200 tokens.

## `retrieve()`

| Argument | Default | Meaning |
|---|---|---|
| `query` | | The question or search text. |
| `file_id` | `None` | One ID or a list. `None` searches everything; an empty list is an error. |
| `collection_name` | `"default"` | Collection to search. |
| `top_k` | `20` | Number of chunks to return. |
| `metadata_filter` | `None` | All conditions must match. |
| `mode` | `"hybrid"` | `"hybrid"` searches by meaning and by keyword. `"vector"` searches by meaning only. |
| `db_path` | `./.snaprag` | Where the database lives. |

```python
retrieve("travel limits", metadata_filter={"team": "hr"})              # equals
retrieve("travel limits", metadata_filter={"year": [2024, 2025]})      # any of
retrieve("travel limits", metadata_filter={"year": {"$gte": 2024}})    # operator
```

Each result has `text`, `score`, `similarity`, `file_id`, `file_name`, `source_path`, `chunk_index`,
`heading`, `page`, `page_end` and `metadata`.

- `page` and `page_end` are the first and last page of the chunk, counting from 1. They are set for PDF files only.
  When citing a result, show the whole range.
- `score` is what results are ordered by, higher first. In `"hybrid"` mode it only ranks results:
  it is not a measure of confidence, so do not use a fixed cutoff.
- `similarity` is how close the chunk's meaning is to the query (cosine similarity). It means the same in both modes.

### Hybrid search

Hybrid search combines the best matches by meaning with the best matches by keyword (reciprocal rank fusion).
Keyword search helps with names, codes and exact terms. It looks at the chunk text, headings and your metadata,
and ignores case and accents. It does not match other forms of a word: "invoices" does not match "invoice".

## OCR

- Scanned pages and image files are read with OCR by default.
- Pictures inside a page that also has real text, such as a pasted table or chart, are **not** read by default.
  Use `index(path, ocr_images=True)` for them.
- Check any figure that came from OCR: it can misread digits.

## Managing files and settings

```python
from snaprag import SnapRAG

rag = SnapRAG("data/my-index")   # a fixed path, recommended for deployed apps
rag.index(folder_path="docs", metadata={"team": "hr"})
rag.list_files()
rag.delete("handbook_483920184756")
```

The functions `index`, `retrieve`, `list_files` and `delete` do the same using `db_path`.

The default database is `.snaprag/` in the **current working directory**, which is not necessarily your project root.
Importing the package creates nothing, and only `index()` creates a database.
Only one process should write to a database at a time.

## License

[MIT](https://github.com/Dipanshu3108/snaprag/blob/main/LICENSE). The bundled model files in `snaprag-model` have their own
[MIT license](https://github.com/Dipanshu3108/snaprag/blob/main/model_package/src/snaprag_model/MODEL_LICENSE.txt).
