offline-rag-kit 0.1.2__tar.gz → 0.1.3__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 (23) hide show
  1. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/PKG-INFO +23 -3
  2. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/README.md +22 -2
  3. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/pyproject.toml +16 -1
  4. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag/__init__.py +1 -1
  5. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag/cli.py +39 -8
  6. offline_rag_kit-0.1.3/src/offline_rag/embeddings.py +177 -0
  7. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag/eval.py +25 -5
  8. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag/index.py +26 -7
  9. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag/ollama.py +1 -2
  10. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag_kit.egg-info/PKG-INFO +23 -3
  11. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag_kit.egg-info/SOURCES.txt +2 -0
  12. offline_rag_kit-0.1.3/tests/test_embeddings.py +178 -0
  13. offline_rag_kit-0.1.3/tests/test_eval.py +56 -0
  14. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/tests/test_index.py +13 -2
  15. offline_rag_kit-0.1.2/tests/test_eval.py +0 -25
  16. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/LICENSE +0 -0
  17. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/setup.cfg +0 -0
  18. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag_kit.egg-info/dependency_links.txt +0 -0
  19. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag_kit.egg-info/entry_points.txt +0 -0
  20. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag_kit.egg-info/requires.txt +0 -0
  21. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/src/offline_rag_kit.egg-info/top_level.txt +0 -0
  22. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/tests/test_cli.py +0 -0
  23. {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.3}/tests/test_ollama.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: offline-rag-kit
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Privacy-first local document search with PDF citations and optional Ollama answers
5
5
  Author: HugoDelgadoo
6
6
  Maintainer: HugoDelgadoo
