offline-rag-kit 0.1.3__tar.gz → 0.1.5__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.5}/PKG-INFO +48 -2
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/README.md +47 -1
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/pyproject.toml +1 -1
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag/__init__.py +1 -1
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag/cli.py +110 -5
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag/index.py +62 -7
- offline_rag_kit-0.1.5/src/offline_rag/serve.py +332 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/PKG-INFO +48 -2
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/SOURCES.txt +4 -1
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/tests/test_cli.py +46 -0
- offline_rag_kit-0.1.5/tests/test_files.py +108 -0
- offline_rag_kit-0.1.5/tests/test_serve.py +222 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/LICENSE +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/setup.cfg +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag/embeddings.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag/eval.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag/ollama.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/dependency_links.txt +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/entry_points.txt +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/requires.txt +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/top_level.txt +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/tests/test_embeddings.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/tests/test_eval.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/tests/test_index.py +0 -0
- {offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/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.5
|
|
4
4
|
Summary: Privacy-first local document search with PDF citations and optional Ollama answers
|
|
5
5
|
Author: HugoDelgadoo
|
|
6
6
|
Maintainer: HugoDelgadoo
|
|
@@ -43,6 +43,19 @@ Offline RAG Kit helps developers find evidence in local PDFs, Markdown and plain
|
|
|
43
43
|
- **No cloud inference:** optional generation calls `127.0.0.1:11434` only.
|
|
44
44
|
- **Useful foundation:** roadmap includes hybrid vector/BM25 retrieval, OCR, audio, reranking and automated evaluations.
|
|
45
45
|
|
|
46
|
+
## Install on Windows (one script)
|
|
47
|
+
|
|
48
|
+
Requirements: Python 3.10 or newer ([python.org](https://www.python.org/downloads/), tick "Add python.exe to PATH"). No administrator rights needed.
|
|
49
|
+
|
|
50
|
+
1. Download [`install-windows.ps1`](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/scripts/install-windows.ps1) (open it, read it, then use the "Download raw file" button).
|
|
51
|
+
2. Run it in PowerShell:
|
|
52
|
+
|
|
53
|
+
```powershell
|
|
54
|
+
powershell -ExecutionPolicy Bypass -File .\install-windows.ps1
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
It installs the program in its own private environment (your Python is not modified), adds the `offline-rag` command to your PATH (open a new terminal afterwards) and creates two Start Menu entries: **Offline RAG** (opens the local web page) and **Offline RAG - index a folder** (asks for a folder and indexes it). To remove everything, run `uninstall-windows.ps1`; your documents and your index are kept.
|
|
58
|
+
|
|
46
59
|
## Quickstart (Windows PowerShell)
|
|
47
60
|
|
|
48
61
|
Requirements: Python 3.10 or newer.
|
|
@@ -62,6 +75,17 @@ offline-rag ingest "C:\Users\YourUser\Documents\knowledge"
|
|
|
62
75
|
offline-rag search "retention policy"
|
|
63
76
|
```
|
|
64
77
|
|
|
78
|
+
### Use it from any terminal, and where the index lives
|
|
79
|
+
|
|
80
|
+
- **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.
|
|
81
|
+
- **The index lives in one fixed folder per user**, so it works from any directory: `%LOCALAPPDATA%\offline-rag\index.sqlite3` on Windows, `~/Library/Application Support/offline-rag/` on macOS, `~/.local/share/offline-rag/` on Linux. Run `offline-rag --json ingest FOLDER` to see the exact path (`database`). To use another file, pass `--db PATH` or set `OFFLINE_RAG_DB`:
|
|
82
|
+
|
|
83
|
+
```powershell
|
|
84
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 ingest C:\Users\You\Documents
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
- If you used an older version, an index in `.offline-rag/` inside the current folder is still used (with a hint) until a fixed-location index exists; move the file to the new location to use it from anywhere.
|
|
88
|
+
|
|
65
89
|
To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
|
|
66
90
|
|
|
67
91
|
```powershell
|
|
@@ -75,12 +99,34 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
|
|
|
75
99
|
|
|
76
100
|
```text
|
|
77
101
|
offline-rag [--db PATH] [--json] ingest FOLDER
|
|
78
|
-
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid]
|
|
102
|
+
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid] [--files]
|
|
79
103
|
offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
|
|
80
104
|
offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
|
|
81
105
|
[--ollama-host URL] [--allow-remote]
|
|
106
|
+
offline-rag [--db PATH] serve [--port 8765] [--open]
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Web interface
|
|
110
|
+
|
|
111
|
+
`offline-rag serve --open` starts a small **read-only** web page at `http://127.0.0.1:8765/` where you type words and see passages (with the matching words highlighted) or the list of files. For PDF results, **Show page** displays the page as an image with the passage highlighted in yellow. It listens only on your own computer (`127.0.0.1`; there is no option to expose it), never modifies the index or your documents, and needs no extra packages. Index your folder first with `ingest`. Press Ctrl+C to stop it.
|
|
112
|
+
|
|
113
|
+
### Which files contain a word?
|
|
114
|
+
|
|
115
|
+
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.
|
|
116
|
+
|
|
117
|
+
```powershell
|
|
118
|
+
offline-rag search "policy" --files
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
```text
|
|
122
|
+
3 files contain 'policy':
|
|
123
|
+
C:\Users\You\Documents\notes\meeting.md (2 matching passages)
|
|
124
|
+
C:\Users\You\Documents\handbook.md (1 matching passage)
|
|
125
|
+
C:\Users\You\Documents\contract.pdf (2 matching passages; pages 1, 3)
|
|
82
126
|
```
|
|
83
127
|
|
|
128
|
+
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.
|
|
129
|
+
|
|
84
130
|
Re-running `ingest` is incremental: unchanged files (by content hash) are not re-parsed.
|
|
85
131
|
|
|
86
132
|
`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.
|
|
@@ -21,6 +21,19 @@ Offline RAG Kit helps developers find evidence in local PDFs, Markdown and plain
|
|
|
21
21
|
- **No cloud inference:** optional generation calls `127.0.0.1:11434` only.
|
|
22
22
|
- **Useful foundation:** roadmap includes hybrid vector/BM25 retrieval, OCR, audio, reranking and automated evaluations.
|
|
23
23
|
|
|
24
|
+
## Install on Windows (one script)
|
|
25
|
+
|
|
26
|
+
Requirements: Python 3.10 or newer ([python.org](https://www.python.org/downloads/), tick "Add python.exe to PATH"). No administrator rights needed.
|
|
27
|
+
|
|
28
|
+
1. Download [`install-windows.ps1`](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/scripts/install-windows.ps1) (open it, read it, then use the "Download raw file" button).
|
|
29
|
+
2. Run it in PowerShell:
|
|
30
|
+
|
|
31
|
+
```powershell
|
|
32
|
+
powershell -ExecutionPolicy Bypass -File .\install-windows.ps1
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
It installs the program in its own private environment (your Python is not modified), adds the `offline-rag` command to your PATH (open a new terminal afterwards) and creates two Start Menu entries: **Offline RAG** (opens the local web page) and **Offline RAG - index a folder** (asks for a folder and indexes it). To remove everything, run `uninstall-windows.ps1`; your documents and your index are kept.
|
|
36
|
+
|
|
24
37
|
## Quickstart (Windows PowerShell)
|
|
25
38
|
|
|
26
39
|
Requirements: Python 3.10 or newer.
|
|
@@ -40,6 +53,17 @@ offline-rag ingest "C:\Users\YourUser\Documents\knowledge"
|
|
|
40
53
|
offline-rag search "retention policy"
|
|
41
54
|
```
|
|
42
55
|
|
|
56
|
+
### Use it from any terminal, and where the index lives
|
|
57
|
+
|
|
58
|
+
- **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.
|
|
59
|
+
- **The index lives in one fixed folder per user**, so it works from any directory: `%LOCALAPPDATA%\offline-rag\index.sqlite3` on Windows, `~/Library/Application Support/offline-rag/` on macOS, `~/.local/share/offline-rag/` on Linux. Run `offline-rag --json ingest FOLDER` to see the exact path (`database`). To use another file, pass `--db PATH` or set `OFFLINE_RAG_DB`:
|
|
60
|
+
|
|
61
|
+
```powershell
|
|
62
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 ingest C:\Users\You\Documents
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- If you used an older version, an index in `.offline-rag/` inside the current folder is still used (with a hint) until a fixed-location index exists; move the file to the new location to use it from anywhere.
|
|
66
|
+
|
|
43
67
|
To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
|
|
44
68
|
|
|
45
69
|
```powershell
|
|
@@ -53,12 +77,34 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
|
|
|
53
77
|
|
|
54
78
|
```text
|
|
55
79
|
offline-rag [--db PATH] [--json] ingest FOLDER
|
|
56
|
-
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid]
|
|
80
|
+
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid] [--files]
|
|
57
81
|
offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
|
|
58
82
|
offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
|
|
59
83
|
[--ollama-host URL] [--allow-remote]
|
|
84
|
+
offline-rag [--db PATH] serve [--port 8765] [--open]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Web interface
|
|
88
|
+
|
|
89
|
+
`offline-rag serve --open` starts a small **read-only** web page at `http://127.0.0.1:8765/` where you type words and see passages (with the matching words highlighted) or the list of files. For PDF results, **Show page** displays the page as an image with the passage highlighted in yellow. It listens only on your own computer (`127.0.0.1`; there is no option to expose it), never modifies the index or your documents, and needs no extra packages. Index your folder first with `ingest`. Press Ctrl+C to stop it.
|
|
90
|
+
|
|
91
|
+
### Which files contain a word?
|
|
92
|
+
|
|
93
|
+
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.
|
|
94
|
+
|
|
95
|
+
```powershell
|
|
96
|
+
offline-rag search "policy" --files
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
```text
|
|
100
|
+
3 files contain 'policy':
|
|
101
|
+
C:\Users\You\Documents\notes\meeting.md (2 matching passages)
|
|
102
|
+
C:\Users\You\Documents\handbook.md (1 matching passage)
|
|
103
|
+
C:\Users\You\Documents\contract.pdf (2 matching passages; pages 1, 3)
|
|
60
104
|
```
|
|
61
105
|
|
|
106
|
+
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.
|
|
107
|
+
|
|
62
108
|
Re-running `ingest` is incremental: unchanged files (by content hash) are not re-parsed.
|
|
63
109
|
|
|
64
110
|
`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.5"
|
|
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"
|
|
@@ -2,18 +2,55 @@
|
|
|
2
2
|
|
|
3
3
|
import argparse
|
|
4
4
|
import json
|
|
5
|
+
import os
|
|
5
6
|
import sys
|
|
7
|
+
from pathlib import Path
|
|
6
8
|
|
|
7
9
|
from .embeddings import DEFAULT_MODEL, embed_index, hybrid_search, indexed_model, ollama_embedder, vector_search
|
|
8
|
-
from .index import citation, ingest, search
|
|
10
|
+
from .index import citation, ingest, search, search_files
|
|
9
11
|
from .ollama import answer_with_ollama
|
|
10
12
|
|
|
13
|
+
LEGACY_DB = Path(".offline-rag") / "index.sqlite3"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def default_db_path() -> Path:
|
|
17
|
+
"""Fixed per-user index location, so the index does not depend on the current directory."""
|
|
18
|
+
override = os.environ.get("OFFLINE_RAG_DB")
|
|
19
|
+
if override:
|
|
20
|
+
return Path(override).expanduser()
|
|
21
|
+
if sys.platform == "win32":
|
|
22
|
+
base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")
|
|
23
|
+
elif sys.platform == "darwin":
|
|
24
|
+
base = Path.home() / "Library" / "Application Support"
|
|
25
|
+
else:
|
|
26
|
+
base = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share")
|
|
27
|
+
return base / "offline-rag" / "index.sqlite3"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve_db(explicit: str | None) -> str:
|
|
31
|
+
"""--db wins, then $OFFLINE_RAG_DB, then the fixed folder. A pre-0.1.5 index in the current
|
|
32
|
+
folder is still used (with a hint) until a fixed-location index exists."""
|
|
33
|
+
if explicit:
|
|
34
|
+
return explicit
|
|
35
|
+
fixed = default_db_path()
|
|
36
|
+
if not os.environ.get("OFFLINE_RAG_DB") and not fixed.exists() and LEGACY_DB.exists():
|
|
37
|
+
print(
|
|
38
|
+
f"Using the index in this folder ({LEGACY_DB}). New default location: {fixed}. "
|
|
39
|
+
f"Move the file there, or pass --db, to use it from any folder.",
|
|
40
|
+
file=sys.stderr,
|
|
41
|
+
)
|
|
42
|
+
return str(LEGACY_DB)
|
|
43
|
+
return str(fixed)
|
|
44
|
+
|
|
11
45
|
|
|
12
46
|
def build_parser() -> argparse.ArgumentParser:
|
|
13
47
|
parser = argparse.ArgumentParser(
|
|
14
48
|
prog="offline-rag", description="Search private documents entirely on your machine."
|
|
15
49
|
)
|
|
16
|
-
parser.add_argument(
|
|
50
|
+
parser.add_argument(
|
|
51
|
+
"--db", default=None,
|
|
52
|
+
help="Local SQLite index path (default: $OFFLINE_RAG_DB, or a fixed per-user folder; see README)",
|
|
53
|
+
)
|
|
17
54
|
parser.add_argument(
|
|
18
55
|
"--json", action="store_true", help="Print machine-readable JSON on stdout (errors stay on stderr)"
|
|
19
56
|
)
|
|
@@ -30,10 +67,17 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
30
67
|
emb.add_argument("--ollama-host", help="Ollama URL (default: $OLLAMA_HOST or 127.0.0.1:11434)")
|
|
31
68
|
emb.add_argument("--allow-remote", action="store_true", help="Allow a non-loopback Ollama host")
|
|
32
69
|
|
|
70
|
+
srv = commands.add_parser("serve", help="Open a local, read-only web interface (127.0.0.1 only)")
|
|
71
|
+
srv.add_argument("--port", type=int, default=8765, help="Port on 127.0.0.1 (default: 8765, 0 = any free port)")
|
|
72
|
+
srv.add_argument("--open", action="store_true", help="Open the page in your default browser")
|
|
73
|
+
|
|
33
74
|
for command in ("search", "ask"):
|
|
34
75
|
sub = commands.add_parser(command, help="Search locally" if command == "search" else "Ask local Ollama")
|
|
35
76
|
sub.add_argument("query", help="Question or search terms")
|
|
36
|
-
sub.add_argument(
|
|
77
|
+
sub.add_argument(
|
|
78
|
+
"--limit", type=int, default=None,
|
|
79
|
+
help="Maximum results (default: 5 passages, or 20 files with --files)",
|
|
80
|
+
)
|
|
37
81
|
sub.add_argument(
|
|
38
82
|
"--mode", choices=("lexical", "vector", "hybrid"), default="lexical",
|
|
39
83
|
help="lexical (default, offline); vector/hybrid need 'offline-rag embed' and a running Ollama",
|
|
@@ -43,6 +87,11 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
43
87
|
"--allow-remote", action="store_true",
|
|
44
88
|
help="Allow a non-loopback Ollama host (text is sent to it)",
|
|
45
89
|
)
|
|
90
|
+
if command == "search":
|
|
91
|
+
sub.add_argument(
|
|
92
|
+
"--files", action="store_true",
|
|
93
|
+
help="List the files that contain the terms (full path, matches, pages) instead of passages",
|
|
94
|
+
)
|
|
46
95
|
if command == "ask":
|
|
47
96
|
sub.add_argument("--model", default="llama3.2", help="Ollama model used to write the answer")
|
|
48
97
|
return parser
|
|
@@ -65,19 +114,64 @@ def _dump(payload: dict) -> None:
|
|
|
65
114
|
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
66
115
|
|
|
67
116
|
|
|
117
|
+
def _format_pages(pages: list[int], shown: int = 10) -> str:
|
|
118
|
+
text = ", ".join(str(p) for p in pages[:shown])
|
|
119
|
+
return text + (f", … (+{len(pages) - shown})" if len(pages) > shown else "")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _print_files(query: str, result: dict) -> None:
|
|
123
|
+
total = result["total"]
|
|
124
|
+
if not total:
|
|
125
|
+
print("No files found.")
|
|
126
|
+
return
|
|
127
|
+
noun, verb = ("file", "contains") if total == 1 else ("files", "contain")
|
|
128
|
+
if result["match"] == "any":
|
|
129
|
+
print(f"No file contains all the words of {query!r}; {total} {noun} {verb} at least one of them:")
|
|
130
|
+
else:
|
|
131
|
+
print(f"{total} {noun} {verb} {query!r}:")
|
|
132
|
+
for item in result["files"]:
|
|
133
|
+
count = item["matches"]
|
|
134
|
+
detail = f"{count} matching passage{'s' if count != 1 else ''}"
|
|
135
|
+
if item["pages"]:
|
|
136
|
+
detail += f"; page{'s' if len(item['pages']) != 1 else ''} {_format_pages(item['pages'])}"
|
|
137
|
+
print(f" {item['path']} ({detail})")
|
|
138
|
+
if total > len(result["files"]):
|
|
139
|
+
print(f"Showing the first {len(result['files'])} of {total}. Use --limit to see more (up to 100).")
|
|
140
|
+
|
|
141
|
+
|
|
68
142
|
def _retrieve(args) -> list[dict]:
|
|
143
|
+
limit = args.limit if args.limit is not None else 5
|
|
69
144
|
if args.mode == "lexical":
|
|
70
|
-
return search(args.query, args.db,
|
|
145
|
+
return search(args.query, args.db, limit)
|
|
71
146
|
model = indexed_model(args.db)
|
|
72
147
|
if model is None:
|
|
73
148
|
raise ValueError("This index has no embeddings. Run 'offline-rag embed' first.")
|
|
74
149
|
embedder = ollama_embedder(model, args.ollama_host, args.allow_remote)
|
|
75
150
|
run = vector_search if args.mode == "vector" else hybrid_search
|
|
76
|
-
return run(args.query, args.db, embedder,
|
|
151
|
+
return run(args.query, args.db, embedder, limit)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _serve(args: argparse.Namespace) -> None:
|
|
155
|
+
from .serve import make_server
|
|
156
|
+
|
|
157
|
+
if not 0 <= args.port <= 65535:
|
|
158
|
+
raise ValueError("--port must be between 0 and 65535")
|
|
159
|
+
with make_server(args.db, args.port) as server:
|
|
160
|
+
url = f"http://127.0.0.1:{server.server_address[1]}/"
|
|
161
|
+
print(f"Serving {args.db} at {url} (read-only, this computer only). Press Ctrl+C to stop.")
|
|
162
|
+
if args.open:
|
|
163
|
+
import webbrowser
|
|
164
|
+
|
|
165
|
+
webbrowser.open(url)
|
|
166
|
+
try:
|
|
167
|
+
server.serve_forever()
|
|
168
|
+
except KeyboardInterrupt:
|
|
169
|
+
print("\nStopped.")
|
|
77
170
|
|
|
78
171
|
|
|
79
172
|
def main(argv: list[str] | None = None) -> None:
|
|
80
173
|
args = build_parser().parse_args(argv)
|
|
174
|
+
args.db = resolve_db(args.db)
|
|
81
175
|
try:
|
|
82
176
|
if args.command == "ingest":
|
|
83
177
|
result = ingest(args.folder, args.db)
|
|
@@ -94,6 +188,8 @@ def main(argv: list[str] | None = None) -> None:
|
|
|
94
188
|
f"Indexed {result.files} files ({result.unchanged} unchanged) and "
|
|
95
189
|
f"{result.passages} passages in {args.db}"
|
|
96
190
|
)
|
|
191
|
+
elif args.command == "serve":
|
|
192
|
+
_serve(args)
|
|
97
193
|
elif args.command == "embed":
|
|
98
194
|
embedder = ollama_embedder(args.model, args.ollama_host, args.allow_remote)
|
|
99
195
|
count = embed_index(args.db, embedder, args.model, rebuild=args.rebuild)
|
|
@@ -101,6 +197,15 @@ def main(argv: list[str] | None = None) -> None:
|
|
|
101
197
|
_dump({"embedded": count, "model": args.model, "database": args.db})
|
|
102
198
|
else:
|
|
103
199
|
print(f"Embedded {count} passages with {args.model} in {args.db}")
|
|
200
|
+
elif args.command == "search" and args.files:
|
|
201
|
+
if args.mode != "lexical":
|
|
202
|
+
raise ValueError("--files lists files that contain the words, so it only works with --mode lexical.")
|
|
203
|
+
limit = args.limit if args.limit is not None else 20
|
|
204
|
+
result = search_files(args.query, args.db, limit)
|
|
205
|
+
if args.json:
|
|
206
|
+
_dump({"query": args.query, **result})
|
|
207
|
+
else:
|
|
208
|
+
_print_files(args.query, result)
|
|
104
209
|
else:
|
|
105
210
|
hits = _retrieve(args)
|
|
106
211
|
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"]:
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
"""Local, read-only web interface: ``offline-rag serve``.
|
|
2
|
+
|
|
3
|
+
The server listens only on the loopback interface, never writes to the index or to the
|
|
4
|
+
documents, and uses nothing but the standard library. Requests whose ``Host`` header is not
|
|
5
|
+
the loopback address are refused (protection against DNS rebinding).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import sqlite3
|
|
10
|
+
import threading
|
|
11
|
+
from contextlib import closing
|
|
12
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from urllib.parse import parse_qs, urlsplit
|
|
15
|
+
|
|
16
|
+
import pymupdf
|
|
17
|
+
|
|
18
|
+
from .index import search, search_files
|
|
19
|
+
|
|
20
|
+
LOOPBACK = "127.0.0.1"
|
|
21
|
+
MAX_QUERY_CHARS = 500
|
|
22
|
+
MAX_PREVIEW_PIXELS = 1600 # width of the rendered page image
|
|
23
|
+
HIGHLIGHT_FILL = (1.0, 0.85, 0.0)
|
|
24
|
+
|
|
25
|
+
_render_lock = threading.Lock() # PyMuPDF is not thread-safe
|
|
26
|
+
|
|
27
|
+
INDEX_HTML = """<!doctype html>
|
|
28
|
+
<html lang="en">
|
|
29
|
+
<head>
|
|
30
|
+
<meta charset="utf-8">
|
|
31
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
32
|
+
<title>offline-rag</title>
|
|
33
|
+
<style>
|
|
34
|
+
:root { color-scheme: light dark; --bg:#fafaf9; --fg:#1c1917; --muted:#78716c; --card:#fff;
|
|
35
|
+
--line:#e7e5e4; --accent:#2563eb; --mark:#fde68a; }
|
|
36
|
+
@media (prefers-color-scheme: dark) {
|
|
37
|
+
:root { --bg:#161513; --fg:#f5f5f4; --muted:#a8a29e; --card:#1f1d1b; --line:#33302d;
|
|
38
|
+
--accent:#60a5fa; --mark:#854d0e; } }
|
|
39
|
+
* { box-sizing: border-box; }
|
|
40
|
+
body { margin:0; background:var(--bg); color:var(--fg);
|
|
41
|
+
font:16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
|
|
42
|
+
main { max-width: 52rem; margin: 0 auto; padding: 2rem 1rem 4rem; }
|
|
43
|
+
h1 { font-size: 1.25rem; margin: 0 0 .25rem; }
|
|
44
|
+
.sub { color: var(--muted); margin: 0 0 1.5rem; font-size: .9rem; }
|
|
45
|
+
form { display:flex; gap:.5rem; }
|
|
46
|
+
input[type=search] { flex:1; padding:.7rem .9rem; font:inherit; color:inherit; background:var(--card);
|
|
47
|
+
border:1px solid var(--line); border-radius:.5rem; }
|
|
48
|
+
button { padding:.7rem 1.1rem; font:inherit; color:#fff; background:var(--accent); border:0;
|
|
49
|
+
border-radius:.5rem; cursor:pointer; }
|
|
50
|
+
input:focus-visible, button:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
|
|
51
|
+
.tabs { display:flex; gap:1rem; margin:1.25rem 0 .75rem; border-bottom:1px solid var(--line); }
|
|
52
|
+
.tabs button { background:none; color:var(--muted); padding:.4rem 0; border-radius:0;
|
|
53
|
+
border-bottom:2px solid transparent; }
|
|
54
|
+
.tabs button[aria-selected=true] { color:var(--fg); border-bottom-color:var(--accent); }
|
|
55
|
+
#status { color:var(--muted); font-size:.9rem; margin:.5rem 0; }
|
|
56
|
+
ol { list-style:none; padding:0; margin:0; display:grid; gap:.75rem; }
|
|
57
|
+
li { background:var(--card); border:1px solid var(--line); border-radius:.6rem; padding:.8rem 1rem; }
|
|
58
|
+
.where { font-size:.85rem; color:var(--muted); margin-bottom:.3rem; word-break:break-all; }
|
|
59
|
+
.where b { color:var(--fg); font-weight:600; }
|
|
60
|
+
mark { background:var(--mark); color:inherit; border-radius:.2rem; padding:0 .1rem; }
|
|
61
|
+
p { margin:0; }
|
|
62
|
+
.linkbtn { background:none; color:var(--accent); padding:0; margin-top:.5rem; font-size:.9rem;
|
|
63
|
+
text-decoration:underline; }
|
|
64
|
+
img.preview { display:block; max-width:100%; height:auto; margin-top:.6rem; background:#fff;
|
|
65
|
+
border:1px solid var(--line); border-radius:.4rem; }
|
|
66
|
+
.err { color:var(--muted); font-size:.9rem; margin-top:.5rem; }
|
|
67
|
+
</style>
|
|
68
|
+
</head>
|
|
69
|
+
<body>
|
|
70
|
+
<main>
|
|
71
|
+
<h1>offline-rag</h1>
|
|
72
|
+
<p class="sub">Searching your local index. Nothing leaves this computer.</p>
|
|
73
|
+
<form id="form" role="search">
|
|
74
|
+
<input id="q" type="search" placeholder="Search your documents" aria-label="Search" autofocus
|
|
75
|
+
autocomplete="off" maxlength="500">
|
|
76
|
+
<button type="submit">Search</button>
|
|
77
|
+
</form>
|
|
78
|
+
<div class="tabs" role="tablist">
|
|
79
|
+
<button type="button" role="tab" id="tab-passages" aria-selected="true">Passages</button>
|
|
80
|
+
<button type="button" role="tab" id="tab-files" aria-selected="false">Files</button>
|
|
81
|
+
</div>
|
|
82
|
+
<div id="status" role="status" aria-live="polite"></div>
|
|
83
|
+
<ol id="results"></ol>
|
|
84
|
+
</main>
|
|
85
|
+
<script>
|
|
86
|
+
"use strict";
|
|
87
|
+
const form = document.getElementById("form"), box = document.getElementById("q");
|
|
88
|
+
const list = document.getElementById("results"), status = document.getElementById("status");
|
|
89
|
+
const tabs = { passages: document.getElementById("tab-passages"), files: document.getElementById("tab-files") };
|
|
90
|
+
let view = "passages";
|
|
91
|
+
|
|
92
|
+
function el(tag, text, cls) {
|
|
93
|
+
const node = document.createElement(tag);
|
|
94
|
+
if (text !== undefined) node.textContent = text;
|
|
95
|
+
if (cls) node.className = cls;
|
|
96
|
+
return node;
|
|
97
|
+
}
|
|
98
|
+
// The snippet marks matches with **...**; build DOM nodes instead of HTML so that
|
|
99
|
+
// document text can never be interpreted as markup.
|
|
100
|
+
function snippetNode(snippet) {
|
|
101
|
+
const p = el("p");
|
|
102
|
+
snippet.split("**").forEach((part, i) => {
|
|
103
|
+
if (i % 2) p.appendChild(el("mark", part)); else p.appendChild(document.createTextNode(part));
|
|
104
|
+
});
|
|
105
|
+
return p;
|
|
106
|
+
}
|
|
107
|
+
// "Show page" loads /preview?id=N, the PDF page as an image with the passage highlighted.
|
|
108
|
+
function previewControl(r) {
|
|
109
|
+
const wrap = el("div"), label = "Show page " + r.page;
|
|
110
|
+
const button = el("button", label, "linkbtn");
|
|
111
|
+
button.type = "button";
|
|
112
|
+
let open = null;
|
|
113
|
+
button.addEventListener("click", () => {
|
|
114
|
+
if (open) { open.remove(); open = null; button.textContent = label; return; }
|
|
115
|
+
const img = document.createElement("img");
|
|
116
|
+
img.className = "preview";
|
|
117
|
+
img.alt = "Page " + r.page + " of " + r.path + " with the passage highlighted";
|
|
118
|
+
img.addEventListener("error", () => {
|
|
119
|
+
const note = el("p", "Preview not available: the file may have moved or changed. Run ingest again.", "err");
|
|
120
|
+
img.replaceWith(note); open = note;
|
|
121
|
+
});
|
|
122
|
+
img.src = "/preview?id=" + encodeURIComponent(r.id);
|
|
123
|
+
wrap.appendChild(img); open = img; button.textContent = "Hide page";
|
|
124
|
+
});
|
|
125
|
+
wrap.prepend(button);
|
|
126
|
+
return wrap;
|
|
127
|
+
}
|
|
128
|
+
function show(message) { status.textContent = message; list.replaceChildren(); }
|
|
129
|
+
|
|
130
|
+
async function run() {
|
|
131
|
+
const q = box.value.trim();
|
|
132
|
+
const url = new URL(location.href);
|
|
133
|
+
url.searchParams.set("q", q); url.searchParams.set("view", view);
|
|
134
|
+
history.replaceState(null, "", url);
|
|
135
|
+
if (!q) return show("");
|
|
136
|
+
status.textContent = "Searching…";
|
|
137
|
+
let data;
|
|
138
|
+
try {
|
|
139
|
+
const response = await fetch("/api/" + (view === "files" ? "files" : "search") + "?q=" + encodeURIComponent(q));
|
|
140
|
+
data = await response.json();
|
|
141
|
+
if (!response.ok) return show(data.error || "Search failed.");
|
|
142
|
+
} catch (error) { return show("Could not reach the local server."); }
|
|
143
|
+
list.replaceChildren();
|
|
144
|
+
if (view === "files") {
|
|
145
|
+
status.textContent = data.total ? data.total + (data.total === 1 ? " file" : " files")
|
|
146
|
+
+ (data.match === "any" ? " (no file contains every word; showing files with at least one)" : "")
|
|
147
|
+
: "No files found.";
|
|
148
|
+
data.files.forEach(f => {
|
|
149
|
+
const item = el("li");
|
|
150
|
+
item.appendChild(el("div", f.path, "where"));
|
|
151
|
+
item.appendChild(el("p", f.matches + (f.matches === 1 ? " matching passage" : " matching passages")
|
|
152
|
+
+ (f.pages.length ? " · pages " + f.pages.join(", ") : "")));
|
|
153
|
+
list.appendChild(item);
|
|
154
|
+
});
|
|
155
|
+
} else {
|
|
156
|
+
status.textContent = data.results.length ? "" : "No matching passages found.";
|
|
157
|
+
data.results.forEach(r => {
|
|
158
|
+
const item = el("li"), where = el("div", undefined, "where");
|
|
159
|
+
where.appendChild(el("b", r.path));
|
|
160
|
+
if (r.page) where.appendChild(document.createTextNode(" · page " + r.page));
|
|
161
|
+
item.appendChild(where);
|
|
162
|
+
item.appendChild(snippetNode(r.snippet));
|
|
163
|
+
if (r.page) item.appendChild(previewControl(r));
|
|
164
|
+
list.appendChild(item);
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function select(next) {
|
|
169
|
+
view = next;
|
|
170
|
+
for (const [name, tab] of Object.entries(tabs)) tab.setAttribute("aria-selected", String(name === next));
|
|
171
|
+
run();
|
|
172
|
+
}
|
|
173
|
+
tabs.passages.addEventListener("click", () => select("passages"));
|
|
174
|
+
tabs.files.addEventListener("click", () => select("files"));
|
|
175
|
+
form.addEventListener("submit", event => { event.preventDefault(); run(); });
|
|
176
|
+
const params = new URLSearchParams(location.search);
|
|
177
|
+
if (params.get("q")) { box.value = params.get("q"); select(params.get("view") === "files" ? "files" : "passages"); }
|
|
178
|
+
</script>
|
|
179
|
+
</body>
|
|
180
|
+
</html>
|
|
181
|
+
"""
|
|
182
|
+
|
|
183
|
+
SECURITY_HEADERS = {
|
|
184
|
+
"Content-Security-Policy": (
|
|
185
|
+
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
|
|
186
|
+
"connect-src 'self'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'"
|
|
187
|
+
),
|
|
188
|
+
"X-Content-Type-Options": "nosniff",
|
|
189
|
+
"Referrer-Policy": "no-referrer",
|
|
190
|
+
"Cache-Control": "no-store",
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class PreviewError(Exception):
|
|
195
|
+
"""The preview cannot be produced; ``status`` is the HTTP status to answer with."""
|
|
196
|
+
|
|
197
|
+
def __init__(self, status: int, message: str):
|
|
198
|
+
super().__init__(message)
|
|
199
|
+
self.status = status
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def render_preview(database: str | Path, passage_id: int) -> bytes:
|
|
203
|
+
"""Render the PDF page of an indexed passage as PNG with the passage highlighted.
|
|
204
|
+
|
|
205
|
+
The file is found through the index (never through a path sent by the browser), must sit
|
|
206
|
+
inside the folder that was ingested, and is opened read-only and never saved.
|
|
207
|
+
"""
|
|
208
|
+
uri = Path(database).expanduser().resolve().as_uri() + "?mode=ro"
|
|
209
|
+
with closing(sqlite3.connect(uri, uri=True)) as connection:
|
|
210
|
+
row = connection.execute(
|
|
211
|
+
"SELECT root, path, page, bbox FROM passages WHERE rowid = ?", (passage_id,)
|
|
212
|
+
).fetchone()
|
|
213
|
+
if row is None:
|
|
214
|
+
raise PreviewError(404, "Unknown passage.")
|
|
215
|
+
root, relative, page_number, bbox = row
|
|
216
|
+
if not page_number or not relative.lower().endswith(".pdf"):
|
|
217
|
+
raise PreviewError(404, "Only PDF passages have a preview.")
|
|
218
|
+
root_path = Path(root).resolve()
|
|
219
|
+
file = (root_path / relative).resolve()
|
|
220
|
+
if not file.is_relative_to(root_path):
|
|
221
|
+
raise PreviewError(403, "The file is outside the indexed folder.")
|
|
222
|
+
if not file.is_file():
|
|
223
|
+
raise PreviewError(404, "The file is no longer there. Run 'offline-rag ingest' again.")
|
|
224
|
+
try:
|
|
225
|
+
with _render_lock, pymupdf.open(file) as document:
|
|
226
|
+
if not 1 <= int(page_number) <= document.page_count:
|
|
227
|
+
raise PreviewError(404, "The file changed since it was indexed. Run 'offline-rag ingest' again.")
|
|
228
|
+
page = document[int(page_number) - 1]
|
|
229
|
+
if bbox:
|
|
230
|
+
# Stored in the same (unrotated) space PyMuPDF draws in.
|
|
231
|
+
x0, y0, x1, y1 = (float(n) for n in bbox.split(","))
|
|
232
|
+
page.draw_rect(
|
|
233
|
+
pymupdf.Rect(x0, y0, x1, y1), color=HIGHLIGHT_FILL, fill=HIGHLIGHT_FILL,
|
|
234
|
+
fill_opacity=0.35, width=1.2,
|
|
235
|
+
)
|
|
236
|
+
zoom = min(2.0, MAX_PREVIEW_PIXELS / max(page.rect.width, 1.0))
|
|
237
|
+
return page.get_pixmap(matrix=pymupdf.Matrix(zoom, zoom), alpha=False).tobytes("png")
|
|
238
|
+
except PreviewError:
|
|
239
|
+
raise
|
|
240
|
+
except (RuntimeError, ValueError) as exc: # damaged or encrypted PDF, bad stored bbox
|
|
241
|
+
raise PreviewError(422, f"The page could not be rendered: {exc}") from exc
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _hit_payload(hit: dict) -> dict:
|
|
245
|
+
return {
|
|
246
|
+
"id": hit["id"],
|
|
247
|
+
"path": hit["path"],
|
|
248
|
+
"page": hit["page"] or None,
|
|
249
|
+
"bbox": [float(n) for n in hit["bbox"].split(",")] if hit["bbox"] else None,
|
|
250
|
+
"snippet": hit["snippet"],
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
255
|
+
server: "LocalServer"
|
|
256
|
+
server_version = "offline-rag"
|
|
257
|
+
sys_version = ""
|
|
258
|
+
|
|
259
|
+
def log_message(self, format, *args): # noqa: A002 - keep the console quiet; never log queries
|
|
260
|
+
pass
|
|
261
|
+
|
|
262
|
+
def _send(self, status: int, body: bytes, content_type: str) -> None:
|
|
263
|
+
self.send_response(status)
|
|
264
|
+
self.send_header("Content-Type", content_type)
|
|
265
|
+
self.send_header("Content-Length", str(len(body)))
|
|
266
|
+
for name, value in SECURITY_HEADERS.items():
|
|
267
|
+
self.send_header(name, value)
|
|
268
|
+
self.end_headers()
|
|
269
|
+
self.wfile.write(body)
|
|
270
|
+
|
|
271
|
+
def _json(self, status: int, payload: dict) -> None:
|
|
272
|
+
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
273
|
+
self._send(status, body, "application/json; charset=utf-8")
|
|
274
|
+
|
|
275
|
+
def _host_allowed(self) -> bool:
|
|
276
|
+
port = self.server.server_address[1]
|
|
277
|
+
return self.headers.get("Host", "") in {f"{LOOPBACK}:{port}", f"localhost:{port}"}
|
|
278
|
+
|
|
279
|
+
def do_GET(self): # noqa: N802 - http.server API
|
|
280
|
+
if not self._host_allowed():
|
|
281
|
+
return self._json(403, {"error": "Forbidden host."})
|
|
282
|
+
url = urlsplit(self.path)
|
|
283
|
+
if url.path == "/":
|
|
284
|
+
return self._send(200, INDEX_HTML.encode("utf-8"), "text/html; charset=utf-8")
|
|
285
|
+
if url.path in ("/api/search", "/api/files"):
|
|
286
|
+
query = parse_qs(url.query).get("q", [""])[0].strip()
|
|
287
|
+
if not query:
|
|
288
|
+
return self._json(400, {"error": "Missing search terms."})
|
|
289
|
+
if len(query) > MAX_QUERY_CHARS:
|
|
290
|
+
return self._json(400, {"error": f"Query is longer than {MAX_QUERY_CHARS} characters."})
|
|
291
|
+
try:
|
|
292
|
+
if url.path == "/api/search":
|
|
293
|
+
hits = search(query, self.server.database, 10)
|
|
294
|
+
return self._json(200, {"query": query, "results": [_hit_payload(h) for h in hits]})
|
|
295
|
+
return self._json(200, {"query": query, **search_files(query, self.server.database, 50)})
|
|
296
|
+
except (OSError, ValueError) as exc:
|
|
297
|
+
return self._json(500, {"error": str(exc)})
|
|
298
|
+
if url.path == "/preview":
|
|
299
|
+
raw = parse_qs(url.query).get("id", [""])[0]
|
|
300
|
+
if not raw.isascii() or not raw.isdigit():
|
|
301
|
+
return self._json(400, {"error": "Missing or invalid passage id."})
|
|
302
|
+
try:
|
|
303
|
+
png = render_preview(self.server.database, int(raw))
|
|
304
|
+
except PreviewError as exc:
|
|
305
|
+
return self._json(exc.status, {"error": str(exc)})
|
|
306
|
+
except (OSError, sqlite3.Error) as exc:
|
|
307
|
+
return self._json(500, {"error": str(exc)})
|
|
308
|
+
return self._send(200, png, "image/png")
|
|
309
|
+
self._json(404, {"error": "Not found."})
|
|
310
|
+
|
|
311
|
+
def _method_not_allowed(self):
|
|
312
|
+
self.send_response(405)
|
|
313
|
+
self.send_header("Allow", "GET")
|
|
314
|
+
self.send_header("Content-Length", "0")
|
|
315
|
+
self.end_headers()
|
|
316
|
+
|
|
317
|
+
do_POST = do_PUT = do_DELETE = do_PATCH = _method_not_allowed # noqa: N815 - read-only server
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class LocalServer(ThreadingHTTPServer):
|
|
321
|
+
daemon_threads = True
|
|
322
|
+
|
|
323
|
+
def __init__(self, database: str | Path, port: int = 8765):
|
|
324
|
+
self.database = str(database)
|
|
325
|
+
super().__init__((LOOPBACK, port), _Handler)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def make_server(database: str | Path, port: int = 8765) -> LocalServer:
|
|
329
|
+
"""Create the server (bound to 127.0.0.1 only). The index must already exist."""
|
|
330
|
+
if not Path(database).expanduser().is_file():
|
|
331
|
+
raise ValueError(f"No index at {database}. Run 'offline-rag ingest FOLDER' first.")
|
|
332
|
+
return LocalServer(database, port)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: offline-rag-kit
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.5
|
|
4
4
|
Summary: Privacy-first local document search with PDF citations and optional Ollama answers
|
|
5
5
|
Author: HugoDelgadoo
|
|
6
6
|
Maintainer: HugoDelgadoo
|
|
@@ -43,6 +43,19 @@ Offline RAG Kit helps developers find evidence in local PDFs, Markdown and plain
|
|
|
43
43
|
- **No cloud inference:** optional generation calls `127.0.0.1:11434` only.
|
|
44
44
|
- **Useful foundation:** roadmap includes hybrid vector/BM25 retrieval, OCR, audio, reranking and automated evaluations.
|
|
45
45
|
|
|
46
|
+
## Install on Windows (one script)
|
|
47
|
+
|
|
48
|
+
Requirements: Python 3.10 or newer ([python.org](https://www.python.org/downloads/), tick "Add python.exe to PATH"). No administrator rights needed.
|
|
49
|
+
|
|
50
|
+
1. Download [`install-windows.ps1`](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/scripts/install-windows.ps1) (open it, read it, then use the "Download raw file" button).
|
|
51
|
+
2. Run it in PowerShell:
|
|
52
|
+
|
|
53
|
+
```powershell
|
|
54
|
+
powershell -ExecutionPolicy Bypass -File .\install-windows.ps1
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
It installs the program in its own private environment (your Python is not modified), adds the `offline-rag` command to your PATH (open a new terminal afterwards) and creates two Start Menu entries: **Offline RAG** (opens the local web page) and **Offline RAG - index a folder** (asks for a folder and indexes it). To remove everything, run `uninstall-windows.ps1`; your documents and your index are kept.
|
|
58
|
+
|
|
46
59
|
## Quickstart (Windows PowerShell)
|
|
47
60
|
|
|
48
61
|
Requirements: Python 3.10 or newer.
|
|
@@ -62,6 +75,17 @@ offline-rag ingest "C:\Users\YourUser\Documents\knowledge"
|
|
|
62
75
|
offline-rag search "retention policy"
|
|
63
76
|
```
|
|
64
77
|
|
|
78
|
+
### Use it from any terminal, and where the index lives
|
|
79
|
+
|
|
80
|
+
- **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.
|
|
81
|
+
- **The index lives in one fixed folder per user**, so it works from any directory: `%LOCALAPPDATA%\offline-rag\index.sqlite3` on Windows, `~/Library/Application Support/offline-rag/` on macOS, `~/.local/share/offline-rag/` on Linux. Run `offline-rag --json ingest FOLDER` to see the exact path (`database`). To use another file, pass `--db PATH` or set `OFFLINE_RAG_DB`:
|
|
82
|
+
|
|
83
|
+
```powershell
|
|
84
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 ingest C:\Users\You\Documents
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
- If you used an older version, an index in `.offline-rag/` inside the current folder is still used (with a hint) until a fixed-location index exists; move the file to the new location to use it from anywhere.
|
|
88
|
+
|
|
65
89
|
To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
|
|
66
90
|
|
|
67
91
|
```powershell
|
|
@@ -75,12 +99,34 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
|
|
|
75
99
|
|
|
76
100
|
```text
|
|
77
101
|
offline-rag [--db PATH] [--json] ingest FOLDER
|
|
78
|
-
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid]
|
|
102
|
+
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid] [--files]
|
|
79
103
|
offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
|
|
80
104
|
offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
|
|
81
105
|
[--ollama-host URL] [--allow-remote]
|
|
106
|
+
offline-rag [--db PATH] serve [--port 8765] [--open]
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Web interface
|
|
110
|
+
|
|
111
|
+
`offline-rag serve --open` starts a small **read-only** web page at `http://127.0.0.1:8765/` where you type words and see passages (with the matching words highlighted) or the list of files. For PDF results, **Show page** displays the page as an image with the passage highlighted in yellow. It listens only on your own computer (`127.0.0.1`; there is no option to expose it), never modifies the index or your documents, and needs no extra packages. Index your folder first with `ingest`. Press Ctrl+C to stop it.
|
|
112
|
+
|
|
113
|
+
### Which files contain a word?
|
|
114
|
+
|
|
115
|
+
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.
|
|
116
|
+
|
|
117
|
+
```powershell
|
|
118
|
+
offline-rag search "policy" --files
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
```text
|
|
122
|
+
3 files contain 'policy':
|
|
123
|
+
C:\Users\You\Documents\notes\meeting.md (2 matching passages)
|
|
124
|
+
C:\Users\You\Documents\handbook.md (1 matching passage)
|
|
125
|
+
C:\Users\You\Documents\contract.pdf (2 matching passages; pages 1, 3)
|
|
82
126
|
```
|
|
83
127
|
|
|
128
|
+
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.
|
|
129
|
+
|
|
84
130
|
Re-running `ingest` is incremental: unchanged files (by content hash) are not re-parsed.
|
|
85
131
|
|
|
86
132
|
`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.
|
|
@@ -7,6 +7,7 @@ src/offline_rag/embeddings.py
|
|
|
7
7
|
src/offline_rag/eval.py
|
|
8
8
|
src/offline_rag/index.py
|
|
9
9
|
src/offline_rag/ollama.py
|
|
10
|
+
src/offline_rag/serve.py
|
|
10
11
|
src/offline_rag_kit.egg-info/PKG-INFO
|
|
11
12
|
src/offline_rag_kit.egg-info/SOURCES.txt
|
|
12
13
|
src/offline_rag_kit.egg-info/dependency_links.txt
|
|
@@ -16,5 +17,7 @@ src/offline_rag_kit.egg-info/top_level.txt
|
|
|
16
17
|
tests/test_cli.py
|
|
17
18
|
tests/test_embeddings.py
|
|
18
19
|
tests/test_eval.py
|
|
20
|
+
tests/test_files.py
|
|
19
21
|
tests/test_index.py
|
|
20
|
-
tests/test_ollama.py
|
|
22
|
+
tests/test_ollama.py
|
|
23
|
+
tests/test_serve.py
|
|
@@ -73,3 +73,49 @@ class CliJsonTests(unittest.TestCase):
|
|
|
73
73
|
|
|
74
74
|
if __name__ == "__main__":
|
|
75
75
|
unittest.main()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class DefaultDbTests(unittest.TestCase):
|
|
79
|
+
def setUp(self):
|
|
80
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
81
|
+
self.addCleanup(self.tmp.cleanup)
|
|
82
|
+
self.root = Path(self.tmp.name)
|
|
83
|
+
|
|
84
|
+
def env(self, **extra):
|
|
85
|
+
return mock.patch.dict(
|
|
86
|
+
"os.environ",
|
|
87
|
+
{"LOCALAPPDATA": str(self.root / "local"), "XDG_DATA_HOME": str(self.root / "xdg"),
|
|
88
|
+
"HOME": str(self.root), "USERPROFILE": str(self.root), **extra},
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def test_explicit_db_wins(self):
|
|
92
|
+
with self.env(OFFLINE_RAG_DB=str(self.root / "env.sqlite3")):
|
|
93
|
+
self.assertEqual(cli.resolve_db("x.sqlite3"), "x.sqlite3")
|
|
94
|
+
|
|
95
|
+
def test_env_variable_overrides_default(self):
|
|
96
|
+
with self.env(OFFLINE_RAG_DB=str(self.root / "env.sqlite3")):
|
|
97
|
+
self.assertEqual(cli.resolve_db(None), str(self.root / "env.sqlite3"))
|
|
98
|
+
|
|
99
|
+
def test_default_is_fixed_and_independent_of_cwd(self):
|
|
100
|
+
with self.env():
|
|
101
|
+
first = cli.resolve_db(None)
|
|
102
|
+
self.assertTrue(Path(first).is_absolute())
|
|
103
|
+
self.assertEqual(Path(first).name, "index.sqlite3")
|
|
104
|
+
self.assertEqual(Path(first).parent.name, "offline-rag")
|
|
105
|
+
self.assertTrue(str(self.root) in first)
|
|
106
|
+
|
|
107
|
+
def test_legacy_local_index_is_used_with_a_hint(self):
|
|
108
|
+
with self.env(), mock.patch.object(cli, "LEGACY_DB", self.root / "legacy.sqlite3"):
|
|
109
|
+
(self.root / "legacy.sqlite3").write_bytes(b"")
|
|
110
|
+
err = io.StringIO()
|
|
111
|
+
with contextlib.redirect_stderr(err):
|
|
112
|
+
self.assertEqual(cli.resolve_db(None), str(self.root / "legacy.sqlite3"))
|
|
113
|
+
self.assertIn("New default location", err.getvalue())
|
|
114
|
+
|
|
115
|
+
def test_fixed_index_beats_legacy(self):
|
|
116
|
+
with self.env(), mock.patch.object(cli, "LEGACY_DB", self.root / "legacy.sqlite3"):
|
|
117
|
+
(self.root / "legacy.sqlite3").write_bytes(b"")
|
|
118
|
+
fixed = cli.default_db_path()
|
|
119
|
+
fixed.parent.mkdir(parents=True)
|
|
120
|
+
fixed.write_bytes(b"")
|
|
121
|
+
self.assertEqual(cli.resolve_db(None), str(fixed))
|
|
@@ -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()
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Tests for the local read-only web interface."""
|
|
2
|
+
|
|
3
|
+
import http.client
|
|
4
|
+
import json
|
|
5
|
+
import sqlite3
|
|
6
|
+
import tempfile
|
|
7
|
+
import threading
|
|
8
|
+
import unittest
|
|
9
|
+
from contextlib import closing
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import pymupdf
|
|
13
|
+
|
|
14
|
+
from offline_rag import cli
|
|
15
|
+
from offline_rag.index import ingest, search
|
|
16
|
+
from offline_rag.serve import PreviewError, make_server, render_preview
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ServeTests(unittest.TestCase):
|
|
20
|
+
def setUp(self):
|
|
21
|
+
tmp = tempfile.TemporaryDirectory()
|
|
22
|
+
self.addCleanup(tmp.cleanup)
|
|
23
|
+
root = Path(tmp.name)
|
|
24
|
+
docs = root / "docs"
|
|
25
|
+
docs.mkdir()
|
|
26
|
+
(docs / "a.md").write_text("The retention policy keeps invoices for ten years", encoding="utf-8")
|
|
27
|
+
(docs / "b.txt").write_text("<script>alert(1)</script> retention of logs", encoding="utf-8")
|
|
28
|
+
self.db = root / "i.sqlite3"
|
|
29
|
+
ingest(docs, self.db)
|
|
30
|
+
self.before = self.db.read_bytes()
|
|
31
|
+
self.server = make_server(self.db, 0)
|
|
32
|
+
self.port = self.server.server_address[1]
|
|
33
|
+
thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
|
34
|
+
thread.start()
|
|
35
|
+
self.addCleanup(thread.join, 5)
|
|
36
|
+
self.addCleanup(self.server.server_close)
|
|
37
|
+
self.addCleanup(self.server.shutdown)
|
|
38
|
+
|
|
39
|
+
def request(self, method, path, host=None):
|
|
40
|
+
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5)
|
|
41
|
+
connection.request(method, path, headers={"Host": host or f"127.0.0.1:{self.port}"})
|
|
42
|
+
response = connection.getresponse()
|
|
43
|
+
body = response.read()
|
|
44
|
+
connection.close()
|
|
45
|
+
return response, body
|
|
46
|
+
|
|
47
|
+
def test_binds_to_loopback_only(self):
|
|
48
|
+
self.assertEqual(self.server.server_address[0], "127.0.0.1")
|
|
49
|
+
|
|
50
|
+
def test_home_page_and_security_headers(self):
|
|
51
|
+
response, body = self.request("GET", "/")
|
|
52
|
+
self.assertEqual(response.status, 200)
|
|
53
|
+
self.assertIn(b"offline-rag", body)
|
|
54
|
+
self.assertIn("default-src 'none'", response.getheader("Content-Security-Policy"))
|
|
55
|
+
self.assertEqual(response.getheader("X-Content-Type-Options"), "nosniff")
|
|
56
|
+
|
|
57
|
+
def test_page_never_uses_innerhtml(self):
|
|
58
|
+
_, body = self.request("GET", "/")
|
|
59
|
+
self.assertNotIn(b"innerHTML", body)
|
|
60
|
+
|
|
61
|
+
def test_search_returns_passages(self):
|
|
62
|
+
response, body = self.request("GET", "/api/search?q=retention+policy")
|
|
63
|
+
data = json.loads(body)
|
|
64
|
+
self.assertEqual(response.status, 200)
|
|
65
|
+
self.assertEqual(data["results"][0]["path"], "a.md")
|
|
66
|
+
self.assertIn("**retention**", data["results"][0]["snippet"])
|
|
67
|
+
|
|
68
|
+
def test_files_view(self):
|
|
69
|
+
_, body = self.request("GET", "/api/files?q=retention")
|
|
70
|
+
self.assertEqual(json.loads(body)["total"], 2)
|
|
71
|
+
|
|
72
|
+
def test_markup_in_documents_is_returned_as_plain_text(self):
|
|
73
|
+
response, body = self.request("GET", "/api/search?q=alert")
|
|
74
|
+
self.assertTrue(response.getheader("Content-Type").startswith("application/json"))
|
|
75
|
+
self.assertIn("<script>", json.loads(body)["results"][0]["snippet"])
|
|
76
|
+
|
|
77
|
+
def test_empty_and_overlong_queries_are_rejected(self):
|
|
78
|
+
self.assertEqual(self.request("GET", "/api/search?q=")[0].status, 400)
|
|
79
|
+
self.assertEqual(self.request("GET", "/api/search?q=" + "a" * 501)[0].status, 400)
|
|
80
|
+
|
|
81
|
+
def test_foreign_host_header_is_refused(self):
|
|
82
|
+
for host in ("evil.example", f"evil.example:{self.port}", "127.0.0.1"):
|
|
83
|
+
self.assertEqual(self.request("GET", "/", host=host)[0].status, 403, host)
|
|
84
|
+
self.assertEqual(self.request("GET", "/", host=f"localhost:{self.port}")[0].status, 200)
|
|
85
|
+
|
|
86
|
+
def test_only_get_is_allowed(self):
|
|
87
|
+
for method in ("POST", "PUT", "DELETE", "PATCH"):
|
|
88
|
+
self.assertEqual(self.request(method, "/api/search?q=x")[0].status, 405, method)
|
|
89
|
+
|
|
90
|
+
def test_unknown_path_is_404(self):
|
|
91
|
+
self.assertEqual(self.request("GET", "/etc/passwd")[0].status, 404)
|
|
92
|
+
|
|
93
|
+
def test_index_is_not_modified(self):
|
|
94
|
+
self.request("GET", "/api/search?q=retention")
|
|
95
|
+
self.request("GET", "/api/files?q=retention")
|
|
96
|
+
self.assertEqual(self.db.read_bytes(), self.before)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class PreviewTests(unittest.TestCase):
|
|
100
|
+
def setUp(self):
|
|
101
|
+
tmp = tempfile.TemporaryDirectory()
|
|
102
|
+
self.addCleanup(tmp.cleanup)
|
|
103
|
+
self.root = Path(tmp.name)
|
|
104
|
+
self.docs = self.root / "docs"
|
|
105
|
+
self.docs.mkdir()
|
|
106
|
+
(self.docs / "notes.md").write_text("markdown about a quasar", encoding="utf-8")
|
|
107
|
+
self.pdf = self.docs / "report.pdf"
|
|
108
|
+
document = pymupdf.open()
|
|
109
|
+
page = document.new_page()
|
|
110
|
+
page.insert_text((72, 100), "Quasar luminosity report", fontsize=14)
|
|
111
|
+
document.save(self.pdf)
|
|
112
|
+
document.close()
|
|
113
|
+
self.db = self.root / "i.sqlite3"
|
|
114
|
+
ingest(self.docs, self.db)
|
|
115
|
+
self.hits = {h["path"]: h for h in search("quasar", self.db, 10)}
|
|
116
|
+
self.pdf_before = self.pdf.read_bytes()
|
|
117
|
+
|
|
118
|
+
def png(self, passage_id):
|
|
119
|
+
data = render_preview(self.db, passage_id)
|
|
120
|
+
self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n")
|
|
121
|
+
return pymupdf.Pixmap(data)
|
|
122
|
+
|
|
123
|
+
def assert_highlighted(self, pixmap, point):
|
|
124
|
+
"""The pixel is the yellow tint of the highlight, not white paper."""
|
|
125
|
+
r, g, b = pixmap.pixel(int(point[0]), int(point[1]))[:3]
|
|
126
|
+
self.assertGreater(r, 240)
|
|
127
|
+
self.assertLess(b, 200)
|
|
128
|
+
|
|
129
|
+
def test_pdf_preview_highlights_the_passage(self):
|
|
130
|
+
hit = self.hits["report.pdf"]
|
|
131
|
+
pixmap = self.png(hit["id"])
|
|
132
|
+
x0, y0, _, _ = (float(n) for n in hit["bbox"].split(","))
|
|
133
|
+
zoom = pixmap.width / 595.0 # A4 width in points
|
|
134
|
+
self.assert_highlighted(pixmap, ((x0 + 1) * zoom, (y0 + 1) * zoom))
|
|
135
|
+
|
|
136
|
+
def test_rotated_page_keeps_the_highlight_on_the_text(self):
|
|
137
|
+
document = pymupdf.open(self.pdf)
|
|
138
|
+
document[0].set_rotation(90)
|
|
139
|
+
document.save(self.root / "rot.pdf")
|
|
140
|
+
document.close()
|
|
141
|
+
(self.root / "rot.pdf").replace(self.pdf)
|
|
142
|
+
ingest(self.docs, self.db)
|
|
143
|
+
hit = {h["path"]: h for h in search("quasar", self.db, 10)}["report.pdf"]
|
|
144
|
+
pixmap = self.png(hit["id"])
|
|
145
|
+
x0, y0, _, _ = (float(n) for n in hit["bbox"].split(","))
|
|
146
|
+
# 90 degrees clockwise: an unrotated point (x, y) lands at (page_height - y, x).
|
|
147
|
+
zoom = pixmap.width / 842.0
|
|
148
|
+
self.assert_highlighted(pixmap, ((842.0 - (y0 + 1)) * zoom, (x0 + 1) * zoom))
|
|
149
|
+
|
|
150
|
+
def test_text_files_have_no_preview(self):
|
|
151
|
+
with self.assertRaises(PreviewError) as raised:
|
|
152
|
+
render_preview(self.db, self.hits["notes.md"]["id"])
|
|
153
|
+
self.assertEqual(raised.exception.status, 404)
|
|
154
|
+
|
|
155
|
+
def test_unknown_id_and_missing_file(self):
|
|
156
|
+
with self.assertRaises(PreviewError) as raised:
|
|
157
|
+
render_preview(self.db, 99999)
|
|
158
|
+
self.assertEqual(raised.exception.status, 404)
|
|
159
|
+
self.pdf.unlink()
|
|
160
|
+
with self.assertRaises(PreviewError) as raised:
|
|
161
|
+
render_preview(self.db, self.hits["report.pdf"]["id"])
|
|
162
|
+
self.assertEqual(raised.exception.status, 404)
|
|
163
|
+
|
|
164
|
+
def test_file_outside_the_indexed_folder_is_refused(self):
|
|
165
|
+
(self.root / "secret.pdf").write_bytes(self.pdf.read_bytes())
|
|
166
|
+
with closing(sqlite3.connect(self.db)) as connection, connection:
|
|
167
|
+
connection.execute("UPDATE passages SET path = ? WHERE path = 'report.pdf'", ("../secret.pdf",))
|
|
168
|
+
with self.assertRaises(PreviewError) as raised:
|
|
169
|
+
render_preview(self.db, self.hits["report.pdf"]["id"])
|
|
170
|
+
self.assertEqual(raised.exception.status, 403)
|
|
171
|
+
|
|
172
|
+
def test_changed_file_with_fewer_pages_is_a_clean_error(self):
|
|
173
|
+
with closing(sqlite3.connect(self.db)) as connection, connection:
|
|
174
|
+
connection.execute("UPDATE passages SET page = 7 WHERE path = 'report.pdf'")
|
|
175
|
+
with self.assertRaises(PreviewError) as raised:
|
|
176
|
+
render_preview(self.db, self.hits["report.pdf"]["id"])
|
|
177
|
+
self.assertEqual(raised.exception.status, 404)
|
|
178
|
+
|
|
179
|
+
def test_preview_never_modifies_the_pdf_or_the_index(self):
|
|
180
|
+
index_before = self.db.read_bytes()
|
|
181
|
+
self.png(self.hits["report.pdf"]["id"])
|
|
182
|
+
self.assertEqual(self.pdf.read_bytes(), self.pdf_before)
|
|
183
|
+
self.assertEqual(self.db.read_bytes(), index_before)
|
|
184
|
+
|
|
185
|
+
def test_http_endpoint(self):
|
|
186
|
+
server = make_server(self.db, 0)
|
|
187
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
188
|
+
thread.start()
|
|
189
|
+
self.addCleanup(thread.join, 5)
|
|
190
|
+
self.addCleanup(server.server_close)
|
|
191
|
+
self.addCleanup(server.shutdown)
|
|
192
|
+
port = server.server_address[1]
|
|
193
|
+
|
|
194
|
+
def get(path):
|
|
195
|
+
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
|
|
196
|
+
connection.request("GET", path, headers={"Host": f"127.0.0.1:{port}"})
|
|
197
|
+
response = connection.getresponse()
|
|
198
|
+
body = response.read()
|
|
199
|
+
connection.close()
|
|
200
|
+
return response, body
|
|
201
|
+
|
|
202
|
+
response, body = get(f"/preview?id={self.hits['report.pdf']['id']}")
|
|
203
|
+
self.assertEqual((response.status, response.getheader("Content-Type")), (200, "image/png"))
|
|
204
|
+
self.assertEqual(body[:4], b"\x89PNG")
|
|
205
|
+
for bad in ("/preview", "/preview?id=abc", "/preview?id=-1", "/preview?id=1;2", "/preview?id=%C2%B2"):
|
|
206
|
+
self.assertEqual(get(bad)[0].status, 400, bad)
|
|
207
|
+
self.assertEqual(get("/preview?id=99999")[0].status, 404)
|
|
208
|
+
self.assertEqual(get("/api/search?q=quasar")[0].status, 200)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class ServeCommandTests(unittest.TestCase):
|
|
212
|
+
def test_missing_index_is_a_clear_error(self):
|
|
213
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
214
|
+
missing = Path(tmp) / "none.sqlite3"
|
|
215
|
+
with self.assertRaises(SystemExit) as raised:
|
|
216
|
+
cli.main(["--db", str(missing), "serve", "--port", "0"])
|
|
217
|
+
self.assertEqual(raised.exception.code, 1)
|
|
218
|
+
self.assertFalse(missing.exists())
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
if __name__ == "__main__":
|
|
222
|
+
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.5}/src/offline_rag_kit.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{offline_rag_kit-0.1.3 → offline_rag_kit-0.1.5}/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
|