offline-rag-kit 0.1.4__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.
Files changed (25) hide show
  1. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/PKG-INFO +22 -3
  2. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/README.md +21 -2
  3. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/pyproject.toml +1 -1
  4. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag/__init__.py +1 -1
  5. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag/cli.py +63 -1
  6. offline_rag_kit-0.1.5/src/offline_rag/serve.py +332 -0
  7. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/PKG-INFO +22 -3
  8. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/SOURCES.txt +3 -1
  9. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/tests/test_cli.py +46 -0
  10. offline_rag_kit-0.1.5/tests/test_serve.py +222 -0
  11. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/LICENSE +0 -0
  12. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/setup.cfg +0 -0
  13. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag/embeddings.py +0 -0
  14. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag/eval.py +0 -0
  15. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag/index.py +0 -0
  16. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag/ollama.py +0 -0
  17. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/dependency_links.txt +0 -0
  18. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/entry_points.txt +0 -0
  19. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/requires.txt +0 -0
  20. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/src/offline_rag_kit.egg-info/top_level.txt +0 -0
  21. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/tests/test_embeddings.py +0 -0
  22. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/tests/test_eval.py +0 -0
  23. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/tests/test_files.py +0 -0
  24. {offline_rag_kit-0.1.4 → offline_rag_kit-0.1.5}/tests/test_index.py +0 -0
  25. {offline_rag_kit-0.1.4 → 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.4
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.
@@ -65,13 +78,14 @@ offline-rag search "retention policy"
65
78
  ### Use it from any terminal, and where the index lives
66
79
 
67
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.
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`:
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`:
69
82
 
70
83
  ```powershell
71
84
  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
85
  ```
74
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
+
75
89
  To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
76
90
 
77
91
  ```powershell
@@ -89,8 +103,13 @@ offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vect
89
103
  offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
90
104
  offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
91
105
  [--ollama-host URL] [--allow-remote]
106
+ offline-rag [--db PATH] serve [--port 8765] [--open]
92
107
  ```
93
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
+
94
113
  ### Which files contain a word?
95
114
 
96
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.
@@ -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.
@@ -43,13 +56,14 @@ offline-rag search "retention policy"
43
56
  ### Use it from any terminal, and where the index lives
44
57
 
45
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.
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`:
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`:
47
60
 
48
61
  ```powershell
49
62
  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
63
  ```
52
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
+
53
67
  To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
54
68
 
55
69
  ```powershell
@@ -67,8 +81,13 @@ offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vect
67
81
  offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
68
82
  offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
69
83
  [--ollama-host URL] [--allow-remote]
84
+ offline-rag [--db PATH] serve [--port 8765] [--open]
70
85
  ```
71
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
+
72
91
  ### Which files contain a word?
73
92
 
74
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.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "offline-rag-kit"
7
- version = "0.1.4"
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"
@@ -1,3 +1,3 @@
1
1
  """Privacy-first retrieval over local documents."""
2
2
 
3
- __version__ = "0.1.4"
3
+ __version__ = "0.1.5"
@@ -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
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("--db", default=".offline-rag/index.sqlite3", help="Local SQLite index path")
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,6 +67,10 @@ 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")
@@ -110,8 +151,27 @@ def _retrieve(args) -> list[dict]:
110
151
  return run(args.query, args.db, embedder, limit)
111
152
 
112
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.")
170
+
171
+
113
172
  def main(argv: list[str] | None = None) -> None:
114
173
  args = build_parser().parse_args(argv)
174
+ args.db = resolve_db(args.db)
115
175
  try:
116
176
  if args.command == "ingest":
117
177
  result = ingest(args.folder, args.db)
@@ -128,6 +188,8 @@ def main(argv: list[str] | None = None) -> None:
128
188
  f"Indexed {result.files} files ({result.unchanged} unchanged) and "
129
189
  f"{result.passages} passages in {args.db}"
130
190
  )
191
+ elif args.command == "serve":
192
+ _serve(args)
131
193
  elif args.command == "embed":
132
194
  embedder = ollama_embedder(args.model, args.ollama_host, args.allow_remote)
133
195
  count = embed_index(args.db, embedder, args.model, rebuild=args.rebuild)
@@ -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.4
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.
@@ -65,13 +78,14 @@ offline-rag search "retention policy"
65
78
  ### Use it from any terminal, and where the index lives
66
79
 
67
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.
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`:
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`:
69
82
 
70
83
  ```powershell
71
84
  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
85
  ```
74
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
+
75
89
  To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
76
90
 
77
91
  ```powershell
@@ -89,8 +103,13 @@ offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vect
89
103
  offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
90
104
  offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
91
105
  [--ollama-host URL] [--allow-remote]
106
+ offline-rag [--db PATH] serve [--port 8765] [--open]
92
107
  ```
93
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
+
94
113
  ### Which files contain a word?
95
114
 
96
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.
@@ -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
@@ -18,4 +19,5 @@ tests/test_embeddings.py
18
19
  tests/test_eval.py
19
20
  tests/test_files.py
20
21
  tests/test_index.py
21
- 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,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