studyrag 0.1.0__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.
- studyrag-0.1.0/LICENSE +21 -0
- studyrag-0.1.0/PKG-INFO +53 -0
- studyrag-0.1.0/PYPI.md +23 -0
- studyrag-0.1.0/README.md +155 -0
- studyrag-0.1.0/pyproject.toml +48 -0
- studyrag-0.1.0/setup.cfg +4 -0
- studyrag-0.1.0/src/studyrag/__init__.py +7 -0
- studyrag-0.1.0/src/studyrag/__main__.py +3 -0
- studyrag-0.1.0/src/studyrag/answer.py +104 -0
- studyrag-0.1.0/src/studyrag/bm25.py +80 -0
- studyrag-0.1.0/src/studyrag/chunking.py +201 -0
- studyrag-0.1.0/src/studyrag/cli.py +152 -0
- studyrag-0.1.0/src/studyrag/config.py +98 -0
- studyrag-0.1.0/src/studyrag/core.py +57 -0
- studyrag-0.1.0/src/studyrag/embeddings.py +57 -0
- studyrag-0.1.0/src/studyrag/hybrid.py +22 -0
- studyrag-0.1.0/src/studyrag/ingest/__init__.py +6 -0
- studyrag-0.1.0/src/studyrag/ingest/cleaning.py +80 -0
- studyrag-0.1.0/src/studyrag/ingest/loaders.py +266 -0
- studyrag-0.1.0/src/studyrag/ingest/models.py +46 -0
- studyrag-0.1.0/src/studyrag/ingest/ocr.py +154 -0
- studyrag-0.1.0/src/studyrag/library.py +180 -0
- studyrag-0.1.0/src/studyrag/llm/__init__.py +19 -0
- studyrag-0.1.0/src/studyrag/llm/base.py +50 -0
- studyrag-0.1.0/src/studyrag/llm/llamacpp.py +94 -0
- studyrag-0.1.0/src/studyrag/llm/openai_compat.py +142 -0
- studyrag-0.1.0/src/studyrag/prompts.py +165 -0
- studyrag-0.1.0/src/studyrag/retrieval.py +86 -0
- studyrag-0.1.0/src/studyrag/study/__init__.py +1 -0
- studyrag-0.1.0/src/studyrag/study/generate.py +257 -0
- studyrag-0.1.0/src/studyrag/study/quiz.py +63 -0
- studyrag-0.1.0/src/studyrag/study/summarize.py +69 -0
- studyrag-0.1.0/src/studyrag/text.py +67 -0
- studyrag-0.1.0/src/studyrag/vector_index.py +55 -0
- studyrag-0.1.0/src/studyrag/verify.py +106 -0
- studyrag-0.1.0/src/studyrag.egg-info/PKG-INFO +53 -0
- studyrag-0.1.0/src/studyrag.egg-info/SOURCES.txt +44 -0
- studyrag-0.1.0/src/studyrag.egg-info/dependency_links.txt +1 -0
- studyrag-0.1.0/src/studyrag.egg-info/entry_points.txt +2 -0
- studyrag-0.1.0/src/studyrag.egg-info/requires.txt +13 -0
- studyrag-0.1.0/src/studyrag.egg-info/top_level.txt +1 -0
- studyrag-0.1.0/tests/test_api_backend.py +52 -0
- studyrag-0.1.0/tests/test_config_home.py +23 -0
- studyrag-0.1.0/tests/test_ingest_chunking.py +109 -0
- studyrag-0.1.0/tests/test_pipeline.py +169 -0
- studyrag-0.1.0/tests/test_retrieval_core.py +62 -0
studyrag-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Abubakar Idrees
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
studyrag-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: studyrag
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A private, offline study assistant: grounded Q&A with citations over your own slides, PDFs and notes (OCR included).
|
|
5
|
+
Author: Abubakar Idrees
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/01-rag-from-scratch
|
|
8
|
+
Project-URL: Source, https://github.com/Abubakar-idrees-01/data-to-impact
|
|
9
|
+
Project-URL: Documentation, https://github.com/Abubakar-idrees-01/data-to-impact/blob/main/01-rag-from-scratch/docs/SETUP.md
|
|
10
|
+
Keywords: rag,retrieval,bm25,study,ocr,citations,llm
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Intended Audience :: Education
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Classifier: Topic :: Text Processing :: Indexing
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: fastembed>=0.9
|
|
19
|
+
Requires-Dist: rapidocr>=3.10
|
|
20
|
+
Requires-Dist: python-pptx>=1.0
|
|
21
|
+
Requires-Dist: python-docx>=1.2
|
|
22
|
+
Requires-Dist: pypdf>=7.1
|
|
23
|
+
Requires-Dist: httpx>=0.28
|
|
24
|
+
Requires-Dist: numpy<3,>=1.26
|
|
25
|
+
Provides-Extra: local-llm
|
|
26
|
+
Requires-Dist: llama-cpp-python>=0.3.37; extra == "local-llm"
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: pytest; extra == "dev"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# StudyRAG
|
|
32
|
+
|
|
33
|
+
A private study assistant that answers **only from your own course material** (slides, PDFs, Word files, notes,
|
|
34
|
+
even image-only slides through OCR), with a citation to the exact slide or page, and says "not in your documents"
|
|
35
|
+
when the answer isn't there. Everything runs on a CPU; no GPU needed.
|
|
36
|
+
|
|
37
|
+

