snaprag 0.1.0__py3-none-any.whl

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.
snaprag/__init__.py ADDED
@@ -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
+ ]
snaprag/client.py ADDED
@@ -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)
snaprag/config.py ADDED
@@ -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
snaprag/embedding.py ADDED
@@ -0,0 +1,91 @@
1
+ """The bundled model: embeddings, token counting and fitting text into the model's limit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from functools import lru_cache
7
+ from typing import Any
8
+
9
+ import snaprag_model
10
+
11
+ from . import config
12
+ from .errors import MetadataError, SnapRAGError
13
+ from .metadata import metadata_text
14
+
15
+ _lock = threading.Lock()
16
+
17
+
18
+ def _require_model_files() -> None:
19
+ if not snaprag_model.TOKENIZER_PATH.is_file():
20
+ raise SnapRAGError(
21
+ f"Model files are missing from {snaprag_model.MODEL_DIR}. Reinstall the snaprag-model package."
22
+ )
23
+
24
+
25
+ @lru_cache(maxsize=1)
26
+ def _tokenizer() -> Any:
27
+ from tokenizers import Tokenizer
28
+
29
+ _require_model_files()
30
+ tokenizer = Tokenizer.from_file(str(snaprag_model.TOKENIZER_PATH))
31
+ tokenizer.no_truncation()
32
+ tokenizer.no_padding()
33
+ return tokenizer
34
+
35
+
36
+ def count_tokens(text: str) -> int:
37
+ """Number of model tokens in text, without the special tokens."""
38
+ return len(_tokenizer().encode(text, add_special_tokens=False).ids)
39
+
40
+
41
+ @lru_cache(maxsize=1)
42
+ def _model() -> Any:
43
+ from fastembed import TextEmbedding
44
+
45
+ _require_model_files()
46
+ # specific_model_path makes fastembed load the bundled files without any download.
47
+ return TextEmbedding(snaprag_model.MODEL_NAME, specific_model_path=str(snaprag_model.MODEL_DIR))
48
+
49
+
50
+ def _embed(texts: list[str]) -> list[list[float]]:
51
+ with _lock:
52
+ model = _model()
53
+ return [vector.tolist() for vector in model.embed(texts)]
54
+
55
+
56
+ def embed_documents(texts: list[str]) -> list[list[float]]:
57
+ return _embed(texts)
58
+
59
+
60
+ def embed_query(query: str) -> list[float]:
61
+ return _embed([query])[0]
62
+
63
+
64
+ def truncate_to_tokens(text: str, limit: int) -> str:
65
+ encoding = _tokenizer().encode(text, add_special_tokens=False)
66
+ if len(encoding.ids) <= limit:
67
+ return text
68
+ return text[: encoding.offsets[limit - 1][1]].rstrip()
69
+
70
+
71
+ def metadata_header(metadata: dict[str, Any]) -> str:
72
+ """User metadata as text. Raises if it would leave too little room for the chunk."""
73
+ header = metadata_text(metadata)
74
+ tokens = count_tokens(header)
75
+ if tokens > config.MAX_METADATA_TOKENS:
76
+ raise MetadataError(
77
+ f"metadata is {tokens} tokens when embedded; the limit is {config.MAX_METADATA_TOKENS}. "
78
+ "Shorten or remove some values."
79
+ )
80
+ return header
81
+
82
+
83
+ def embedding_text(header: str, heading: str | None, content: str) -> str:
84
+ """The text that gets embedded. The database stores only the content."""
85
+ parts = []
86
+ if header:
87
+ parts.append(header)
88
+ if heading:
89
+ parts.append(f"Section: {truncate_to_tokens(heading, config.MAX_HEADING_TOKENS)}")
90
+ parts.append(content)
91
+ return "\n\n".join(parts)
snaprag/errors.py ADDED
@@ -0,0 +1,33 @@
1
+ """Exceptions raised by snaprag."""
2
+
3
+
4
+ class SnapRAGError(Exception):
5
+ """Base class for all snaprag errors."""
6
+
7
+
8
+ class InvalidArgumentError(SnapRAGError, ValueError):
9
+ """An argument is missing, malformed or conflicts with another."""
10
+
11
+
12
+ class MetadataError(InvalidArgumentError):
13
+ """Metadata or a metadata filter cannot be stored or searched."""
14
+
15
+
16
+ class ParsingError(SnapRAGError):
17
+ """A file could not be turned into chunks."""
18
+
19
+
20
+ class FileIdConflictError(SnapRAGError):
21
+ """A file_id already belongs to a different file."""
22
+
23
+
24
+ class DatabaseNotFoundError(SnapRAGError):
25
+ """No database exists at the given path."""
26
+
27
+
28
+ class CollectionNotFoundError(SnapRAGError):
29
+ """The database has no collection with the given name."""
30
+
31
+
32
+ class CollectionMismatchError(SnapRAGError):
33
+ """A collection was built with a different model or settings."""
snaprag/ids.py ADDED
@@ -0,0 +1,41 @@
1
+ """File IDs, content hashes and chunk IDs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ import secrets
9
+ import unicodedata
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ _MAX_WORD = 40
14
+
15
+
16
+ def generate_file_id(path: Path) -> str:
17
+ """First word of the file name in lowercase, an underscore and 12 random digits."""
18
+ ascii_name = unicodedata.normalize("NFKD", path.stem).encode("ascii", "ignore").decode()
19
+ spaced = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", ascii_name) # AnnualReport -> Annual Report
20
+ words = re.findall(r"[A-Za-z0-9]+", spaced)
21
+ word = words[0].lower()[:_MAX_WORD] if words else "file"
22
+ return f"{word}_{secrets.randbelow(10**12):012d}"
23
+
24
+
25
+ def file_hash(path: Path) -> str:
26
+ digest = hashlib.sha256()
27
+ with path.open("rb") as handle:
28
+ while block := handle.read(1024 * 1024):
29
+ digest.update(block)
30
+ return digest.hexdigest()
31
+
32
+
33
+ def fingerprint(content_hash: str, metadata: dict[str, Any], settings: dict[str, Any]) -> str:
34
+ """Changes when the file content, the user metadata or the index settings change."""
35
+ payload = json.dumps([content_hash, metadata, settings], sort_keys=True, ensure_ascii=False)
36
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
37
+
38
+
39
+ def chunk_id(file_id: str, file_fingerprint: str, index: int) -> str:
40
+ owner = hashlib.sha256(file_id.encode("utf-8")).hexdigest()[:24]
41
+ return f"{owner}-{file_fingerprint[:24]}-{index}"
snaprag/indexing.py ADDED
@@ -0,0 +1,135 @@
1
+ """Indexing: choose files, then index, skip or replace each one."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Iterator
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from . import config, embedding, ids, parsing
11
+ from .errors import FileIdConflictError, ParsingError
12
+ from .results import FailedFile, IndexedFile, IndexResult, SkippedFile
13
+ from .store import Collection
14
+
15
+
16
+ def iter_files(folder: Path, recursive: bool, exclude: Path) -> Iterator[Path]:
17
+ """Files in a folder, skipping hidden entries, Office lock files and the database folder."""
18
+ for root, directories, names in os.walk(folder):
19
+ directories[:] = sorted(
20
+ d for d in directories if recursive and not d.startswith(".") and Path(root, d).resolve() != exclude
21
+ )
22
+ for name in sorted(names):
23
+ path = Path(root, name)
24
+ if not name.startswith((".", "~$")) and path.is_file():
25
+ yield path
26
+
27
+
28
+ def _index_settings(ocr_images: bool, is_pdf: bool) -> dict[str, Any]:
29
+ settings = {
30
+ "version": config.INDEX_VERSION,
31
+ "chunk_tokens": config.CHUNK_TOKENS,
32
+ "chunk_overlap": config.CHUNK_OVERLAP,
33
+ }
34
+ if ocr_images: # added only when on, so files indexed without it are not indexed again
35
+ settings["ocr_images"] = True
36
+ if is_pdf: # PDFs indexed before page ranges are indexed again. Other files are not affected.
37
+ settings["page_ranges"] = True
38
+ return settings
39
+
40
+
41
+ def index_file(
42
+ collection: Collection,
43
+ path: Path,
44
+ file_id: str | None,
45
+ metadata: dict[str, Any],
46
+ header: str,
47
+ ocr_images: bool,
48
+ ) -> IndexedFile | SkippedFile:
49
+ source = str(path)
50
+ content_hash = ids.file_hash(path)
51
+ file_fingerprint = ids.fingerprint(content_hash, metadata, _index_settings(ocr_images, parsing.is_pdf(path)))
52
+
53
+ # A file is identified by its path. One path has one file_id within a collection.
54
+ previous = collection.find({"source_path": source})
55
+ if file_id is None:
56
+ file_id = previous[0][1]["file_id"] if previous else ids.generate_file_id(path)
57
+ else:
58
+ owned = collection.find({"file_id": file_id})
59
+ other = next((m["source_path"] for _, m in owned if m["source_path"] != source), None)
60
+ if other is not None:
61
+ raise FileIdConflictError(
62
+ f"file_id {file_id!r} already belongs to {other}. Delete it first or choose another file_id."
63
+ )
64
+
65
+ # Skip only a complete, identical copy, so an interrupted run is repaired by the next one.
66
+ if previous and all(
67
+ m["fingerprint"] == file_fingerprint and m["file_id"] == file_id and m["chunk_count"] == len(previous)
68
+ for _, m in previous
69
+ ):
70
+ return SkippedFile(source, file_id, "unchanged")
71
+
72
+ document = parsing.parse(path, ocr_images)
73
+ chunks = [piece for chunk in document.chunks for piece in parsing.fit_to_limit(chunk, header)]
74
+ if not chunks:
75
+ raise ParsingError("No chunks were produced.")
76
+ # The file may have changed while it was being read.
77
+ if ids.file_hash(path) != content_hash:
78
+ raise ParsingError("The file changed while it was being indexed. Index it again.")
79
+
80
+ vectors = embedding.embed_documents(
81
+ [embedding.embedding_text(header, chunk.heading, chunk.text) for chunk in chunks]
82
+ )
83
+ new_ids = [ids.chunk_id(file_id, file_fingerprint, number) for number in range(len(chunks))]
84
+ records = []
85
+ for number, chunk in enumerate(chunks):
86
+ record = {
87
+ **metadata,
88
+ "file_id": file_id,
89
+ "file_name": path.name,
90
+ "source_path": source,
91
+ "chunk_index": number,
92
+ "chunk_count": len(chunks),
93
+ "fingerprint": file_fingerprint,
94
+ }
95
+ if chunk.heading:
96
+ record["heading"] = chunk.heading
97
+ if chunk.page is not None:
98
+ record["page"] = chunk.page
99
+ if chunk.page_end is not None:
100
+ record["page_end"] = chunk.page_end
101
+ records.append(record)
102
+
103
+ # Write the new chunks before deleting the old ones, so a failure never loses the old version.
104
+ old_ids = {chunk_id for chunk_id, _ in previous}
105
+ try:
106
+ collection.upsert(new_ids, vectors, [chunk.text for chunk in chunks], records)
107
+ except BaseException:
108
+ collection.delete([i for i in new_ids if i not in old_ids])
109
+ raise
110
+ stale = sorted(old_ids - set(new_ids))
111
+ if stale:
112
+ collection.delete(stale)
113
+ return IndexedFile(source, file_id, len(chunks), replaced=bool(previous), warnings=document.warnings)
114
+
115
+
116
+ def index_files(
117
+ collection: Collection,
118
+ paths: list[Path],
119
+ file_id: str | None,
120
+ metadata: dict[str, Any],
121
+ header: str,
122
+ ocr_images: bool,
123
+ ) -> IndexResult:
124
+ result = IndexResult()
125
+ for path in paths:
126
+ try:
127
+ outcome = index_file(collection, path, file_id, metadata, header, ocr_images)
128
+ except Exception as exc: # one bad file must not stop the others
129
+ result.failed.append(FailedFile(str(path), str(exc) or type(exc).__name__))
130
+ continue
131
+ if isinstance(outcome, IndexedFile):
132
+ result.indexed.append(outcome)
133
+ else:
134
+ result.skipped.append(outcome)
135
+ return result
snaprag/keyword.py ADDED
@@ -0,0 +1,109 @@
1
+ """Keyword search over chunks, kept in a SQLite full-text index beside the Chroma database.
2
+
3
+ Chroma holds the real data. This index is a copy of its text that can always be rebuilt from it.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ import sqlite3
10
+ from collections.abc import Iterable, Iterator
11
+ from contextlib import contextmanager
12
+ from pathlib import Path
13
+
14
+ from .errors import SnapRAGError
15
+
16
+ FILE_NAME = "keyword.sqlite3"
17
+ _WORD = re.compile(r"\w+")
18
+ # These are in nearly every chunk, so they say little, yet matching them means scoring nearly every chunk.
19
+ _COMMON_WORDS = frozenset(
20
+ "a an and are as at be been but by can could did do does for from had has have how i if in into is it its "
21
+ "may me might much my no not of on or our shall should so such than that the their them then there these "
22
+ "they this those to was we were what when where which who whom why will with would you your".split()
23
+ )
24
+
25
+
26
+ class KeywordIndex:
27
+ """The keyword index of one collection. Each call opens and closes its own connection."""
28
+
29
+ def __init__(self, path: Path, collection: str) -> None:
30
+ self.path = path
31
+ # Hex, because SQLite ignores case in table names and collection names do not.
32
+ key = collection.encode().hex()
33
+ self._ids = f"ids_{key}"
34
+ self._text = f"text_{key}"
35
+
36
+ @contextmanager
37
+ def _connect(self) -> Iterator[sqlite3.Connection]:
38
+ connection = sqlite3.connect(self.path, timeout=30)
39
+ try:
40
+ with connection: # one transaction: commit on success, roll back on error
41
+ connection.execute(
42
+ f"CREATE TABLE IF NOT EXISTS {self._ids} "
43
+ "(number INTEGER PRIMARY KEY, chunk_id TEXT NOT NULL UNIQUE)"
44
+ )
45
+ try:
46
+ connection.execute(
47
+ f"CREATE VIRTUAL TABLE IF NOT EXISTS {self._text} "
48
+ "USING fts5(body, tokenize = 'unicode61 remove_diacritics 2')"
49
+ )
50
+ except sqlite3.OperationalError as exc:
51
+ if "fts5" not in str(exc):
52
+ raise
53
+ raise SnapRAGError("This Python's SQLite was built without FTS5, which snaprag needs.") from exc
54
+ yield connection
55
+ finally:
56
+ connection.close() # an open handle would lock the file on Windows
57
+
58
+ def _delete(self, connection: sqlite3.Connection, chunk_ids: Iterable[str]) -> None:
59
+ for chunk_id in chunk_ids:
60
+ row = connection.execute(f"SELECT number FROM {self._ids} WHERE chunk_id = ?", (chunk_id,)).fetchone()
61
+ if row:
62
+ connection.execute(f"DELETE FROM {self._text} WHERE rowid = ?", row)
63
+ connection.execute(f"DELETE FROM {self._ids} WHERE number = ?", row)
64
+
65
+ def add(self, entries: list[tuple[str, str]]) -> None:
66
+ """Insert or replace (chunk_id, text) pairs."""
67
+ with self._connect() as connection:
68
+ self._delete(connection, [chunk_id for chunk_id, _ in entries])
69
+ for chunk_id, body in entries:
70
+ number = connection.execute(f"INSERT INTO {self._ids} (chunk_id) VALUES (?)", (chunk_id,)).lastrowid
71
+ connection.execute(f"INSERT INTO {self._text} (rowid, body) VALUES (?, ?)", (number, body))
72
+
73
+ def remove(self, chunk_ids: list[str]) -> None:
74
+ with self._connect() as connection:
75
+ self._delete(connection, chunk_ids)
76
+
77
+ def count(self) -> int:
78
+ with self._connect() as connection:
79
+ return connection.execute(f"SELECT count(*) FROM {self._ids}").fetchone()[0]
80
+
81
+ def chunk_ids(self) -> set[str]:
82
+ with self._connect() as connection:
83
+ return {row[0] for row in connection.execute(f"SELECT chunk_id FROM {self._ids}")}
84
+
85
+ def search(self, query: str, limit: int, allowed: set[str] | None = None) -> list[str]:
86
+ """IDs of the chunks that best match the query's words, best first.
87
+
88
+ allowed restricts the results to those IDs. None allows every chunk.
89
+ """
90
+ words = list(dict.fromkeys(_WORD.findall(query.lower())))
91
+ words = [word for word in words if word not in _COMMON_WORDS] or words # unless there is nothing else
92
+ if not words or allowed == set():
93
+ return []
94
+ # Quoted, so that words such as AND or NEAR are not read as search operators.
95
+ expression = " OR ".join(f'"{word}"' for word in words)
96
+ found: list[str] = []
97
+ with self._connect() as connection:
98
+ rows = connection.execute(
99
+ f"SELECT i.chunk_id FROM {self._text} AS t JOIN {self._ids} AS i ON i.number = t.rowid "
100
+ f"WHERE {self._text} MATCH ? ORDER BY bm25({self._text}), t.rowid",
101
+ (expression,),
102
+ )
103
+ for (chunk_id,) in rows:
104
+ if allowed is None or chunk_id in allowed:
105
+ found.append(chunk_id)
106
+ if len(found) == limit:
107
+ break
108
+ rows.close()
109
+ return found