-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcortex.py
More file actions
2883 lines (2576 loc) · 109 KB
/
Copy pathcortex.py
File metadata and controls
2883 lines (2576 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
cortex.py - Offline chat app with built-in indexer + RAG.
Drag-and-drop or upload PDF / EPUB / DOCX / TXT / MD files. Cortex
extracts, chunks, embeds, and caches them locally. Attach indexed
documents to conversations to ground answers in their content.
Cache lives at:
Linux: ~/.config/cortex/library/
macOS: ~/Library/Application Support/cortex/library/
Windows: %APPDATA%/cortex/library/
Setup:
pip install fastapi uvicorn ollama numpy python-multipart \
pypdf ebooklib beautifulsoup4 python-docx
ollama pull qwen2.5:7b
ollama pull nomic-embed-text
python cortex.py
Configure via environment:
CORTEX_MODEL=qwen2.5:7b # default; bump to :14b or :32b on bigger GPUs
CORTEX_EMBED_MODEL=nomic-embed-text
CORTEX_HOST=127.0.0.1
CORTEX_PORT=8000
CORTEX_TOP_K=6
CORTEX_LIBRARY=/custom/library/path # auto by platform if unset
CORTEX_SMARTREADER_CACHE=/path # set to also read SmartReader caches
"""
from __future__ import annotations
import asyncio
import hashlib
import io
import json
import os
import pickle
import re
import sqlite3
import sys
import threading
import time
import uuid
from contextlib import asynccontextmanager
from pathlib import Path
from typing import AsyncIterator, Callable, Iterable
import numpy as np
import ollama
import uvicorn
from fastapi import FastAPI, HTTPException, UploadFile, File
from fastapi.responses import HTMLResponse, StreamingResponse
from pydantic import BaseModel
# === Configuration ========================================================
# === Model tiers ==========================================================
# Cortex ships with three model tiers in a single executable. Users select
# at runtime via the UI dropdown; the choice persists across launches via
# a small JSON file alongside the conversation DB.
#
# Each tier has:
# id: stable identifier used by the UI and config
# ollama_name: the actual Ollama model tag to call
# label: display name in the UI
# description: tooltip / detail line
# tier: numeric capability ranking (1=lite, 2=standard, 3=research)
# used by mode gating to hide scaffolds the model can't handle
# recommended_top_k: per-tier retrieval default
MODEL_TIERS: dict[str, dict] = {
"lite": {
"ollama_name": "qwen2.5:7b",
"label": "Lite (7B)",
"description": "Fast, fits 8 GB VRAM. Good for quick lookups and RAG-grounded queries.",
"tier": 1,
"recommended_top_k": 4,
},
"standard": {
"ollama_name": "qwen2.5:14b",
"label": "Standard (14B)",
"description": "Balanced. Needs ~10 GB VRAM. Stronger reasoning than 7B at usable speed.",
"tier": 2,
"recommended_top_k": 6,
},
"research": {
"ollama_name": "qwen2.5:32b-instruct-q4_K_L",
"label": "Research (32B Q4_K_L)",
"description": "Highest precision. Needs 24 GB VRAM for full speed, or 32+ GB system RAM for slow CPU offload.",
"tier": 3,
"recommended_top_k": 6,
},
}
DEFAULT_TIER = os.environ.get("CORTEX_DEFAULT_TIER", "lite")
if DEFAULT_TIER not in MODEL_TIERS:
DEFAULT_TIER = "lite"
# Runtime state for the active model. Persisted to disk so the user's
# choice survives restarts. The legacy CORTEX_MODEL env var still works
# for power users — it overrides the tier system entirely with a raw
# Ollama model name.
_ACTIVE_TIER: str = DEFAULT_TIER
_OVERRIDE_MODEL: str | None = os.environ.get("CORTEX_MODEL") # if set, bypasses tiers
def _state_file() -> Path:
return LIBRARY_DIR.parent / "cortex_state.json"
def _load_active_tier() -> None:
"""Read the persisted tier choice from disk, fall back to default."""
global _ACTIVE_TIER
if _OVERRIDE_MODEL:
return # env override wins, ignore persisted state
try:
f = _state_file()
if f.exists():
data = json.loads(f.read_text())
tier = data.get("active_tier")
if tier in MODEL_TIERS:
_ACTIVE_TIER = tier
except Exception:
pass
def _save_active_tier(tier: str) -> None:
"""Persist the user's tier choice."""
try:
f = _state_file()
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text(json.dumps({"active_tier": tier}))
except Exception as e:
print(f"WARN: could not persist tier: {e}", file=sys.stderr)
def active_model_name() -> str:
"""Return the Ollama model name to call right now."""
if _OVERRIDE_MODEL:
return _OVERRIDE_MODEL
return MODEL_TIERS[_ACTIVE_TIER]["ollama_name"]
def active_tier_info() -> dict:
"""Return descriptive info about the currently active model."""
if _OVERRIDE_MODEL:
return {
"id": "custom",
"ollama_name": _OVERRIDE_MODEL,
"label": _OVERRIDE_MODEL,
"description": "Custom model set via CORTEX_MODEL env var.",
"tier": 3, # treat custom as full-capability for mode gating
"recommended_top_k": int(os.environ.get("CORTEX_TOP_K", "6")),
}
return {"id": _ACTIVE_TIER, **MODEL_TIERS[_ACTIVE_TIER]}
EMBED_MODEL = os.environ.get("CORTEX_EMBED_MODEL", "nomic-embed-text")
HOST = os.environ.get("CORTEX_HOST", "127.0.0.1")
PORT = int(os.environ.get("CORTEX_PORT", "8000"))
def active_top_k() -> int:
"""Resolve the retrieval count for the currently active model.
Honors CORTEX_TOP_K override if set, otherwise uses the tier's recommendation."""
env_override = os.environ.get("CORTEX_TOP_K")
if env_override:
try:
return int(env_override)
except ValueError:
pass
return active_tier_info()["recommended_top_k"]
CHUNK_SIZE = 1000 # characters per chunk
CHUNK_OVERLAP = 200 # overlap between adjacent chunks
EMBED_TRUNCATE = 500 # SmartReader-compatible: embed first N chars only
def _cortex_library_dir() -> Path:
override = os.environ.get("CORTEX_LIBRARY")
if override:
return Path(override)
if sys.platform == "win32":
return Path(os.environ.get("APPDATA", "")) / "cortex" / "library"
if sys.platform == "darwin":
return Path.home() / "Library" / "Application Support" / "cortex" / "library"
return Path.home() / ".config" / "cortex" / "library"
def _smartreader_cache_dir() -> Path | None:
"""SmartReader cache integration is opt-in.
To enable, set the CORTEX_SMARTREADER_CACHE environment variable to the
path of an existing SmartReader cache directory. Cortex then exposes
those caches as read-only library entries tagged `sr`.
Auto-detection was removed in 1.2: SmartReader caches lack the hierarchical
section summaries Cortex now produces, and surfacing them by default
created confusing duplicates with Cortex-native caches of the same books.
Users migrating from SmartReader should re-index in Cortex to take
advantage of structure-aware indexing.
"""
override = os.environ.get("CORTEX_SMARTREADER_CACHE")
if not override:
return None
p = Path(override)
if not p.exists():
print(
f"WARN: CORTEX_SMARTREADER_CACHE={override} but path does not exist",
file=sys.stderr,
)
return None
return p
LIBRARY_DIR = _cortex_library_dir()
SMARTREADER_DIR = _smartreader_cache_dir()
DB_PATH = LIBRARY_DIR.parent / "conversations.db"
# === Chunk class ==========================================================
class TextChunk:
"""Compatible with SmartReader's pickled cache format.
Note: no __slots__ on purpose — SmartReader's TextChunk doesn't use slots,
so its pickles carry a __dict__ that needs to land on a regular class."""
def __init__(self, text="", page_number=0, chunk_id=0, embedding=None, metadata=None):
self.text = text
self.page_number = page_number
self.chunk_id = chunk_id
self.embedding = embedding
self.metadata = metadata if metadata is not None else {}
class _CompatUnpickler(pickle.Unpickler):
"""Remap any TextChunk class path (SmartReader's, ours) to ours."""
def find_class(self, module: str, name: str):
if name == "TextChunk":
return TextChunk
return super().find_class(module, name)
def load_pickle_chunks(path: Path) -> list[TextChunk]:
with open(path, "rb") as f:
chunks = _CompatUnpickler(f).load()
return [c for c in chunks if getattr(c, "embedding", None)]
def save_pickle_chunks(path: Path, chunks: list[TextChunk]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as f:
pickle.dump(chunks, f)
# === Text extractors per format ==========================================
SUPPORTED_EXT = {".pdf", ".epub", ".docx", ".txt", ".md", ".markdown"}
def extract_pdf(path: Path) -> Iterable[tuple[int, str]]:
try:
from pypdf import PdfReader
except ImportError:
from PyPDF2 import PdfReader # fallback
reader = PdfReader(str(path))
for i, page in enumerate(reader.pages, start=1):
try:
text = page.extract_text() or ""
except Exception:
text = ""
if text.strip():
yield i, text
def extract_epub(path: Path) -> Iterable[tuple[int, str]]:
from ebooklib import epub, ITEM_DOCUMENT
from bs4 import BeautifulSoup
book = epub.read_epub(str(path))
chapter_idx = 0
for item in book.get_items():
if item.get_type() != ITEM_DOCUMENT:
continue
chapter_idx += 1
soup = BeautifulSoup(item.get_content(), "html.parser")
# Drop scripts/styles, get readable text
for tag in soup(["script", "style"]):
tag.decompose()
text = soup.get_text(separator="\n")
text = re.sub(r"\n{3,}", "\n\n", text).strip()
if text:
yield chapter_idx, text
def extract_docx(path: Path) -> Iterable[tuple[int, str]]:
from docx import Document
doc = Document(str(path))
# Group paragraphs into pseudo-pages of ~3000 chars to keep
# citation page numbers meaningful instead of one-per-paragraph.
PAGE_BUDGET = 3000
page = 1
buf: list[str] = []
size = 0
for para in doc.paragraphs:
text = para.text.strip()
if not text:
continue
buf.append(text)
size += len(text) + 1
if size >= PAGE_BUDGET:
yield page, "\n\n".join(buf)
page += 1
buf, size = [], 0
if buf:
yield page, "\n\n".join(buf)
def extract_text(path: Path) -> Iterable[tuple[int, str]]:
text = path.read_text(encoding="utf-8", errors="replace")
PAGE_BUDGET = 3000
page = 1
for start in range(0, len(text), PAGE_BUDGET):
chunk = text[start:start + PAGE_BUDGET]
if chunk.strip():
yield page, chunk
page += 1
def extract(path: Path) -> Iterable[tuple[int, str]]:
ext = path.suffix.lower()
if ext == ".pdf":
yield from extract_pdf(path)
elif ext == ".epub":
yield from extract_epub(path)
elif ext == ".docx":
yield from extract_docx(path)
elif ext in {".txt", ".md", ".markdown"}:
yield from extract_text(path)
else:
raise ValueError(f"unsupported file type: {ext}")
# === Chunking =============================================================
def chunk_pages(pages: Iterable[tuple[int, str]],
chunk_size: int = CHUNK_SIZE,
overlap: int = CHUNK_OVERLAP) -> list[TextChunk]:
chunks: list[TextChunk] = []
chunk_id = 0
for page_num, page_text in pages:
paragraphs = re.split(r"\n\s*\n", page_text)
current = ""
for para in paragraphs:
para = para.strip()
if not para:
continue
# If a single paragraph is larger than chunk_size, hard-split it
while len(para) > chunk_size:
head, para = para[:chunk_size], para[chunk_size - overlap:]
if current:
chunks.append(TextChunk(current.strip(), page_num, chunk_id))
chunk_id += 1
current = ""
chunks.append(TextChunk(head, page_num, chunk_id))
chunk_id += 1
if len(current) + len(para) + 2 < chunk_size:
current += para + "\n\n"
else:
if current.strip():
chunks.append(TextChunk(current.strip(), page_num, chunk_id))
chunk_id += 1
# Keep tail-of-current as overlap context
tail = current[-overlap:] if len(current) >= overlap else current
current = tail + para + "\n\n"
if current.strip():
chunks.append(TextChunk(current.strip(), page_num, chunk_id))
chunk_id += 1
return chunks
# === Embedding ============================================================
def embed_text(text: str) -> list[float] | None:
try:
resp = ollama.embeddings(model=EMBED_MODEL, prompt=text[:EMBED_TRUNCATE])
return resp["embedding"]
except Exception as e:
print(f"WARN: embed failed: {e}", file=sys.stderr)
return None
def embed_query(text: str) -> np.ndarray | None:
try:
resp = ollama.embeddings(model=EMBED_MODEL, prompt=text)
except Exception as e:
print(f"WARN: embed query failed: {e}", file=sys.stderr)
return None
vec = np.array(resp["embedding"], dtype=np.float32)
n = np.linalg.norm(vec) + 1e-10
return vec / n
# === Indexing pipeline ====================================================
INDEX_JOBS: dict[str, dict] = {} # book_id -> {status, progress, total, message}
def cache_path_for(file_hash: str, title: str) -> Path:
safe = re.sub(r"[^\w\s.-]", "", title).replace(" ", "_")[:60]
return LIBRARY_DIR / f"{safe}_{file_hash[:8]}.pkl"
def file_hash(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(1 << 16), b""):
h.update(block)
return h.hexdigest()
# === Hierarchical summarization ===========================================
# At index time, group chunks into sections (~10-20 chunks each, aligned
# to page/chapter boundaries when possible) and produce an LLM summary
# of each section. At query time, when chunks are retrieved we also
# fetch their section summaries — this gives the model both detail
# (verbatim chunks) and context (what the surrounding section is about),
# which addresses the most common chunk-retrieval failure: technically
# correct answer that misses the larger argument.
#
# Summaries are stored separately from chunks so:
# - existing caches remain loadable without re-indexing
# - summaries can be regenerated without redoing embeddings
# - the format change is incremental, not breaking
#
# Summarization is conditional: skipped on small documents where the
# whole thing fits in context anyway. Defaults are tuned for the Lite
# tier; higher tiers are fine with the same numbers.
SUMMARIZE_MIN_CHUNKS = 30 # don't summarize tiny documents
SUMMARIZE_SECTION_SIZE = 15 # ~15 chunks per section (~15000 chars)
SUMMARIZE_MAX_INPUT_CHARS = 12000 # cap section size handed to the LLM
SUMMARIZE_TARGET_WORDS = 120 # asked-for summary length
class Section:
"""A contiguous group of chunks plus an LLM-produced summary.
`title` is set when the section corresponds to a known structural unit
(PDF outline entry, parsed TOC entry); empty for fallback page-count sections."""
def __init__(self, section_id: int, chunk_ids: list[int],
page_range: tuple[int, int], summary: str = "",
title: str = ""):
self.section_id = section_id
self.chunk_ids = chunk_ids
self.page_range = page_range
self.summary = summary
self.title = title
def to_dict(self) -> dict:
return {
"section_id": self.section_id,
"chunk_ids": self.chunk_ids,
"page_range": list(self.page_range),
"summary": self.summary,
"title": self.title,
}
@classmethod
def from_dict(cls, d: dict) -> "Section":
return cls(
d["section_id"],
list(d["chunk_ids"]),
tuple(d["page_range"]),
d.get("summary", ""),
d.get("title", ""),
)
def summaries_path_for(cache_path: Path) -> Path:
"""Companion path for a chunk cache's summaries file."""
return cache_path.with_suffix(".summaries.json")
def load_summaries(cache_path: Path) -> list[Section]:
"""Load summaries for a cache. Returns empty list if not yet summarized
(older caches, small documents, or summarization skipped)."""
p = summaries_path_for(cache_path)
if not p.exists():
return []
try:
data = json.loads(p.read_text(encoding="utf-8"))
return [Section.from_dict(s) for s in data.get("sections", [])]
except Exception as e:
print(f"WARN: could not load summaries {p}: {e}", file=sys.stderr)
return []
def save_summaries(cache_path: Path, sections: list[Section]) -> None:
p = summaries_path_for(cache_path)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(
json.dumps({"sections": [s.to_dict() for s in sections]}, indent=2),
encoding="utf-8",
)
# --- Document structure extraction ----------------------------------------
# Books usually have explicit chapter/section structure. When we can recover
# it, the resulting sections are far more coherent than fixed-size chunking.
# Three approaches, tried in order:
# 1. PDF outline / bookmarks (built into well-made PDFs)
# 2. Table-of-contents page parsing (regex on text)
# 3. Fallback: fixed-size page-aligned chunking (the original strategy)
TOC_MIN_ENTRIES = 4 # need at least N entries to trust a structure
TOC_MIN_SECTION_CHUNKS = 4 # below this, merge with neighbor
def extract_pdf_outline(pdf_path: Path) -> list[tuple[str, int]]:
"""Read the PDF's built-in outline (bookmarks). Returns a flat list of
(title, 1-indexed page number) entries, or [] if no usable outline exists.
PDF outlines are trees; we flatten to a list. Sub-entries become their
own sections at the same level — which is what we want for retrieval
purposes (chapter and its subsections are both queryable units).
"""
try:
from pypdf import PdfReader
except ImportError:
try:
from PyPDF2 import PdfReader
except ImportError:
return []
try:
reader = PdfReader(str(pdf_path))
outline = reader.outline
except Exception as e:
print(f"WARN: could not read PDF outline: {e}", file=sys.stderr)
return []
entries: list[tuple[str, int]] = []
def _walk(items, depth: int = 0) -> None:
for item in items:
if isinstance(item, list):
_walk(item, depth + 1)
continue
try:
title = getattr(item, "title", None) or ""
title = str(title).strip()
if not title:
continue
# Resolve the page reference to a 1-indexed page number
page_num = reader.get_destination_page_number(item) # 0-indexed
if page_num is None:
continue
entries.append((title, page_num + 1))
except Exception:
continue
try:
_walk(outline)
except Exception as e:
print(f"WARN: outline walk failed: {e}", file=sys.stderr)
return []
# Deduplicate consecutive entries pointing at the same page
deduped: list[tuple[str, int]] = []
for title, page in entries:
if deduped and deduped[-1][1] == page:
continue
deduped.append((title, page))
return deduped
# Regex patterns for matching TOC lines. The structure varies but most
# have "Chapter N Title ... page" or "N.N Title ... page" formats.
# We match conservatively to avoid false positives in body text.
_TOC_LINE_PATTERNS = [
# "Chapter 3 The Brain 47"
re.compile(r"^\s*(?:Chapter|Ch\.?|Part|Section)\s+(\d+|[IVXLCDM]+)\s+(.+?)\s+(\d{1,4})\s*$",
re.IGNORECASE),
# "3.2 Synaptic plasticity 142"
re.compile(r"^\s*(\d+(?:\.\d+)*)\s+(.+?)\s+(\d{1,4})\s*$"),
# "Introduction ............. 1" (dot leaders)
re.compile(r"^\s*([^\d\.][^\.]{2,80}?)\s*\.{2,}\s*(\d{1,4})\s*$"),
# "The Limbic System 73" (loose form, last-resort)
re.compile(r"^\s*([A-Z][^\d]{4,80}?)\s{2,}(\d{1,4})\s*$"),
]
def parse_toc_from_text(pages: list[tuple[int, str]]) -> list[tuple[str, int]]:
"""Find a TOC page by name, parse it for chapter/page entries.
Looks for pages near the front of the document whose text contains the
word "Contents" or "Table of Contents." Then parses lines using the
patterns above. Returns [] if no plausible TOC is found.
"""
# Search the first 30 pages for a TOC marker
toc_pages: list[str] = []
in_toc = False
for page_num, text in pages[:30]:
head = text.strip().split("\n", 3)[0:3]
head_text = " ".join(head).lower()
if not in_toc and ("contents" in head_text or "table of contents" in head_text):
in_toc = True
if in_toc:
toc_pages.append(text)
# TOC usually doesn't span more than 5-8 pages; stop if we find
# what looks like chapter content (paragraph-shaped text)
line_count = len([l for l in text.split("\n") if l.strip()])
avg_line_len = (sum(len(l) for l in text.split("\n")) / max(1, line_count))
if avg_line_len > 80 and len(toc_pages) >= 2:
break
if len(toc_pages) >= 8:
break
if not toc_pages:
return []
# Apply patterns to each line
entries: list[tuple[str, int]] = []
for page_text in toc_pages:
for line in page_text.split("\n"):
line = line.strip()
if not line or len(line) < 6:
continue
for pat in _TOC_LINE_PATTERNS:
m = pat.match(line)
if not m:
continue
groups = m.groups()
# Last group is always the page number
try:
page = int(groups[-1])
except ValueError:
break
# Title is everything before the page number
title_parts = [g for g in groups[:-1] if g]
title = " ".join(title_parts).strip()
# Reject obvious false positives
if not title or page < 1 or page > 9999:
break
if len(title) > 120: # probably matched a sentence, not a TOC line
break
entries.append((title, page))
break
# Sanity: TOC pages should monotonically increase
cleaned: list[tuple[str, int]] = []
last_page = 0
for title, page in entries:
if page < last_page:
# Out-of-order — this isn't really a TOC entry, skip
continue
cleaned.append((title, page))
last_page = page
return cleaned
def sections_from_structure(chunks: list[TextChunk],
structure: list[tuple[str, int]]
) -> list[Section]:
"""Given a list of (chapter_title, start_page) entries, build sections
by assigning each chunk to the chapter that contains its page.
Tiny sections (fewer than TOC_MIN_SECTION_CHUNKS chunks) are merged
backward into the previous section — these are usually preface entries,
appendix subsections, or TOC parsing artifacts that we don't want as
standalone summarizable units.
"""
if not chunks or not structure:
return []
# Sort structure by page number; the outline order isn't always page-order
# (e.g. some books list appendices before bibliography)
structure = sorted(structure, key=lambda t: t[1])
# Build sections by walking chunks and assigning to the latest chapter
# whose start_page is <= the chunk's page.
sections: list[Section] = []
current_chunks: list[int] = []
current_title = ""
current_start_page = chunks[0].page_number
current_struct_idx = -1
def _flush(end_page: int) -> None:
nonlocal current_chunks
if not current_chunks:
return
sections.append(Section(
section_id=len(sections),
chunk_ids=current_chunks.copy(),
page_range=(current_start_page, end_page),
title=current_title,
))
current_chunks = []
last_page = chunks[0].page_number
for chunk in chunks:
# Which structural entry does this chunk fall under?
target_idx = current_struct_idx
for i, (_, start_page) in enumerate(structure):
if start_page <= chunk.page_number:
target_idx = i
else:
break
# Crossed into a new chapter — flush the previous section
if target_idx != current_struct_idx:
_flush(last_page)
current_struct_idx = target_idx
if target_idx >= 0:
current_title = structure[target_idx][0]
current_start_page = structure[target_idx][1]
else:
current_title = "" # pre-first-chapter material
current_start_page = chunk.page_number
current_chunks.append(chunk.chunk_id)
last_page = chunk.page_number
_flush(last_page)
# Merge tiny sections backward — TOC parsing often produces single-page
# entries for things like "About the Author" that aren't worth their own
# summary. The threshold of TOC_MIN_SECTION_CHUNKS is conservative.
merged: list[Section] = []
for section in sections:
if (merged
and len(section.chunk_ids) < TOC_MIN_SECTION_CHUNKS
and len(merged[-1].chunk_ids) + len(section.chunk_ids) < SUMMARIZE_SECTION_SIZE * 2):
prev = merged[-1]
prev.chunk_ids.extend(section.chunk_ids)
prev.page_range = (prev.page_range[0], section.page_range[1])
# Keep the earlier title — usually the parent chapter
else:
merged.append(section)
# Renumber section_ids after merging
for i, s in enumerate(merged):
s.section_id = i
return merged
def build_sections(chunks: list[TextChunk],
src_path: Path | None = None,
pages: list[tuple[int, str]] | None = None,
target_chunks_per_section: int = SUMMARIZE_SECTION_SIZE,
) -> list[Section]:
"""Build sections for a document, preferring structural cues over
fixed-size chunking.
Strategy in order of preference:
1. If src_path is a PDF and has a usable outline → use that
2. If pages were provided and contain a parseable TOC → use that
3. Fallback: page-aligned fixed-size grouping (the original strategy)
"""
if not chunks:
return []
# Attempt 1: PDF outline
if src_path and src_path.suffix.lower() == ".pdf":
structure = extract_pdf_outline(src_path)
if len(structure) >= TOC_MIN_ENTRIES:
sections = sections_from_structure(chunks, structure)
if sections:
print(f" Used PDF outline: {len(sections)} sections", file=sys.stderr)
return sections
# Attempt 2: TOC page parsing
if pages:
structure = parse_toc_from_text(pages)
if len(structure) >= TOC_MIN_ENTRIES:
sections = sections_from_structure(chunks, structure)
if sections:
print(f" Parsed TOC: {len(sections)} sections", file=sys.stderr)
return sections
# Attempt 3: fallback to original fixed-size strategy
return _build_sections_fixed(chunks, target_chunks_per_section)
def _build_sections_fixed(chunks: list[TextChunk],
target_chunks_per_section: int,
) -> list[Section]:
"""Original fixed-size, page-aligned section builder. Used as fallback
when no structural cues are recoverable."""
if not chunks:
return []
sections: list[Section] = []
buf: list[int] = []
buf_start_page = chunks[0].page_number
last_page = chunks[0].page_number
for chunk in chunks:
# If buffer is full enough AND we just crossed a page boundary,
# close the section. The page-boundary check avoids splitting
# arbitrary content mid-page.
if (len(buf) >= target_chunks_per_section
and chunk.page_number != last_page):
sections.append(Section(
section_id=len(sections),
chunk_ids=buf.copy(),
page_range=(buf_start_page, last_page),
))
buf = []
buf_start_page = chunk.page_number
buf.append(chunk.chunk_id)
last_page = chunk.page_number
if buf:
sections.append(Section(
section_id=len(sections),
chunk_ids=buf.copy(),
page_range=(buf_start_page, last_page),
))
return sections
def summarize_section(section_text: str, doc_title: str) -> str:
"""Ask the active LLM to summarize a section of the document.
Returns empty string on failure — caller can decide whether to retry."""
# Truncate input to avoid blowing out context on small models.
truncated = section_text[:SUMMARIZE_MAX_INPUT_CHARS]
if len(section_text) > SUMMARIZE_MAX_INPUT_CHARS:
truncated += "\n\n[...section continues; this is a partial view...]"
system = (
"You are summarizing a section of a longer document for a retrieval "
"system. Your summary will be shown alongside specific excerpts from "
"this section when a user asks a question that touches it. The "
"summary's job is to give context — what this section is fundamentally "
"about, what it argues or describes, and how it connects to the "
"broader document. Be concrete; mention specific concepts, methods, "
"or claims by name. Avoid generic phrasing like 'this section "
"discusses various topics'."
)
user = (
f"Document title: {doc_title}\n\n"
f"Section content:\n{truncated}\n\n"
f"Produce a {SUMMARIZE_TARGET_WORDS}-word summary of what this "
f"section is about. Output only the summary text, no preamble."
)
try:
resp = ollama.chat(
model=active_model_name(),
messages=[
{"role": "system", "content": system},
{"role": "user", "content": user},
],
options={"temperature": 0.3}, # lower than chat — we want consistency
)
return resp["message"]["content"].strip()
except Exception as e:
print(f"WARN: summarization failed: {e}", file=sys.stderr)
return ""
def summarize_book(chunks: list[TextChunk], doc_title: str,
progress: Callable[[int, int, str], None],
progress_start: int = 96, progress_end: int = 99,
src_path: Path | None = None,
pages: list[tuple[int, str]] | None = None,
) -> list[Section]:
"""Build sections and summarize each one. Updates progress in the
given range. Returns sections with summaries filled in (may be empty
strings on failure — we don't fail the whole index if summarization
has trouble).
src_path and pages are passed to build_sections so it can use structural
cues (PDF outline, TOC page) when available; without them, falls back
to fixed-size page-aligned grouping."""
sections = build_sections(chunks, src_path=src_path, pages=pages)
if not sections:
return []
progress(progress_start, 100, f"Summarizing {len(sections)} sections...")
chunks_by_id = {c.chunk_id: c for c in chunks}
for i, section in enumerate(sections):
# Assemble section text from its chunks
section_text = "\n\n".join(
chunks_by_id[cid].text
for cid in section.chunk_ids
if cid in chunks_by_id
)
section.summary = summarize_section(section_text, doc_title)
# Smooth progress update across the summarization range
if i % 2 == 0 or i == len(sections) - 1:
span = max(1, progress_end - progress_start)
pct = progress_start + int((i + 1) / len(sections) * span)
progress(pct, 100, f"Summarizing {i + 1}/{len(sections)} sections...")
return sections
def index_file(src_path: Path, book_id: str,
progress: Callable[[int, int, str], None],
display_title: str | None = None) -> Path:
"""Run extraction → chunking → embedding → save. Updates progress.
`display_title` is what the user sees in the library — typically derived
from the original upload filename, NOT from src_path (which is a temp
file with a UUID prefix). Falls back to src_path.stem if not provided.
"""
title = display_title or src_path.stem
progress(0, 100, f"Reading {src_path.name}...")
pages = list(extract(src_path))
if not pages:
raise RuntimeError("no extractable text")
progress(10, 100, f"Chunking {len(pages)} sections...")
chunks = chunk_pages(pages)
if not chunks:
raise RuntimeError("no chunks produced")
total = len(chunks)
progress(15, 100, f"Embedding {total} chunks...")
for i, chunk in enumerate(chunks):
emb = embed_text(chunk.text)
if emb is None:
raise RuntimeError(f"embedding failed at chunk {i}")
chunk.embedding = emb
if i % 10 == 0 or i == total - 1:
pct = 15 + int((i + 1) / total * 80)
progress(pct, 100, f"Embedding {i + 1}/{total} chunks...")
progress(96, 100, "Saving cache...")
fh = file_hash(src_path)
out = cache_path_for(fh, title)
save_pickle_chunks(out, chunks)
# Hierarchical summarization — only worth doing for documents large enough
# that section-level context actually helps. Small documents fit in
# context anyway.
skip_summaries = os.environ.get("CORTEX_SKIP_SUMMARIES", "").lower() in ("1", "true", "yes")
if not skip_summaries and len(chunks) >= SUMMARIZE_MIN_CHUNKS:
try:
sections = summarize_book(chunks, title, progress,
progress_start=96, progress_end=99,
src_path=src_path, pages=pages)
save_summaries(out, sections)
except Exception as e:
print(f"WARN: summarization failed for {title}: {e}", file=sys.stderr)
progress(100, 100, "Done")
return out
async def run_index_job(book_id: str, src_path: Path,
display_title: str | None = None) -> None:
job = INDEX_JOBS[book_id]
def progress(cur: int, tot: int, msg: str) -> None:
job["progress"] = cur
job["total"] = tot
job["message"] = msg
try:
# Run blocking work off the event loop
out_path = await asyncio.to_thread(
index_file, src_path, book_id, progress, display_title,
)
job["status"] = "done"
job["cache_path"] = str(out_path)
# Refresh in-memory book registry so the new book is queryable
discover_books()
except Exception as e:
job["status"] = "error"
job["message"] = str(e)
finally:
# Clean up the temp upload
try:
src_path.unlink(missing_ok=True)
except Exception:
pass
# === In-memory book index =================================================
class Book:
def __init__(self, book_id: str, title: str, path: Path, source: str):
self.id = book_id
self.title = title
self.path = path
self.source = source # "cortex" or "smartreader"
self.chunks: list[TextChunk] = []
self.matrix: np.ndarray | None = None
self.sections: list[Section] = []
# chunk_id -> section_id, built once at load time for O(1) lookup
self._chunk_to_section: dict[int, int] = {}
def load(self) -> None:
self.chunks = load_pickle_chunks(self.path)
if not self.chunks:
self.matrix = None
return
embs = np.array([c.embedding for c in self.chunks], dtype=np.float32)
norms = np.linalg.norm(embs, axis=1, keepdims=True) + 1e-10
self.matrix = embs / norms
# Load hierarchical summaries if available — older caches won't have them
self.sections = load_summaries(self.path)
self._chunk_to_section = {
cid: s.section_id
for s in self.sections