Spaces:
Sleeping
Sleeping
asingh38 commited on
Commit ·
f7e925b
0
Parent(s):
initial commit: clean project structure
Browse files- .env.example +12 -0
- .github/workflows/ci.yml +45 -0
- .github/workflows/deploy.yml +24 -0
- .gitignore +29 -0
- README.md +36 -0
- app.py +592 -0
- backend/__init__.py +0 -0
- backend/artifacts.py +0 -0
- backend/chat.py +0 -0
- backend/ingestion.py +257 -0
- backend/retrieval.py +0 -0
- backend/storage.py +172 -0
- requirements.txt +18 -0
.env.example
ADDED
|
@@ -0,0 +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= "YOUR 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= "YOUR HF 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
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: CI
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: ["main", "dev"]
|
| 6 |
+
pull_request:
|
| 7 |
+
branches: ["main"]
|
| 8 |
+
|
| 9 |
+
jobs:
|
| 10 |
+
lint-and-test:
|
| 11 |
+
runs-on: ubuntu-latest
|
| 12 |
+
|
| 13 |
+
steps:
|
| 14 |
+
- name: Checkout
|
| 15 |
+
uses: actions/checkout@v4
|
| 16 |
+
|
| 17 |
+
- name: Set up Python 3.11
|
| 18 |
+
uses: actions/setup-python@v5
|
| 19 |
+
with:
|
| 20 |
+
python-version: "3.11"
|
| 21 |
+
|
| 22 |
+
- name: Cache pip
|
| 23 |
+
uses: actions/cache@v4
|
| 24 |
+
with:
|
| 25 |
+
path: ~/.cache/pip
|
| 26 |
+
key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
|
| 27 |
+
restore-keys: ${{ runner.os }}-pip-
|
| 28 |
+
|
| 29 |
+
- name: Install dependencies
|
| 30 |
+
run: |
|
| 31 |
+
pip install --upgrade pip
|
| 32 |
+
pip install -r requirements.txt
|
| 33 |
+
pip install flake8 pytest
|
| 34 |
+
|
| 35 |
+
- name: Lint
|
| 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: Test
|
| 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."
|
.github/workflows/deploy.yml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Deploy to Hugging Face Spaces
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
|
| 8 |
+
jobs:
|
| 9 |
+
deploy:
|
| 10 |
+
runs-on: ubuntu-latest
|
| 11 |
+
|
| 12 |
+
steps:
|
| 13 |
+
- name: Checkout
|
| 14 |
+
uses: actions/checkout@v4
|
| 15 |
+
with:
|
| 16 |
+
fetch-depth: 0
|
| 17 |
+
lfs: true
|
| 18 |
+
|
| 19 |
+
- name: Push to Hugging Face Space
|
| 20 |
+
env:
|
| 21 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 22 |
+
run: |
|
| 23 |
+
git remote add hf https://user:$HF_TOKEN@huggingface.co/spaces/asingh38/new-space
|
| 24 |
+
git push hf main --force
|
.gitignore
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Secrets
|
| 2 |
+
.env
|
| 3 |
+
|
| 4 |
+
# User data (never commit)
|
| 5 |
+
data/
|
| 6 |
+
|
| 7 |
+
# Python
|
| 8 |
+
__pycache__/
|
| 9 |
+
*.pyc
|
| 10 |
+
*.pyo
|
| 11 |
+
*.pyd
|
| 12 |
+
*.egg-info/
|
| 13 |
+
dist/
|
| 14 |
+
build/
|
| 15 |
+
.eggs/
|
| 16 |
+
|
| 17 |
+
# Virtual environments
|
| 18 |
+
.venv/
|
| 19 |
+
venv/
|
| 20 |
+
env/
|
| 21 |
+
|
| 22 |
+
# OS
|
| 23 |
+
.DS_Store
|
| 24 |
+
Thumbs.db
|
| 25 |
+
|
| 26 |
+
# IDE
|
| 27 |
+
.vscode/
|
| 28 |
+
.idea/
|
| 29 |
+
*.swp
|
README.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: NotebookLM 2.0
|
| 3 |
+
emoji: 📓
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: "4.44.0"
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# NotebookLM 2.0
|
| 13 |
+
|
| 14 |
+
An AI-powered research assistant. Upload documents, chat with your sources,
|
| 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 workspace** — create and manage separate notebooks per topic
|
| 21 |
+
- **Source ingestion** — upload PDF, PPTX, TXT, or paste a URL
|
| 22 |
+
- **RAG chat** — GPT-4o answers grounded in your sources with inline citations
|
| 23 |
+
- **Artifacts** — one-click study report, quiz, and podcast (transcript + audio)
|
| 24 |
+
- **Login system** — simple username/password auth via environment variable
|
| 25 |
+
|
| 26 |
+
## Hugging Face Spaces Setup
|
| 27 |
+
|
| 28 |
+
Set these in your Space → **Settings → Repository secrets**:
|
| 29 |
+
|
| 30 |
+
| Secret | Description |
|
| 31 |
+
|------------------|------------------------------------------------------|
|
| 32 |
+
| `OPENAI_API_KEY` |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Auth
|
| 21 |
+
# ---------------------------------------------------------------------------
|
| 22 |
+
|
| 23 |
+
def _parse_users() -> dict[str, str]:
|
| 24 |
+
"""
|
| 25 |
+
Parse USERS env var into {username: password}.
|
| 26 |
+
Format: "alice:pass1,bob:pass2"
|
| 27 |
+
Falls back to demo:demo if not set.
|
| 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 |
+
# Backend (lazy import so HF Spaces cold-start doesn't fail on missing keys)
|
| 52 |
+
# ---------------------------------------------------------------------------
|
| 53 |
+
|
| 54 |
+
def _be():
|
| 55 |
+
"""Return dict of backend callables."""
|
| 56 |
+
from backend.storage import (
|
| 57 |
+
get_user_notebooks,
|
| 58 |
+
create_notebook_for_user,
|
| 59 |
+
delete_notebook,
|
| 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 |
+
# Notebook dropdown helpers
|
| 79 |
+
# ---------------------------------------------------------------------------
|
| 80 |
+
|
| 81 |
+
def _nb_choices(username: str) -> list[str]:
|
| 82 |
+
"""Return list of 'Notebook Name [uuid]' strings for the dropdown."""
|
| 83 |
+
nbs = _be()["get_notebooks"](username)
|
| 84 |
+
return [f"{nb['name']} [{nb['id']}]" for nb in nbs]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _parse_choice(choice: str) -> tuple[str, str]:
|
| 88 |
+
"""Extract (name, nb_id) from a dropdown choice string."""
|
| 89 |
+
if not choice:
|
| 90 |
+
return "", ""
|
| 91 |
+
name, _, rest = choice.rpartition(" [")
|
| 92 |
+
return name.strip(), rest.rstrip("]").strip()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _sources_md(username: str, nb_id: str) -> str:
|
| 96 |
+
"""Return a Markdown list of indexed source names for a notebook."""
|
| 97 |
+
if not username or not nb_id:
|
| 98 |
+
return "_No notebook selected._"
|
| 99 |
+
try:
|
| 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 |
+
# CSS — dark editorial theme
|
| 110 |
+
# ---------------------------------------------------------------------------
|
| 111 |
+
|
| 112 |
+
CSS = """
|
| 113 |
+
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&family=JetBrains+Mono:wght@300;400;500&display=swap');
|
| 114 |
+
|
| 115 |
+
:root {
|
| 116 |
+
--bg: #0a0a0f;
|
| 117 |
+
--bg2: #111118;
|
| 118 |
+
--bg3: #16161f;
|
| 119 |
+
--bg4: #1c1c28;
|
| 120 |
+
--accent: #7c6af7;
|
| 121 |
+
--accent2: #9d8fff;
|
| 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 |
+
# Build UI
|
| 335 |
+
# ---------------------------------------------------------------------------
|
| 336 |
+
|
| 337 |
+
def build_ui() -> gr.Blocks:
|
| 338 |
+
|
| 339 |
+
with gr.Blocks(css=CSS, title="NotebookLM 2.0", theme=gr.themes.Base()) as demo:
|
| 340 |
+
|
| 341 |
+
# ── Persistent state ───────────────────────────────────────────────
|
| 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 |
+
for trigger in [btn_login.click, inp_pass.submit]:
|
| 456 |
+
trigger(
|
| 457 |
+
do_login,
|
| 458 |
+
inputs=[inp_user, inp_pass],
|
| 459 |
+
outputs=[screen_login, screen_main, s_user, dd_nb, lbl_user, msg_login],
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
# ── Notebook selection ─────────────────────────────────────────────
|
| 463 |
+
def on_nb_select(choice):
|
| 464 |
+
_, nb_id = _parse_choice(choice)
|
| 465 |
+
return nb_id
|
| 466 |
+
|
| 467 |
+
dd_nb.change(on_nb_select, inputs=[dd_nb], outputs=[s_nb_id])
|
| 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 |
+
# Entry point
|
| 588 |
+
# ---------------------------------------------------------------------------
|
| 589 |
+
|
| 590 |
+
if __name__ == "__main__":
|
| 591 |
+
demo = build_ui()
|
| 592 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
backend/__init__.py
ADDED
|
File without changes
|
backend/artifacts.py
ADDED
|
File without changes
|
backend/chat.py
ADDED
|
File without changes
|
backend/ingestion.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
backend/ingestion.py
|
| 3 |
+
--------------------
|
| 4 |
+
Ingestion pipeline: extract → chunk → embed → store in ChromaDB.
|
| 5 |
+
|
| 6 |
+
Chunking strategies:
|
| 7 |
+
- "fixed" : fixed character windows with overlap
|
| 8 |
+
- "sentence" : sentence-boundary-aware sliding window
|
| 9 |
+
- "recursive" : recursive character splitter (default, best quality)
|
| 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
|
| 18 |
+
|
| 19 |
+
import chromadb
|
| 20 |
+
from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
|
| 21 |
+
|
| 22 |
+
from backend import storage
|
| 23 |
+
|
| 24 |
+
# ---------------------------------------------------------------------------
|
| 25 |
+
# Config
|
| 26 |
+
# ---------------------------------------------------------------------------
|
| 27 |
+
|
| 28 |
+
OPENAI_API_KEY: str = os.getenv("OPENAI_API_KEY", "")
|
| 29 |
+
CHUNK_SIZE: int = int(os.getenv("CHUNK_SIZE", "800"))
|
| 30 |
+
CHUNK_OVERLAP: int = int(os.getenv("CHUNK_OVERLAP", "150"))
|
| 31 |
+
EMBED_MODEL: str = os.getenv("EMBED_MODEL", "text-embedding-3-small")
|
| 32 |
+
|
| 33 |
+
ChunkStrategy = Literal["fixed", "sentence", "recursive"]
|
| 34 |
+
DEFAULT_STRATEGY: ChunkStrategy = "recursive"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# ---------------------------------------------------------------------------
|
| 38 |
+
# ChromaDB helpers
|
| 39 |
+
# ---------------------------------------------------------------------------
|
| 40 |
+
|
| 41 |
+
def _embedding_fn():
|
| 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 |
+
return client.get_or_create_collection(
|
| 52 |
+
name="sources",
|
| 53 |
+
embedding_function=_embedding_fn(),
|
| 54 |
+
metadata={"hnsw:space": "cosine"},
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ---------------------------------------------------------------------------
|
| 59 |
+
# Text extraction
|
| 60 |
+
# ---------------------------------------------------------------------------
|
| 61 |
+
|
| 62 |
+
def _extract_pdf(file_path: Path) -> str:
|
| 63 |
+
import pdfplumber
|
| 64 |
+
texts = []
|
| 65 |
+
with pdfplumber.open(str(file_path)) as pdf:
|
| 66 |
+
for page in pdf.pages:
|
| 67 |
+
t = page.extract_text()
|
| 68 |
+
if t:
|
| 69 |
+
texts.append(t)
|
| 70 |
+
return "\n\n".join(texts)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _extract_pptx(file_path: Path) -> str:
|
| 74 |
+
from pptx import Presentation
|
| 75 |
+
prs = Presentation(str(file_path))
|
| 76 |
+
slides = []
|
| 77 |
+
for i, slide in enumerate(prs.slides, start=1):
|
| 78 |
+
lines = [f"[Slide {i}]"]
|
| 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 |
+
lines.append(line)
|
| 85 |
+
slides.append("\n".join(lines))
|
| 86 |
+
return "\n\n".join(slides)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _extract_url(url: str) -> str:
|
| 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 = _extract_url(src)
|
| 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 _extract_pdf(p), p.name
|
| 113 |
+
elif suffix in (".pptx", ".ppt"):
|
| 114 |
+
return _extract_pptx(p), p.name
|
| 115 |
+
elif suffix in (".txt", ".md"):
|
| 116 |
+
return p.read_text(encoding="utf-8", errors="ignore"), p.name
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError(f"Unsupported file type: {suffix}")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# ---------------------------------------------------------------------------
|
| 122 |
+
# Chunking strategies
|
| 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 |
+
chunks.append(text[start: start + size])
|
| 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 |
+
tail, tlen = [], 0
|
| 141 |
+
for s in reversed(current):
|
| 142 |
+
tlen += len(s)
|
| 143 |
+
tail.insert(0, s)
|
| 144 |
+
if tlen >= overlap:
|
| 145 |
+
break
|
| 146 |
+
current, current_len = tail, sum(len(s) for s in tail)
|
| 147 |
+
current.append(sent)
|
| 148 |
+
current_len += slen
|
| 149 |
+
if current:
|
| 150 |
+
chunks.append(" ".join(current))
|
| 151 |
+
return [c.strip() for c in chunks if c.strip()]
|
| 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]:
|
| 158 |
+
if len(t) <= size:
|
| 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 |
+
result, current = [], ""
|
| 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 |
+
result.extend(_split(current, seps[1:]))
|
| 172 |
+
current = part
|
| 173 |
+
if current:
|
| 174 |
+
result.extend(_split(current, seps[1:]))
|
| 175 |
+
return result
|
| 176 |
+
|
| 177 |
+
raw = _split(text, separators)
|
| 178 |
+
overlapped = []
|
| 179 |
+
for i, chunk in enumerate(raw):
|
| 180 |
+
if i > 0 and overlap > 0:
|
| 181 |
+
chunk = raw[i - 1][-overlap:] + " " + chunk
|
| 182 |
+
overlapped.append(chunk.strip())
|
| 183 |
+
return [c for c in overlapped if c]
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def chunk_text(text: str, strategy: ChunkStrategy = DEFAULT_STRATEGY) -> list[str]:
|
| 187 |
+
if strategy == "fixed":
|
| 188 |
+
return _fixed_chunks(text)
|
| 189 |
+
elif strategy == "sentence":
|
| 190 |
+
return _sentence_chunks(text)
|
| 191 |
+
else:
|
| 192 |
+
return _recursive_chunks(text)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# ---------------------------------------------------------------------------
|
| 196 |
+
# Public API
|
| 197 |
+
# ---------------------------------------------------------------------------
|
| 198 |
+
|
| 199 |
+
def ingest_source(
|
| 200 |
+
username: str,
|
| 201 |
+
notebook_id: str,
|
| 202 |
+
source: str | Path,
|
| 203 |
+
chunk_strategy: ChunkStrategy = DEFAULT_STRATEGY,
|
| 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()
|
| 218 |
+
ids.append(chunk_id)
|
| 219 |
+
documents.append(chunk)
|
| 220 |
+
metadatas.append({
|
| 221 |
+
"source": source_name,
|
| 222 |
+
"chunk_index": i,
|
| 223 |
+
"total_chunks": len(chunks),
|
| 224 |
+
"strategy": chunk_strategy,
|
| 225 |
+
})
|
| 226 |
+
|
| 227 |
+
collection = _get_collection(username, notebook_id)
|
| 228 |
+
for start in range(0, len(ids), 100):
|
| 229 |
+
collection.upsert(
|
| 230 |
+
ids=ids[start: start + 100],
|
| 231 |
+
documents=documents[start: start + 100],
|
| 232 |
+
metadatas=metadatas[start: start + 100],
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
return {
|
| 236 |
+
"source_name": source_name,
|
| 237 |
+
"char_count": len(text),
|
| 238 |
+
"chunk_count": len(chunks),
|
| 239 |
+
"strategy": chunk_strategy,
|
| 240 |
+
}
|
| 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"]:
|
| 247 |
+
collection.delete(ids=results["ids"])
|
| 248 |
+
return len(results["ids"])
|
| 249 |
+
return 0
|
| 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 |
+
if not results["metadatas"]:
|
| 256 |
+
return []
|
| 257 |
+
return sorted({m["source"] for m in results["metadatas"]})
|
backend/retrieval.py
ADDED
|
File without changes
|
backend/storage.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 2 |
+
backend/storage.py
|
| 3 |
+
------------------
|
| 4 |
+
All filesystem reads/writes for user data.
|
| 5 |
+
|
| 6 |
+
Directory layout:
|
| 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/
|
| 10 |
+
data/users/<username>/notebooks/<nb-id>/artifacts/quizzes/
|
| 11 |
+
data/users/<username>/notebooks/<nb-id>/artifacts/podcasts/
|
| 12 |
+
data/users/<username>/notebooks/<nb-id>/files_raw/
|
| 13 |
+
data/users/<username>/notebooks/<nb-id>/files_extracted/
|
| 14 |
+
data/users/<username>/notebooks/<nb-id>/chroma/
|
| 15 |
+
"""
|
| 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"
|
| 32 |
+
p.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
return p
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def notebook_dir(username: str, nb_id: str) -> Path:
|
| 37 |
+
p = user_dir(username) / nb_id
|
| 38 |
+
p.mkdir(parents=True, exist_ok=True)
|
| 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 []
|
| 60 |
+
with open(path) as f:
|
| 61 |
+
return json.load(f)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _save_index(username: str, notebooks: list):
|
| 65 |
+
with open(index_path(username), "w") as f:
|
| 66 |
+
json.dump(notebooks, f, indent=2)
|
| 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({
|
| 73 |
+
"id": nb_id,
|
| 74 |
+
"name": name,
|
| 75 |
+
"created_at": datetime.utcnow().isoformat(),
|
| 76 |
+
})
|
| 77 |
+
_save_index(username, notebooks)
|
| 78 |
+
|
| 79 |
+
nb = notebook_dir(username, nb_id)
|
| 80 |
+
for sub in [
|
| 81 |
+
"files_raw", "files_extracted", "chroma", "chat",
|
| 82 |
+
"artifacts/reports", "artifacts/quizzes", "artifacts/podcasts",
|
| 83 |
+
]:
|
| 84 |
+
(nb / sub).mkdir(parents=True, exist_ok=True)
|
| 85 |
+
|
| 86 |
+
return nb_id
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def rename_notebook(username: str, nb_id: str, new_name: str):
|
| 90 |
+
notebooks = get_user_notebooks(username)
|
| 91 |
+
for nb in notebooks:
|
| 92 |
+
if nb["id"] == nb_id:
|
| 93 |
+
nb["name"] = new_name
|
| 94 |
+
_save_index(username, notebooks)
|
| 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)
|
| 101 |
+
if nb_path.exists():
|
| 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"
|
| 111 |
+
p.mkdir(parents=True, exist_ok=True)
|
| 112 |
+
return p / "messages.jsonl"
|
| 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({
|
| 119 |
+
"role": role,
|
| 120 |
+
"content": content,
|
| 121 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 122 |
+
}) + "\n")
|
| 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 []
|
| 129 |
+
with open(path) as f:
|
| 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 |
+
idx = len(existing) + 1
|
| 143 |
+
path = folder / f"{artifact_type[:-1]}_{idx}.{extension}"
|
| 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"
|
| 161 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 162 |
+
path = folder / filename
|
| 163 |
+
path.write_bytes(data)
|
| 164 |
+
return path
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def save_extracted_text(username: str, nb_id: str, filename: str, text: str) -> Path:
|
| 168 |
+
folder = notebook_dir(username, nb_id) / "files_extracted"
|
| 169 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 170 |
+
path = folder / (filename + ".txt")
|
| 171 |
+
path.write_text(text, encoding="utf-8")
|
| 172 |
+
return path
|
requirements.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLM + embeddings + TTS
|
| 2 |
+
openai>=1.0.0
|
| 3 |
+
|
| 4 |
+
# Gradio (Hugging Face Spaces runtime)
|
| 5 |
+
gradio>=4.44.0
|
| 6 |
+
|
| 7 |
+
# Vector database
|
| 8 |
+
chromadb>=0.5.0
|
| 9 |
+
|
| 10 |
+
# Document parsing
|
| 11 |
+
pdfplumber>=0.9.0
|
| 12 |
+
python-pptx>=0.6.21
|
| 13 |
+
trafilatura>=1.6.0
|
| 14 |
+
|
| 15 |
+
# Utilities
|
| 16 |
+
python-dotenv>=1.0.0
|
| 17 |
+
requests>=2.31.0
|
| 18 |
+
beautifulsoup4>=4.12.0
|