@@ -27,6 +27,8 @@ Dynamic: license-file
27
27
  [![Python](https://img.shields.io/pypi/pyversions/offline-rag-kit)](https://pypi.org/project/offline-rag-kit/)
28
28
  [![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/LICENSE)
29
29
 
30
+ **English** | [Español](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/README.es.md)
31
+
30
32
  **Privacy-first local document search with PDF citations and optional local AI answers.**
31
33
 
32
34
  > **Status: v0.1 alpha — a working retrieval-first prototype, not yet a complete multimodal RAG system.**
@@ -73,7 +75,8 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
73
75
 
74
76
  ```text
75
77
  offline-rag [--db PATH] [--json] ingest FOLDER
76
- offline-rag [--db PATH] [--json] search "TERMS" [--limit 5]
78
+ offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid]
79
+ offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
77
80
  offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
78
81
  [--ollama-host URL] [--allow-remote]
79
82
  ```
@@ -82,6 +85,23 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
82
85
 
83
86
  `ask` talks to `127.0.0.1:11434` by default. Set `OLLAMA_HOST` or `--ollama-host` to use another port. Non-loopback hosts are refused unless you pass `--allow-remote`, because retrieved passages would then leave your machine.
84
87
 
88
+ ### Optional semantic search (local Ollama)
89
+
90
+ Plain `search` is lexical and works fully offline. To also match by meaning (for example "work from home" ~ "teletrabajo"), create embeddings **explicitly** with a local Ollama model, then choose a mode:
91
+
92
+ ```powershell
93
+ ollama pull bge-m3 # a multilingual embedding model
94
+ offline-rag embed --model bge-m3 # explicit step; only embeds new passages
95
+ offline-rag search "work from home" --mode hybrid # BM25 + vectors fused (RRF)
96
+ offline-rag search "work from home" --mode vector # vectors only
97
+ ```
98
+
99
+ - `ingest` never calls Ollama, and the default mode stays `lexical`. Semantic modes need Ollama running when you search, because the question must be embedded too.
100
+ - The index remembers which model made its vectors. Switching models needs `offline-rag embed --model NEW --rebuild`.
101
+ - Same privacy rule as `ask`: only loopback hosts are accepted unless you pass `--allow-remote`.
102
+ - Vectors are compared with a plain scan, which is fine for thousands of passages but slows down on very large collections. Embedding speed depends on your hardware and model.
103
+ - **Not yet measured with a real model.** Use `python -m offline_rag.eval --mode hybrid --model bge-m3` to see what it does on the bundled dataset.
104
+
85
105
  `--json` (placed before the subcommand) prints a single JSON document on stdout, with the full passage text, page, bounding box and score for each hit. Errors and exit codes are unchanged and still go to stderr.
86
106
 
87
107
  ## Current capabilities and limitations
@@ -92,7 +112,7 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
92
112
  | Lexical ranking with SQLite FTS5 (BM25) | Supported |
93
113
  | PDF source pages and block bounding boxes | Supported |
94
114
  | Local Ollama text generation | Optional, supported |
95
- | Semantic / vector retrieval | Planned |
115
+ | Semantic / vector retrieval | Optional, via local Ollama embeddings (not yet benchmarked) |
96
116
  | OCR, image understanding, audio transcription | Planned |
97
117
  | Web dashboard / user authentication | Planned |
98
118
  | Reliable claim-level grounding evaluation | Planned |
@@ -5,6 +5,8 @@
5
5
  [![Python](https://img.shields.io/pypi/pyversions/offline-rag-kit)](https://pypi.org/project/offline-rag-kit/)
6
6
  [![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/LICENSE)
7
7
 
8
+ **English** | [Español](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/README.es.md)
9
+
8
10
  **Privacy-first local document search with PDF citations and optional local AI answers.**
9
11
 
10
12
  > **Status: v0.1 alpha — a working retrieval-first prototype, not yet a complete multimodal RAG system.**
@@ -51,7 +53,8 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
51
53
 
52
54
  ```text
53
55
  offline-rag [--db PATH] [--json] ingest FOLDER
54
- offline-rag [--db PATH] [--json] search "TERMS" [--limit 5]
56
+ offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid]
57
+ offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
55
58
  offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
56
59
  [--ollama-host URL] [--allow-remote]
57
60
  ```
@@ -60,6 +63,23 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
60
63
 
61
64
  `ask` talks to `127.0.0.1:11434` by default. Set `OLLAMA_HOST` or `--ollama-host` to use another port. Non-loopback hosts are refused unless you pass `--allow-remote`, because retrieved passages would then leave your machine.
62
65
 
66
+ ### Optional semantic search (local Ollama)
67
+
68
+ Plain `search` is lexical and works fully offline. To also match by meaning (for example "work from home" ~ "teletrabajo"), create embeddings **explicitly** with a local Ollama model, then choose a mode:
69
+
70
+ ```powershell
71
+ ollama pull bge-m3 # a multilingual embedding model
72
+ offline-rag embed --model bge-m3 # explicit step; only embeds new passages
73
+ offline-rag search "work from home" --mode hybrid # BM25 + vectors fused (RRF)
74
+ offline-rag search "work from home" --mode vector # vectors only
75
+ ```
76
+
77
+ - `ingest` never calls Ollama, and the default mode stays `lexical`. Semantic modes need Ollama running when you search, because the question must be embedded too.
78
+ - The index remembers which model made its vectors. Switching models needs `offline-rag embed --model NEW --rebuild`.
79
+ - Same privacy rule as `ask`: only loopback hosts are accepted unless you pass `--allow-remote`.
80
+ - Vectors are compared with a plain scan, which is fine for thousands of passages but slows down on very large collections. Embedding speed depends on your hardware and model.
81
+ - **Not yet measured with a real model.** Use `python -m offline_rag.eval --mode hybrid --model bge-m3` to see what it does on the bundled dataset.
82
+
63
83
  `--json` (placed before the subcommand) prints a single JSON document on stdout, with the full passage text, page, bounding box and score for each hit. Errors and exit codes are unchanged and still go to stderr.
64
84
 
65
85
  ## Current capabilities and limitations
@@ -70,7 +90,7 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
70
90
  | Lexical ranking with SQLite FTS5 (BM25) | Supported |
71
91
  | PDF source pages and block bounding boxes | Supported |
72
92
  | Local Ollama text generation | Optional, supported |
73
- | Semantic / vector retrieval | Planned |
93
+ | Semantic / vector retrieval | Optional, via local Ollama embeddings (not yet benchmarked) |
74
94
  | OCR, image understanding, audio transcription | Planned |
75
95
  | Web dashboard / user authentication | Planned |
76
96
  | Reliable claim-level grounding evaluation | Planned |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "offline-rag-kit"
7
- version = "0.1.2"
7
+ version = "0.1.3"
8
8
  description = "Privacy-first local document search with PDF citations and optional Ollama answers"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -31,3 +31,18 @@ offline-rag = "offline_rag.cli:main"
31
31
 
32
32
  [tool.setuptools.packages.find]
33
33
  where = ["src"]
34
+
35
+ [tool.ruff]
36
+ line-length = 120
37
+ target-version = "py310"
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "F", "W", "I", "B", "UP"]
41
+
42
+ [tool.coverage.run]
43
+ source = ["src/offline_rag"]
44
+ branch = true
45
+
46
+ [tool.coverage.report]
47
+ show_missing = true
48
+ exclude_also = ["if __name__ == .__main__.:"]
@@ -1,3 +1,3 @@
1
1
  """Privacy-first retrieval over local documents."""
2
2
 
3
- __version__ = "0.1.2"
3
+ __version__ = "0.1.3"
@@ -4,6 +4,7 @@ import argparse
4
4
  import json
5
5
  import sys
6
6
 
7
+ from .embeddings import DEFAULT_MODEL, embed_index, hybrid_search, indexed_model, ollama_embedder, vector_search
7
8
  from .index import citation, ingest, search
8
9
  from .ollama import answer_with_ollama
9
10
 
@@ -21,17 +22,29 @@ def build_parser() -> argparse.ArgumentParser:
21
22
  ing = commands.add_parser("ingest", help="Index PDFs, .txt and .md files recursively")
22
23
  ing.add_argument("folder", help="Directory containing documents")
23
24
 
25
+ emb = commands.add_parser(
26
+ "embed", help="Create embeddings with local Ollama for semantic search (explicit, optional)"
27
+ )
28
+ emb.add_argument("--model", default=DEFAULT_MODEL, help="Ollama embedding model (ollama pull <model>)")
29
+ emb.add_argument("--rebuild", action="store_true", help="Discard existing embeddings first")
30
+ emb.add_argument("--ollama-host", help="Ollama URL (default: $OLLAMA_HOST or 127.0.0.1:11434)")
31
+ emb.add_argument("--allow-remote", action="store_true", help="Allow a non-loopback Ollama host")
32
+
24
33
  for command in ("search", "ask"):
25
34
  sub = commands.add_parser(command, help="Search locally" if command == "search" else "Ask local Ollama")
26
35
  sub.add_argument("query", help="Question or search terms")
27
36
  sub.add_argument("--limit", type=int, default=5)
37
+ sub.add_argument(
38
+ "--mode", choices=("lexical", "vector", "hybrid"), default="lexical",
39
+ help="lexical (default, offline); vector/hybrid need 'offline-rag embed' and a running Ollama",
40
+ )
41
+ sub.add_argument("--ollama-host", help="Ollama URL (default: $OLLAMA_HOST or 127.0.0.1:11434)")
42
+ sub.add_argument(
43
+ "--allow-remote", action="store_true",
44
+ help="Allow a non-loopback Ollama host (text is sent to it)",
45
+ )
28
46
  if command == "ask":
29
- sub.add_argument("--model", default="llama3.2", help="Ollama model installed locally")
30
- sub.add_argument("--ollama-host", help="Ollama URL (default: $OLLAMA_HOST or 127.0.0.1:11434)")
31
- sub.add_argument(
32
- "--allow-remote", action="store_true",
33
- help="Allow a non-loopback Ollama host (retrieved passages are sent to it)",
34
- )
47
+ sub.add_argument("--model", default="llama3.2", help="Ollama model used to write the answer")
35
48
  return parser
36
49
 
37
50
 
@@ -52,12 +65,23 @@ def _dump(payload: dict) -> None:
52
65
  print(json.dumps(payload, ensure_ascii=False, indent=2))
53
66
 
54
67
 
68
+ def _retrieve(args) -> list[dict]:
69
+ if args.mode == "lexical":
70
+ return search(args.query, args.db, args.limit)
71
+ model = indexed_model(args.db)
72
+ if model is None:
73
+ raise ValueError("This index has no embeddings. Run 'offline-rag embed' first.")
74
+ embedder = ollama_embedder(model, args.ollama_host, args.allow_remote)
75
+ run = vector_search if args.mode == "vector" else hybrid_search
76
+ return run(args.query, args.db, embedder, args.limit)
77
+
78
+
55
79
  def main(argv: list[str] | None = None) -> None:
56
80
  args = build_parser().parse_args(argv)
57
81
  try:
58
82
  if args.command == "ingest":
59
83
  result = ingest(args.folder, args.db)
60
- skipped = [{"path": str(p), "error": str(e)} for p, e in result.skipped]
84
+ skipped = [{"path": str(p), "error": message} for p, message in result.skipped]
61
85
  if args.json:
62
86
  _dump({
63
87
  "files": result.files, "passages": result.passages,
@@ -70,8 +94,15 @@ def main(argv: list[str] | None = None) -> None:
70
94
  f"Indexed {result.files} files ({result.unchanged} unchanged) and "
71
95
  f"{result.passages} passages in {args.db}"
72
96
  )
97
+ elif args.command == "embed":
98
+ embedder = ollama_embedder(args.model, args.ollama_host, args.allow_remote)
99
+ count = embed_index(args.db, embedder, args.model, rebuild=args.rebuild)
100
+ if args.json:
101
+ _dump({"embedded": count, "model": args.model, "database": args.db})
102
+ else:
103
+ print(f"Embedded {count} passages with {args.model} in {args.db}")
73
104
  else:
74
- hits = search(args.query, args.db, args.limit)
105
+ hits = _retrieve(args)
75
106
  if args.command == "search":
76
107
  if args.json:
77
108
  _dump({"query": args.query, "results": [_hit_json(i, h) for i, h in enumerate(hits, 1)]})
@@ -0,0 +1,177 @@
1
+ """Optional semantic retrieval with embeddings from a local Ollama server.
2
+
3
+ Nothing here runs unless the user asks for it: ``offline-rag embed`` creates the vectors
4
+ (an explicit step), and ``search --mode vector|hybrid`` uses them. Only the Python standard
5
+ library is needed; vectors live in the same SQLite file as the passages.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import heapq
11
+ import json
12
+ import math
13
+ import operator
14
+ import struct
15
+ from collections.abc import Callable
16
+ from contextlib import closing
17
+ from pathlib import Path
18
+ from urllib.error import HTTPError, URLError
19
+ from urllib.request import Request, urlopen
20
+
21
+ from .index import open_index, search
22
+ from .ollama import resolve_host
23
+
24
+ DEFAULT_MODEL = "bge-m3" # multilingual; pull it first with `ollama pull bge-m3`
25
+ Embedder = Callable[[list[str]], list[list[float]]]
26
+
27
+
28
+ def ollama_embedder(
29
+ model: str, host: str | None = None, allow_remote: bool = False, timeout: int = 180
30
+ ) -> Embedder:
31
+ """Return a function that embeds texts through Ollama's ``/api/embed`` endpoint."""
32
+ base_url = resolve_host(host, allow_remote) # refuses non-loopback hosts by default
33
+
34
+ def embed(texts: list[str]) -> list[list[float]]:
35
+ payload = json.dumps({"model": model, "input": texts, "truncate": True}).encode("utf-8")
36
+ request = Request(
37
+ f"{base_url}/api/embed",
38
+ data=payload,
39
+ headers={"Content-Type": "application/json"},
40
+ method="POST",
41
+ )
42
+ try:
43
+ with urlopen(request, timeout=timeout) as response:
44
+ data = json.load(response)
45
+ except HTTPError as exc:
46
+ detail = ""
47
+ try:
48
+ detail = json.load(exc).get("error", "")
49
+ except Exception:
50
+ pass
51
+ hint = f" Run: ollama pull {model}" if exc.code == 404 else ""
52
+ raise RuntimeError(f"Ollama returned HTTP {exc.code} for model {model!r}: {detail}.{hint}") from exc
53
+ except URLError as exc:
54
+ raise RuntimeError(
55
+ f"Cannot reach Ollama at {base_url}. Run 'ollama serve' and 'ollama pull {model}'."
56
+ ) from exc
57
+ vectors = data.get("embeddings")
58
+ if (
59
+ not isinstance(vectors, list)
60
+ or len(vectors) != len(texts)
61
+ or not all(isinstance(v, list) and v for v in vectors)
62
+ ):
63
+ raise RuntimeError("Unexpected response from Ollama's /api/embed endpoint.")
64
+ return vectors
65
+
66
+ return embed
67
+
68
+
69
+ def _normalize(vector: list[float]) -> list[float]:
70
+ norm = math.sqrt(sum(x * x for x in vector))
71
+ if norm == 0:
72
+ raise ValueError("The embedding model returned a zero vector.")
73
+ return [x / norm for x in vector]
74
+
75
+
76
+ def _encode(vector: list[float]) -> bytes:
77
+ return struct.pack(f"<{len(vector)}f", *vector)
78
+
79
+
80
+ def _decode(blob: bytes) -> tuple[float, ...]:
81
+ return struct.unpack(f"<{len(blob) // 4}f", blob)
82
+
83
+
84
+ def indexed_model(database: str | Path) -> str | None:
85
+ """Model that produced the vectors in this index, or None if it has none."""
86
+ with closing(open_index(database)) as connection:
87
+ models = [row[0] for row in connection.execute("SELECT DISTINCT model FROM embeddings")]
88
+ if len(models) > 1:
89
+ raise ValueError(f"Index mixes embeddings from several models: {', '.join(sorted(models))}.")
90
+ return models[0] if models else None
91
+
92
+
93
+ def embed_index(
94
+ database: str | Path,
95
+ embedder: Embedder,
96
+ model: str,
97
+ batch_size: int = 16,
98
+ rebuild: bool = False,
99
+ ) -> int:
100
+ """Embed every passage that has no vector yet; return how many were embedded."""
101
+ with closing(open_index(database)) as connection:
102
+ if rebuild:
103
+ with connection:
104
+ connection.execute("DELETE FROM embeddings")
105
+ existing = [row[0] for row in connection.execute("SELECT DISTINCT model FROM embeddings")]
106
+ if existing and existing != [model]:
107
+ raise ValueError(
108
+ f"This index already has embeddings from {existing[0]!r}. "
109
+ f"Use --rebuild to replace them with {model!r}."
110
+ )
111
+ todo = connection.execute(
112
+ """SELECT p.rowid AS id, p.body FROM passages p
113
+ LEFT JOIN embeddings e ON e.passage_rowid = p.rowid
114
+ WHERE e.passage_rowid IS NULL ORDER BY p.rowid"""
115
+ ).fetchall()
116
+ dims = {row[0] for row in connection.execute("SELECT DISTINCT dim FROM embeddings")}
117
+ for start in range(0, len(todo), batch_size):
118
+ batch = todo[start:start + batch_size]
119
+ vectors = [_normalize(v) for v in embedder([row["body"] for row in batch])]
120
+ dims |= {len(v) for v in vectors}
121
+ if len(dims) > 1:
122
+ raise ValueError("The embedding model returned vectors of different sizes.")
123
+ with connection:
124
+ connection.executemany(
125
+ "INSERT OR REPLACE INTO embeddings (passage_rowid, model, dim, vector) VALUES (?, ?, ?, ?)",
126
+ ((row["id"], model, len(v), _encode(v)) for row, v in zip(batch, vectors, strict=True)),
127
+ )
128
+ return len(todo)
129
+
130
+
131
+ def vector_search(query: str, database: str | Path, embedder: Embedder, limit: int = 5) -> list[dict]:
132
+ """Rank passages by cosine similarity to the query (brute force over all vectors)."""
133
+ if limit < 1 or limit > 100:
134
+ raise ValueError("limit must be between 1 and 100")
135
+ with closing(open_index(database)) as connection:
136
+ stored = connection.execute("SELECT passage_rowid, dim, vector FROM embeddings").fetchall()
137
+ if not stored:
138
+ raise ValueError("This index has no embeddings. Run 'offline-rag embed' first.")
139
+ query_vector = _normalize(embedder([query])[0])
140
+ if len(query_vector) != stored[0]["dim"]:
141
+ raise ValueError("The query embedding does not match the indexed vectors: was the model changed?")
142
+ dot = operator.mul
143
+ scored = (
144
+ (sum(map(dot, query_vector, _decode(row["vector"]))), row["passage_rowid"]) for row in stored
145
+ )
146
+ top = heapq.nlargest(limit, scored)
147
+ hits = []
148
+ for score, rowid in top:
149
+ row = connection.execute(
150
+ "SELECT root, path, page, bbox, body FROM passages WHERE rowid = ?", (rowid,)
151
+ ).fetchone()
152
+ if row:
153
+ body = row["body"]
154
+ hits.append({
155
+ "id": rowid, "root": row["root"], "path": row["path"], "page": row["page"],
156
+ "bbox": row["bbox"], "body": body, "score": score,
157
+ "snippet": body if len(body) <= 240 else body[:240].rstrip() + " …",
158
+ })
159
+ return hits
160
+
161
+
162
+ def hybrid_search(
163
+ query: str, database: str | Path, embedder: Embedder, limit: int = 5, k: int = 60
164
+ ) -> list[dict]:
165
+ """Fuse BM25 and vector rankings with Reciprocal Rank Fusion."""
166
+ if limit < 1 or limit > 100:
167
+ raise ValueError("limit must be between 1 and 100")
168
+ pool = min(100, max(limit * 4, 20))
169
+ rankings = [search(query, database, pool), vector_search(query, database, embedder, pool)]
170
+ fused: dict[int, float] = {}
171
+ best: dict[int, dict] = {}
172
+ for hits in rankings:
173
+ for rank, hit in enumerate(hits, start=1):
174
+ fused[hit["id"]] = fused.get(hit["id"], 0.0) + 1.0 / (k + rank)
175
+ best.setdefault(hit["id"], hit) # the lexical hit comes first and has a highlighted snippet
176
+ ordered = sorted(fused, key=lambda i: (-fused[i], i))[:limit]
177
+ return [{**best[i], "score": fused[i]} for i in ordered]
@@ -14,18 +14,27 @@ import sys
14
14
  import tempfile
15
15
  from pathlib import Path
16
16
 
17
+ from .embeddings import DEFAULT_MODEL, embed_index, hybrid_search, ollama_embedder, vector_search
17
18
  from .index import ingest, search
18
19
 
19
20
  KS = (1, 3, 5)
20
21
 
21
22
 
22
- def evaluate(corpus: Path, questions: list[dict]) -> dict:
23
+ def evaluate(corpus: Path, questions: list[dict], mode: str = "lexical", embedder=None, model: str = "") -> dict:
24
+ """Run the questions. ``mode`` is lexical, vector or hybrid; the last two need ``embedder``."""
23
25
  with tempfile.TemporaryDirectory() as tmp:
24
26
  database = Path(tmp) / "eval.sqlite3"
25
27
  ingest(corpus, database)
28
+ if mode != "lexical":
29
+ embed_index(database, embedder, model)
26
30
  rows = []
27
31
  for item in questions:
28
- hits = search(item["q"], database, limit=max(KS))
32
+ if mode == "lexical":
33
+ hits = search(item["q"], database, limit=max(KS))
34
+ elif mode == "vector":
35
+ hits = vector_search(item["q"], database, embedder, limit=max(KS))
36
+ else:
37
+ hits = hybrid_search(item["q"], database, embedder, limit=max(KS))
29
38
  rank = next(
30
39
  (
31
40
  i
@@ -56,11 +65,21 @@ def main(argv: list[str] | None = None) -> None:
56
65
  parser.add_argument("--corpus", default="eval/corpus", type=Path)
57
66
  parser.add_argument("--questions", default="eval/questions.json", type=Path)
58
67
  parser.add_argument("--json", action="store_true")
68
+ parser.add_argument(
69
+ "--mode", choices=("lexical", "vector", "hybrid"), default="lexical",
70
+ help="vector/hybrid embed the corpus with local Ollama first (needs 'ollama serve' and the model)",
71
+ )
72
+ parser.add_argument("--model", default=DEFAULT_MODEL, help="Ollama embedding model for vector/hybrid")
73
+ parser.add_argument("--ollama-host")
74
+ parser.add_argument("--allow-remote", action="store_true")
59
75
  args = parser.parse_args(argv)
60
76
  try:
61
77
  questions = json.loads(args.questions.read_text(encoding="utf-8"))["questions"]
62
- report = evaluate(args.corpus, questions)
63
- except (OSError, ValueError, KeyError) as exc:
78
+ embedder = None
79
+ if args.mode != "lexical":
80
+ embedder = ollama_embedder(args.model, args.ollama_host, args.allow_remote)
81
+ report = evaluate(args.corpus, questions, args.mode, embedder, args.model)
82
+ except (OSError, ValueError, KeyError, RuntimeError) as exc:
64
83
  print(f"Error: {exc}", file=sys.stderr)
65
84
  raise SystemExit(1) from exc
66
85
  if args.json:
@@ -68,7 +87,8 @@ def main(argv: list[str] | None = None) -> None:
68
87
  return
69
88
  print(f"{'subset':<12}{'n':>4}" + "".join(f"{'R@' + str(k):>8}" for k in KS) + f"{'MRR':>8}")
70
89
  for name, st in [("overall", report["overall"]), *report["by_kind"].items()]:
71
- print(f"{name:<12}{st['questions']:>4}" + "".join(f"{st[f'recall@{k}']:>8.3f}" for k in KS) + f"{st['mrr']:>8.3f}")
90
+ recalls = "".join(f"{st[f'recall@{k}']:>8.3f}" for k in KS)
91
+ print(f"{name:<12}{st['questions']:>4}{recalls}{st['mrr']:>8.3f}")
72
92
  missed = [r["q"] for r in report["rows"] if not r["rank"]]
73
93
  if missed:
74
94
  print("\nNot found in top 5:")
@@ -6,10 +6,10 @@ import hashlib
6
6
  import os
7
7
  import re
8
8
  import sqlite3
9
+ from collections.abc import Iterator
9
10
  from contextlib import closing
10
11
  from dataclasses import dataclass, field
11
12
  from pathlib import Path
12
- from typing import Callable, Iterator
13
13
 
14
14
  import pymupdf
15
15
 
@@ -42,6 +42,12 @@ def open_index(database: str | Path) -> sqlite3.Connection:
42
42
  tokenize = 'unicode61 remove_diacritics 2'
43
43
  )"""
44
44
  )
45
+ connection.execute(
46
+ """CREATE TABLE IF NOT EXISTS embeddings (
47
+ passage_rowid INTEGER PRIMARY KEY,
48
+ model TEXT NOT NULL, dim INTEGER NOT NULL, vector BLOB NOT NULL
49
+ )"""
50
+ )
45
51
  connection.execute(
46
52
  """CREATE TABLE IF NOT EXISTS files (
47
53
  root TEXT NOT NULL, path TEXT NOT NULL,
@@ -70,7 +76,7 @@ def join_hyphenated(text: str) -> str:
70
76
  return _HYPHEN_BREAK.sub(repair, text)
71
77
 
72
78
 
73
- def _table_passages(page: "pymupdf.Page") -> list[tuple[pymupdf.Rect, str]]:
79
+ def _table_passages(page: pymupdf.Page) -> list[tuple[pymupdf.Rect, str]]:
74
80
  """Return (bbox, text) for each ruled table on the page; never raises."""
75
81
  try:
76
82
  tables = page.find_tables().tables
@@ -128,7 +134,7 @@ class IngestResult:
128
134
  files: int = 0
129
135
  passages: int = 0
130
136
  unchanged: int = 0
131
- skipped: list[tuple[Path, Exception]] = field(default_factory=list)
137
+ skipped: list[tuple[Path, str]] = field(default_factory=list)
132
138
 
133
139
 
134
140
  def _sha256(path: Path) -> str:
@@ -186,10 +192,12 @@ def ingest(folder: str | Path, database: str | Path) -> IngestResult:
186
192
  continue
187
193
  entries = list(extract_passages(path))
188
194
  except Exception as exc: # parsers raise many different error types
189
- result.skipped.append((path, exc))
195
+ # Keep only the message: holding the exception would keep its traceback (and the
196
+ # half-opened PDF it references) alive, which locks the file on Windows.
197
+ result.skipped.append((path, str(exc)))
190
198
  continue
191
199
  with connection:
192
- connection.execute("DELETE FROM passages WHERE root = ? AND path = ?", (root_key, relative))
200
+ _delete_passages(connection, root_key, relative)
193
201
  connection.executemany(
194
202
  "INSERT INTO passages (root, path, page, bbox, body) VALUES (?, ?, ?, ?, ?)",
195
203
  ((root_key, relative, page, bbox, body) for page, bbox, body in entries),
@@ -204,6 +212,16 @@ def ingest(folder: str | Path, database: str | Path) -> IngestResult:
204
212
  return result
205
213
 
206
214
 
215
+ def _delete_passages(connection: sqlite3.Connection, root: str, path: str) -> None:
216
+ """Delete a file's passages together with their embeddings."""
217
+ connection.execute(
218
+ "DELETE FROM embeddings WHERE passage_rowid IN "
219
+ "(SELECT rowid FROM passages WHERE root = ? AND path = ?)",
220
+ (root, path),
221
+ )
222
+ connection.execute("DELETE FROM passages WHERE root = ? AND path = ?", (root, path))
223
+
224
+
207
225
  def _remove_stale(connection: sqlite3.Connection, root_key: str, present: set[str]) -> None:
208
226
  """Delete data of removed files, and of folders that no longer exist (moved/renamed)."""
209
227
  rows = connection.execute(
@@ -216,7 +234,8 @@ def _remove_stale(connection: sqlite3.Connection, root_key: str, present: set[st
216
234
  or (row["root"] != root_key and not os.path.isdir(row["root"]))
217
235
  ]
218
236
  with connection:
219
- connection.executemany("DELETE FROM passages WHERE root = ? AND path = ?", stale)
237
+ for root_value, path_value in stale:
238
+ _delete_passages(connection, root_value, path_value)
220
239
  connection.executemany("DELETE FROM files WHERE root = ? AND path = ?", stale)
221
240
 
222
241
 
@@ -254,7 +273,7 @@ def search(query: str, database: str | Path, limit: int = 5) -> list[dict]:
254
273
  if row["rowid"] not in seen and len(results) < limit:
255
274
  seen.add(row["rowid"])
256
275
  hit = dict(row)
257
- del hit["rowid"]
276
+ hit["id"] = hit.pop("rowid") # passage id, used to fuse rankings
258
277
  results.append(hit)
259
278
  if len(results) >= limit:
260
279
  break
@@ -3,13 +3,12 @@
3
3
  import ipaddress
4
4
  import json
5
5
  import os
6
- from urllib.parse import urlparse
7
6
  from urllib.error import HTTPError, URLError
7
+ from urllib.parse import urlparse
8
8
  from urllib.request import Request, urlopen
9
9
 
10
10
  from .index import citation
11
11
 
12
-
13
12
  DEFAULT_HOST = "http://127.0.0.1:11434"
14
13
 
15
14
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: offline-rag-kit
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Privacy-first local document search with PDF citations and optional Ollama answers
5
5
  Author: HugoDelgadoo
6
6
  Maintainer: HugoDelgadoo
@@ -27,6 +27,8 @@ Dynamic: license-file
27
27
  [![Python](https://img.shields.io/pypi/pyversions/offline-rag-kit)](https://pypi.org/project/offline-rag-kit/)
28
28
  [![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/LICENSE)
29
29
 
30
+ **English** | [Español](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/README.es.md)
31
+
30
32
  **Privacy-first local document search with PDF citations and optional local AI answers.**
31
33
 
32
34
  > **Status: v0.1 alpha — a working retrieval-first prototype, not yet a complete multimodal RAG system.**
@@ -73,7 +75,8 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
73
75
 
74
76
  ```text
75
77
  offline-rag [--db PATH] [--json] ingest FOLDER
76
- offline-rag [--db PATH] [--json] search "TERMS" [--limit 5]
78
+ offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid]
79
+ offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
77
80
  offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
78
81
  [--ollama-host URL] [--allow-remote]
79
82
  ```
@@ -82,6 +85,23 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
82
85
 
83
86
  `ask` talks to `127.0.0.1:11434` by default. Set `OLLAMA_HOST` or `--ollama-host` to use another port. Non-loopback hosts are refused unless you pass `--allow-remote`, because retrieved passages would then leave your machine.
84
87
 
88
+ ### Optional semantic search (local Ollama)
89
+
90
+ Plain `search` is lexical and works fully offline. To also match by meaning (for example "work from home" ~ "teletrabajo"), create embeddings **explicitly** with a local Ollama model, then choose a mode:
91
+
92
+ ```powershell
93
+ ollama pull bge-m3 # a multilingual embedding model
94
+ offline-rag embed --model bge-m3 # explicit step; only embeds new passages
95
+ offline-rag search "work from home" --mode hybrid # BM25 + vectors fused (RRF)
96
+ offline-rag search "work from home" --mode vector # vectors only
97
+ ```
98
+
99
+ - `ingest` never calls Ollama, and the default mode stays `lexical`. Semantic modes need Ollama running when you search, because the question must be embedded too.
100
+ - The index remembers which model made its vectors. Switching models needs `offline-rag embed --model NEW --rebuild`.
101
+ - Same privacy rule as `ask`: only loopback hosts are accepted unless you pass `--allow-remote`.
102
+ - Vectors are compared with a plain scan, which is fine for thousands of passages but slows down on very large collections. Embedding speed depends on your hardware and model.
103
+ - **Not yet measured with a real model.** Use `python -m offline_rag.eval --mode hybrid --model bge-m3` to see what it does on the bundled dataset.
104
+
85
105
  `--json` (placed before the subcommand) prints a single JSON document on stdout, with the full passage text, page, bounding box and score for each hit. Errors and exit codes are unchanged and still go to stderr.
86
106
 
87
107
  ## Current capabilities and limitations
@@ -92,7 +112,7 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
92
112
  | Lexical ranking with SQLite FTS5 (BM25) | Supported |
93
113
  | PDF source pages and block bounding boxes | Supported |
94
114
  | Local Ollama text generation | Optional, supported |
95
- | Semantic / vector retrieval | Planned |
115
+ | Semantic / vector retrieval | Optional, via local Ollama embeddings (not yet benchmarked) |
96
116
  | OCR, image understanding, audio transcription | Planned |
97
117
  | Web dashboard / user authentication | Planned |
98
118
  | Reliable claim-level grounding evaluation | Planned |
@@ -3,6 +3,7 @@ README.md
3
3
  pyproject.toml
4
4
  src/offline_rag/__init__.py
5
5
  src/offline_rag/cli.py
6
+ src/offline_rag/embeddings.py
6
7
  src/offline_rag/eval.py
7
8
  src/offline_rag/index.py
8
9
  src/offline_rag/ollama.py
@@ -13,6 +14,7 @@ src/offline_rag_kit.egg-info/entry_points.txt
13
14
  src/offline_rag_kit.egg-info/requires.txt
14
15
  src/offline_rag_kit.egg-info/top_level.txt
15
16
  tests/test_cli.py
17
+ tests/test_embeddings.py
16
18
  tests/test_eval.py
17
19
  tests/test_index.py
18
20
  tests/test_ollama.py
@@ -0,0 +1,178 @@
1
+ """Semantic retrieval tests with a fake embedder (no Ollama needed)."""
2
+
3
+ import contextlib
4
+ import io
5
+ import json
6
+ import sqlite3
7
+ import tempfile
8
+ import unittest
9
+ from contextlib import closing
10
+ from pathlib import Path
11
+ from unittest import mock
12
+ from urllib.error import HTTPError, URLError
13
+
14
+ from offline_rag import cli, embeddings
15
+ from offline_rag.embeddings import embed_index, hybrid_search, indexed_model, ollama_embedder, vector_search
16
+ from offline_rag.index import ingest, search
17
+
18
+ # Toy "semantic" space: words from the same group map to the same axis, so synonyms match.
19
+ GROUPS = [
20
+ {"remote", "home", "telework", "teletrabajo"},
21
+ {"vacation", "holiday", "leave", "vacaciones"},
22
+ {"password", "credential", "contraseña"},
23
+ {"invoice", "bill"},
24
+ ]
25
+
26
+
27
+ def fake_embedder(texts):
28
+ vectors = []
29
+ for text in texts:
30
+ words = {w.strip(".,?¿¡!").lower() for w in text.split()}
31
+ vector = [1.0 if words & group else 0.0 for group in GROUPS]
32
+ vector.append(0.05) # keeps vectors non-zero for unrelated text
33
+ vectors.append(vector)
34
+ return vectors
35
+
36
+
37
+ class EmbeddingTestBase(unittest.TestCase):
38
+ def setUp(self):
39
+ self.tmp = tempfile.TemporaryDirectory()
40
+ self.addCleanup(self.tmp.cleanup)
41
+ root = Path(self.tmp.name)
42
+ self.docs = root / "docs"
43
+ self.docs.mkdir()
44
+ self.db = root / "i.sqlite3"
45
+ (self.docs / "wfh.md").write_text("Telework is allowed three days a week.", encoding="utf-8")
46
+ (self.docs / "leave.md").write_text("Holiday requests need fifteen days of notice.", encoding="utf-8")
47
+ (self.docs / "pw.md").write_text("Credential sharing is forbidden.", encoding="utf-8")
48
+ ingest(self.docs, self.db)
49
+
50
+ def count(self, table):
51
+ with closing(sqlite3.connect(self.db)) as c:
52
+ return c.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
53
+
54
+
55
+ class EmbedIndexTests(EmbeddingTestBase):
56
+ def test_embeds_all_passages_once_and_incrementally(self):
57
+ self.assertEqual(embed_index(self.db, fake_embedder, "toy"), 3)
58
+ self.assertEqual(embed_index(self.db, fake_embedder, "toy"), 0) # nothing new
59
+ (self.docs / "bill.md").write_text("Every invoice is archived.", encoding="utf-8")
60
+ ingest(self.docs, self.db)
61
+ self.assertEqual(embed_index(self.db, fake_embedder, "toy"), 1)
62
+ self.assertEqual(indexed_model(self.db), "toy")
63
+
64
+ def test_switching_model_requires_rebuild(self):
65
+ embed_index(self.db, fake_embedder, "toy")
66
+ with self.assertRaisesRegex(ValueError, "--rebuild"):
67
+ embed_index(self.db, fake_embedder, "other")
68
+ self.assertEqual(embed_index(self.db, fake_embedder, "other", rebuild=True), 3)
69
+ self.assertEqual(indexed_model(self.db), "other")
70
+
71
+ def test_reindexing_or_deleting_files_removes_their_vectors(self):
72
+ embed_index(self.db, fake_embedder, "toy")
73
+ (self.docs / "wfh.md").write_text("Telework changed text.", encoding="utf-8")
74
+ (self.docs / "pw.md").unlink()
75
+ ingest(self.docs, self.db)
76
+ self.assertEqual(self.count("embeddings"), 1) # only leave.md keeps its vector
77
+ self.assertEqual(embed_index(self.db, fake_embedder, "toy"), 1) # the changed file
78
+ self.assertEqual(self.count("embeddings"), self.count("passages"))
79
+
80
+ def test_vectors_of_different_sizes_are_rejected(self):
81
+ sizes = iter([[1.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0]])
82
+ with self.assertRaisesRegex(ValueError, "different sizes"):
83
+ embed_index(self.db, lambda texts: [next(sizes) for _ in texts], "toy", batch_size=1)
84
+
85
+
86
+ class SearchTests(EmbeddingTestBase):
87
+ def setUp(self):
88
+ super().setUp()
89
+ embed_index(self.db, fake_embedder, "toy")
90
+
91
+ def test_vector_search_finds_synonyms_that_bm25_misses(self):
92
+ self.assertEqual(search("remote", self.db), []) # no shared word with the passage
93
+ hit = vector_search("remote", self.db, fake_embedder, limit=1)[0]
94
+ self.assertEqual(hit["path"], "wfh.md")
95
+ self.assertGreater(hit["score"], 0.9)
96
+
97
+ def test_hybrid_keeps_lexical_matches_and_adds_semantic_ones(self):
98
+ (self.docs / "extra.md").write_text("Retention schedule for logs.", encoding="utf-8")
99
+ ingest(self.docs, self.db)
100
+ embed_index(self.db, fake_embedder, "toy")
101
+ by_lexical = hybrid_search("retention", self.db, fake_embedder, limit=3)
102
+ self.assertEqual(by_lexical[0]["path"], "extra.md") # exact word still wins
103
+ by_meaning = hybrid_search("holiday", self.db, fake_embedder, limit=1)
104
+ self.assertEqual(by_meaning[0]["path"], "leave.md")
105
+ paths = [h["path"] for h in hybrid_search("remote", self.db, fake_embedder, limit=3)]
106
+ self.assertEqual(paths[0], "wfh.md")
107
+ self.assertEqual(len(paths), len(set(paths))) # fused list has no duplicates
108
+
109
+ def test_vector_search_without_embeddings_explains_what_to_do(self):
110
+ other = Path(self.tmp.name) / "plain.sqlite3"
111
+ ingest(self.docs, other)
112
+ with self.assertRaisesRegex(ValueError, "offline-rag embed"):
113
+ vector_search("x", other, fake_embedder)
114
+
115
+ def test_query_with_wrong_dimension_is_reported(self):
116
+ with self.assertRaisesRegex(ValueError, "model changed"):
117
+ vector_search("x", self.db, lambda texts: [[1.0, 0.0]])
118
+
119
+
120
+ class OllamaProtocolTests(unittest.TestCase):
121
+ def response(self, payload):
122
+ return io.BytesIO(json.dumps(payload).encode())
123
+
124
+ def test_posts_to_api_embed_and_returns_vectors(self):
125
+ reply = self.response({"embeddings": [[1, 0], [0, 1]]})
126
+ with mock.patch.object(embeddings, "urlopen", return_value=reply) as urlopen:
127
+ vectors = ollama_embedder("bge-m3", host="localhost:5555")(["a", "b"])
128
+ request = urlopen.call_args.args[0]
129
+ self.assertEqual(request.full_url, "http://localhost:5555/api/embed")
130
+ body = json.loads(request.data)
131
+ self.assertEqual((body["model"], body["input"]), ("bge-m3", ["a", "b"]))
132
+ self.assertEqual(vectors, [[1, 0], [0, 1]])
133
+
134
+ def test_remote_host_refused_before_any_request(self):
135
+ with mock.patch.object(embeddings, "urlopen") as urlopen:
136
+ with self.assertRaisesRegex(ValueError, "non-loopback"):
137
+ ollama_embedder("m", host="example.com")
138
+ urlopen.assert_not_called()
139
+
140
+ def test_errors_are_actionable(self):
141
+ with mock.patch.object(embeddings, "urlopen", side_effect=URLError("refused")):
142
+ with self.assertRaisesRegex(RuntimeError, "ollama serve"):
143
+ ollama_embedder("m")(["a"])
144
+ not_found = HTTPError("u", 404, "nf", {}, io.BytesIO(b'{"error": "model not found"}'))
145
+ with mock.patch.object(embeddings, "urlopen", side_effect=not_found):
146
+ with self.assertRaisesRegex(RuntimeError, "ollama pull m"):
147
+ ollama_embedder("m")(["a"])
148
+
149
+ def test_malformed_response_is_rejected(self):
150
+ for bad in ({}, {"embeddings": [[1.0]]}, {"embeddings": [[]]}):
151
+ with self.subTest(bad=bad):
152
+ with mock.patch.object(embeddings, "urlopen", return_value=self.response(bad)):
153
+ with self.assertRaisesRegex(RuntimeError, "Unexpected response"):
154
+ ollama_embedder("m")(["a", "b"])
155
+
156
+
157
+ class CliTests(EmbeddingTestBase):
158
+ def run_cli(self, *argv):
159
+ out = io.StringIO()
160
+ with contextlib.redirect_stdout(out), mock.patch.object(cli, "ollama_embedder", return_value=fake_embedder):
161
+ cli.main(["--db", str(self.db), *argv])
162
+ return out.getvalue()
163
+
164
+ def test_embed_then_semantic_search_and_json(self):
165
+ self.assertIn("Embedded 3 passages with toy", self.run_cli("embed", "--model", "toy"))
166
+ data = json.loads(self.run_cli("--json", "search", "remote", "--mode", "hybrid", "--limit", "1"))
167
+ self.assertEqual(data["results"][0]["citation"], "wfh.md")
168
+ self.assertEqual(self.run_cli("search", "remote"), "No matching passages found.\n") # default stays lexical
169
+
170
+ def test_vector_mode_without_embeddings_fails_clearly(self):
171
+ err = io.StringIO()
172
+ with contextlib.redirect_stderr(err), self.assertRaises(SystemExit):
173
+ self.run_cli("search", "remote", "--mode", "vector")
174
+ self.assertIn("offline-rag embed", err.getvalue())
175
+
176
+
177
+ if __name__ == "__main__":
178
+ unittest.main()
@@ -0,0 +1,56 @@
1
+ """The bundled evaluation set must stay valid and keep a minimum BM25 baseline."""
2
+
3
+ import contextlib
4
+ import io
5
+ import json
6
+ import unittest
7
+ from pathlib import Path
8
+
9
+ from offline_rag import eval as eval_cli
10
+ from offline_rag.eval import evaluate
11
+
12
+ ROOT = Path(__file__).resolve().parent.parent
13
+
14
+
15
+ class EvalTests(unittest.TestCase):
16
+ def test_bundled_dataset_is_consistent_and_meets_baseline(self):
17
+ corpus = ROOT / "eval" / "corpus"
18
+ questions = json.loads((ROOT / "eval" / "questions.json").read_text(encoding="utf-8"))["questions"]
19
+ for item in questions: # every expected passage really exists in the corpus
20
+ text = (corpus / item["path"]).read_text(encoding="utf-8").lower()
21
+ self.assertIn(item["contains"].lower(), text, item["q"])
22
+ report = evaluate(corpus, questions)
23
+ # Word-overlap questions must keep working; paraphrase / cross-lingual kinds are
24
+ # tracked in docs/EVALUATION.md but are expected to be weak for lexical search.
25
+ for kind in ("lexical", "multilingual"):
26
+ self.assertGreaterEqual(report["by_kind"][kind]["mrr"], 0.9, kind)
27
+ self.assertGreaterEqual(report["overall"]["recall@5"], 0.8)
28
+
29
+ def run_main(self, *argv):
30
+ out = io.StringIO()
31
+ with contextlib.redirect_stdout(out):
32
+ eval_cli.main([
33
+ "--corpus", str(ROOT / "eval" / "corpus"),
34
+ "--questions", str(ROOT / "eval" / "questions.json"),
35
+ *argv,
36
+ ])
37
+ return out.getvalue()
38
+
39
+ def test_command_prints_table_and_json(self):
40
+ table = self.run_main()
41
+ self.assertIn("overall", table)
42
+ self.assertIn("Not found in top 5", table) # paraphrase questions BM25 cannot answer
43
+ report = json.loads(self.run_main("--json"))
44
+ self.assertEqual(report["overall"]["questions"], len(report["rows"]))
45
+
46
+ def test_missing_questions_file_is_a_clean_error(self):
47
+ with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
48
+ eval_cli.main(["--questions", str(ROOT / "nope.json")])
49
+
50
+ def test_semantic_modes_refuse_remote_hosts(self):
51
+ with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
52
+ eval_cli.main(["--mode", "hybrid", "--ollama-host", "example.com"])
53
+
54
+
55
+ if __name__ == "__main__":
56
+ unittest.main()
@@ -122,7 +122,9 @@ class IndexTests(unittest.TestCase):
122
122
  import sqlite3
123
123
 
124
124
  with sqlite3.connect(self.db) as old:
125
- old.execute("CREATE VIRTUAL TABLE passages USING fts5(path UNINDEXED, page UNINDEXED, bbox UNINDEXED, body)")
125
+ old.execute(
126
+ "CREATE VIRTUAL TABLE passages USING fts5(path UNINDEXED, page UNINDEXED, bbox UNINDEXED, body)"
127
+ )
126
128
  old.close()
127
129
  with self.assertRaisesRegex(ValueError, "older version"):
128
130
  search("anything", self.db)
@@ -135,6 +137,13 @@ class IndexTests(unittest.TestCase):
135
137
  self.assertIn("**needle**", hit["snippet"])
136
138
  self.assertLess(len(hit["snippet"]), len(hit["body"]))
137
139
 
140
+ def test_broken_pdf_is_not_left_open_after_ingest(self):
141
+ broken = self.docs / "broken.pdf"
142
+ broken.write_bytes(b"not a real pdf")
143
+ result = ingest(self.docs, self.db)
144
+ self.assertEqual(len(result.skipped), 1)
145
+ broken.unlink() # raises PermissionError on Windows if the file is still held open
146
+
138
147
  def test_unchanged_files_are_not_reparsed(self):
139
148
  (self.docs / "a.md").write_text("stable text", encoding="utf-8")
140
149
  ingest(self.docs, self.db)
@@ -174,7 +183,9 @@ class IndexTests(unittest.TestCase):
174
183
  def _pdf_with_table(self, path):
175
184
  with pymupdf.open() as doc:
176
185
  page = doc.new_page()
177
- page.insert_textbox(pymupdf.Rect(72, 72, 300, 120), "Retention periods are reviewed every year.", fontsize=11)
186
+ page.insert_textbox(
187
+ pymupdf.Rect(72, 72, 300, 120), "Retention periods are reviewed every year.", fontsize=11
188
+ )
178
189
  for r, row in enumerate([["Item", "Years"], ["Invoices", "10"], ["Tickets", "3"]]):
179
190
  for c, value in enumerate(row):
180
191
  rect = pymupdf.Rect(72 + c * 100, 230 + r * 24, 172 + c * 100, 254 + r * 24)
@@ -1,25 +0,0 @@
1
- """The bundled evaluation set must stay valid and keep a minimum BM25 baseline."""
2
-
3
- import json
4
- import unittest
5
- from pathlib import Path
6
-
7
- from offline_rag.eval import evaluate
8
-
9
- ROOT = Path(__file__).resolve().parent.parent
10
-
11
-
12
- class EvalTests(unittest.TestCase):
13
- def test_bundled_dataset_is_consistent_and_meets_baseline(self):
14
- corpus = ROOT / "eval" / "corpus"
15
- questions = json.loads((ROOT / "eval" / "questions.json").read_text(encoding="utf-8"))["questions"]
16
- for item in questions: # every expected passage really exists in the corpus
17
- text = (corpus / item["path"]).read_text(encoding="utf-8").lower()
18
- self.assertIn(item["contains"].lower(), text, item["q"])
19
- report = evaluate(corpus, questions)
20
- self.assertGreaterEqual(report["overall"]["recall@5"], 0.9)
21
- self.assertGreaterEqual(report["by_kind"]["lexical"]["mrr"], 0.9)
22
-
23
-
24
- if __name__ == "__main__":
25
- unittest.main()
File without changes