offline-rag-kit 0.1.1__tar.gz → 0.1.2__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 (20) hide show
  1. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/PKG-INFO +2 -2
  2. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/README.md +1 -1
  3. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/pyproject.toml +1 -1
  4. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag/__init__.py +1 -1
  5. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag/index.py +57 -5
  6. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag_kit.egg-info/PKG-INFO +2 -2
  7. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/tests/test_index.py +61 -1
  8. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/LICENSE +0 -0
  9. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/setup.cfg +0 -0
  10. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag/cli.py +0 -0
  11. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag/eval.py +0 -0
  12. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag/ollama.py +0 -0
  13. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag_kit.egg-info/SOURCES.txt +0 -0
  14. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag_kit.egg-info/dependency_links.txt +0 -0
  15. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag_kit.egg-info/entry_points.txt +0 -0
  16. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag_kit.egg-info/requires.txt +0 -0
  17. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/src/offline_rag_kit.egg-info/top_level.txt +0 -0
  18. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/tests/test_cli.py +0 -0
  19. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/tests/test_eval.py +0 -0
  20. {offline_rag_kit-0.1.1 → offline_rag_kit-0.1.2}/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.1
3
+ Version: 0.1.2
4
4
  Summary: Privacy-first local document search with PDF citations and optional Ollama answers
5
5
  Author: HugoDelgadoo
6
6
  Maintainer: HugoDelgadoo
@@ -97,7 +97,7 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
97
97
  | Web dashboard / user authentication | Planned |
98
98
  | Reliable claim-level grounding evaluation | Planned |
99
99
 
100
- The first version **does not** OCR scanned PDFs or interpret PDF tables reliably. Each PDF text block is a retrieval unit, so coordinates describe blocks rather than arbitrary answer spans. Changed files are refreshed on re-ingest and deleted files are removed from the index. This is a single-user developer prototype, not a hardened multi-user service.
100
+ The first version **does not** OCR scanned PDFs. Tables that PyMuPDF detects (ruled, and often well-aligned borderless ones) are indexed as one passage per table; detection is heuristic and can miss or misread complex layouts. Words split by a hyphen at a line end are rejoined. Each PDF text block is a retrieval unit, so coordinates describe blocks rather than arbitrary answer spans. Changed files are refreshed on re-ingest and deleted files are removed from the index. This is a single-user developer prototype, not a hardened multi-user service.
101
101
 
102
102
  ## Evaluation
103
103
 
@@ -75,7 +75,7 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
75
75
  | Web dashboard / user authentication | Planned |
76
76
  | Reliable claim-level grounding evaluation | Planned |
77
77
 
78
- The first version **does not** OCR scanned PDFs or interpret PDF tables reliably. Each PDF text block is a retrieval unit, so coordinates describe blocks rather than arbitrary answer spans. Changed files are refreshed on re-ingest and deleted files are removed from the index. This is a single-user developer prototype, not a hardened multi-user service.
78
+ The first version **does not** OCR scanned PDFs. Tables that PyMuPDF detects (ruled, and often well-aligned borderless ones) are indexed as one passage per table; detection is heuristic and can miss or misread complex layouts. Words split by a hyphen at a line end are rejoined. Each PDF text block is a retrieval unit, so coordinates describe blocks rather than arbitrary answer spans. Changed files are refreshed on re-ingest and deleted files are removed from the index. This is a single-user developer prototype, not a hardened multi-user service.
79
79
 
80
80
  ## Evaluation
81
81
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "offline-rag-kit"
7
- version = "0.1.1"
7
+ version = "0.1.2"
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.1"
3
+ __version__ = "0.1.2"
@@ -14,6 +14,10 @@ from typing import Callable, Iterator
14
14
  import pymupdf
15
15
 
16
16
  SUPPORTED_EXTENSIONS = {".md", ".txt", ".pdf"}
17
+ # Bump when extraction changes, so files indexed by older versions are re-extracted
18
+ # even though their content hash is unchanged. Stored as a prefix of the file hash.
19
+ EXTRACTOR_VERSION = 3
20
+ _HASH_PREFIX = f"x{EXTRACTOR_VERSION}:"
17
21
 
18
22
 
19
23
  def open_index(database: str | Path) -> sqlite3.Connection:
@@ -48,17 +52,64 @@ def open_index(database: str | Path) -> sqlite3.Connection:
48
52
  return connection
49
53
 
50
54
 
