studyrag 0.1.0__py3-none-any.whl
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.
- studyrag/__init__.py +7 -0
- studyrag/__main__.py +3 -0
- studyrag/answer.py +104 -0
- studyrag/bm25.py +80 -0
- studyrag/chunking.py +201 -0
- studyrag/cli.py +152 -0
- studyrag/config.py +98 -0
- studyrag/core.py +57 -0
- studyrag/embeddings.py +57 -0
- studyrag/hybrid.py +22 -0
- studyrag/ingest/__init__.py +6 -0
- studyrag/ingest/cleaning.py +80 -0
- studyrag/ingest/loaders.py +266 -0
- studyrag/ingest/models.py +46 -0
- studyrag/ingest/ocr.py +154 -0
- studyrag/library.py +180 -0
- studyrag/llm/__init__.py +19 -0
- studyrag/llm/base.py +50 -0
- studyrag/llm/llamacpp.py +94 -0
- studyrag/llm/openai_compat.py +142 -0
- studyrag/prompts.py +165 -0
- studyrag/retrieval.py +86 -0
- studyrag/study/__init__.py +1 -0
- studyrag/study/generate.py +257 -0
- studyrag/study/quiz.py +63 -0
- studyrag/study/summarize.py +69 -0
- studyrag/text.py +67 -0
- studyrag/vector_index.py +55 -0
- studyrag/verify.py +106 -0
- studyrag-0.1.0.dist-info/METADATA +53 -0
- studyrag-0.1.0.dist-info/RECORD +35 -0
- studyrag-0.1.0.dist-info/WHEEL +5 -0
- studyrag-0.1.0.dist-info/entry_points.txt +2 -0
- studyrag-0.1.0.dist-info/licenses/LICENSE +21 -0
- studyrag-0.1.0.dist-info/top_level.txt +1 -0
studyrag/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""studyrag: a private, offline study assistant built on retrieval-augmented generation (RAG).
|
|
2
|
+
|
|
3
|
+
Pipeline: load documents -> chunk -> index (BM25 + vectors) -> hybrid retrieval -> rerank
|
|
4
|
+
-> grounded generation with citations -> claim verification.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
studyrag/__main__.py
ADDED
studyrag/answer.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Grounded question answering: retrieve -> (maybe refuse) -> generate with citations -> verify.
|
|
2
|
+
|
|
3
|
+
The flow is split into prepare() / finalize() so the web app can stream the model's tokens
|
|
4
|
+
in between, while scripts and evals simply call ask().
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from .config import Settings
|
|
13
|
+
from .prompts import NOT_FOUND, QA_SYSTEM, qa_user
|
|
14
|
+
from .retrieval import RetrievalResult, Retriever
|
|
15
|
+
from .verify import Verification, extract_citations, verify_answer
|
|
16
|
+
|
|
17
|
+
REFUSAL_TEXT = "I couldn't find this in your documents."
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Prepared:
|
|
22
|
+
question: str
|
|
23
|
+
retrieval: RetrievalResult
|
|
24
|
+
messages: list[dict]
|
|
25
|
+
refused_early: bool # True when retrieval found nothing relevant: skip the LLM entirely
|
|
26
|
+
t_start: float = field(default_factory=time.perf_counter)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Answer:
|
|
31
|
+
question: str
|
|
32
|
+
text: str
|
|
33
|
+
status: str # "answered" | "not_found"
|
|
34
|
+
sources: list # Hits shown to the LLM; source [n] = sources[n-1]
|
|
35
|
+
cited: list[int]
|
|
36
|
+
verification: Verification
|
|
37
|
+
confidence: str # "high" | "medium" | "low" | "none"
|
|
38
|
+
retrieval: RetrievalResult
|
|
39
|
+
seconds: float
|
|
40
|
+
auto_cited: list[int] = field(default_factory=list) # citations added by the verifier, not the model
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class QAEngine:
|
|
44
|
+
def __init__(self, retriever: Retriever, llm, embedder, settings: Settings):
|
|
45
|
+
self.retriever = retriever
|
|
46
|
+
self.llm = llm
|
|
47
|
+
self.embedder = embedder
|
|
48
|
+
self.s = settings
|
|
49
|
+
|
|
50
|
+
def prepare(self, question: str, doc_ids: list[str] | None = None) -> Prepared:
|
|
51
|
+
t0 = time.perf_counter()
|
|
52
|
+
res = self.retriever.retrieve(question, doc_ids=doc_ids)
|
|
53
|
+
refused = not res.hits or res.top_relevance < self.s.refusal_threshold
|
|
54
|
+
msgs = [{"role": "system", "content": QA_SYSTEM},
|
|
55
|
+
{"role": "user", "content": qa_user(question, [h.chunk for h in res.hits])}]
|
|
56
|
+
return Prepared(question, res, msgs, refused, t_start=t0)
|
|
57
|
+
|
|
58
|
+
def finalize(self, prep: Prepared, raw_text: str) -> Answer:
|
|
59
|
+
hits = prep.retrieval.hits
|
|
60
|
+
elapsed = time.perf_counter() - prep.t_start
|
|
61
|
+
text = raw_text.strip()
|
|
62
|
+
if prep.refused_early or not text or text.upper().startswith(NOT_FOUND) or NOT_FOUND in text[:40]:
|
|
63
|
+
return Answer(prep.question, REFUSAL_TEXT, "not_found", hits, [], Verification(), "none",
|
|
64
|
+
prep.retrieval, elapsed)
|
|
65
|
+
ver = verify_answer(text, [h.chunk for h in hits], self.embedder, self.s.support_threshold)
|
|
66
|
+
text, auto = self.add_missing_citations(text, ver)
|
|
67
|
+
cited = sorted({n for n in extract_citations(text) if 1 <= n <= len(hits)})
|
|
68
|
+
return Answer(prep.question, text, "answered", hits, cited, ver,
|
|
69
|
+
self.confidence(prep.retrieval.top_relevance, ver, cited), prep.retrieval, elapsed,
|
|
70
|
+
auto_cited=auto)
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def add_missing_citations(text: str, ver: Verification) -> tuple[str, list[int]]:
|
|
74
|
+
"""Small models often skip [n] markers in bullet lists. If the verifier found that an uncited
|
|
75
|
+
sentence IS supported by a source, append that source's citation (and record that we did)."""
|
|
76
|
+
added = []
|
|
77
|
+
for c in ver.checks:
|
|
78
|
+
if c.cited or not c.supported or not c.best_source or not c.raw:
|
|
79
|
+
continue
|
|
80
|
+
raw = c.raw.rstrip()
|
|
81
|
+
pos = text.find(raw)
|
|
82
|
+
if pos == -1:
|
|
83
|
+
continue
|
|
84
|
+
end = pos + len(raw)
|
|
85
|
+
text = f"{text[:end]} [{c.best_source}]{text[end:]}"
|
|
86
|
+
c.cited, c.auto = [c.best_source], True
|
|
87
|
+
added.append(c.best_source)
|
|
88
|
+
return text, sorted(set(added))
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def confidence(top_relevance: float, ver: Verification, cited: list[int]) -> str:
|
|
92
|
+
"""Combine 'did we find relevant material?' with 'is the answer backed by it?'."""
|
|
93
|
+
r = ver.supported_ratio
|
|
94
|
+
if top_relevance >= 0.5 and r >= 0.8 and cited:
|
|
95
|
+
return "high"
|
|
96
|
+
if top_relevance >= 0.1 and r >= 0.5:
|
|
97
|
+
return "medium"
|
|
98
|
+
return "low"
|
|
99
|
+
|
|
100
|
+
def ask(self, question: str, doc_ids: list[str] | None = None, max_tokens: int = 400) -> Answer:
|
|
101
|
+
prep = self.prepare(question, doc_ids)
|
|
102
|
+
raw = "" if prep.refused_early else self.llm.generate(prep.messages, max_tokens=max_tokens,
|
|
103
|
+
temperature=self.s.temperature)
|
|
104
|
+
return self.finalize(prep, raw)
|
studyrag/bm25.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""BM25 keyword search, implemented from scratch with an inverted index.
|
|
2
|
+
|
|
3
|
+
For a query q and chunk d, BM25 sums over each query term t:
|
|
4
|
+
|
|
5
|
+
idf(t) * tf(t,d) * (k1 + 1) / ( tf(t,d) + k1 * (1 - b + b * |d| / avgdl) )
|
|
6
|
+
|
|
7
|
+
idf(t) = ln( (N - df(t) + 0.5) / (df(t) + 0.5) + 1 )
|
|
8
|
+
|
|
9
|
+
- tf(t,d): how often t appears in d. More is better, but with diminishing returns (k1 controls
|
|
10
|
+
how fast the score saturates).
|
|
11
|
+
- idf(t): rare terms are worth more than common ones ("seo" beats "marketing" in a marketing course).
|
|
12
|
+
- |d| / avgdl: long chunks naturally contain more words, so b normalises by length.
|
|
13
|
+
|
|
14
|
+
The inverted index maps each term to the chunks containing it, so a search only touches
|
|
15
|
+
chunks that share at least one term with the query instead of scanning everything.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import math
|
|
21
|
+
from collections import Counter, defaultdict
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class BM25Index:
|
|
27
|
+
def __init__(self, k1: float = 1.5, b: float = 0.75):
|
|
28
|
+
self.k1 = k1
|
|
29
|
+
self.b = b
|
|
30
|
+
self.postings: dict[str, list[tuple[int, int]]] = {} # term -> [(chunk_idx, term_freq)]
|
|
31
|
+
self.idf: dict[str, float] = {}
|
|
32
|
+
self.doc_len = np.zeros(0, dtype=np.float32)
|
|
33
|
+
self.avgdl = 0.0
|
|
34
|
+
self.n_docs = 0
|
|
35
|
+
|
|
36
|
+
def build(self, corpus_tokens: list[list[str]]) -> "BM25Index":
|
|
37
|
+
postings: dict[str, list[tuple[int, int]]] = defaultdict(list)
|
|
38
|
+
for idx, tokens in enumerate(corpus_tokens):
|
|
39
|
+
for term, tf in Counter(tokens).items():
|
|
40
|
+
postings[term].append((idx, tf))
|
|
41
|
+
self.postings = dict(postings)
|
|
42
|
+
self.n_docs = len(corpus_tokens)
|
|
43
|
+
self.doc_len = np.array([len(t) for t in corpus_tokens], dtype=np.float32)
|
|
44
|
+
self.avgdl = float(self.doc_len.mean()) if self.n_docs else 0.0
|
|
45
|
+
n = self.n_docs
|
|
46
|
+
self.idf = {t: math.log((n - len(p) + 0.5) / (len(p) + 0.5) + 1.0) for t, p in self.postings.items()}
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
def scores(self, query_tokens: list[str]) -> np.ndarray:
|
|
50
|
+
"""BM25 score of every chunk for this query (0 for chunks sharing no terms)."""
|
|
51
|
+
scores = np.zeros(self.n_docs, dtype=np.float32)
|
|
52
|
+
if not self.n_docs:
|
|
53
|
+
return scores
|
|
54
|
+
norm = self.k1 * (1 - self.b + self.b * self.doc_len / max(self.avgdl, 1e-9))
|
|
55
|
+
for term in query_tokens: # repeated query terms count again, as in classic BM25
|
|
56
|
+
plist = self.postings.get(term)
|
|
57
|
+
if not plist:
|
|
58
|
+
continue
|
|
59
|
+
idx = np.fromiter((p[0] for p in plist), dtype=np.int64, count=len(plist))
|
|
60
|
+
tf = np.fromiter((p[1] for p in plist), dtype=np.float32, count=len(plist))
|
|
61
|
+
scores[idx] += self.idf[term] * tf * (self.k1 + 1) / (tf + norm[idx])
|
|
62
|
+
return scores
|
|
63
|
+
|
|
64
|
+
def search(self, query_tokens: list[str], top_k: int = 10,
|
|
65
|
+
allowed: np.ndarray | None = None) -> list[tuple[int, float]]:
|
|
66
|
+
"""Top-k (chunk_idx, score) pairs. `allowed` is an optional boolean mask (document filter)."""
|
|
67
|
+
s = self.scores(query_tokens)
|
|
68
|
+
if allowed is not None:
|
|
69
|
+
s = np.where(allowed, s, 0.0)
|
|
70
|
+
return top_k_positive(s, top_k)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def top_k_positive(scores: np.ndarray, k: int) -> list[tuple[int, float]]:
|
|
74
|
+
"""Indices of the k highest strictly-positive scores, best first (O(n) selection, then sort k)."""
|
|
75
|
+
k = min(k, int((scores > 0).sum()))
|
|
76
|
+
if k <= 0:
|
|
77
|
+
return []
|
|
78
|
+
idx = np.argpartition(-scores, k - 1)[:k]
|
|
79
|
+
idx = idx[np.argsort(-scores[idx], kind="stable")]
|
|
80
|
+
return [(int(i), float(scores[i])) for i in idx]
|
studyrag/chunking.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Chunking: split Documents into retrieval units ("chunks").
|
|
2
|
+
|
|
3
|
+
Why chunk at all? An embedding of a whole 40-slide lecture is a blurry average of everything in it;
|
|
4
|
+
an embedding of one slide is specific. But chunks that are too small lose context ("it increases
|
|
5
|
+
conversion" — what does?). Chunking is the trade-off between precision and context.
|
|
6
|
+
|
|
7
|
+
Three strategies, compared with measurements in docs/DECISIONS.md:
|
|
8
|
+
|
|
9
|
+
1. fixed — sliding window of N words with overlap. Ignores structure. The classic baseline.
|
|
10
|
+
2. structure — respects the document's own units (slide / page / section). Oversized units are
|
|
11
|
+
split recursively (paragraphs -> lines -> sentences -> words); tiny neighbouring
|
|
12
|
+
units (e.g. a title-only slide) are merged so no chunk is too thin to be useful.
|
|
13
|
+
3. semantic — splits where the *meaning* shifts: embeds each sentence and cuts where adjacent
|
|
14
|
+
sentences are least similar.
|
|
15
|
+
|
|
16
|
+
Every chunk carries a contextual header (document title + location + heading) that is prepended
|
|
17
|
+
when embedding/indexing, so a chunk like "- 3 key benefits..." is still findable by its topic.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
from dataclasses import dataclass, asdict
|
|
24
|
+
from typing import Callable
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
from .ingest.models import Block, Document, location_label
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Chunk:
|
|
33
|
+
chunk_id: str
|
|
34
|
+
doc_id: str
|
|
35
|
+
doc_title: str
|
|
36
|
+
text: str
|
|
37
|
+
kind: str # slide | page | section
|
|
38
|
+
loc_start: int
|
|
39
|
+
loc_end: int
|
|
40
|
+
heading: str = ""
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def location(self) -> str:
|
|
44
|
+
return location_label(self.kind, self.loc_start, self.loc_end, self.heading)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def header(self) -> str:
|
|
48
|
+
return f"{self.doc_title} — {self.location}"
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def index_text(self) -> str:
|
|
52
|
+
"""What BM25 and the embedding model see: contextual header + chunk text."""
|
|
53
|
+
return f"{self.header}\n{self.text}"
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def word_count(self) -> int:
|
|
57
|
+
return len(self.text.split())
|
|
58
|
+
|
|
59
|
+
def to_dict(self) -> dict:
|
|
60
|
+
return asdict(self)
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_dict(cls, d: dict) -> "Chunk":
|
|
64
|
+
return cls(**d)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ------------------------------------------------------------------ helpers
|
|
68
|
+
_SENT_SPLIT = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9\"'(\-])|\n+")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def split_sentences(text: str) -> list[str]:
|
|
72
|
+
"""Sentence-ish units. On slides, each bullet line counts as a sentence."""
|
|
73
|
+
return [s.strip() for s in _SENT_SPLIT.split(text) if s and s.strip()]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _words(text: str) -> int:
|
|
77
|
+
return len(text.split())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _recursive_split(text: str, max_words: int) -> list[str]:
|
|
81
|
+
"""Split text into pieces <= max_words, preferring the largest natural boundary available."""
|
|
82
|
+
if _words(text) <= max_words:
|
|
83
|
+
return [text]
|
|
84
|
+
for sep in ("\n\n", "\n", "SENT", " "):
|
|
85
|
+
parts = split_sentences(text) if sep == "SENT" else text.split(sep)
|
|
86
|
+
parts = [p for p in parts if p.strip()]
|
|
87
|
+
if len(parts) <= 1:
|
|
88
|
+
continue
|
|
89
|
+
joiner = " " if sep in ("SENT", " ") else sep
|
|
90
|
+
pieces, current = [], ""
|
|
91
|
+
for part in parts:
|
|
92
|
+
candidate = f"{current}{joiner}{part}" if current else part
|
|
93
|
+
if _words(candidate) <= max_words:
|
|
94
|
+
current = candidate
|
|
95
|
+
else:
|
|
96
|
+
if current:
|
|
97
|
+
pieces.append(current)
|
|
98
|
+
current = part
|
|
99
|
+
if current:
|
|
100
|
+
pieces.append(current)
|
|
101
|
+
out = []
|
|
102
|
+
for p in pieces: # a single part may still be too long: recurse deeper
|
|
103
|
+
out.extend(_recursive_split(p, max_words) if _words(p) > max_words else [p])
|
|
104
|
+
return out
|
|
105
|
+
words = text.split()
|
|
106
|
+
return [" ".join(words[i:i + max_words]) for i in range(0, len(words), max_words)]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _make(doc: Document, n: int, text: str, kind: str, start: int, end: int, heading: str) -> Chunk:
|
|
110
|
+
return Chunk(chunk_id=f"{doc.doc_id}:{n}", doc_id=doc.doc_id, doc_title=doc.title,
|
|
111
|
+
text=text.strip(), kind=kind, loc_start=start, loc_end=end, heading=heading)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ------------------------------------------------------------------ 1. fixed
|
|
115
|
+
def chunk_fixed(doc: Document, size: int = 180, overlap: int = 30) -> list[Chunk]:
|
|
116
|
+
words: list[tuple[str, int]] = [(w, b.location) for b in doc.blocks for w in b.text.split()]
|
|
117
|
+
if not words:
|
|
118
|
+
return []
|
|
119
|
+
kind = doc.blocks[0].kind
|
|
120
|
+
step = max(1, size - overlap)
|
|
121
|
+
chunks = []
|
|
122
|
+
for n, i in enumerate(range(0, len(words), step)):
|
|
123
|
+
window = words[i:i + size]
|
|
124
|
+
chunks.append(_make(doc, n, " ".join(w for w, _ in window), kind,
|
|
125
|
+
window[0][1], window[-1][1], ""))
|
|
126
|
+
if i + size >= len(words):
|
|
127
|
+
break
|
|
128
|
+
return chunks
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ------------------------------------------------------------------ 2. structure-aware
|
|
132
|
+
def chunk_structure(doc: Document, max_words: int = 180, min_words: int = 50) -> list[Chunk]:
|
|
133
|
+
# a) split oversized blocks recursively
|
|
134
|
+
units: list[tuple[str, Block]] = []
|
|
135
|
+
for b in doc.blocks:
|
|
136
|
+
pieces = _recursive_split(b.text, max_words)
|
|
137
|
+
for j, piece in enumerate(pieces):
|
|
138
|
+
# continuation pieces of a long section repeat its heading so they stay findable
|
|
139
|
+
if j > 0 and b.heading and not piece.startswith(b.heading):
|
|
140
|
+
piece = f"{b.heading} (cont.)\n{piece}"
|
|
141
|
+
units.append((piece, b))
|
|
142
|
+
# b) merge thin neighbours (e.g. a title-only slide + the next slide)
|
|
143
|
+
chunks: list[Chunk] = []
|
|
144
|
+
buf_text, buf_blocks = "", []
|
|
145
|
+
for text, b in units:
|
|
146
|
+
if buf_blocks and (_words(buf_text) >= min_words or _words(buf_text) + _words(text) > max_words):
|
|
147
|
+
chunks.append(_flush(doc, len(chunks), buf_text, buf_blocks))
|
|
148
|
+
buf_text, buf_blocks = "", []
|
|
149
|
+
buf_text = f"{buf_text}\n\n{text}" if buf_text else text
|
|
150
|
+
buf_blocks.append(b)
|
|
151
|
+
if buf_blocks:
|
|
152
|
+
if chunks and _words(buf_text) < min_words // 2 and \
|
|
153
|
+
_words(chunks[-1].text) + _words(buf_text) <= max_words:
|
|
154
|
+
last = chunks.pop() # fold a tiny tail into the previous chunk
|
|
155
|
+
chunks.append(_make(doc, len(chunks), f"{last.text}\n\n{buf_text}", last.kind,
|
|
156
|
+
last.loc_start, buf_blocks[-1].location, last.heading))
|
|
157
|
+
else:
|
|
158
|
+
chunks.append(_flush(doc, len(chunks), buf_text, buf_blocks))
|
|
159
|
+
return chunks
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _flush(doc: Document, n: int, text: str, blocks: list[Block]) -> Chunk:
|
|
163
|
+
heading = next((b.heading for b in blocks if b.heading), "")
|
|
164
|
+
return _make(doc, n, text, blocks[0].kind, blocks[0].location, blocks[-1].location, heading)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# ------------------------------------------------------------------ 3. semantic
|
|
168
|
+
def chunk_semantic(doc: Document, embed: Callable[[list[str]], np.ndarray],
|
|
169
|
+
max_words: int = 180, min_words: int = 40, percentile: float = 25.0) -> list[Chunk]:
|
|
170
|
+
sents: list[tuple[str, Block]] = [(s, b) for b in doc.blocks for s in split_sentences(b.text)]
|
|
171
|
+
if not sents:
|
|
172
|
+
return []
|
|
173
|
+
vecs = np.asarray(embed([s for s, _ in sents]), dtype=np.float32)
|
|
174
|
+
vecs /= np.maximum(np.linalg.norm(vecs, axis=1, keepdims=True), 1e-12)
|
|
175
|
+
sims = (vecs[:-1] * vecs[1:]).sum(axis=1) if len(sents) > 1 else np.array([])
|
|
176
|
+
cut_below = float(np.percentile(sims, percentile)) if len(sims) else 0.0
|
|
177
|
+
|
|
178
|
+
chunks: list[Chunk] = []
|
|
179
|
+
cur: list[tuple[str, Block]] = [sents[0]]
|
|
180
|
+
for i in range(1, len(sents)):
|
|
181
|
+
cur_words = sum(_words(s) for s, _ in cur)
|
|
182
|
+
topic_shift = sims[i - 1] < cut_below and cur_words >= min_words
|
|
183
|
+
if topic_shift or cur_words + _words(sents[i][0]) > max_words:
|
|
184
|
+
chunks.append(_flush(doc, len(chunks), "\n".join(s for s, _ in cur), [b for _, b in cur]))
|
|
185
|
+
cur = []
|
|
186
|
+
cur.append(sents[i])
|
|
187
|
+
chunks.append(_flush(doc, len(chunks), "\n".join(s for s, _ in cur), [b for _, b in cur]))
|
|
188
|
+
return chunks
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def chunk_document(doc: Document, strategy: str = "structure", *, size: int = 180, overlap: int = 30,
|
|
192
|
+
min_words: int = 50, embed: Callable | None = None) -> list[Chunk]:
|
|
193
|
+
if strategy == "fixed":
|
|
194
|
+
return chunk_fixed(doc, size, overlap)
|
|
195
|
+
if strategy == "structure":
|
|
196
|
+
return chunk_structure(doc, size, min_words)
|
|
197
|
+
if strategy == "semantic":
|
|
198
|
+
if embed is None:
|
|
199
|
+
raise ValueError("semantic chunking needs an embed function")
|
|
200
|
+
return chunk_semantic(doc, embed, size)
|
|
201
|
+
raise ValueError(f"unknown chunk strategy: {strategy}")
|
studyrag/cli.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Command-line interface.
|
|
2
|
+
|
|
3
|
+
python -m studyrag sync data/my_docs index a folder (new/changed/removed files)
|
|
4
|
+
python -m studyrag list show indexed documents
|
|
5
|
+
python -m studyrag search "what is seo" retrieval only, with the full ranking trace
|
|
6
|
+
python -m studyrag ask "what is seo" grounded answer with citations
|
|
7
|
+
python -m studyrag mcq -n 5 --doc "Lec 2" generate MCQs
|
|
8
|
+
python -m studyrag flashcards -n 5 --topic "email marketing"
|
|
9
|
+
python -m studyrag summary --doc "Lec 1"
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
|
|
18
|
+
from .core import StudyRAG
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _doc_ids(rag: StudyRAG, names: list[str] | None) -> list[str] | None:
|
|
22
|
+
if not names:
|
|
23
|
+
return None
|
|
24
|
+
ids = []
|
|
25
|
+
for n in names:
|
|
26
|
+
d = rag.library.find_doc(n)
|
|
27
|
+
if d is None:
|
|
28
|
+
sys.exit(f"No indexed document matches '{n}'. Try: python -m studyrag list")
|
|
29
|
+
ids.append(d.doc_id)
|
|
30
|
+
return ids
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def cmd_sync(rag, a):
|
|
34
|
+
t = time.perf_counter()
|
|
35
|
+
report = rag.library.sync_folder(a.folder)
|
|
36
|
+
for k, v in report.items():
|
|
37
|
+
if v:
|
|
38
|
+
print(f"{k:>9}: {', '.join(v)}")
|
|
39
|
+
print(f"Library: {len(rag.library.docs)} documents, {len(rag.library.chunks)} chunks "
|
|
40
|
+
f"({time.perf_counter() - t:.1f}s)")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cmd_list(rag, a):
|
|
44
|
+
if not rag.library.docs:
|
|
45
|
+
print("Library is empty. Run: python -m studyrag sync data/my_docs")
|
|
46
|
+
for d in rag.library.docs.values():
|
|
47
|
+
print(f"{d.doc_id} {d.doc_type:<5} {d.n_chunks:>4} chunks {d.n_words:>6} words {d.title}")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cmd_search(rag, a):
|
|
51
|
+
res = rag.retriever.retrieve(a.query, top_k=a.k, doc_ids=_doc_ids(rag, a.doc), mode=a.mode)
|
|
52
|
+
print(f"timings (ms): { {k: round(v, 1) for k, v in res.timings_ms.items()} }\n")
|
|
53
|
+
for i, h in enumerate(res.hits, 1):
|
|
54
|
+
rr = f"{h.rerank_score:.3f}" if h.rerank_score is not None else "-"
|
|
55
|
+
print(f"#{i} rerank={rr} rrf={h.rrf_score:.4f} bm25_rank={h.bm25_rank} vector_rank={h.vector_rank}")
|
|
56
|
+
print(f" {h.chunk.header}")
|
|
57
|
+
print(" " + h.chunk.text[:220].replace("\n", " ") + ("..." if len(h.chunk.text) > 220 else "") + "\n")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cmd_ask(rag, a):
|
|
61
|
+
qa = rag.qa
|
|
62
|
+
prep = qa.prepare(a.question, _doc_ids(rag, a.doc))
|
|
63
|
+
raw = ""
|
|
64
|
+
if not prep.refused_early:
|
|
65
|
+
for piece in rag.llm.generate(prep.messages, max_tokens=400, temperature=rag.settings.temperature,
|
|
66
|
+
stream=True):
|
|
67
|
+
raw += piece
|
|
68
|
+
print(piece, end="", flush=True)
|
|
69
|
+
print()
|
|
70
|
+
ans = qa.finalize(prep, raw)
|
|
71
|
+
if ans.status == "not_found":
|
|
72
|
+
print(ans.text)
|
|
73
|
+
if ans.sources:
|
|
74
|
+
print("closest passages (not relevant enough to answer from):")
|
|
75
|
+
for h in ans.sources[:2]:
|
|
76
|
+
print(f" - {h.chunk.header}")
|
|
77
|
+
return
|
|
78
|
+
print(f"\nconfidence: {ans.confidence} ({ans.seconds:.1f}s)")
|
|
79
|
+
for n, h in enumerate(ans.sources, 1):
|
|
80
|
+
mark = "*" if n in ans.cited else " "
|
|
81
|
+
print(f" {mark}[{n}] {h.chunk.header}")
|
|
82
|
+
for c in ans.verification.unsupported:
|
|
83
|
+
print(f" ! weakly supported: \"{c.sentence[:90]}\" (support {c.support:.2f})")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def cmd_mcq(rag, a):
|
|
87
|
+
from .study.generate import generate_mcqs, select_passages
|
|
88
|
+
passages = select_passages(rag.library, rag.retriever, a.n, _doc_ids(rag, a.doc), a.topic)
|
|
89
|
+
for i, q in enumerate(generate_mcqs(rag.llm, passages, a.difficulty, rag.embedder), 1):
|
|
90
|
+
print(f"\nQ{i}. {q.question}")
|
|
91
|
+
for j, opt in enumerate(q.options):
|
|
92
|
+
print(f" {'ABCD'[j]}) {opt}")
|
|
93
|
+
print(f" Answer: {q.answer_letter} — {q.explanation}")
|
|
94
|
+
print(f" Source: {q.source.header}" + (f" ⚠ {'; '.join(q.issues)}" if q.issues else ""))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_flashcards(rag, a):
|
|
98
|
+
from .study.generate import generate_flashcards, select_passages
|
|
99
|
+
passages = select_passages(rag.library, rag.retriever, a.n, _doc_ids(rag, a.doc), a.topic)
|
|
100
|
+
for c in generate_flashcards(rag.llm, passages, rag.embedder):
|
|
101
|
+
print(f"\n[{c.front}]\n {c.back}\n ({c.source.header})")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def cmd_summary(rag, a):
|
|
105
|
+
from .study.summarize import outline, summarize_document, summarize_topic
|
|
106
|
+
if a.topic:
|
|
107
|
+
stream, chunks = summarize_topic(rag.llm, rag.retriever, a.topic, _doc_ids(rag, a.doc))
|
|
108
|
+
for piece in stream:
|
|
109
|
+
print(piece, end="", flush=True)
|
|
110
|
+
print("\n\nSources:\n" + "\n".join(f"[{i}] {c.header}" for i, c in enumerate(chunks, 1)))
|
|
111
|
+
return
|
|
112
|
+
if not a.doc:
|
|
113
|
+
sys.exit("Give --doc NAME (whole-document summary) or --topic TEXT")
|
|
114
|
+
doc = rag.library.find_doc(a.doc[0])
|
|
115
|
+
chunks = rag.library.chunks_of(doc.doc_id)
|
|
116
|
+
print("Outline:\n " + "\n ".join(outline(chunks)) + "\n\nSummary:\n")
|
|
117
|
+
for piece in summarize_document(rag.llm, doc.title, chunks,
|
|
118
|
+
on_progress=lambda i, n: print(f"(reading part {i}/{n}...)")):
|
|
119
|
+
print(piece, end="", flush=True)
|
|
120
|
+
print()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def main(argv: list[str] | None = None) -> None:
|
|
124
|
+
p = argparse.ArgumentParser(prog="studyrag", description="Private study assistant over your own documents.")
|
|
125
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
126
|
+
|
|
127
|
+
s = sub.add_parser("sync", help="index a folder"); s.add_argument("folder"); s.set_defaults(fn=cmd_sync)
|
|
128
|
+
s = sub.add_parser("list", help="list indexed documents"); s.set_defaults(fn=cmd_list)
|
|
129
|
+
|
|
130
|
+
s = sub.add_parser("search", help="retrieval only (debug view)")
|
|
131
|
+
s.add_argument("query"); s.add_argument("-k", type=int, default=5)
|
|
132
|
+
s.add_argument("--mode", choices=["hybrid", "bm25", "vector"], default="hybrid")
|
|
133
|
+
s.add_argument("--doc", action="append"); s.set_defaults(fn=cmd_search)
|
|
134
|
+
|
|
135
|
+
s = sub.add_parser("ask", help="ask a question"); s.add_argument("question")
|
|
136
|
+
s.add_argument("--doc", action="append"); s.set_defaults(fn=cmd_ask)
|
|
137
|
+
|
|
138
|
+
for name, fn in (("mcq", cmd_mcq), ("flashcards", cmd_flashcards)):
|
|
139
|
+
s = sub.add_parser(name); s.add_argument("-n", type=int, default=5)
|
|
140
|
+
s.add_argument("--doc", action="append"); s.add_argument("--topic")
|
|
141
|
+
s.add_argument("--difficulty", default="medium", choices=["easy", "medium", "hard"])
|
|
142
|
+
s.set_defaults(fn=fn)
|
|
143
|
+
|
|
144
|
+
s = sub.add_parser("summary"); s.add_argument("--doc", action="append"); s.add_argument("--topic")
|
|
145
|
+
s.set_defaults(fn=cmd_summary)
|
|
146
|
+
|
|
147
|
+
a = p.parse_args(argv)
|
|
148
|
+
a.fn(StudyRAG(), a)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
if __name__ == "__main__":
|
|
152
|
+
main()
|
studyrag/config.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Central configuration.
|
|
2
|
+
|
|
3
|
+
Every tunable value lives here so experiments (and docs/DECISIONS.md) can point at one place.
|
|
4
|
+
Any field can be overridden with an environment variable named STUDYRAG_<FIELD_NAME>,
|
|
5
|
+
e.g. STUDYRAG_LLM_BACKEND=openai or STUDYRAG_TOP_K=8.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
from dataclasses import dataclass, fields
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
SOURCE_ROOT = Path(__file__).resolve().parents[2]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def default_home() -> Path:
|
|
18
|
+
"""Where the index, models and OCR cache live.
|
|
19
|
+
|
|
20
|
+
- STUDYRAG_HOME, if set;
|
|
21
|
+
- a source checkout (git clone, `pip install -e .`): the project folder itself, as before;
|
|
22
|
+
- an installed package (`pip install studyrag`): ~/.studyrag, never inside Python's site-packages.
|
|
23
|
+
"""
|
|
24
|
+
env = os.environ.get("STUDYRAG_HOME")
|
|
25
|
+
if env:
|
|
26
|
+
return Path(env).expanduser()
|
|
27
|
+
if (SOURCE_ROOT / "pyproject.toml").exists() and (SOURCE_ROOT / "src" / "studyrag").is_dir():
|
|
28
|
+
return SOURCE_ROOT
|
|
29
|
+
return Path.home() / ".studyrag"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
PROJECT_ROOT = default_home()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Settings:
|
|
37
|
+
# --- where things live ---
|
|
38
|
+
storage_dir: Path = PROJECT_ROOT / "storage" # built index (gitignored)
|
|
39
|
+
models_dir: Path = PROJECT_ROOT / "models" # downloaded models (gitignored)
|
|
40
|
+
|
|
41
|
+
# --- ingestion ---
|
|
42
|
+
ocr: bool = True # read text from image-only slides / scanned pages
|
|
43
|
+
ocr_cache_file: Path = PROJECT_ROOT / "storage" / "ocr_cache.json" # shared by every index
|
|
44
|
+
|
|
45
|
+
# --- chunking ---
|
|
46
|
+
chunk_strategy: str = "structure" # "fixed" | "structure" | "semantic"
|
|
47
|
+
chunk_size: int = 180 # target max words per chunk
|
|
48
|
+
chunk_overlap: int = 30 # words of overlap (fixed strategy)
|
|
49
|
+
min_chunk_words: int = 50 # structure strategy merges smaller neighbours
|
|
50
|
+
|
|
51
|
+
# --- retrieval ---
|
|
52
|
+
embedding_model: str = "BAAI/bge-small-en-v1.5"
|
|
53
|
+
reranker_model: str = "Xenova/ms-marco-MiniLM-L-6-v2"
|
|
54
|
+
candidates: int = 10 # results taken from each retriever before fusion (measured: D13)
|
|
55
|
+
rrf_k: int = 60 # Reciprocal Rank Fusion constant
|
|
56
|
+
top_k: int = 4 # chunks given to the LLM
|
|
57
|
+
use_reranker: bool = True
|
|
58
|
+
refusal_threshold: float = 0.2 # min reranker probability to attempt an answer (calibrated: D14)
|
|
59
|
+
|
|
60
|
+
# --- generation ---
|
|
61
|
+
llm_backend: str = "llamacpp" # "llamacpp" (local, offline) | "openai" (any OpenAI-compatible API)
|
|
62
|
+
llm_model_file: str = "Qwen3.5-2B-Q4_K_M.gguf"
|
|
63
|
+
llm_context: int = 4096
|
|
64
|
+
llm_threads: int = 0 # 0 = auto
|
|
65
|
+
api_base_url: str = "https://api.openai.com/v1"
|
|
66
|
+
api_model: str = "gpt-4o-mini"
|
|
67
|
+
api_key: str = ""
|
|
68
|
+
temperature: float = 0.2
|
|
69
|
+
|
|
70
|
+
# --- verification ---
|
|
71
|
+
support_threshold: float = 0.55 # min support score for a sentence to count as grounded
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def from_env(cls) -> "Settings":
|
|
75
|
+
s = cls()
|
|
76
|
+
for f in fields(cls):
|
|
77
|
+
raw = os.environ.get(f"STUDYRAG_{f.name.upper()}")
|
|
78
|
+
if raw is None:
|
|
79
|
+
continue
|
|
80
|
+
current = getattr(s, f.name)
|
|
81
|
+
if isinstance(current, bool):
|
|
82
|
+
value = raw.strip().lower() in {"1", "true", "yes", "on"}
|
|
83
|
+
elif isinstance(current, int):
|
|
84
|
+
value = int(raw)
|
|
85
|
+
elif isinstance(current, float):
|
|
86
|
+
value = float(raw)
|
|
87
|
+
elif isinstance(current, Path):
|
|
88
|
+
value = Path(raw)
|
|
89
|
+
else:
|
|
90
|
+
value = raw
|
|
91
|
+
setattr(s, f.name, value)
|
|
92
|
+
if not s.api_key:
|
|
93
|
+
s.api_key = os.environ.get("OPENAI_API_KEY", "")
|
|
94
|
+
return s
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def llm_model_path(self) -> Path:
|
|
98
|
+
return self.models_dir / "llm" / self.llm_model_file
|