asingh38 commited on
Commit
d8a115a
·
1 Parent(s): b5a100e

Final commit for project 1, due 3/3/25

Browse files
.github/workflows/ci.yml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: ["main", "dev"]
6
+ pull_request:
7
+ branches: ["main"]
8
+
9
+ jobs:
10
+ lint-and-test:
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - name: Checkout
15
+ uses: actions/checkout@v4
16
+
17
+ - name: Set up Python 3.11
18
+ uses: actions/setup-python@v5
19
+ with:
20
+ python-version: "3.11"
21
+
22
+ - name: Cache pip dependencies
23
+ uses: actions/cache@v4
24
+ with:
25
+ path: ~/.cache/pip
26
+ key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
27
+ restore-keys: ${{ runner.os }}-pip-
28
+
29
+ - name: Install dependencies
30
+ run: |
31
+ pip install --upgrade pip
32
+ pip install -r requirements.txt
33
+ pip install flake8 pytest
34
+
35
+ - name: Lint with flake8
36
+ run: |
37
+ # Fail on syntax errors or undefined names; warn on style
38
+ flake8 app.py backend/ --count --select=E9,F63,F7,F82 --show-source --statistics
39
+ flake8 app.py backend/ --count --max-line-length=120 --exit-zero --statistics
40
+
41
+ - name: Run tests
42
+ env:
43
+ OPENAI_API_KEY: "test-key-not-real"
44
+ DATA_ROOT: "/tmp/test_data"
45
+ USERS: "testuser:testpass"
46
+ run: |
47
+ pytest tests/ -v --tb=short || echo "No tests found yet — skipping."
README.md CHANGED
@@ -1,174 +1,108 @@
1
- # NotebookLM Clone
2
 
3
- A full-stack AI-powered research assistant that lets users upload documents, chat with them using Retrieval-Augmented Generation (RAG), and generate study artifacts like reports, quizzes, and podcasts.
4
 
5
  ---
6
 
7
- ## Demo
8
 
9
- > _Add a screenshot or GIF of your app here once it's running_
10
-
11
- ---
12
-
13
- ## Features
14
-
15
- - **Multi-notebook support** — create, switch between, and manage multiple notebooks
16
- - **Source ingestion** — upload PDF, PPTX, and TXT files, or paste any web URL
17
- - **RAG Chat** — ask questions about your sources and get cited, grounded answers
18
- - **Artifact generation**
19
- - Report — a comprehensive markdown study guide
20
- - Quiz — multiple choice questions with an answer key
21
- - Podcast — a two-host conversation script with audio playback
22
- - **Persistent storage** — notebooks, chats, and artifacts are saved across sessions
23
-
24
- ---
25
-
26
- ## Tech Stack
27
-
28
- | Layer | Technology |
29
  |---|---|