55
+ _HYPHEN_BREAK = re.compile(r"(\w)-[ \t]*\n[ \t]*(\w)")
56
+
57
+
58
+ def join_hyphenated(text: str) -> str:
59
+ """Rejoin words split by a hyphen at the end of a line ("docu-\\nment" -> "document").
60
+
61
+ The break is removed when the next line continues in lowercase; if it starts with a
62
+ capital or digit ("Jean-\\nPaul") the hyphen is kept. A real compound split at a
63
+ line end ("state-\\nof-the-art") loses its hyphen: an accepted trade-off, because
64
+ unjoined fragments ("docu- ment") cannot be found by search at all.
65
+ """
66
+ def repair(match: re.Match) -> str:
67
+ before, after = match.group(1), match.group(2)
68
+ return before + after if after.islower() else f"{before}-{after}"
69
+
70
+ return _HYPHEN_BREAK.sub(repair, text)
71
+
72
+
73
+ def _table_passages(page: "pymupdf.Page") -> list[tuple[pymupdf.Rect, str]]:
74
+ """Return (bbox, text) for each ruled table on the page; never raises."""
75
+ try:
76
+ tables = page.find_tables().tables
77
+ except Exception: # table detection is best-effort; plain text extraction still works
78
+ return []
79
+ found = []
80
+ for table in tables:
81
+ rows = [
82
+ [" ".join(str(cell or "").split()) for cell in row]
83
+ for row in table.extract()
84
+ ]
85
+ rows = [row for row in rows if any(row)]
86
+ if len(rows) < 2 or max(len(row) for row in rows) < 2:
87
+ continue # a single row or column is not worth treating as a table
88
+ found.append((pymupdf.Rect(table.bbox), "; ".join(" | ".join(row) for row in rows)))
89
+ return found
90
+
91
+
51
92
  def extract_passages(path: Path) -> Iterator[tuple[int, str, str]]:
52
- """Yield (page number, bounding box, paragraph text). Page 0 means text file."""
93
+ """Yield (page number, bounding box, paragraph text). Page 0 means text file.
94
+
95
+ Ruled PDF tables are emitted as one passage ("Item | Years; Invoices | 10; ...")
96
+ so a row stays connected to its header; text blocks inside a table are not repeated.
97
+ """
53
98
  if path.suffix.lower() == ".pdf":
54
99
  with pymupdf.open(path) as document:
55
100
  for page_number, page in enumerate(document, start=1):
101
+ tables = _table_passages(page)
102
+ for rect, text in tables:
103
+ yield page_number, ",".join(f"{n:.1f}" for n in rect), text
56
104
  for block in page.get_text("blocks"):
57
105
  if len(block) > 6 and block[6] != 0:
58
106
  continue # Skip image blocks.
59
- body = " ".join(str(block[4]).split())
107
+ body = " ".join(join_hyphenated(str(block[4])).split())
60
108
  if not body:
61
109
  continue
110
+ centre = pymupdf.Point((block[0] + block[2]) / 2, (block[1] + block[3]) / 2)
111
+ if any(centre in rect for rect, _ in tables):
112
+ continue # already part of a table passage
62
113
  bbox = ",".join(f"{float(n):.1f}" for n in block[:4])
63
114
  yield page_number, bbox, body
64
115
  else:
@@ -115,11 +166,12 @@ def ingest(folder: str | Path, database: str | Path) -> IngestResult:
115
166
  "SELECT size, mtime_ns, sha256 FROM files WHERE root = ? AND path = ?",
116
167
  (root_key, relative),
117
168
  ).fetchone()
118
- if known and (known["size"], known["mtime_ns"]) == (stat.st_size, stat.st_mtime_ns):
169
+ current = bool(known) and known["sha256"].startswith(_HASH_PREFIX)
170
+ if current and (known["size"], known["mtime_ns"]) == (stat.st_size, stat.st_mtime_ns):
119
171
  digest = known["sha256"] # same size and mtime: trust it, skip hashing
120
172
  else:
121
- digest = _sha256(path)
122
- if known and known["sha256"] == digest:
173
+ digest = _HASH_PREFIX + _sha256(path)
174
+ if current and known["sha256"] == digest:
123
175
  count = connection.execute(
124
176
  "SELECT COUNT(*) FROM passages WHERE root = ? AND path = ?", (root_key, relative)
125
177
  ).fetchone()[0]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: offline-rag-kit
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Privacy-first local document search with PDF citations and optional Ollama answers
5
5
  Author: HugoDelgadoo
6
6
  Maintainer: HugoDelgadoo
@@ -97,7 +97,7 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
97
97
  | Web dashboard / user authentication | Planned |
98
98
  | Reliable claim-level grounding evaluation | Planned |
99
99
 
100
- The first version **does not** OCR scanned PDFs or interpret PDF tables reliably. Each PDF text block is a retrieval unit, so coordinates describe blocks rather than arbitrary answer spans. Changed files are refreshed on re-ingest and deleted files are removed from the index. This is a single-user developer prototype, not a hardened multi-user service.
100
+ The first version **does not** OCR scanned PDFs. Tables that PyMuPDF detects (ruled, and often well-aligned borderless ones) are indexed as one passage per table; detection is heuristic and can miss or misread complex layouts. Words split by a hyphen at a line end are rejoined. Each PDF text block is a retrieval unit, so coordinates describe blocks rather than arbitrary answer spans. Changed files are refreshed on re-ingest and deleted files are removed from the index. This is a single-user developer prototype, not a hardened multi-user service.
101
101
 
