Spaces:
Runtime error
Runtime error
Update .env.example with all required variables
#1
by asingh38 - opened
- .env.example +3 -3
- .github/workflows/ci.yml +6 -4
- .github/workflows/deploy.yml +3 -3
- .gitignore +10 -16
- README.md +166 -20
- app.py +189 -552
- backend/artifacts.py +145 -0
- backend/chat.py +74 -0
- backend/ingest.py +173 -0
- backend/ingestion.py +99 -58
- backend/retrieval.py +51 -0
- backend/storage.py +18 -29
- requirements.txt +12 -10
.env.example
CHANGED
|
@@ -1,12 +1,12 @@
|
|
| 1 |
# Required — OpenAI API key for LLM, embeddings, and TTS
|
| 2 |
# Get yours at: https://platform.openai.com/api-keys
|
| 3 |
-
OPENAI_API_KEY=
|
| 4 |
|
| 5 |
# Required locally — your Hugging Face token for OAuth mock login
|
| 6 |
# Get yours at: https://huggingface.co/settings/tokens
|
| 7 |
-
HF_TOKEN=
|
| 8 |
|
| 9 |
# Optional — chunking settings (defaults shown)
|
| 10 |
CHUNK_SIZE=800
|
| 11 |
CHUNK_OVERLAP=150
|
| 12 |
-
EMBED_MODEL=text-embedding-3-small
|
|
|
|
| 1 |
# Required — OpenAI API key for LLM, embeddings, and TTS
|
| 2 |
# Get yours at: https://platform.openai.com/api-keys
|
| 3 |
+
OPENAI_API_KEY=sk-your-openai-api-key-here
|
| 4 |
|
| 5 |
# Required locally — your Hugging Face token for OAuth mock login
|
| 6 |
# Get yours at: https://huggingface.co/settings/tokens
|
| 7 |
+
HF_TOKEN=hf_your-huggingface-token-here
|
| 8 |
|
| 9 |
# Optional — chunking settings (defaults shown)
|
| 10 |
CHUNK_SIZE=800
|
| 11 |
CHUNK_OVERLAP=150
|
| 12 |
+
EMBED_MODEL=text-embedding-3-small
|
.github/workflows/ci.yml
CHANGED
|
@@ -19,7 +19,7 @@ jobs:
|
|
| 19 |
with:
|
| 20 |
python-version: "3.11"
|
| 21 |
|
| 22 |
-
- name: Cache pip
|
| 23 |
uses: actions/cache@v4
|
| 24 |
with:
|
| 25 |
path: ~/.cache/pip
|
|
@@ -32,14 +32,16 @@ jobs:
|
|
| 32 |
pip install -r requirements.txt
|
| 33 |
pip install flake8 pytest
|
| 34 |
|
| 35 |
-
- name: Lint
|
| 36 |
run: |
|
|
|
|
| 37 |
flake8 app.py backend/ --count --select=E9,F63,F7,F82 --show-source --statistics
|
| 38 |
flake8 app.py backend/ --count --max-line-length=120 --exit-zero --statistics
|
| 39 |
|
| 40 |
-
- name:
|
| 41 |
env:
|
| 42 |
OPENAI_API_KEY: "test-key-not-real"
|
|
|
|
| 43 |
USERS: "testuser:testpass"
|
| 44 |
run: |
|
| 45 |
-
pytest tests/ -v --tb=short || echo "No tests yet — skipping."
|
|
|
|
| 19 |
with:
|
| 20 |
python-version: "3.11"
|
| 21 |
|
| 22 |
+
- name: Cache pip dependencies
|
| 23 |
uses: actions/cache@v4
|
| 24 |
with:
|
| 25 |
path: ~/.cache/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."
|
.github/workflows/deploy.yml
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
name: Deploy to Hugging Face
|
| 2 |
|
| 3 |
on:
|
| 4 |
push:
|
|
@@ -10,8 +10,8 @@ jobs:
|
|
| 10 |
runs-on: ubuntu-latest
|
| 11 |
|
| 12 |
steps:
|
| 13 |
-
- name: Checkout
|
| 14 |
-
uses: actions/checkout@
|
| 15 |
with:
|
| 16 |
fetch-depth: 0
|
| 17 |
lfs: true
|
|
|
|
| 1 |
+
name: Deploy to Hugging Face Space
|
| 2 |
|
| 3 |
on:
|
| 4 |
push:
|
|
|
|
| 10 |
runs-on: ubuntu-latest
|
| 11 |
|
| 12 |
steps:
|
| 13 |
+
- name: Checkout repo
|
| 14 |
+
uses: actions/checkout@v3
|
| 15 |
with:
|
| 16 |
fetch-depth: 0
|
| 17 |
lfs: true
|
.gitignore
CHANGED
|
@@ -1,29 +1,23 @@
|
|
| 1 |
-
#
|
| 2 |
.env
|
|
|
|
| 3 |
|
| 4 |
-
# User data
|
| 5 |
data/
|
| 6 |
|
| 7 |
# Python
|
| 8 |
__pycache__/
|
| 9 |
*.pyc
|
| 10 |
*.pyo
|
| 11 |
-
|
| 12 |
-
*.egg-info/
|
| 13 |
-
dist/
|
| 14 |
-
build/
|
| 15 |
-
.eggs/
|
| 16 |
|
| 17 |
-
# Virtual
|
| 18 |
.venv/
|
| 19 |
venv/
|
| 20 |
-
env/
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
.
|
| 24 |
-
Thumbs.db
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
.
|
| 28 |
-
|
| 29 |
-
*.swp
|
|
|
|
| 1 |
+
# Environment variables - NEVER commit these
|
| 2 |
.env
|
| 3 |
+
HF_TOKEN.txt
|
| 4 |
|
| 5 |
+
# User data - created at runtime
|
| 6 |
data/
|
| 7 |
|
| 8 |
# Python
|
| 9 |
__pycache__/
|
| 10 |
*.pyc
|
| 11 |
*.pyo
|
| 12 |
+
.DS_Store
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Virtual environment
|
| 15 |
.venv/
|
| 16 |
venv/
|
|
|
|
| 17 |
|
| 18 |
+
# Audio files generated by the app
|
| 19 |
+
*.mp3
|
|
|
|
| 20 |
|
| 21 |
+
# ChromaDB files
|
| 22 |
+
*.chroma
|
| 23 |
+
chroma/
|
|
|
README.md
CHANGED
|
@@ -1,36 +1,182 @@
|
|
| 1 |
---
|
| 2 |
-
title: NotebookLM
|
| 3 |
emoji: 📓
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: "
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
and generate study reports, quizzes, and podcasts — powered by GPT-4o and
|
| 16 |
-
ChromaDB RAG with recursive chunking.
|
| 17 |
|
| 18 |
## Features
|
| 19 |
|
| 20 |
-
- **Multi-notebook
|
| 21 |
-
- **Source ingestion** — upload PDF, PPTX, TXT, or paste
|
| 22 |
-
- **RAG
|
| 23 |
-
- **
|
| 24 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|------------------|------------------------------------------------------|
|
| 32 |
-
| `OPENAI_API_KEY` | Your OpenAI API key |
|
| 33 |
-
| `USERS` | Comma-separated credentials: `alice:pass1,bob:pass2` |
|
| 34 |
|
| 35 |
-
|
| 36 |
-
```bash
|
|
|
|
| 1 |
---
|
| 2 |
+
title: NotebookLM Clone
|
| 3 |
emoji: 📓
|
| 4 |
+
colorFrom: blue
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: "6.8.0"
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
hf_oauth: true
|
| 11 |
---
|
| 12 |
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
## Demo
|
| 16 |
+
|
| 17 |
+
> _Add a screenshot or GIF of your app here once it's running_
|
| 18 |
|
| 19 |
+
---
|
|
|
|
|
|
|
| 20 |
|
| 21 |
## Features
|
| 22 |
|
| 23 |
+
- **Multi-notebook support** — create, switch between, and manage multiple notebooks
|
| 24 |
+
- **Source ingestion** — upload PDF, PPTX, and TXT files, or paste any web URL
|
| 25 |
+
- **RAG Chat** — ask questions about your sources and get cited, grounded answers
|
| 26 |
+
- **Artifact generation**
|
| 27 |
+
- Report — a comprehensive markdown study guide
|
| 28 |
+
- Quiz — multiple choice questions with an answer key
|
| 29 |
+
- Podcast — a two-host conversation script with audio playback
|
| 30 |
+
- **Persistent storage** — notebooks, chats, and artifacts are saved across sessions
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## Tech Stack
|
| 35 |
+
|
| 36 |
+
| Layer | Technology |
|
| 37 |
+
|---|---|
|
| 38 |
+
| Frontend | [Gradio](https://gradio.app) |
|
| 39 |
+
| LLM | [OpenAI GPT-4o](https://platform.openai.com) |
|
| 40 |
+
| Vector DB | [ChromaDB](https://trychroma.com) |
|
| 41 |
+
| PDF parsing | PyPDF2 |
|
| 42 |
+
| PPTX parsing | python-pptx |
|
| 43 |
+
| Web scraping | BeautifulSoup4 + requests |
|
| 44 |
+
| Text to Speech | OpenAI TTS |
|
| 45 |
+
|
| 46 |
+
---
|
| 47 |
+
|
| 48 |
+
## Project Structure
|
| 49 |
+
|
| 50 |
+
```
|
| 51 |
+
notebooklm-clone/
|
| 52 |
+
├── app.py # Gradio UI and event wiring
|
| 53 |
+
├── backend/
|
| 54 |
+
│ ├── ingest.py # File & URL ingestion, chunking, embedding
|
| 55 |
+
│ ├── retrieval.py # ChromaDB vector search
|
| 56 |
+
│ ├── chat.py # RAG chat with source citations
|
| 57 |
+
│ └── artifacts.py # Report, quiz, and podcast generation
|
| 58 |
+
├── data/ # Runtime user data (gitignored)
|
| 59 |
+
│ └── users/
|
| 60 |
+
│ └── <username>/
|
| 61 |
+
│ └── notebooks/
|
| 62 |
+
│ └── <notebook-id>/
|
| 63 |
+
│ ├── files_raw/
|
| 64 |
+
│ ├── files_extracted/
|
| 65 |
+
│ ├── chroma/
|
| 66 |
+
│ ├── chat/messages.jsonl
|
| 67 |
+
│ └── artifacts/
|
| 68 |
+
├── requirements.txt
|
| 69 |
+
├── .env.example
|
| 70 |
+
└── README.md
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
---
|
| 74 |
+
|
| 75 |
+
## Setup
|
| 76 |
+
|
| 77 |
+
### Prerequisites
|
| 78 |
+
|
| 79 |
+
- Python 3.10+
|
| 80 |
+
- An OpenAI API key — get one at [platform.openai.com](https://platform.openai.com)
|
| 81 |
+
|
| 82 |
+
### Installation
|
| 83 |
+
|
| 84 |
+
1. **Clone the repository**
|
| 85 |
+
```bash
|
| 86 |
+
git clone https://github.com/4681Project/notebooklm-clone
|
| 87 |
+
cd notebooklm-clone
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
2. **Create and activate a virtual environment**
|
| 91 |
+
```bash
|
| 92 |
+
python -m venv venv
|
| 93 |
+
source venv/bin/activate # Mac/Linux
|
| 94 |
+
venv\Scripts\activate # Windows
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
3. **Install dependencies**
|
| 98 |
+
```bash
|
| 99 |
+
pip install -r requirements.txt
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
4. **Set up environment variables**
|
| 103 |
+
```bash
|
| 104 |
+
cp .env.example .env
|
| 105 |
+
```
|
| 106 |
+
Open `.env` and add your API key:
|
| 107 |
+
```
|
| 108 |
+
OPENAI_API_KEY=sk-...
|
| 109 |
+
```
|
| 110 |
|
| 111 |
+
5. **Run the app**
|
| 112 |
+
```bash
|
| 113 |
+
python app.py
|
| 114 |
+
```
|
| 115 |
+
The app will be available at `http://localhost:7860`
|
| 116 |
|
| 117 |
+
---
|
| 118 |
+
|
| 119 |
+
## Environment Variables
|
| 120 |
+
|
| 121 |
+
| Variable | Required | Description |
|
| 122 |
+
|---|---|---|
|
| 123 |
+
| `OPENAI_API_KEY` | Yes | Your OpenAI API key for LLM and TTS calls |
|
| 124 |
+
|
| 125 |
+
---
|
| 126 |
+
|
| 127 |
+
## Team & Module Ownership
|
| 128 |
+
|
| 129 |
+
| Person | Module | File |
|
| 130 |
+
|---|---|---|
|
| 131 |
+
| Person 1 | Gradio UI | `app.py` |
|
| 132 |
+
| Person 2 | Ingestion pipeline | `backend/ingest.py` |
|
| 133 |
+
| Person 3 | RAG + ChromaDB | `backend/retrieval.py` |
|
| 134 |
+
| Person 4 | Chat + citations | `backend/chat.py` |
|
| 135 |
+
| Person 5 | Artifact generation | `backend/artifacts.py` |
|
| 136 |
+
|
| 137 |
+
---
|
| 138 |
+
|
| 139 |
+
## Contributing
|
| 140 |
+
|
| 141 |
+
We use a feature-branch workflow. Please do **not** push directly to `main`.
|
| 142 |
+
|
| 143 |
+
```bash
|
| 144 |
+
# 1. Pull the latest main
|
| 145 |
+
git checkout main
|
| 146 |
+
git pull origin main
|
| 147 |
+
|
| 148 |
+
# 2. Create a feature branch
|
| 149 |
+
git checkout -b feature/your-feature-name
|
| 150 |
+
|
| 151 |
+
# 3. Make your changes, then commit
|
| 152 |
+
git add .
|
| 153 |
+
git commit -m "Short description of what you changed"
|
| 154 |
+
|
| 155 |
+
# 4. Push your branch
|
| 156 |
+
git push origin feature/your-feature-name
|
| 157 |
+
|
| 158 |
+
# 5. Open a Pull Request on GitHub and request a review
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
---
|
| 162 |
+
|
| 163 |
+
## Architecture Overview
|
| 164 |
+
|
| 165 |
+
```
|
| 166 |
+
User
|
| 167 |
+
│
|
| 168 |
+
▼
|
| 169 |
+
Gradio UI (app.py)
|
| 170 |
+
│
|
| 171 |
+
├──► Ingest ──► Extract text ──► Chunk ──► Embed ──► ChromaDB
|
| 172 |
+
│
|
| 173 |
+
├──► Chat ──► Retrieve top-k chunks ──► Prompt LLM ──► Response + citations
|
| 174 |
+
│
|
| 175 |
+
└──► Artifacts ──► Retrieve chunks ���─► Prompt LLM ──► Report / Quiz / Podcast
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
---
|
| 179 |
|
| 180 |
+
## License
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
+
MIT
|
|
|
app.py
CHANGED
|
@@ -1,592 +1,229 @@
|
|
| 1 |
-
"""
|
| 2 |
-
app.py — NotebookLM 2.0
|
| 3 |
-
Gradio frontend / Hugging Face Spaces entry point.
|
| 4 |
-
|
| 5 |
-
Screens:
|
| 6 |
-
1. Login — username + password (configured via USERS env var)
|
| 7 |
-
2. Main — Notebook selector, then three tabs:
|
| 8 |
-
💬 Chat | 📂 Sources | ✨ Artifacts
|
| 9 |
-
"""
|
| 10 |
-
|
| 11 |
import os
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
from dotenv import load_dotenv
|
| 14 |
import gradio as gr
|
|
|
|
| 15 |
|
|
|
|
| 16 |
load_dotenv()
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# ---------------------------------------------------------------------------
|
| 20 |
-
#
|
| 21 |
# ---------------------------------------------------------------------------
|
| 22 |
|
| 23 |
-
def
|
| 24 |
-
"""
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
"""
|
| 29 |
-
raw = os.getenv("USERS", "demo:demo")
|
| 30 |
-
users = {}
|
| 31 |
-
for pair in raw.split(","):
|
| 32 |
-
pair = pair.strip()
|
| 33 |
-
if ":" in pair:
|
| 34 |
-
u, p = pair.split(":", 1)
|
| 35 |
-
users[u.strip()] = p.strip()
|
| 36 |
-
return users
|
| 37 |
-
|
| 38 |
-
USERS = _parse_users()
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
def login(username: str, password: str) -> tuple[bool, str]:
|
| 42 |
-
"""Return (success, username_or_error_message)."""
|
| 43 |
-
if not username or not password:
|
| 44 |
-
return False, "Please enter both username and password."
|
| 45 |
-
if USERS.get(username) == password:
|
| 46 |
-
return True, username
|
| 47 |
-
return False, "Invalid username or password."
|
| 48 |
|
| 49 |
|
| 50 |
# ---------------------------------------------------------------------------
|
| 51 |
-
#
|
| 52 |
# ---------------------------------------------------------------------------
|
| 53 |
|
| 54 |
-
def
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
)
|
| 61 |
-
from backend.ingestion import ingest_source, list_indexed_sources
|
| 62 |
-
from backend.chat import chat_with_sources
|
| 63 |
-
from backend.artifacts import generate_report, generate_quiz, generate_podcast
|
| 64 |
-
return {
|
| 65 |
-
"get_notebooks": get_user_notebooks,
|
| 66 |
-
"create_notebook": create_notebook_for_user,
|
| 67 |
-
"delete_notebook": delete_notebook,
|
| 68 |
-
"list_sources": list_indexed_sources,
|
| 69 |
-
"ingest": ingest_source,
|
| 70 |
-
"chat": chat_with_sources,
|
| 71 |
-
"report": generate_report,
|
| 72 |
-
"quiz": generate_quiz,
|
| 73 |
-
"podcast": generate_podcast,
|
| 74 |
-
}
|
| 75 |
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
def
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
|
| 95 |
-
def
|
| 96 |
-
|
| 97 |
-
if not
|
| 98 |
-
return "
|
| 99 |
-
|
| 100 |
-
sources = _be()["list_sources"](username, nb_id)
|
| 101 |
-
if not sources:
|
| 102 |
-
return "_No sources indexed yet. Upload files or add a URL in the Sources tab._"
|
| 103 |
-
return "\n".join(f"- `{s}`" for s in sources)
|
| 104 |
-
except Exception as e:
|
| 105 |
-
return f"_Could not load sources: {e}_"
|
| 106 |
|
| 107 |
|
| 108 |
# ---------------------------------------------------------------------------
|
| 109 |
-
#
|
| 110 |
# ---------------------------------------------------------------------------
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
:
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
--glow: rgba(124,106,247,0.15);
|
| 123 |
-
--text: #e8e6f0;
|
| 124 |
-
--text2: #8b87a8;
|
| 125 |
-
--muted: #504d6e;
|
| 126 |
-
--border: #2a2840;
|
| 127 |
-
--border2: #3d3960;
|
| 128 |
-
--ok: #5af0a0;
|
| 129 |
-
--warn: #f0c45a;
|
| 130 |
-
--err: #f05a7a;
|
| 131 |
-
--r: 10px;
|
| 132 |
-
--mono: 'JetBrains Mono', 'Fira Code', monospace;
|
| 133 |
-
--display: 'Playfair Display', Georgia, serif;
|
| 134 |
-
}
|
| 135 |
-
|
| 136 |
-
*, *::before, *::after { box-sizing: border-box; }
|
| 137 |
-
|
| 138 |
-
body, .gradio-container {
|
| 139 |
-
background: var(--bg) !important;
|
| 140 |
-
color: var(--text) !important;
|
| 141 |
-
font-family: var(--mono) !important;
|
| 142 |
-
}
|
| 143 |
-
|
| 144 |
-
#login-wrap {
|
| 145 |
-
max-width: 420px;
|
| 146 |
-
margin: 72px auto 0;
|
| 147 |
-
padding: 48px 40px 40px;
|
| 148 |
-
background: var(--bg3);
|
| 149 |
-
border: 1px solid var(--border);
|
| 150 |
-
border-radius: 18px;
|
| 151 |
-
box-shadow: 0 0 80px var(--glow);
|
| 152 |
-
}
|
| 153 |
-
#login-title {
|
| 154 |
-
font-family: var(--display);
|
| 155 |
-
font-size: 2rem;
|
| 156 |
-
font-weight: 700;
|
| 157 |
-
text-align: center;
|
| 158 |
-
margin-bottom: 4px;
|
| 159 |
-
color: var(--text);
|
| 160 |
-
letter-spacing: -0.5px;
|
| 161 |
-
}
|
| 162 |
-
#login-sub {
|
| 163 |
-
font-size: 0.72rem;
|
| 164 |
-
color: var(--muted);
|
| 165 |
-
text-align: center;
|
| 166 |
-
letter-spacing: 0.12em;
|
| 167 |
-
text-transform: uppercase;
|
| 168 |
-
margin-bottom: 36px;
|
| 169 |
-
}
|
| 170 |
-
|
| 171 |
-
#hdr {
|
| 172 |
-
display: flex;
|
| 173 |
-
align-items: center;
|
| 174 |
-
justify-content: space-between;
|
| 175 |
-
padding: 16px 28px;
|
| 176 |
-
background: var(--bg2);
|
| 177 |
-
border-bottom: 1px solid var(--border);
|
| 178 |
-
}
|
| 179 |
-
#hdr-title {
|
| 180 |
-
font-family: var(--display);
|
| 181 |
-
font-size: 1.35rem;
|
| 182 |
-
color: var(--text);
|
| 183 |
-
}
|
| 184 |
-
#hdr-title span { color: var(--accent2); }
|
| 185 |
-
|
| 186 |
-
#nb-bar {
|
| 187 |
-
display: flex;
|
| 188 |
-
gap: 10px;
|
| 189 |
-
align-items: flex-end;
|
| 190 |
-
padding: 12px 20px;
|
| 191 |
-
background: var(--bg2);
|
| 192 |
-
border-bottom: 1px solid var(--border);
|
| 193 |
-
}
|
| 194 |
-
|
| 195 |
-
.gr-button, button {
|
| 196 |
-
font-family: var(--mono) !important;
|
| 197 |
-
font-size: 0.8rem !important;
|
| 198 |
-
font-weight: 500 !important;
|
| 199 |
-
letter-spacing: 0.04em !important;
|
| 200 |
-
border-radius: var(--r) !important;
|
| 201 |
-
transition: all 0.18s ease !important;
|
| 202 |
-
}
|
| 203 |
-
.gr-button-primary {
|
| 204 |
-
background: var(--accent) !important;
|
| 205 |
-
color: #fff !important;
|
| 206 |
-
border: none !important;
|
| 207 |
-
}
|
| 208 |
-
.gr-button-primary:hover {
|
| 209 |
-
background: var(--accent2) !important;
|
| 210 |
-
box-shadow: 0 0 18px var(--glow) !important;
|
| 211 |
-
transform: translateY(-1px) !important;
|
| 212 |
-
}
|
| 213 |
-
.gr-button-stop {
|
| 214 |
-
background: transparent !important;
|
| 215 |
-
color: var(--err) !important;
|
| 216 |
-
border: 1px solid var(--err) !important;
|
| 217 |
-
}
|
| 218 |
-
|
| 219 |
-
input, textarea, .gr-textbox textarea {
|
| 220 |
-
background: var(--bg4) !important;
|
| 221 |
-
border: 1px solid var(--border) !important;
|
| 222 |
-
border-radius: var(--r) !important;
|
| 223 |
-
color: var(--text) !important;
|
| 224 |
-
font-family: var(--mono) !important;
|
| 225 |
-
font-size: 0.85rem !important;
|
| 226 |
-
transition: border-color 0.2s, box-shadow 0.2s !important;
|
| 227 |
-
}
|
| 228 |
-
input:focus, textarea:focus {
|
| 229 |
-
border-color: var(--accent) !important;
|
| 230 |
-
box-shadow: 0 0 0 3px var(--glow) !important;
|
| 231 |
-
outline: none !important;
|
| 232 |
-
}
|
| 233 |
-
|
| 234 |
-
label, .gr-block-label {
|
| 235 |
-
color: var(--text2) !important;
|
| 236 |
-
font-family: var(--mono) !important;
|
| 237 |
-
font-size: 0.72rem !important;
|
| 238 |
-
font-weight: 500 !important;
|
| 239 |
-
letter-spacing: 0.08em !important;
|
| 240 |
-
text-transform: uppercase !important;
|
| 241 |
-
}
|
| 242 |
-
|
| 243 |
-
.tab-nav button {
|
| 244 |
-
background: transparent !important;
|
| 245 |
-
border: none !important;
|
| 246 |
-
border-bottom: 2px solid transparent !important;
|
| 247 |
-
color: var(--text2) !important;
|
| 248 |
-
font-family: var(--mono) !important;
|
| 249 |
-
font-size: 0.78rem !important;
|
| 250 |
-
font-weight: 500 !important;
|
| 251 |
-
letter-spacing: 0.1em !important;
|
| 252 |
-
text-transform: uppercase !important;
|
| 253 |
-
padding: 12px 20px !important;
|
| 254 |
-
transition: all 0.2s !important;
|
| 255 |
-
}
|
| 256 |
-
.tab-nav button.selected {
|
| 257 |
-
color: var(--accent2) !important;
|
| 258 |
-
border-bottom-color: var(--accent) !important;
|
| 259 |
-
}
|
| 260 |
-
|
| 261 |
-
.chatbot {
|
| 262 |
-
background: var(--bg) !important;
|
| 263 |
-
border: 1px solid var(--border) !important;
|
| 264 |
-
border-radius: var(--r) !important;
|
| 265 |
-
}
|
| 266 |
-
.message.user {
|
| 267 |
-
background: var(--bg4) !important;
|
| 268 |
-
border: 1px solid var(--border) !important;
|
| 269 |
-
border-radius: var(--r) !important;
|
| 270 |
-
font-family: var(--mono) !important;
|
| 271 |
-
font-size: 0.85rem !important;
|
| 272 |
-
color: var(--text) !important;
|
| 273 |
-
}
|
| 274 |
-
.message.bot {
|
| 275 |
-
background: var(--bg3) !important;
|
| 276 |
-
border: 1px solid var(--border2) !important;
|
| 277 |
-
border-left: 3px solid var(--accent) !important;
|
| 278 |
-
border-radius: var(--r) !important;
|
| 279 |
-
font-family: var(--mono) !important;
|
| 280 |
-
font-size: 0.85rem !important;
|
| 281 |
-
color: var(--text) !important;
|
| 282 |
-
}
|
| 283 |
-
|
| 284 |
-
.gr-markdown {
|
| 285 |
-
background: var(--bg3) !important;
|
| 286 |
-
border: 1px solid var(--border) !important;
|
| 287 |
-
border-radius: var(--r) !important;
|
| 288 |
-
padding: 20px !important;
|
| 289 |
-
font-family: var(--mono) !important;
|
| 290 |
-
font-size: 0.84rem !important;
|
| 291 |
-
line-height: 1.75 !important;
|
| 292 |
-
color: var(--text) !important;
|
| 293 |
-
}
|
| 294 |
-
.gr-markdown h1, .gr-markdown h2, .gr-markdown h3 {
|
| 295 |
-
font-family: var(--display) !important;
|
| 296 |
-
color: var(--text) !important;
|
| 297 |
-
}
|
| 298 |
-
|
| 299 |
-
select, .gr-dropdown select {
|
| 300 |
-
background: var(--bg4) !important;
|
| 301 |
-
border: 1px solid var(--border) !important;
|
| 302 |
-
color: var(--text) !important;
|
| 303 |
-
font-family: var(--mono) !important;
|
| 304 |
-
border-radius: var(--r) !important;
|
| 305 |
-
}
|
| 306 |
-
|
| 307 |
-
.gr-accordion {
|
| 308 |
-
background: var(--bg3) !important;
|
| 309 |
-
border: 1px solid var(--border) !important;
|
| 310 |
-
border-radius: var(--r) !important;
|
| 311 |
-
margin-bottom: 8px !important;
|
| 312 |
-
}
|
| 313 |
-
|
| 314 |
-
.ok { color: var(--ok) !important; }
|
| 315 |
-
.warn { color: var(--warn) !important; }
|
| 316 |
-
.err { color: var(--err) !important; }
|
| 317 |
-
|
| 318 |
-
.gr-file-upload {
|
| 319 |
-
background: var(--bg3) !important;
|
| 320 |
-
border: 1px dashed var(--border2) !important;
|
| 321 |
-
border-radius: var(--r) !important;
|
| 322 |
-
}
|
| 323 |
-
|
| 324 |
-
::-webkit-scrollbar { width: 5px; height: 5px; }
|
| 325 |
-
::-webkit-scrollbar-track { background: var(--bg); }
|
| 326 |
-
::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 3px; }
|
| 327 |
-
::-webkit-scrollbar-thumb:hover{ background: var(--accent); }
|
| 328 |
-
|
| 329 |
-
audio { width: 100%; border-radius: var(--r); }
|
| 330 |
-
"""
|
| 331 |
|
| 332 |
|
| 333 |
# ---------------------------------------------------------------------------
|
| 334 |
-
#
|
| 335 |
# ---------------------------------------------------------------------------
|
| 336 |
|
| 337 |
-
def
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
s_user = gr.State("")
|
| 343 |
-
s_nb_id = gr.State("")
|
| 344 |
-
|
| 345 |
-
# ==================================================================
|
| 346 |
-
# LOGIN SCREEN
|
| 347 |
-
# ==================================================================
|
| 348 |
-
with gr.Column(elem_id="login-wrap", visible=True) as screen_login:
|
| 349 |
-
gr.HTML('<div id="login-title">NotebookLM 2.0</div>')
|
| 350 |
-
gr.HTML('<div id="login-sub">AI Research Assistant</div>')
|
| 351 |
-
inp_user = gr.Textbox(label="Username", placeholder="username")
|
| 352 |
-
inp_pass = gr.Textbox(label="Password", placeholder="password", type="password")
|
| 353 |
-
btn_login = gr.Button("Sign In", variant="primary")
|
| 354 |
-
msg_login = gr.Markdown("")
|
| 355 |
-
|
| 356 |
-
# ==================================================================
|
| 357 |
-
# MAIN APP
|
| 358 |
-
# ==================================================================
|
| 359 |
-
with gr.Column(visible=False) as screen_main:
|
| 360 |
-
|
| 361 |
-
# Header
|
| 362 |
-
with gr.Row(elem_id="hdr"):
|
| 363 |
-
gr.HTML('<div id="hdr-title">Notebook<span>LM</span> 2.0</div>')
|
| 364 |
-
lbl_user = gr.Markdown("", elem_classes=["ok"])
|
| 365 |
-
|
| 366 |
-
# Notebook bar
|
| 367 |
-
with gr.Row(elem_id="nb-bar"):
|
| 368 |
-
dd_nb = gr.Dropdown(choices=[], label="Active Notebook", scale=4, interactive=True)
|
| 369 |
-
inp_nb_name = gr.Textbox(placeholder="New notebook name…", label="", scale=3, show_label=False)
|
| 370 |
-
btn_create = gr.Button("+ Create", scale=1, variant="primary")
|
| 371 |
-
btn_delete = gr.Button("✕ Delete", scale=1, variant="stop")
|
| 372 |
-
|
| 373 |
-
md_nb_status = gr.Markdown("")
|
| 374 |
-
|
| 375 |
-
# ── Tabs ───────────────────────────────────────────────────────
|
| 376 |
-
with gr.Tabs():
|
| 377 |
|
| 378 |
-
# TAB 1 — CHAT
|
| 379 |
-
with gr.TabItem("💬 Chat"):
|
| 380 |
-
chatbot = gr.Chatbot(
|
| 381 |
-
label="", height=460, type="messages",
|
| 382 |
-
show_label=False, bubble_full_width=False,
|
| 383 |
-
)
|
| 384 |
-
with gr.Row():
|
| 385 |
-
inp_chat = gr.Textbox(
|
| 386 |
-
placeholder="Ask anything about your sources…",
|
| 387 |
-
label="", show_label=False, scale=5, lines=1,
|
| 388 |
-
)
|
| 389 |
-
btn_send = gr.Button("Send →", scale=1, variant="primary")
|
| 390 |
-
btn_clear = gr.Button("Clear chat", size="sm")
|
| 391 |
-
|
| 392 |
-
# TAB 2 — SOURCES
|
| 393 |
-
with gr.TabItem("📂 Sources"):
|
| 394 |
-
with gr.Row():
|
| 395 |
-
with gr.Column(scale=1):
|
| 396 |
-
gr.Markdown("### Upload Files")
|
| 397 |
-
inp_files = gr.File(
|
| 398 |
-
label="PDF / PPTX / TXT",
|
| 399 |
-
file_types=[".pdf", ".pptx", ".txt"],
|
| 400 |
-
file_count="multiple",
|
| 401 |
-
)
|
| 402 |
-
btn_upload = gr.Button("Ingest Files", variant="primary")
|
| 403 |
-
with gr.Column(scale=1):
|
| 404 |
-
gr.Markdown("### Add URL")
|
| 405 |
-
inp_url = gr.Textbox(label="Web URL", placeholder="https://…")
|
| 406 |
-
btn_url = gr.Button("Ingest URL", variant="primary")
|
| 407 |
-
|
| 408 |
-
md_ingest = gr.Markdown("")
|
| 409 |
-
gr.Markdown("---")
|
| 410 |
-
gr.Markdown("### Indexed Sources")
|
| 411 |
-
md_sources = gr.Markdown("_No sources indexed yet._")
|
| 412 |
-
btn_refresh = gr.Button("↻ Refresh", size="sm")
|
| 413 |
-
|
| 414 |
-
# TAB 3 — ARTIFACTS
|
| 415 |
-
with gr.TabItem("✨ Artifacts"):
|
| 416 |
-
with gr.Row():
|
| 417 |
-
btn_report = gr.Button("📄 Generate Report", variant="primary", scale=1)
|
| 418 |
-
btn_quiz = gr.Button("❓ Generate Quiz", variant="primary", scale=1)
|
| 419 |
-
btn_podcast = gr.Button("🎙️ Generate Podcast", variant="primary", scale=1)
|
| 420 |
-
|
| 421 |
-
md_art_status = gr.Markdown("")
|
| 422 |
-
|
| 423 |
-
with gr.Accordion("📄 Report", open=False):
|
| 424 |
-
md_report = gr.Markdown("")
|
| 425 |
-
with gr.Accordion("❓ Quiz", open=False):
|
| 426 |
-
md_quiz = gr.Markdown("")
|
| 427 |
-
with gr.Accordion("🎙️ Podcast", open=False):
|
| 428 |
-
md_transcript = gr.Markdown("")
|
| 429 |
-
aud_podcast = gr.Audio(label="Listen", visible=False)
|
| 430 |
-
|
| 431 |
-
# ==================================================================
|
| 432 |
-
# EVENT HANDLERS
|
| 433 |
-
# ==================================================================
|
| 434 |
-
|
| 435 |
-
# ── Login ──────────────────────────────────────────────────────────
|
| 436 |
-
def do_login(username, password):
|
| 437 |
-
ok, result = login(username, password)
|
| 438 |
-
if ok:
|
| 439 |
-
choices = _nb_choices(result)
|
| 440 |
-
return (
|
| 441 |
-
gr.update(visible=False),
|
| 442 |
-
gr.update(visible=True),
|
| 443 |
-
result,
|
| 444 |
-
gr.update(choices=choices, value=choices[0] if choices else None),
|
| 445 |
-
f"✦ **{result}**",
|
| 446 |
-
"",
|
| 447 |
-
)
|
| 448 |
-
return (
|
| 449 |
-
gr.update(visible=True),
|
| 450 |
-
gr.update(visible=False),
|
| 451 |
-
"", gr.update(), "",
|
| 452 |
-
f"⚠ {result}",
|
| 453 |
-
)
|
| 454 |
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
)
|
| 461 |
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
# ── Create notebook ────────────────────────────────────────────────
|
| 470 |
-
def do_create(username, name):
|
| 471 |
-
if not name.strip():
|
| 472 |
-
return gr.update(), "", "⚠ Enter a notebook name."
|
| 473 |
-
if not username:
|
| 474 |
-
return gr.update(), "", "⚠ Not signed in."
|
| 475 |
-
_be()["create_notebook"](username, name.strip())
|
| 476 |
-
choices = _nb_choices(username)
|
| 477 |
-
return gr.update(choices=choices, value=choices[-1]), "", f"✦ Created **{name.strip()}**"
|
| 478 |
-
|
| 479 |
-
btn_create.click(
|
| 480 |
-
do_create,
|
| 481 |
-
inputs=[s_user, inp_nb_name],
|
| 482 |
-
outputs=[dd_nb, inp_nb_name, md_nb_status],
|
| 483 |
-
)
|
| 484 |
-
|
| 485 |
-
# ── Delete notebook ────────────────────────────────────────────────
|
| 486 |
-
def do_delete(username, nb_id):
|
| 487 |
-
if not nb_id:
|
| 488 |
-
return gr.update(), "⚠ No notebook selected."
|
| 489 |
-
_be()["delete_notebook"](username, nb_id)
|
| 490 |
-
choices = _nb_choices(username)
|
| 491 |
-
return gr.update(choices=choices, value=choices[0] if choices else None), "✦ Deleted."
|
| 492 |
-
|
| 493 |
-
btn_delete.click(do_delete, inputs=[s_user, s_nb_id], outputs=[dd_nb, md_nb_status])
|
| 494 |
-
|
| 495 |
-
# ── Chat ───────────────────────────────────────────────────────────
|
| 496 |
-
def do_chat(message, nb_id, username, history):
|
| 497 |
-
if not message.strip():
|
| 498 |
-
return history, ""
|
| 499 |
-
if not nb_id:
|
| 500 |
-
history = (history or []) + [{"role": "assistant", "content": "⚠ Select a notebook first."}]
|
| 501 |
-
return history, ""
|
| 502 |
-
history = list(history or [])
|
| 503 |
-
history.append({"role": "user", "content": message})
|
| 504 |
-
reply = _be()["chat"](message, nb_id, username, history[:-1])
|
| 505 |
-
history.append({"role": "assistant", "content": reply})
|
| 506 |
-
return history, ""
|
| 507 |
-
|
| 508 |
-
btn_send.click(do_chat, inputs=[inp_chat, s_nb_id, s_user, chatbot], outputs=[chatbot, inp_chat])
|
| 509 |
-
inp_chat.submit(do_chat, inputs=[inp_chat, s_nb_id, s_user, chatbot], outputs=[chatbot, inp_chat])
|
| 510 |
-
btn_clear.click(lambda: [], outputs=[chatbot])
|
| 511 |
-
|
| 512 |
-
# ── Ingest files ───────────────────────────────────────────────────
|
| 513 |
-
def do_upload(files, nb_id, username):
|
| 514 |
-
if not nb_id:
|
| 515 |
-
return "⚠ Select a notebook first.", _sources_md(username, nb_id)
|
| 516 |
-
if not files:
|
| 517 |
-
return "⚠ No files selected.", _sources_md(username, nb_id)
|
| 518 |
-
msgs = []
|
| 519 |
-
for f in files:
|
| 520 |
-
path = f.name if hasattr(f, "name") else str(f)
|
| 521 |
-
raw = Path(path).read_bytes()
|
| 522 |
-
try:
|
| 523 |
-
res = _be()["ingest"](username, nb_id, path, raw_bytes=raw)
|
| 524 |
-
msgs.append(f"✦ **{res['source_name']}** — {res['chunk_count']} chunks ({res['strategy']})")
|
| 525 |
-
except Exception as e:
|
| 526 |
-
msgs.append(f"✕ {e}")
|
| 527 |
-
return "\n\n".join(msgs), _sources_md(username, nb_id)
|
| 528 |
-
|
| 529 |
-
btn_upload.click(do_upload, inputs=[inp_files, s_nb_id, s_user], outputs=[md_ingest, md_sources])
|
| 530 |
-
|
| 531 |
-
# ── Ingest URL ─────────────────────────────────────────────────────
|
| 532 |
-
def do_url(url, nb_id, username):
|
| 533 |
-
if not nb_id:
|
| 534 |
-
return "⚠ Select a notebook first.", _sources_md(username, nb_id)
|
| 535 |
-
if not url.strip():
|
| 536 |
-
return "⚠ Enter a URL.", _sources_md(username, nb_id)
|
| 537 |
-
try:
|
| 538 |
-
res = _be()["ingest"](username, nb_id, url.strip())
|
| 539 |
-
msg = f"✦ **{res['source_name']}** — {res['chunk_count']} chunks ({res['strategy']})"
|
| 540 |
-
except Exception as e:
|
| 541 |
-
msg = f"✕ {e}"
|
| 542 |
-
return msg, _sources_md(username, nb_id)
|
| 543 |
-
|
| 544 |
-
btn_url.click(do_url, inputs=[inp_url, s_nb_id, s_user], outputs=[md_ingest, md_sources])
|
| 545 |
-
|
| 546 |
-
# ── Refresh sources ──────────────────────────────��─────────────────
|
| 547 |
-
btn_refresh.click(
|
| 548 |
-
lambda u, n: _sources_md(u, n),
|
| 549 |
-
inputs=[s_user, s_nb_id],
|
| 550 |
-
outputs=[md_sources],
|
| 551 |
-
)
|
| 552 |
-
|
| 553 |
-
# ── Report ─────────────────────────────────────────────────────────
|
| 554 |
-
def do_report(nb_id, username):
|
| 555 |
-
if not nb_id:
|
| 556 |
-
return "⚠ Select a notebook first.", ""
|
| 557 |
-
return "✦ Report generated.", _be()["report"](nb_id, username)
|
| 558 |
-
|
| 559 |
-
btn_report.click(do_report, inputs=[s_nb_id, s_user], outputs=[md_art_status, md_report])
|
| 560 |
-
|
| 561 |
-
# ── Quiz ───────────────────────────────────────────────────────────
|
| 562 |
-
def do_quiz(nb_id, username):
|
| 563 |
-
if not nb_id:
|
| 564 |
-
return "⚠ Select a notebook first.", ""
|
| 565 |
-
return "✦ Quiz generated.", _be()["quiz"](nb_id, username)
|
| 566 |
-
|
| 567 |
-
btn_quiz.click(do_quiz, inputs=[s_nb_id, s_user], outputs=[md_art_status, md_quiz])
|
| 568 |
-
|
| 569 |
-
# ── Podcast ────────────────────────────────────────────────────────
|
| 570 |
-
def do_podcast(nb_id, username):
|
| 571 |
-
if not nb_id:
|
| 572 |
-
return "⚠ Select a notebook first.", "", gr.update(visible=False)
|
| 573 |
-
transcript, audio_path = _be()["podcast"](nb_id, username)
|
| 574 |
-
audio_update = gr.update(value=audio_path, visible=True) if audio_path else gr.update(visible=False)
|
| 575 |
-
return "✦ Podcast generated.", transcript, audio_update
|
| 576 |
-
|
| 577 |
-
btn_podcast.click(
|
| 578 |
-
do_podcast,
|
| 579 |
-
inputs=[s_nb_id, s_user],
|
| 580 |
-
outputs=[md_art_status, md_transcript, aud_podcast],
|
| 581 |
-
)
|
| 582 |
-
|
| 583 |
-
return demo
|
| 584 |
|
| 585 |
|
| 586 |
# ---------------------------------------------------------------------------
|
| 587 |
-
#
|
| 588 |
# ---------------------------------------------------------------------------
|
| 589 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 590 |
if __name__ == "__main__":
|
| 591 |
-
demo
|
| 592 |
-
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
|
| 5 |
+
# Load .env locally; on HF Spaces the secrets are injected automatically
|
| 6 |
load_dotenv()
|
| 7 |
|
| 8 |
+
# Verify the OpenAI key is present at startup so errors are obvious
|
| 9 |
+
if not os.getenv("OPENAI_API_KEY"):
|
| 10 |
+
raise EnvironmentError(
|
| 11 |
+
"OPENAI_API_KEY is not set. "
|
| 12 |
+
"Add it to your .env file locally, or to Space Secrets on Hugging Face."
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
from backend.ingest import ingest_file, ingest_url
|
| 16 |
+
from backend.chat import chat_with_sources
|
| 17 |
+
from backend.artifacts import generate_report, generate_quiz, generate_podcast
|
| 18 |
+
from backend.storage import (
|
| 19 |
+
create_notebook_for_user,
|
| 20 |
+
get_user_notebooks,
|
| 21 |
+
load_chat_history,
|
| 22 |
+
save_message,
|
| 23 |
+
)
|
| 24 |
|
| 25 |
# ---------------------------------------------------------------------------
|
| 26 |
+
# Helpers — all data is now keyed by HF username
|
| 27 |
# ---------------------------------------------------------------------------
|
| 28 |
|
| 29 |
+
def get_username(profile: gr.OAuthProfile | None) -> str:
|
| 30 |
+
"""Return HF username, or 'guest' if not logged in."""
|
| 31 |
+
if profile is None:
|
| 32 |
+
return "guest"
|
| 33 |
+
return profile.username
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
# ---------------------------------------------------------------------------
|
| 37 |
+
# Notebook actions
|
| 38 |
# ---------------------------------------------------------------------------
|
| 39 |
|
| 40 |
+
def create_notebook(name: str, profile: gr.OAuthProfile | None):
|
| 41 |
+
username = get_username(profile)
|
| 42 |
+
nb_id = create_notebook_for_user(username, name)
|
| 43 |
+
notebooks = get_user_notebooks(username)
|
| 44 |
+
choices = [nb["name"] for nb in notebooks]
|
| 45 |
+
return gr.update(choices=choices, value=name), f"Created notebook: {name}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
+
def load_notebooks(profile: gr.OAuthProfile | None):
|
| 49 |
+
"""Populate notebook dropdown when user logs in."""
|
| 50 |
+
username = get_username(profile)
|
| 51 |
+
notebooks = get_user_notebooks(username)
|
| 52 |
+
choices = [nb["name"] for nb in notebooks]
|
| 53 |
+
return gr.update(choices=choices)
|
| 54 |
+
|
| 55 |
|
| 56 |
+
def switch_notebook(name: str, profile: gr.OAuthProfile | None):
|
| 57 |
+
username = get_username(profile)
|
| 58 |
+
notebooks = get_user_notebooks(username)
|
| 59 |
+
for nb in notebooks:
|
| 60 |
+
if nb["name"] == name:
|
| 61 |
+
history = load_chat_history(username, nb["id"])
|
| 62 |
+
messages = [{"role": msg["role"], "content": msg["content"]} for msg in history]
|
| 63 |
+
return nb["id"], f"Switched to: {name}", messages
|
| 64 |
+
return None, "Notebook not found.", []
|
| 65 |
|
| 66 |
|
| 67 |
+
# ---------------------------------------------------------------------------
|
| 68 |
+
# Ingestion
|
| 69 |
+
# ---------------------------------------------------------------------------
|
| 70 |
+
|
| 71 |
+
def handle_file_upload(files, nb_id: str, profile: gr.OAuthProfile | None):
|
| 72 |
+
username = get_username(profile)
|
| 73 |
+
if not nb_id:
|
| 74 |
+
return "Please create or select a notebook first."
|
| 75 |
+
results = []
|
| 76 |
+
for f in files:
|
| 77 |
+
result = ingest_file(f.name, nb_id, username)
|
| 78 |
+
results.append(result)
|
| 79 |
+
return "\n".join(results)
|
| 80 |
|
| 81 |
|
| 82 |
+
def handle_url_ingest(url: str, nb_id: str, profile: gr.OAuthProfile | None):
|
| 83 |
+
username = get_username(profile)
|
| 84 |
+
if not nb_id:
|
| 85 |
+
return "Please create or select a notebook first."
|
| 86 |
+
return ingest_url(url, nb_id, username)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
# ---------------------------------------------------------------------------
|
| 90 |
+
# Chat
|
| 91 |
# ---------------------------------------------------------------------------
|
| 92 |
|
| 93 |
+
def handle_chat(message: str, history: list, nb_id: str, profile: gr.OAuthProfile | None):
|
| 94 |
+
username = get_username(profile)
|
| 95 |
+
if not nb_id:
|
| 96 |
+
return history + [{"role": "user", "content": message}, {"role": "assistant", "content": "Please create or select a notebook first."}], ""
|
| 97 |
+
response = chat_with_sources(message, nb_id, username, history)
|
| 98 |
+
save_message(username, nb_id, "user", message)
|
| 99 |
+
save_message(username, nb_id, "assistant", response)
|
| 100 |
+
history.append({"role": "user", "content": message})
|
| 101 |
+
history.append({"role": "assistant", "content": response})
|
| 102 |
+
return history, ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
|
| 105 |
# ---------------------------------------------------------------------------
|
| 106 |
+
# Artifacts
|
| 107 |
# ---------------------------------------------------------------------------
|
| 108 |
|
| 109 |
+
def handle_generate_report(nb_id: str, profile: gr.OAuthProfile | None):
|
| 110 |
+
username = get_username(profile)
|
| 111 |
+
if not nb_id:
|
| 112 |
+
return "Please create or select a notebook first."
|
| 113 |
+
return generate_report(nb_id, username)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
+
def handle_generate_quiz(nb_id: str, profile: gr.OAuthProfile | None):
|
| 117 |
+
username = get_username(profile)
|
| 118 |
+
if not nb_id:
|
| 119 |
+
return "Please create or select a notebook first."
|
| 120 |
+
return generate_quiz(nb_id, username)
|
|
|
|
| 121 |
|
| 122 |
+
|
| 123 |
+
def handle_generate_podcast(nb_id: str, profile: gr.OAuthProfile | None):
|
| 124 |
+
username = get_username(profile)
|
| 125 |
+
if not nb_id:
|
| 126 |
+
return "Please create or select a notebook first.", None
|
| 127 |
+
return generate_podcast(nb_id, username)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
|
| 130 |
# ---------------------------------------------------------------------------
|
| 131 |
+
# Gradio UI
|
| 132 |
# ---------------------------------------------------------------------------
|
| 133 |
|
| 134 |
+
with gr.Blocks(title="NotebookLM Clone") as demo:
|
| 135 |
+
# Stores the currently selected notebook ID in browser state
|
| 136 |
+
current_nb_id = gr.State(None)
|
| 137 |
+
|
| 138 |
+
with gr.Row():
|
| 139 |
+
gr.Markdown("# NotebookLM Clone")
|
| 140 |
+
# HF OAuth login button — appears automatically on HF Spaces
|
| 141 |
+
login_btn = gr.LoginButton()
|
| 142 |
+
|
| 143 |
+
with gr.Row():
|
| 144 |
+
# ── Left sidebar ──────────────────────────────────────────
|
| 145 |
+
with gr.Column(scale=1):
|
| 146 |
+
gr.Markdown("### Notebooks")
|
| 147 |
+
notebook_dropdown = gr.Dropdown(
|
| 148 |
+
label="Select Notebook", choices=[], interactive=True
|
| 149 |
+
)
|
| 150 |
+
new_notebook_name = gr.Textbox(
|
| 151 |
+
label="New Notebook Name", placeholder="My Notebook"
|
| 152 |
+
)
|
| 153 |
+
create_btn = gr.Button("+ New Notebook")
|
| 154 |
+
notebook_status = gr.Textbox(label="Status", interactive=False)
|
| 155 |
+
|
| 156 |
+
gr.Markdown("### Sources")
|
| 157 |
+
file_upload = gr.File(
|
| 158 |
+
label="Upload Files (.pdf .pptx .txt)", file_count="multiple"
|
| 159 |
+
)
|
| 160 |
+
upload_btn = gr.Button("Upload")
|
| 161 |
+
url_input = gr.Textbox(label="Ingest URL", placeholder="https://...")
|
| 162 |
+
url_btn = gr.Button("Add URL")
|
| 163 |
+
ingest_status = gr.Textbox(label="Ingestion Status", interactive=False)
|
| 164 |
+
|
| 165 |
+
# ── Main panel ────────────────────────────────────────────
|
| 166 |
+
with gr.Column(scale=3):
|
| 167 |
+
with gr.Tabs():
|
| 168 |
+
with gr.Tab("Chat"):
|
| 169 |
+
chatbot = gr.Chatbot(label="Chat with your sources", height=400)
|
| 170 |
+
chat_input = gr.Textbox(label="Ask a question...")
|
| 171 |
+
chat_btn = gr.Button("Send")
|
| 172 |
+
|
| 173 |
+
with gr.Tab("Artifacts"):
|
| 174 |
+
with gr.Tabs():
|
| 175 |
+
with gr.Tab("Report"):
|
| 176 |
+
report_btn = gr.Button("Generate Report")
|
| 177 |
+
report_output = gr.Markdown()
|
| 178 |
+
with gr.Tab("Quiz"):
|
| 179 |
+
quiz_btn = gr.Button("Generate Quiz")
|
| 180 |
+
quiz_output = gr.Markdown()
|
| 181 |
+
with gr.Tab("Podcast"):
|
| 182 |
+
podcast_btn = gr.Button("Generate Podcast")
|
| 183 |
+
podcast_transcript = gr.Markdown()
|
| 184 |
+
podcast_audio = gr.Audio(label="Podcast Audio")
|
| 185 |
+
|
| 186 |
+
# ── Event wiring ──────────────────────────────────────────────
|
| 187 |
+
|
| 188 |
+
# Load user's notebooks after login
|
| 189 |
+
demo.load(load_notebooks, inputs=None, outputs=[notebook_dropdown])
|
| 190 |
+
|
| 191 |
+
create_btn.click(
|
| 192 |
+
create_notebook,
|
| 193 |
+
inputs=[new_notebook_name],
|
| 194 |
+
outputs=[notebook_dropdown, notebook_status],
|
| 195 |
+
)
|
| 196 |
+
notebook_dropdown.change(
|
| 197 |
+
switch_notebook,
|
| 198 |
+
inputs=[notebook_dropdown],
|
| 199 |
+
outputs=[current_nb_id, notebook_status, chatbot],
|
| 200 |
+
)
|
| 201 |
+
upload_btn.click(
|
| 202 |
+
handle_file_upload,
|
| 203 |
+
inputs=[file_upload, current_nb_id],
|
| 204 |
+
outputs=[ingest_status],
|
| 205 |
+
)
|
| 206 |
+
url_btn.click(
|
| 207 |
+
handle_url_ingest,
|
| 208 |
+
inputs=[url_input, current_nb_id],
|
| 209 |
+
outputs=[ingest_status],
|
| 210 |
+
)
|
| 211 |
+
chat_btn.click(
|
| 212 |
+
handle_chat,
|
| 213 |
+
inputs=[chat_input, chatbot, current_nb_id],
|
| 214 |
+
outputs=[chatbot, chat_input],
|
| 215 |
+
)
|
| 216 |
+
report_btn.click(
|
| 217 |
+
handle_generate_report, inputs=[current_nb_id], outputs=[report_output]
|
| 218 |
+
)
|
| 219 |
+
quiz_btn.click(
|
| 220 |
+
handle_generate_quiz, inputs=[current_nb_id], outputs=[quiz_output]
|
| 221 |
+
)
|
| 222 |
+
podcast_btn.click(
|
| 223 |
+
handle_generate_podcast,
|
| 224 |
+
inputs=[current_nb_id],
|
| 225 |
+
outputs=[podcast_transcript, podcast_audio],
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
if __name__ == "__main__":
|
| 229 |
+
demo.launch()
|
|
|
backend/artifacts.py
CHANGED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
from backend.retrieval import get_retriever
|
| 6 |
+
from backend.storage import save_artifact, notebook_dir
|
| 7 |
+
|
| 8 |
+
load_dotenv()
|
| 9 |
+
client = OpenAI() # reads OPENAI_API_KEY from environment automatically
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _get_context(nb_id: str, username: str, query: str = "summarize all content") -> str:
|
| 13 |
+
"""Retrieve top chunks and format them as a context string."""
|
| 14 |
+
retrieve = get_retriever(nb_id, username=username, top_k=10)
|
| 15 |
+
chunks, metas = retrieve(query)
|
| 16 |
+
parts = []
|
| 17 |
+
for chunk, meta in zip(chunks, metas):
|
| 18 |
+
source = meta.get("source", "unknown")
|
| 19 |
+
parts.append(f"[Source: {source}]\n{chunk}")
|
| 20 |
+
return "\n\n---\n\n".join(parts)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _call_llm(prompt: str, temperature: float = 0.4) -> str:
|
| 24 |
+
"""Call GPT-4o and return the response text."""
|
| 25 |
+
response = client.chat.completions.create(
|
| 26 |
+
model="gpt-4o",
|
| 27 |
+
messages=[{"role": "user", "content": prompt}],
|
| 28 |
+
temperature=temperature,
|
| 29 |
+
)
|
| 30 |
+
return response.choices[0].message.content
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# ---------------------------------------------------------------------------
|
| 34 |
+
# Report
|
| 35 |
+
# ---------------------------------------------------------------------------
|
| 36 |
+
|
| 37 |
+
def generate_report(nb_id: str, username: str) -> str:
|
| 38 |
+
"""Generate a comprehensive markdown study report from notebook sources."""
|
| 39 |
+
try:
|
| 40 |
+
context = _get_context(nb_id, username, query="summarize all key information")
|
| 41 |
+
|
| 42 |
+
prompt = (
|
| 43 |
+
"Using ONLY the source material provided below, write a comprehensive "
|
| 44 |
+
"study report in Markdown format. Structure it with:\n"
|
| 45 |
+
"1. A clear title (# heading)\n"
|
| 46 |
+
"2. An executive summary\n"
|
| 47 |
+
"3. Key concepts and themes (## headings)\n"
|
| 48 |
+
"4. Important details and supporting evidence\n"
|
| 49 |
+
"5. Conclusions\n\n"
|
| 50 |
+
"Cite sources inline using [Source: filename] format.\n\n"
|
| 51 |
+
f"Source Material:\n{context}"
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
report = _call_llm(prompt)
|
| 55 |
+
save_artifact(username, nb_id, "reports", report, extension="md")
|
| 56 |
+
return report
|
| 57 |
+
|
| 58 |
+
except Exception as e:
|
| 59 |
+
return f"Error generating report: {str(e)}"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ---------------------------------------------------------------------------
|
| 63 |
+
# Quiz
|
| 64 |
+
# ---------------------------------------------------------------------------
|
| 65 |
+
|
| 66 |
+
def generate_quiz(nb_id: str, username: str) -> str:
|
| 67 |
+
"""Generate a 10-question multiple-choice quiz with answer key."""
|
| 68 |
+
try:
|
| 69 |
+
context = _get_context(nb_id, username, query="key facts, concepts, and details")
|
| 70 |
+
|
| 71 |
+
prompt = (
|
| 72 |
+
"Using ONLY the source material provided below, create a 10-question "
|
| 73 |
+
"multiple-choice quiz in Markdown format.\n\n"
|
| 74 |
+
"Format each question exactly like this:\n"
|
| 75 |
+
"**Q1.** Question text here?\n"
|
| 76 |
+
"- A) Option one\n"
|
| 77 |
+
"- B) Option two\n"
|
| 78 |
+
"- C) Option three\n"
|
| 79 |
+
"- D) Option four\n\n"
|
| 80 |
+
"After all 10 questions, include a section:\n"
|
| 81 |
+
"## Answer Key\n"
|
| 82 |
+
"1. A, 2. C, ... etc, with a one-sentence explanation for each answer.\n\n"
|
| 83 |
+
f"Source Material:\n{context}"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
quiz = _call_llm(prompt)
|
| 87 |
+
save_artifact(username, nb_id, "quizzes", quiz, extension="md")
|
| 88 |
+
return quiz
|
| 89 |
+
|
| 90 |
+
except Exception as e:
|
| 91 |
+
return f"Error generating quiz: {str(e)}"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------
|
| 95 |
+
# Podcast
|
| 96 |
+
# ---------------------------------------------------------------------------
|
| 97 |
+
|
| 98 |
+
def generate_podcast(nb_id: str, username: str):
|
| 99 |
+
"""
|
| 100 |
+
Generate a two-host podcast transcript and convert it to audio.
|
| 101 |
+
Returns (transcript_markdown, audio_file_path).
|
| 102 |
+
"""
|
| 103 |
+
try:
|
| 104 |
+
context = _get_context(nb_id, username, query="main topics and interesting insights")
|
| 105 |
+
|
| 106 |
+
# Step 1: Generate transcript
|
| 107 |
+
transcript_prompt = (
|
| 108 |
+
"Using ONLY the source material below, write an engaging podcast script "
|
| 109 |
+
"as a conversation between two hosts: Alex and Jordan.\n\n"
|
| 110 |
+
"Guidelines:\n"
|
| 111 |
+
"- Alex introduces topics and asks questions\n"
|
| 112 |
+
"- Jordan provides deeper explanations and insights\n"
|
| 113 |
+
"- Make it conversational, informative, and around 5-7 minutes when read aloud\n"
|
| 114 |
+
"- Format each line as: **Alex:** text or **Jordan:** text\n"
|
| 115 |
+
"- Start with a brief intro and end with a summary and sign-off\n\n"
|
| 116 |
+
f"Source Material:\n{context}"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
transcript = _call_llm(transcript_prompt, temperature=0.6)
|
| 120 |
+
|
| 121 |
+
# Save transcript as markdown
|
| 122 |
+
save_artifact(username, nb_id, "podcasts", transcript, extension="md")
|
| 123 |
+
|
| 124 |
+
# Step 2: Convert transcript to audio using OpenAI TTS
|
| 125 |
+
# Strip markdown formatting for cleaner audio
|
| 126 |
+
clean_transcript = transcript.replace("**Alex:**", "Alex:").replace("**Jordan:**", "Jordan:")
|
| 127 |
+
|
| 128 |
+
audio_response = client.audio.speech.create(
|
| 129 |
+
model="tts-1",
|
| 130 |
+
voice="alloy",
|
| 131 |
+
input=clean_transcript,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Save audio file
|
| 135 |
+
podcasts_dir = notebook_dir(username, nb_id) / "artifacts" / "podcasts"
|
| 136 |
+
podcasts_dir.mkdir(parents=True, exist_ok=True)
|
| 137 |
+
existing = list(podcasts_dir.glob("*.mp3"))
|
| 138 |
+
audio_path = str(podcasts_dir / f"podcast_{len(existing) + 1}.mp3")
|
| 139 |
+
audio_response.stream_to_file(audio_path)
|
| 140 |
+
|
| 141 |
+
return transcript, audio_path
|
| 142 |
+
|
| 143 |
+
except Exception as e:
|
| 144 |
+
error_msg = f"Error generating podcast: {str(e)}"
|
| 145 |
+
return error_msg, None
|
backend/chat.py
CHANGED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
from backend.retrieval import get_retriever
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
client = OpenAI() # reads OPENAI_API_KEY from environment automatically
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def format_history_for_openai(history: list) -> list:
|
| 11 |
+
"""
|
| 12 |
+
Convert Gradio chat history (list of {role, content} dicts)
|
| 13 |
+
into OpenAI message format.
|
| 14 |
+
"""
|
| 15 |
+
return [{"role": msg["role"], "content": msg["content"]} for msg in history if msg.get("content")]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def chat_with_sources(message: str, nb_id: str, username: str, history: list) -> str:
|
| 19 |
+
"""
|
| 20 |
+
Retrieve relevant chunks from ChromaDB, then ask GPT-4o
|
| 21 |
+
to answer using only those chunks. Returns answer with citations.
|
| 22 |
+
"""
|
| 23 |
+
try:
|
| 24 |
+
# Retrieve top-k relevant chunks
|
| 25 |
+
retrieve = get_retriever(nb_id, username=username, top_k=5)
|
| 26 |
+
chunks, metas = retrieve(message)
|
| 27 |
+
|
| 28 |
+
# Build context string with source labels
|
| 29 |
+
context_parts = []
|
| 30 |
+
for chunk, meta in zip(chunks, metas):
|
| 31 |
+
source = meta.get("source", "unknown")
|
| 32 |
+
chunk_num = meta.get("chunk", "?")
|
| 33 |
+
context_parts.append(f"[Source: {source} | Chunk: {chunk_num}]\n{chunk}")
|
| 34 |
+
context = "\n\n---\n\n".join(context_parts)
|
| 35 |
+
|
| 36 |
+
system_prompt = (
|
| 37 |
+
"You are a helpful research assistant. "
|
| 38 |
+
"Answer the user's question using ONLY the context provided below. "
|
| 39 |
+
"After each claim, cite the source inline using the format: "
|
| 40 |
+
"[Source: filename | Chunk: N]. "
|
| 41 |
+
"If the context does not contain enough information to answer, "
|
| 42 |
+
"say so clearly rather than making things up.\n\n"
|
| 43 |
+
f"Context:\n{context}"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Build message history for multi-turn conversation
|
| 47 |
+
openai_messages = [{"role": "system", "content": system_prompt}]
|
| 48 |
+
openai_messages += format_history_for_openai(history)
|
| 49 |
+
openai_messages.append({"role": "user", "content": message})
|
| 50 |
+
|
| 51 |
+
response = client.chat.completions.create(
|
| 52 |
+
model="gpt-4o",
|
| 53 |
+
messages=openai_messages,
|
| 54 |
+
temperature=0.3,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
answer = response.choices[0].message.content
|
| 58 |
+
|
| 59 |
+
# Append a deduplicated source list at the bottom
|
| 60 |
+
seen_sources = set()
|
| 61 |
+
source_list = []
|
| 62 |
+
for meta in metas:
|
| 63 |
+
src = meta.get("source", "unknown")
|
| 64 |
+
if src not in seen_sources:
|
| 65 |
+
seen_sources.add(src)
|
| 66 |
+
source_list.append(f"- {src}")
|
| 67 |
+
|
| 68 |
+
if source_list:
|
| 69 |
+
answer += "\n\n**Sources consulted:**\n" + "\n".join(source_list)
|
| 70 |
+
|
| 71 |
+
return answer
|
| 72 |
+
|
| 73 |
+
except Exception as e:
|
| 74 |
+
return f"Error generating response: {str(e)}"
|
backend/ingest.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
from PyPDF2 import PdfReader
|
| 7 |
+
from pptx import Presentation
|
| 8 |
+
import requests
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
+
import chromadb
|
| 11 |
+
from openai import OpenAI
|
| 12 |
+
from backend.storage import save_raw_file, save_extracted_text, notebook_dir
|
| 13 |
+
|
| 14 |
+
load_dotenv()
|
| 15 |
+
client = OpenAI() # reads OPENAI_API_KEY from environment automatically
|
| 16 |
+
DATA_DIR = Path("data/users")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# Directory helper
|
| 20 |
+
|
| 21 |
+
def get_chroma_path(username: str, nb_id: str) -> str:
|
| 22 |
+
path = notebook_dir(username, nb_id) / "chroma"
|
| 23 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 24 |
+
return str(path)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Chunking
|
| 28 |
+
|
| 29 |
+
def chunk_text(text: str, chunk_size: int = 500, overlap: int = 50) -> list:
|
| 30 |
+
"""Split text into overlapping word-based chunks."""
|
| 31 |
+
words = text.split()
|
| 32 |
+
chunks = []
|
| 33 |
+
for i in range(0, len(words), chunk_size - overlap):
|
| 34 |
+
chunk = " ".join(words[i : i + chunk_size])
|
| 35 |
+
if chunk:
|
| 36 |
+
chunks.append(chunk)
|
| 37 |
+
return chunks
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# Embedding + ChromaDB storage
|
| 41 |
+
|
| 42 |
+
def embed_and_store(chunks: list, source_name: str, nb_id: str, username: str):
|
| 43 |
+
"""Embed chunks using OpenAI and store in ChromaDB."""
|
| 44 |
+
chroma_path = get_chroma_path(username, nb_id)
|
| 45 |
+
chroma_client = chromadb.PersistentClient(path=chroma_path)
|
| 46 |
+
collection = chroma_client.get_or_create_collection(
|
| 47 |
+
name="sources",
|
| 48 |
+
metadata={"hnsw:space": "cosine"},
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Embed in batches of 100 to stay within API limits
|
| 52 |
+
batch_size = 100
|
| 53 |
+
for batch_start in range(0, len(chunks), batch_size):
|
| 54 |
+
batch = chunks[batch_start : batch_start + batch_size]
|
| 55 |
+
|
| 56 |
+
response = client.embeddings.create(
|
| 57 |
+
model="text-embedding-3-small",
|
| 58 |
+
input=batch,
|
| 59 |
+
)
|
| 60 |
+
embeddings = [item.embedding for item in response.data]
|
| 61 |
+
|
| 62 |
+
collection.add(
|
| 63 |
+
documents=batch,
|
| 64 |
+
embeddings=embeddings,
|
| 65 |
+
metadatas=[
|
| 66 |
+
{"source": source_name, "chunk": batch_start + i}
|
| 67 |
+
for i in range(len(batch))
|
| 68 |
+
],
|
| 69 |
+
ids=[str(uuid.uuid4()) for _ in batch],
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# Text extraction
|
| 74 |
+
|
| 75 |
+
def extract_pdf(filepath: str) -> str:
|
| 76 |
+
"""Extract text from a PDF file."""
|
| 77 |
+
reader = PdfReader(filepath)
|
| 78 |
+
pages = []
|
| 79 |
+
for page_num, page in enumerate(reader.pages):
|
| 80 |
+
text = page.extract_text() or ""
|
| 81 |
+
if text.strip():
|
| 82 |
+
pages.append(f"[Page {page_num + 1}]\n{text}")
|
| 83 |
+
return "\n\n".join(pages)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def extract_pptx(filepath: str) -> str:
|
| 87 |
+
"""Extract text from a PPTX file."""
|
| 88 |
+
prs = Presentation(filepath)
|
| 89 |
+
texts = []
|
| 90 |
+
for slide_num, slide in enumerate(prs.slides):
|
| 91 |
+
slide_texts = []
|
| 92 |
+
for shape in slide.shapes:
|
| 93 |
+
if hasattr(shape, "text") and shape.text.strip():
|
| 94 |
+
slide_texts.append(shape.text.strip())
|
| 95 |
+
if slide_texts:
|
| 96 |
+
texts.append(f"[Slide {slide_num + 1}]\n" + "\n".join(slide_texts))
|
| 97 |
+
return "\n\n".join(texts)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def extract_txt(filepath: str) -> str:
|
| 101 |
+
"""Read a plain text file."""
|
| 102 |
+
with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
|
| 103 |
+
return f.read()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def fetch_url(url: str) -> str:
|
| 107 |
+
"""Fetch and extract readable text from a web page."""
|
| 108 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
| 109 |
+
response = requests.get(url, timeout=15, headers=headers)
|
| 110 |
+
response.raise_for_status()
|
| 111 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 112 |
+
|
| 113 |
+
# Remove script and style tags
|
| 114 |
+
for tag in soup(["script", "style", "nav", "footer", "header"]):
|
| 115 |
+
tag.decompose()
|
| 116 |
+
|
| 117 |
+
return soup.get_text(separator=" ", strip=True)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# Public ingest functions
|
| 121 |
+
|
| 122 |
+
def ingest_file(filepath: str, nb_id: str, username: str) -> str:
|
| 123 |
+
"""Extract, chunk, embed, and store a file into the notebook vector store."""
|
| 124 |
+
ext = Path(filepath).suffix.lower()
|
| 125 |
+
filename = Path(filepath).name
|
| 126 |
+
|
| 127 |
+
try:
|
| 128 |
+
if ext == ".pdf":
|
| 129 |
+
text = extract_pdf(filepath)
|
| 130 |
+
elif ext == ".pptx":
|
| 131 |
+
text = extract_pptx(filepath)
|
| 132 |
+
elif ext == ".txt":
|
| 133 |
+
text = extract_txt(filepath)
|
| 134 |
+
else:
|
| 135 |
+
return f"Unsupported file type: {ext}. Supported: .pdf, .pptx, .txt"
|
| 136 |
+
|
| 137 |
+
if not text.strip():
|
| 138 |
+
return f"Warning: no text could be extracted from {filename}"
|
| 139 |
+
|
| 140 |
+
# Save raw file and extracted text
|
| 141 |
+
with open(filepath, "rb") as f:
|
| 142 |
+
save_raw_file(username, nb_id, filename, f.read())
|
| 143 |
+
save_extracted_text(username, nb_id, filename, text)
|
| 144 |
+
|
| 145 |
+
# Chunk and embed
|
| 146 |
+
chunks = chunk_text(text)
|
| 147 |
+
embed_and_store(chunks, filename, nb_id, username)
|
| 148 |
+
|
| 149 |
+
return f"Ingested {filename} ({len(chunks)} chunks)"
|
| 150 |
+
|
| 151 |
+
except Exception as e:
|
| 152 |
+
return f"Error ingesting {filename}: {str(e)}"
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def ingest_url(url: str, nb_id: str, username: str) -> str:
|
| 156 |
+
"""Fetch, chunk, embed, and store a web page into the notebook vector store."""
|
| 157 |
+
try:
|
| 158 |
+
text = fetch_url(url)
|
| 159 |
+
|
| 160 |
+
if not text.strip():
|
| 161 |
+
return f"Warning: no text found at {url}"
|
| 162 |
+
|
| 163 |
+
save_extracted_text(username, nb_id, url.replace("/", "_"), text)
|
| 164 |
+
|
| 165 |
+
chunks = chunk_text(text)
|
| 166 |
+
embed_and_store(chunks, url, nb_id, username)
|
| 167 |
+
|
| 168 |
+
return f"Ingested URL: {url} ({len(chunks)} chunks)"
|
| 169 |
+
|
| 170 |
+
except requests.exceptions.RequestException as e:
|
| 171 |
+
return f"Error fetching URL {url}: {str(e)}"
|
| 172 |
+
except Exception as e:
|
| 173 |
+
return f"Error ingesting URL {url}: {str(e)}"
|
backend/ingestion.py
CHANGED
|
@@ -1,17 +1,21 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
------------
|
| 4 |
-
Ingestion pipeline: extract
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
- "
|
| 9 |
-
- "
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
import hashlib
|
| 13 |
-
import os
|
| 14 |
import re
|
|
|
|
| 15 |
from pathlib import Path
|
| 16 |
from typing import Literal, Optional
|
| 17 |
from urllib.parse import urlparse
|
|
@@ -25,41 +29,46 @@ from backend import storage
|
|
| 25 |
# Config
|
| 26 |
# ---------------------------------------------------------------------------
|
| 27 |
|
| 28 |
-
OPENAI_API_KEY
|
| 29 |
-
CHUNK_SIZE
|
| 30 |
-
CHUNK_OVERLAP
|
| 31 |
-
EMBED_MODEL
|
| 32 |
-
|
| 33 |
ChunkStrategy = Literal["fixed", "sentence", "recursive"]
|
| 34 |
-
|
| 35 |
|
| 36 |
|
| 37 |
# ---------------------------------------------------------------------------
|
| 38 |
-
#
|
| 39 |
# ---------------------------------------------------------------------------
|
| 40 |
|
| 41 |
-
def
|
| 42 |
return OpenAIEmbeddingFunction(
|
| 43 |
api_key=OPENAI_API_KEY,
|
| 44 |
model_name=EMBED_MODEL,
|
| 45 |
)
|
| 46 |
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
def _get_collection(username: str, notebook_id: str):
|
| 49 |
chroma_path = storage.get_chroma_path(username, notebook_id)
|
| 50 |
client = chromadb.PersistentClient(path=chroma_path)
|
| 51 |
-
|
| 52 |
name="sources",
|
| 53 |
-
embedding_function=
|
| 54 |
metadata={"hnsw:space": "cosine"},
|
| 55 |
)
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
# ---------------------------------------------------------------------------
|
| 59 |
# Text extraction
|
| 60 |
# ---------------------------------------------------------------------------
|
| 61 |
|
| 62 |
-
def
|
|
|
|
| 63 |
import pdfplumber
|
| 64 |
texts = []
|
| 65 |
with pdfplumber.open(str(file_path)) as pdf:
|
|
@@ -70,48 +79,53 @@ def _extract_pdf(file_path: Path) -> str:
|
|
| 70 |
return "\n\n".join(texts)
|
| 71 |
|
| 72 |
|
| 73 |
-
def
|
|
|
|
| 74 |
from pptx import Presentation
|
| 75 |
prs = Presentation(str(file_path))
|
| 76 |
-
|
| 77 |
-
for
|
| 78 |
-
|
| 79 |
for shape in slide.shapes:
|
| 80 |
if shape.has_text_frame:
|
| 81 |
for para in shape.text_frame.paragraphs:
|
| 82 |
line = para.text.strip()
|
| 83 |
if line:
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
return "\n\n".join(
|
| 87 |
|
| 88 |
|
| 89 |
-
def
|
|
|
|
| 90 |
import trafilatura
|
| 91 |
downloaded = trafilatura.fetch_url(url)
|
| 92 |
if downloaded is None:
|
| 93 |
raise ValueError(f"Could not fetch URL: {url}")
|
| 94 |
text = trafilatura.extract(downloaded, include_links=False, include_tables=True)
|
| 95 |
if not text:
|
| 96 |
-
raise ValueError(f"No readable text found at: {url}")
|
| 97 |
return text
|
| 98 |
|
| 99 |
|
| 100 |
def extract_text(source: str | Path) -> tuple[str, str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
src = str(source)
|
| 102 |
parsed = urlparse(src)
|
| 103 |
-
|
| 104 |
if parsed.scheme in ("http", "https"):
|
| 105 |
-
text =
|
| 106 |
name = parsed.netloc + parsed.path.replace("/", "_")
|
| 107 |
return text, name
|
| 108 |
|
| 109 |
p = Path(src)
|
| 110 |
suffix = p.suffix.lower()
|
| 111 |
if suffix == ".pdf":
|
| 112 |
-
return
|
| 113 |
elif suffix in (".pptx", ".ppt"):
|
| 114 |
-
return
|
| 115 |
elif suffix in (".txt", ".md"):
|
| 116 |
return p.read_text(encoding="utf-8", errors="ignore"), p.name
|
| 117 |
else:
|
|
@@ -123,27 +137,33 @@ def extract_text(source: str | Path) -> tuple[str, str]:
|
|
| 123 |
# ---------------------------------------------------------------------------
|
| 124 |
|
| 125 |
def _fixed_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
|
|
|
|
| 126 |
chunks, start = [], 0
|
| 127 |
while start < len(text):
|
| 128 |
-
|
|
|
|
| 129 |
start += size - overlap
|
| 130 |
return [c.strip() for c in chunks if c.strip()]
|
| 131 |
|
| 132 |
|
| 133 |
def _sentence_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
|
|
|
|
| 134 |
sentences = re.split(r'(?<=[.!?])\s+', text)
|
| 135 |
chunks, current, current_len = [], [], 0
|
| 136 |
for sent in sentences:
|
| 137 |
slen = len(sent)
|
| 138 |
if current_len + slen > size and current:
|
| 139 |
chunks.append(" ".join(current))
|
| 140 |
-
|
|
|
|
|
|
|
| 141 |
for s in reversed(current):
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
if
|
| 145 |
break
|
| 146 |
-
current
|
|
|
|
| 147 |
current.append(sent)
|
| 148 |
current_len += slen
|
| 149 |
if current:
|
|
@@ -152,6 +172,10 @@ def _sentence_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVE
|
|
| 152 |
|
| 153 |
|
| 154 |
def _recursive_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
separators = ["\n\n", "\n", ". ", " ", ""]
|
| 156 |
|
| 157 |
def _split(t: str, seps: list[str]) -> list[str]:
|
|
@@ -159,31 +183,34 @@ def _recursive_chunks(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OV
|
|
| 159 |
return [t] if t.strip() else []
|
| 160 |
if not seps:
|
| 161 |
return _fixed_chunks(t, size, overlap)
|
|
|
|
| 162 |
sep = seps[0]
|
| 163 |
parts = t.split(sep)
|
| 164 |
-
|
| 165 |
for part in parts:
|
| 166 |
candidate = current + (sep if current else "") + part
|
| 167 |
if len(candidate) <= size:
|
| 168 |
current = candidate
|
| 169 |
else:
|
| 170 |
if current:
|
| 171 |
-
|
| 172 |
current = part
|
| 173 |
if current:
|
| 174 |
-
|
| 175 |
-
return
|
| 176 |
|
| 177 |
raw = _split(text, separators)
|
| 178 |
-
|
|
|
|
| 179 |
for i, chunk in enumerate(raw):
|
| 180 |
if i > 0 and overlap > 0:
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
| 184 |
|
| 185 |
|
| 186 |
-
def chunk_text(text: str, strategy: ChunkStrategy =
|
| 187 |
if strategy == "fixed":
|
| 188 |
return _fixed_chunks(text)
|
| 189 |
elif strategy == "sentence":
|
|
@@ -193,25 +220,34 @@ def chunk_text(text: str, strategy: ChunkStrategy = DEFAULT_STRATEGY) -> list[st
|
|
| 193 |
|
| 194 |
|
| 195 |
# ---------------------------------------------------------------------------
|
| 196 |
-
#
|
| 197 |
# ---------------------------------------------------------------------------
|
| 198 |
|
| 199 |
def ingest_source(
|
| 200 |
username: str,
|
| 201 |
notebook_id: str,
|
| 202 |
source: str | Path,
|
| 203 |
-
chunk_strategy: ChunkStrategy =
|
| 204 |
raw_bytes: Optional[bytes] = None,
|
| 205 |
) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
text, source_name = extract_text(source)
|
| 207 |
|
|
|
|
| 208 |
if raw_bytes is not None:
|
| 209 |
storage.save_raw_file(username, notebook_id, source_name, raw_bytes)
|
| 210 |
-
|
|
|
|
| 211 |
storage.save_extracted_text(username, notebook_id, source_name, text)
|
| 212 |
|
|
|
|
| 213 |
chunks = chunk_text(text, strategy=chunk_strategy)
|
| 214 |
|
|
|
|
| 215 |
ids, documents, metadatas = [], [], []
|
| 216 |
for i, chunk in enumerate(chunks):
|
| 217 |
chunk_id = hashlib.md5(f"{source_name}_{i}_{chunk[:40]}".encode()).hexdigest()
|
|
@@ -224,12 +260,16 @@ def ingest_source(
|
|
| 224 |
"strategy": chunk_strategy,
|
| 225 |
})
|
| 226 |
|
|
|
|
| 227 |
collection = _get_collection(username, notebook_id)
|
| 228 |
-
|
|
|
|
|
|
|
|
|
|
| 229 |
collection.upsert(
|
| 230 |
-
ids=ids[start:
|
| 231 |
-
documents=documents[start:
|
| 232 |
-
metadatas=metadatas[start:
|
| 233 |
)
|
| 234 |
|
| 235 |
return {
|
|
@@ -241,6 +281,7 @@ def ingest_source(
|
|
| 241 |
|
| 242 |
|
| 243 |
def delete_source(username: str, notebook_id: str, source_name: str) -> int:
|
|
|
|
| 244 |
collection = _get_collection(username, notebook_id)
|
| 245 |
results = collection.get(where={"source": source_name})
|
| 246 |
if results and results["ids"]:
|
|
@@ -250,8 +291,8 @@ def delete_source(username: str, notebook_id: str, source_name: str) -> int:
|
|
| 250 |
|
| 251 |
|
| 252 |
def list_indexed_sources(username: str, notebook_id: str) -> list[str]:
|
|
|
|
| 253 |
collection = _get_collection(username, notebook_id)
|
| 254 |
results = collection.get(include=["metadatas"])
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
return sorted({m["source"] for m in results["metadatas"]})
|
|
|
|
| 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
|
|
|
|
| 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:
|
|
|
|
| 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:
|
|
|
|
| 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:
|
|
|
|
| 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]:
|
|
|
|
| 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":
|
|
|
|
| 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()
|
|
|
|
| 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 {
|
|
|
|
| 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"]:
|
|
|
|
| 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
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import chromadb
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
from backend.storage import notebook_dir
|
| 6 |
+
|
| 7 |
+
load_dotenv()
|
| 8 |
+
client = OpenAI() # reads OPENAI_API_KEY from environment automatically
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def get_embedding(text: str) -> list:
|
| 12 |
+
"""Get an embedding vector for a query string."""
|
| 13 |
+
response = client.embeddings.create(
|
| 14 |
+
model="text-embedding-3-small",
|
| 15 |
+
input=[text],
|
| 16 |
+
)
|
| 17 |
+
return response.data[0].embedding
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_retriever(nb_id: str, username: str = "default", top_k: int = 5):
|
| 21 |
+
"""
|
| 22 |
+
Returns a retrieval function for the given notebook.
|
| 23 |
+
The returned function takes a query string and returns (chunks, metadatas).
|
| 24 |
+
"""
|
| 25 |
+
def retrieve(query: str):
|
| 26 |
+
try:
|
| 27 |
+
chroma_path = str(notebook_dir(username, nb_id) / "chroma")
|
| 28 |
+
chroma_client = chromadb.PersistentClient(path=chroma_path)
|
| 29 |
+
collection = chroma_client.get_or_create_collection(
|
| 30 |
+
name="sources",
|
| 31 |
+
metadata={"hnsw:space": "cosine"},
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Return empty if nothing has been ingested yet
|
| 35 |
+
if collection.count() == 0:
|
| 36 |
+
return ["No sources have been ingested yet."], [{"source": "none", "chunk": 0}]
|
| 37 |
+
|
| 38 |
+
query_embedding = get_embedding(query)
|
| 39 |
+
results = collection.query(
|
| 40 |
+
query_embeddings=[query_embedding],
|
| 41 |
+
n_results=min(top_k, collection.count()),
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
chunks = results["documents"][0]
|
| 45 |
+
metadatas = results["metadatas"][0]
|
| 46 |
+
return chunks, metadatas
|
| 47 |
+
|
| 48 |
+
except Exception as e:
|
| 49 |
+
return [f"Retrieval error: {str(e)}"], [{"source": "error", "chunk": 0}]
|
| 50 |
+
|
| 51 |
+
return retrieve
|
backend/storage.py
CHANGED
|
@@ -1,9 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
------------------
|
| 4 |
-
All filesystem reads/writes for user data.
|
| 5 |
|
| 6 |
-
|
| 7 |
data/users/<username>/notebooks/index.json
|
| 8 |
data/users/<username>/notebooks/<nb-id>/chat/messages.jsonl
|
| 9 |
data/users/<username>/notebooks/<nb-id>/artifacts/reports/
|
|
@@ -16,16 +14,12 @@ Directory layout:
|
|
| 16 |
|
| 17 |
import json
|
| 18 |
import uuid
|
| 19 |
-
import shutil
|
| 20 |
from datetime import datetime
|
| 21 |
from pathlib import Path
|
| 22 |
|
| 23 |
DATA_ROOT = Path("data/users")
|
| 24 |
|
| 25 |
-
|
| 26 |
-
# ---------------------------------------------------------------------------
|
| 27 |
# Path helpers
|
| 28 |
-
# ---------------------------------------------------------------------------
|
| 29 |
|
| 30 |
def user_dir(username: str) -> Path:
|
| 31 |
p = DATA_ROOT / username / "notebooks"
|
|
@@ -39,21 +33,14 @@ def notebook_dir(username: str, nb_id: str) -> Path:
|
|
| 39 |
return p
|
| 40 |
|
| 41 |
|
| 42 |
-
def get_chroma_path(username: str, nb_id: str) -> str:
|
| 43 |
-
p = notebook_dir(username, nb_id) / "chroma"
|
| 44 |
-
p.mkdir(parents=True, exist_ok=True)
|
| 45 |
-
return str(p)
|
| 46 |
-
|
| 47 |
-
|
| 48 |
def index_path(username: str) -> Path:
|
| 49 |
return user_dir(username) / "index.json"
|
| 50 |
|
| 51 |
|
| 52 |
-
# ---------------------------------------------------------------------------
|
| 53 |
# Notebook CRUD
|
| 54 |
-
# ---------------------------------------------------------------------------
|
| 55 |
|
| 56 |
def get_user_notebooks(username: str) -> list:
|
|
|
|
| 57 |
path = index_path(username)
|
| 58 |
if not path.exists():
|
| 59 |
return []
|
|
@@ -67,6 +54,7 @@ def _save_index(username: str, notebooks: list):
|
|
| 67 |
|
| 68 |
|
| 69 |
def create_notebook_for_user(username: str, name: str) -> str:
|
|
|
|
| 70 |
nb_id = str(uuid.uuid4())
|
| 71 |
notebooks = get_user_notebooks(username)
|
| 72 |
notebooks.append({
|
|
@@ -76,11 +64,10 @@ def create_notebook_for_user(username: str, name: str) -> str:
|
|
| 76 |
})
|
| 77 |
_save_index(username, notebooks)
|
| 78 |
|
|
|
|
| 79 |
nb = notebook_dir(username, nb_id)
|
| 80 |
-
for sub in [
|
| 81 |
-
|
| 82 |
-
"artifacts/reports", "artifacts/quizzes", "artifacts/podcasts",
|
| 83 |
-
]:
|
| 84 |
(nb / sub).mkdir(parents=True, exist_ok=True)
|
| 85 |
|
| 86 |
return nb_id
|
|
@@ -95,6 +82,7 @@ def rename_notebook(username: str, nb_id: str, new_name: str):
|
|
| 95 |
|
| 96 |
|
| 97 |
def delete_notebook(username: str, nb_id: str):
|
|
|
|
| 98 |
notebooks = [nb for nb in get_user_notebooks(username) if nb["id"] != nb_id]
|
| 99 |
_save_index(username, notebooks)
|
| 100 |
nb_path = notebook_dir(username, nb_id)
|
|
@@ -102,9 +90,7 @@ def delete_notebook(username: str, nb_id: str):
|
|
| 102 |
shutil.rmtree(nb_path)
|
| 103 |
|
| 104 |
|
| 105 |
-
# ---------------------------------------------------------------------------
|
| 106 |
# Chat persistence
|
| 107 |
-
# ---------------------------------------------------------------------------
|
| 108 |
|
| 109 |
def _chat_path(username: str, nb_id: str) -> Path:
|
| 110 |
p = notebook_dir(username, nb_id) / "chat"
|
|
@@ -113,6 +99,7 @@ def _chat_path(username: str, nb_id: str) -> Path:
|
|
| 113 |
|
| 114 |
|
| 115 |
def save_message(username: str, nb_id: str, role: str, content: str):
|
|
|
|
| 116 |
path = _chat_path(username, nb_id)
|
| 117 |
with open(path, "a") as f:
|
| 118 |
f.write(json.dumps({
|
|
@@ -123,6 +110,7 @@ def save_message(username: str, nb_id: str, role: str, content: str):
|
|
| 123 |
|
| 124 |
|
| 125 |
def load_chat_history(username: str, nb_id: str) -> list:
|
|
|
|
| 126 |
path = _chat_path(username, nb_id)
|
| 127 |
if not path.exists():
|
| 128 |
return []
|
|
@@ -130,31 +118,32 @@ def load_chat_history(username: str, nb_id: str) -> list:
|
|
| 130 |
return [json.loads(line) for line in f if line.strip()]
|
| 131 |
|
| 132 |
|
| 133 |
-
# ---------------------------------------------------------------------------
|
| 134 |
# Artifact helpers
|
| 135 |
-
# ---------------------------------------------------------------------------
|
| 136 |
|
| 137 |
def save_artifact(username: str, nb_id: str, artifact_type: str,
|
| 138 |
content: str, extension: str = "md") -> Path:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
folder = notebook_dir(username, nb_id) / "artifacts" / artifact_type
|
| 140 |
folder.mkdir(parents=True, exist_ok=True)
|
| 141 |
existing = list(folder.glob(f"*.{extension}"))
|
| 142 |
-
|
| 143 |
-
path = folder / f"{artifact_type[:-1]}_{
|
| 144 |
path.write_text(content, encoding="utf-8")
|
| 145 |
return path
|
| 146 |
|
| 147 |
|
| 148 |
def list_artifacts(username: str, nb_id: str, artifact_type: str) -> list:
|
|
|
|
| 149 |
folder = notebook_dir(username, nb_id) / "artifacts" / artifact_type
|
| 150 |
if not folder.exists():
|
| 151 |
return []
|
| 152 |
return [p.name for p in sorted(folder.iterdir())]
|
| 153 |
|
| 154 |
|
| 155 |
-
#
|
| 156 |
-
# Raw / extracted file storage
|
| 157 |
-
# ---------------------------------------------------------------------------
|
| 158 |
|
| 159 |
def save_raw_file(username: str, nb_id: str, filename: str, data: bytes) -> Path:
|
| 160 |
folder = notebook_dir(username, nb_id) / "files_raw"
|
|
|
|
| 1 |
"""
|
| 2 |
+
storage.py — handles all reading/writing to the /data folder.
|
|
|
|
|
|
|
| 3 |
|
| 4 |
+
Structure:
|
| 5 |
data/users/<username>/notebooks/index.json
|
| 6 |
data/users/<username>/notebooks/<nb-id>/chat/messages.jsonl
|
| 7 |
data/users/<username>/notebooks/<nb-id>/artifacts/reports/
|
|
|
|
| 14 |
|
| 15 |
import json
|
| 16 |
import uuid
|
|
|
|
| 17 |
from datetime import datetime
|
| 18 |
from pathlib import Path
|
| 19 |
|
| 20 |
DATA_ROOT = Path("data/users")
|
| 21 |
|
|
|
|
|
|
|
| 22 |
# Path helpers
|
|
|
|
| 23 |
|
| 24 |
def user_dir(username: str) -> Path:
|
| 25 |
p = DATA_ROOT / username / "notebooks"
|
|
|
|
| 33 |
return p
|
| 34 |
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
def index_path(username: str) -> Path:
|
| 37 |
return user_dir(username) / "index.json"
|
| 38 |
|
| 39 |
|
|
|
|
| 40 |
# Notebook CRUD
|
|
|
|
| 41 |
|
| 42 |
def get_user_notebooks(username: str) -> list:
|
| 43 |
+
"""Return list of notebook dicts for a user."""
|
| 44 |
path = index_path(username)
|
| 45 |
if not path.exists():
|
| 46 |
return []
|
|
|
|
| 54 |
|
| 55 |
|
| 56 |
def create_notebook_for_user(username: str, name: str) -> str:
|
| 57 |
+
"""Create a new notebook and return its ID."""
|
| 58 |
nb_id = str(uuid.uuid4())
|
| 59 |
notebooks = get_user_notebooks(username)
|
| 60 |
notebooks.append({
|
|
|
|
| 64 |
})
|
| 65 |
_save_index(username, notebooks)
|
| 66 |
|
| 67 |
+
# Pre-create subdirectories
|
| 68 |
nb = notebook_dir(username, nb_id)
|
| 69 |
+
for sub in ["files_raw", "files_extracted", "chroma", "chat",
|
| 70 |
+
"artifacts/reports", "artifacts/quizzes", "artifacts/podcasts"]:
|
|
|
|
|
|
|
| 71 |
(nb / sub).mkdir(parents=True, exist_ok=True)
|
| 72 |
|
| 73 |
return nb_id
|
|
|
|
| 82 |
|
| 83 |
|
| 84 |
def delete_notebook(username: str, nb_id: str):
|
| 85 |
+
import shutil
|
| 86 |
notebooks = [nb for nb in get_user_notebooks(username) if nb["id"] != nb_id]
|
| 87 |
_save_index(username, notebooks)
|
| 88 |
nb_path = notebook_dir(username, nb_id)
|
|
|
|
| 90 |
shutil.rmtree(nb_path)
|
| 91 |
|
| 92 |
|
|
|
|
| 93 |
# Chat persistence
|
|
|
|
| 94 |
|
| 95 |
def _chat_path(username: str, nb_id: str) -> Path:
|
| 96 |
p = notebook_dir(username, nb_id) / "chat"
|
|
|
|
| 99 |
|
| 100 |
|
| 101 |
def save_message(username: str, nb_id: str, role: str, content: str):
|
| 102 |
+
"""Append a single message to the chat history file."""
|
| 103 |
path = _chat_path(username, nb_id)
|
| 104 |
with open(path, "a") as f:
|
| 105 |
f.write(json.dumps({
|
|
|
|
| 110 |
|
| 111 |
|
| 112 |
def load_chat_history(username: str, nb_id: str) -> list:
|
| 113 |
+
"""Return list of {role, content} dicts."""
|
| 114 |
path = _chat_path(username, nb_id)
|
| 115 |
if not path.exists():
|
| 116 |
return []
|
|
|
|
| 118 |
return [json.loads(line) for line in f if line.strip()]
|
| 119 |
|
| 120 |
|
|
|
|
| 121 |
# Artifact helpers
|
|
|
|
| 122 |
|
| 123 |
def save_artifact(username: str, nb_id: str, artifact_type: str,
|
| 124 |
content: str, extension: str = "md") -> Path:
|
| 125 |
+
"""
|
| 126 |
+
Save an artifact and return its path.
|
| 127 |
+
artifact_type: 'reports' | 'quizzes' | 'podcasts'
|
| 128 |
+
"""
|
| 129 |
folder = notebook_dir(username, nb_id) / "artifacts" / artifact_type
|
| 130 |
folder.mkdir(parents=True, exist_ok=True)
|
| 131 |
existing = list(folder.glob(f"*.{extension}"))
|
| 132 |
+
index = len(existing) + 1
|
| 133 |
+
path = folder / f"{artifact_type[:-1]}_{index}.{extension}"
|
| 134 |
path.write_text(content, encoding="utf-8")
|
| 135 |
return path
|
| 136 |
|
| 137 |
|
| 138 |
def list_artifacts(username: str, nb_id: str, artifact_type: str) -> list:
|
| 139 |
+
"""Return list of artifact filenames for a given type."""
|
| 140 |
folder = notebook_dir(username, nb_id) / "artifacts" / artifact_type
|
| 141 |
if not folder.exists():
|
| 142 |
return []
|
| 143 |
return [p.name for p in sorted(folder.iterdir())]
|
| 144 |
|
| 145 |
|
| 146 |
+
# Raw file storage
|
|
|
|
|
|
|
| 147 |
|
| 148 |
def save_raw_file(username: str, nb_id: str, filename: str, data: bytes) -> Path:
|
| 149 |
folder = notebook_dir(username, nb_id) / "files_raw"
|
requirements.txt
CHANGED
|
@@ -1,18 +1,20 @@
|
|
| 1 |
-
#
|
| 2 |
-
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
|
| 6 |
|
| 7 |
-
# Vector
|
| 8 |
chromadb>=0.5.0
|
| 9 |
|
| 10 |
# Document parsing
|
| 11 |
-
|
| 12 |
python-pptx>=0.6.21
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# Utilities
|
| 16 |
-
python-dotenv>=1.0.0
|
| 17 |
-
requests>=2.31.0
|
| 18 |
-
beautifulsoup4>=4.12.0
|
|
|
|
| 1 |
+
# UI
|
| 2 |
+
gradio[oauth]==6.8.0
|
| 3 |
|
| 4 |
+
# LLM + Embeddings
|
| 5 |
+
openai>=1.0.0
|
| 6 |
|
| 7 |
+
# Vector DB
|
| 8 |
chromadb>=0.5.0
|
| 9 |
|
| 10 |
# Document parsing
|
| 11 |
+
PyPDF2>=3.0.0
|
| 12 |
python-pptx>=0.6.21
|
| 13 |
+
beautifulsoup4>=4.12.0
|
| 14 |
+
requests>=2.31.0
|
| 15 |
+
|
| 16 |
+
# Audio / TTS
|
| 17 |
+
pydub>=0.25.1
|
| 18 |
|
| 19 |
# Utilities
|
| 20 |
+
python-dotenv>=1.0.0
|
|
|
|
|
|