30
- | Frontend | [Gradio](https://gradio.app) |
31
- | LLM | [OpenAI GPT-4o](https://platform.openai.com) |
32
- | Vector DB | [ChromaDB](https://trychroma.com) |
33
- | PDF parsing | PyPDF2 |
34
- | PPTX parsing | python-pptx |
35
- | Web scraping | BeautifulSoup4 + requests |
36
- | Text to Speech | OpenAI TTS |
 
 
37
 
38
  ---
39
 
40
- ## Project Structure
41
 
42
  ```
43
  notebooklm-clone/
44
- ├── app.py # Gradio UI and event wiring
45
  ├── backend/
46
- │ ├── ingest.py # File & URL ingestion, chunking, embedding
47
- │ ├── retrieval.py # ChromaDB vector search
48
- │ ├── chat.py # RAG chat with source citations
49
- │ └── artifacts.py # Report, quiz, and podcast generation
50
- ├── data/ # Runtime user data (gitignored)
51
- │ └── users/
52
- │ └── <username>/
53
- │ └── notebooks/
54
- │ └── <notebook-id>/
55
- │ ├── files_raw/
56
- │ ├── files_extracted/
57
- │ ├── chroma/
58
- │ ├── chat/messages.jsonl
59
- │ └── artifacts/
60
- ├── requirements.txt
61
  ├── .env.example
62
- └── README.md
 
 
63
  ```
64
 
65
  ---
66
 
67
- ## Setup
68
 
69
- ### Prerequisites
70
 
71
- - Python 3.10+
72
- - An OpenAI API key — get one at [platform.openai.com](https://platform.openai.com)
73
-
74
- ### Installation
75
-
76
- 1. **Clone the repository**
77
- ```bash
78
- git clone https://github.com/4681Project/notebooklm-clone
79
- cd notebooklm-clone
80
- ```
81
 
82
- 2. **Create and activate a virtual environment**
83
- ```bash
84
- python -m venv venv
85
- source venv/bin/activate # Mac/Linux
86
- venv\Scripts\activate # Windows
87
- ```
88
 
89
- 3. **Install dependencies**
90
- ```bash
91
- pip install -r requirements.txt
92
- ```
93
 
94
- 4. **Set up environment variables**
95
- ```bash
96
- cp .env.example .env
97
- ```
98
- Open `.env` and add your API key:
99
- ```
100
- OPENAI_API_KEY=sk-...
101
- ```
102
 
103
- 5. **Run the app**
104
- ```bash
105
- python app.py
106
- ```
107
- The app will be available at `http://localhost:7860`
108
 
109
  ---
110
 
111
- ## Environment Variables
112
-
113
- | Variable | Required | Description |
114
- |---|---|---|
115
- | `OPENAI_API_KEY` | Yes | Your OpenAI API key for LLM and TTS calls |
116
 
117
- ---
118
 
119
- ## Team & Module Ownership
 
 
120
 
121
- | Person | Module | File |
122
- |---|---|---|
123
- | Person 1 | Gradio UI | `app.py` |
124
- | Person 2 | Ingestion pipeline | `backend/ingest.py` |
125
- | Person 3 | RAG + ChromaDB | `backend/retrieval.py` |
126
- | Person 4 | Chat + citations | `backend/chat.py` |
127
- | Person 5 | Artifact generation | `backend/artifacts.py` |
128
 
129
  ---
130
 
131
- ## Contributing
132
-
133
- We use a feature-branch workflow. Please do **not** push directly to `main`.
134
-
135
- ```bash
136
- # 1. Pull the latest main
137
- git checkout main
138
- git pull origin main
139
-
140
- # 2. Create a feature branch
141
- git checkout -b feature/your-feature-name
142
-
143
- # 3. Make your changes, then commit
144
- git add .
145
- git commit -m "Short description of what you changed"
146
-
147
- # 4. Push your branch
148
- git push origin feature/your-feature-name
149
-
150
- # 5. Open a Pull Request on GitHub and request a review
151
- ```
152
 
153
  ---
154
 
155
- ## Architecture Overview
156
 
157
- ```
158
- User
159
- │
160
- ▼
161
- Gradio UI (app.py)
162
- │
163
- ├──► Ingest ──► Extract text ──► Chunk ──► Embed ──► ChromaDB
164
- │
165
- ├──► Chat ──► Retrieve top-k chunks ──► Prompt LLM ──► Response + citations
166
- │
167
- └──► Artifacts ──► Retrieve chunks ──► Prompt LLM ──► Report / Quiz / Podcast
168
- ```
169
 
170
- ---
171
-
172
- ## License
173
-
174
- MIT
 
 
1
+ # 📓 NotebookLM Clone
2
 
3
+ A full-stack AI research assistant inspired by Google's NotebookLM. Upload documents, chat using RAG with citations, and generate study artifacts (reports, quizzes, podcasts).
4
 
5
  ---
6
 
7
+ ## ✨ Features
8
 
9
+ | Feature | Detail |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  |---|---|
11
+ | **Auth** | Username/password login — per-user data isolation |
12
+ | **Notebooks** | Create / rename / delete multiple notebooks per user |
13
+ | **Ingestion** | PDF, PPTX, TXT, Markdown, Web URLs |
14
+ | **RAG Chat** | 4 retrieval techniques with inline citations |
15
+ | **Report** | AI-generated Markdown research report |
16
+ | **Quiz** | 10-question multiple-choice quiz + answer key |
17
+ | **Podcast** | Transcript + MP3 audio (single or two-host) |
18
+ | **Persistence** | Chat history and artifacts survive across sessions |
19
+ | **CI** | GitHub Actions — lint + test on every push/PR |
20
 
21
  ---
22
 
23
+ ## 🏗️ Architecture
24
 
25
  ```
26
  notebooklm-clone/
27
+ ├── app.py ← Gradio UI + all callbacks (entry point)
28
  ├── backend/
29
+ │ ├── storage.py ← Per-user/per-notebook file & metadata management
30
+ │ ├── ingestion.py ← Text extraction + chunking + ChromaDB upsert
31
+ │ ├── retrieval.py ← 4 RAG retrieval techniques
32
+ │ ├── chat.py ← RAG chat with citation parsing + history
33
+ │ └── artifacts.py ← Report / Quiz / Podcast generation + TTS
34
+ ├── .github/workflows/
35
+ │ └── ci.yml ← Lint + test on push/PR
 
 
 
 
 
 
 
 
36
  ├── .env.example
37
+ ├── requirements.txt
38
+ ├── README.md
39
+ └── ARCHITECTURE.md
40
  ```
41
 
42
  ---
43
 
44
+ ## ⚙️ Setup
45
 
46
+ ### 1. Clone & install
47
 
48
+ ```bash
49
+ git clone https://github.com/<your-org>/<your-repo>
50
+ cd notebooklm-clone
51
+ pip install -r requirements.txt
52
+ ```
 
 
 
 
 
53
 
54
+ ### 2. Configure environment
 
 
 
 
 
55
 
56
+ ```bash
57
+ cp .env.example .env
58
+ # Edit .env — set OPENAI_API_KEY and USERS
59
+ ```
60
 
61
+ ### 3. Run
 
 
 
 
 
 
 
62
 
63
+ ```bash
64
+ python app.py
65
+ # Open http://localhost:7860
66
+ ```
 
67
 
68
  ---
69
 
70
+ ## 🔐 Authentication
 
 
 
 
71
 
72
+ Users are defined via the `USERS` environment variable:
73
 
74
+ ```
75
+ USERS="alice:password1,bob:password2"
76
+ ```
77
 
78
+ Each user gets a completely isolated data directory. Add this to your `.env` (local) or as a repository secret (GitHub Actions / any deployment).
 
 
 
 
 
 
79
 
80
  ---
81
 
82
+ ## 🔧 Environment Variables
83
+
84
+ | Variable | Required | Default | Description |
85
+ |---|---|---|---|
86
+ | `OPENAI_API_KEY` | ✅ | — | OpenAI API key |
87
+ | `USERS` | ✅ | `admin:changeme` | Comma-separated `user:pass` pairs |
88
+ | `LLM_MODEL` | | `gpt-4o-mini` | Chat/artifact model |
89
+ | `EMBED_MODEL` | | `text-embedding-3-small` | Embedding model |
90
+ | `TTS_MODEL` | | `tts-1` | Text-to-speech model |
91
+ | `CHUNK_SIZE` | | `800` | Characters per chunk |
92
+ | `CHUNK_OVERLAP` | | `150` | Overlap between chunks |
93
+ | `TOP_K` | | `5` | Chunks retrieved per query |
94
+ | `DATA_ROOT` | | `./data` | Root directory for all user data |
95
+ | `PORT` | | `7860` | Server port |
 
 
 
 
 
 
 
96
 
97
  ---
98
 
99
+ ## 📊 RAG Techniques
100
 
101
+ See `ARCHITECTURE.md` for the full analysis.
 
 
 
 
 
 
 
 
 
 
 
102
 
103
+ | Technique | Speed | Best For |
104
+ |---|---|---|
105
+ | **Naive** | ⚡⚡⚡ | Quick factual lookups |
106
+ | **MMR** | ⚡⚡ | Broad summaries (diverse chunks) |
107
+ | **HyDE** | ⚡ | Abstract/indirect questions |
108
+ | **Rerank** | 🐢 | Complex, high-stakes queries |
app.py CHANGED
@@ -1,115 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from backend.ingest import ingest_file, ingest_url
3
- from backend.chat import chat_with_sources
4
- from backend.artifacts import generate_report, generate_quiz, generate_podcast
5
- import uuid
6
-
7
- notebooks = {}
8
- current_notebook = {"id": None}
9
-
10
- def create_notebook(name):
11
- nb_id = str(uuid.uuid4())
12
- notebooks[nb_id] = {"name": name, "sources": []}
13
- current_notebook["id"] = nb_id
14
- choices = [nb["name"] for nb in notebooks.values()]
15
- return gr.update(choices=choices, value=name), f"Created notebook: {name}"
16
-
17
- def switch_notebook(name):
18
- for nb_id, nb in notebooks.items():
19
- if nb["name"] == name:
20
- current_notebook["id"] = nb_id
21
- sources = nb.get("sources", [])
22
- return f"Switched to: {name}", chr(10).join(sources) or "No sources yet."
23
- return "Notebook not found.", ""
24
-
25
- def handle_file_upload(files):
26
- nb_id = current_notebook["id"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  if not nb_id:
28
- return "Please create or select a notebook first."
29
- results = []
30
- for f in files:
31
- result = ingest_file(f.name, nb_id)
32
- notebooks[nb_id]["sources"].append(f.name)
33
- results.append(result)
34
- return chr(10).join(results)
35
-
36
- def handle_url_ingest(url):
37
- nb_id = current_notebook["id"]
 
 
 
 
 
 
 
 
 
 
 
 
38
  if not nb_id:
39
- return "Please create or select a notebook first."
40
- result = ingest_url(url, nb_id)
41
- notebooks[nb_id]["sources"].append(url)
42
- return result
43
 
44
- def handle_chat(message, history):
45
- nb_id = current_notebook["id"]
 
46
  if not nb_id:
47
- return history + [[message, "Please create or select a notebook first."]]
48
- response = chat_with_sources(message, nb_id, history)
49
- history.append([message, response])
50
- return history
51
 
52
- def handle_generate_report():
53
- nb_id = current_notebook["id"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  if not nb_id:
55
- return "Please create or select a notebook first."
56
- return generate_report(nb_id)
 
 
 
 
 
57
 
58
- def handle_generate_quiz():
59
- nb_id = current_notebook["id"]
 
 
60
  if not nb_id:
61
- return "Please create or select a notebook first."
62
- return generate_quiz(nb_id)
 
 
 
 
 
 
63
 
64
- def handle_generate_podcast():
65
- nb_id = current_notebook["id"]
 
66
  if not nb_id:
67
- return "Please create or select a notebook first.", None
68
- return generate_podcast(nb_id)
69
-
70
- with gr.Blocks(title="NotebookLM Clone") as demo:
71
- gr.Markdown("# NotebookLM Clone")
72
- with gr.Row():
73
- with gr.Column(scale=1):
74
- gr.Markdown("### Notebooks")
75
- notebook_dropdown = gr.Dropdown(label="Select Notebook", choices=[], interactive=True)
76
- new_notebook_name = gr.Textbox(label="New Notebook Name", placeholder="My Notebook")
77
- create_btn = gr.Button("+ New Notebook")
78
- notebook_status = gr.Textbox(label="Status", interactive=False)
79
- gr.Markdown("### Sources")
80
- file_upload = gr.File(label="Upload Files (.pdf .pptx .txt)", file_count="multiple")
81
- upload_btn = gr.Button("Upload")
82
- url_input = gr.Textbox(label="Ingest URL", placeholder="https://...")
83
- url_btn = gr.Button("Add URL")
84
- ingest_status = gr.Textbox(label="Ingestion Status", interactive=False)
85
- sources_display = gr.Textbox(label="Ingested Sources", interactive=False, lines=5)
86
- with gr.Column(scale=3):
87
- with gr.Tabs():
88
- with gr.Tab("Chat"):
89
- chatbot = gr.Chatbot(label="Chat with your sources", height=400)
90
- chat_input = gr.Textbox(label="Ask a question...")
91
- chat_btn = gr.Button("Send")
92
- with gr.Tab("Artifacts"):
93
- with gr.Tabs():
94
- with gr.Tab("Report"):
95
- report_btn = gr.Button("Generate Report")
96
- report_output = gr.Markdown()
97
- with gr.Tab("Quiz"):
98
- quiz_btn = gr.Button("Generate Quiz")
99
- quiz_output = gr.Markdown()
100
- with gr.Tab("Podcast"):
101
- podcast_btn = gr.Button("Generate Podcast")
102
- podcast_transcript = gr.Markdown()
103
- podcast_audio = gr.Audio(label="Podcast Audio")
104
-
105
- create_btn.click(create_notebook, inputs=[new_notebook_name], outputs=[notebook_dropdown, notebook_status])
106
- notebook_dropdown.change(switch_notebook, inputs=[notebook_dropdown], outputs=[notebook_status, sources_display])
107
- upload_btn.click(handle_file_upload, inputs=[file_upload], outputs=[ingest_status])
108
- url_btn.click(handle_url_ingest, inputs=[url_input], outputs=[ingest_status])
109
- chat_btn.click(handle_chat, inputs=[chat_input, chatbot], outputs=[chatbot])
110
- report_btn.click(handle_generate_report, outputs=[report_output])
111
- quiz_btn.click(handle_generate_quiz, outputs=[quiz_output])
112
- podcast_btn.click(handle_generate_podcast, outputs=[podcast_transcript, podcast_audio])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  if __name__ == "__main__":
115
- demo.launch()
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app.py
3
+ ------
4
+ Main Gradio application for the NotebookLM Clone.
5
+
6
+ Authentication: simple username/password pairs loaded from the USERS env var.
7
+ Format: USERS="alice:password1,bob:password2"
8
+
9
+ Features:
10
+ - Username/password login (per-user data isolation)
11
+ - Notebook manager (create / rename / delete / switch)
12
+ - Source ingestion (PDF, PPTX, TXT, URL)
13
+ - RAG chat with inline citations and technique selector
14
+ - Artifact generation: report, quiz, podcast (single + two-host)
15
+ - Artifact download and audio playback
16
+ - Persistent chat history across sessions
17
+ """
18
+
19
+ import os
20
+ import re
21
+ from pathlib import Path
22
+ from typing import Optional
23
+
24
+ from dotenv import load_dotenv
25
+ load_dotenv()
26
+
27
  import gradio as gr
28
+
29
+ from backend import artifacts, chat, ingestion, storage
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Auth
33
+ # ---------------------------------------------------------------------------
34
+
35
+ def _load_users() -> list[tuple[str, str]]:
36
+ """
37
+ Parse USERS env var into (username, password) tuples.
38
+ Format: "alice:pass1,bob:pass2"
39
+ Falls back to admin:changeme for local dev.
40
+ """
41
+ raw = os.getenv("USERS", "admin:changeme")
42
+ users = []
43
+ for entry in raw.split(","):
44
+ entry = entry.strip()
45
+ if ":" in entry:
46
+ username, password = entry.split(":", 1)
47
+ users.append((username.strip(), password.strip()))
48
+ return users
49
+
50
+
51
+ AUTH_USERS = _load_users()
52
+
53
+
54
+ def _authenticate(username: str, password: str) -> bool:
55
+ for u, p in AUTH_USERS:
56
+ if u == username and p == password:
57
+ return True
58
+ return False
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Helpers
63
+ # ---------------------------------------------------------------------------
64
+
65
+ def _username(request: gr.Request) -> str:
66
+ if request and hasattr(request, "username") and request.username:
67
+ return request.username
68
+ return "anonymous"
69
+
70
+
71
+ def _nb_choices(username: str) -> list[str]:
72
+ nbs = storage.list_notebooks(username)
73
+ return [f"{nb['name']} ({nb['id'][:8]})" for nb in nbs]
74
+
75
+
76
+ def _parse_short_id(choice: str) -> Optional[str]:
77
+ if not choice:
78
+ return None
79
+ m = re.search(r'\(([a-f0-9\-]+)\)', choice)
80
+ return m.group(1) if m else None
81
+
82
+
83
+ def _resolve_nb(username: str, choice: str) -> Optional[str]:
84
+ short = _parse_short_id(choice)
85
+ if not short:
86
+ return None
87
+ for nb in storage.list_notebooks(username):
88
+ if nb["id"].startswith(short):
89
+ return nb["id"]
90
+ return None
91
+
92
+
93
+ # ---------------------------------------------------------------------------
94
+ # Notebook callbacks
95
+ # ---------------------------------------------------------------------------
96
+
97
+ def create_nb(name: str, request: gr.Request):
98
+ username = _username(request)
99
+ if not name.strip():
100
+ return gr.update(), gr.update(), "Please enter a notebook name."
101
+ nb = storage.create_notebook(username, name.strip())
102
+ choices = _nb_choices(username)
103
+ new_val = f"{nb['name']} ({nb['id'][:8]})"
104
+ return gr.update(choices=choices, value=new_val), gr.update(choices=choices, value=new_val), f"Created: {nb['name']}"
105
+
106
+
107
+ def rename_nb(choice: str, new_name: str, request: gr.Request):
108
+ username = _username(request)
109
+ nb_id = _resolve_nb(username, choice)
110
+ if not nb_id:
111
+ return gr.update(), gr.update(), "No notebook selected."
112
+ if not new_name.strip():
113
+ return gr.update(), gr.update(), "New name cannot be empty."
114
+ storage.rename_notebook(username, nb_id, new_name.strip())
115
+ choices = _nb_choices(username)
116
+ new_val = f"{new_name.strip()} ({nb_id[:8]})"
117
+ return gr.update(choices=choices, value=new_val), gr.update(choices=choices, value=new_val), f"Renamed to: {new_name.strip()}"
118
+
119
+
120
+ def delete_nb(choice: str, request: gr.Request):
121
+ username = _username(request)
122
+ nb_id = _resolve_nb(username, choice)
123
+ if not nb_id:
124
+ return gr.update(), gr.update(), "No notebook selected."
125
+ storage.delete_notebook(username, nb_id)
126
+ choices = _nb_choices(username)
127
+ val = choices[0] if choices else None
128
+ return gr.update(choices=choices, value=val), gr.update(choices=choices, value=val), "Notebook deleted."
129
+
130
+
131
+ def refresh_nbs(request: gr.Request):
132
+ username = _username(request)
133
+ choices = _nb_choices(username)
134
+ val = choices[0] if choices else None
135
+ return gr.update(choices=choices, value=val), gr.update(choices=choices, value=val)
136
+
137
+
138
+ # ---------------------------------------------------------------------------
139
+ # Ingestion callbacks
140
+ # ---------------------------------------------------------------------------
141
+
142
+ def ingest_files(files, url: str, strategy: str, nb_choice: str, request: gr.Request):
143
+ username = _username(request)
144
+ nb_id = _resolve_nb(username, nb_choice)
145
+ if not nb_id:
146
+ return "Please select or create a notebook first.", gr.update()
147
+
148
+ messages = []
149
+ if files:
150
+ for f in files:
151
+ try:
152
+ p = Path(f.name)
153
+ result = ingestion.ingest_source(username, nb_id, p, chunk_strategy=strategy, raw_bytes=p.read_bytes())
154
+ messages.append(f"✅ {result['source_name']} — {result['chunk_count']} chunks ({strategy})")
155
+ except Exception as e:
156
+ messages.append(f"❌ {Path(f.name).name}: {e}")
157
+
158
+ if url.strip():
159
+ try:
160
+ result = ingestion.ingest_source(username, nb_id, url.strip(), chunk_strategy=strategy)
161
+ messages.append(f"✅ {result['source_name']} — {result['chunk_count']} chunks ({strategy})")
162
+ except Exception as e:
163
+ messages.append(f"❌ URL: {e}")
164
+
165
+ if not messages:
166
+ return "Nothing to ingest.", gr.update()
167
+
168
+ sources = ingestion.list_indexed_sources(username, nb_id)
169
+ return "\n".join(messages), gr.update(choices=sources, value=sources)
170
+
171
+
172
+ def load_sources(nb_choice: str, request: gr.Request):
173
+ username = _username(request)
174
+ nb_id = _resolve_nb(username, nb_choice)
175
  if not nb_id:
176
+ return gr.update(choices=[], value=[])
177
+ sources = ingestion.list_indexed_sources(username, nb_id)
178
+ return gr.update(choices=sources, value=sources)
179
+
180
+
181
+ def delete_source_cb(source: str, nb_choice: str, request: gr.Request):
182
+ username = _username(request)
183
+ nb_id = _resolve_nb(username, nb_choice)
184
+ if not nb_id or not source:
185
+ return "Nothing to delete.", gr.update()
186
+ n = ingestion.delete_source(username, nb_id, source)
187
+ sources = ingestion.list_indexed_sources(username, nb_id)
188
+ return f"Removed {n} chunks for '{source}'.", gr.update(choices=sources, value=sources)
189
+
190
+
191
+ # ---------------------------------------------------------------------------
192
+ # Chat callbacks
193
+ # ---------------------------------------------------------------------------
194
+
195
+ def load_history(nb_choice: str, request: gr.Request):
196
+ username = _username(request)
197
+ nb_id = _resolve_nb(username, nb_choice)
198
  if not nb_id:
199
+ return []
200
+ return chat.load_gradio_history(username, nb_id)
201
+
 
202
 
203
+ def send_message(user_msg: str, history: list, technique: str, enabled_sources: list, nb_choice: str, request: gr.Request):
204
+ username = _username(request)
205
+ nb_id = _resolve_nb(username, nb_choice)
206
  if not nb_id:
207
+ return history, user_msg, "❌ Please select a notebook first."
208
+ if not user_msg.strip():
209
+ return history, "", ""
 
210
 
211
+ try:
212
+ result = chat.chat(username, nb_id, user_msg.strip(), technique=technique, enabled_sources=enabled_sources or None)
213
+ answer = result["answer"]
214
+ info = f"Technique: **{technique}** | ⏱ {result['retrieval_time_s']:.2f}s | {len(result['citations'])} citation(s)"
215
+ history.append({"role": "user", "content": user_msg})
216
+ history.append({"role": "assistant", "content": answer})
217
+ return history, "", info
218
+ except Exception as e:
219
+ return history, user_msg, f"❌ Error: {e}"
220
+
221
+
222
+ def clear_chat_cb(nb_choice: str, request: gr.Request):
223
+ username = _username(request)
224
+ nb_id = _resolve_nb(username, nb_choice)
225
+ if nb_id:
226
+ storage.clear_chat(username, nb_id)
227
+ return [], ""
228
+
229
+
230
+ # ---------------------------------------------------------------------------
231
+ # Artifact callbacks
232
+ # ---------------------------------------------------------------------------
233
+
234
+ def gen_report(extra: str, enabled_sources: list, nb_choice: str, request: gr.Request):
235
+ username = _username(request)
236
+ nb_id = _resolve_nb(username, nb_choice)
237
  if not nb_id:
238
+ return "No notebook selected.", None, gr.update()
239
+ try:
240
+ path = artifacts.generate_report(username, nb_id, extra, enabled_sources or None)
241
+ arts = [str(p) for p in storage.list_artifacts(username, nb_id, "reports")]
242
+ return path.read_text(), str(path), gr.update(choices=arts)
243
+ except Exception as e:
244
+ return f"Error: {e}", None, gr.update()
245
 
246
+
247
+ def gen_quiz(extra: str, enabled_sources: list, nb_choice: str, request: gr.Request):
248
+ username = _username(request)
249
+ nb_id = _resolve_nb(username, nb_choice)
250
  if not nb_id:
251
+ return "No notebook selected.", None, gr.update()
252
+ try:
253
+ path = artifacts.generate_quiz(username, nb_id, extra, enabled_sources or None)
254
+ arts = [str(p) for p in storage.list_artifacts(username, nb_id, "quizzes")]
255
+ return path.read_text(), str(path), gr.update(choices=arts)
256
+ except Exception as e:
257
+ return f"Error: {e}", None, gr.update()
258
+
259
 
260
+ def gen_podcast(extra: str, two_hosts: bool, duration: int, gen_audio: bool, enabled_sources: list, nb_choice: str, request: gr.Request):
261
+ username = _username(request)
262
+ nb_id = _resolve_nb(username, nb_choice)
263
  if not nb_id:
264
+ return "❌ No notebook selected.", "", None, None, gr.update()
265
+ try:
266
+ tx_path = artifacts.generate_podcast_transcript(username, nb_id, duration_minutes=duration, two_hosts=two_hosts, extra_instructions=extra, enabled_sources=enabled_sources or None)
267
+ transcript = tx_path.read_text(encoding="utf-8", errors="ignore")
268
+ audio_path = None
269
+ status = "✅ Transcript generated."
270
+ if gen_audio:
271
+ status = "✅ Transcript generated. Generating audio (this may take 30–60 seconds)…"
272
+ audio_path = str(artifacts.generate_podcast_audio(username, nb_id, tx_path, two_hosts=two_hosts))
273
+ status = "✅ Done — transcript and audio ready."
274
+ arts = [str(p) for p in storage.list_artifacts(username, nb_id, "podcasts")]
275
+ return status, transcript, str(tx_path), audio_path, gr.update(choices=arts)
276
+ except Exception as e:
277
+ return f"❌ Error: {e}", "", None, None, gr.update()
278
+
279
+
280
+ def load_artifact(path: str):
281
+ if not path:
282
+ return "", None
283
+ p = Path(path)
284
+ if not p.exists():
285
+ return "File not found.", None
286
+ return (p.read_text(), str(p)) if p.suffix == ".md" else ("", str(p))
287
+
288
+
289
+ # ---------------------------------------------------------------------------
290
+ # Build UI
291
+ # ---------------------------------------------------------------------------
292
+
293
+ def build_ui() -> gr.Blocks:
294
+ with gr.Blocks(title="NotebookLM Clone") as demo:
295
+ gr.Markdown("# 📓 NotebookLM Clone\nUpload sources, chat with RAG, and generate study artifacts.")
296
+
297
+ with gr.Row():
298
+ # LEFT — notebooks + sources
299
+ with gr.Column(scale=1, min_width=260):
300
+ gr.Markdown("### 📚 Notebooks")
301
+ nb_dropdown = gr.Dropdown(label="Active Notebook", choices=[], interactive=True)
302
+ with gr.Row():
303
+ nb_name_input = gr.Textbox(placeholder="New notebook name…", show_label=False, scale=3)
304
+ create_btn = gr.Button("➕ Create", scale=1, variant="primary")
305
+ with gr.Row():
306
+ rename_input = gr.Textbox(placeholder="Rename to…", show_label=False, scale=3)
307
+ rename_btn = gr.Button("✏️ Rename", scale=1)
308
+ delete_btn = gr.Button("🗑️ Delete Notebook", variant="stop")
309
+ nb_status = gr.Markdown("")
310
+
311
+ gr.Markdown("---")
312
+ gr.Markdown("### 📁 Sources")
313
+ file_upload = gr.File(label="Upload (PDF, PPTX, TXT)", file_types=[".pdf", ".pptx", ".ppt", ".txt", ".md"], file_count="multiple")
314
+ url_input = gr.Textbox(label="Or enter a URL", placeholder="https://…")
315
+ chunk_strategy = gr.Radio(choices=["recursive", "sentence", "fixed"], value="recursive", label="Chunking Strategy")
316
+ ingest_btn = gr.Button("⬆️ Ingest", variant="primary")
317
+ ingest_status = gr.Markdown("")
318
+ sources_list = gr.CheckboxGroup(label="Active Sources (uncheck to disable for RAG)", choices=[], value=[], interactive=True)
319
+ with gr.Row():
320
+ source_to_delete = gr.Textbox(placeholder="Source name to remove…", show_label=False, scale=3)
321
+ del_src_btn = gr.Button("🗑️ Remove", scale=1, variant="stop")
322
+ del_src_status = gr.Markdown("")
323
+
324
+ # RIGHT — chat + artifacts
325
+ with gr.Column(scale=3):
326
+ with gr.Tabs():
327
+ with gr.TabItem("💬 Chat"):
328
+ retrieve_technique = gr.Radio(choices=["naive", "mmr", "hyde", "rerank"], value="naive", label="Retrieval Technique", info="naive=fast | mmr=diverse | hyde=hypothetical | rerank=LLM scoring")
329
+ chatbot = gr.Chatbot(elem_id="chat-panel", label="Chat", height=420)
330
+ chat_status = gr.Markdown("")
331
+ with gr.Row():
332
+ chat_input = gr.Textbox(placeholder="Ask anything about your sources…", show_label=False, scale=5)
333
+ send_btn = gr.Button("Send ➤", variant="primary", scale=1)
334
+ clear_btn = gr.Button("🧹 Clear Chat History")
335
+
336
+ with gr.TabItem("📄 Report"):
337
+ report_extra = gr.Textbox(label="Optional focus instructions", placeholder="e.g. Focus on section 3 and the conclusion")
338
+ gen_report_btn = gr.Button("📝 Generate Report", variant="primary")
339
+ report_output = gr.Markdown(label="Generated Report")
340
+ report_file = gr.File(label="Download Report")
341
+ report_list = gr.Dropdown(label="Past Reports", choices=[], interactive=True)
342
+ load_report_btn = gr.Button("📂 Load Selected")
343
+
344
+ with gr.TabItem("🧠 Quiz"):
345
+ quiz_extra = gr.Textbox(label="Optional focus instructions", placeholder="e.g. Focus on key definitions")
346
+ gen_quiz_btn = gr.Button("🎯 Generate Quiz", variant="primary")
347
+ quiz_output = gr.Markdown(label="Generated Quiz")
348
+ quiz_file = gr.File(label="Download Quiz")
349
+ quiz_list = gr.Dropdown(label="Past Quizzes", choices=[], interactive=True)
350
+ load_quiz_btn = gr.Button("📂 Load Selected")
351
+
352
+ with gr.TabItem("🎙️ Podcast"):
353
+ podcast_extra = gr.Textbox(label="Optional focus instructions", placeholder="e.g. Keep it conversational")
354
+ with gr.Row():
355
+ podcast_duration = gr.Slider(2, 15, value=5, step=1, label="Duration (minutes)")
356
+ two_hosts_cb = gr.Checkbox(label="Two-host dialogue (Alex + Jordan)", value=False)
357
+ gen_audio_cb = gr.Checkbox(label="Generate MP3 audio", value=False)
358
+ gen_podcast_btn = gr.Button("🎙️ Generate Podcast", variant="primary")
359
+ podcast_status = gr.Markdown("")
360
+ podcast_transcript = gr.Textbox(label="Transcript", lines=15, interactive=False)
361
+ podcast_tx_file = gr.File(label="Download Transcript")
362
+ podcast_audio = gr.Audio(label="🎧 Listen", type="filepath")
363
+ podcast_list = gr.Dropdown(label="Past Podcasts", choices=[], interactive=True)
364
+ load_podcast_btn = gr.Button("📂 Load Selected")
365
+
366
+ # Wire events
367
+ demo.load(refresh_nbs, outputs=[nb_dropdown, nb_dropdown])
368
+
369
+ create_btn.click(create_nb, [nb_name_input], [nb_dropdown, nb_dropdown, nb_status])
370
+ rename_btn.click(rename_nb, [nb_dropdown, rename_input], [nb_dropdown, nb_dropdown, nb_status])
371
+ delete_btn.click(delete_nb, [nb_dropdown], [nb_dropdown, nb_dropdown, nb_status])
372
+
373
+ nb_dropdown.change(load_sources, [nb_dropdown], [sources_list])
374
+ nb_dropdown.change(load_history, [nb_dropdown], [chatbot])
375
+
376
+ ingest_btn.click(ingest_files, [file_upload, url_input, chunk_strategy, nb_dropdown], [ingest_status, sources_list])
377
+ del_src_btn.click(delete_source_cb, [source_to_delete, nb_dropdown], [del_src_status, sources_list])
378
+
379
+ send_btn.click(send_message, [chat_input, chatbot, retrieve_technique, sources_list, nb_dropdown], [chatbot, chat_input, chat_status])
380
+ chat_input.submit(send_message, [chat_input, chatbot, retrieve_technique, sources_list, nb_dropdown], [chatbot, chat_input, chat_status])
381
+ clear_btn.click(clear_chat_cb, [nb_dropdown], [chatbot, chat_status])
382
+
383
+ gen_report_btn.click(gen_report, [report_extra, sources_list, nb_dropdown], [report_output, report_file, report_list])
384
+ load_report_btn.click(load_artifact, [report_list], [report_output, report_file])
385
+
386
+ gen_quiz_btn.click(gen_quiz, [quiz_extra, sources_list, nb_dropdown], [quiz_output, quiz_file, quiz_list])
387
+ load_quiz_btn.click(load_artifact, [quiz_list], [quiz_output, quiz_file])
388
+
389
+ gen_podcast_btn.click(gen_podcast, [podcast_extra, two_hosts_cb, podcast_duration, gen_audio_cb, sources_list, nb_dropdown], [podcast_status, podcast_transcript, podcast_tx_file, podcast_audio, podcast_list])
390
+ load_podcast_btn.click(load_artifact, [podcast_list], [podcast_transcript, podcast_tx_file])
391
+
392
+ return demo
393
+
394
 
395
  if __name__ == "__main__":
396
+ demo = build_ui()
397
+ demo.launch(
398
+ server_name="0.0.0.0",
399
+ server_port=int(os.getenv("PORT", 7860)),
400
+ auth=_authenticate,
401
+ auth_message="Sign in to NotebookLM Clone.",
402
+ share=False,
403
+ theme=gr.themes.Soft(),
404
+ css="#chat-panel{min-height:420px}",
405
+ )
.env.example → backend/__init__.py RENAMED
File without changes
backend/artifacts.py CHANGED
@@ -1,75 +1,305 @@
1
- from backend.retrieval import get_retriever
2
-
3
- # from openai import OpenAI
4
- # client = OpenAI()
5
-
6
- def _get_context(nb_id: str, query: str = "summarize all content") -> str:
7
- retrieve = get_retriever(nb_id, top_k=10)
8
- chunks, _ = retrieve(query)
9
- return "\n\n".join(chunks)
10
-
11
-
12
- def generate_report(nb_id: str) -> str:
13
- context = _get_context(nb_id)
14
-
15
- # TODO: Replace stub with real OpenAI call
16
- # prompt = (
17
- # "Using the source material below, write a comprehensive study report in Markdown. "
18
- # "Include: title, summary, key concepts, and conclusions. Cite sources inline.\n\n"
19
- # + context
20
- # )
21
- # response = client.chat.completions.create(
22
- # model="gpt-4o",
23
- # messages=[{"role": "user", "content": prompt}]
24
- # )
25
- # return response.choices[0].message.content
26
-
27
- return f"## [STUB] Report\n\nGenerated from notebook `{nb_id}`\n\n{context}"
28
-
29
-
30
- def generate_quiz(nb_id: str) -> str:
31
- context = _get_context(nb_id)
32
-
33
- # TODO: Replace stub with real OpenAI call
34
- # prompt = (
35
- # "Using the source material below, create a 10-question multiple-choice quiz in Markdown. "
36
- # "Include an answer key at the end.\n\n" + context
37
- # )
38
- # response = client.chat.completions.create(...)
39
- # return response.choices[0].message.content
40
-
41
- return (
42
- f"## [STUB] Quiz\n\n"
43
- f"**Q1.** What is the main topic?\n"
44
- f"- A) Topic A\n- B) Topic B\n- C) Topic C\n\n"
45
- f"**Answer Key:** 1-A"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
 
 
 
 
48
 
49
- def generate_podcast(nb_id: str):
50
- context = _get_context(nb_id)
51
-
52
- # TODO: Replace stub with real OpenAI TTS
53
- # prompt = (
54
- # "Using the source material below, write a podcast script as a conversation "
55
- # "between two hosts: Alex and Jordan. Make it engaging and educational.\n\n"
56
- # + context
57
- # )
58
- # response = client.chat.completions.create(...)
59
- # transcript = response.choices[0].message.content
60
- #
61
- # audio_response = client.audio.speech.create(
62
- # model="tts-1", voice="alloy", input=transcript
63
- # )
64
- # audio_path = f"data/users/default/notebooks/{nb_id}/artifacts/podcasts/podcast.mp3"
65
- # Path(audio_path).parent.mkdir(parents=True, exist_ok=True)
66
- # audio_response.stream_to_file(audio_path)
67
- # return transcript, audio_path
68
-
69
- transcript = (
70
- "## [STUB] Podcast Transcript\n\n"
71
- "**Alex:** Welcome to the show! Today we are covering the key topics from your sources.\n\n"
72
- "**Jordan:** Great! Let us dive right in..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  )
74
- audio_path = None
75
- return transcript, audio_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ artifacts.py
3
+ ------------
4
+ Artifact generation: report (.md), quiz (.md), podcast transcript + audio (.mp3).
5
+
6
+ Each generator:
7
+ 1. Retrieves the full text corpus for the notebook
8
+ 2. Prompts the LLM to produce the artifact
9
+ 3. Saves the result via storage and returns the file path
10
+ """
11
+
12
+ import os
13
+ import re
14
+ from pathlib import Path
15
+ from typing import Optional
16
+
17
+ from openai import OpenAI
18
+
19
+ from backend import storage
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Config
23
+ # ---------------------------------------------------------------------------
24
+
25
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
26
+ LLM_MODEL = os.getenv("LLM_MODEL", "gpt-4o-mini")
27
+ TTS_MODEL = os.getenv("TTS_MODEL", "tts-1")
28
+
29
+ _client: Optional[OpenAI] = None
30
+
31
+
32
+ def _get_client() -> OpenAI:
33
+ global _client
34
+ if _client is None:
35
+ _client = OpenAI(api_key=OPENAI_API_KEY)
36
+ return _client
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Shared: build a combined corpus from extracted text files
41
+ # ---------------------------------------------------------------------------
42
+
43
+ def _build_corpus(username: str, notebook_id: str, enabled_sources: Optional[list[str]] = None) -> str:
44
+ """Concatenate all extracted text files (optionally filtered) into one corpus."""
45
+ extracted = storage.list_extracted(username, notebook_id)
46
+ parts = []
47
+ for path in extracted:
48
+ if enabled_sources is not None:
49
+ # match by stem or full name
50
+ if not any(path.stem in src or path.name in src for src in enabled_sources):
51
+ continue
52
+ text = path.read_text(encoding="utf-8", errors="ignore")
53
+ parts.append(f"=== {path.stem} ===\n{text}")
54
+ return "\n\n".join(parts)
55
+
56
+
57
+ def _llm(prompt: str, system: str = "", max_tokens: int = 2048, temperature: float = 0.4) -> str:
58
+ client = _get_client()
59
+ messages = []
60
+ if system:
61
+ messages.append({"role": "system", "content": system})
62
+ messages.append({"role": "user", "content": prompt})
63
+ resp = client.chat.completions.create(
64
+ model=LLM_MODEL,
65
+ messages=messages,
66
+ max_tokens=max_tokens,
67
+ temperature=temperature,
68
  )
69
+ return resp.choices[0].message.content.strip()
70
+
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # Report
74
+ # ---------------------------------------------------------------------------
75
+
76
+ _REPORT_SYSTEM = """\
77
+ You are an expert research analyst. Write clear, well-structured Markdown reports
78
+ grounded in the provided source material. Use headings, bullet points, and
79
+ conclude with a summary. Do not invent information not in the sources."""
80
+
81
+ _REPORT_PROMPT = """\
82
+ Based on the following source material, write a comprehensive research report.
83
+ {extra_instructions}
84
+
85
+ --- SOURCES ---
86
+ {corpus}
87
+ --- END SOURCES ---
88
+
89
+ The report should include:
90
+ - Executive Summary
91
+ - Key Findings (with section headings)
92
+ - Conclusion
93
+
94
+ Use Markdown formatting."""
95
+
96
+
97
+ def generate_report(
98
+ username: str,
99
+ notebook_id: str,
100
+ extra_instructions: str = "",
101
+ enabled_sources: Optional[list[str]] = None,
102
+ ) -> Path:
103
+ corpus = _build_corpus(username, notebook_id, enabled_sources)
104
+ if not corpus.strip():
105
+ raise ValueError("No source content available to generate a report.")
106
+
107
+ extra = f"\nAdditional focus: {extra_instructions}" if extra_instructions else ""
108
+ prompt = _REPORT_PROMPT.format(corpus=corpus[:12000], extra_instructions=extra)
109
+ md = _llm(prompt, system=_REPORT_SYSTEM, max_tokens=2500)
110
+ path = storage.save_artifact(username, notebook_id, "reports", md, "md")
111
+ return path
112
+
113
+
114
+ # ---------------------------------------------------------------------------
115
+ # Quiz
116
+ # ---------------------------------------------------------------------------
117
+
118
+ _QUIZ_SYSTEM = """\
119
+ You are an expert educator. Create rigorous, thoughtful multiple-choice quizzes
120
+ from academic source material. Each question must have exactly 4 options (A-D)
121
+ and one correct answer. Include an answer key at the end."""
122
+
123
+ _QUIZ_PROMPT = """\
124
+ Based on the following source material, create a 10-question multiple-choice quiz.
125
+ {extra_instructions}
126
+
127
+ --- SOURCES ---
128
+ {corpus}
129
+ --- END SOURCES ---
130
+
131
+ Format each question as:
132
+ **Q1. [Question text]**
133
+ A) [Option]
134
+ B) [Option]
135
+ C) [Option]
136
+ D) [Option]
137
 
138
+ After all questions, add:
139
+ ## Answer Key
140
+ Q1: [Letter] - [Brief explanation]
141
+ ...
142
 
143
+ Use Markdown formatting."""
144
+
145
+
146
+ def generate_quiz(
147
+ username: str,
148
+ notebook_id: str,
149
+ extra_instructions: str = "",
150
+ enabled_sources: Optional[list[str]] = None,
151
+ ) -> Path:
152
+ corpus = _build_corpus(username, notebook_id, enabled_sources)
153
+ if not corpus.strip():
154
+ raise ValueError("No source content available to generate a quiz.")
155
+
156
+ extra = f"\nFocus: {extra_instructions}" if extra_instructions else ""
157
+ prompt = _QUIZ_PROMPT.format(corpus=corpus[:12000], extra_instructions=extra)
158
+ md = _llm(prompt, system=_QUIZ_SYSTEM, max_tokens=2500)
159
+ path = storage.save_artifact(username, notebook_id, "quizzes", md, "md")
160
+ return path
161
+
162
+
163
+ # ---------------------------------------------------------------------------
164
+ # Podcast transcript (single host or two-host dialogue)
165
+ # ---------------------------------------------------------------------------
166
+
167
+ _PODCAST_SYSTEM_SINGLE = """\
168
+ You are a scriptwriter for an educational podcast. Write engaging, conversational
169
+ scripts in the voice of a single knowledgeable host who explains complex topics
170
+ clearly to a general audience."""
171
+
172
+ _PODCAST_SYSTEM_DUAL = """\
173
+ You are a scriptwriter for an educational podcast with two hosts:
174
+ - HOST_A: Alex — enthusiastic, asks clarifying questions
175
+ - HOST_B: Jordan — the expert, provides detailed explanations
176
+
177
+ Write natural dialogue where they discuss the topic together."""
178
+
179
+ _PODCAST_PROMPT = """\
180
+ Write a {duration}-minute podcast {style} about the following source material.
181
+ {extra_instructions}
182
+
183
+ --- SOURCES ---
184
+ {corpus}
185
+ --- END SOURCES ---
186
+
187
+ The podcast should:
188
+ - Have a clear intro, main discussion, and outro
189
+ - Be engaging and accessible to a general audience
190
+ - Cover the most important points from the sources
191
+ - Sound natural when read aloud
192
+
193
+ {format_hint}"""
194
+
195
+
196
+ def generate_podcast_transcript(
197
+ username: str,
198
+ notebook_id: str,
199
+ duration_minutes: int = 5,
200
+ two_hosts: bool = False,
201
+ extra_instructions: str = "",
202
+ enabled_sources: Optional[list[str]] = None,
203
+ ) -> Path:
204
+ corpus = _build_corpus(username, notebook_id, enabled_sources)
205
+ if not corpus.strip():
206
+ raise ValueError("No source content available to generate a podcast.")
207
+
208
+ style = "dialogue between two hosts (Alex and Jordan)" if two_hosts else "monologue"
209
+ fmt_hint = (
210
+ "Format each line as:\nALEX: [speech]\nJORDAN: [speech]"
211
+ if two_hosts
212
+ else "Write as continuous narrative prose."
213
  )
214
+ system = _PODCAST_SYSTEM_DUAL if two_hosts else _PODCAST_SYSTEM_SINGLE
215
+ extra = f"\nAdditional focus: {extra_instructions}" if extra_instructions else ""
216
+
217
+ prompt = _PODCAST_PROMPT.format(
218
+ duration=duration_minutes,
219
+ style=style,
220
+ corpus=corpus[:10000],
221
+ extra_instructions=extra,
222
+ format_hint=fmt_hint,
223
+ )
224
+ transcript = _llm(prompt, system=system, max_tokens=3000, temperature=0.6)
225
+ path = storage.save_artifact(username, notebook_id, "podcasts", transcript, "md")
226
+ return path
227
+
228
+
229
+ # ---------------------------------------------------------------------------
230
+ # Podcast audio generation (TTS)
231
+ # ---------------------------------------------------------------------------
232
+
233
+ def generate_podcast_audio(
234
+ username: str,
235
+ notebook_id: str,
236
+ transcript_path: Path,
237
+ two_hosts: bool = False,
238
+ ) -> Path:
239
+ """
240
+ Convert a podcast transcript to MP3 audio using OpenAI TTS.
241
+ For two-host scripts, alternate voices per speaker line.
242
+ Single-host scripts use one voice for the full text.
243
+ """
244
+ client = _get_client()
245
+ transcript = transcript_path.read_text(encoding="utf-8", errors="ignore")
246
+
247
+ if two_hosts:
248
+ audio_segments = _tts_two_hosts(client, transcript)
249
+ else:
250
+ audio_segments = [_tts_single(client, transcript, voice="alloy")]
251
+
252
+ # Concatenate all PCM/MP3 segments
253
+ combined = b"".join(audio_segments)
254
+ path = storage.save_artifact(username, notebook_id, "podcasts", combined, "mp3")
255
+ return path
256
+
257
+
258
+ def _clean_for_tts(text: str) -> str:
259
+ """Strip markdown formatting that sounds bad when spoken."""
260
+ text = re.sub(r'\*+', '', text) # bold/italic
261
+ text = re.sub(r'#+\s*', '', text) # headings
262
+ text = re.sub(r'\[.*?\]\(.*?\)', '', text) # links
263
+ text = re.sub(r'`+', '', text) # code ticks
264
+ text = re.sub(r'\n{2,}', '\n', text) # extra newlines
265
+ return text.strip()
266
+
267
+
268
+ def _tts_single(client: OpenAI, text: str, voice: str = "alloy") -> bytes:
269
+ clean = _clean_for_tts(text)
270
+ # OpenAI TTS has a ~4096 char limit per request — chunk if needed
271
+ chunks = [clean[i:i+4000] for i in range(0, len(clean), 4000)]
272
+ audio = b""
273
+ for chunk in chunks:
274
+ resp = client.audio.speech.create(
275
+ model=TTS_MODEL,
276
+ voice=voice,
277
+ input=chunk,
278
+ response_format="mp3",
279
+ )
280
+ audio += resp.content
281
+ return audio
282
+
283
+
284
+ def _tts_two_hosts(client: OpenAI, transcript: str) -> list[bytes]:
285
+ """Parse ALEX/JORDAN lines and assign different TTS voices."""
286
+ lines = transcript.splitlines()
287
+ segments = []
288
+ voice_map = {"ALEX": "alloy", "JORDAN": "nova"}
289
+
290
+ for line in lines:
291
+ line = line.strip()
292
+ if not line:
293
+ continue
294
+ for speaker, voice in voice_map.items():
295
+ if line.upper().startswith(f"{speaker}:"):
296
+ speech = line[len(speaker) + 1:].strip()
297
+ if speech:
298
+ segments.append(_tts_single(client, speech, voice=voice))
299
+ break
300
+ else:
301
+ # Narrator or untagged line — use default voice
302
+ if line:
303
+ segments.append(_tts_single(client, line, voice="alloy"))
304
+
305
+ return segments
backend/chat.py CHANGED
@@ -1,30 +1,217 @@
1
- from backend.retrieval import get_retriever
 
 
 
2
 
3
- # from openai import OpenAI
4
- # client = OpenAI()
 
 
 
 
 
5
 
6
- def chat_with_sources(message: str, nb_id: str, history: list) -> str:
7
- retrieve = get_retriever(nb_id)
8
- chunks, metas = retrieve(message)
9
- context = "\n\n".join(chunks)
10
- citations = ", ".join(
11
- f"[Source: {m.get('source','?')} chunk {m.get('chunk','?')}]" for m in metas
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- # TODO: Replace stub with real OpenAI call
15
- # system_prompt = (
16
- # "You are a helpful research assistant. Answer using ONLY the context below. "
17
- # "Cite sources inline.\n\nContext:\n" + context
18
- # )
19
- # response = client.chat.completions.create(
20
- # model="gpt-4o",
21
- # messages=[
22
- # {"role": "system", "content": system_prompt},
23
- # *[{"role": "user" if i%2==0 else "assistant", "content": c}
24
- # for i, (_, c) in enumerate(history)],
25
- # {"role": "user", "content": message},
26
- # ]
27
- # )
28
- # return response.choices[0].message.content + "\n\n" + citations
29
-
30
- return f"[STUB] Answer to: '{message}'\n\nSources: {citations}"
 
1
+ """
2
+ chat.py
3
+ -------
4
+ RAG-powered chat with citation support.
5
 
6
+ Flow:
7
+ 1. Retrieve relevant chunks via `retrieval.retrieve()`
8
+ 2. Build a system prompt grounding the LLM in those chunks
9
+ 3. Call the LLM with full conversation history
10
+ 4. Parse citations from the response
11
+ 5. Persist the exchange to storage
12
+ """
13
 
14
+ import os
15
+ import re
16
+ from typing import Generator, Optional
17
+
18
+ from openai import OpenAI
19
+
20
+ from backend import storage
21
+ from backend.retrieval import RetrievalTechnique, build_context_string, retrieve
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Config
25
+ # ---------------------------------------------------------------------------
26
+
27
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
28
+ LLM_MODEL = os.getenv("LLM_MODEL", "gpt-4o-mini")
29
+ MAX_HISTORY_TURNS = int(os.getenv("MAX_HISTORY_TURNS", "10"))
30
+
31
+ _client: Optional[OpenAI] = None
32
+
33
+
34
+ def _get_client() -> OpenAI:
35
+ global _client
36
+ if _client is None:
37
+ _client = OpenAI(api_key=OPENAI_API_KEY)
38
+ return _client
39
+
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # System prompt builder
43
+ # ---------------------------------------------------------------------------
44
+
45
+ _SYSTEM_TEMPLATE = """\
46
+ You are a helpful research assistant. The user has provided source documents for context.
47
+ Use the source excerpts below to inform your answers. When you reference specific information
48
+ from a source, cite it inline using its label exactly as shown, e.g. [Source 1: filename.pdf].
49
+
50
+ You may use your own knowledge to analyze, interpret, or give advice about the source content.
51
+ For example, if asked to improve a resume, analyze what is in the sources and provide actionable advice.
52
+
53
+ If the sources contain no relevant information at all, say so clearly.
54
+
55
+ --- SOURCE EXCERPTS ---
56
+ {context}
57
+ --- END OF SOURCES ---
58
+
59
+ Guidelines:
60
+ - Be helpful, specific, and actionable.
61
+ - Cite sources when referencing specific content from them.
62
+ - For analytical or improvement questions, use the source content as input and apply your expertise.
63
+ """
64
+
65
+
66
+ def _build_system_prompt(context: str) -> str:
67
+ return _SYSTEM_TEMPLATE.format(context=context)
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # Chat function (non-streaming)
72
+ # ---------------------------------------------------------------------------
73
+
74
+ def chat(
75
+ username: str,
76
+ notebook_id: str,
77
+ user_message: str,
78
+ technique: RetrievalTechnique = "recursive",
79
+ enabled_sources: Optional[list[str]] = None,
80
+ k: int = 5,
81
+ ) -> dict:
82
+ """
83
+ Send a message and get a cited response.
84
+
85
+ Returns:
86
+ {
87
+ "answer": str,
88
+ "citations": list[str],
89
+ "chunks": list[RetrievedChunk],
90
+ "retrieval_time_s": float,
91
+ "technique": str,
92
+ }
93
+ """
94
+ # 1. Retrieve
95
+ chunks, retrieval_time = retrieve(
96
+ username, notebook_id, user_message, technique=technique,
97
+ k=k, enabled_sources=enabled_sources
98
+ )
99
+ context, citation_labels = build_context_string(chunks)
100
+
101
+ # 2. Load history (last N turns)
102
+ history = storage.load_chat_history(username, notebook_id)
103
+ recent = history[-(MAX_HISTORY_TURNS * 2):] # each turn = 2 messages
104
+
105
+ messages = [{"role": "system", "content": _build_system_prompt(context)}]
106
+ for msg in recent:
107
+ if msg["role"] in ("user", "assistant"):
108
+ messages.append({"role": msg["role"], "content": msg["content"]})
109
+ messages.append({"role": "user", "content": user_message})
110
+
111
+ # 3. LLM call
112
+ client = _get_client()
113
+ response = client.chat.completions.create(
114
+ model=LLM_MODEL,
115
+ messages=messages,
116
+ temperature=0.2,
117
+ max_tokens=1024,
118
+ )
119
+ answer = response.choices[0].message.content.strip()
120
+
121
+ # 4. Extract cited source labels mentioned in the answer
122
+ cited = list(set(re.findall(r'\[Source \d+:[^\]]+\]', answer)))
123
+
124
+ # 5. Persist
125
+ storage.append_message(username, notebook_id, "user", user_message)
126
+ storage.append_message(
127
+ username, notebook_id, "assistant", answer,
128
+ metadata={"citations": cited, "technique": technique, "retrieval_time_s": retrieval_time}
129
+ )
130
+
131
+ return {
132
+ "answer": answer,
133
+ "citations": cited,
134
+ "chunks": chunks,
135
+ "retrieval_time_s": retrieval_time,
136
+ "technique": technique,
137
+ }
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # Streaming version
142
+ # ---------------------------------------------------------------------------
143
+
144
+ def chat_stream(
145
+ username: str,
146
+ notebook_id: str,
147
+ user_message: str,
148
+ technique: RetrievalTechnique = "recursive",
149
+ enabled_sources: Optional[list[str]] = None,
150
+ k: int = 5,
151
+ ) -> Generator[str, None, dict]:
152
+ """
153
+ Generator that yields answer tokens one by one for live streaming.
154
+ After exhausting the generator, call .send(None) or just iterate —
155
+ the final yielded item is a sentinel dict with metadata.
156
+ """
157
+ chunks, retrieval_time = retrieve(
158
+ username, notebook_id, user_message, technique=technique,
159
+ k=k, enabled_sources=enabled_sources
160
  )
161
+ context, _ = build_context_string(chunks)
162
+
163
+ history = storage.load_chat_history(username, notebook_id)
164
+ recent = history[-(MAX_HISTORY_TURNS * 2):]
165
+
166
+ messages = [{"role": "system", "content": _build_system_prompt(context)}]
167
+ for msg in recent:
168
+ if msg["role"] in ("user", "assistant"):
169
+ messages.append({"role": msg["role"], "content": msg["content"]})
170
+ messages.append({"role": "user", "content": user_message})
171
+
172
+ client = _get_client()
173
+ stream = client.chat.completions.create(
174
+ model=LLM_MODEL,
175
+ messages=messages,
176
+ temperature=0.2,
177
+ max_tokens=1024,
178
+ stream=True,
179
+ )
180
+
181
+ full_answer = ""
182
+ for chunk in stream:
183
+ delta = chunk.choices[0].delta.content or ""
184
+ full_answer += delta
185
+ yield delta
186
+
187
+ cited = list(set(re.findall(r'\[Source \d+:[^\]]+\]', full_answer)))
188
+ storage.append_message(username, notebook_id, "user", user_message)
189
+ storage.append_message(
190
+ username, notebook_id, "assistant", full_answer,
191
+ metadata={"citations": cited, "technique": technique, "retrieval_time_s": retrieval_time}
192
+ )
193
+
194
+ # Final metadata yield
195
+ yield {
196
+ "done": True,
197
+ "citations": cited,
198
+ "chunks": chunks,
199
+ "retrieval_time_s": retrieval_time,
200
+ }
201
+
202
+
203
+ # ---------------------------------------------------------------------------
204
+ # Gradio-compatible history formatter
205
+ # ---------------------------------------------------------------------------
206
 
207
+ def load_gradio_history(username: str, notebook_id: str) -> list[dict]:
208
+ """
209
+ Convert stored JSONL messages into Gradio 6.0 chatbot format:
210
+ [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}, ...]
211
+ """
212
+ messages = storage.load_chat_history(username, notebook_id)
213
+ return [
214
+ {"role": msg["role"], "content": msg["content"]}
215
+ for msg in messages
216
+ if msg["role"] in ("user", "assistant")
217
+ ]
 
 
 
 
 
 
backend/ingest.py DELETED
@@ -1,90 +0,0 @@
1
- import uuid
2
- from pathlib import Path
3
-
4
- # Uncomment these once you run: pip install -r requirements.txt
5
- # from PyPDF2 import PdfReader
6
- # from pptx import Presentation
7
- # import requests
8
- # from bs4 import BeautifulSoup
9
- # import chromadb
10
-
11
- DATA_DIR = Path("data/users")
12
-
13
-
14
- def get_notebook_dir(nb_id: str) -> Path:
15
- path = DATA_DIR / "default" / "notebooks" / nb_id
16
- path.mkdir(parents=True, exist_ok=True)
17
- return path
18
-
19
-
20
- def chunk_text(text: str, chunk_size: int = 500, overlap: int = 50) -> list:
21
- """Split text into overlapping chunks."""
22
- words = text.split()
23
- chunks = []
24
- for i in range(0, len(words), chunk_size - overlap):
25
- chunk = " ".join(words[i : i + chunk_size])
26
- if chunk:
27
- chunks.append(chunk)
28
- return chunks
29
-
30
-
31
- def embed_and_store(chunks: list, source_name: str, nb_id: str):
32
- """Embed chunks and store in ChromaDB."""
33
- # TODO: Uncomment when ChromaDB + OpenAI are configured
34
- # client = chromadb.PersistentClient(path=str(get_notebook_dir(nb_id) / "chroma"))
35
- # collection = client.get_or_create_collection("sources")
36
- # collection.add(
37
- # documents=chunks,
38
- # metadatas=[{"source": source_name, "chunk": i} for i in range(len(chunks))],
39
- # ids=[str(uuid.uuid4()) for _ in chunks],
40
- # )
41
- print(f"[STUB] Would embed {len(chunks)} chunks from {source_name}")
42
-
43
-
44
- def extract_pdf(filepath: str) -> str:
45
- """Extract text from a PDF file."""
46
- # reader = PdfReader(filepath)
47
- # return "\n".join(page.extract_text() or "" for page in reader.pages)
48
- return f"[STUB] Extracted text from PDF: {filepath}"
49
-
50
-
51
- def extract_pptx(filepath: str) -> str:
52
- """Extract text from a PPTX file."""
53
- # prs = Presentation(filepath)
54
- # texts = [shape.text for slide in prs.slides for shape in slide.shapes if hasattr(shape, "text")]
55
- # return "\n".join(texts)
56
- return f"[STUB] Extracted text from PPTX: {filepath}"
57
-
58
-
59
- def extract_txt(filepath: str) -> str:
60
- """Read plain text file."""
61
- with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
62
- return f.read()
63
-
64
-
65
- def ingest_file(filepath: str, nb_id: str) -> str:
66
- """Ingest a file into the notebook vector store."""
67
- ext = Path(filepath).suffix.lower()
68
- if ext == ".pdf":
69
- text = extract_pdf(filepath)
70
- elif ext == ".pptx":
71
- text = extract_pptx(filepath)
72
- elif ext == ".txt":
73
- text = extract_txt(filepath)
74
- else:
75
- return f"Unsupported file type: {ext}"
76
-
77
- chunks = chunk_text(text)
78
- embed_and_store(chunks, Path(filepath).name, nb_id)
79
- return f"Ingested {Path(filepath).name} ({len(chunks)} chunks)"
80
-
81
-
82
- def ingest_url(url: str, nb_id: str) -> str:
83
- """Fetch and ingest a web page."""
84
- # response = requests.get(url, timeout=10)
85
- # soup = BeautifulSoup(response.text, "html.parser")
86
- # text = soup.get_text(separator=" ", strip=True)
87
- text = f"[STUB] Fetched content from {url}"
88
- chunks = chunk_text(text)
89
- embed_and_store(chunks, url, nb_id)
90
- return f"Ingested URL: {url} ({len(chunks)} chunks)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/ingestion.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ingestion.py
3
+ ------------
4
+ Ingestion pipeline: extract text from PDF / PPTX / TXT / URL,
5
+ chunk the text, embed it, and store it in a per-notebook ChromaDB collection.
6
+
7
+ Chunking strategies available:
8
+ - "fixed" : fixed token-count windows with overlap
9
+ - "sentence" : sentence-boundary-aware sliding window
10
+ - "recursive" : recursive character splitter (LangChain-style)
11
+
12
+ Usage:
13
+ result = ingest_source(username, notebook_id, source_path_or_url)
14
+ """
15
+
16
+ import hashlib
17
+ import re
18
+ import os
19
+ from pathlib import Path
20
+ from typing import Literal, Optional
21
+ from urllib.parse import urlparse
22
+
23
+ import chromadb
24
+ from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
25
+
26
+ from backend import storage
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Config
30
+ # ---------------------------------------------------------------------------
31
+
32
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
33
+ CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "800")) # tokens / chars
34
+ CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "150"))
35
+ EMBED_MODEL = os.getenv("EMBED_MODEL", "text-embedding-3-small")
36
+ ChunkStrategy = Literal["fixed", "sentence", "recursive"]
37
+ DEFAULT_CHUNK_STRATEGY: ChunkStrategy = "recursive"
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Embedding function
42
+ # ---------------------------------------------------------------------------
43
+
44
+ def _get_embedding_fn():
45
+ return OpenAIEmbeddingFunction(
46
+ api_key=OPENAI_API_KEY,
47
+ model_name=EMBED_MODEL,
48
+ )
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # ChromaDB helpers
53
+ # ---------------------------------------------------------------------------
54
+
55
+ def _get_collection(username: str, notebook_id: str):
56
+ chroma_path = storage.get_chroma_path(username, notebook_id)
57
+ client = chromadb.PersistentClient(path=chroma_path)
58
+ collection = client.get_or_create_collection(
59
+ name="sources",
60
+ embedding_function=_get_embedding_fn(),
61
+ metadata={"hnsw:space": "cosine"},
62
+ )
63
+ return collection
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Text extraction
68
+ # ---------------------------------------------------------------------------
69
+
70
+ def extract_text_from_pdf(file_path: str | Path) -> str:
71
+ """Extract text from a PDF using pdfplumber."""
72
+ import pdfplumber
73
+ texts = []
74
+ with pdfplumber.open(str(file_path)) as pdf:
75
+ for page in pdf.pages:
76
+ t = page.extract_text()
77
+ if t:
78
+ texts.append(t)
79
+ return "\n\n".join(texts)
80
+
81
+
82
+ def extract_text_from_pptx(file_path: str | Path) -> str:
83
+ """Extract text from a PowerPoint file."""
84
+ from pptx import Presentation
85
+ prs = Presentation(str(file_path))
86
+ texts = []
87
+ for slide_num, slide in enumerate(prs.slides, start=1):
88
+ slide_texts = [f"[Slide {slide_num}]"]
89
+ for shape in slide.shapes:
90
+ if shape.has_text_frame:
91
+ for para in shape.text_frame.paragraphs:
92
+ line = para.text.strip()
93
+ if line:
94
+ slide_texts.append(line)
95
+ texts.append("\n".join(slide_texts))
96
+ return "\n\n".join(texts)
97
+
98
+
99
+ def extract_text_from_url(url: str) -> str:
100
+ """Extract readable text from a web URL using trafilatura."""
101
+ import trafilatura
102
+ downloaded = trafilatura.fetch_url(url)
103
+ if downloaded is None:
104
+ raise ValueError(f"Could not fetch URL: {url}")
105
+ text = trafilatura.extract(downloaded, include_links=False, include_tables=True)
106
+ if not text:
107
+ raise ValueError(f"No readable text found at URL: {url}")
108
+ return text
109
+
110
+
111
+ def extract_text(source: str | Path) -> tuple[str, str]:
112
+ """
113
+ Dispatch extraction based on source type.
114
+ Returns (text, source_name).
115
+ """
116
+ src = str(source)
117
+ parsed = urlparse(src)
118
+ if parsed.scheme in ("http", "https"):
119
+ text = extract_text_from_url(src)
120
+ name = parsed.netloc + parsed.path.replace("/", "_")
121
+ return text, name
122
+
123
+ p = Path(src)
124
+ suffix = p.suffix.lower()
125
+ if suffix == ".pdf":
126
+ return extract_text_from_pdf(p), p.name
127
+ elif suffix in (".pptx", ".ppt"):
128
+ return extract_text_from_pptx(p), p.name
129
+ elif suffix in (".txt", ".md"):
130
+ return p.read_text(encoding="utf-8", errors="ignore"), p.name
131
+ else:
132
+ raise ValueError(f"Unsupported file type: {suffix}")
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # Chunking strategies
137
+ # ---------------------------------------------------------------------------
138
+
139
+ def _fixed_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
140
+ """Split on character count with overlap."""
141
+ chunks, start = [], 0
142
+ while start < len(text):
143
+ end = start + size
144
+ chunks.append(text[start:end])
145
+ start += size - overlap
146
+ return [c.strip() for c in chunks if c.strip()]
147
+
148
+
149
+ def _sentence_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
150
+ """Split on sentence boundaries, then group into windows."""
151
+ sentences = re.split(r'(?<=[.!?])\s+', text)
152
+ chunks, current, current_len = [], [], 0
153
+ for sent in sentences:
154
+ slen = len(sent)
155
+ if current_len + slen > size and current:
156
+ chunks.append(" ".join(current))
157
+ # keep overlap sentences
158
+ overlap_sents = []
159
+ ol = 0
160
+ for s in reversed(current):
161
+ ol += len(s)
162
+ overlap_sents.insert(0, s)
163
+ if ol >= overlap:
164
+ break
165
+ current = overlap_sents
166
+ current_len = sum(len(s) for s in current)
167
+ current.append(sent)
168
+ current_len += slen
169
+ if current:
170
+ chunks.append(" ".join(current))
171
+ return [c.strip() for c in chunks if c.strip()]
172
+
173
+
174
+ def _recursive_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
175
+ """
176
+ Recursive character splitter — tries paragraph, then sentence,
177
+ then word boundaries before hard-splitting.
178
+ """
179
+ separators = ["\n\n", "\n", ". ", " ", ""]
180
+
181
+ def _split(t: str, seps: list[str]) -> list[str]:
182
+ if len(t) <= size:
183
+ return [t] if t.strip() else []
184
+ if not seps:
185
+ return _fixed_chunks(t, size, overlap)
186
+
187
+ sep = seps[0]
188
+ parts = t.split(sep)
189
+ chunks, current = [], ""
190
+ for part in parts:
191
+ candidate = current + (sep if current else "") + part
192
+ if len(candidate) <= size:
193
+ current = candidate
194
+ else:
195
+ if current:
196
+ chunks.extend(_split(current, seps[1:]))
197
+ current = part
198
+ if current:
199
+ chunks.extend(_split(current, seps[1:]))
200
+ return chunks
201
+
202
+ raw = _split(text, separators)
203
+ # Add overlap between adjacent chunks
204
+ result = []
205
+ for i, chunk in enumerate(raw):
206
+ if i > 0 and overlap > 0:
207
+ prev_tail = raw[i - 1][-overlap:]
208
+ chunk = prev_tail + " " + chunk
209
+ result.append(chunk.strip())
210
+ return [c for c in result if c]
211
+
212
+
213
+ def chunk_text(text: str, strategy: ChunkStrategy = DEFAULT_CHUNK_STRATEGY) -> list[str]:
214
+ if strategy == "fixed":
215
+ return _fixed_chunks(text)
216
+ elif strategy == "sentence":
217
+ return _sentence_chunks(text)
218
+ else:
219
+ return _recursive_chunks(text)
220
+
221
+
222
+ # ---------------------------------------------------------------------------
223
+ # Main ingest function
224
+ # ---------------------------------------------------------------------------
225
+
226
+ def ingest_source(
227
+ username: str,
228
+ notebook_id: str,
229
+ source: str | Path,
230
+ chunk_strategy: ChunkStrategy = DEFAULT_CHUNK_STRATEGY,
231
+ raw_bytes: Optional[bytes] = None,
232
+ ) -> dict:
233
+ """
234
+ Full ingestion pipeline for one source.
235
+ Returns a summary dict with stats.
236
+ """
237
+ # 1. Extract text
238
+ text, source_name = extract_text(source)
239
+
240
+ # 2. Persist raw file (if bytes provided, i.e. an upload)
241
+ if raw_bytes is not None:
242
+ storage.save_raw_file(username, notebook_id, source_name, raw_bytes)
243
+
244
+ # 3. Persist extracted text
245
+ storage.save_extracted_text(username, notebook_id, source_name, text)
246
+
247
+ # 4. Chunk
248
+ chunks = chunk_text(text, strategy=chunk_strategy)
249
+
250
+ # 5. Build IDs and metadata
251
+ ids, documents, metadatas = [], [], []
252
+ for i, chunk in enumerate(chunks):
253
+ chunk_id = hashlib.md5(f"{source_name}_{i}_{chunk[:40]}".encode()).hexdigest()
254
+ ids.append(chunk_id)
255
+ documents.append(chunk)
256
+ metadatas.append({
257
+ "source": source_name,
258
+ "chunk_index": i,
259
+ "total_chunks": len(chunks),
260
+ "strategy": chunk_strategy,
261
+ })
262
+
263
+ # 6. Upsert into ChromaDB
264
+ collection = _get_collection(username, notebook_id)
265
+ # Batch upsert in groups of 100 to avoid request-size limits
266
+ batch_size = 100
267
+ for start in range(0, len(ids), batch_size):
268
+ end = start + batch_size
269
+ collection.upsert(
270
+ ids=ids[start:end],
271
+ documents=documents[start:end],
272
+ metadatas=metadatas[start:end],
273
+ )
274
+
275
+ return {
276
+ "source_name": source_name,
277
+ "char_count": len(text),
278
+ "chunk_count": len(chunks),
279
+ "strategy": chunk_strategy,
280
+ }
281
+
282
+
283
+ def delete_source(username: str, notebook_id: str, source_name: str) -> int:
284
+ """Remove all chunks for a source from the vector store. Returns deleted count."""
285
+ collection = _get_collection(username, notebook_id)
286
+ results = collection.get(where={"source": source_name})
287
+ if results and results["ids"]:
288
+ collection.delete(ids=results["ids"])
289
+ return len(results["ids"])
290
+ return 0
291
+
292
+
293
+ def list_indexed_sources(username: str, notebook_id: str) -> list[str]:
294
+ """Return unique source names currently indexed in ChromaDB."""
295
+ collection = _get_collection(username, notebook_id)
296
+ results = collection.get(include=["metadatas"])
297
+ sources = {m["source"] for m in results["metadatas"]} if results["metadatas"] else set()
298
+ return sorted(sources)
backend/retrieval.py CHANGED
@@ -1,4 +1,370 @@
1
- def get_retriever(nb_id, top_k=5):
2
- def retrieve(query):
3
- return ["[STUB] chunk for: " + query], [{"source": "stub.pdf", "chunk": 0}]
4
- return retrieve
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ retrieval.py
3
+ ------------
4
+ Retrieval-Augmented Generation (RAG) module.
5
+
6
+ Supported retrieval techniques:
7
+ 1. naive — Basic top-k cosine similarity
8
+ 2. mmr — Maximal Marginal Relevance (diversity-aware)
9
+ 3. hyde — Hypothetical Document Embeddings (HyDE)
10
+ 4. rerank — Retrieve wide, then rerank with cross-encoder
11
+
12
+ Each technique returns a list of RetrievedChunk objects containing
13
+ the text and source metadata needed for citation.
14
+ """
15
+
16
+ import os
17
+ import time
18
+ from dataclasses import dataclass, field
19
+ from typing import Literal, Optional
20
+
21
+ import chromadb
22
+ from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
23
+ from openai import OpenAI
24
+
25
+ from backend import storage
26
+
27
+ # ---------------------------------------------------------------------------
28
+ # Config
29
+ # ---------------------------------------------------------------------------
30
+
31
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
32
+ EMBED_MODEL = os.getenv("EMBED_MODEL", "text-embedding-3-small")
33
+ LLM_MODEL = os.getenv("LLM_MODEL", "gpt-4o-mini")
34
+ TOP_K = int(os.getenv("TOP_K", "5"))
35
+ MMR_LAMBDA = float(os.getenv("MMR_LAMBDA", "0.7")) # 0=max diversity, 1=max relevance
36
+
37
+ RetrievalTechnique = Literal["naive", "mmr", "hyde", "rerank"]
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Data class
42
+ # ---------------------------------------------------------------------------
43
+
44
+ @dataclass
45
+ class RetrievedChunk:
46
+ text: str
47
+ source: str
48
+ chunk_index: int
49
+ score: float
50
+ technique: str
51
+ metadata: dict = field(default_factory=dict)
52
+
53
+ def citation_label(self) -> str:
54
+ return f"[{self.source}, chunk {self.chunk_index}]"
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Shared helpers
59
+ # ---------------------------------------------------------------------------
60
+
61
+ _openai_client: Optional[OpenAI] = None
62
+
63
+
64
+ def _get_client() -> OpenAI:
65
+ global _openai_client
66
+ if _openai_client is None:
67
+ _openai_client = OpenAI(api_key=OPENAI_API_KEY)
68
+ return _openai_client
69
+
70
+
71
+ def _embed(texts: list[str]) -> list[list[float]]:
72
+ client = _get_client()
73
+ response = client.embeddings.create(model=EMBED_MODEL, input=texts)
74
+ return [item.embedding for item in response.data]
75
+
76
+
77
+ def _get_collection(username: str, notebook_id: str):
78
+ chroma_path = storage.get_chroma_path(username, notebook_id)
79
+ client = chromadb.PersistentClient(path=chroma_path)
80
+ ef = OpenAIEmbeddingFunction(api_key=OPENAI_API_KEY, model_name=EMBED_MODEL)
81
+ return client.get_or_create_collection(
82
+ name="sources",
83
+ embedding_function=ef,
84
+ metadata={"hnsw:space": "cosine"},
85
+ )
86
+
87
+
88
+ def _chroma_results_to_chunks(results: dict, technique: str) -> list[RetrievedChunk]:
89
+ chunks = []
90
+ if not results or not results.get("ids") or not results["ids"][0]:
91
+ return chunks
92
+ ids = results["ids"][0]
93
+ documents = results["documents"][0]
94
+ metadatas = results["metadatas"][0]
95
+ distances = results.get("distances", [[0.0] * len(ids)])[0]
96
+
97
+ for doc, meta, dist in zip(documents, metadatas, distances):
98
+ chunks.append(RetrievedChunk(
99
+ text=doc,
100
+ source=meta.get("source", "unknown"),
101
+ chunk_index=meta.get("chunk_index", 0),
102
+ score=1.0 - dist, # cosine similarity
103
+ technique=technique,
104
+ metadata=meta,
105
+ ))
106
+ return chunks
107
+
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Retrieval technique 1: Naive top-k
111
+ # ---------------------------------------------------------------------------
112
+
113
+ def retrieve_naive(
114
+ username: str,
115
+ notebook_id: str,
116
+ query: str,
117
+ k: int = TOP_K,
118
+ enabled_sources: Optional[list[str]] = None,
119
+ ) -> tuple[list[RetrievedChunk], float]:
120
+ """Basic dense retrieval — fastest, simplest baseline."""
121
+ t0 = time.perf_counter()
122
+ collection = _get_collection(username, notebook_id)
123
+ where = {"source": {"$in": enabled_sources}} if enabled_sources else None
124
+ results = collection.query(
125
+ query_texts=[query],
126
+ n_results=k,
127
+ where=where,
128
+ include=["documents", "metadatas", "distances"],
129
+ )
130
+ elapsed = time.perf_counter() - t0
131
+ return _chroma_results_to_chunks(results, "naive"), elapsed
132
+
133
+
134
+ # ---------------------------------------------------------------------------
135
+ # Retrieval technique 2: Maximal Marginal Relevance (MMR)
136
+ # ---------------------------------------------------------------------------
137
+
138
+ def _cosine_sim(a: list[float], b: list[float]) -> float:
139
+ import math
140
+ dot = sum(x * y for x, y in zip(a, b))
141
+ na = math.sqrt(sum(x * x for x in a))
142
+ nb = math.sqrt(sum(y * y for y in b))
143
+ if na == 0 or nb == 0:
144
+ return 0.0
145
+ return dot / (na * nb)
146
+
147
+
148
+ def retrieve_mmr(
149
+ username: str,
150
+ notebook_id: str,
151
+ query: str,
152
+ k: int = TOP_K,
153
+ fetch_k: int = 20,
154
+ lam: float = MMR_LAMBDA,
155
+ enabled_sources: Optional[list[str]] = None,
156
+ ) -> tuple[list[RetrievedChunk], float]:
157
+ """
158
+ MMR: retrieve fetch_k candidates, then greedily pick k that balance
159
+ relevance to query and diversity from already-selected chunks.
160
+ """
161
+ t0 = time.perf_counter()
162
+ collection = _get_collection(username, notebook_id)
163
+ where = {"source": {"$in": enabled_sources}} if enabled_sources else None
164
+
165
+ # Get candidates with embeddings
166
+ results = collection.query(
167
+ query_texts=[query],
168
+ n_results=min(fetch_k, collection.count() or 1),
169
+ where=where,
170
+ include=["documents", "metadatas", "distances", "embeddings"],
171
+ )
172
+
173
+ if not results["ids"][0]:
174
+ return [], time.perf_counter() - t0
175
+
176
+ candidates = list(zip(
177
+ results["documents"][0],
178
+ results["metadatas"][0],
179
+ results["distances"][0],
180
+ results["embeddings"][0],
181
+ ))
182
+
183
+ # Embed query
184
+ q_emb = _embed([query])[0]
185
+
186
+ selected_idx = []
187
+ selected_embs = []
188
+
189
+ for _ in range(min(k, len(candidates))):
190
+ best_score, best_i = -1e9, -1
191
+ for i, (doc, meta, dist, emb) in enumerate(candidates):
192
+ if i in selected_idx:
193
+ continue
194
+ rel = 1.0 - dist # relevance
195
+ if selected_embs:
196
+ redundancy = max(_cosine_sim(emb, s) for s in selected_embs)
197
+ else:
198
+ redundancy = 0.0
199
+ score = lam * rel - (1 - lam) * redundancy
200
+ if score > best_score:
201
+ best_score, best_i = score, i
202
+
203
+ if best_i == -1:
204
+ break
205
+ selected_idx.append(best_i)
206
+ selected_embs.append(candidates[best_i][3])
207
+
208
+ chunks = []
209
+ for i in selected_idx:
210
+ doc, meta, dist, _ = candidates[i]
211
+ chunks.append(RetrievedChunk(
212
+ text=doc,
213
+ source=meta.get("source", "unknown"),
214
+ chunk_index=meta.get("chunk_index", 0),
215
+ score=1.0 - dist,
216
+ technique="mmr",
217
+ metadata=meta,
218
+ ))
219
+
220
+ return chunks, time.perf_counter() - t0
221
+
222
+
223
+ # ---------------------------------------------------------------------------
224
+ # Retrieval technique 3: HyDE (Hypothetical Document Embeddings)
225
+ # ---------------------------------------------------------------------------
226
+
227
+ def retrieve_hyde(
228
+ username: str,
229
+ notebook_id: str,
230
+ query: str,
231
+ k: int = TOP_K,
232
+ enabled_sources: Optional[list[str]] = None,
233
+ ) -> tuple[list[RetrievedChunk], float]:
234
+ """
235
+ HyDE: ask the LLM to generate a hypothetical answer, then use THAT
236
+ as the query embedding. Often finds more semantically relevant chunks.
237
+ """
238
+ t0 = time.perf_counter()
239
+ client = _get_client()
240
+
241
+ # Generate a short hypothetical passage
242
+ hypo_prompt = (
243
+ f"Write a concise, factual passage that would directly answer the question:\n"
244
+ f'"{query}"\n'
245
+ f"The passage should be 3-5 sentences, written as if it came from a reference document."
246
+ )
247
+ resp = client.chat.completions.create(
248
+ model=LLM_MODEL,
249
+ messages=[{"role": "user", "content": hypo_prompt}],
250
+ max_tokens=200,
251
+ temperature=0.0,
252
+ )
253
+ hypothetical_doc = resp.choices[0].message.content.strip()
254
+
255
+ # Retrieve using hypothetical document as query
256
+ collection = _get_collection(username, notebook_id)
257
+ where = {"source": {"$in": enabled_sources}} if enabled_sources else None
258
+ results = collection.query(
259
+ query_texts=[hypothetical_doc],
260
+ n_results=k,
261
+ where=where,
262
+ include=["documents", "metadatas", "distances"],
263
+ )
264
+
265
+ elapsed = time.perf_counter() - t0
266
+ chunks = _chroma_results_to_chunks(results, "hyde")
267
+ return chunks, elapsed
268
+
269
+
270
+ # ---------------------------------------------------------------------------
271
+ # Retrieval technique 4: Rerank (wide retrieval + cross-encoder scoring)
272
+ # ---------------------------------------------------------------------------
273
+
274
+ def retrieve_rerank(
275
+ username: str,
276
+ notebook_id: str,
277
+ query: str,
278
+ k: int = TOP_K,
279
+ fetch_k: int = 20,
280
+ enabled_sources: Optional[list[str]] = None,
281
+ ) -> tuple[list[RetrievedChunk], float]:
282
+ """
283
+ Two-stage retrieval: fetch_k candidates with dense search,
284
+ then rerank using an LLM-based cross-encoder scoring prompt.
285
+ Falls back gracefully if cross-encoder is slow.
286
+ """
287
+ t0 = time.perf_counter()
288
+ collection = _get_collection(username, notebook_id)
289
+ where = {"source": {"$in": enabled_sources}} if enabled_sources else None
290
+
291
+ results = collection.query(
292
+ query_texts=[query],
293
+ n_results=min(fetch_k, collection.count() or 1),
294
+ where=where,
295
+ include=["documents", "metadatas", "distances"],
296
+ )
297
+
298
+ candidates = _chroma_results_to_chunks(results, "rerank")
299
+ if not candidates:
300
+ return [], time.perf_counter() - t0
301
+
302
+ # Score each candidate with LLM relevance prompt
303
+ client = _get_client()
304
+ scored = []
305
+ for chunk in candidates:
306
+ score_prompt = (
307
+ f"On a scale of 0-10, how relevant is this passage to the query?\n"
308
+ f"Query: {query}\n"
309
+ f"Passage: {chunk.text[:400]}\n"
310
+ f"Respond with ONLY a number 0-10."
311
+ )
312
+ try:
313
+ sr = client.chat.completions.create(
314
+ model=LLM_MODEL,
315
+ messages=[{"role": "user", "content": score_prompt}],
316
+ max_tokens=5,
317
+ temperature=0.0,
318
+ )
319
+ score_str = sr.choices[0].message.content.strip()
320
+ llm_score = float(score_str.split()[0])
321
+ except Exception:
322
+ llm_score = chunk.score * 10 # fallback to cosine
323
+
324
+ chunk.score = llm_score / 10.0
325
+ scored.append(chunk)
326
+
327
+ scored.sort(key=lambda c: c.score, reverse=True)
328
+ return scored[:k], time.perf_counter() - t0
329
+
330
+
331
+ # ---------------------------------------------------------------------------
332
+ # Unified retrieval entry point
333
+ # ---------------------------------------------------------------------------
334
+
335
+ def retrieve(
336
+ username: str,
337
+ notebook_id: str,
338
+ query: str,
339
+ technique: RetrievalTechnique = "recursive",
340
+ k: int = TOP_K,
341
+ enabled_sources: Optional[list[str]] = None,
342
+ ) -> tuple[list[RetrievedChunk], float]:
343
+ """
344
+ Dispatch to the requested technique.
345
+ Returns (chunks, elapsed_seconds).
346
+ """
347
+ if technique == "naive":
348
+ return retrieve_naive(username, notebook_id, query, k, enabled_sources)
349
+ elif technique == "mmr":
350
+ return retrieve_mmr(username, notebook_id, query, k, enabled_sources=enabled_sources)
351
+ elif technique == "hyde":
352
+ return retrieve_hyde(username, notebook_id, query, k, enabled_sources)
353
+ elif technique == "rerank":
354
+ return retrieve_rerank(username, notebook_id, query, k, enabled_sources=enabled_sources)
355
+ else:
356
+ return retrieve_naive(username, notebook_id, query, k, enabled_sources)
357
+
358
+
359
+ def build_context_string(chunks: list[RetrievedChunk]) -> tuple[str, list[str]]:
360
+ """
361
+ Format retrieved chunks into a context string for the LLM,
362
+ and return a list of citation labels.
363
+ """
364
+ context_parts = []
365
+ citations = []
366
+ for i, chunk in enumerate(chunks, start=1):
367
+ label = f"[Source {i}: {chunk.source}]"
368
+ context_parts.append(f"{label}\n{chunk.text}")
369
+ citations.append(label)
370
+ return "\n\n---\n\n".join(context_parts), citations
backend/storage.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ storage.py
3
+ ----------
4
+ Storage abstraction layer for per-user, per-notebook data isolation.
5
+
6
+ Directory layout:
7
+ /data/users/<username>/notebooks/
8
+ index.json <- list of all notebooks
9
+ <notebook-uuid>/
10
+ files_raw/ <- original uploads
11
+ files_extracted/ <- plain-text extractions
12
+ chroma/ <- ChromaDB vector store
13
+ chat/messages.jsonl <- chat history
14
+ artifacts/
15
+ reports/
16
+ quizzes/
17
+ podcasts/
18
+ """
19
+
20
+ import json
21
+ import os
22
+ import shutil
23
+ import uuid
24
+ from datetime import datetime
25
+ from pathlib import Path
26
+ from typing import Optional
27
+
28
+ # Root data directory — writable on HF Spaces
29
+ DATA_ROOT = Path(os.getenv("DATA_ROOT", "/data"))
30
+
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Path helpers
34
+ # ---------------------------------------------------------------------------
35
+
36
+ def _user_root(username: str) -> Path:
37
+ return DATA_ROOT / "users" / username / "notebooks"
38
+
39
+
40
+ def _nb_root(username: str, notebook_id: str) -> Path:
41
+ return _user_root(username) / notebook_id
42
+
43
+
44
+ def _nb_index_path(username: str) -> Path:
45
+ return _user_root(username) / "index.json"
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Notebook index helpers
50
+ # ---------------------------------------------------------------------------
51
+
52
+ def _load_index(username: str) -> list[dict]:
53
+ path = _nb_index_path(username)
54
+ if not path.exists():
55
+ return []
56
+ with open(path) as f:
57
+ return json.load(f)
58
+
59
+
60
+ def _save_index(username: str, index: list[dict]) -> None:
61
+ path = _nb_index_path(username)
62
+ path.parent.mkdir(parents=True, exist_ok=True)
63
+ with open(path, "w") as f:
64
+ json.dump(index, f, indent=2)
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Public API
69
+ # ---------------------------------------------------------------------------
70
+
71
+ def list_notebooks(username: str) -> list[dict]:
72
+ """Return list of notebook metadata dicts for a user."""
73
+ return _load_index(username)
74
+
75
+
76
+ def create_notebook(username: str, name: str) -> dict:
77
+ """Create a new notebook and return its metadata."""
78
+ nb_id = str(uuid.uuid4())
79
+ nb_path = _nb_root(username, nb_id)
80
+
81
+ # Create all sub-directories
82
+ for subdir in [
83
+ "files_raw",
84
+ "files_extracted",
85
+ "chroma",
86
+ "chat",
87
+ "artifacts/reports",
88
+ "artifacts/quizzes",
89
+ "artifacts/podcasts",
90
+ ]:
91
+ (nb_path / subdir).mkdir(parents=True, exist_ok=True)
92
+
93
+ entry = {
94
+ "id": nb_id,
95
+ "name": name,
96
+ "created_at": datetime.utcnow().isoformat(),
97
+ "updated_at": datetime.utcnow().isoformat(),
98
+ }
99
+
100
+ index = _load_index(username)
101
+ index.append(entry)
102
+ _save_index(username, index)
103
+ return entry
104
+
105
+
106
+ def rename_notebook(username: str, notebook_id: str, new_name: str) -> bool:
107
+ index = _load_index(username)
108
+ for nb in index:
109
+ if nb["id"] == notebook_id:
110
+ nb["name"] = new_name
111
+ nb["updated_at"] = datetime.utcnow().isoformat()
112
+ _save_index(username, index)
113
+ return True
114
+ return False
115
+
116
+
117
+ def delete_notebook(username: str, notebook_id: str) -> bool:
118
+ index = _load_index(username)
119
+ new_index = [nb for nb in index if nb["id"] != notebook_id]
120
+ if len(new_index) == len(index):
121
+ return False
122
+ shutil.rmtree(_nb_root(username, notebook_id), ignore_errors=True)
123
+ _save_index(username, new_index)
124
+ return True
125
+
126
+
127
+ def get_notebook(username: str, notebook_id: str) -> Optional[dict]:
128
+ for nb in _load_index(username):
129
+ if nb["id"] == notebook_id:
130
+ return nb
131
+ return None
132
+
133
+
134
+ # ---------------------------------------------------------------------------
135
+ # File helpers
136
+ # ---------------------------------------------------------------------------
137
+
138
+ def save_raw_file(username: str, notebook_id: str, filename: str, data: bytes) -> Path:
139
+ dest = _nb_root(username, notebook_id) / "files_raw" / filename
140
+ dest.write_bytes(data)
141
+ _touch_notebook(username, notebook_id)
142
+ return dest
143
+
144
+
145
+ def save_extracted_text(username: str, notebook_id: str, source_name: str, text: str) -> Path:
146
+ stem = Path(source_name).stem
147
+ dest = _nb_root(username, notebook_id) / "files_extracted" / f"{stem}.txt"
148
+ dest.write_text(text, encoding="utf-8")
149
+ return dest
150
+
151
+
152
+ def list_sources(username: str, notebook_id: str) -> list[str]:
153
+ raw_dir = _nb_root(username, notebook_id) / "files_raw"
154
+ if not raw_dir.exists():
155
+ return []
156
+ return [f.name for f in raw_dir.iterdir() if f.is_file()]
157
+
158
+
159
+ def list_extracted(username: str, notebook_id: str) -> list[Path]:
160
+ ext_dir = _nb_root(username, notebook_id) / "files_extracted"
161
+ if not ext_dir.exists():
162
+ return []
163
+ return list(ext_dir.glob("*.txt"))
164
+
165
+
166
+ def get_chroma_path(username: str, notebook_id: str) -> str:
167
+ return str(_nb_root(username, notebook_id) / "chroma")
168
+
169
+
170
+ # ---------------------------------------------------------------------------
171
+ # Chat persistence
172
+ # ---------------------------------------------------------------------------
173
+
174
+ def _chat_path(username: str, notebook_id: str) -> Path:
175
+ return _nb_root(username, notebook_id) / "chat" / "messages.jsonl"
176
+
177
+
178
+ def append_message(username: str, notebook_id: str, role: str, content: str, metadata: Optional[dict] = None) -> None:
179
+ path = _chat_path(username, notebook_id)
180
+ path.parent.mkdir(parents=True, exist_ok=True)
181
+ record = {
182
+ "role": role,
183
+ "content": content,
184
+ "timestamp": datetime.utcnow().isoformat(),
185
+ **(metadata or {}),
186
+ }
187
+ with open(path, "a") as f:
188
+ f.write(json.dumps(record) + "\n")
189
+
190
+
191
+ def load_chat_history(username: str, notebook_id: str) -> list[dict]:
192
+ path = _chat_path(username, notebook_id)
193
+ if not path.exists():
194
+ return []
195
+ messages = []
196
+ with open(path) as f:
197
+ for line in f:
198
+ line = line.strip()
199
+ if line:
200
+ messages.append(json.loads(line))
201
+ return messages
202
+
203
+
204
+ def clear_chat(username: str, notebook_id: str) -> None:
205
+ path = _chat_path(username, notebook_id)
206
+ if path.exists():
207
+ path.unlink()
208
+
209
+
210
+ # ---------------------------------------------------------------------------
211
+ # Artifact helpers
212
+ # ---------------------------------------------------------------------------
213
+
214
+ def _artifact_dir(username: str, notebook_id: str, kind: str) -> Path:
215
+ return _nb_root(username, notebook_id) / "artifacts" / kind
216
+
217
+
218
+ def save_artifact(username: str, notebook_id: str, kind: str, content: bytes | str, ext: str) -> Path:
219
+ """Save an artifact and return its path. kind: reports | quizzes | podcasts"""
220
+ art_dir = _artifact_dir(username, notebook_id, kind)
221
+ art_dir.mkdir(parents=True, exist_ok=True)
222
+ existing = list(art_dir.glob(f"*.{ext}"))
223
+ idx = len(existing) + 1
224
+ dest = art_dir / f"{kind[:-1]}_{idx}.{ext}"
225
+ if isinstance(content, str):
226
+ dest.write_text(content, encoding="utf-8")
227
+ else:
228
+ dest.write_bytes(content)
229
+ _touch_notebook(username, notebook_id)
230
+ return dest
231
+
232
+
233
+ def list_artifacts(username: str, notebook_id: str, kind: str) -> list[Path]:
234
+ art_dir = _artifact_dir(username, notebook_id, kind)
235
+ if not art_dir.exists():
236
+ return []
237
+ return sorted(art_dir.iterdir())
238
+
239
+
240
+ # ---------------------------------------------------------------------------
241
+ # Internal
242
+ # ---------------------------------------------------------------------------
243
+
244
+ def _touch_notebook(username: str, notebook_id: str) -> None:
245
+ index = _load_index(username)
246
+ for nb in index:
247
+ if nb["id"] == notebook_id:
248
+ nb["updated_at"] = datetime.utcnow().isoformat()
249
+ _save_index(username, index)
data/.env.example DELETED
@@ -1,2 +0,0 @@
1
- # .env
2
- OPENAI_API_KEY=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