102
102
  ## Evaluation
103
103
 
@@ -8,7 +8,7 @@ from unittest import mock
8
8
 
9
9
  import pymupdf
10
10
 
11
- from offline_rag.index import citation, ingest, search
11
+ from offline_rag.index import citation, ingest, join_hyphenated, search
12
12
 
13
13
 
14
14
  class IndexTests(unittest.TestCase):
@@ -171,6 +171,66 @@ class IndexTests(unittest.TestCase):
171
171
  self.assertEqual(len(result.skipped), 1)
172
172
  self.assertEqual(len(search("keep", self.db)), 1)
173
173
 
174
+ def _pdf_with_table(self, path):
175
+ with pymupdf.open() as doc:
176
+ page = doc.new_page()
177
+ page.insert_textbox(pymupdf.Rect(72, 72, 300, 120), "Retention periods are reviewed every year.", fontsize=11)
178
+ for r, row in enumerate([["Item", "Years"], ["Invoices", "10"], ["Tickets", "3"]]):
179
+ for c, value in enumerate(row):
180
+ rect = pymupdf.Rect(72 + c * 100, 230 + r * 24, 172 + c * 100, 254 + r * 24)
181
+ page.draw_rect(rect, width=0.8)
182
+ page.insert_text((rect.x0 + 4, rect.y1 - 7), value, fontsize=11)
183
+ doc.save(path)
184
+
185
+ def test_pdf_table_is_one_passage_connected_to_its_header(self):
186
+ self._pdf_with_table(self.docs / "table.pdf")
187
+ ingest(self.docs, self.db)
188
+ hit = search("invoices years", self.db)[0] # row label + header word together
189
+ self.assertIn("Item | Years", hit["body"])
190
+ self.assertIn("Invoices | 10", hit["body"])
191
+ self.assertEqual(hit["page"], 1)
192
+ self.assertEqual(len(hit["bbox"].split(",")), 4)
193
+ self.assertEqual(len(search("invoices", self.db)), 1) # row text not indexed twice
194
+ self.assertEqual(len(search("retention", self.db)), 1) # surrounding paragraph kept
195
+
196
+ def test_pdf_without_tables_is_unchanged(self):
197
+ path = self.docs / "plain.pdf"
198
+ with pymupdf.open() as doc:
199
+ doc.new_page().insert_text((72, 90), "Just plain text | with a pipe")
200
+ doc.save(path)
201
+ ingest(self.docs, self.db)
202
+ self.assertEqual(len(search("plain", self.db)), 1)
203
+
204
+ def test_files_indexed_by_older_extractor_are_reextracted(self):
205
+ import sqlite3
206
+
207
+ (self.docs / "a.md").write_text("old extractor", encoding="utf-8")
208
+ ingest(self.docs, self.db)
209
+ connection = sqlite3.connect(self.db) # simulate a row written by v0.1.x (bare hash)
210
+ with connection:
211
+ connection.execute("UPDATE files SET sha256 = substr(sha256, instr(sha256, ':') + 1)")
212
+ connection.close()
213
+ result = ingest(self.docs, self.db)
214
+ self.assertEqual((result.files, result.unchanged), (1, 0))
215
+ self.assertEqual(ingest(self.docs, self.db).unchanged, 1)
216
+
217
+ def test_join_hyphenated_words(self):
218
+ self.assertEqual(join_hyphenated("docu-\nment"), "document")
219
+ self.assertEqual(join_hyphenated("the pol-\n icy covers"), "the policy covers")
220
+ self.assertEqual(join_hyphenated("Jean-\nPaul"), "Jean-Paul") # capital: keep hyphen
221
+ self.assertEqual(join_hyphenated("well-known and a - b"), "well-known and a - b")
222
+
223
+ def test_pdf_hyphenated_line_breaks_are_searchable(self):
224
+ path = self.docs / "hyphen.pdf"
225
+ with pymupdf.open() as doc:
226
+ page = doc.new_page()
227
+ for i, line in enumerate(["The retention pol-", "icy covers every docu-", "ment in the archive."]):
228
+ page.insert_text((72, 90 + i * 14), line, fontsize=10)
229
+ doc.save(path)
230
+ ingest(self.docs, self.db)
231
+ hit = search("retention policy document", self.db)[0]
232
+ self.assertIn("policy covers every document", hit["body"])
233
+
174
234
 
175
235
  if __name__ == "__main__":
176
236
  unittest.main()
File without changes