snaprag 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.
@@ -0,0 +1,13 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .pytest_cache/
8
+ .snaprag/
9
+
10
+
11
+ model_package/src/snaprag_model/files/
12
+
13
+ notes.md
snaprag-0.1.0/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright 2026 Dipanshu Singh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
snaprag-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.5
2
+ Name: snaprag
3
+ Version: 0.1.0
4
+ Summary: Local, CPU-only RAG with two core calls: index() and retrieve().
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: chromadb<1.6,>=1.5.9
9
+ Requires-Dist: fastembed<0.10,>=0.9.1
10
+ Requires-Dist: snaprag-model==1.0.0
11
+ Requires-Dist: tokenizers<0.24,>=0.23
12
+ Requires-Dist: xberg<1.6,>=1.5.4
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=8; extra == 'dev'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # snaprag
18
+
19
+ ![snaprag](https://raw.githubusercontent.com/Dipanshu3108/snaprag/main/assets/banner.png)
20
+
21
+ Local, CPU-only retrieval for RAG: `index()` your documents, then `retrieve()` the relevant chunks.
22
+ Parsing uses [xberg](https://github.com/xberg-io/xberg), embeddings use fastembed and storage uses ChromaDB.
23
+ The embedding model (`bge-small-en-v1.5`, for English) is installed by pip, so nothing is downloaded the first time you run it.
24
+
25
+ ## Install
26
+
27
+ ```powershell
28
+ pip install snaprag
29
+ ```
30
+
31
+ Requires Python 3.11 or later. Tested on Windows with Python 3.13.
32
+
33
+ ## Install from source
34
+
35
+ Name both folders in one command, so pip takes the model package from disk:
36
+
37
+ ```powershell
38
+ python -m pip install -e .\model_package -e ".[dev]"
39
+ ```
40
+
41
+ Python 3.11 or later. In a fresh clone, first run `python model_package/fetch_model.py` to restore the model files.
42
+
43
+ ## Quick start
44
+
45
+ ```python
46
+ from snaprag import index, retrieve
47
+
48
+ result = index("handbook.pdf")
49
+ print(result.file_ids) # for example ['handbook_483920184756']
50
+
51
+ for hit in retrieve("How many leave days carry over?"):
52
+ print(hit.file_name, hit.page, hit.page_end, hit.text) # page numbers are for PDFs
53
+ ```
54
+
55
+ ## `index()`
56
+
57
+ | Argument | Default | Meaning |
58
+ |---|---|---|
59
+ | `file_path` | | One file. Pass this or `folder_path`. |
60
+ | `folder_path` | | Every file in a folder. |
61
+ | `file_id` | generated | Your ID for a single file. Not allowed with `folder_path`. |
62
+ | `metadata` | `None` | Added to every chunk, and embedded with its text. |
63
+ | `collection_name` | `"default"` | 3 to 512 characters: letters, digits, `.`, `_`, `-`. |
64
+ | `recursive` | `True` | Include subfolders. |
65
+ | `ocr_images` | `False` | Also read the text in pictures inside documents. Much slower. See [OCR](#ocr). |
66
+ | `db_path` | `./.snaprag` | Where the database lives. |
67
+
68
+ It returns an `IndexResult` with `indexed`, `skipped`, `failed`, `file_ids` and `ok`.
69
+ Wrong arguments raise an error. A file that cannot be indexed does **not** raise: check `result.failed`.
70
+
71
+ - The generated ID is the first word of the file name plus 12 random digits.
72
+ - 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`.
73
+ - 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.
74
+ - If re-indexing fails, the previous version stays searchable.
75
+ - Files are identified by their full path. A moved or renamed file counts as a new file.
76
+ - Deleting a file from disk does not remove it from the index. Use `delete()`.
77
+ - 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.
78
+
79
+ Metadata values can be `str`, `int`, `float`, `bool`, or a non-empty list of one of these types.
80
+ `None` and nested dictionaries are rejected, as are these reserved keys:
81
+ `file_id`, `file_name`, `source_path`, `chunk_index`, `chunk_count`, `fingerprint`, `heading`, `page`, `page_end`.
82
+ Embedded metadata is limited to 200 tokens.
83
+
84
+ ## `retrieve()`
85
+
86
+ | Argument | Default | Meaning |
87
+ |---|---|---|
88
+ | `query` | | The question or search text. |
89
+ | `file_id` | `None` | One ID or a list. `None` searches everything; an empty list is an error. |
90
+ | `collection_name` | `"default"` | Collection to search. |
91
+ | `top_k` | `20` | Number of chunks to return. |
92
+ | `metadata_filter` | `None` | All conditions must match. |
93
+ | `mode` | `"hybrid"` | `"hybrid"` searches by meaning and by keyword. `"vector"` searches by meaning only. |
94
+ | `db_path` | `./.snaprag` | Where the database lives. |
95
+
96
+ ```python
97
+ retrieve("travel limits", metadata_filter={"team": "hr"}) # equals
98
+ retrieve("travel limits", metadata_filter={"year": [2024, 2025]}) # any of
99
+ retrieve("travel limits", metadata_filter={"year": {"$gte": 2024}}) # operator
100
+ ```
101
+
102
+ Each result has `text`, `score`, `similarity`, `file_id`, `file_name`, `source_path`, `chunk_index`,
103
+ `heading`, `page`, `page_end` and `metadata`.
104
+
105
+ - `page` and `page_end` are the first and last page of the chunk, counting from 1. They are set for PDF files only.
106
+ When citing a result, show the whole range.
107
+ - `score` is what results are ordered by, higher first. In `"hybrid"` mode it only ranks results:
108
+ it is not a measure of confidence, so do not use a fixed cutoff.
109
+ - `similarity` is how close the chunk's meaning is to the query (cosine similarity). It means the same in both modes.
110
+
111
+ ### Hybrid search
112
+
113
+ Hybrid search combines the best matches by meaning with the best matches by keyword (reciprocal rank fusion).
114
+ Keyword search helps with names, codes and exact terms. It looks at the chunk text, headings and your metadata,
115
+ and ignores case and accents. It does not match other forms of a word: "invoices" does not match "invoice".
116
+
117
+ ## OCR
118
+
119
+ - Scanned pages and image files are read with OCR by default.
120
+ - Pictures inside a page that also has real text, such as a pasted table or chart, are **not** read by default.
121
+ Use `index(path, ocr_images=True)` for them.
122
+ - Check any figure that came from OCR: it can misread digits.
123
+
124
+ ## Managing files and settings
125
+
126
+ ```python
127
+ from snaprag import SnapRAG
128
+
129
+ rag = SnapRAG("data/my-index") # a fixed path, recommended for deployed apps
130
+ rag.index(folder_path="docs", metadata={"team": "hr"})
131
+ rag.list_files()
132
+ rag.delete("handbook_483920184756")
133
+ ```
134
+
135
+ The functions `index`, `retrieve`, `list_files` and `delete` do the same using `db_path`.
136
+
137
+ The default database is `.snaprag/` in the **current working directory**, which is not necessarily your project root.
138
+ Importing the package creates nothing, and only `index()` creates a database.
139
+ Only one process should write to a database at a time.
140
+
141
+ ## License
142
+
143
+ [MIT](https://github.com/Dipanshu3108/snaprag/blob/main/LICENSE). The bundled model files in `snaprag-model` have their own
144
+ [MIT license](https://github.com/Dipanshu3108/snaprag/blob/main/model_package/src/snaprag_model/MODEL_LICENSE.txt).
@@ -0,0 +1,128 @@
1
+ # snaprag
2
+
3
+ ![snaprag](https://raw.githubusercontent.com/Dipanshu3108/snaprag/main/assets/banner.png)
4
+
5
+ Local, CPU-only retrieval for RAG: `index()` your documents, then `retrieve()` the relevant chunks.
6
+ Parsing uses [xberg](https://github.com/xberg-io/xberg), embeddings use fastembed and storage uses ChromaDB.
7
+ The embedding model (`bge-small-en-v1.5`, for English) is installed by pip, so nothing is downloaded the first time you run it.
8
+
9
+ ## Install
10
+
11
+ ```powershell
12
+ pip install snaprag
13
+ ```
14
+
15
+ Requires Python 3.11 or later. Tested on Windows with Python 3.13.
16
+
17
+ ## Install from source
18
+
19
+ Name both folders in one command, so pip takes the model package from disk:
20
+
21
+ ```powershell
22
+ python -m pip install -e .\model_package -e ".[dev]"
23
+ ```
24
+
25
+ Python 3.11 or later. In a fresh clone, first run `python model_package/fetch_model.py` to restore the model files.
26
+
27
+ ## Quick start
28
+
29
+ ```python
30
+ from snaprag import index, retrieve
31
+
32
+ result = index("handbook.pdf")
33
+ print(result.file_ids) # for example ['handbook_483920184756']
34
+
35
+ for hit in retrieve("How many leave days carry over?"):
36
+ print(hit.file_name, hit.page, hit.page_end, hit.text) # page numbers are for PDFs
37
+ ```
38
+
39
+ ## `index()`
40
+
41
+ | Argument | Default | Meaning |
42
+ |---|---|---|
43
+ | `file_path` | | One file. Pass this or `folder_path`. |
44
+ | `folder_path` | | Every file in a folder. |
45
+ | `file_id` | generated | Your ID for a single file. Not allowed with `folder_path`. |
46
+ | `metadata` | `None` | Added to every chunk, and embedded with its text. |
47
+ | `collection_name` | `"default"` | 3 to 512 characters: letters, digits, `.`, `_`, `-`. |
48
+ | `recursive` | `True` | Include subfolders. |
49
+ | `ocr_images` | `False` | Also read the text in pictures inside documents. Much slower. See [OCR](#ocr). |
50
+ | `db_path` | `./.snaprag` | Where the database lives. |
51
+
52
+ It returns an `IndexResult` with `indexed`, `skipped`, `failed`, `file_ids` and `ok`.
53
+ Wrong arguments raise an error. A file that cannot be indexed does **not** raise: check `result.failed`.
54
+
55
+ - The generated ID is the first word of the file name plus 12 random digits.
56
+ - 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`.
57
+ - 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.
58
+ - If re-indexing fails, the previous version stays searchable.
59
+ - Files are identified by their full path. A moved or renamed file counts as a new file.
60
+ - Deleting a file from disk does not remove it from the index. Use `delete()`.
61
+ - 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.
62
+
63
+ Metadata values can be `str`, `int`, `float`, `bool`, or a non-empty list of one of these types.
64
+ `None` and nested dictionaries are rejected, as are these reserved keys:
65
+ `file_id`, `file_name`, `source_path`, `chunk_index`, `chunk_count`, `fingerprint`, `heading`, `page`, `page_end`.
66
+ Embedded metadata is limited to 200 tokens.
67
+
68
+ ## `retrieve()`
69
+
70
+ | Argument | Default | Meaning |
71
+ |---|---|---|
72
+ | `query` | | The question or search text. |
73
+ | `file_id` | `None` | One ID or a list. `None` searches everything; an empty list is an error. |
74
+ | `collection_name` | `"default"` | Collection to search. |
75
+ | `top_k` | `20` | Number of chunks to return. |
76
+ | `metadata_filter` | `None` | All conditions must match. |
77
+ | `mode` | `"hybrid"` | `"hybrid"` searches by meaning and by keyword. `"vector"` searches by meaning only. |
78
+ | `db_path` | `./.snaprag` | Where the database lives. |
79
+
80
+ ```python
81
+ retrieve("travel limits", metadata_filter={"team": "hr"}) # equals
82
+ retrieve("travel limits", metadata_filter={"year": [2024, 2025]}) # any of
83
+ retrieve("travel limits", metadata_filter={"year": {"$gte": 2024}}) # operator
84
+ ```
85
+
86
+ Each result has `text`, `score`, `similarity`, `file_id`, `file_name`, `source_path`, `chunk_index`,
87
+ `heading`, `page`, `page_end` and `metadata`.
88
+
89
+ - `page` and `page_end` are the first and last page of the chunk, counting from 1. They are set for PDF files only.
90
+ When citing a result, show the whole range.
91
+ - `score` is what results are ordered by, higher first. In `"hybrid"` mode it only ranks results:
92
+ it is not a measure of confidence, so do not use a fixed cutoff.
93
+ - `similarity` is how close the chunk's meaning is to the query (cosine similarity). It means the same in both modes.
94
+
95
+ ### Hybrid search
96
+
97
+ Hybrid search combines the best matches by meaning with the best matches by keyword (reciprocal rank fusion).
98
+ Keyword search helps with names, codes and exact terms. It looks at the chunk text, headings and your metadata,
99
+ and ignores case and accents. It does not match other forms of a word: "invoices" does not match "invoice".
100
+
101
+ ## OCR
102
+
103
+ - Scanned pages and image files are read with OCR by default.
104
+ - Pictures inside a page that also has real text, such as a pasted table or chart, are **not** read by default.
105
+ Use `index(path, ocr_images=True)` for them.
106
+ - Check any figure that came from OCR: it can misread digits.
107
+
108
+ ## Managing files and settings
109
+
110
+ ```python
111
+ from snaprag import SnapRAG
112
+
113
+ rag = SnapRAG("data/my-index") # a fixed path, recommended for deployed apps
114
+ rag.index(folder_path="docs", metadata={"team": "hr"})
115
+ rag.list_files()
116
+ rag.delete("handbook_483920184756")
117
+ ```
118
+
119
+ The functions `index`, `retrieve`, `list_files` and `delete` do the same using `db_path`.
120
+
121
+ The default database is `.snaprag/` in the **current working directory**, which is not necessarily your project root.
122
+ Importing the package creates nothing, and only `index()` creates a database.
123
+ Only one process should write to a database at a time.
124
+
125
+ ## License
126
+
127
+ [MIT](https://github.com/Dipanshu3108/snaprag/blob/main/LICENSE). The bundled model files in `snaprag-model` have their own
128
+ [MIT license](https://github.com/Dipanshu3108/snaprag/blob/main/model_package/src/snaprag_model/MODEL_LICENSE.txt).
@@ -0,0 +1,23 @@
1
+ """Index a file or folder, then search it.
2
+
3
+ python quickstart.py <file-or-folder> "<question>"
4
+ """
5
+
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from snaprag import index, retrieve
10
+
11
+ target, question = Path(sys.argv[1]), sys.argv[2]
12
+
13
+ result = index(folder_path=target) if target.is_dir() else index(target)
14
+ print(f"indexed {len(result.indexed)}, skipped {len(result.skipped)}, failed {len(result.failed)}")
15
+ for failure in result.failed:
16
+ print(f" failed: {failure.path}: {failure.error}")
17
+
18
+ for number, hit in enumerate(retrieve(question, top_k=3) if result.file_ids else [], 1):
19
+ pages = ""
20
+ if hit.page is not None:
21
+ pages = f"p.{hit.page}" if hit.page_end in (None, hit.page) else f"pp.{hit.page}-{hit.page_end}"
22
+ print(f"\n{number}. [similarity {hit.similarity:.3f}] {hit.file_name} {pages} ({hit.file_id}) {hit.heading or ''}")
23
+ print(hit.text[:300])
@@ -0,0 +1,22 @@
1
+ # snaprag-model
2
+
3
+ Model files used by `snaprag`, shipped as a package so that `pip install` is the only setup step.
4
+ You do not need to install this directly.
5
+
6
+ | | |
7
+ |---|---|
8
+ | Model | `BAAI/bge-small-en-v1.5` (English, 384 dimensions, 512-token input limit) |
9
+ | Files | Quantized ONNX port, `Qdrant/bge-small-en-v1.5-onnx-Q` |
10
+ | Revision | `aa8f8b060edb00e03bfdd08813a2949946c8ba55` |
11
+ | License | MIT, see `src/snaprag_model/MODEL_LICENSE.txt` |
12
+
13
+ ## Building
14
+
15
+ The files under `src/snaprag_model/files/` are not kept in Git. Restore and verify them before building:
16
+
17
+ ```
18
+ python fetch_model.py
19
+ python -m pip wheel --no-deps -w ../dist .
20
+ ```
21
+
22
+ Check that the wheel is about 61 MB. A wheel of only a few KB means the model files are missing.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "snaprag" # not published to PyPI yet, so the name is not reserved
7
+ version = "0.1.0"
8
+ description = "Local, CPU-only RAG with two core calls: index() and retrieve()."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = [
14
+ "snaprag-model==1.0.0",
15
+ # Upper bounds keep users on the minor versions this package was tested with.
16
+ "xberg>=1.5.4,<1.6",
17
+ "fastembed>=0.9.1,<0.10",
18
+ "chromadb>=1.5.9,<1.6",
19
+ "tokenizers>=0.23,<0.24",
20
+ ]
21
+
22
+ [project.optional-dependencies]
23
+ dev = ["pytest>=8"]
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/snaprag"]
27
+
28
+ [tool.hatch.build.targets.sdist]
29
+ include = ["src/snaprag", "tests", "examples", "README.md", "LICENSE"]
30
+
31
+ [tool.pytest.ini_options]
32
+ testpaths = ["tests"]
@@ -0,0 +1,106 @@
1
+ """Local, CPU-only RAG with two core calls: index() and retrieve().
2
+
3
+ from snaprag import index, retrieve
4
+
5
+ index("handbook.pdf")
6
+ for hit in retrieve("How many leave days carry over?"):
7
+ print(hit.score, hit.text)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Iterable, Mapping
13
+ from typing import Any
14
+
15
+ from . import config
16
+ from .client import PathLike, SnapRAG
17
+ from .errors import (
18
+ CollectionMismatchError,
19
+ CollectionNotFoundError,
20
+ DatabaseNotFoundError,
21
+ FileIdConflictError,
22
+ InvalidArgumentError,
23
+ MetadataError,
24
+ ParsingError,
25
+ SnapRAGError,
26
+ )
27
+ from .results import FailedFile, FileInfo, IndexedFile, IndexResult, SearchResult, SkippedFile
28
+
29
+ __version__ = "0.1.0"
30
+
31
+
32
+ def index(
33
+ file_path: PathLike | None = None,
34
+ *,
35
+ folder_path: PathLike | None = None,
36
+ file_id: str | None = None,
37
+ metadata: Mapping[str, Any] | None = None,
38
+ collection_name: str | None = None,
39
+ recursive: bool = True,
40
+ ocr_images: bool = False,
41
+ db_path: PathLike | None = None,
42
+ ) -> IndexResult:
43
+ """Index one file or a folder. See SnapRAG.index."""
44
+ return SnapRAG(db_path).index(
45
+ file_path,
46
+ folder_path=folder_path,
47
+ file_id=file_id,
48
+ metadata=metadata,
49
+ collection_name=collection_name,
50
+ recursive=recursive,
51
+ ocr_images=ocr_images,
52
+ )
53
+
54
+
55
+ def retrieve(
56
+ query: str,
57
+ *,
58
+ file_id: str | Iterable[str] | None = None,
59
+ collection_name: str | None = None,
60
+ top_k: int = config.DEFAULT_TOP_K,
61
+ metadata_filter: Mapping[str, Any] | None = None,
62
+ mode: str = config.DEFAULT_SEARCH_MODE,
63
+ db_path: PathLike | None = None,
64
+ ) -> list[SearchResult]:
65
+ """Search indexed files. See SnapRAG.retrieve."""
66
+ return SnapRAG(db_path).retrieve(
67
+ query,
68
+ file_id=file_id,
69
+ collection_name=collection_name,
70
+ top_k=top_k,
71
+ metadata_filter=metadata_filter,
72
+ mode=mode,
73
+ )
74
+
75
+
76
+ def delete(file_id: str, *, collection_name: str | None = None, db_path: PathLike | None = None) -> int:
77
+ """Remove a file. See SnapRAG.delete."""
78
+ return SnapRAG(db_path).delete(file_id, collection_name=collection_name)
79
+
80
+
81
+ def list_files(*, collection_name: str | None = None, db_path: PathLike | None = None) -> list[FileInfo]:
82
+ """List indexed files. See SnapRAG.list_files."""
83
+ return SnapRAG(db_path).list_files(collection_name=collection_name)
84
+
85
+
86
+ __all__ = [
87
+ "CollectionMismatchError",
88
+ "CollectionNotFoundError",
89
+ "DatabaseNotFoundError",
90
+ "FailedFile",
91
+ "FileIdConflictError",
92
+ "FileInfo",
93
+ "IndexResult",
94
+ "IndexedFile",
95
+ "InvalidArgumentError",
96
+ "MetadataError",
97
+ "ParsingError",
98
+ "SnapRAG",
99
+ "SnapRAGError",
100
+ "SearchResult",
101
+ "SkippedFile",
102
+ "delete",
103
+ "index",
104
+ "list_files",
105
+ "retrieve",
106
+ ]
@@ -0,0 +1,132 @@
1
+ """The public client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Iterable, Mapping
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from . import config, embedding, indexing, retrieval
11
+ from .errors import InvalidArgumentError
12
+ from .metadata import (
13
+ build_where,
14
+ normalize_file_ids,
15
+ user_metadata,
16
+ validate_collection_name,
17
+ validate_file_id,
18
+ validate_metadata,
19
+ )
20
+ from .results import FileInfo, IndexResult, SearchResult
21
+ from .store import Store
22
+
23
+ PathLike = str | os.PathLike[str]
24
+
25
+
26
+ def _collection_name(name: str | None) -> str:
27
+ return validate_collection_name(config.DEFAULT_COLLECTION if name is None else name)
28
+
29
+
30
+ class SnapRAG:
31
+ """A snaprag database. Creating the object does not create anything on disk."""
32
+
33
+ def __init__(self, db_path: PathLike | None = None) -> None:
34
+ # Resolved now, so changing directory later does not switch databases.
35
+ self.db_path = Path(config.DEFAULT_DB_DIR if db_path is None else db_path).expanduser().resolve()
36
+ self._store = Store(self.db_path)
37
+
38
+ def index(
39
+ self,
40
+ file_path: PathLike | None = None,
41
+ *,
42
+ folder_path: PathLike | None = None,
43
+ file_id: str | None = None,
44
+ metadata: Mapping[str, Any] | None = None,
45
+ collection_name: str | None = None,
46
+ recursive: bool = True,
47
+ ocr_images: bool = False,
48
+ ) -> IndexResult:
49
+ """Index one file or every file in a folder.
50
+
51
+ ocr_images also reads the text in pictures inside documents, which is much slower.
52
+ Scanned pages and image files are read with OCR either way.
53
+ Unchanged files are skipped. Changed files keep their file_id and their chunks are replaced.
54
+ Invalid arguments raise. A file that cannot be indexed is listed in the result's `failed`.
55
+ """
56
+ if (file_path is None) == (folder_path is None):
57
+ raise InvalidArgumentError("Pass exactly one of file_path or folder_path.")
58
+ if file_id is not None:
59
+ if folder_path is not None:
60
+ raise InvalidArgumentError("file_id identifies a single file, so it cannot be used with folder_path.")
61
+ validate_file_id(file_id)
62
+ if type(ocr_images) is not bool:
63
+ raise InvalidArgumentError("ocr_images must be True or False.")
64
+ name = _collection_name(collection_name)
65
+ clean = validate_metadata(metadata)
66
+
67
+ if file_path is not None:
68
+ path = Path(file_path).expanduser().resolve()
69
+ if not path.is_file():
70
+ raise FileNotFoundError(f"file_path is not a file: {path}")
71
+ paths = [path]
72
+ else:
73
+ folder = Path(folder_path).expanduser().resolve()
74
+ if not folder.is_dir():
75
+ raise NotADirectoryError(f"folder_path is not a folder: {folder}")
76
+ found = indexing.iter_files(folder, recursive, exclude=self.db_path)
77
+ paths = list(dict.fromkeys(p.resolve() for p in found)) # links can repeat a file
78
+
79
+ header = embedding.metadata_header(clean)
80
+ if not paths:
81
+ return IndexResult()
82
+ collection = self._store.collection(name, create=True)
83
+ return indexing.index_files(collection, paths, file_id, clean, header, ocr_images)
84
+
85
+ def retrieve(
86
+ self,
87
+ query: str,
88
+ *,
89
+ file_id: str | Iterable[str] | None = None,
90
+ collection_name: str | None = None,
91
+ top_k: int = config.DEFAULT_TOP_K,
92
+ metadata_filter: Mapping[str, Any] | None = None,
93
+ mode: str = config.DEFAULT_SEARCH_MODE,
94
+ ) -> list[SearchResult]:
95
+ """Return the top_k chunks that best match the query, best first.
96
+
97
+ file_id limits the search to one file or a list of files. None searches every file.
98
+ mode "hybrid" combines search by meaning with keyword search. "vector" searches by meaning only.
99
+ """
100
+ if not isinstance(query, str) or not query.strip():
101
+ raise InvalidArgumentError("query must be a non-empty string.")
102
+ if type(top_k) is not int or top_k < 1:
103
+ raise InvalidArgumentError("top_k must be a positive integer.")
104
+ if mode not in config.SEARCH_MODES:
105
+ raise InvalidArgumentError(f"mode must be one of {', '.join(config.SEARCH_MODES)}, not {mode!r}.")
106
+ where = build_where(normalize_file_ids(file_id), metadata_filter)
107
+ collection = self._store.collection(_collection_name(collection_name))
108
+ return retrieval.search(collection, query, top_k, where, mode)
109
+
110
+ def delete(self, file_id: str, *, collection_name: str | None = None) -> int:
111
+ """Remove a file from a collection. Returns the number of chunks removed (0 if unknown)."""
112
+ validate_file_id(file_id)
113
+ collection = self._store.collection(_collection_name(collection_name))
114
+ found = [chunk_id for chunk_id, _ in collection.find({"file_id": file_id})]
115
+ if found:
116
+ collection.delete(found)
117
+ return len(found)
118
+
119
+ def list_files(self, *, collection_name: str | None = None) -> list[FileInfo]:
120
+ """The files in a collection, ordered by path."""
121
+ collection = self._store.collection(_collection_name(collection_name))
122
+ files = {
123
+ record["file_id"]: FileInfo(
124
+ file_id=record["file_id"],
125
+ file_name=record["file_name"],
126
+ source_path=record["source_path"],
127
+ chunks=record["chunk_count"],
128
+ metadata=user_metadata(record),
129
+ )
130
+ for _, record in collection.find({"chunk_index": 0})
131
+ }
132
+ return sorted(files.values(), key=lambda info: info.source_path)
@@ -0,0 +1,24 @@
1
+ """Package defaults."""
2
+
3
+ DEFAULT_DB_DIR = ".snaprag"
4
+ DEFAULT_COLLECTION = "default"
5
+ DEFAULT_TOP_K = 20
6
+
7
+ SEARCH_MODES = ("hybrid", "vector")
8
+ DEFAULT_SEARCH_MODE = "hybrid"
9
+ # Hybrid search takes at least this many chunks from each search before combining them.
10
+ HYBRID_CANDIDATES = 20
11
+ # Reciprocal rank fusion: a chunk scores 1 / (RRF_K + rank) in each search that finds it.
12
+ RRF_K = 60
13
+
14
+ # Chunk sizes are measured in tokens of the bundled model.
15
+ CHUNK_TOKENS = 400
16
+ CHUNK_OVERLAP = 50
17
+
18
+ # The model reads 512 tokens, 2 of which are special tokens. Anything beyond is silently dropped.
19
+ MAX_EMBED_TOKENS = 510
20
+ MAX_METADATA_TOKENS = 200
21
+ MAX_HEADING_TOKENS = 60
22
+
23
+ # Bump when a change here should make previously indexed files be indexed again.
24
+ INDEX_VERSION = 1