|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install studyrag # search, citations, OCR, CLI (models download on first use)
|
|
41
|
+
pip install "studyrag[local-llm]" # + local LLM answers via llama.cpp (compiles; see the setup guide)
|
|
42
|
+
|
|
43
|
+
studyrag sync ~/my-lecture-notes # index a folder (data lives in ~/.studyrag; STUDYRAG_HOME to change)
|
|
44
|
+
studyrag search "porter five forces" # ranked, cited passages
|
|
45
|
+
studyrag ask "What is a market space?" # needs a local model or an OpenAI-compatible API (STUDYRAG_LLM_BACKEND=openai)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Built from scratch: BM25, vector search, Reciprocal Rank Fusion, cross-encoder reranking, a calibrated refusal
|
|
49
|
+
threshold and a sentence-level answer verifier. Measured on 77 labelled questions: the right passage in the top 3
|
|
50
|
+
for 100% of answerable questions, 14/14 unanswerable questions refused.
|
|
51
|
+
|
|
52
|
+
- Use it from Claude Code, Claude Desktop or Cursor with the MCP server: [`studyrag-mcp`](https://pypi.org/project/studyrag-mcp/)
|
|
53
|
+
- Source, Streamlit web app, results and docs: [https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/01-rag-from-scratch](https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/01-rag-from-scratch)
|
studyrag-0.1.0/PYPI.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# StudyRAG
|
|
2
|
+
|
|
3
|
+
A private study assistant that answers **only from your own course material** (slides, PDFs, Word files, notes,
|
|
4
|
+
even image-only slides through OCR), with a citation to the exact slide or page, and says "not in your documents"
|
|
5
|
+
when the answer isn't there. Everything runs on a CPU; no GPU needed.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install studyrag # search, citations, OCR, CLI (models download on first use)
|
|
11
|
+
pip install "studyrag[local-llm]" # + local LLM answers via llama.cpp (compiles; see the setup guide)
|
|
12
|
+
|
|
13
|
+
studyrag sync ~/my-lecture-notes # index a folder (data lives in ~/.studyrag; STUDYRAG_HOME to change)
|
|
14
|
+
studyrag search "porter five forces" # ranked, cited passages
|
|
15
|
+
studyrag ask "What is a market space?" # needs a local model or an OpenAI-compatible API (STUDYRAG_LLM_BACKEND=openai)
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Built from scratch: BM25, vector search, Reciprocal Rank Fusion, cross-encoder reranking, a calibrated refusal
|
|
19
|
+
threshold and a sentence-level answer verifier. Measured on 77 labelled questions: the right passage in the top 3
|
|
20
|
+
for 100% of answerable questions, 14/14 unanswerable questions refused.
|
|
21
|
+
|
|
22
|
+
- Use it from Claude Code, Claude Desktop or Cursor with the MCP server: [`studyrag-mcp`](https://pypi.org/project/studyrag-mcp/)
|
|
23
|
+
- Source, Streamlit web app, results and docs: [https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/01-rag-from-scratch](https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/01-rag-from-scratch)
|
studyrag-0.1.0/README.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# 📚 StudyRAG: a private study assistant that only answers from *your* material
|
|
2
|
+
|
|
3
|
+
Upload your lecture slides, PDFs and notes. Ask questions, get **summaries**, and practise with
|
|
4
|
+
**MCQs, short-answer questions and flashcards**. Every answer cites the exact slide or page it came from,
|
|
5
|
+
and when the answer isn't in your material it says so instead of making something up.
|
|
6
|
+
|
|
7
|
+
Runs **fully offline on a 2015 laptop CPU** (no GPU, no API key), with an optional API backend for speed.
|
|
8
|
+
|
|
9
|
+
**Measured on a 2015 i5 laptop** (77 labelled questions, details in [docs/RESULTS.md](docs/RESULTS.md)):
|
|
10
|
+
the right passage is in the top 3 for **100%** of answerable questions; **14/14** unanswerable questions are refused;
|
|
11
|
+
**94%** of key facts are found on real OCR'd lecture slides; **98%** of the model's citations point to a passage
|
|
12
|
+
that supports the sentence; ~35 s per answer, fully offline.
|
|
13
|
+
|
|
14
|
+
## Screenshots
|
|
15
|
+
| Grounded answer with citations, verification and the retrieval trace | Honest refusal, with the closest passages offered |
|
|
16
|
+
|---|---|
|
|
17
|
+
|  |  |
|
|
18
|
+
| The verifier flags a sentence that overstates its source ("a key channel"; the source says "an opportunity"). | Off-topic question: refused before calling the LLM (0.7 s). |
|
|
19
|
+
|
|
20
|
+
| MCQ practice: the self-check flags a question with two defensible options | Instant outline from slide titles / headings |
|
|
21
|
+
|---|---|
|
|
22
|
+
|  |  |
|
|
23
|
+
|
|
24
|
+
Screenshots are captured automatically from the running app (`python scripts/screenshots.py`), using the
|
|
25
|
+
public Wikipedia sample corpus.
|
|
26
|
+
|
|
27
|
+
## Why this project exists
|
|
28
|
+
Students get course material as slide decks and PDFs, and general chatbots answer from the internet, not from
|
|
29
|
+
*their* syllabus. They confidently invent things and can't point to the slide an exam question will come from.
|
|
30
|
+
StudyRAG answers only from what your teacher actually gave you, and shows its sources.
|
|
31
|
+
|
|
32
|
+
The first real test exposed a problem that most "chat with your PDF" demos ignore: **all 150 slides of the
|
|
33
|
+
three test lectures were images**, with zero extractable text. So StudyRAG includes an OCR stage that reads
|
|
34
|
+
image-only slides, scanned PDFs and photos of notes.
|
|
35
|
+
|
|
36
|
+
## Features
|
|
37
|
+
| | |
|
|
38
|
+
|---|---|
|
|
39
|
+
| 💬 **Grounded Q&A** | Answers with clickable citations (`Lec 2 — Slide 14`) and a streaming response |
|
|
40
|
+
| 🛑 **Honest refusal** | "Not in your documents" when nothing relevant is found: decided *before* calling the LLM |
|
|
41
|
+
| ✅ **Claim verification** | Every answer sentence is checked against its cited source; weak claims are flagged |
|
|
42
|
+
| 🎯 **Confidence badge** | Combines retrieval relevance with the verified-sentence ratio |
|
|
43
|
+
| 📝 **Summaries** | Instant outline from slide titles + AI summary (map-reduce for long lectures) |
|
|
44
|
+
| ❓ **MCQ practice** | 4 options, explanation and source per question; each question is self-checked by the model before you see it; exam mode with score |
|
|
45
|
+
| ✍️ **Short answers** | Type an answer and the AI grades it against the model answer and source passage |
|
|
46
|
+
| 🃏 **Flashcards** | Exportable to Anki |
|
|
47
|
+
| 📷 **OCR** | Image-only slides, scanned PDFs, PNG/JPG photos (RapidOCR, cached) |
|
|
48
|
+
| 🔍 **How I found this** | Each answer's full retrieval trace: BM25 rank, vector rank, fusion score, reranker score |
|
|
49
|
+
| 📂 **Formats** | PDF, PPTX, DOCX, TXT, MD, images, plus legacy DOC/PPT via LibreOffice; tables are rewritten as sentences so search understands them |
|
|
50
|
+
| ⚡ **Incremental index** | Adding a file only processes that file; OCR results are cached |
|
|
51
|
+
|
|
52
|
+
## Built from scratch vs. off-the-shelf
|
|
53
|
+
| Built in this repo | Used off-the-shelf |
|
|
54
|
+
|---|---|
|
|
55
|
+
| Chunking (fixed / structure-aware / semantic) | File parsers (python-pptx, python-docx, pypdf) |
|
|
56
|
+
| BM25 with inverted index, tokenizer and stemmer | Embedding model (bge-small, via fastembed/ONNX) |
|
|
57
|
+
| Vector search (NumPy cosine) | Cross-encoder reranker (MiniLM, via fastembed) |
|
|
58
|
+
| Reciprocal Rank Fusion | LLM runtime (llama.cpp) + model (Qwen3.5-2B, 4-bit) |
|
|
59
|
+
| Prompting, citation parsing, refusal logic, confidence | OCR models (RapidOCR) |
|
|
60
|
+
| Claim verifier, MCQ validation, self-check and de-biasing | Web UI framework (Streamlit) |
|
|
61
|
+
| Persistent incremental index, OCR layout reconstruction | |
|
|
62
|
+
| Evaluation harness and labelled datasets | |
|
|
63
|
+
|
|
64
|
+
## How it works
|
|
65
|
+
```
|
|
66
|
+
files ─► load + OCR ─► chunk ─► BM25 index + vector index
|
|
67
|
+
question ─► BM25 top-10 ┐
|
|
68
|
+
vector top-10 ┴► Reciprocal Rank Fusion ─► cross-encoder rerank ─► relevant? ──no──► "not in your documents"
|
|
69
|
+
│yes
|
|
70
|
+
local LLM with numbered sources ◄────────┘
|
|
71
|
+
│
|
|
72
|
+
answer + [citations] ─► verify each sentence ─► confidence
|
|
73
|
+
```
|
|
74
|
+
Full walkthrough: **[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md)**
|
|
75
|
+
|
|
76
|
+
## Quickstart
|
|
77
|
+
```bash
|
|
78
|
+
cd 01-rag-from-scratch
|
|
79
|
+
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
|
|
80
|
+
pip install -r requirements.txt # compiles llama.cpp: 5-15 min
|
|
81
|
+
pip install --no-deps -e . # the studyrag package + command
|
|
82
|
+
python scripts/download_models.py # ~1.5 GB, resumable
|
|
83
|
+
streamlit run app/streamlit_app.py
|
|
84
|
+
```
|
|
85
|
+
Put your files in `data/my_docs/` (never pushed to git) and click **Sync**. Full guide, Windows/macOS notes and
|
|
86
|
+
troubleshooting: **[docs/SETUP.md](docs/SETUP.md)**
|
|
87
|
+
|
|
88
|
+
## Results
|
|
89
|
+
| | public set (Wikipedia, 42 q) | private set (OCR'd lectures, 35 q) |
|
|
90
|
+
|---|---|---|
|
|
91
|
+
| retrieval hit@3 / MRR@10 | 1.00 / 0.971 | 1.00 / 0.966 |
|
|
92
|
+
| answerable questions answered | 34 / 34 | 28 / 29 ¹ |
|
|
93
|
+
| unanswerable questions refused | 8 / 8 | 6 / 6 |
|
|
94
|
+
| key-fact recall | 0.90 | 0.94 |
|
|
95
|
+
| answers mostly correct (≥ 50% of key facts) | 0.97 | 0.96 |
|
|
96
|
+
| faithfulness (sentences backed by sources) | 0.95 | 0.95 |
|
|
97
|
+
| citation support (cited passage backs the sentence) | 0.96 | 0.98 |
|
|
98
|
+
| median time per answer (Qwen3.5-2B, CPU) | 32 s | 35 s |
|
|
99
|
+
|
|
100
|
+
¹ A grading-table row the reranker scores low; the refusal still shows that passage ([why](docs/RESULTS.md#2-refusal-calibration)).
|
|
101
|
+
|
|
102
|
+
**Things the evaluation caught** (each fixed and re-measured, see [DECISIONS](docs/DECISIONS.md)):
|
|
103
|
+
an OCR model that turned 3.4% of slide lines into gibberish · tables the reranker couldn't read · MCQ explanations
|
|
104
|
+
pointing at the wrong letter after shuffling · MCQs with two defensible answers (now self-checked) · a 2× slower reranking depth with no accuracy gain.
|
|
105
|
+
|
|
106
|
+
**Model choice, measured:** Qwen3.5-0.8B answers in 15 s and Qwen2.5-1.5B in 23 s, but on real slides the default
|
|
107
|
+
Qwen3.5-2B's citations were the most reliable (0.98 vs 0.80 for the 1.5B). [Full comparison](docs/RESULTS.md#6-which-local-model-same-pipeline-three-models).
|
|
108
|
+
All numbers come from `eval/run_eval.py` and are explained in **[docs/RESULTS.md](docs/RESULTS.md)**. Design choices
|
|
109
|
+
backed by these measurements are in **[docs/DECISIONS.md](docs/DECISIONS.md)**.
|
|
110
|
+
|
|
111
|
+
## Read it as PDFs
|
|
112
|
+
Prefer documents to Markdown? Every guide is also a formatted PDF in [docs/pdf/](docs/pdf/):
|
|
113
|
+
|
|
114
|
+
| | |
|
|
115
|
+
|---|---|
|
|
116
|
+
| 📄 [**Overview**](docs/pdf/StudyRAG-Overview.pdf) | The project on one page (2 pages) |
|
|
117
|
+
| 🗓️ [**Timeline**](docs/pdf/StudyRAG-Timeline.pdf) | How it was built: each phase, the problems met and how they were solved |
|
|
118
|
+
| 🛠️ [**Setup Guide**](docs/pdf/StudyRAG-Setup-Guide.pdf) | Install and run on Linux, Windows or macOS |
|
|
119
|
+
| 🧭 [**How It Works**](docs/pdf/StudyRAG-How-It-Works.pdf) | Architecture, step by step |
|
|
120
|
+
| 📊 [**Results**](docs/pdf/StudyRAG-Results.pdf) · [**Design Decisions**](docs/pdf/StudyRAG-Design-Decisions.pdf) | Every measurement, and the choices they drove |
|
|
121
|
+
| 🎓 [**Concepts Handbook**](docs/pdf/StudyRAG-Concepts-Handbook.pdf) | All 11 concept notes in one book |
|
|
122
|
+
|
|
123
|
+
The Markdown files are the source; `python scripts/build_pdfs.py` regenerates the PDFs (needs pandoc and Chrome).
|
|
124
|
+
|
|
125
|
+
## Learn how it works
|
|
126
|
+
Concept notes, written to be understood and explained in an interview:
|
|
127
|
+
|
|
128
|
+
1. [Chunking](docs/concepts/01-chunking.md) · 2. [BM25](docs/concepts/02-bm25.md) · 3. [Embeddings & vector search](docs/concepts/03-embeddings-and-vector-search.md) ·
|
|
129
|
+
4. [Hybrid search & RRF](docs/concepts/04-hybrid-search-rrf.md) · 5. [Reranking](docs/concepts/05-reranking.md) ·
|
|
130
|
+
6. [Grounded generation](docs/concepts/06-grounded-generation.md) · 7. [Verification](docs/concepts/07-verification.md) ·
|
|
131
|
+
8. [OCR](docs/concepts/08-ocr.md) · 9. [Local LLMs on CPU](docs/concepts/09-local-llms.md) ·
|
|
132
|
+
10. [Question generation](docs/concepts/10-question-generation.md) · 11. [Evaluation](docs/concepts/11-evaluation.md)
|
|
133
|
+
|
|
134
|
+
## Project layout
|
|
135
|
+
```
|
|
136
|
+
src/studyrag/ the library (ingest, chunking, bm25, vector_index, hybrid, retrieval, llm, answer, verify, study)
|
|
137
|
+
app/ Streamlit web app
|
|
138
|
+
eval/ labelled datasets + evaluation harness
|
|
139
|
+
tests/ unit + pipeline tests (fake models, run in seconds)
|
|
140
|
+
scripts/ model download, sample corpus fetch
|
|
141
|
+
docs/ overview, timeline, setup, architecture, concepts, decisions, results (+ PDF editions in docs/pdf/)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Limitations
|
|
145
|
+
- Small local models are slow on old CPUs (see the speed results) and weaker than large cloud models at nuanced
|
|
146
|
+
questions; the API backend exists for that trade-off.
|
|
147
|
+
- The claim verifier is a fast heuristic (word overlap + semantic similarity), not logical entailment.
|
|
148
|
+
- Generated MCQs: in a strict human review, about 1 in 4 had a flaw (e.g. two defensible options). The self-check
|
|
149
|
+
flags some of them; every question shows its source so you can check. A larger model via the API backend does better.
|
|
150
|
+
- One answerable question in 63 was refused (a table row the reranker scores low); the refusal shows that passage.
|
|
151
|
+
- OCR handles printed text well; handwriting and complex diagrams are out of scope.
|
|
152
|
+
- English only (embedding model, stemmer and stopwords).
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
Code: MIT. Sample corpus: Wikipedia articles, CC BY-SA 4.0 (attribution in each file).
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "studyrag"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A private, offline study assistant: grounded Q&A with citations over your own slides, PDFs and notes (OCR included)."
|
|
9
|
+
readme = "PYPI.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Abubakar Idrees" }]
|
|
14
|
+
keywords = ["rag", "retrieval", "bm25", "study", "ocr", "citations", "llm"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Intended Audience :: Education",
|
|
18
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
19
|
+
"Topic :: Text Processing :: Indexing",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"fastembed>=0.9",
|
|
23
|
+
"rapidocr>=3.10",
|
|
24
|
+
"python-pptx>=1.0",
|
|
25
|
+
"python-docx>=1.2",
|
|
26
|
+
"pypdf>=7.1",
|
|
27
|
+
"httpx>=0.28",
|
|
28
|
+
"numpy>=1.26,<3",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
local-llm = ["llama-cpp-python>=0.3.37"]
|
|
33
|
+
dev = ["pytest"]
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
Homepage = "https://github.com/Abubakar-idrees-01/data-to-impact/tree/main/01-rag-from-scratch"
|
|
37
|
+
Source = "https://github.com/Abubakar-idrees-01/data-to-impact"
|
|
38
|
+
Documentation = "https://github.com/Abubakar-idrees-01/data-to-impact/blob/main/01-rag-from-scratch/docs/SETUP.md"
|
|
39
|
+
|
|
40
|
+
[project.scripts]
|
|
41
|
+
studyrag = "studyrag.cli:main"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.packages.find]
|
|
44
|
+
where = ["src"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
testpaths = ["tests"]
|
|
48
|
+
pythonpath = ["src"]
|
studyrag-0.1.0/setup.cfg
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"
|
|
@@ -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)
|
|
@@ -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]
|