offline-rag-kit 0.1.3__tar.gz → 0.1.4__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.
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/PKG-INFO +29 -2
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/README.md +28 -1
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/pyproject.toml +1 -1
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag/__init__.py +1 -1
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag/cli.py +47 -4
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag/index.py +62 -7
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/PKG-INFO +29 -2
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/SOURCES.txt +1 -0
- offline_rag_kit-0.1.4/tests/test_files.py +108 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/LICENSE +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/setup.cfg +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag/embeddings.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag/eval.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag/ollama.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/dependency_links.txt +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/entry_points.txt +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/requires.txt +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/top_level.txt +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/tests/test_cli.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/tests/test_embeddings.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/tests/test_eval.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/tests/test_index.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/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.
|
|
3
|
+
Version: 0.1.4
|
|
4
4
|
Summary: Privacy-first local document search with PDF citations and optional Ollama answers
|
|
5
5
|
Author: HugoDelgadoo
|
|
6
6
|
Maintainer: HugoDelgadoo
|
|
@@ -62,6 +62,16 @@ offline-rag ingest "C:\Users\YourUser\Documents\knowledge"
|
|
|
62
62
|
offline-rag search "retention policy"
|
|
63
63
|
```
|
|
64
64
|
|
|
65
|
+
### Use it from any terminal, and where the index lives
|
|
66
|
+
|
|
67
|
+
- **Install once, use anywhere:** `pipx install offline-rag-kit` makes the `offline-rag` command available in every terminal. With plain `pip` inside a virtual environment it only works while that environment is active. If your terminal says `offline-rag` is not recognized, Python's scripts folder is not on your `PATH`; `pipx ensurepath` fixes that.
|
|
68
|
+
- **The index is saved in the folder where you run the command**, as `.offline-rag/index.sqlite3`. If you index in one folder and search from another, the second folder has no index and finds nothing. To always use the same index, give a fixed path with `--db`:
|
|
69
|
+
|
|
70
|
+
```powershell
|
|
71
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 ingest C:\Users\You\Documents
|
|
72
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 search "policy"
|
|
73
|
+
```
|
|
74
|
+
|
|
65
75
|
To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
|
|
66
76
|
|
|
67
77
|
```powershell
|
|
@@ -75,12 +85,29 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
|
|
|
75
85
|
|
|
76
86
|
```text
|
|
77
87
|
offline-rag [--db PATH] [--json] ingest FOLDER
|
|
78
|
-
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid]
|
|
88
|
+
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid] [--files]
|
|
79
89
|
offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
|
|
80
90
|
offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
|
|
81
91
|
[--ollama-host URL] [--allow-remote]
|
|
82
92
|
```
|
|
83
93
|
|
|
94
|
+
### Which files contain a word?
|
|
95
|
+
|
|
96
|
+
By default `search` prints the best matching **passages** (the same file can appear several times). To get a list of **files** instead, add `--files`: each file appears once, with its full path, how many passages match and, for PDFs, the pages.
|
|
97
|
+
|
|
98
|
+
```powershell
|
|
99
|
+
offline-rag search "policy" --files
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
```text
|
|
103
|
+
3 files contain 'policy':
|
|
104
|
+
C:\Users\You\Documents\notes\meeting.md (2 matching passages)
|
|
105
|
+
C:\Users\You\Documents\handbook.md (1 matching passage)
|
|
106
|
+
C:\Users\You\Documents\contract.pdf (2 matching passages; pages 1, 3)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Files containing **every** word are listed; if there are none, files containing at least one word are listed and the output says so. `--limit` (default 20, up to 100) caps the list, while the first line always shows the total. `--files` works only in the default lexical mode.
|
|
110
|
+
|
|
84
111
|
Re-running `ingest` is incremental: unchanged files (by content hash) are not re-parsed.
|
|
85
112
|
|
|
86
113
|
`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.
|
|
@@ -40,6 +40,16 @@ offline-rag ingest "C:\Users\YourUser\Documents\knowledge"
|
|
|
40
40
|
offline-rag search "retention policy"
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
+
### Use it from any terminal, and where the index lives
|
|
44
|
+
|
|
45
|
+
- **Install once, use anywhere:** `pipx install offline-rag-kit` makes the `offline-rag` command available in every terminal. With plain `pip` inside a virtual environment it only works while that environment is active. If your terminal says `offline-rag` is not recognized, Python's scripts folder is not on your `PATH`; `pipx ensurepath` fixes that.
|
|
46
|
+
- **The index is saved in the folder where you run the command**, as `.offline-rag/index.sqlite3`. If you index in one folder and search from another, the second folder has no index and finds nothing. To always use the same index, give a fixed path with `--db`:
|
|
47
|
+
|
|
48
|
+
```powershell
|
|
49
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 ingest C:\Users\You\Documents
|
|
50
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 search "policy"
|
|
51
|
+
```
|
|
52
|
+
|
|
43
53
|
To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
|
|
44
54
|
|
|
45
55
|
```powershell
|
|
@@ -53,12 +63,29 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
|
|
|
53
63
|
|
|
54
64
|
```text
|
|
55
65
|
offline-rag [--db PATH] [--json] ingest FOLDER
|
|
56
|
-
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid]
|
|
66
|
+
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid] [--files]
|
|
57
67
|
offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
|
|
58
68
|
offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
|
|
59
69
|
[--ollama-host URL] [--allow-remote]
|
|
60
70
|
```
|
|
61
71
|
|
|
72
|
+
### Which files contain a word?
|
|
73
|
+
|
|
74
|
+
By default `search` prints the best matching **passages** (the same file can appear several times). To get a list of **files** instead, add `--files`: each file appears once, with its full path, how many passages match and, for PDFs, the pages.
|
|
75
|
+
|
|
76
|
+
```powershell
|
|
77
|
+
offline-rag search "policy" --files
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
```text
|
|
81
|
+
3 files contain 'policy':
|
|
82
|
+
C:\Users\You\Documents\notes\meeting.md (2 matching passages)
|
|
83
|
+
C:\Users\You\Documents\handbook.md (1 matching passage)
|
|
84
|
+
C:\Users\You\Documents\contract.pdf (2 matching passages; pages 1, 3)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Files containing **every** word are listed; if there are none, files containing at least one word are listed and the output says so. `--limit` (default 20, up to 100) caps the list, while the first line always shows the total. `--files` works only in the default lexical mode.
|
|
88
|
+
|
|
62
89
|
Re-running `ingest` is incremental: unchanged files (by content hash) are not re-parsed.
|
|
63
90
|
|
|
64
91
|
`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.
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "offline-rag-kit"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.4"
|
|
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"
|
|
@@ -5,7 +5,7 @@ import json
|
|
|
5
5
|
import sys
|
|
6
6
|
|
|
7
7
|
from .embeddings import DEFAULT_MODEL, embed_index, hybrid_search, indexed_model, ollama_embedder, vector_search
|
|
8
|
-
from .index import citation, ingest, search
|
|
8
|
+
from .index import citation, ingest, search, search_files
|
|
9
9
|
from .ollama import answer_with_ollama
|
|
10
10
|
|
|
11
11
|
|
|
@@ -33,7 +33,10 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
33
33
|
for command in ("search", "ask"):
|
|
34
34
|
sub = commands.add_parser(command, help="Search locally" if command == "search" else "Ask local Ollama")
|
|
35
35
|
sub.add_argument("query", help="Question or search terms")
|
|
36
|
-
sub.add_argument(
|
|
36
|
+
sub.add_argument(
|
|
37
|
+
"--limit", type=int, default=None,
|
|
38
|
+
help="Maximum results (default: 5 passages, or 20 files with --files)",
|
|
39
|
+
)
|
|
37
40
|
sub.add_argument(
|
|
38
41
|
"--mode", choices=("lexical", "vector", "hybrid"), default="lexical",
|
|
39
42
|
help="lexical (default, offline); vector/hybrid need 'offline-rag embed' and a running Ollama",
|
|
@@ -43,6 +46,11 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
43
46
|
"--allow-remote", action="store_true",
|
|
44
47
|
help="Allow a non-loopback Ollama host (text is sent to it)",
|
|
45
48
|
)
|
|
49
|
+
if command == "search":
|
|
50
|
+
sub.add_argument(
|
|
51
|
+
"--files", action="store_true",
|
|
52
|
+
help="List the files that contain the terms (full path, matches, pages) instead of passages",
|
|
53
|
+
)
|
|
46
54
|
if command == "ask":
|
|
47
55
|
sub.add_argument("--model", default="llama3.2", help="Ollama model used to write the answer")
|
|
48
56
|
return parser
|
|
@@ -65,15 +73,41 @@ def _dump(payload: dict) -> None:
|
|
|
65
73
|
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
66
74
|
|
|
67
75
|
|
|
76
|
+
def _format_pages(pages: list[int], shown: int = 10) -> str:
|
|
77
|
+
text = ", ".join(str(p) for p in pages[:shown])
|
|
78
|
+
return text + (f", … (+{len(pages) - shown})" if len(pages) > shown else "")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _print_files(query: str, result: dict) -> None:
|
|
82
|
+
total = result["total"]
|
|
83
|
+
if not total:
|
|
84
|
+
print("No files found.")
|
|
85
|
+
return
|
|
86
|
+
noun, verb = ("file", "contains") if total == 1 else ("files", "contain")
|
|
87
|
+
if result["match"] == "any":
|
|
88
|
+
print(f"No file contains all the words of {query!r}; {total} {noun} {verb} at least one of them:")
|
|
89
|
+
else:
|
|
90
|
+
print(f"{total} {noun} {verb} {query!r}:")
|
|
91
|
+
for item in result["files"]:
|
|
92
|
+
count = item["matches"]
|
|
93
|
+
detail = f"{count} matching passage{'s' if count != 1 else ''}"
|
|
94
|
+
if item["pages"]:
|
|
95
|
+
detail += f"; page{'s' if len(item['pages']) != 1 else ''} {_format_pages(item['pages'])}"
|
|
96
|
+
print(f" {item['path']} ({detail})")
|
|
97
|
+
if total > len(result["files"]):
|
|
98
|
+
print(f"Showing the first {len(result['files'])} of {total}. Use --limit to see more (up to 100).")
|
|
99
|
+
|
|
100
|
+
|
|
68
101
|
def _retrieve(args) -> list[dict]:
|
|
102
|
+
limit = args.limit if args.limit is not None else 5
|
|
69
103
|
if args.mode == "lexical":
|
|
70
|
-
return search(args.query, args.db,
|
|
104
|
+
return search(args.query, args.db, limit)
|
|
71
105
|
model = indexed_model(args.db)
|
|
72
106
|
if model is None:
|
|
73
107
|
raise ValueError("This index has no embeddings. Run 'offline-rag embed' first.")
|
|
74
108
|
embedder = ollama_embedder(model, args.ollama_host, args.allow_remote)
|
|
75
109
|
run = vector_search if args.mode == "vector" else hybrid_search
|
|
76
|
-
return run(args.query, args.db, embedder,
|
|
110
|
+
return run(args.query, args.db, embedder, limit)
|
|
77
111
|
|
|
78
112
|
|
|
79
113
|
def main(argv: list[str] | None = None) -> None:
|
|
@@ -101,6 +135,15 @@ def main(argv: list[str] | None = None) -> None:
|
|
|
101
135
|
_dump({"embedded": count, "model": args.model, "database": args.db})
|
|
102
136
|
else:
|
|
103
137
|
print(f"Embedded {count} passages with {args.model} in {args.db}")
|
|
138
|
+
elif args.command == "search" and args.files:
|
|
139
|
+
if args.mode != "lexical":
|
|
140
|
+
raise ValueError("--files lists files that contain the words, so it only works with --mode lexical.")
|
|
141
|
+
limit = args.limit if args.limit is not None else 20
|
|
142
|
+
result = search_files(args.query, args.db, limit)
|
|
143
|
+
if args.json:
|
|
144
|
+
_dump({"query": args.query, **result})
|
|
145
|
+
else:
|
|
146
|
+
_print_files(args.query, result)
|
|
104
147
|
else:
|
|
105
148
|
hits = _retrieve(args)
|
|
106
149
|
if args.command == "search":
|
|
@@ -239,6 +239,21 @@ def _remove_stale(connection: sqlite3.Connection, root_key: str, present: set[st
|
|
|
239
239
|
connection.executemany("DELETE FROM files WHERE root = ? AND path = ?", stale)
|
|
240
240
|
|
|
241
241
|
|
|
242
|
+
def _match_expressions(query: str) -> list[tuple[str, str]]:
|
|
243
|
+
"""FTS5 expressions for a query: ("all", every term) first, then ("any", some term).
|
|
244
|
+
|
|
245
|
+
Quoting every user token avoids injecting FTS5 operators or syntax.
|
|
246
|
+
"""
|
|
247
|
+
tokens = list(dict.fromkeys(re.findall(r"\w+", query, flags=re.UNICODE)))
|
|
248
|
+
if not tokens:
|
|
249
|
+
return []
|
|
250
|
+
quoted = [f'"{token}"' for token in tokens]
|
|
251
|
+
expressions = [("all", " AND ".join(quoted))]
|
|
252
|
+
if len(quoted) > 1:
|
|
253
|
+
expressions.append(("any", " OR ".join(quoted)))
|
|
254
|
+
return expressions
|
|
255
|
+
|
|
256
|
+
|
|
242
257
|
def search(query: str, database: str | Path, limit: int = 5) -> list[dict]:
|
|
243
258
|
"""Rank passages with BM25, preferring passages that contain every term.
|
|
244
259
|
|
|
@@ -248,14 +263,9 @@ def search(query: str, database: str | Path, limit: int = 5) -> list[dict]:
|
|
|
248
263
|
"""
|
|
249
264
|
if limit < 1 or limit > 100:
|
|
250
265
|
raise ValueError("limit must be between 1 and 100")
|
|
251
|
-
|
|
252
|
-
if not
|
|
266
|
+
modes = [expression for _, expression in _match_expressions(query)]
|
|
267
|
+
if not modes:
|
|
253
268
|
return []
|
|
254
|
-
# Quoting every user token avoids injecting FTS5 operators or syntax.
|
|
255
|
-
quoted = [f'"{token}"' for token in tokens]
|
|
256
|
-
modes = [" AND ".join(quoted)]
|
|
257
|
-
if len(quoted) > 1:
|
|
258
|
-
modes.append(" OR ".join(quoted))
|
|
259
269
|
results: list[dict] = []
|
|
260
270
|
seen: set[int] = set()
|
|
261
271
|
with closing(open_index(database)) as connection:
|
|
@@ -280,6 +290,51 @@ def search(query: str, database: str | Path, limit: int = 5) -> list[dict]:
|
|
|
280
290
|
return results
|
|
281
291
|
|
|
282
292
|
|
|
293
|
+
def search_files(query: str, database: str | Path, limit: int = 20) -> dict:
|
|
294
|
+
"""List the files that contain the query, each once, with how many passages match.
|
|
295
|
+
|
|
296
|
+
Files containing every term are listed; if there are none and the query has several
|
|
297
|
+
terms, files containing at least one term are listed instead (``match`` is then "any").
|
|
298
|
+
``total`` counts all matching files, ``files`` holds the best ``limit`` of them.
|
|
299
|
+
"""
|
|
300
|
+
if limit < 1 or limit > 100:
|
|
301
|
+
raise ValueError("limit must be between 1 and 100")
|
|
302
|
+
expressions = _match_expressions(query)
|
|
303
|
+
kind, rows = "all", []
|
|
304
|
+
with closing(open_index(database)) as connection:
|
|
305
|
+
for kind, expression in expressions: # noqa: B007 - the last kind is reported if nothing matches
|
|
306
|
+
rows = connection.execute(
|
|
307
|
+
"SELECT root, path, page, bm25(passages) AS score FROM passages WHERE passages MATCH ?",
|
|
308
|
+
(expression,),
|
|
309
|
+
).fetchall()
|
|
310
|
+
if rows:
|
|
311
|
+
break
|
|
312
|
+
grouped: dict[tuple[str, str], dict] = {}
|
|
313
|
+
for row in rows:
|
|
314
|
+
entry = grouped.setdefault(
|
|
315
|
+
(row["root"], row["path"]),
|
|
316
|
+
{"root": row["root"], "path": row["path"], "matches": 0, "pages": set(), "score": row["score"]},
|
|
317
|
+
)
|
|
318
|
+
entry["matches"] += 1
|
|
319
|
+
entry["score"] = min(entry["score"], row["score"])
|
|
320
|
+
if row["page"]:
|
|
321
|
+
entry["pages"].add(row["page"])
|
|
322
|
+
files = sorted(grouped.values(), key=lambda e: (e["score"], e["root"], e["path"]))
|
|
323
|
+
return {
|
|
324
|
+
"match": kind,
|
|
325
|
+
"total": len(files),
|
|
326
|
+
"files": [
|
|
327
|
+
{
|
|
328
|
+
"path": str(Path(e["root"]) / e["path"]),
|
|
329
|
+
"relative_path": e["path"],
|
|
330
|
+
"matches": e["matches"],
|
|
331
|
+
"pages": sorted(e["pages"]),
|
|
332
|
+
}
|
|
333
|
+
for e in files[:limit]
|
|
334
|
+
],
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
|
|
283
338
|
def citation(result: dict) -> str:
|
|
284
339
|
name = result["path"]
|
|
285
340
|
if result["page"]:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: offline-rag-kit
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
4
4
|
Summary: Privacy-first local document search with PDF citations and optional Ollama answers
|
|
5
5
|
Author: HugoDelgadoo
|
|
6
6
|
Maintainer: HugoDelgadoo
|
|
@@ -62,6 +62,16 @@ offline-rag ingest "C:\Users\YourUser\Documents\knowledge"
|
|
|
62
62
|
offline-rag search "retention policy"
|
|
63
63
|
```
|
|
64
64
|
|
|
65
|
+
### Use it from any terminal, and where the index lives
|
|
66
|
+
|
|
67
|
+
- **Install once, use anywhere:** `pipx install offline-rag-kit` makes the `offline-rag` command available in every terminal. With plain `pip` inside a virtual environment it only works while that environment is active. If your terminal says `offline-rag` is not recognized, Python's scripts folder is not on your `PATH`; `pipx ensurepath` fixes that.
|
|
68
|
+
- **The index is saved in the folder where you run the command**, as `.offline-rag/index.sqlite3`. If you index in one folder and search from another, the second folder has no index and finds nothing. To always use the same index, give a fixed path with `--db`:
|
|
69
|
+
|
|
70
|
+
```powershell
|
|
71
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 ingest C:\Users\You\Documents
|
|
72
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 search "policy"
|
|
73
|
+
```
|
|
74
|
+
|
|
65
75
|
To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
|
|
66
76
|
|
|
67
77
|
```powershell
|
|
@@ -75,12 +85,29 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
|
|
|
75
85
|
|
|
76
86
|
```text
|
|
77
87
|
offline-rag [--db PATH] [--json] ingest FOLDER
|
|
78
|
-
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid]
|
|
88
|
+
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid] [--files]
|
|
79
89
|
offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
|
|
80
90
|
offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
|
|
81
91
|
[--ollama-host URL] [--allow-remote]
|
|
82
92
|
```
|
|
83
93
|
|
|
94
|
+
### Which files contain a word?
|
|
95
|
+
|
|
96
|
+
By default `search` prints the best matching **passages** (the same file can appear several times). To get a list of **files** instead, add `--files`: each file appears once, with its full path, how many passages match and, for PDFs, the pages.
|
|
97
|
+
|
|
98
|
+
```powershell
|
|
99
|
+
offline-rag search "policy" --files
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
```text
|
|
103
|
+
3 files contain 'policy':
|
|
104
|
+
C:\Users\You\Documents\notes\meeting.md (2 matching passages)
|
|
105
|
+
C:\Users\You\Documents\handbook.md (1 matching passage)
|
|
106
|
+
C:\Users\You\Documents\contract.pdf (2 matching passages; pages 1, 3)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Files containing **every** word are listed; if there are none, files containing at least one word are listed and the output says so. `--limit` (default 20, up to 100) caps the list, while the first line always shows the total. `--files` works only in the default lexical mode.
|
|
110
|
+
|
|
84
111
|
Re-running `ingest` is incremental: unchanged files (by content hash) are not re-parsed.
|
|
85
112
|
|
|
86
113
|
`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.
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""`search --files`: one line per file with full path, match count and pages."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import io
|
|
5
|
+
import json
|
|
6
|
+
import tempfile
|
|
7
|
+
import unittest
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import pymupdf
|
|
11
|
+
|
|
12
|
+
from offline_rag import cli
|
|
13
|
+
from offline_rag.index import ingest, search_files
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FilesTestBase(unittest.TestCase):
|
|
17
|
+
def setUp(self):
|
|
18
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
19
|
+
self.addCleanup(self.tmp.cleanup)
|
|
20
|
+
root = Path(self.tmp.name)
|
|
21
|
+
self.docs = root / "docs"
|
|
22
|
+
(self.docs / "notes").mkdir(parents=True)
|
|
23
|
+
self.db = root / "i.sqlite3"
|
|
24
|
+
(self.docs / "notes" / "meeting.md").write_text(
|
|
25
|
+
"We reviewed the vacation policy.\n\nThe retention policy was postponed.\n\nLunch is at noon.",
|
|
26
|
+
encoding="utf-8",
|
|
27
|
+
)
|
|
28
|
+
(self.docs / "handbook.md").write_text("Our policy on remote work.", encoding="utf-8")
|
|
29
|
+
(self.docs / "other.md").write_text("Nothing relevant here.", encoding="utf-8")
|
|
30
|
+
with pymupdf.open() as doc:
|
|
31
|
+
for text in ("Page one has the policy text.", "Page two is unrelated.", "Page three repeats policy."):
|
|
32
|
+
doc.new_page().insert_text((72, 90), text)
|
|
33
|
+
doc.save(self.docs / "contract.pdf")
|
|
34
|
+
ingest(self.docs, self.db)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class SearchFilesTests(FilesTestBase):
|
|
38
|
+
def test_each_file_once_with_count_pages_and_full_path(self):
|
|
39
|
+
result = search_files("policy", self.db)
|
|
40
|
+
self.assertEqual(result["match"], "all")
|
|
41
|
+
self.assertEqual(result["total"], 3)
|
|
42
|
+
by_name = {Path(f["path"]).name: f for f in result["files"]}
|
|
43
|
+
self.assertEqual(set(by_name), {"meeting.md", "handbook.md", "contract.pdf"})
|
|
44
|
+
self.assertEqual(by_name["meeting.md"]["matches"], 2) # two passages mention it
|
|
45
|
+
self.assertEqual(by_name["contract.pdf"]["pages"], [1, 3])
|
|
46
|
+
self.assertEqual(by_name["meeting.md"]["pages"], [])
|
|
47
|
+
self.assertEqual(Path(by_name["meeting.md"]["path"]), self.docs.resolve() / "notes" / "meeting.md")
|
|
48
|
+
self.assertEqual(by_name["meeting.md"]["relative_path"], "notes/meeting.md")
|
|
49
|
+
|
|
50
|
+
def test_requires_all_terms_then_falls_back_to_any(self):
|
|
51
|
+
both = search_files("retention policy", self.db)
|
|
52
|
+
self.assertEqual((both["match"], both["total"]), ("all", 1))
|
|
53
|
+
fallback = search_files("retention vacation lunch zzz", self.db) # no passage has all four
|
|
54
|
+
self.assertEqual(fallback["match"], "any")
|
|
55
|
+
self.assertEqual(fallback["total"], 1) # only meeting.md contains any of them
|
|
56
|
+
|
|
57
|
+
def test_limit_keeps_the_total(self):
|
|
58
|
+
result = search_files("policy", self.db, limit=1)
|
|
59
|
+
self.assertEqual((result["total"], len(result["files"])), (3, 1))
|
|
60
|
+
|
|
61
|
+
def test_no_results_and_invalid_input(self):
|
|
62
|
+
self.assertEqual(search_files("zzzz", self.db)["total"], 0)
|
|
63
|
+
self.assertEqual(search_files("???", self.db), {"match": "all", "total": 0, "files": []})
|
|
64
|
+
with self.assertRaises(ValueError):
|
|
65
|
+
search_files("policy", self.db, limit=0)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class CliFilesTests(FilesTestBase):
|
|
69
|
+
def run_cli(self, *argv):
|
|
70
|
+
out = io.StringIO()
|
|
71
|
+
with contextlib.redirect_stdout(out):
|
|
72
|
+
cli.main(["--db", str(self.db), *argv])
|
|
73
|
+
return out.getvalue()
|
|
74
|
+
|
|
75
|
+
def test_text_output_lists_files_with_paths_and_pages(self):
|
|
76
|
+
text = self.run_cli("search", "policy", "--files")
|
|
77
|
+
self.assertIn("3 files contain 'policy':", text)
|
|
78
|
+
self.assertIn(str(self.docs.resolve() / "notes" / "meeting.md"), text)
|
|
79
|
+
self.assertIn("2 matching passages", text)
|
|
80
|
+
self.assertIn("pages 1, 3", text)
|
|
81
|
+
|
|
82
|
+
def test_singular_forms_and_truncation_hint(self):
|
|
83
|
+
self.assertIn("1 file contains 'retention policy':", self.run_cli("search", "retention policy", "--files"))
|
|
84
|
+
self.assertIn("Showing the first 1 of 3", self.run_cli("search", "policy", "--files", "--limit", "1"))
|
|
85
|
+
self.assertEqual(self.run_cli("search", "zzzz", "--files"), "No files found.\n")
|
|
86
|
+
|
|
87
|
+
def test_fallback_is_explained(self):
|
|
88
|
+
text = self.run_cli("search", "retention vacation zzz", "--files")
|
|
89
|
+
self.assertIn("No file contains all the words", text)
|
|
90
|
+
self.assertIn("1 file contains at least one of them", text)
|
|
91
|
+
|
|
92
|
+
def test_json_output(self):
|
|
93
|
+
data = json.loads(self.run_cli("--json", "search", "policy", "--files"))
|
|
94
|
+
self.assertEqual((data["query"], data["total"], data["match"]), ("policy", 3, "all"))
|
|
95
|
+
self.assertTrue(all({"path", "relative_path", "matches", "pages"} <= set(f) for f in data["files"]))
|
|
96
|
+
|
|
97
|
+
def test_default_search_is_unchanged(self):
|
|
98
|
+
self.assertIn("[1] ", self.run_cli("search", "policy"))
|
|
99
|
+
|
|
100
|
+
def test_files_only_works_in_lexical_mode(self):
|
|
101
|
+
err = io.StringIO()
|
|
102
|
+
with contextlib.redirect_stderr(err), self.assertRaises(SystemExit):
|
|
103
|
+
self.run_cli("search", "policy", "--files", "--mode", "hybrid")
|
|
104
|
+
self.assertIn("only works with --mode lexical", err.getvalue())
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
if __name__ == "__main__":
|
|
108
|
+
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{offline_rag_kit-0.1.3 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/entry_points.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|